# Bitquery Docs — full text > Full text of every documentation page (excludes the auto-generated GraphQL reference). > Curated entry points: /llms.txt > This file is over 5 MB; the same pages split by topic into files under 1.5 MB are listed in /llms.txt. ## APE Store API - Base Chain Token Trades & Transaction Data URL: https://docs.bitquery.io/docs/blockchain/Base/apestore-base-api/ APE Store on Base: find the APE Store contract and its methods, then query all trades, trades by a trader and trades of a specific token. # APE Store API In this section we will see how we can use the [Transaction](/docs/cubes/transaction-cube/) and [Calls](/docs/schema/evm/calls/) API from Bitquery to get info about trades on APE Store using one of the token address traded on the platform. For this section the token address is the following - `0xb2779752b8abe50e2a06bddd774bf0a40353f867`. ## Get APE Store Address Firstly, we can find the smart contract address of the APE Store using [this](https://ide.bitquery.io/ape-store-token-event_1#) query. ``` graphql query MyQuery { EVM(network: base) { Events( where: {Arguments: {includes: {Value: {Address: {is: "0xb2779752b8abe50e2a06bddd774bf0a40353f867"}}}}} ) { Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Transaction { From Hash To } count } } } ``` The address labeled as `To` under the `Transaction` block is the smart contract address of APE Store. The APE Store address is - `0x0bf8edd756ff6caf3f583d67a9fd8b237e40f58a`. ## Get All the Methods for APE Store We need to get all methods for the APE Store for better understanding of its functionality and get the `signatures` used for buying tokens. [This](https://ide.bitquery.io/methods-for-ape-store#) query returns all the methods associated with the APE Store. ``` graphql query MyQuery { EVM(network: base) { Calls( where: {Transaction: {To: {is: "0x0bf8edd756ff6caf3f583d67a9fd8b237e40f58a"}}} orderBy: {descendingByField: "count"} ) { Call { Signature { Name Signature } } count } } } ``` From the results we get a signature named `buy` that will be analyzed to get the trades on APE Store. ## Get Trades for APE Store [This](https://ide.bitquery.io/ape-store-buys_1#) query returns the `buy` method Calls to the APE Store that are potentially the trades on the APE Store. ``` graphql query MyQuery { EVM(network: base) { Calls( where: {Transaction: {To: {is: "0x0bf8edd756ff6caf3f583d67a9fd8b237e40f58a"}}, Call: {Signature: {Name: {is: "buy"}}}} ) { Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Transaction { Cost From Hash Time GasPrice } } } } ``` ## Get Trades of a Trader [This](https://ide.bitquery.io/ape-store-buys-from-a-wallet) query returns the trades by a particular trader on APE Store. In this example the trader wallet address is - `0x2870cbffae4cf005dd1c3587e2f0db3cb00dbafd`. ``` graphql query MyQuery { EVM(network: base) { Calls( where: {Transaction: {To: {is: "0x0bf8edd756ff6caf3f583d67a9fd8b237e40f58a"}, From: {is: "0x2870cbffae4cf005dd1c3587e2f0db3cb00dbafd"}}, Call: {Signature: {Name: {is: "buy"}}}} ) { Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Transaction { Cost From Hash Time GasPrice } } } } ``` ## Get Trades of a Token [This](https://ide.bitquery.io/ape-store-token-trades) query returns the trades of a token on APE Store. In this example the token is - `0x442a62e390e16cec26998dd965c606efbd06b8ed`. ``` graphql query MyQuery { EVM(network: base) { Calls( where: {Transaction: {To: {is: "0x0bf8edd756ff6caf3f583d67a9fd8b237e40f58a"}}, Call: {Signature: {Name: {is: "buy"}}}, Arguments: {includes: {Value: {Address: {is: "0x442a62e390e16cec26998dd965c606efbd06b8ed"}}}}} ) { Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Transaction { Cost From Hash Time GasPrice } } } } ``` --- ## API Schema Overview URL: https://docs.bitquery.io/docs/schema/schema-intro/ API Schema Overview: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. Great for bots, dashboards, and alerts. # API Schema Overview This section documents the Bitquery GraphQL **schema** — the fields, filters, and relationships you use to build queries — for both EVM and non-EVM chains. ## How the schema is organized Bitquery models blockchain data as **cubes** — typed collections like `Transfers`, `DEXTrades`, `Balances`, `Events`, and `Calls`. Each cube exposes: - **Dimensions** — the fields you select and group by (addresses, tokens, block time, amounts). - **Filters** — the `where` conditions that narrow results (see [filters](/docs/graphql/filters/)). - **Metrics** — aggregations like `sum`, `count`, and `uniq` (see [metrics](/docs/graphql/metrics/metrics/)). EVM chains (Ethereum, BSC, Base, Arbitrum, Arc, …) share one cube shape under the `EVM(...)` root; non-EVM chains (Solana, Tron, Bitcoin) have parallel cubes under their own roots. ## Browse the schema in the IDE The fastest way to explore fields is the schema explorer in the [Bitquery IDE](https://ide.bitquery.io/) — the left panel lists every cube and field for the selected endpoint, with inline types and descriptions. ## Which dataset a field comes from Field availability and history depth depend on the **dataset** (`realtime`, `archive`, `combined`) and the chain — see the [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/) before assuming a field has deep history. ## Next steps - [Understanding cubes](/docs/category/understanding-cubes/) - [Building queries](/docs/graphql/query/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) --- ## Add-Liquidity Signals Telegram Bot URL: https://docs.bitquery.io/docs/usecases/add-liquidity-signal-bot/ Build Add-Liquidity Signals Telegram Bot: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Add-Liquidity Signals Telegram Bot This bot fetches real-time data on added liquidity for Solana DEX pools and sends alerts via Telegram. It highlights key details such as added liquidity, post-liquidity amounts, and provides direct trading links. Github Repository Link - [here](https://github.com/Akshat-cs/Add-Liquidity-Signal-Bot/tree/main) ## Tutorial Video ## Features - Monitors added liquidity for Solana DEX pools in real-time. - Sends detailed updates on: - Base and Quote currencies. - Added liquidity and post-liquidity values. - DEX protocol details. - Includes "Trade Now" links for immediate trading actions. - Handles Telegram message length limitations with intelligent splitting. - Periodically fetches updates (default: every 30 minutes). ## Prerequisites 1. **Python 3.8+** installed on your system. 2. **Telegram Bot Token** from [BotFather](https://telegram.me/BotFather). 3. **Bitquery API Token** for accessing Solana liquidity data. Get your API token [here](/docs/authorization/how-to-generate/). ## Installation 1. Clone this repository and navigate to the project directory: ```bash git clone https://github.com/Akshat-cs/Add-Liquidity-Signal-Bot ``` 2. Install the required dependencies: ```bash pip install python-telegram-bot aiohttp ``` 3. Replace Bot token and OAuth Token values in the `top-liquidity-additions.py` file with your own tokens. Get the BOT_TOKEN from Bot father and Bitquery OAuth token using these [steps](/docs/authorization/how-to-generate/): ``` BOT_TOKEN=your-telegram-bot-token OAUTH_TOKEN=your-bitquery-oauth-token ``` 4. Start the bot: ```bash python top-liquidity-additions.py ``` 5. Use the `/start` command in your Telegram chat with the bot to begin monitoring Solana pools with liquidity additions. ## How It Works 1. **Real-Time Monitoring**: - The bot queries the Bitquery API every 30 minutes for liquidity data from Solana DEX pools. - Fetches and formats data for pools with added liquidity in the last 5 minutes. 2. **Data Formatting**: - Extracts details about: - **Base and Quote Currencies**: Names, symbols, and mint addresses. - **Liquidity Information**: Added liquidity and post-liquidity values. - **Protocol Details**: Protocol family and name. - Includes direct "Trade Now" links for each pool. 3. **Message Splitting**: - Automatically splits long messages exceeding Telegram's character limit (4096 characters). - Handles Telegram's flood control by waiting and retrying if rate limits are exceeded. ## Code Walkthrough ### 1. **Configuration** - **`BOT_TOKEN`**: Your Telegram bot token from BotFather. - **`OAUTH_TOKEN`**: Your Bitquery API token for accessing Solana DEX data. - **Logging**: Configures logging to track bot operations and errors. ### 2. **Helper Functions** - **`split_text(text, max_length)`**: - Splits long messages into smaller parts to adhere to Telegram's 4096-character limit. - **`send_long_message(update, context, message_generator)`**: - Sends long messages as multiple parts. - Handles Telegram’s flood control by retrying after delays. ### 3. **GraphQL Query** - Queries the Bitquery API for Solana DEX pools with recently added liquidity: - Filters for pools with added liquidity (`ChangeAmount > 0`). - Retrieves market details, added liquidity, and post-liquidity values. - Limits results to the top 10 pools based on the `Block_Time`. ### 4. **Core Functions** - **`send_query_and_process(update, context)`**: - Sends the GraphQL query to the API and processes the response. - Formats the data into a user-friendly message using `format_message()`. - Sends the formatted messages to the Telegram chat. - **`format_message(data)`**: - Processes the API response data to extract: - Base and quote currency details. - Added liquidity and post-liquidity values. - Protocol information and trading links. - Constructs HTML-formatted Telegram messages. - Splits messages if they exceed the character limit. ### 5. **Task Management** - **Global Flag (`is_task_running`)**: - Prevents multiple instances of the periodic task from running simultaneously. - **`start_regular_requests(update, context)`**: - Continuously fetches and sends updates every 30 minutes. - Handles errors gracefully and ensures the global flag resets on task completion. ### 6. **Command Handlers** - **`/start` Command**: - Initializes the bot and starts the periodic task for fetching liquidity updates. ### 7. **Main Execution** - Initializes the Telegram bot using the `ApplicationBuilder` from `python-telegram-bot`. - Adds the `/start` command handler to the bot. - Runs the bot with polling to listen for incoming commands. --- ## Address Details Panel - Inflow, Outflow, Tracing Balance and Labels URL: https://docs.bitquery.io/docs/moneyflow-lite/address-details/ What the address panel in MoneyFlow Lite shows when you click a node: address group totals, inflow, outflow, tracing balance, address labels, custom tags, underlying assets and report generation. # Address Details Panel Click a node in the chart to open its details in the right-hand panel. The panel header shows the address, or `origin` for the starting address. ![Address group panel with labels](/img/moneyflow-lite/address-group-labels.jpg) ## Address Group The top block summarises the whole node. With **Depth-based Entity Split** on, a node can group several addresses, so these totals cover all of them. | Field | Meaning | | --- | --- | | **Inflow** | USD value received by the group within the trace. | | **Outflow** | USD value sent by the group within the trace. | | **Tracing Balance** | Inflow minus outflow, multiplied by the current price. It is the amount of traced money still sitting at the node. It is not the on-chain balance of the address. | **New Tag** adds your own tag to the group. See [Address labels and tags](/docs/moneyflow-lite/address-labels). ## Show underlying assets On account-based chains the panel has a **Show underlying assets** button. It lists each asset held at the node with the amount, the current price and the USD value. ![Underlying assets on an Ethereum address](/img/moneyflow-lite/underlying-assets.jpg) ## Addresses The **Addresses (n)** section lists every address in the group. Each entry shows: - The full address, a copy icon, and a link icon. The link opens a new instant MoneyFlow for that address. - Address labels, such as `bitmex-hot` and `bitmex-wallet`. A `+1` badge means more labels exist. Hover it to see them all. - Inflow, outflow and tracing balance for that single address. - **New Tag** for a custom tag on that address. Use **Search by address** to find one address in a large group. ## Generate report **Generate report** builds a report of the node's transactions. The report opens as its own page with a **Summary** button and a **CSV** download. It lists every transaction with depth, time, hash, sender, receiver and amount, and marks the origin address. ![Generated report with CSV download](/img/moneyflow-lite/report-view.png) Reports also appear under the **Reports** tab of the MoneyFlows list, with a **Status** column, so you can download them later. ## Get API **Get API** opens the Coinpath® query for this panel in the Bitquery IDE. See [Get API](/docs/moneyflow-lite/get-api-coinpath-query). ## Transactions of the node When a node is selected, the table at the bottom changes to **Transactions of <address>**. It lists only the transfers that touch this node. See [transactions table](/docs/moneyflow-lite/transactions-table). --- ## Address Labels API: Identify Crypto Wallets URL: https://docs.bitquery.io/docs/labels/address-labels-api/ Identify wallets and contracts with the Bitquery Address Labels API: exchange hot and cold wallets, deposit addresses, token contracts and clones, any chain. # Address Labels API: Identify Crypto Wallets The Address Labels API tells you **who is behind a blockchain address**: which exchange owns a hot wallet, whether an address is a per-user deposit address, whether a contract is a token (or a clone imitating one), and whether an address has been frozen by a stablecoin issuer. One GraphQL query, `Metadata { Labels }`, answers this across EVM chains, Solana, Bitcoin, and Tron. | | | | -------------- | ---------------------------------------------------------------------------------------- | | **Cube** | `Metadata.Labels` | | **Endpoints** | `https://streaming.bitquery.io/graphql` | | **Auth** | [OAuth token](/docs/authorization/how-to-generate) as `Authorization: Bearer ` | | **Required** | An `Address` filter on every query | | **Batch size** | Up to **100 addresses** per query | | **Streaming** | Query-only, no subscription. Poll `RecordedAt` for newly added labels | Most people use it as the second step of a two-query pattern: pull addresses from an activity API such as [DEXTrades](/docs/cubes/dextrades) or [Transfers](/docs/cubes/transfers-cube), then resolve those addresses to entities here. Use the result to enrich analytics, screen flows for exchange or gambling exposure, or strip exchange and contract addresses out of "real user" metrics. ## Rules that matter 1. **The `Address` filter is mandatory.** Every query must pin `Address` with `is` or `in`. There is no way to list all addresses carrying a label. Without it you get: `"Labels query requires a Address filter in the where clause"`. 2. **Up to 100 addresses per query.** Split larger lists into batches of 100. 3. **Matching is exact and case-sensitive.** Pass EVM addresses in **lowercase**. A checksummed `0xAbC…` returns zero rows. Bitcoin, Solana, and Tron addresses are case-sensitive by nature, so pass them exactly as they appear on-chain. 4. **Labels can be corrected or removed, and old versions are not kept.** An address returns one row per chain, per label, per recording pass, so the same label can recur with different `RecordedAt` values. Fold that into a current view with `limitBy`, [shown below](#how-to-get-only-the-current-labels). When we find a wrong label we fix or delete it in place, so re-run a full lookup to pick up corrections. ## How to look up labels for one address ```graphql { Metadata { Labels( where: {Address: {in: ["0x18e296053cbdf986196903e889b7dca7a73882f6"]}} ) { Address Chain Label { Type Value } RecordedAt } } } ``` The response identifies the address as a Bybit hot wallet on every chain where it is labeled (abridged; the full response also repeats labels recorded on earlier passes): ```json { "Metadata": { "Labels": [ { "Address": "0x18e296053cbdf986196903e889b7dca7a73882f6", "Chain": "ethereum", "Label": { "Type": "cex-hot-wallet", "Value": "bybit-hot-1" }, "RecordedAt": "2026-07-31T13:11:13Z" }, { "Address": "0x18e296053cbdf986196903e889b7dca7a73882f6", "Chain": "bsc", "Label": { "Type": "cex-hot-wallet", "Value": "bybit-hot" }, "RecordedAt": "2026-07-22T07:53:03Z" } ] } } ``` ## How to get only the current labels Because the same label can come back once per recording pass, most applications want the **latest record per address, chain, and label type**. `limitBy` plus a `RecordedAt` sort does exactly that, and this is the shape you should reach for by default: ```graphql { Metadata { Labels( where: {Address: {is: "0x18e296053cbdf986196903e889b7dca7a73882f6"}} limitBy: {by: [Address, Chain, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } RecordedAt } } } ``` This returns one clean row per chain instead of the wallet's full recording history. Note the nested field is addressed as `Label_Type` in `limitBy` and `orderBy`. The groupable and sortable names are `Address`, `Chain`, `Label_Type`, `Label_Value`, and `RecordedAt`. Keep `Label_Type` in the `limitBy` key unless you deliberately want one row per address: an address can legitimately carry several different labels, since a token contract is often tagged both `token-contract` and `contract`. ## How to label up to 100 addresses at once Pass the list as a variable. This is the shape to use when enriching the output of another query, such as top traders, transfer counterparties, or token holders: ```graphql query ($addresses: [String!]) { Metadata { Labels( where: {Address: {in: $addresses}} limitBy: {by: [Address, Chain, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } RecordedAt } } } ``` ```json { "addresses": [ "0x18e296053cbdf986196903e889b7dca7a73882f6", "0x28c6c06298d514db089934071355e5743bf21d60" ] } ``` Addresses with no labels are simply absent from the response, with no error and no placeholder row. Anything missing is "unlabeled so far", which in wallet analytics usually means an ordinary user wallet. ## How to check if an address is an exchange wallet Combine a batch with a `Label.Type` filter to keep only exchange-owned addresses: ```graphql { Metadata { Labels( where: { Address: {in: [ "0x28c6c06298d514db089934071355e5743bf21d60", "0x18e296053cbdf986196903e889b7dca7a73882f6", "0x7a250d5630b4cf539739df2c5dacb4c659f2488d" ]} Label: {Type: {in: ["cex-hot-wallet", "cex-cold-wallet", "cex-deposit-address"]}} Chain: {is: "ethereum"} } limitBy: {by: [Address, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Label { Type Value } RecordedAt } } } ``` Only the Binance and Bybit hot wallets come back. The Uniswap router drops out because its labels (`contract: uniswap`) don't match the requested types, which is exactly how you separate exchange addresses from protocol contracts in a mixed list. ## How to screen for issuer-blocked (frozen) addresses Stablecoin issuers freeze addresses on their own contracts. `issuer-blocked-usdt` and `issuer-blocked-usdc` capture those, so a `startsWith` filter screens for both at once: ```graphql { Metadata { Labels( where: { Address: {in: [ "0x098b716b8aaf21512996dc57eb0615e2383e2f96", "0x28c6c06298d514db089934071355e5743bf21d60" ]} Label: {Type: {startsWith: "issuer-blocked"}} } limitBy: {by: [Address, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } } } } ``` ## How to label Bitcoin, Tron, and Solana addresses Address formats mix freely in one batch. Each row's `Chain` tells you where the label applies: ```graphql { Metadata { Labels( where: {Address: {in: [ "34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM" ]}} limitBy: {by: [Address, Chain, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } } } } ``` This resolves a Binance Bitcoin cold wallet (`Chain: "bitcoin"`), the USDT contract on Tron (`Chain: "tron"`), and a Binance cold wallet on Solana (`Chain: "solana"`). ## How to watch for newly added labels The cube has no subscription, so poll the addresses you track with a `RecordedAt` window and keep the high-water mark on your side: ```graphql { Metadata { Labels( where: { Address: {is: "0x18e296053cbdf986196903e889b7dca7a73882f6"} RecordedAt: {since: "2026-07-15T00:00:00Z"} } ) { Chain Label { Type Value } RecordedAt } } } ``` This window catches newly added labels only. Labels can be corrected or removed when we find errors, and earlier versions are not kept. A label we fix can keep its old `RecordedAt`, so it never enters the window, and a label we remove simply disappears. To catch corrections, re-run a full lookup on the addresses you track from time to time and compare it with what you stored. ## How to aggregate labels The cube supports the standard [metrics](/docs/graphql/calculations) `count` and `uniq`, and the dimensions you select become the grouping key. This counts label records and distinct labeled addresses per chain: ```graphql { Metadata { Labels( where: {Address: {in: [ "0x18e296053cbdf986196903e889b7dca7a73882f6", "0x28c6c06298d514db089934071355e5743bf21d60", "0xdac17f958d2ee523a2206206994597c13d831ec7" ]}} ) { Chain count uniq(of: Address) } } } ``` ## Filters Full [filter](/docs/graphql/filters) support applies on top of the mandatory `Address`: | Filter | Operators | Notes | | --- | --- | --- | | `Address` | `is`, `in` **only** | Mandatory, max 100 in `in`. No negation, so you cannot exclude addresses server-side. | | `Chain` | `is`, `in`, `not`, `notIn`, `like`, `includes`, `startsWith`, … | Exact chain slugs, listed in the table below. | | `Label: {Type: …}` | full string set | e.g. `{is: "cex-hot-wallet"}` | | `Label: {Value: …}` | full string set | e.g. `{startsWith: "binance"}` | | `RecordedAt` | `since`, `till`, `after`, `before`, `is`, plus `_relative` variants | Standard [DateTime filters](/docs/graphql/datetime). | | `any` | list of sub-filters | OR-combinator across conditions. | ## Response fields | Field | Type | Meaning | | --- | --- | --- | | `Address` | String | The queried address, exactly as stored (EVM addresses lowercase). | | `Chain` | String | Chain this label applies to. One address can map to many chains. | | `Label.Type` | String | Label category, listed below. | | `Label.Value` | String | Entity slug within the category, e.g. `binance-hot-1`, `bybit-hot`, `wavax`, `banned-by-usdt`. Numbered suffixes distinguish instances of the same entity. | | `RecordedAt` | DateTime | When the row was added to Bitquery's label table. Most Bitcoin labels carry 28 May 2026, the date of the first bulk load, so it does not tell you when an address was first identified. A corrected label can keep its old `RecordedAt`. | ### Supported chains `Chain` values are plain slugs and the set grows as coverage expands. Verified live: | Ecosystem | `Chain` values | | --- | --- | | EVM | `ethereum`, `bsc`, `polygon`, `arbitrum`, `base`, `avalanche-c`, `fantom`, `ethpow` | | Non-EVM | `bitcoin`, `tron`, `solana` | If you're unsure what a chain is called, query a known address from it without a `Chain` filter and read the slug off the response. ### Label types `Label.Type` is an **open taxonomy**. New categories appear as the pipeline learns new entity classes, so handle unknown types gracefully. The common ones: | `Label.Type` | Meaning | Example `Value` | | --- | --- | --- | | `cex-hot-wallet` | Exchange-operated hot wallet | `binance-hot-1`, `bybit-hot` | | `cex-cold-wallet` | Exchange cold storage | `binance-cold` | | `cex-deposit-address` | Per-user deposit address swept to an exchange | `coinex-deposit` | | `token-contract` | A token's contract or mint address | `usdt`, `wavax`, `wbnb` | | `token-clone` | Contract imitating a well-known token | `clone-wmatic-2` | | `contract` | General smart-contract tag | `uniswap`, `bridge`, `stablecoin` | | `gambling` | Gambling platform wallet | `stake-com-hot` | | `issuer-blocked-usdt` | Frozen or blacklisted by Tether | `banned-by-usdt` | | `issuer-blocked-usdc` | Frozen or blacklisted by Circle | `banned-by-usdc` | ## Limits and common errors - **Missing `Address` filter.** The query fails with `"Labels query requires a Address filter in the where clause"`. A `Chain` or `Label` filter alone does not satisfy it. - **Wrong casing.** A checksummed EVM address silently returns zero rows. Lowercase before querying. - **No negation on `Address`.** `not`/`notIn` aren't part of the `Address` filter. Exclusion belongs client-side, or in `Chain`/`Label` filters, which do support it. - **Subscriptions.** `subscription { Metadata { … } }` is rejected; the cube exists only under `query`. - **Empty result is not an error.** Unlabeled addresses, and an empty `in: []`, return an empty list. - **[`limit` / `limitBy`](/docs/graphql/limits) and [`orderBy`](/docs/graphql/sorting)** behave as on every other cube. ## Pick the right query | You need | Use | | --- | --- | | Who is behind one address | `Address: {is: …}` | | Enrich a list of ≤100 addresses | `Address: {in: …}` with `limitBy: {by: [Address, Chain, Label_Type], count: 1}` | | Exchange-wallet screening | `Label: {Type: {in: ["cex-hot-wallet", "cex-cold-wallet", "cex-deposit-address"]}}` | | Fake-token checks | `Label: {Type: {is: "token-clone"}}` | | Sanctions and issuer-freeze screening | `Label: {Type: {startsWith: "issuer-blocked"}}` | | Newly added labels | Poll with `RecordedAt: {since: …}`, plus a periodic full lookup for corrections | ## Related - [DEXTrades cube](/docs/cubes/dextrades): trade activity whose maker and taker addresses you can label - [Transfers cube](/docs/cubes/transfers-cube): transfer counterparties to enrich - [Balances & Holders cubes](/docs/cubes/balances-cube): what the addresses you identified actually hold - [Filtering](/docs/graphql/filters), [Sorting](/docs/graphql/sorting), [Limits](/docs/graphql/limits): the query mechanics used above --- ## Address Labels and Tags in MoneyFlow Lite - Identify Exchange Wallets URL: https://docs.bitquery.io/docs/moneyflow-lite/address-labels/ How MoneyFlow Lite labels known addresses such as exchange hot wallets and deposit addresses, how to read the label badges, how to add your own tags, and how to refresh labels. # Address Labels and Tags MoneyFlow Lite attaches labels to addresses it recognises. Labels tell you what an address is, for example an exchange hot wallet, without leaving the trace. The labels come from Bitquery's [Address Labels API](/docs/labels/address-labels-api). The app shows them for the addresses in a trace. The API returns the same labels for any address, on any chain, in bulk. See [Query labels with the API](#query-labels-with-the-api) below. ## Where labels appear - **Trace title**: when the origin is a known address, its label shows next to the title, for example `bitkub-deposit`. - **Address details panel**: under each address in the **Addresses** list. - **Transactions table**: under the sender and receiver addresses. ![Receiver addresses labelled hacker-truebit-hacker in the transactions table](/img/moneyflow-lite/labels-in-table-truebit.png) In this Truebit exploit trace both receivers carry `hacker-truebit-hacker` plus one more label behind the **+1** badge. ![Address labels on an exchange deposit address](/img/moneyflow-lite/underlying-assets.jpg) ## Label format Labels are lower-case, hyphen-separated and follow the pattern `-`. Labels seen in the app include: | Label | Meaning | | --- | --- | | `bitmex-hot` | BitMEX hot wallet | | `bitmex-wallet` | A BitMEX-controlled wallet | | `bitmex-proof-of-reserves` | Address BitMEX publishes in its proof of reserves | | `bitkub-deposit` | Deposit address belonging to the Bitkub exchange | | `bitkub-proof-of-reserves` | Address Bitkub publishes in its proof of reserves | An address can carry several labels. The app shows the first one and a **+n** badge. Hover the badge to see the rest. Each label has a type as well as a value. The app shows the value. The [Address Labels API](/docs/labels/address-labels-api) returns both, for example type `cex-hot-wallet` with value `bitmex-hot`. ## What labels tell you in a trace - Funds reaching a `-deposit` or `-hot` address have most likely entered an exchange. The exchange can identify the account holder. - Funds leaving a `-hot` address are an exchange withdrawal. The sender is the exchange, not an individual. - `-proof-of-reserves` addresses are exchange treasury addresses. ## Query labels with the API Use the [Address Labels API](/docs/labels/address-labels-api) when you need labels outside a trace: to screen a list of deposit addresses, to check one counterparty before you trace it, or to enrich your own tooling. One query labels up to 100 addresses. This query looks up one Ethereum address. Run it in the [Bitquery IDE](https://ide.bitquery.io/). ```graphql { Metadata { Labels( where: {Address: {in: ["0x18e296053cbdf986196903e889b7dca7a73882f6"]}} ) { Address Chain Label { Type Value } RecordedAt } } } ``` The response identifies the address as a Bybit hot wallet on each chain where it is labelled: ```json { "Metadata": { "Labels": [ { "Address": "0x18e296053cbdf986196903e889b7dca7a73882f6", "Chain": "ethereum", "Label": { "Type": "cex-hot-wallet", "Value": "bybit-hot-1" }, "RecordedAt": "2026-07-31T13:11:13Z" }, { "Address": "0x18e296053cbdf986196903e889b7dca7a73882f6", "Chain": "bsc", "Label": { "Type": "cex-hot-wallet", "Value": "bybit-hot" }, "RecordedAt": "2026-07-22T07:53:03Z" } ] } } ``` Rules to remember: - The `Address` filter is mandatory. Pass EVM addresses in lowercase. - Up to 100 addresses per query. Bitcoin, Tron and Solana addresses work the same way. - Labels can be corrected over time, so re-run a lookup to pick up changes. The [Address Labels API](/docs/labels/address-labels-api) page covers batching, current-label views, exchange checks, frozen-address screening and the full list of label types. ## Refresh labels The crosshair icon in the toolbar above the panels schedules a fresh label scan for the addresses in the trace. The app confirms with **Force scan task has been scheduled**. Use it when a trace was created a while ago and new labels may exist. ## Add your own tags Every address, address group and edge has a **New Tag** button. Click it, type a tag and press Enter. Tags are your own notes, for example `victim`, `mixer-suspect` or a case number. They are stored with the MoneyFlow and show up in the **Tags** column of the MoneyFlows list. Tags you add do not change Bitquery's labels and are not visible to other users unless you share the MoneyFlow. --- ## Aerodrome Finance API — Base DEX Trades & Liquidity URL: https://docs.bitquery.io/docs/blockchain/Base/aerodrome-base-api/ Aerodrome on Base: latest trades, most traded tokens, real-time prices and OHLC for all pairs, new liquidity pools and pool liquidity. # Aerodrome Finance API - Base DEX Trades, Liquidity Pools, Token Analytics Get real-time Aerodrome Finance DEX trades, liquidity pools, token prices, trading volume and comprehensive analytics on Base network. Access live trading data, pool creation events, liquidity metrics and token statistics through our Aerodrome Finance API, Streams and Data services. The GraphQL APIs and Streams below provide extensive data points for the Aerodrome Finance ecosystem. If you have any questions on other data points, reach out to [support](https://t.me/Bloxy_info). You may also be interested in: - [Base Network DEX APIs ➤](/docs/blockchain/Ethereum/dextrades/dex-api/) - [Token Trades APIs ➤](/docs/blockchain/Ethereum/dextrades/token-trades-apis/) - [Liquidity Pool APIs ➤](/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api/) :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ### Table of Contents ### 1. DEX Trades & Trading Activity - [Subscribe to Latest Trades on Aerodrome Finance ➤](#subscribe-to-latest-trades-on-aerodrome-finance) - [Most Traded Tokens on Aerodrome Finance ➤](#most-traded-tokens-on-aerodrome-finance) - [Realtime Prices, OHLC, Trading Volume of all pairs ➤](#realtime-prices-ohlc-trading-volume-of-all-pairs) ### 2. Liquidity Pools & Analytics - [Latest Liquidity Pools on Aerodrome Finance ➤](#latest-liquidity-pools-on-aerodrome-finance) - [Get Liquidity of a Pool ➤](#get-liquidity-of-a-pool) ### 3. [Video Tutorials](#video-tutorials) ## DEX Trades & Trading Activity ## Subscribe to Latest Trades on Aerodrome Finance Stream real-time DEX trades on Aerodrome Finance with this subscription query. Monitor live buy/sell activity, token pairs, prices, and trading volumes as they happen on the Base network. This query filters Aerodrome DEX trades by the protocol's `OwnerAddress` (`0x420dd381b31aef6683db6b902084cb0ffece40da`). [Subscribe to Aerodrome Finance trades in real-time — Stream ➤](https://ide.bitquery.io/Latest-Trades-on-Aerodrome)
Click to expand GraphQL query ```graphql subscription { EVM(network: base) { DEXTrades( where: { Trade: { Dex: { OwnerAddress: { is: "0x420dd381b31aef6683db6b902084cb0ffece40da" } } } } ) { Block { Time } Trade { Buy { AmountInUSD(selectWhere: { gt: "0" }) Buyer Currency { Name Symbol SmartContract } PriceInUSD Seller } Dex { ProtocolFamily ProtocolName } Sell { Currency { SmartContract Symbol Name } Seller Buyer AmountInUSD } } } } } ```
## Most Traded Tokens on Aerodrome Finance Discover the most actively traded tokens on Aerodrome Finance over any time period. This query analyzes all DEX trades within a specified timeframe and ranks tokens by trade count, helping you identify trending tokens and market activity patterns. [Get most traded tokens on Aerodrome Finance — Query ➤](https://ide.bitquery.io/Most-Traded-Tokens-on-Aerodome-Last-Month)
Click to expand GraphQL query ```graphql query MyQuery { EVM(dataset: archive, network: base) { DEXTradeByTokens( limit: { count: 10 } where: { Block: { Time: { after: "2024-06-10T00:00:00Z" before: "2024-07-10T00:00:00Z" } } Trade: { Dex: { OwnerAddress: { is: "0x420dd381b31aef6683db6b902084cb0ffece40da" } } } } orderBy: { descendingByField: "count" } ) { Trade { Currency { Name SmartContract } } count } } } ```
## Realtime Prices, OHLC, Trading Volume of all pairs Below API gives you instant access to live Aerodrome market data with pre-calculated OHLC, moving averages, and trading volumes updating every second—no complex calculations needed, just plug and play for your trading bots or analytics platform. [Realtime Prices, OHLC, Trading Volume of all pairs — Query ➤](https://ide.bitquery.io/aerodrome-dex---realtime-prices-1-sec-ohlc-trading-volumes)
Click to expand GraphQL query ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true } Market: { ProtocolFamily: { is: "Aerodrome" } } } ) { Token { Name Symbol Address } Price { Average { Estimate Mean ExponentialMoving SimpleMoving WeightedSimpleMoving } Ohlc { Open High Low Close } } QuoteToken { Name Symbol Address } Market { ProtocolFamily } Volume { Base Quote } Interval { Time { Duration Start End } } } } } ```
## Liquidity Pools & Analytics ## Latest Liquidity Pools on Aerodrome Finance Track newly created liquidity pools on Aerodrome Finance in real-time. Discover fresh trading pairs and potential liquidity provision opportunities as pools are created. This query monitors `PoolCreated` events from the Aerodrome Finance smart contract, returning pool addresses, token pairs, and creation timestamps. [Get latest liquidity pools on Aerodrome Finance — Query ➤](https://ide.bitquery.io/Latest-Liquidity-Pools-on-Aerodome)
Click to expand GraphQL query ```graphql { EVM(dataset: combined, network: base) { Events( orderBy: { descending: Block_Number } limit: { count: 10 } where: { Log: { SmartContract: { is: "0x420dd381b31aef6683db6b902084cb0ffece40da" } Signature: { Name: { is: "PoolCreated" } } } } ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Value { ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ```
**Response Structure:** The query returns pool creation events with the following information: ```json { "Arguments": [ { "Value": { "address": "0x02f92800f57bcd74066f5709f1daa1a4302df875" } }, { "Value": { "address": "0xf564f589f58ced0127e48e1a02093ba53c2856ed" } }, { "Value": { "bool": false } }, { "Value": { "address": "0xa187378f0f3613e42b6ad5cc063a01060f82763f" } }, { "Value": { "bigInteger": "1539" } } ], "Block": { "Date": "2024-07-10", "Number": "16894743" }, "Log": { "Signature": { "Name": "PoolCreated", "Parsed": true, "Signature": "PoolCreated(address,address,bool,address,uint256)" }, "SmartContract": "0x420dd381b31aef6683db6b902084cb0ffece40da" }, "Transaction": { "Hash": "0xc5049804074b77ccb975b9617974ee40533634b8d6d8cabf2865cebb94c462a4" } } ``` **Understanding the Response:** - **Token Addresses**: The first two address arguments (`0x02f92800f57bcd74066f5709f1daa1a4302df875` and `0xf564f589f58ced0127e48e1a02093ba53c2856ed`) represent the two tokens in the trading pair. - **Pool Address**: The fourth argument (`0xa187378f0f3613e42b6ad5cc063a01060f82763f`) is the newly created liquidity pool address. - **Pool Type**: The boolean value indicates whether the pool is stable or volatile. - **Pool ID**: The bigInteger value is the unique pool identifier. ## Get Liquidity of a Pool Query the current liquidity levels for any Aerodrome Finance pool by pool address. This query retrieves the token balances for both assets in a liquidity pool, allowing you to calculate total value locked (TVL), assess pool depth, and analyze liquidity distribution.
Click to expand GraphQL query ```graphql query MyQuery { EVM(dataset: combined, network: base) { Balances( where: { Balance: { Address: { is: "0x1e039aade407a94df380649b33b52cb8ad41c755" } } Currency: { SmartContract: { in: [ "0x4200000000000000000000000000000000000006" "0xa999542c71febba77602fbc2f784ba9ba0c850f6" ] } } } orderBy: { descending: Balance_Amount } ) { Currency { Name } Balance { Amount(selectWhere: { gt: "0" }) } } } } ```
## Video Tutorials ### Video Tutorial | How to stream Realtime Prices, OHLCV, and Moving Averages for trading pairs on Aerodrome DEX ### Video Tutorial | How to Get Latest Trades and Most Traded Tokens on Aerodrome Finance ### Video Tutorial | How to Get Latest Liquidity Pools and Pool Liquidity on Aerodrome Finance --- ## Aerodrome Gauge Vaults API URL: https://docs.bitquery.io/docs/blockchain/Base/aerodrome-gauge-vaults-api/ Aerodrome gauge vaults on Base: get newly created vaults and the latest deposits, withdraws and ClaimRewards events, overall or for a specific gauge pool. # Aerodrome Gauge Vaults API — Base (Deposits, Withdraws, Rewards) Aerodrome Finance gauge vaults are staking contracts for LP tokens that let liquidity providers earn AERO emissions. veAERO holders (who lock AERO for up to four years) vote every week to direct emissions across pool gauges. LPs staking in the most‑voted gauges earn more AERO, while veAERO voters receive trading fees from the pools they support and may be incentivized by external bribes. Users can also auto‑compound earned AERO into veAERO to build long‑term voting power. This page covers, on Base: - New gauge creation events (where emissions can flow next) - Deposits and withdraws into gauge vaults (LP staking flows) - Reward claims from gauges (realized emissions) You may also be interested in: - [Base Network DEX APIs ➤](/docs/blockchain/Ethereum/dextrades/dex-api/) - [Token Trades APIs ➤](/docs/blockchain/Ethereum/dextrades/token-trades-apis/) - [Liquidity Pool APIs ➤](/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api/) Use the GraphQL queries below to monitor governance‑directed liquidity incentives across Aerodrome on Base. If you need other data points, reach out to [support](https://t.me/Bloxy_info). :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ### Table of Contents - [Latest Created Aerodrome Gauge Vaults](#latest-created-aerodrome-gauge-vaults) - [Latest Aerodrome Gauge Vaults Deposits](#latest-aerodrome-gauge-vaults-deposits) - [Latest Aerodrome Gauge Vaults ClaimRewards](#latest-aerodrome-gauge-vaults-claimrewards) - [Latest Aerodrome Gauge Vaults Withdraws](#latest-aerodrome-gauge-vaults-withdraws) - [Get Latest Withdraws of a specific gauge pool](#get-latest-withdraws-of-a-specific-gauge-pool) - [Get Latest Deposits of a specific gauge pool](#get-latest-deposits-of-a-specific-gauge-pool) - [Get Latest ClaimRewards on a specific gauge pool](#get-latest-claimrewards-on-a-specific-gauge-pool) ## Latest Created Aerodrome Gauge Vaults Discover newly created gauge vaults on Aerodrome (Base). Gauges are staking contracts that receive veAERO‑directed emissions. Use this to track where future AERO rewards may flow as new pools receive gauges. `0xf5601f95708256a118ef5971820327f362442d2d` is the `Aerodrome : Voter` contract. [Latest Created Gauge Vaults — Query ➤](https://ide.bitquery.io/latest-created-gauges#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: base) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Log: { Signature: { Name: { is: "GaugeCreated" } } SmartContract: { is: "0x16613524e02ad97eDfeF371bC883F2F5d6C480A5" } } } ) { Block { Time } Transaction { Hash } Arguments { Index Name Path { Index Name Type } Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { From To } Log { Signature { Name } SmartContract } } } } ```
## Latest Aerodrome Gauge Vaults Deposits Monitor LP staking into gauge vaults. This shows recent `Deposit` events to a gauge contract, helping you track which pools are attracting liquidity ahead of weekly emissions. `0xf5601f95708256a118ef5971820327f362442d2d` is the `Aerodrome : Gauge Implementation` contract. [Latest Gauge Vaults Deposits — Query ➤](https://ide.bitquery.io/latest-gauge-vaults-deposits-transactions#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: base) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Call: { To: { is: "0xf5601f95708256a118ef5971820327f362442d2d" } } Log: { Signature: { Name: { is: "Deposit" } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Arguments { Index Name Path { Index Name Type } Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { From To } Log { Signature { Name Signature } SmartContract } } } } ```
## Latest Aerodrome Gauge Vaults ClaimRewards Track when stakers claim accumulated AERO emissions from gauges. Use this to measure realized rewards and active participation across gauge vaults. `0xf5601f95708256a118ef5971820327f362442d2d` is the `Aerodrome : Gauge Implementation` contract. [Latest Aerodrome Gauge Vaults ClaimRewards — Query ➤](https://ide.bitquery.io/latest-gauge-vaults-claimRewards-transactions#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: base) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Call: { To: { is: "0xf5601f95708256a118ef5971820327f362442d2d" } } Log: { Signature: { Name: { is: "ClaimRewards" } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Arguments { Index Name Path { Index Name Type } Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { From To } Log { Signature { Name Signature } SmartContract } } } } ```
## Latest Aerodrome Gauge Vaults Withdraws Observe LP exits from gauge vaults via `Withdraw` events. This helps you detect liquidity outflows and shifts in staking positions across pools. `0xf5601f95708256a118ef5971820327f362442d2d` is the `Aerodrome : Gauge Implementation` contract. [Latest Aerodrome Gauge Vaults Withdraws — Query ➤](https://ide.bitquery.io/latest-gauge-vaults-withdraw-transactions_1#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: base) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Call: { To: { is: "0xf5601f95708256a118ef5971820327f362442d2d" } } Log: { Signature: { Name: { is: "Withdraw" } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Arguments { Index Name Path { Index Name Type } Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { From To } Log { Signature { Name Signature } SmartContract } } } } ```
## Get Latest Withdraws of a specific gauge pool Filter withdraw activity for a single gauge pool. Useful for monitoring liquidity changes and unstaking patterns of a targeted pool. `0x5d05ef25a5f933271e1f0fdc02dc3eab6a4ea687` is the `Aerodrome Finance CL100 WETHVVV Pool Gauge` contract. [Get Latest Withdraws of a specific gauge pool — Query ➤](https://ide.bitquery.io/latest-Aerodrome-Finance-CL100-WETHVVV-Pool-Gauge-withdraw-transactions_1)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: base) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Call: { From: { is: "0x5d05ef25a5f933271e1f0fdc02dc3eab6a4ea687" } } Log: { Signature: { Name: { is: "Withdraw" } } } TransactionStatus: { Success: true } } ) { Block { Time Number } Transaction { Hash } Arguments { Index Name Path { Index Name Type } Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { From To } Log { Signature { Name Signature } SmartContract } } } } ```
## Get Latest Deposits of a specific gauge pool View deposit activity for a specific gauge pool to understand where LPs are allocating capital and how staking momentum evolves. `0x5d05ef25a5f933271e1f0fdc02dc3eab6a4ea687` is the `Aerodrome Finance CL100 WETHVVV Pool Gauge` contract. [Get Latest Deposits of a specific gauge pool — Query ➤](https://ide.bitquery.io/latest-Aerodrome-Finance-CL100-WETHVVV-Pool-Gauge-deposits#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: base) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Call: { From: { is: "0x5d05ef25a5f933271e1f0fdc02dc3eab6a4ea687" } } Log: { Signature: { Name: { is: "Deposit" } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Arguments { Index Name Path { Index Name Type } Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { From To } Log { Signature { Name Signature } SmartContract } } } } ```
## Get Latest ClaimRewards on a specific gauge pool See reward claims for a particular gauge pool to quantify realized emissions by its stakers over time. `0x5d05ef25a5f933271e1f0fdc02dc3eab6a4ea687` is the `Aerodrome Finance CL100 WETHVVV Pool Gauge` contract. [Get Latest ClaimRewards on a specific gauge pool — Query ➤](https://ide.bitquery.io/latest-Aerodrome-Finance-CL100-WETHVVV-Pool-Gauge-claimRewards-Transactions#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: base) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Call: { From: { is: "0x5d05ef25a5f933271e1f0fdc02dc3eab6a4ea687" } } Log: { Signature: { Name: { is: "ClaimRewards" } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Arguments { Index Name Path { Index Name Type } Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { From To } Log { Signature { Name Signature } SmartContract } } } } ```
--- ## Algorand API Documentation URL: https://docs.bitquery.io/docs/blockchain/Algorand/ Algorand API overview: query blocks, transactions, addresses, smart contracts and fund tracing on Algorand, with a quick start and links to each API page. # Algorand API Documentation ## Overview Bitquery's Algorand APIs let you query the chain through GraphQL — blocks, transactions, ALGO and ASA transfers, address balances, smart contract calls, parsed call arguments, and multi-hop fund flow. Replace the example addresses and asset IDs in any query with your own values to point them at real wallets and assets. If you get stuck or need a data point that isn't covered here, reach out on [Telegram](https://t.me/Bloxy_info). :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ### What you can do with the Algorand API - Pull blocks by proposer, height, or time window with protocol version, rewards, and timestamps. - Get transactions with fees, types, senders, groups, and daily or per-address counts. - Track ALGO and ASA transfers filtered by asset ID, sender, receiver, or date range. - Look up native ALGO balances, multi-address snapshots, and smart contract bytecode. - Count and filter smart contract calls by transaction type (`pay`, `acfg`, and others). - Read parsed argument names, types, and values from smart contract calls and events. - Trace ALGO and ASA flows across multiple hops with Coinpath. ### How the Algorand API differs from running your own node | Algorand node / indexer | Bitquery Algorand API | | --- | --- | | Raw chain state — you build the indexer | Pre-indexed and parsed: blocks, txs, transfers, app calls | | No historical analytics out of the box | History, joins, aggregations, USD conversion on transfers | | You decode transaction types and app args yourself | GraphQL response — pick the fields you need | | Best for submitting transactions and full validation | Best for analytics, dashboards, wallet UIs, and compliance work | ## Quick start This query returns the 5 most recent Algorand blocks with height, hash, reward, proposer, and timestamp. ```graphql { algorand(network: algorand) { blocks(options: {desc: "height", limit: 5}) { height hash reward proposer { address } timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } } } ``` ## API reference ### Core data - [Algorand Blocks API](/docs/blockchain/Algorand/algorand-blocks-api) — block lookups by proposer, height, or time, plus reward aggregates. - [Algorand Transactions API](/docs/blockchain/Algorand/algorand-transactions-api) — transaction details, daily counts, unique senders, and hash lookups. - [Algorand Transfers API](/docs/blockchain/Algorand/algorand-transfers-api) — ALGO and ASA transfer history with USD amounts. ### Addresses and contracts - [Algorand Address API](/docs/blockchain/Algorand/algorand-address-api) — ALGO balances, multi-address lookups, and smart contract bytecode. - [Algorand Smart Contract Calls API](/docs/blockchain/Algorand/algorand-smart-contract-calls-api) — app call counts, transaction-type filters, and new asset creation tracking. - [Algorand Arguments API](/docs/blockchain/Algorand/algorand-arguments-api) — parsed argument names, types, and values from calls and events. ### Fund tracing - [Algorand Coinpath API](/docs/blockchain/Algorand/algorand-coinpath-api) — multi-hop ALGO and ASA flow tracing for compliance and treasury work. ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Algorand Address API URL: https://docs.bitquery.io/docs/blockchain/Algorand/algorand-address-api/ Algorand address queries: get ALGO balances for one or many addresses, plus smart contract bytecode and source, with GraphQL examples you can run. # Algorand Address API The Address API gives you native ALGO balances for one or many accounts, plus smart contract details — bytecode and source — for application addresses. Use it for wallet dashboards, treasury monitoring, and inspecting on-chain program code without running your own indexer. :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get ALGO balance for a single address Returns the native ALGO balance for one account. Replace the address with your target wallet or contract. ```graphql { algorand(network: algorand) { address( address: {is: "ADDRESS_HERE"} ) { address { address } balance } } } ``` Add a `date` filter to reconstruct balance context at a point in time, or use the `in` operator shown below for batch lookups. ## Get ALGO balances for multiple addresses Pull balances for several addresses in a single request. Handy for portfolio views and treasury snapshots. ```graphql { algorand(network: algorand) { address(address: {in: ["ADDRESS_ONE", "ADDRESS_TWO", "ADDRESS_THREE"]}) { address { address } balance } } } ``` ## Get smart contract bytecode and source Returns the bytecode and source of an Algorand application address. Add the `balance` field to the `smartContract` block if you also need the contract's ALGO holdings. ```graphql { algorand(network: algorand) { address(address: {is: "SMART_CONTRACT_ADDRESS"}) { smartContract { address { address } bytecode source } } } } ``` ## Related resources - [Algorand Transfers API](/docs/blockchain/Algorand/algorand-transfers-api) — ALGO and ASA transfer history per address - [Algorand Coinpath API](/docs/blockchain/Algorand/algorand-coinpath-api) — multi-hop fund flow tracing --- ## Algorand Arguments API URL: https://docs.bitquery.io/docs/blockchain/Algorand/algorand-arguments-api/ Algorand smart contract arguments: list recent application call arguments and filter them by smart contract address, with GraphQL query examples. # Algorand Arguments API When Bitquery parses an Algorand smart contract call or event, the Arguments API exposes each argument's index, type, and value alongside transaction and block context. Use it to inspect app call payloads, filter calls by specific argument values, or build dashboards around on-chain program activity. :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## List recent smart contract arguments Returns the 10 most recent parsed arguments across Algorand, with transaction hash, sender, transaction type, and block timestamp. Each row includes the argument index and decoded value. ```graphql { algorand(network: algorand) { arguments(options: {limit: 10, desc: "block.timestamp.iso8601"}) { argindex block { timestamp { iso8601 } } firstRound genesisId lastRound note transaction { hash } txSender { address annotation } txType value } } } ``` ## Filter arguments by smart contract address Narrow results to a specific application. You can also filter by `txType`, `txHash`, `argindex`, or `value` depending on what you're looking for. ```graphql { algorand(network: algorand) { arguments( smartContractAddress: {is: "2TUBOBZ7CP7EZXFOWULEG5HE6WJ34TT7SBZ5AMHGR222O7RZNBK3I4BUMY"} options: {limit: 10, desc: "block.timestamp.iso8601"} ) { argindex value txType transaction { hash } txSender { address } smartContract { address { address } } } } } ``` ## Related resources - [Algorand Smart Contract Calls API](/docs/blockchain/Algorand/algorand-smart-contract-calls-api) — call counts and transaction-type filters - [Algorand Transactions API](/docs/blockchain/Algorand/algorand-transactions-api) — full transaction details and hash lookups --- ## Algorand Blocks API - Query Blocks by Proposer URL: https://docs.bitquery.io/docs/blockchain/Algorand/algorand-blocks-api/ Algorand blocks by proposer: list recent blocks proposed by an address and sum the block rewards a proposer earned, with ready-to-run GraphQL queries. # Algorand Blocks API The Blocks API returns block-level data on Algorand: height, hash, protocol version, proposer, seed, reward, and timestamp. Use it to drive explorer front-ends, monitor chain progression, track validator participation, or aggregate block rewards over time. :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get recent blocks proposed by an address Returns the 10 most recent blocks proposed by a specific address after a given date, ordered by timestamp descending. Swap the `proposer` filter for a height or time window when you need a broader scan. ```graphql { algorand(network: algorand) { blocks( date: {after: "2023-08-05"} options: {desc: "timestamp.iso8601", limit: 10} proposer: {is: "PROPOSER_ADDRESS_HERE"} ) { currentProtocol hash height proposer { address } reward seed timestamp { iso8601 } } } } ``` Remove the `proposer` filter to query all blocks in the date range, or adjust `limit` and `date` for different windows. ## Sum block rewards earned by a proposer Aggregates total block rewards for a proposer address. Add a `date` filter to limit the time range, or swap `sum` for `average` to get mean reward per block. ```graphql { algorand(network: algorand) { blocks( proposer: {is: "PROPOSER_ADDRESS_HERE"} ) { reward(calculate: sum) } } } ``` ## Related resources - [Algorand Transactions API](/docs/blockchain/Algorand/algorand-transactions-api) — per-block transaction details and daily counts - [Algorand Address API](/docs/blockchain/Algorand/algorand-address-api) — proposer and wallet balances --- ## Algorand Coinpath API URL: https://docs.bitquery.io/docs/blockchain/Algorand/algorand-coinpath-api/ Algorand Coinpath queries to trace outgoing fund flows from a sender and count coinpath transactions received by an address, with ready-to-run GraphQL examples. # Algorand Coinpath API Coinpath walks ALGO and ASA flows between Algorand addresses — forward to see where funds went, backward to see where they came from. The API returns senders, receivers, hop depth, amounts, currency metadata, and transaction details at each level. Common use cases: AML screening, treasury audits, exchange deposit tracing, and source-of-funds verification. :::tip Trace Algorand funds with AI — no queries needed Connect the [Bitquery MCP server](https://mcp.bitquery.io/) to Claude, Cursor, or ChatGPT and ask in plain English: _"Trace where ALGO from this address went, 3 hops deep, and show the largest receivers."_ The agent walks the fund flow for you. See [AI Investigations](https://bitquery.io/solutions/ai-investigations) and the [Tracing MCP guide](/docs/mcp/Tracing/overview). ::: :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Trace outgoing fund flows from a sender Returns the 10 most recent coinpath entries for transfers sent from a specific address after a given date. Swap `sender` for `receiver` to trace incoming flows instead. ```graphql { algorand(network: algorand) { coinpath( date: {after: "2023-08-05"} options: {desc: "block.timestamp.iso8601", limit: 10} sender: {is: "SENDER_ADDRESS_HERE"} ) { amount block { timestamp { iso8601 } } currency { address name } depth receiver { address } transaction { hash value } } } } ``` ## Count coinpath transactions received by an address Counts total coinpath entries received by an address after a given date. Add a `sender` filter to narrow by source, or replace `count` with `amount(calculate: sum)` to get total value moved. ```graphql { algorand(network: algorand) { coinpath( date: {after: "2023-08-01"} receiver: {is: "BWSNMG43TUYEOHE76J6KDWIY6MU4U6JFJYGAYCZA2RF5IS3XPO3P3G4FEI"} ) { count } } } ``` ## Related resources - [Algorand Transfers API](/docs/blockchain/Algorand/algorand-transfers-api) — raw ALGO and ASA transfer history - [Algorand Address API](/docs/blockchain/Algorand/algorand-address-api) — wallet balances and contract bytecode --- ## Algorand Smart Contract Calls API URL: https://docs.bitquery.io/docs/blockchain/Algorand/algorand-smart-contract-calls-api/ Algorand smart contract calls: count calls per block and by transaction type, filter latest calls by type, and track newly created assets (acfg). # Algorand Smart Contract Calls API The Smart Contract Calls API returns parsed application call data on Algorand: transaction type, sender, smart contract address, block context, and call counts. Filter by `txType` to isolate payments (`pay`), asset configuration (`acfg`), or any other Algorand transaction type. :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Count unique smart contract calls in the latest block Returns the count of unique smart contract calls in the most recent block after a given date. [Run query](https://ide.bitquery.io/Get-Count-of-Smart-Contract-Calls-in-Latest-Block_1) ```graphql { algorand(network: algorand) { smartContractCalls( date: {after: "2023-08-05"} options: {desc: "block.timestamp.iso8601", limit: 1} ) { block { timestamp { iso8601 } } count(uniq: calls) } } } ``` ## Track newly created assets (acfg transactions) Returns the 10 most recent asset configuration transactions — `acfg` stands for asset config. Each result includes the smart contract address, transaction hash, sender, and block timestamp. [Run query](https://ide.bitquery.io/Track-latest-assets-created-on-Algorand-network_1#) ```graphql { algorand(network: algorand) { smartContractCalls( options: {desc: "block.timestamp.iso8601", limit: 10} txType: {is: acfg} ) { block { timestamp { iso8601 } } smartContract { address { address } } transaction { hash } txSender { address } txType } } } ``` ## Count smart contract calls by transaction type since genesis Returns the total number of calls grouped by transaction type across Algorand mainnet history. [Run query](https://ide.bitquery.io/Count-of-each-trxn-type-called-till-now-on-Algorand-network#) ```graphql query MyQuery { algorand(network: algorand) { smartContractCalls(options: {desc: "count"}) { txType count } } } ``` ## Get latest smart contract calls filtered by type Returns the 10 most recent `pay` (payment) transactions with smart contract address, hash, sender, and block timestamp. Swap `pay` for any other `txType` value. ```graphql { algorand(network: algorand) { smartContractCalls( date: {after: "2023-08-05"} options: {desc: "block.timestamp.iso8601", limit: 10} txType: {is: pay} ) { block { timestamp { iso8601 } } smartContract { address { address } } transaction { hash } txSender { address } txType } } } ``` ## Video: tracking newly created tokens on Algorand ## Related resources - [Algorand Arguments API](/docs/blockchain/Algorand/algorand-arguments-api) — parsed argument names, types, and values - [Algorand Transactions API](/docs/blockchain/Algorand/algorand-transactions-api) — full transaction details and daily counts --- ## Algorand Transactions API URL: https://docs.bitquery.io/docs/blockchain/Algorand/algorand-transactions-api/ Algorand transactions: latest and date-range transactions, daily counts, unique senders per day, counts sent from an address, and lookup by hash. # Algorand Transactions API The Transactions API returns transaction-level data on Algorand: block context, fees, types, senders, groups, and currency metadata. Use it for paginated transaction feeds, daily activity dashboards, sender analytics, and hash-based lookups. :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get the latest Algorand transactions Returns the 10 most recent transactions after a given date with block height, timestamp, currency, fee, group, hash, sender, subtype, and type. ```graphql { algorand(network: algorand) { transactions( date: {after: "2023-08-05"} options: {desc: "block.timestamp.iso8601", limit: 10} ) { block { height timestamp { iso8601 } } currency { address name } fee group hash index sender { address } subtype type } } } ``` ## Get transactions in a date range Paginated query for all transactions in a specific window. [Run query](https://ide.bitquery.io/All-Transactions-on-Algorand#) ```graphql query MyQuery { algorand(network: algorand) { transactions( options: {desc: "block.height", limit: 10, offset: 0} date: {since: "2024-07-08", till: "2024-07-09"} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } currency { tokenType tokenId symbol name decimals address } fee firstRound poolerror note lastRound index hash group genesisId genesisHash subtype type sender { address annotation } } } } ``` ## Get daily transaction counts for recent days Returns the number of transactions per day over the last 10 days, ordered by date descending. [Run query](https://ide.bitquery.io/Daily-Transaction-Count-for-last-10-days#) ```graphql query MyQuery { algorand(network: algorand) { transactions(options: {desc: "date.date", limit: 10}) { date { date } count } } } ``` ## Count unique senders for a single day Counts distinct transaction senders on a specific date. [Run query](https://ide.bitquery.io/Daily-Unique-Txn-Senders-on-algorand#) ```graphql query MyQuery { algorand(network: algorand) { transactions(date: {is: "2024-07-08"}) { Unique_senders: count(uniq: senders) } } } ``` ## Count transactions sent from an address Returns the total number of transactions sent by a specific address. ```graphql { algorand(network: algorand) { transactions( txSender: {is: "ADDRESS_HERE"} ) { count } } } ``` ## Look up a transaction by hash Returns block context, currency, sender, subtype, and type for a single transaction hash. ```graphql { algorand(network: algorand) { transactions( txHash: {is: "TXN_HASH_HERE"} ) { block { height timestamp { iso8601 } } currency { address name } sender { address } subtype type } } } ``` ## Video: Algorand transaction data with Bitquery ## Related resources - [Algorand Transfers API](/docs/blockchain/Algorand/algorand-transfers-api) — ALGO and ASA transfer history - [Algorand Blocks API](/docs/blockchain/Algorand/algorand-blocks-api) — block-level context for each transaction --- ## Algorand Transfers API - Track ALGO & ASA Token Transfers URL: https://docs.bitquery.io/docs/blockchain/Algorand/algorand-transfers-api/ Algorand Transfers API - Track ALGO & ASA Token Transfers: monitor Algorand native and token transfers in real time with Bitquery GraphQL APIs. # Algorand Transfers API The Transfers API returns ALGO and ASA (Algorand Standard Asset) movements with amounts in native units and USD, sender and receiver addresses, block context, and transaction hashes. Filter by asset ID, date range, or address to build wallet history feeds, treasury monitors, and token analytics dashboards. :::info Endpoint Algorand GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get transfers for a specific asset in a date range Returns transfers for asset ID `31566704` between two dates, ordered by block height descending. Swap the `currency` filter for any ASA ID or ALGO. [Run query](https://ide.bitquery.io/All-the-transfers-of-an-asset-on-Algorand-Mainnet-in-a-specific-timeframe) ```graphql query MyQuery { algorand(network: algorand) { transfers( options: {desc: "block.height", limit: 10, offset: 0} currency: {is: 31566704} date: {since: "2024-07-01", till: "2024-07-09"} ) { amount amount_usd: amount(in: USD) currency { tokenType tokenId symbol name decimals address } receiver { address annotation } sender { address annotation } block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } transferType transaction { hash } } } } ``` ## Get transfers to or from an address for a specific asset Uses the `any` filter to match transfers where the address appears as either sender or receiver. [Run query](https://ide.bitquery.io/traansfers-where-a-currency-is-sent-from-or-sent-to-a-particular-address) ```graphql query MyQuery { algorand(network: algorand) { transfers( date: {since: "2024-07-01", till: "2024-07-09"} currency: {is: 849191641} any: [ {sender: {in: ["OLP2LMN4NDMT6FKRFCMV5J7U3LTUFXKOHOMGWYBMIA675FSRVWT4C5HWVI"]}} {receiver: {in: ["OLP2LMN4NDMT6FKRFCMV5J7U3LTUFXKOHOMGWYBMIA675FSRVWT4C5HWVI"]}} ] ) { block { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } height } sender { address annotation } receiver { address annotation } currency { address symbol } amount amount_usd: amount(in: USD) transaction { hash } } } } ``` ## Video: Algorand transfer data with Bitquery ## Related resources - [Algorand Address API](/docs/blockchain/Algorand/algorand-address-api) — wallet balances and contract bytecode - [Algorand Coinpath API](/docs/blockchain/Algorand/algorand-coinpath-api) — multi-hop fund flow tracing --- ## Analyze a Token ICO with the Transfers API: Mint, Distributor, Investors URL: https://docs.bitquery.io/docs/blockchain/Ethereum/transfers/ico-token-ownership-transfer/ Rebuild a token sale from Ethereum transfers with Bitquery GraphQL: find the mint, the distributor contract and every buyer, then count them. # Analyze a Token ICO with the Transfers API: Mint, Distributor, Investors A token sale leaves a clean trail in transfer data. The token is minted to a distributor contract, the contract sends tokens to each buyer as the sale's conditions are met, and the set of receivers is the investor list. Three `Transfers` queries on the `combined` dataset rebuild that trail for any ERC-20 sale: the mint from the zero address tells you where the supply went, transfers from that address list the buyers, and `count` with `uniq` size the sale. The worked example is the PEPU token, `0x906cc2ad139eb6637e28605f908903c8adce566a`, whose sale ran in 2024; put another token contract in its place for a current one. Every query runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. ## Step 1: find where the supply was minted A mint is a transfer from the zero address. The `Receiver` of the mint is the contract that distributes the sale. Saved query [here](https://ide.bitquery.io/Get-Minted-Address-of-the-ICO-Token). ```graphql query MyQuery { EVM(network: eth, dataset: combined) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0x906cc2ad139eb6637e28605f908903c8adce566a"}}, Success: true, Sender: {is: "0x0000000000000000000000000000000000000000"}}} ) { Transfer { Amount Currency { Name Symbol SmartContract } Receiver Sender } } } } ``` For PEPU the mint went to `0xf0163c18f8d3fc8d5b4ca15e07d0f9f75460335f`, the distributor used in the next two queries. ## Step 2: list the buyers Every transfer sent by the distributor is a delivery to a buyer. The `Receiver` column is the investor list, with the amount each one received. Saved query [here](https://ide.bitquery.io/Get-all-Holders-Address-of-the-ICO-Token_1). ```graphql query MyQuery { EVM(network: eth, dataset: combined) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0x906cc2ad139eb6637e28605f908903c8adce566a"}}, Success: true, Sender: {is: "0xf0163c18f8d3fc8d5b4ca15e07d0f9f75460335f"}}} ) { Transfer { Amount Currency { Name Symbol SmartContract } Receiver Sender } count } } } ``` ## Step 3: size the sale The same filter with `count` and `uniq` gives the number of deliveries and the number of distinct buyers in one row. Saved query [here](https://ide.bitquery.io/Number-of-Purchasers-in-ICO#). ```graphql query MyQuery { EVM(network: eth, dataset: combined) { Transfers( where: {Transfer: {Amount: {gt: "0"}, Currency: {SmartContract: {is: "0x906cc2ad139eb6637e28605f908903c8adce566a"}}, Sender: {is: "0xf0163c18f8d3fc8d5b4ca15e07d0f9f75460335f"}}} ) { count buyers: uniq(of: Transfer_Receiver) Transfer { Currency { Name Symbol SmartContract } } } } } ``` ## Where to go from here - Did buyers hold or sell? Run the [Balances and Holders cubes](/docs/cubes/balances-cube) on the buyer list, or filter `DEXTrades` on the token to see the first sells. - What did the sale raise? The ETH or stablecoin transfers into the distributor, or the `Calls` into it with `Value`, give the other side of each purchase. - Watching a live sale: change `query` to `subscription`, drop the dataset argument, and keep the distributor as `Sender` to see each delivery as it happens. ## Video tutorial on analyzing the PEPU sale ## Related pages - [Ethereum transfers API](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api) - [Balances and Holders cubes](/docs/cubes/balances-cube) - [Transfers cube](/docs/cubes/transfers-cube) - [Ethereum API hub](/docs/blockchain/Ethereum/) --- ## Arbitrum API Documentation URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/ Arbitrum on-chain data: DEX and perp trades, slippage, liquidity, transfers and balances, plus WebSocket and webhook delivery and cross-chain queries. # Arbitrum API Documentation Unlock the full potential of Arbitrum with comprehensive blockchain data—from GMX perpetual trading analytics and DEX swaps to liquidity monitoring, slippage analysis, cross-chain bridge monitoring, and smart contract interactions. This complete guide delivers production-ready GraphQL APIs, real-time streaming data, and practical examples for tracking trades, balances, liquidity pools, slippage, events, and more across the Arbitrum ecosystem. Whether you're building DeFi dashboards, trading algorithms, or cross-chain applications, discover all the Arbitrum data solutions you need here. Need help crafting a query or subscription? Message us on [support](https://t.me/Bloxy_info). ## What is the Bitquery Arbitrum API? :::tip Building a trading app or DEX UI on Arbitrum? For **real-time trades and prices on Arbitrum** (and the last ~30 days), use the curated [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. For **historical Arbitrum data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: It's a GraphQL interface over curated, indexed Arbitrum data. Write powerful queries instead of building and maintaining your own indexer for the fastest L2 solution. ## What can you build with it? Track GMX perpetual positions, monitor DEX liquidity, pool reserves, slippage, and trading volumes, analyze cross-chain bridge flows, stream smart contract events, compute trading KPIs, and power real-time dashboards for the most active L2 ecosystem. ## How is it different from raw Arbitrum RPC? | Feature | Arbitrum RPC | Bitquery Arbitrum API | | ------------------- | -------------------------------- | ------------------------------ | | **Data Format** | Raw JSON-RPC responses | Pre-indexed, enriched GraphQL | | **Historical Data** | No built-in history | Full historical data since L2 | | **Analytics** | Manual aggregation required | Built-in joins, aggregations | | **Real-time** | Basic subscription support | Rich streaming with filtering | | **Use Case** | Transaction submission, node ops | Analytics, monitoring, trading | | **Infrastructure** | Run your own nodes | Fully managed, auto-scaling | ## WebSockets and Webhooks Most queries can be turned into live streams by switching `query` to `subscription`, and consumed over WebSocket. See examples and code snippets [here](/docs/subscriptions/websockets/). ## DEX and Perp APIs - [Arbitrum Dex Trades](./DexTrades) - [GMX API](./gmx-api) - [esGMX API](./esgmx-api) Query and subscribe to perpetual trading data, DEX swaps, liquidity events, and trading analytics across Arbitrum's leading protocols. ## Arbitrum Slippage API - [Arbitrum Slippage API](./arbitrum-slippage-api) Get slippage and price impact data for Arbitrum DEX pools. Understand price impact and liquidity depth for token swaps, calculate maximum input amounts at different slippage tolerances, and monitor real-time slippage data across all DEX pools on Arbitrum. ## Arbitrum Liquidity API - [Arbitrum Liquidity API](./arbitrum-liquidity-api) Monitor real-time liquidity changes, track pool reserves, and analyze liquidity depth for token pairs on Arbitrum DEX pools. Track when liquidity is added or removed, monitor pool health and depth, and analyze liquidity patterns across different pools. ## Core Arbitrum APIs - [Blocks & Transactions](./Blocks_Transactions) - [Smart Contract Calls](./Smart_Contract_Calls) - [Smart Contract Events](./Smart_Contract_Events) - [Balance API](./arbitrum-balance-api) Access comprehensive blockchain data including blocks, transactions, contract interactions, and real-time balance updates. ## Cross-chain - [Arbitrum Cross Chain](./arbitrum-cross-chain) Monitor cross-chain bridge activities, deposits, withdrawals, and asset flows between Arbitrum and other networks. ## Videos ### Video Tutorial | GMX and esGMX ### Video Tutorial | Across Bridge Deposits on Arbitrum ### Video Tutorial | Top Traders of a Token on Arbitrum ### Video Tutorial | Track Realtime DEXTrades of a Token on Arbitrum ### Video Tutorial | OHLC Data of a Token Pair on Arbitrum ### Video Tutorial | Top Bought & Top Sold Tokens on Arbitrum ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Arbitrum Address Balance API URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/arbitrum-balance-api/ Arbitrum Address Balance API: fetch current and historical Arbitrum balances with Bitquery GraphQL balance queries. Keep queries fast with indexed filters. # Arbitrum Address Balance API The **Balances** API returns current and historical token balances for an address on Arbitrum. To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | | -------------- | ------------------------------------------------------------------------------------------- | | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | Examples: [All Token Balances](#balance-of-an-address) · [Native ETH (Arbitrum)](#native-eth-arbitrum-balance) · [Balance on a Date](#balance-on-a-specific-date) · [Specific Token](#balance-for-a-specific-token) · [Holder Snapshot](#token-holder-snapshot) ## Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. [Run in IDE](https://ide.bitquery.io/Arbitrum-Balance-of-an-Address) ```graphql query { EVM(network: arbitrum, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xDef1C0ded9bec7F1a1670819833240f027b25EfF" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Native ETH (Arbitrum) Balance Returns the native ETH balance for a wallet on Arbitrum (not ERC-20 tokens). Filter with `Currency: { Native: true }` instead of a token contract address. [Run in IDE](https://ide.bitquery.io/arbitrum-native-balances-address) ```graphql query { EVM(network: arbitrum, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xDef1C0ded9bec7F1a1670819833240f027b25EfF" } } Currency: { Native: true } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` **Parameters** - `network: arbitrum`: Arbitrum mainnet. - `dataset: combined`: Merges realtime and archive data for the latest balance state. - `Balance.Address`: Wallet address to query. - `Currency.Native: true`: Native ETH on Arbitrum only (see [Native ETH (Arbitrum) Balance](#native-eth-arbitrum-balance)). **Returned fields** - `Currency.Symbol`, `Currency.SmartContract`: Token metadata. - `Balance.Amount`, `Balance.AmountInUSD`: Token balance and USD value (use `selectWhere` to filter non-zero amounts). ## Balance on a Specific Date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. [Run in IDE](https://ide.bitquery.io/arbitrum-balances-by-date) ```graphql query { EVM(network: arbitrum, dataset: archive) { Balances( where: { Block: { Date: { till: "2026-05-05" } } Balance: { Address: { is: "0xDef1C0ded9bec7F1a1670819833240f027b25EfF" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Balance for a Specific Token Add a `Currency.SmartContract` filter. Always use the contract address, not the token name. Use `0x` for native ETH on Arbitrum, or the ERC-20 contract address for a token. [Run in IDE](https://ide.bitquery.io/arbitrum-balances-specific-token) ```graphql query { EVM(network: arbitrum, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xDef1C0ded9bec7F1a1670819833240f027b25EfF" } } Currency: { SmartContract: { is: "0x82af49447d8a07e3bd95bd0d56f35241523fbab1" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Token Holder Snapshot The number of unique holders, token supply, and Gini coefficient for the balance amount before a specific timestamp can be derived using the query below. These stats provide a useful holder snapshot for any given time. [Run in IDE](https://ide.bitquery.io/token-holder-snapshot-arbitrum)
Click to expand GraphQL query ```graphql query { EVM(network: arbitrum, dataset: archive) { Holders( where: { Currency: { SmartContract: { is: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9" } } Balance: { Amount: { gt: "0" } LastChangeTime: { till: "2026-05-20T00:00:00Z" } } Holder: { Address: { not: "0x" } } } ) { Balance { LastChangeTime(maximum: Balance_LastChangeTime) } holders: uniq(of: Holder_Address) supply: sum(of: Balance_Amount) gini(of: Balance_Amount) } } } ```
## Balance History by Date Returns balance snapshots over time for an address. Use `dataset: archive`. Order by `Block_Date` descending and use `limit` to paginate. Add `Currency.SmartContract` under `Currency` to filter by a specific token. [Run in IDE](https://ide.bitquery.io/arbitrum-balances-history) ```graphql query { EVM(network: arbitrum, dataset: archive) { Balances( where: { Balance: { Address: { is: "0xDef1C0ded9bec7F1a1670819833240f027b25EfF" } } } orderBy: { descending: Block_Date } limit: { count: 100 } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } Block { Date } } } } ``` --- ## Arbitrum Cross Chain API URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/arbitrum-cross-chain/ Arbitrum Across bridge tracking: get the latest deposits on the Across Protocol SpokePool and the latest transfers to the Arbitrum SpokePool from its events. # Arbitrum Cross Chain API ## Overview Explore the integration of the **Arbitrum Cross Chain API** to track bridge transfers, interact with smart contracts, and fetch detailed transaction data. For detailed reference, visit the [official Arbitrum documentation](https://docs.arbitrum.io/build-decentralized-apps/token-bridging/token-bridge-erc20). Additional information about migrating to the latest version of Across Protocol is available [here](https://docs.across.to/introduction/migration-guides/migration-from-v2-to-v3#event-changes). ## Tracking Across Bridge Transfers Using SpokePool Events SpokePool events in Across Protocol can be used to monitor the status of bridge transfers effectively. Below are queries that retrieve the latest deposits and transfers related to the Arbitrum SpokePool. ### Latest Deposits on Across Protocol Bridge SpokePool Query the latest deposits made on the Across Protocol Bridge SpokePool. Fetch the most recent deposits and associated details using `V3FundsDeposited` events. - **Query link**: [Run this query](https://ide.bitquery.io/Latest-deposits-on-Across-Bridge) ```graphql { EVM(network: arbitrum) { Events( where: { Log: { SmartContract: { is: "0xe35e9842fceaca96570b734083f4a58e8f7c5f2a" } Signature: { Name: { is: "V3FundsDeposited" } } } } orderBy: { descending: Block_Time } ) { Log { SmartContract Signature { Name } } Transaction { From To } Block { Time ParentHash } Arguments { Name Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` --- ### Latest Transfers to Arbitrum SpokePool Retrieve the latest transfers directed to the Arbitrum SpokePool.Get information on transfers to the SpokePool, such as sender, receiver, currency, and block details. - **Query link**: [Run this query](https://ide.bitquery.io/Across-Protocol-Arbitrum-Transfers) ```graphql { EVM(dataset: combined, network: arbitrum) { Transfers( where: { Transaction: { To: { is: "0xe35e9842fceaca96570b734083f4a58e8f7c5f2a" } } Block: { Date: { is: "2024-12-12" } } } limit: { count: 10 } orderBy: { descending: Block_Number } ) { Transfer { Amount Currency { Name Symbol SmartContract } Sender Receiver } Call { Signature { Name } From To Value CallPath } Block { Number Time } } } } ``` ## Video Tutorial | How to track Across Bridge Deposits on Arbitrum --- ## Arbitrum DEX Trades API URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/DexTrades/ Arbitrum DEX Trades API: get Arbitrum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Scale further with WebSocket subscriptions or Kafka streams. # Arbitrum DEX Trades API :::tip Need real-time Arbitrum DEX data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API** (filter with `Pair.Market.Network: Arbitrum`). Use this page when you need **historical Arbitrum data older than ~30 days** (with `dataset: combined` or `archive`), raw per-swap detail, or call / event context. ::: In this section we will see how to get Arbitrum DEX trades information using our API. ## Live DEX swap stream (Arbitrum) {#crypto-trades-live-stream} [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api): one row per swap, with USD and supply. Filter **`Pair.Market.Network: Arbitrum`**. [When to use this vs chain DEX APIs](/docs/cubes/dextrades-dextradebytokens-trading-trades). Run this subscription in the [Bitquery IDE](https://ide.bitquery.io) (open a new tab, paste the subscription below, and run). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Arbitrum" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` ## Top Trending Pairs on Arbitrum [This](https://ide.bitquery.io/trending-token-pairs-on-Arbitrum) query returns the top trending pairs traded on Arbitrum Chain based on the trade volume for the last 24 hours, and returns info such as latest price, number of buyers and sellers, number of trades in a day and much more. Read [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) to get a better understanding on when to use which cube. ```graphql query pairs( $min_count: String $network: evm_network $time_ago: DateTime $time_10min_ago: DateTime $time_1h_ago: DateTime $time_3h_ago: DateTime $weth: String! $usdc: String! $usdt: String! $usdc2: String! ) { EVM(network: $network) { DEXTradeByTokens( where: { Block: { Time: { since: $time_ago } } any: [ { Trade: { Side: { Currency: { SmartContract: { is: $usdt } } } } } { Trade: { Side: { Currency: { SmartContract: { is: $usdc } } } Currency: { SmartContract: { notIn: [$usdt] } } } } { Trade: { Side: { Currency: { SmartContract: { is: $usdc2 } } } Currency: { SmartContract: { notIn: [$usdt, $usdc] } } } } { Trade: { Side: { Currency: { SmartContract: { is: $weth } } } Currency: { SmartContract: { notIn: [$usdc, $usdt, $usdc2] } } } } { Trade: { Side: { Currency: { SmartContract: { notIn: [$usdc, $usdt, $weth] } } } Currency: { SmartContract: { notIn: [$usdc, $usdc2, $usdt, $weth] } } } } ] } orderBy: { descendingByField: "usd" } limit: { count: 100 } ) { Trade { Currency { Symbol Name SmartContract ProtocolName } Side { Currency { Symbol Name SmartContract ProtocolName } } price_last: PriceInUSD(maximum: Block_Number) price_10min_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_10min_ago } } } ) price_1h_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_1h_ago } } } ) price_3h_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_3h_ago } } } ) } dexes: uniq(of: Trade_Dex_OwnerAddress) amount: sum(of: Trade_Side_Amount) usd: sum(of: Trade_Side_AmountInUSD) sellers: uniq(of: Trade_Seller) buyers: uniq(of: Trade_Buyer) count(selectWhere: { ge: $min_count }) } } } ``` Implementation of this data in a full scale project could be seen on [DEXRabbit](https://dexrabbit.bitquery.io/arbitrum/pair). ![Trending Pairs on Arbitrum](/img/dexrabbit/arbitrum/arbitrum_trending_pairs.png) ## Latest Trades for a Token Pair on Arbitrum This query retrieves all DEX trades on the arbitrum where the Arbitrum currency is `ArbitrumCurrency` and the quote currency is `quoteCurrency` that occurred between the specified dates. You can find the query [here](https://ide.bitquery.io/Pair-last-trades_2) ```graphql query ($network: evm_network!, $ArbitrumCurrency: String!, $limit: Int, $quoteCurrency: String!, $from: String, $till: String) { EVM(network: $network, dataset: archive) { sell: DEXTrades( where: {Trade: {Sell: {Currency: {SmartContract: {is: $ArbitrumCurrency}}}, Buy: {Currency: {SmartContract: {is: $quoteCurrency}}}}, Block: {Date: {since: $from, till: $till}}} orderBy: {descending: Block_Date} limit: {count: $limit} ) { ChainId Block { Time Number } Trade { Sell { Buyer Amount Currency { Symbol Name SmartContract } } Buy { Price Amount Currency { Symbol SmartContract Name } } Dex { ProtocolName SmartContract ProtocolFamily ProtocolVersion } } } } } { "network": "arbitrum", "limit": 15, "from": "2023-09-07", "till": "2023-09-07", "ArbitrumCurrency": "0xff970a61a04b1ca14834a43f5de4533ebddb5cc8", "quoteCurrency": "0x82af49447d8a07e3bd95bd0d56f35241523fbab1" } ``` ## OHLC for a Token Pair [This](https://ide.bitquery.io/ohlc-for-a-pair-on-Arbitrum_1) query returns the OHLC/K Line Data for a specified token pair. For this example we are considering the ARB `0x912ce59144191c1204e64559fe8253a0e49e6548` and USDC `0xff970a61a04b1ca14834a43f5de4533ebddb5cc8` pair. ```graphql query tradingViewPairs( $network: evm_network $dataset: dataset_arg_enum $interval: Int $token: String $base: String $time_ago: DateTime ) { EVM(network: $network, dataset: $dataset) { DEXTradeByTokens( orderBy: { ascendingByField: "Block_Time" } where: { Trade: { Side: { Amount: { gt: "0" } Currency: { SmartContract: { is: $token } } } Currency: { SmartContract: { is: $base } } PriceAsymmetry: { le: 0.1 } } Block: { Time: { since: $time_ago } } } ) { Block { Time(interval: { count: $interval, in: minutes }) } Trade { open: PriceInUSD(minimum: Block_Time) close: PriceInUSD(maximum: Block_Time) max: PriceInUSD(maximum: Trade_PriceInUSD) min: PriceInUSD(minimum: Trade_PriceInUSD) } volume: sum(of: Trade_AmountInUSD) } } } ``` An example for the data visualisation of the data obtained could be seen on the [DEXRabbit](https://dexrabbit.bitquery.io/arbitrum/pair/0x912ce59144191c1204e64559fe8253a0e49e6548/0xff970a61a04b1ca14834a43f5de4533ebddb5cc8). ![OHLC/ K Line for a Pair on Arbitrum](/img/dexrabbit/arbitrum/arbitrum_ohlc_pair.png) ## Latest Trades in Realtime with Subscription This example uses the chain-specific **DEXTrades** cube via `EVM(network: arbitrum) { DEXTrades }` (pool-side Buy/Sell; see [DEXTrades cube](/docs/cubes/dextrades)). USD can be weak on thin pools. For trader + USD swap rows, use the [stream at the top](#crypto-trades-live-stream). You can find the query [here](https://ide.bitquery.io/Arbitrum-Dextrades-subscription) ```graphql subscription { EVM(network: arbitrum) { DEXTrades { Trade { Dex { ProtocolFamily ProtocolName } Sender Buy { Amount Buyer Currency { Name SmartContract Symbol } Price Seller } Sell { Amount Buyer Currency { Name Symbol SmartContract } Price Seller } } } } } ``` ## Top Bought Tokens on Arbitrum network This query will give you top bought tokens on Arbitrum network in last 1 hour. Change the timestamp in `{Block: {Time: {since: "2024-12-24T08:20:00Z"}}}` accordingly. You can find the query [here](https://ide.bitquery.io/top-bought-tokens-on-Arbitrum#) ```graphql query MyQuery { EVM(network: arbitrum) { DEXTradeByTokens( where: {Block: {Time: {since: "2024-12-24T08:20:00Z"}}} limit: {count: 100} orderBy: {descendingByField: "total_bought"} ) { Trade { Currency { Name Symbol SmartContract } } total_bought: sum(of:Trade_Side_AmountInUSD if:{Trade:{Side:{Type:{is:buy}}}}) total_sold: sum(of:Trade_Side_AmountInUSD if:{Trade:{Side:{Type:{is:sell}}}}) } } } ``` ## Get Price Change 5min, 1h, 6h and 24h of a specific token Use below query to get price change 5min, 1h, 6h and 24h of a specific token. Change the `Currency{SmartContract}` and `Dex{SmartContract}` according to your needs. Test the query [here] (https://ide.bitquery.io/Price-change-5min-1hr-6hr-24hr-precentage-of-a-specific-token_1). ```graphql query MyQuery { EVM(dataset: combined network:arbitrum) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0x30a538eFFD91ACeFb1b12CE9Bc0074eD18c9dFc9"}}, Dex: {SmartContract: {is: "0xdaAe914e4Bae2AAe4f536006C353117B90Fb37e3"}}}, TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ){ Trade { Price_5min_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{minutes_ago:5}}}}) Price_1h_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{hours_ago:1}}}}) Price_6h_ago: PriceInUSD(minimum: Block_Number if:{Block:{Time:{since_relative:{hours_ago:6}}}}) Price_24h_ago: PriceInUSD(minimum: Block_Number) CurrentPrice: PriceInUSD(maximum: Block_Number) } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum( of: Trade_Side_AmountInUSD ) Price_Change_5min: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100") Price_Change_1h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100") Price_Change_6h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100") Price_Change_24h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100") } } } ``` ## Top 10 Arbitrum Tokens by Price Change in last 1h Use below query to get top 10 Arbitrum Tokens by Price Change in last 1h. Test the query [here] (https://ide.bitquery.io/Top-10-arb-tokens-by-price-change-in-last-1-hr). ```graphql query MyQuery { EVM(dataset: combined network:arbitrum) { DEXTradeByTokens( limit:{count:10} orderBy:{descendingByField:"Price_Change_1h"} where: {TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Trade { Currency { Name Symbol SmartContract } Price_5min_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) Price_1h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) Price_6h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) Price_24h_ago: PriceInUSD(minimum: Block_Number) CurrentPrice: PriceInUSD(maximum: Block_Number) Side { Currency { Name Symbol SmartContract } } Dex{ SmartContract } } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum(of: Trade_Side_AmountInUSD) Price_Change_5min: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100" ) Price_Change_1h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100" ) Price_Change_6h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100" ) Price_Change_24h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100" ) } } } ``` ## Top Sold Tokens on Arbitrum network This query will give you top sold tokens on Arbitrum network in last 1 hour. Change the timestamp in `{Block: {Time: {since: "2024-12-24T08:20:00Z"}}}` accordingly. You can find the query [here](https://ide.bitquery.io/Top-Sold-Tokens-on-Arbitrum#) ```graphql query MyQuery { EVM(network: arbitrum) { DEXTradeByTokens( where: {Block: {Time: {since: "2024-12-24T08:20:00Z"}}} limit: {count: 100} orderBy: {descendingByField: "total_sold"} ) { Trade { Currency { Name Symbol SmartContract } } total_bought: sum(of:Trade_Side_AmountInUSD if:{Trade:{Side:{Type:{is:buy}}}}) total_sold: sum(of:Trade_Side_AmountInUSD if:{Trade:{Side:{Type:{is:sell}}}}) } } } ``` ## Top Traders of a Token on Arbitrum [This](https://ide.bitquery.io/top-traders-for-a-token-on-Arbitrum_3) query returns the top traders of a token on arbitrum based on the volume of trades involving the particular token. This query returns info such as buyers, sellers, DEX Protocol used, amount bought and sold. ```graphql query topTraders($network: evm_network, $time_ago: DateTime, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}}, Block: {Time: {since: $time_ago}}} ) { Trade { Buyer Dex { ProtocolFamily } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "arbitrum", "token": "0x912ce59144191c1204e64559fe8253a0e49e6548", "time_ago": "2024-11-17T08:11:44Z" } ``` The implementation of this data could also be seen on the [DEXRabbit](https://dexrabbit.bitquery.io/arbitrum/token/0x912ce59144191c1204e64559fe8253a0e49e6548#top_traders). ![Top Traders for a token on Arbitrum](/img/dexrabbit/arbitrum/arbitrum_top_traders_token.png) The `DEXTrades` API contains the following information about each trade: - `Dex`: The details of the decentralized exchange where the trade was executed, including the protocol family and the protocol name. - `Sender`: The address of the sender of the trade. - `Buy`: The details of the buy order, including the amount of token bought, the buyer's address, the token's symbol, and the price of the trade. - `Sell`: The details of the sell order, including the amount of token sold, the seller's address, the token's symbol, and the price of the trade. ## Video Tutorial | How to get Top Traders of a Token on Arbitrum ## Video Tutorial | How to track Realtime DEXTrades of a Token on Arbitrum ## Video Tutorial | How to get OHLC Data of a Token Pair on Arbitrum ## Video Tutorial | How to get Top Bought & Top Sold Tokens on Arbitrum network --- ## Arbitrum Liquidity API: Pool Reserves and Liquidity Changes in Real Time URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/arbitrum-liquidity-api/ Read Arbitrum pool reserves and spot prices with Bitquery GraphQL: one pool now or as a stream, every Uniswap v4 pool, and the pools that hold a token, in USD. # Arbitrum Liquidity API: Pool Reserves and Liquidity Changes in Real Time The `DEXPoolEvents` cube under `EVM(network: arbitrum)` emits one row every time a pool's reserves change, whether by a swap, a deposit or a withdrawal. Each row carries the reserves of both tokens after the change, in token units and in USD, the spot price in both directions, the pool and its protocol, and the transaction that moved it. On Arbitrum the rows come from Uniswap v2, v3 and v4 pools and PancakeSwap v3 pools. Balancer, Curve, Fluid and DODO pools have their swaps in the [DEX trades API](/docs/blockchain/Arbitrum/DexTrades) but no reserve rows here, and Camelot is not indexed at all. The cube holds the recent realtime window only and has no archive dataset: to keep a history, record the stream. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked pool is the Uniswap v3 WETH/ARB pool, `0xc6f780497a95e246eb9449f5e4770916dcd6396a`, one of the busiest on the chain. ## Reserves of one pool now The newest rows for a pool. `AmountCurrencyA` and `AmountCurrencyB` are the reserves after each change, the `InUSD` twins price them, and `AtoBPrice` is how much of B one unit of A buys at the spot. Saved query [here](https://ide.bitquery.io/latest-liquidity-changes-of-a-specific-pool). ```graphql { EVM(network: arbitrum) { DEXPoolEvents( limit: { count: 10 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { SmartContract: { is: "0xc6f780497a95e246eb9449f5e4770916dcd6396a" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Dex { ProtocolName } } Transaction { Hash } } } } ``` ## Stream one pool The same filter as a subscription delivers a row on every reserve change, which for this pool means several per minute. Saved stream [here](https://ide.bitquery.io/realtime-liquidity-stream-of-a-specific-pool). ```graphql subscription { EVM(network: arbitrum) { DEXPoolEvents( where: { PoolEvent: { Pool: { SmartContract: { is: "0xc6f780497a95e246eb9449f5e4770916dcd6396a" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { SmartContract CurrencyA { Symbol } CurrencyB { Symbol } } } Transaction { Hash } } } } ``` ## Every Uniswap v4 pool on Arbitrum Filter on the protocol to follow a whole family of pools. Uniswap v4 keeps all pools inside one PoolManager contract, `0x360e68faccca8ca495c1b759fd9eee466db9fb32` on Arbitrum, so `Pool.SmartContract` is the same on every row and `Pool.PoolId` is the field that tells pools apart. For v2 and v3 pools `PoolId` is empty and `SmartContract` is the pool. Saved stream [here](https://ide.bitquery.io/latest-liquidity-changes-in-uniswap-v4-pools). ```graphql subscription { EVM(network: arbitrum) { DEXPoolEvents( where: { PoolEvent: { Dex: { ProtocolName: { is: "uniswap_v4" } } } } ) { Block { Time } PoolEvent { Pool { PoolId SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } Transaction { Hash } } } } ``` Other protocol names that report on Arbitrum: `uniswap_v3`, `uniswap_v2` and `pancake_swap_v3`. ## Pools that hold a token, with their current reserves `limitBy` on the pool address keeps the newest row per pool, so the result is the current state of every pool that had the token as `CurrencyA` and changed inside the window. Run it a second time with the token under `CurrencyB` to catch pools that list it second. The example is ARB, `0x912ce59144191c1204e64559fe8253a0e49e6548`; sort the rows by the USD reserve in your code to rank the pools. Saved query [here](https://ide.bitquery.io/realtime-liquidity-stream_1). ```graphql { EVM(network: arbitrum) { DEXPoolEvents( limit: { count: 20 } limitBy: { by: PoolEvent_Pool_SmartContract, count: 1 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { CurrencyA: { SmartContract: { is: "0x912ce59144191c1204e64559fe8253a0e49e6548" } } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time } PoolEvent { Dex { ProtocolName } Pool { SmartContract PoolId CurrencyB { Symbol SmartContract } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } } } } } ``` ## Fields on every row | Field | Meaning | |---|---| | `PoolEvent.Liquidity.AmountCurrencyA`, `AmountCurrencyB` | Reserves of each token after the change, in token units | | `AmountCurrencyAInUSD`, `AmountCurrencyBInUSD` | The same reserves priced in USD | | `PoolEvent.AtoBPrice`, `BtoAPrice` | Spot price in each direction after the change | | `PoolEvent.Pool.SmartContract`, `PoolId` | Pool contract; for Uniswap v4 the PoolManager plus the pool id | | `PoolEvent.Dex.ProtocolName` | `uniswap_v2`, `uniswap_v3`, `uniswap_v4` or `pancake_swap_v3` | | `Transaction.Hash` | The transaction that changed the reserves | ## The same data over Kafka The `arbitrum.dexpools.proto` topic carries the same rows as protobuf messages with lower latency and no WebSocket to keep alive. Kafka needs its own credentials, separate from the IDE token; see the [Kafka streams hub](/docs/category/kafka-streams). The slippage tables for the same pools are on the [Arbitrum slippage API](/docs/blockchain/Arbitrum/arbitrum-slippage-api) page. ## Related pages - [Arbitrum slippage API](/docs/blockchain/Arbitrum/arbitrum-slippage-api) - [Arbitrum DEX trades API](/docs/blockchain/Arbitrum/DexTrades) - [DEXPools cube](/docs/cubes/evm-dexpool/) - [BNB Chain liquidity API](/docs/blockchain/BSC/bsc-liquidity-api) - [Base liquidity API](/docs/blockchain/Base/base-liquidity-api) --- ## Arbitrum Slippage API: How Much a Pool Can Absorb at Each Slippage Level URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/arbitrum-slippage-api/ Slippage tables for Arbitrum pools with Bitquery GraphQL: the largest trade a pool takes at each level, the minimum output, and the deepest pool for a token. # Arbitrum Slippage API: How Much a Pool Can Absorb at Each Slippage Level The `DEXPoolSlippages` cube under `EVM(network: arbitrum)` publishes a slippage table for a pool every time its reserves change. For seven slippage levels, 0, 10, 50, 100, 200, 500 and 1000 basis points, it gives the largest input the pool can take before the price moves past that level, the minimum output that trade would return, and the average execution price, in both directions. That answers the pre-trade question directly: can this pool take my size at my tolerance, and what do I get back. The tables cover the same pools as the [Arbitrum liquidity API](/docs/blockchain/Arbitrum/arbitrum-liquidity-api): Uniswap v2, v3 and v4 and PancakeSwap v3. The cube holds the recent realtime window only; record the stream for history. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked pool is the Uniswap v3 WETH/ARB pool, `0xc6f780497a95e246eb9449f5e4770916dcd6396a`. ## The slippage table of one pool Seven rows per update, one per level. At 50 basis points the `AtoB.MaxAmountIn` row reads as: selling this much WETH moves the price by no more than 0.5%, and `MinAmountOut` is the ARB you get for it. The 0 basis point row carries the spot price with zero size. Saved query [here](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Uniswap-v3). ```graphql { EVM(network: arbitrum) { DEXPoolSlippages( where: { Price: { Pool: { SmartContract: { is: "0xc6f780497a95e246eb9449f5e4770916dcd6396a" } } } } limit: { count: 7 } orderBy: { descending: Block_Time } ) { Block { Time Number } Price { SlippageBasisPoints AtoB { Price MaxAmountIn MinAmountOut } BtoA { Price MaxAmountIn MinAmountOut } Pool { SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Dex { ProtocolName } } } } } ``` ## One level, as a stream Fix `SlippageBasisPoints` to the tolerance you trade with and subscribe: each message is the pool's new capacity at that level. Saved stream [here](https://ide.bitquery.io/realtime-slippage-on-arbitrum). ```graphql subscription { EVM(network: arbitrum) { DEXPoolSlippages( where: { Price: { Pool: { SmartContract: { is: "0xc6f780497a95e246eb9449f5e4770916dcd6396a" } } SlippageBasisPoints: { eq: 50 } } } ) { Block { Time } Price { SlippageBasisPoints AtoB { Price MaxAmountIn MinAmountOut } BtoA { Price MaxAmountIn MinAmountOut } } } } } ``` ## The deepest pool for a token at a given tolerance Which pool takes the largest WETH sell within 0.5%? Keep the newest row per pool with `limitBy`, fix the level, and compare `AtoB.MaxAmountIn` across pools that list WETH first. On Arbitrum the large WETH pools against USDC and USDT0 lead. Repeat with WETH under `CurrencyB` and read `BtoA` for pools that list it second. ```graphql { EVM(network: arbitrum) { DEXPoolSlippages( where: { Price: { SlippageBasisPoints: { eq: 50 } Pool: { CurrencyA: { SmartContract: { is: "0x82af49447d8a07e3bd95bd0d56f35241523fbab1" } } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } limitBy: { by: Price_Pool_SmartContract, count: 1 } orderBy: { descending: Block_Time } limit: { count: 20 } ) { Price { Pool { SmartContract CurrencyB { Symbol SmartContract } } Dex { ProtocolName } AtoB { MaxAmountIn MinAmountOut Price } } } } } ``` ## Reading the fields | Field | Meaning | |---|---| | `Price.SlippageBasisPoints` | The level of the row: 0, 10, 50, 100, 200, 500 or 1000 (100 = 1%) | | `Price.AtoB.MaxAmountIn` | Largest amount of CurrencyA the pool takes within that level | | `Price.AtoB.MinAmountOut` | CurrencyB returned for that input | | `Price.AtoB.Price` | Average execution price of that trade | | `Price.BtoA` | The same three numbers for selling CurrencyB | | `Price.Pool`, `Price.Dex` | Pool contract, the two tokens, protocol name | The `arbitrum.dexpools.proto` Kafka topic carries the same tables as protobuf messages; Kafka needs its own credentials, see the [Kafka streams hub](/docs/category/kafka-streams). ## Related pages - [Arbitrum liquidity API](/docs/blockchain/Arbitrum/arbitrum-liquidity-api) - [Arbitrum DEX trades API](/docs/blockchain/Arbitrum/DexTrades) - [DEXPools cube](/docs/cubes/evm-dexpool/) - [Base slippage API](/docs/blockchain/Base/base-slippage-api) --- ## Arbitrum Smart Contract Calls API URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/Smart_Contract_Calls/ Arbitrum smart contract calls: get the full call trace of an Arbitrum transaction, including caller, callee, method signatures and arguments. # Arbitrum Smart Contract Calls API In this section we will see how to get Arbitrum Smart contract calls information using our API. ## Transaction Call Trace for a Arbitrum Transaction This query gets the transaction call trace for an Arbitrum transaction. The `Calls` API in the query returns a list of all calls made by the transaction. You can find the query [here](https://ide.bitquery.io/Transaction-Call-Trace-Arbitrum) ```graphql query myquery($network: evm_network!, $hash: String!) { EVM(dataset: combined, network: $network) { Calls( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Hash: {is: $hash}}} ) { Call { From Gas GasUsed To Value CallPath Opcode { Code Name } SelfDestruct Create Delegated Depth InternalCalls Success Reverted Output LogCount Input } Transaction { Hash } Arguments { Index Path { Name } Type Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } { "hash": "0x0ca5e462cace62c893cefb57c4491eabf9aebe873a86f9cb16377a127b17589b", "network": "arbitrum" } ``` Each call contains the following information: - `CallPath`: The call path, which is a list of the contract addresses that were called. - `Create`: Whether the call created a new contract. - `Delegated`: Whether the call was a delegated call. - `Depth`: The depth of the call, which is the number of nested calls. - `From`: The address that made the call. - `Gas`: The gas limit for the call. - `GasUsed`: The gas used by the call. - `Input`: The input data for the call. - `InternalCalls`: The number of internal calls made by the call. - `LogCount`: The number of logs generated by the call. - `Opcode`: The opcode of the call. - `Output`: The output data for the call. - `Reverted`: Whether the call reverted. - `SelfDestruct`: Whether the call self-destructed the contract. - `Success`: Whether the call was successful. - `To`: The address that was called. - `Value`: The value transferred to the called contract. --- ## Arbitrum Smart Contract Events API URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/Smart_Contract_Events/ Arbitrum smart contract events: query decoded contract logs on Arbitrum, with an example that tracks DEX swap events by event signature. # Arbitrum Smart Contract Events API In this section we will see how to get Arbitrum Smart Contract Events information using our API. ## Tracking Swap Events on Arbitrum The query returns the 10 most recent `swap` events on the Arbitrum network. We get this by using the signature hash `c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67` for the swap event. You can find the query [here](https://ide.bitquery.io/Swap-Events-Arbitrum) ```graphql query ($network: evm_network, $limit: Int, $method: String) { EVM(dataset: archive, network: $network) { Events( where: {Log: {Signature: {SignatureHash: {is: $method}}}} limit: {count: $limit} orderBy: {descending: Block_Time} ) { ChainId Transaction { Hash } Log { Signature { Name } } Fee { SenderFee } Block { Time Number } } } } { "limit": 10, "network": "arbitrum", "method": "c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67" } ``` The `Log` field in each event contains the following information: - `Signature`: The signature of the event. - `Name`: The name of the event. The `Transaction` field in each event contains the following information: - `Hash`: The hash of the transaction that emitted the event. The `Fee` field in each event contains the following information: - `SenderFee`: The fee paid by the sender of the transaction. The `Block` field in each event contains the following information: - `Time`: The time at which the block was mined. - `Number`: The block number. --- ## Arbitrum Sniper Bot URL: https://docs.bitquery.io/docs/usecases/arbitrum-sniper-bot/ Build Arbitrum Sniper Bot: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. See examples in the Bitquery IDE. # Tutorial : Building a Arbitrum Sniper Bot Using Bitquery Arbitrum Events API and Uniswap SDK This tutorial will guide you through building a Arbitrum sniper bot using Bitquery Events API and the Uniswap SDK for executing swaps. > Note: This material is for educational and informational purposes only and is not intended as investment advice. The content reflects the author's personal research and understanding. While specific investments and strategies are mentioned, no endorsement or association with these entities is implied. Readers should conduct their own research and consult with qualified professionals before making any investment decisions. Bitquery is not liable for any losses or damages resulting from the application of this information. ## Tutorial Video ## ## Tutorial Github Code Repository - [Repository Link](https://github.com/Akshat-cs/Arbitrum-sniper-bot) ### Prerequisites 1. **Node.js** and **npm** installed on your system. 2. **Bitquery Free Developer Account** with OAuth token (follow instructions [here](/docs/authorization/how-to-generate/)). 3. **Any Arbitrum Chain supported Wallet** with some Arbitrum ETH for transaction fees and also some WETH as I have used WETH in the video tutorial to make swap. I have used the Bitquery Arbitrum Events API to get the latest created pool which has Token A as WETH with Token Addres `0x82aF49447D8a07e3bd95BD0d56f35241523fBab1`. - If you want to conduct the swap using different Token then you can change the address in this `Arguments: {startsWith: {Value: {Address: {is: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"}}}}` in tokens.ts file to your Token Address that you want to conduct swaps with. ### Step 1: Setting Up the Environment 1. **Initialize a new Node.js project:** ```bash mkdir Arbitrum-sniper-bot cd Arbitrum-sniper-bot npm init -y ``` 2. **Install the necessary dependencies:** ```bash npm install @types/node @uniswap/sdk-core @uniswap/smart-order-router @uniswap/v3-sdk axios dotenv ethers ts-node tslib typescript ``` ### Step 2: Creating the Bot 1. **Create a `.env` file :** This file will contain all the environment variables. Put in your Wallet private key that you are using to conduct swap. And also put in the Bitquery OAuth Token, follow the instructions on how to get it [here](/docs/authorization/how-to-generate/). ```javascript # Arbitrum MAINNET RPC=https://arb1.arbitrum.io/rpc WALLET_PRIVATE_KEY= CHAIN_ID=42161 SWAP_ROUTER_ADDRESS=0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45 SLIPPAGE_TOLERANCE=5 DEADLINE_IN_MINUTES=30 BITQUERY_TOKEN= ``` 2. **Create a `config.ts` file:** This is a basic configuration file which helps us to expose our environment variables to our application and we are also using Ethers to set provider and signer. ```javascript import { Percent } from "@uniswap/sdk-core"; import { ethers, providers, Wallet } from "ethers"; import { config as loadEnvironmentVariables } from "dotenv"; loadEnvironmentVariables(); export const WALLET_PRIVATE_KEY = process.env.WALLET_PRIVATE_KEY || ""; export const SWAP_ROUTER_ADDRESS = process.env.SWAP_ROUTER_ADDRESS || ""; export const CHAIN_ID = parseInt(process.env.CHAIN_ID || "1"); export const DEADLINE = Math.floor( (Date.now() / 1000) _ (parseInt(process.env.DEADLINE_IN_MINUTES || "30") _ 60) ); export const SLIPPAGE_TOLERANCE = new Percent( process.env.SLIPPAGE_TOLERANCE || 5, 100 ); const RPC = process.env.RPC; export const provider = ethers.providers.getDefaultProvider(RPC); export const signer = new Wallet(WALLET_PRIVATE_KEY, provider); ``` 3. **Create a `tokens.ts` file:** In this step we are importing necessary modules then loading environment variables and also setting ERC20 ABI as we are going to need it to make the token contract instance from token address. ```javascript loadEnvironmentVariables(); const ERC20_ABI = [ "function name() view returns (string)", "function symbol() view returns (string)", "function decimals() view returns (uint8)", "function allowance(address, address) external view returns (uint256)", "function approve(address, uint) external returns (bool)", "function balanceOf(address) external view returns(uint256)", ]; ``` We are going to need Token Contract to call different functions like `balanceOf`, `decimals` and `symbol`. So we are building Token Contract using `buildERC20TokenWithContract` function by providing the token address and the provider. ```javascript type TokenWithContract = { contract: Contract, walletHas: (signer: Signer, requiredAmount: BigNumberish) => Promise, token: Token, }; const buildERC20TokenWithContract = async ( address: string, provider: Provider ): Promise => { try { const contract = new Contract(address, ERC20_ABI, provider); const [name, symbol, decimals] = await Promise.all([ contract.name(), contract.symbol(), contract.decimals(), ]); return { contract: contract, walletHas: async (signer, requiredAmount) => { const signerBalance = await contract .connect(signer) .balanceOf(await signer.getAddress()); return signerBalance.gte(BigNumber.from(requiredAmount)); }, token: new Token(CHAIN_ID, address, decimals, symbol, name), }; } catch (error) { console.error( `Failed to fetch token details for address ${address}:`, error ); return null; } }; ``` Setting provider and type of Tokens here as we are using Typescript. Then we built a function `getTokens` which makes an API call and gets the address of Tokens 0 and 1 in the latest created liquidity pool. This function finally returns the Token Contract for the fetched Token 0 and Token 1 addresses using `buildERC20TokenWithContract`. Keep in mind we have set the Token 0 address as WETH token address. In the `index.ts` file we are going to swap this WETH with the other token i.e token 1 in the pool. ```javascript // Example usage for ARBITRUM const provider = new providers.JsonRpcProvider(process.env.RPC); type Tokens = { Token0: TokenWithContract | null, Token1: TokenWithContract | null, }; export const getTokens = async (): Promise => { try { let data = JSON.stringify({ query: 'query {\n EVM(network: arbitrum) {\n Events(\n limit: {count:1}\n orderBy: {descending: Block_Time}\n where: {Log: {Signature: {Name: {is: "PoolCreated"}}, SmartContract: {is: "0x1F98431c8aD98523631AE4a59f267346ea31F984"}}, Arguments: {startsWith: {Value: {Address: {is: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"}}}}}\n ) {\n Transaction {\n Hash\n }\n Block {\n Time\n }\n Log {\n Signature {\n Name\n }\n }\n Arguments {\n Name\n Type\n Value {\n ... on EVM_ABI_Integer_Value_Arg {\n integer\n }\n ... on EVM_ABI_String_Value_Arg {\n string\n }\n ... on EVM_ABI_Address_Value_Arg {\n address\n }\n ... on EVM_ABI_BigInt_Value_Arg {\n bigInteger\n }\n ... on EVM_ABI_Bytes_Value_Arg {\n hex\n }\n ... on EVM_ABI_Boolean_Value_Arg {\n bool\n }\n }\n }\n }\n }\n}\n', variables: "{}", }); const axiosConfig: AxiosRequestConfig = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.BITQUERY_TOKEN}`, // put your oauth token here }, data: data, }; const response = await axios.request(axiosConfig); const token0Address = response.data.data.EVM.Events[0].Arguments[0].Value.address; const token1Address = response.data.data.EVM.Events[0].Arguments[1].Value.address; console.log(token0Address); console.log(token1Address); const Token0 = await buildERC20TokenWithContract(token0Address, provider); const Token1 = await buildERC20TokenWithContract(token1Address, provider); return { Token0, Token1 }; } catch (error) { console.error("Error fetching tokens:", error); return { Token0: null, Token1: null }; } }; ``` For the sake of the demo we have used a query, to **track new tokens in real-time** use the below subscriptions ([link](https://ide.bitquery.io/Subscription-Latest-created-pool-on-uniswap-V3-on-Arbirum-chain-with-Token0-as-WETH_1)). ```javascript subscription { EVM(network: arbitrum) { Events( orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "PoolCreated"}}, SmartContract: {is: "0x1F98431c8aD98523631AE4a59f267346ea31F984"}}, Arguments: {startsWith: {Value: {Address: {is: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"}}}}} ) { Transaction { Hash } Block { Time } Log { Signature { Name } } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` 4. **Create a `index.ts` file:** a. **Doing the necessary imports** ```javascript import { BigNumber, ethers } from "ethers"; import { AlphaRouter, SwapType, SwapRoute, } from "@uniswap/smart-order-router"; import { CurrencyAmount, TradeType } from "@uniswap/sdk-core"; import type { TransactionRequest } from "@ethersproject/abstract-provider"; import { getTokens } from "./tokens"; import { provider, signer, CHAIN_ID, SWAP_ROUTER_ADDRESS, SLIPPAGE_TOLERANCE, DEADLINE, } from "./config"; ``` b. **Building the main function** All of the code covered under this section b is going to be in the main function. 1. Firstly it calls the `getTokens` function and fetches the Token0 and Token1 token contracts. And then set `tokenFrom` and `tokenTo` tokens and `tokenFromContract` to call functions on tokenFrom token. ```javascript // Wait for the getTokens function to resolve const { Token0, Token1 } = await getTokens(); // Ensure tokens are not null if (!Token0 || !Token1) { throw new Error("Tokens are not initialized."); } const tokenFrom = Token0.token; const tokenFromContract = Token0.contract; const tokenTo = Token1.token; ``` 2. Then we check if we have passed the argument in the terminal while running the bot. This means that if we have not passed the amount of WETH we want to swap with then throw error. Then we are checking if we have enough amount of the TokenFrom token or not. It must be grater than the passed argument in the terminal. ```javascript if (typeof process.argv[2] === "undefined") { throw new Error(`Pass in the amount of ${tokenFrom.symbol} to swap.`); } const walletAddress = await signer.getAddress(); const amountIn = ethers.utils.parseUnits( process.argv[2], tokenFrom.decimals ); const balance = await tokenFromContract.balanceOf(walletAddress); if (!(await Token0.walletHas(signer, amountIn))) { throw new Error( `Not enough ${tokenFrom.symbol}. Needs ${amountIn}, but balance is ${balance}.` ); } ``` 3. We are using `AlphaRouter` here from Uniswap to swap tokens on Uniswap efficiently. Then we use this router object to create a route which takes the specific details of our swap. If no route is found then it throws error. ```javascript const router = new AlphaRouter({ chainId: CHAIN_ID, provider }); const route = await router.route( CurrencyAmount.fromRawAmount(tokenFrom, amountIn.toString()), tokenTo, TradeType.EXACT_INPUT, { recipient: walletAddress, slippageTolerance: SLIPPAGE_TOLERANCE, deadline: DEADLINE, type: SwapType.SWAP_ROUTER_02, } ); if (!route) { throw new Error("No route found for the swap."); } console.log( `Swapping ${amountIn} ${tokenFrom.symbol} for ${route.quote.toFixed( tokenTo.decimals )} ${tokenTo.symbol}.` ); ``` 4. Then we check the allowance. We are just defining here `buildSwapTransaction` and then also using `swapTransaction` to populate the `buildSwapTransaction`. Then we have also defined `attemptSwapTransaction` which sends the transaction to the network. ```javascript const allowance: BigNumber = await tokenFromContract.allowance( walletAddress, SWAP_ROUTER_ADDRESS ); const buildSwapTransaction = ( walletAddress: string, routerAddress: string, route: SwapRoute ): TransactionRequest => { return { data: route.methodParameters?.calldata, to: routerAddress, value: BigNumber.from(route.methodParameters?.value), from: walletAddress, gasLimit: BigNumber.from("2000000"), // Set your desired gas limit here // Optionally, you can specify gasPrice here if needed // gasPrice: YOUR_GAS_PRICE_IN_WEI }; }; const swapTransaction = buildSwapTransaction( walletAddress, SWAP_ROUTER_ADDRESS, route ); const attemptSwapTransaction = async ( signer: ethers.Wallet, transaction: TransactionRequest ) => { const signerBalance = await signer.getBalance(); if (!signerBalance.gte(transaction.gasLimit || "0")) { throw new Error(`Not enough ETH to cover gas: ${transaction.gasLimit}`); } // Send the transaction with the specified gas-related parameters signer.sendTransaction(transaction).then((tx) => { tx.wait().then((receipt) => { console.log("Completed swap transaction:", receipt.transactionHash); }); }); }; ``` 5. Here we finally call the before defined functions. Firstly we check if there is enough WETH allowance. And if there is not then we send an approve transaction to the network with the `AmountIn` amount of WETH. Then we call the `attemptSwapTransaction` which des the actual swap. ```javascript if (allowance.lt(amountIn)) { console.log(`Requesting ${tokenFrom.symbol} approval…`); const approvalTx = await tokenFromContract .connect(signer) .approve( SWAP_ROUTER_ADDRESS, ethers.utils.parseUnits(amountIn.mul(1000).toString(), 18) ); approvalTx.wait(3).then(() => { attemptSwapTransaction(signer, swapTransaction); }); } else { console.log( `Sufficient ${tokenFrom.symbol} allowance, no need for approval.` ); attemptSwapTransaction(signer, swapTransaction); } ``` c. **Calling the main function with some error handling** ```javascript main().catch((error) => { console.error(error); process.exit(1); }); ``` ### Step 3: Running the Bot 1. **Check the .env:** - Make sure that you have replace `PRIVATE_KEY` with your actual Arbitrum account public key. - Make sure that you have replace `BITQUERY_TOKEN` with your actual Bitquery OAuth token. 2. **Run the bot:** 0.001 in the below script is the amount of WETH that I want to use for the swap. ```bash ts-node index.ts 0.001 ``` ### Conclusion You've successfully set up a Arbitrum sniper bot using Bitquery for Arbitrum Events API and Uniswap SDK for executing swaps. You need to change the query in tokens.ts file into subscription if you want to use it to listen for on-chain events and then buy the token B from each new pool that gets created on Uniswap. But you will need to make some necessary changes before that. This tutorial just shows you how you can get the recently created pool on uniswap and which token B it has as token A we have already set as WETH in the query and swap a token in that pool. Ensure your bot is monitored and managed appropriately, as we are running on the mainnet with real funds. --- ## Arbitrum TimeBoost API & Streams URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/arbitrum-timeboost-api/ Arbitrum TimeBoost auctions in real time: a GraphQL subscription on the auction contract returning transaction context and decoded bids for priority inclusion. # Arbitrum TimeBoost API & Streams Arbitrum sequencers traditionally ordered transactions on a first-come-first-serve (FCFS) basis. **TimeBoost** introduced an auction-driven priority lane that lets searchers bid for earlier inclusion. With Bitquery’s Stream you can subscribe to every call that interacts with the TimeBoost auction contract and correlate it with other Arbitrum insights described in our [Arbitrum Overview](./). ## Real-time subscription Use the following subscription in the Bitquery IDE to watch every TimeBoost auction interaction. The query filters on the auction contract address and surfaces both transaction context and decoded ABI arguments. [Run this stream](https://ide.bitquery.io/Arbitrum-Timeboost-Auction-Transactions-in-Realtime) ```graphql subscription { EVM(network: arbitrum) { Events( where: { Transaction: { To: { is: "0x5fcb496a31b7AE91e7c9078Ec662bd7A55cd3079" } } } ) { Block { Number } Call { CallPath InternalCalls Signature { Name } } Topics { Hash } Receipt { CumulativeGasUsed } Transaction { From To Type } Arguments { Name Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } } } } } } ``` --- ## Arbitrum Token Market Cap API URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/arbitrum-token-marketcap-api/ Arbitrum Token Market Cap API: stream Arbitrum market cap, FDV, supply, and price using Bitquery Trading GraphQL APIs. See examples in the Bitquery IDE. # Arbitrum Token Market Cap API Use Bitquery’s **Trading** API **`Tokens`** cube to stream or query **market cap**, **fully diluted valuation (USD)**, **total supply**, **price** (OHLC and averages), and **volume** for tokens traded on **Arbitrum One**. Filter with token/currency **`Id`** values such as **`arbitrum:`** plus a **lowercase** contract address. For schema details and field meanings, see the **[Tokens cube](/docs/trading/crypto-price-api/tokens)** and **[Supply fields](/docs/trading/crypto-price-api/supply-fields)**. :::note Trading API and EVM addresses On **Arbitrum** (EVM), the **Trading** API expects **lowercase** hex in **`Id`** values (e.g. `arbitrum:0x97e6…`, not mixed-case checksum addresses). ::: ## Related APIs - **[Ethereum Token Market Cap API](/docs/blockchain/Ethereum/token-supply/ethereum-token-marketcap-api)** — same patterns with **`eth:`** ids - **[BSC Token Market Cap API](/docs/blockchain/BSC/bsc-token-marketcap-api)** — same patterns with **`bsc:`** ids - **[Polygon (Matic) Token Market Cap API](/docs/blockchain/Matic/matic-token-marketcap-api)** — same patterns with **`matic:`** ids - **[Base Token Market Cap API](/docs/blockchain/Base/base-token-marketcap-api)** — same patterns with **`base:`** ids - **[Solana Token Market Cap API](/docs/blockchain/Solana/solana-token-marketcap-api)** — same patterns with **`solana:`** ids - **[Crypto Price API — Tokens](/docs/trading/crypto-price-api/tokens)** — full `Tokens` cube reference --- ## How do I stream live Arbitrum token market cap, price, and volume? Subscribe to **`Tokens`** where **currency id** includes **`arbitrum`**, with **interval duration** greater than **1** (second). You get **token fields**, **block time**, **supply** (**MarketCap**, **FullyDilutedValuationUsd**), **price** (OHLC and mean), and **volume**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/arbitrum-token-marketcap-stream). ```graphql subscription MyQuery { Trading { Tokens( where: {Currency: {Id: {includes: "arbitrum"}}, Interval: {Time: {Duration: {gt: 1}}}} ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` --- ## How do I get the latest market cap for a specific token on Arbitrum? Use **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, and filter **`Token.Id`** with **`includesCaseInsensitive`** (e.g. **`arbitrum:`** + lowercase contract). You can run this query [in the Bitquery IDE](https://ide.bitquery.io/specific-arbitrum-token-latest-marketcap). ```graphql query { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: {Token: {Id: {includesCaseInsensitive: "arbitrum:0x97e66d3c4d5bcd7c64e3e55af28544c9addf9281"}}, Interval: {Time: {Duration: {gt: 1}}}} ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` Replace the `includesCaseInsensitive` value with your token’s **`arbitrum:`** id (lowercase hex). --- ## How do I stream Arbitrum tokens with market cap above $1 million? Subscribe when **`Token.Id`** matches **Arbitrum** (**`arbitrum`**) and **`Supply.MarketCap`** **>** **1,000,000** (USD). You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-stream-arbitrum-tokens-with-marketcap-above-1-million). ```graphql subscription { Trading { Tokens( where: {Token: {Id: {includesCaseInsensitive: "arbitrum"}}, Interval: {Time: {Duration: {gt: 1}}}, Supply: {MarketCap: {gt: 1000000}}} ) { Currency { Name Id Symbol } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` :::tip Threshold and interval Tune **`Supply.MarketCap`** and **`Interval.Time.Duration`** for your alerts or dashboards. See **[Tokens cube](/docs/trading/crypto-price-api/tokens)** for more filters. ::: --- ## How do I get top Arbitrum tokens by market cap? This query ranks **Arbitrum** tokens by **`Supply.MarketCap`**. It uses roughly the **last 24 hours** (`since_relative: { hours_ago: 24 }`), **1-second** intervals, at least **$1,000** **USD volume**, **`limitBy`** one row per **`Token_Id`**, and up to **50** tokens. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Arbitrum). ```graphql { Trading { Tokens( limit: { count: 50 } limitBy: { count: 1, by: Token_Id } orderBy: { descending: Supply_MarketCap } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 1000 } } Token: { Network: { is: "Arbitrum" } } } ) { Currency { Id Name Symbol } Price { Average { Mean(maximum: Block_Time) } } Volume { Base(maximum: Block_Time) Quote(maximum: Block_Time) Usd(maximum: Block_Time) } Token { Network Symbol Address } Supply { MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) TotalSupply(maximum: Block_Time) } } } } ``` --- ## How do I get top Arbitrum tokens by market cap change in 1 hour? Uses a **1-hour** OHLC interval (`Duration: { eq: 3600 }`) and orders by **`change_mcap`**: **(close − open) × total supply**. **`Token.Network`** is **Arbitrum**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/top-arb-tokens-by-Market-Cap-Change-1h). ```graphql { Trading { Tokens( limit: { count: 50 } orderBy: { descendingByField: "change_mcap" } where: { Interval: { Time: { Duration: { eq: 3600 } } } Token: { Network: { is: "Arbitrum" } } } ) { Currency { Id Name Symbol } Token { Network Symbol Address } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } change_mcap: calculate( expression: "($Price_Ohlc_Close-$Price_Ohlc_Open) * Supply_TotalSupply" ) Price { Ohlc { Open Close } } } } } ``` --- ## Arbitrum Transactions API URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/Blocks_Transactions/ Arbitrum transactions and blocks: fetch the latest transactions, filter transactions from or to a wallet, and list the latest blocks with GraphQL examples. # Arbitrum Transactions API In this section we'll have a look at some examples using the Arbitrum Transactions API. ## Latest Transactions The query below retrieves the latest 10 transactions on the Arbitrum network. You can find the query [here](https://ide.bitquery.io/Latest-Transactions_3) ```graphql { EVM(network: arbitrum, dataset: archive) { Transactions( limit: {count: 10, offset: 0} orderBy: {descending: Block_Time} where: {Block: {Date: {since: "2023-07-01", till: "2023-07-15"}}} ) { ChainId Block { Number Time } Transaction { To From Hash Value } Receipt { GasUsed } Fee { EffectiveGasPrice SenderFee } } } } ``` ## Latest Transactions From/To a Wallet To retrieve the latest transactions from or to a specific wallet address we will be using the `any` filter which acts as the OR condition. This query fetches the 10 most recent transactions from/to the specified wallet address, ordered by the block time in descending order. ```graphql { EVM(network: arbitrum, dataset: archive) { Transactions( limit: {count: 10} where: {any: {Transaction: {From: {is: "0x16a92c43b270fbb1916501470f70c42cf6f00326"}, To: {is: "0x16a92c43b270fbb1916501470f70c42cf6f00326"}}}} orderBy: {descending: Block_Time} ) { ChainId Block { Number Time } Transaction { To From Hash Value } Receipt { GasUsed } Fee { EffectiveGasPrice SenderFee } } } } ``` ## Latest Blocks The query below retrieves the latest 10 blocks on the Arbitrum network. You can find the query [here](https://ide.bitquery.io/Latest-Arbitrum-blocks) ```graphql query MyQuery { EVM(network: arbitrum) { Blocks(limit: {count: 10}, orderBy: {descending: Block_Time}) { Block { BaseFee Coinbase Difficulty Time Root } } } } ``` --- ## Arbitrum Uniswap v4 API: Swaps, Pools by PoolId, Traders and Liquidity URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/uniswap-v4-api/ Uniswap v4 on Arbitrum with Bitquery GraphQL: live swaps, pools of a token by PoolId, daily pool stats, top traders and reserves, worked on ETH/USDC. # Arbitrum Uniswap v4 API: Swaps, Pools by PoolId, Traders and Liquidity Uniswap v4 on Arbitrum runs through one contract, the PoolManager at `0x360e68faccca8ca495c1b759fd9eee466db9fb32`. Every pool is a record inside it, identified by a `PoolId` hash of the two tokens, the fee, the tick spacing and the hook, not by an address of its own. That changes how you query: the protocol name `uniswap_v4` selects the whole venue, `Trade.PoolId` selects a pool, and on swap rows the buyer and seller fields both show the PoolManager, so the trader is `Transaction.From`. Activity on Arbitrum sits in a few majors: ETH/USDC, USDC against the USDT0 bridged stablecoin, WBTC/USDC, and a rotating set of launch tokens. Every example runs in the [IDE](https://ide.bitquery.io); the `archive` and `combined` ones need an archive add-on, because the free trial is real-time only. The worked pool is ETH/USDC, `PoolId 0x864abca0a6202dba5b8868772308da953ff125b0f95015adbf89aaf579e903a8`, and the worked token is USDC, `0xaf88d065e77c8cc2239327c5edb3a432268e5831`. ## Live swaps across all v4 pools Filter `DEXTrades` on the protocol name and subscribe. Each message is one swap with both sides priced in USD; `Trade.PoolId` says which pool. Saved stream [here](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-arbitrum). ```graphql subscription { EVM(network: arbitrum) { DEXTrades(where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } } }) { Block { Time } Trade { PoolId Buy { Currency { Symbol SmartContract } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol SmartContract } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Every v4 pool that trades a token Group `DEXTradeByTokens` by `PoolId` with the token in `Currency` to list its pools, ranked by trades in the window, with the other token of each pool and its USD volume. This is how you find the `PoolId` to use in the queries below. Saved query [here](https://ide.bitquery.io/get-virtual-pool-address-for-a-token-on-uniswap-v4-arbitrum). ```graphql { EVM(network: arbitrum) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } Currency: { SmartContract: { is: "0xaf88d065e77c8cc2239327c5edb3a432268e5831" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "count" } limit: { count: 20 } ) { Trade { PoolId Side { Currency { Symbol SmartContract } } } count volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Latest swaps in one pool Filter on the `PoolId`. Saved query [here](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-arbitrum). ```graphql { EVM(network: arbitrum) { DEXTrades( where: { Trade: { PoolId: { is: "0x864abca0a6202dba5b8868772308da953ff125b0f95015adbf89aaf579e903a8" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Currency { Symbol } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Pool stats for the last 24 hours One row with trades, distinct buyers and sellers, and volume split by direction, for the token you name in `Currency`. Saved query [here](https://ide.bitquery.io/trade-stats-for-a-token-pair-on-uniswap-v4-arbitrum). ```graphql { EVM(network: arbitrum) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x864abca0a6202dba5b8868772308da953ff125b0f95015adbf89aaf579e903a8" } Currency: { SmartContract: { is: "0xaf88d065e77c8cc2239327c5edb3a432268e5831" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol } Side { Currency { Symbol } } } trades: count buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) volumeUsd: sum(of: Trade_Side_AmountInUSD) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) } } } ``` ## Top traders of a pool Because the PoolManager settles every v4 swap, `Trade.Buyer` and `Trade.Seller` on `DEXTrades` are the PoolManager itself. Group by `Transaction.From` instead to rank the accounts that sent the swaps. `bought` sums the token the trader received and `sold` the token it gave up; `Side.Type` describes the counter-side of the trade, which is why the two conditions look reversed. Saved query [here](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-arbitrum). ```graphql { EVM(network: arbitrum) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x864abca0a6202dba5b8868772308da953ff125b0f95015adbf89aaf579e903a8" } Currency: { SmartContract: { is: "0xaf88d065e77c8cc2239327c5edb3a432268e5831" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 20 } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` Put one of those addresses into `Transaction: { From: { is: "0x..." } }` on the latest-swaps query to see its trades. The [top sellers](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-arbitrum) saved query is the same shape sorted on `sold`. ## Reserves of a v4 pool `DEXPoolEvents` emits a row on every reserve change. For v4 the reserves are rebuilt from the concentrated positions around the current price, so they are what the PoolManager holds for that pool, priced in USD. Filter by `PoolId`; drop the filter and keep the protocol name to stream every v4 pool on Arbitrum. Saved stream for [all pools](https://ide.bitquery.io/uniswap-v4-pool-liquidity-arbitrum). ```graphql { EVM(network: arbitrum) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0x864abca0a6202dba5b8868772308da953ff125b0f95015adbf89aaf579e903a8" } } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } } } } ``` ## Related pages - [Arbitrum liquidity API](/docs/blockchain/Arbitrum/arbitrum-liquidity-api) - [Arbitrum DEX trades API](/docs/blockchain/Arbitrum/DexTrades) - [Uniswap v4 on Ethereum](/docs/blockchain/Ethereum/dextrades/uniswap-v4-api) - [Uniswap v4 on Base](/docs/blockchain/Base/uniswap-v4-api) - [Uniswap v4 on BNB Chain](/docs/blockchain/BSC/uniswap-v4-api) --- ## Arc Balances & Token Supply API URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/arc-mainnet-balances-api/ Query Arc wallet balances, balance history, token holders and total supply with Bitquery GraphQL APIs, including multi-wallet portfolio queries. # Arc Balances & Token Supply API Query **wallet balances, holders and token supply on Arc** with Bitquery GraphQL. Four cubes on `network: arc` cover it: | Cube | What it returns | | --- | --- | | `Balances` | Computed current balance per address and currency, with first and last change time and update count | | `Holders` | Current holder and token pairs, ranked by token balance | | `TransactionBalances` | Per-transaction pre- and post-balances, and the token's `TotalSupply` | | `Transfers` | Every transfer in and out of a wallet | Every query on this page was executed against the production endpoint before publishing. :::info Availability checked 16 September 2026 `Balances`, `Holders`, `TransactionBalances` and `Transfers` all returned Arc data. Only the realtime path answered, so leave the `dataset` argument out until `archive` and `combined` are enabled. Join balances to the [latest price query](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/#latest-price-of-a-token) when you need a USD value. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Blockchain API overview](/docs/blockchain/arc-mainnet/) — network facts, every cube and stream in one place - [Arc Transfers API](/docs/blockchain/arc-mainnet/arc-mainnet-transfers-api/) - [Arc DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) - [EVM Balances schema](/docs/schema/evm/balances/) - [EVM Token Supply API](/docs/blockchain/Ethereum/token-supply/evm-token-supply/) ::: **On this page:** [Portfolio](#portfolio-of-a-wallet) · [One token](#balance-of-one-token) · [Batch](#balances-of-several-wallets) · [Top holders](#top-holders-of-a-token) · [History](#balance-history-of-a-wallet) · [Stream](#stream-balance-changes) · [Supply](#total-supply-of-a-token) · [Supply stream](#stream-supply-changes) · [FAQ](#faq) --- ## Portfolio of a wallet ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-balances-portfolio-of-a-wallet) Every currency an address holds, with the computed balance and when it last changed. Native USDC has `Native: true`; the ERC-20 interface at `0x3600...` is listed separately. ```graphql { EVM(network: arc) { Balances( where: {Balance: {Address: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} orderBy: {descending: Balance_Amount} ) { Currency { Name Symbol SmartContract Native } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Balance of one token ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-balances-balance-of-one-token) The `balanceOf` equivalent for ERC-20 USDC. For the gas token use `Currency: {Native: true}` instead of a contract filter. ```graphql { EVM(network: arc) { Balances( where: { Balance: {Address: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}} Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } ) { Currency { Symbol Decimals } Balance { Amount LastChangeTime } } } } ``` --- ## Balances of several wallets ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-balances-balances-of-several-wallets) One call for a batch of addresses, grouped by address and currency. ```graphql { EVM(network: arc) { Balances( where: { Balance: { Address: { in: [ "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb" "0xb40bd0f6b1332daf9e987a0ca33efe6e90d0b938" "0x2bf981e99011ae4050aaa6f33af4bfc26b89f224" ] } } Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } orderBy: {descending: Balance_Amount} ) { Balance { Address Amount } Currency { Symbol } } } } ``` --- ## Top holders of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-balances-top-holders-of-a-token) Current EURC holders ranked by token balance. Add `Balance: {Amount: {gt: "0"}}` so wallets that once held the token but now hold zero do not appear. ```graphql { EVM(network: arc) { Holders( where: { Currency: {SmartContract: {is: "0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1"}} Balance: {Amount: {gt: "0"}} } orderBy: {descending: Balance_Amount} limit: {count: 20} ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Balance history of a wallet Each change to a wallet's USDC balance, newest first, with the transaction behind it. `TransactionBalances` returns the balance before and after each transaction; `change` is the difference, so positive values are inflows. ```graphql { EVM(network: arc) { TransactionBalances( limit: {count: 20} orderBy: {descending: Block_Time} where: { TokenBalance: { Address: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"} Currency: {Native: true} } } ) { Block { Number Time } Transaction { Hash } TokenBalance { PreBalance PostBalance Currency { Symbol } } change: calculate(expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance") } } } ``` ### Net change per currency over a window Sum the transfers in and out per currency to see what a wallet gained or lost over the last 24 hours. ```graphql { EVM(network: arc) { Transfers( where: { any: [ {Transfer: {Receiver: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} {Transfer: {Sender: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} ] Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Transfer { Currency { Symbol SmartContract Native } } inflow: sum(of: Transfer_Amount, if: {Transfer: {Receiver: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}}) outflow: sum(of: Transfer_Amount, if: {Transfer: {Sender: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}}) transfers: count } } } ``` --- ## Stream balance changes Every balance change of a wallet as it happens, from `TransactionBalances`. Widen the filter to a list of addresses or a single token to build alerts. ```graphql subscription { EVM(network: arc) { TransactionBalances( where: { TokenBalance: {Address: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}} } ) { Block { Number Time } Transaction { Hash } TokenBalance { PreBalance PostBalance Currency { Symbol SmartContract Native } } } } } ``` --- ## Total supply of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-balances-total-supply-of-a-token) `TransactionBalances` records the token's total supply after each transaction that touched it. The latest row is the current supply, already adjusted for decimals. ```graphql { EVM(network: arc) { TransactionBalances( limit: {count: 1} orderBy: {descending: Block_Time} where: { TokenBalance: { Currency: {SmartContract: {is: "0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1"}} } } ) { Block { Time } TokenBalance { Currency { Symbol SmartContract } TotalSupply } } } } ``` --- ## Stream supply changes ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-balances-stream-supply-changes) A new row arrives whenever a mint or burn changes the supply of the token. ```graphql subscription { EVM(network: arc) { TransactionBalances( where: { TokenBalance: { Currency: {SmartContract: {is: "0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1"}} } } ) { Block { Time } Transaction { Hash } TokenBalance { Currency { Symbol } TotalSupply } } } } ``` --- ## FAQ **Does the `Holders` cube work?** Yes. It returned Arc holder rows in the production check on 16 September 2026. Filter `Balance.Amount` above zero for current holders. **Why does the same wallet show USDC twice?** Native USDC (`Native: true`, 18 decimals) and the ERC-20 USDC interface (`0x3600...`, 6 decimals) appear as separate Bitquery currencies. Arc's ERC-20 interface acts on the native balance, so do not add the rows without checking the flow you are measuring. A third row with contract `0xfff...fffe` and no symbol is a system ledger mirror and can be ignored. **Are USD values available?** The balance cubes return token amounts. Fetch current prices from `Trading.Pairs` with `Market.Network: "Arc"`, or use `Trading.Tokens` for prices across pools, then match tokens in your app. Check the price timestamp before valuing a balance. For a historical price more than 30 days old, derive it from `EVM.DEXTrades` or `EVM.DEXTradeByTokens` only after confirming Arc archive data is available. **Is `TotalSupply` raw or decimal-adjusted?** Decimal-adjusted. A token with a billion supply reads `1000000000.000000000000000000`. --- ## Arc Blockchain API: GraphQL and WebSocket URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/ Query and stream Circle’s Arc blockchain data with Bitquery’s Arc Blockchain API. Get trades, transfers, balances and blocks through GraphQL and WebSocket. # Arc Blockchain API Bitquery’s [**Arc Blockchain API**](https://bitquery.io/blockchains/arc-blockchain-api) queries and streams data from Circle’s Arc blockchain (chain ID `5042`). Use `Trading` for trading queries and streams, with `Pair.Market.Network: "Arc"` on `Trading.Trades`. Use `EVM(network: arc)` for transfers, balances, logs, calls, transactions and blocks. :::tip Trading queries and streams Use `Trading.Trades`, `Trading.Tokens` and `Trading.Pairs` for live data and the last 30 days. Use `EVM.DEXTrades` or `EVM.DEXTradeByTokens` only for trades older than 30 days, subject to Arc archive availability. ::: Arc is Circle's EVM-compatible Layer 1. USDC pays gas, blocks reach finality in under a second, and the network is built for payments, foreign exchange and tokenized assets. [Arc launched](https://www.arc.io/blog/arc-mainnet-goes-live-on-september-16-2026) on **16 September 2026**. Circle's current RPC reference still labels its listed Arc endpoints and explorer as permissioned; Bitquery's indexed API is live. :::info Availability checked 16 September 2026 `Trading.Trades`, `Trading.Tokens`, `Trading.Pairs`, and the realtime EVM cubes returned Arc data in production tests. Leave the dataset argument out of `Trading`; it does not support archive or combined. Arc's EVM `dataset: combined` and `dataset: archive` did not answer at this check. ::: :::note API Key Required To query or stream outside the Bitquery IDE, create an [API access token](/docs/authorization/how-to-generate/). ::: --- ## Arc at a glance {#network-facts} | Property | Value | | --- | --- | | Trading network | `Arc` in `Pair.Market.Network` for trades; `Market.Network` for pair candles; `Token.Network` for token candles | | EVM network | `arc` in `EVM(network: arc)` for other chain data | | Chain ID | `5042` | | Gas token | USDC, tracked as `Currency.Native: true` | | USDC ERC-20 interface | `0x3600000000000000000000000000000000000000` (6 decimals) | | EURC | `0xbEf5f6d51CB62b58e6A8f77868681825C6fe21c1` (6 decimals) | | USYC | `0x8a5D989Bbb96929F689B0200f435f53dA42bF490` (6 decimals) | | Uniswap v4 PoolManager seen by Bitquery | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | | Arc explorer | [explorer.arc.io](https://explorer.arc.io) (listed as permissioned in Arc's RPC reference) | | Arc RPC | `https://rpc.mainnet.arc.io` (listed as permissioned in Arc's RPC reference) | | Bitquery GraphQL | `https://streaming.bitquery.io/graphql` | Arc's [network reference](https://docs.arc.io/arc/references/rpc-endpoints) confirms chain ID `5042`, USDC as the currency symbol, the RPC and the explorer. Arc's [contract list](https://docs.arc.io/arc/references/contract-addresses) gives the stablecoin addresses. --- ## Quick start: latest Arc swaps {#quick-start} This Trading query returns the newest Arc trade rows with USD amounts and the market name. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-overview-quick-start-latest-arc-mainnet-swaps) ```graphql { Trading { Trades( limit: {count: 10} orderBy: {descending: Block_Time} where: {Pair: {Market: {Network: {is: "Arc"}}}} ) { Block { Time } TransactionHeader { Hash } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Quote } PriceInUsd Pair { Market { Network Protocol } Token { Id Symbol } QuoteToken { Id Symbol } } } } } ``` Change `query` to `subscription` and remove `limit` and `orderBy` for a live feed. Follow [WebSocket authentication](/docs/authorization/websocket/) to connect. See the [Arc trades guide](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) for token, pool, trader and protocol filters. --- ## Pick the right API {#pick-the-right-api} | What you need | Cube | Guide | | --- | --- | --- | | Recent trades, USD volume and traders | `Trading.Trades` | [DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) | | Recent token prices and OHLCV | `Trading.Tokens`, `Trading.Pairs` | [Prices and candles](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/#ohlcv-candles-for-a-token) | | Trades older than 30 days, once Arc archive is available | `EVM.DEXTrades`, `EVM.DEXTradeByTokens` | [Older history](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/#trades-older-than-30-days) | | New tokens from verified launchpads, then their first trades | `EVM.Events`, then `Trading.Trades` | [Launchpads API](/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/) | | Argus decoded launches, dev buys, launch calls, token trades and OHLCV | `Events`, `Calls`, `Trading.Trades`, `Trading.Pairs`, `Trading.Tokens` | [Argus Launchpad API](/docs/blockchain/arc-mainnet/argus-launchpad-api/) | | Tolly launches, token trades, trader rankings and OHLCV | `Events`, `Trading.Trades`, `Trading.Pairs`, `Trading.Tokens` | [Tolly Launchpad API](/docs/blockchain/arc-mainnet/tolly-launchpad-api/) | | RadarDEX Classic and Reflection launches, trades and prices | `Events`, `Trading.Trades`, `Trading.Pairs`, `Trading.Tokens` | [RadarDEX Launchpad API](/docs/blockchain/arc-mainnet/radardex-launchpad-api/) | | Minara launches, pool creators, trades and OHLCV | `Events`, `Trading.Trades`, `Trading.Pairs`, `Trading.Tokens` | [Minara Launchpad API](/docs/blockchain/arc-mainnet/minara-launchpad-api/) | | Token and native USDC movement | `Transfers` | [Transfers API](/docs/blockchain/arc-mainnet/arc-mainnet-transfers-api/) | | Decoded logs and new pool events | `Events` | [Events API](/docs/blockchain/arc-mainnet/arc-mainnet-events-api/) | | Method calls, call trees and reverts | `Calls` | [Calls API](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/) | | Transactions, receipts, blocks and fees | `Transactions`, `Blocks` | [Transactions API](/docs/blockchain/arc-mainnet/arc-mainnet-transactions-api/) | | Portfolios, holders, balance history and supply | `Balances`, `Holders`, `TransactionBalances` | [Balances API](/docs/blockchain/arc-mainnet/arc-mainnet-balances-api/) | --- ## USDC on Arc {#usdc} Native USDC and the ERC-20 interface share Arc's USDC model, but Bitquery exposes separate rows so each source stays clear. | Form | Bitquery fields | Decimals | | --- | --- | --- | | Native USDC | `Token.Id: "bid:arc"` and empty `Token.Address` in Trading; `Currency.Native: true`, `SmartContract: "0x"` in EVM transfers and balances | 18 | | ERC-20 USDC | `SmartContract: "0x3600000000000000000000000000000000000000"` | 6 | | System ledger mirror | `0xfffffffffffffffffffffffffffffffffffffffe`, no symbol | raw integer | Filter on `Native: true` for gas-token value transfers. Use the `0x3600...` address for ERC-20 calls and transfers. Exclude the system ledger mirror from token rankings. --- ## DEX data on launch day {#dexes} Production checks found active Uniswap v4, v3 and v2 markets. Use `Trading.Trades` with `Pair.Market.Network: "Arc"` for these trades. The feed can include NFT market fills; filter `Pair.Market.Protocol` or `Pair.Market.ProtocolFamily` when you need a specific swap venue. Arc token IDs use `bid:arc:`, and native USDC uses `bid:arc`. To inspect a trade's calls, logs or transfers, take `TransactionHeader.Hash` and query the matching EVM cube separately. --- ## Datasets and history {#datasets} Trading serves live data and a rolling window of about 30 days. Arc may have less history while indexing starts. Only use the EVM trade cubes for older trades, after archive support is confirmed. On 16 September 2026, only Arc's realtime EVM path answered. The following check measures EVM block history; it does not measure the Trading window: ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-overview-datasets-and-history) ```graphql { EVM(network: arc) { Blocks { count earliest: Block { Number(minimum: Block_Number) Time(minimum: Block_Time) } latest: Block { Number(maximum: Block_Number) Time(maximum: Block_Time) } } } } ``` `dataset: combined` returned an unavailable-data error and `dataset: archive` could not reach its backing host during the check. Retry before treating those modes as live. --- ## Real-time streams {#streaming} Use `Trading.Trades` for trade streams and `Trading.Tokens` or `Trading.Pairs` for price and candle streams. Change the operation to `subscription` and drop `limit`, `orderBy`, and historical time filters. Keep token and trader leaderboards built with aggregates such as `count` or `sum` as HTTP queries; see [streaming limits](/docs/subscriptions/what-does-not-survive-streaming/). The `Ranking.Position` filter on the candle cubes can still be used in a subscription. See [WebSocket subscriptions](/docs/subscriptions/websockets/) and [WebSocket authorization](/docs/authorization/websocket/). --- --- ## Arc Calls & Traces API URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/ Query and stream Arc smart contract calls and traces with Bitquery GraphQL, including selectors, internal calls, deployments, reverts and top methods. # Arc Calls & Traces API Query and stream **smart contract calls on Arc** with Bitquery GraphQL. The `EVM.Calls` cube on `network: arc` holds every call in every transaction, including internal calls, with the decoded method signature, the call path, value, gas, success and revert flags, and the enclosing transaction. It returns what `debug_traceTransaction` and `trace_filter` return, without running a node, and the same query runs as a subscription. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows. :::info Availability checked 16 September 2026 The realtime path returned live calls and populated USD fields. Leave the `dataset` argument out until `combined` and `archive` are enabled. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Blockchain API overview](/docs/blockchain/arc-mainnet/) — network facts, every cube and stream in one place - [Arc Events API](/docs/blockchain/arc-mainnet/arc-mainnet-events-api/) - [Arc Transactions API](/docs/blockchain/arc-mainnet/arc-mainnet-transactions-api/) - [EVM Calls schema](/docs/schema/evm/calls/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) ::: **On this page:** [Call anatomy](#what-one-call-row-contains) · [Stream](#stream-calls-to-a-contract) · [Latest](#latest-calls) · [By method](#calls-of-one-method) · [By selector](#calls-by-4-byte-selector) · [Internal calls of a transaction](#internal-calls-of-a-transaction) · [Deployments](#contract-deployments) · [Reverts](#reverted-calls) · [Top methods](#most-called-methods) · [Value-carrying calls](#calls-that-move-native-usdc) · [FAQ](#faq) --- ## What one call row contains | Group | What it gives you | | --- | --- | | `Call` | `From`, `To`, `Value`, `Input`, `Output`, `Gas`, `GasUsed`, `Success`, `Reverted`, `Error`, `Create`, `Delegated`, `SelfDestruct`, `CallPath`, `Index`, `Depth` | | `Call.Signature` | `Name`, full `Signature`, `SignatureHash` (the 4-byte selector, without `0x`) | | `Arguments` | Decoded, typed inputs for registered ABIs | | `Transaction` | Hash, `From`, `To`, value, gas and fee fields | | `Receipt` | `Status`, `GasUsed`, deployed `ContractAddress` | | `Block` | `Number`, `Time` | A transaction's top-level call has `Call.Index` 0 and an empty `CallPath`; internal calls have deeper paths. Filter `Call: {Index: {eq: 0}}` when you want one row per transaction. ### Example addresses on this page | Item | Address | | --- | --- | | Uniswap v4 PoolManager | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | | USDC (ERC-20) | `0x3600000000000000000000000000000000000000` | --- ## Stream calls to a contract ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-stream-calls-to-contract) Every call into the Uniswap v4 PoolManager, internal or top-level, as it happens. ```graphql subscription { EVM(network: arc) { Calls( where: {Call: {To: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}}} ) { Block { Number Time } Transaction { Hash From } Call { From To Value Success CallPath Signature { Name Signature SignatureHash } } } } } ``` --- ## Latest calls ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-latest-calls) The most recent top-level calls, one per transaction. ```graphql { EVM(network: arc) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Index: {eq: 0}}} ) { Block { Number Time } Transaction { Hash } Call { From To Value Success Gas GasUsed Signature { Name SignatureHash } } } } } ``` --- ## Calls of one method ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-calls-of-a-method) Filter on the decoded method name and the contract. This reads `transfer` calls into the ERC-20 USDC contract with their decoded arguments. ```graphql { EVM(network: arc) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: { Call: { To: {is: "0x3600000000000000000000000000000000000000"} Signature: {Name: {is: "transfer"}} } } ) { Block { Time } Transaction { Hash } Call { From Success Signature { Signature } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## Calls by 4-byte selector ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-calls-by-selector) When the ABI is not registered, filter on the selector in `Call.Input` instead. This matches `approve(address,uint256)` by its `0x095ea7b3` prefix on any contract. ```graphql { EVM(network: arc) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Input: {startsWith: "0x095ea7b3"}}} ) { Block { Time } Transaction { Hash } Call { From To Input Success Signature { Name } } } } } ``` --- ## Internal calls of a transaction ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-internal-calls-of-transaction) The full call tree of one transaction, ordered by call index. Replace the hash with any recent transaction from the [Transactions API](/docs/blockchain/arc-mainnet/arc-mainnet-transactions-api/). ```graphql { EVM(network: arc) { Calls( orderBy: {ascending: Call_Index} where: { Transaction: { Hash: {is: "0x3fb2f3f18ae8ef86dbf6d25f268c861d2982f67308031df45574b5a7fcc02b9f"} } } ) { Call { Index Depth CallPath From To Value Gas GasUsed Success Reverted Delegated Signature { Name Signature } } } } } ``` --- ## Contract deployments ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-contract-deployments) `Call.Create: true` marks a call that deployed a contract. The new address is in `Receipt.ContractAddress` for top-level deployments; for factory deployments read `Call.To` on the create call. ```graphql { EVM(network: arc) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Create: true}} ) { Block { Time Number } Transaction { Hash From } Call { From To Success CallPath } Receipt { ContractAddress } } } } ``` --- ## Reverted calls ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-reverted-calls) Calls that reverted, with the error string when the EVM returned one. Useful for debugging a contract under test. ```graphql { EVM(network: arc) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Reverted: true}} ) { Block { Time } Transaction { Hash From } Call { From To Error CallPath Signature { Name } } } } } ``` --- ## Most called methods ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-most-called-methods) Method signatures ranked by call count over 24 hours. ERC-20 `transfer`, `balanceOf` and `approve` dominate, followed by Uniswap v4 hook callbacks. ```graphql { EVM(network: arc) { Calls( limit: {count: 20} orderBy: {descendingByField: "count"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Call: {Signature: {Name: {not: ""}}} } ) { Call { Signature { Name Signature SignatureHash } } count contracts: uniq(of: Call_To) } } } ``` --- ## Calls that move native USDC ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-calls-with-value) Internal calls that carried native USDC value. This is how value moves between contracts shows up, since those movements are not ERC-20 `Transfer` events. ```graphql { EVM(network: arc) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Value: {gt: "10"}}} ) { Block { Time } Transaction { Hash } Call { From To Value Index Signature { Name } } } } } ``` --- ## FAQ **How do I get one row per transaction?** Filter `Call: {Index: {eq: 0}}`. Every other row is an internal call. **Why is `Signature.Name` empty on some calls?** The ABI is not registered. The raw `Input` and the selector prefix are still there, so filter with `Input: {startsWith: ...}`, and ask support to register the ABI if you need decoded arguments. **Is `Call.Value` in USDC?** Yes. The gas token on Arc is USDC, so `Call.Value` and `Transaction.Value` are native USDC amounts. `ValueInUSD` also returned populated values in the launch-day check. **Does this replace `debug_traceTransaction`?** For call trees, yes: `CallPath`, `Depth`, `Index`, gas per call and revert reasons are all here. Opcode-level traces are not. **Can I read calls older than the realtime window?** Not yet. Only the realtime path answered on 16 September 2026. Retry `archive` and `combined` before using them. --- ## Arc DEX Trades API & Streams URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/ Query and stream Circle Arc trades with the Bitquery Trading cube. Get token prices, OHLCV, USD volume and wallet activity for the last 30 days. # Arc DEX Trades API & Streams Use **`Trading` for Arc trading queries and live streams**. `Trading.Trades` returns trades, USD amounts, token pairs and trader addresses. Use `Trading.Tokens` for token candles across pools and `Trading.Pairs` for prices from a chosen market. :::tip Choose by time range For live streams and trades within the last **30 days**, use the Trading cube. Filter trades with `Pair: {Market: {Network: {is: "Arc"}}}`. Use `EVM.DEXTrades` or `EVM.DEXTradeByTokens` only for trades **older than 30 days**, after confirming Arc archive availability. Trading has a rolling window; a newly indexed chain may have less than 30 days of data. ::: :::info Availability checked 16 September 2026 `Trading.Trades`, `Trading.Tokens` and `Trading.Pairs` return Arc data. Use the root `Trading` without `dataset: archive` or `dataset: combined`. Arc's EVM archive and combined datasets were unavailable at the launch-day check. ::: Open each example with its **Run in IDE** link. Where available, **Run stream** opens the subscription version. For your own app, [create an API access token](/docs/authorization/how-to-generate/) and send queries to `https://streaming.bitquery.io/graphql`. See [WebSocket authentication](/docs/authorization/websocket/) for streams. :::tip Related docs - [Arc Blockchain API overview](/docs/blockchain/arc-mainnet/) - [Arc launchpad token launches and trades](/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/) - [Trading.Trades reference](/docs/trading/crypto-trades-api/trades-api/) - [Token candles](/docs/trading/crypto-price-api/tokens/) and [pair prices](/docs/trading/crypto-price-api/pairs/) - [Trading data and history](/docs/trading/trading-data-overview/) ::: **On this page:** [Identifiers](#network-and-example-addresses) · [Stream](#stream-real-time-trades) · [Latest](#latest-trades) · [By token](#trades-of-a-token) · [By DEX](#trades-on-one-dex) · [By pool](#trades-in-one-pool) · [By trader](#trades-of-a-wallet) · [OHLCV](#ohlcv-candles-for-a-token) · [Latest price](#latest-price-of-a-token) · [Top tokens](#most-traded-tokens) · [DEX breakdown](#trade-count-by-dex-protocol) · [Top traders](#most-active-traders) · [Older history](#trades-older-than-30-days) · [FAQ](#faq) ## Network and example addresses | Item | Trading field or value | | --- | --- | | Arc trades | `Pair.Market.Network: "Arc"` | | Arc pair candles | `Market.Network: "Arc"` | | Arc token candles | `Token.Network: "Arc"` | | Chain ID | `5042` | | Native USDC | `Token.Id: "bid:arc"`, empty `Token.Address` | | ERC-20 USDC | `bid:arc:0x3600000000000000000000000000000000000000` | | EURC example | `bid:arc:0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1` | | Uniswap v4 | `Pair.Market.Protocol: "uniswap_v4"` | | Uniswap v3 pool example | `Pair.Pool.Address: "0x01be77f0a364bddafd34521892ea4745ebf9b5a2"` | `Pair.Token` is the base token; `Pair.QuoteToken` is the quote token. `Side` is the trade direction for the base token. Token IDs include the chain prefix; use `Address` when filtering with a raw contract address. For a v4 pool, use `Pair.Pool.Id`. `Pair.Pool.Address` is the shared PoolManager, so it alone cannot select one v4 pool. On EVM, `Pair.Market.Address` describes the factory and should not be used as a pool filter. ## Stream real-time trades Subscribe to Arc trades with the Trading cube. The network filter is case-sensitive: use `Arc`. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-stream-real-time-trades) ```graphql subscription { Trading { Trades(where: {Pair: {Market: {Network: {is: "Arc"}}}}) { Block { Time } TransactionHeader { Hash } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Quote } Price PriceInUsd Pair { Market { Network Protocol ProtocolFamily } Pool { Address Id } Token { Id Address Symbol } QuoteToken { Id Address Symbol } } } } } ``` The feed can include NFT market fills. Add a protocol filter, as in [Trades on one DEX](#trades-on-one-dex), when you need a specific swap venue. Stream selections use no `limit` or `orderBy`. ## Latest trades Read the latest 20 Arc trade rows. `AmountsInUsd.Quote` gives the USD value of the quote side; use it for USD volume. `PriceInUsd` is the base token's reference USD price and may differ from the executed price during fast moves. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-latest-trades) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Pair: {Market: {Network: {is: "Arc"}}}} ) { Block { Time } TransactionHeader { Hash } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Quote } Price PriceInUsd Pair { Market { Network Protocol } Pool { Address Id } Token { Id Symbol } QuoteToken { Id Symbol } } } } } ``` A transaction can produce several trade rows. Use `count(distinct: TransactionHeader_Hash)` for transaction counts. See the [Trades row notes](/docs/trading/crypto-trades-api/trades-api/#before-you-aggregate-three-things-about-a-trades-row) before reporting exact volumes or counts; duplicate rows can affect sums. ## Trades of a token Match EURC on either side of the pair. The returned amounts and `Side` still describe `Pair.Token`, so check whether EURC is the base or quote token on each row. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-trades-of-a-token) · [Run stream](https://ide.bitquery.io/arc-mainnet-trading-trades-trades-of-a-token-stream) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Pair: {Market: {Network: {is: "Arc"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1"}}}} ] } ) { Block { Time } TransactionHeader { Hash } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Quote } Pair { Token { Id Symbol } QuoteToken { Id Symbol } Market { Network Protocol } } } } } ``` To stream this token, change the operation to `subscription` and remove `limit` and `orderBy`. ## Trades on one DEX Use `Pair.Market.Protocol` to select Uniswap v4 on Arc. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-trades-on-one-dex) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Pair: {Market: {Network: {is: "Arc"}, Protocol: {is: "uniswap_v4"}}} } ) { Block { Time } TransactionHeader { Hash } Side Amounts { Base Quote } AmountsInUsd { Quote } Pair { Market { Network Protocol } Pool { Address Id } Token { Id Symbol } QuoteToken { Id Symbol } } } } } ``` ## Trades in one pool Use `Pair.Pool.Address` for a v2 or v3 pool. This example uses the BUILDOG/USDC v3 pool observed at launch. For v4, replace the address filter with `Pool: {Id: {is: "YOUR_POOL_ID"}}`, using an ID from the live trade feed. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-trades-in-one-pool) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Pair: { Market: {Network: {is: "Arc"}} Pool: {Address: {is: "0x01be77f0a364bddafd34521892ea4745ebf9b5a2"}} } } ) { Block { Time } TransactionHeader { Hash } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Quote } Pair { Pool { Address Id } Token { Id Symbol } QuoteToken { Id Symbol } } } } } ``` ## Trades of a wallet Filter with `Trader.Address`. Replace the sample address with the wallet you want to track. Use `TransactionHeader.Hash` to fetch its [transaction details](/docs/blockchain/arc-mainnet/arc-mainnet-transactions-api/), [calls](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/) or [logs](/docs/blockchain/arc-mainnet/arc-mainnet-events-api/) in a separate EVM query. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-trades-of-a-wallet) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Pair: {Market: {Network: {is: "Arc"}}} Trader: {Address: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}} } ) { Block { Time } TransactionHeader { Hash } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Quote } Pair { Market { Network Protocol } Token { Id Symbol } QuoteToken { Id Symbol } } } } } ``` ## OHLCV candles for a token Use `Trading.Tokens` for hourly EURC candles across its markets. Duration is in seconds: `3600` is one hour, `300` is five minutes. Select one duration to avoid adding overlapping candle intervals. This query returns the newest 24 intervals within the last 24 hours; reverse the rows before plotting from oldest to newest. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-ohlcv-candles-for-a-token-v2) · [Run stream](https://ide.bitquery.io/arc-mainnet-trading-trades-ohlcv-candles-for-a-token-stream-v2) ```graphql { Trading { Tokens( limit: {count: 24} orderBy: {descending: Block_Time} where: { Token: { Network: {is: "Arc"} Address: {is: "0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1"} } Interval: {Time: {Duration: {eq: 3600}}} Block: {Time: {since_relative: {hours_ago: 24}}} Price: {IsQuotedInUsd: true} } ) { Token { Id Symbol Network } Interval { Time { Start End Duration } } Price { IsQuotedInUsd Ohlc { Open High Low Close } } Volume { Base Usd } } } } ``` Missing intervals may be absent, and the current candle can still change. Check the [Tokens field notes](/docs/trading/crypto-price-api/tokens/#field-notes) before treating every row as a unique candle. For a chart tied to one pool or quote token, use [Trading.Pairs](/docs/trading/crypto-price-api/pairs/) with `Market.Network: "Arc"` and the desired pool or quote-token filter. To stream candle updates, use `subscription` and remove `limit`, `orderBy`, and the historical `Block.Time` filter. The stream sends updates after connection; fetch earlier candles with the HTTP query. ## Latest price of a token Query `Trading.Pairs` with rank 1 for EURC's price from its top market. `Price.Ohlc.Close` is the closing USD price of the returned one-minute interval. Check `Interval.Time.End`: a quiet top market can return a stale interval or no row within the last 24 hours. Widen the time window or use `Trading.Tokens` to check other indexed markets. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-latest-price-of-a-token-v2) · [Run stream](https://ide.bitquery.io/arc-mainnet-trading-trades-latest-price-of-a-token-stream-v2) ```graphql { Trading { Pairs( limit: {count: 1} orderBy: {descending: Block_Time} where: { Market: {Network: {is: "Arc"}} Token: {Address: {is: "0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {hours_ago: 24}}} Price: {IsQuotedInUsd: true} } ) { Block { Time } Token { Id Symbol } QuoteToken { Id Symbol } Market { Network Protocol } Pool { Address Id } Interval { Time { Start End Duration } } Price { IsQuotedInUsd Ohlc { Close } } Ranking { Position Weight } Volume { Usd } } } } ``` For the saved price stream, remove `limit`, `orderBy`, and the historical `Block.Time` filter. Keep the token, network, interval, USD and rank filters. The top market can change as trading moves between pools. ## Most traded tokens Rank base tokens by trade-row count over the last 24 hours. These are base-token totals: quote-token activity is not grouped into the same token row. USD volume uses the quote side of each trade. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-most-traded-tokens) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descendingByField: "trade_rows"} where: { Pair: {Market: {Network: {is: "Arc"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Token { Id Symbol } } trade_rows: count transactions: count(distinct: TransactionHeader_Hash) traders: count(distinct: Trader_Address) volume_usd: sum(of: AmountsInUsd_Quote) } } } ``` ## Trade count by DEX protocol Compare protocols by trade-row count and USD volume over the last 24 hours. The network-wide result may also include NFT protocols; filter `Pair.Market.ProtocolFamily` to narrow the comparison. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-trade-count-by-dex-protocol) ```graphql { Trading { Trades( limit: {count: 10} orderBy: {descendingByField: "trade_rows"} where: { Pair: {Market: {Network: {is: "Arc"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Market { Network Protocol ProtocolFamily } } trade_rows: count traders: count(distinct: Trader_Address) volume_usd: sum(of: AmountsInUsd_Quote) } } } ``` ## Most active traders Rank trader addresses by trade-row count. The same wallet can send several swaps in a single transaction, so the query also returns a distinct transaction count. A wallet address can belong to a bot or router. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-trades-most-active-traders) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descendingByField: "trade_rows"} where: { Pair: {Market: {Network: {is: "Arc"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Trader { Address } trade_rows: count transactions: count(distinct: TransactionHeader_Hash) base_tokens: count(distinct: Pair_Token_Id) volume_usd: sum(of: AmountsInUsd_Quote) } } } ``` ## Trades older than 30 days Use chain-level `EVM(network: arc)` trade cubes only when the requested trades are older than the Trading window. Choose [`DEXTrades`](/docs/schema/evm/dextrades/) for swaps or [`DEXTradeByTokens`](/docs/cubes/dextradesbyTokens/) for token-based history. For a range that crosses the 30-day cutoff, query recent trades through Trading and older trades through EVM, then join the results in your app. Set the cutoff once in UTC and avoid counting its boundary twice; Trading time bounds are inclusive. The cubes have different row shapes, so do not add their raw row counts as if they were the same measure. Arc's `dataset: archive` and `dataset: combined` did not answer at the 16 September 2026 check. Confirm support and the date range before using either mode. The [Arc history check](/docs/blockchain/arc-mainnet/#datasets) explains the launch-day limits. Do not send archive or combined arguments to `Trading`. ## FAQ **Which cube should I use for Arc trading streams?** Use `Trading.Trades` with `Pair.Market.Network` set to `Arc`. Use `Trading.Tokens` or `Trading.Pairs` for candle and price streams. **When should I use `DEXTrades` or `DEXTradeByTokens`?** Only for trades older than 30 days, subject to Arc archive support. Query EVM events, calls, transfers and transactions separately when you need those types of data. **Which fields give USD prices and volume?** `Trading.Trades` uses `PriceInUsd` and `AmountsInUsd.Quote`. Candle cubes use `Price.Ohlc` and `Volume.Usd`. Field names are case-sensitive. **Does Arc already have 30 days of Trading history?** The Trading cube's window is about 30 days, but Arc's available history depends on when indexing began. A rolling limit does not guarantee a full 30 days for a newly indexed chain. **How do I identify native USDC?** In Trading, native USDC has ID `bid:arc` and an empty address. ERC-20 USDC has ID `bid:arc:0x3600000000000000000000000000000000000000`. In EVM transfer and balance cubes, use `Currency.Native: true` for native USDC. --- ## Arc Events API & WebSocket Streams URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/arc-mainnet-events-api/ Query and stream Arc smart contract events with Bitquery GraphQL, including decoded logs, topics, arguments and new Uniswap pool events in real time. # Arc Events API & WebSocket Streams Stream **every smart contract event on Arc** with Bitquery GraphQL. The `EVM.Events` cube on `network: arc` returns each log with decoded, typed arguments for known signatures, the raw topics, and the transaction, internal call and receipt that produced it. It covers what `eth_getLogs` and `eth_subscribe("logs")` return, and adds server-side filtering on decoded values. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows. :::info Availability checked 16 September 2026 The realtime path and USD fields returned live data. Leave the `dataset` argument out until `combined` and `archive` are enabled. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Blockchain API overview](/docs/blockchain/arc-mainnet/) — network facts, every cube and stream in one place - [Arc Calls API](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/) - [Arc DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) - [Arc Transfers API](/docs/blockchain/arc-mainnet/arc-mainnet-transfers-api/) - [EVM Events schema](/docs/schema/evm/events/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) ::: **On this page:** [Event anatomy](#what-one-event-row-contains) · [Firehose](#stream-all-events) · [By contract](#events-from-one-contract) · [By signature](#one-event-across-all-contracts) · [By topic0](#filter-by-raw-topic0) · [By argument](#filter-by-a-decoded-argument) · [New v4 pools](#new-uniswap-v4-pools) · [New v3 and v2 pools](#new-uniswap-v3-and-v2-pools) · [Busiest contracts](#busiest-contracts-and-signatures) · [Undecoded events](#undecoded-events) · [FAQ](#faq) --- ## What one event row contains | Group | What it gives you | | --- | --- | | `Log` | `SmartContract` (the code that produced the log), log `Index`, and `Signature` (`Name`, full `Signature`, `SignatureHash`) | | `LogHeader` | `Address`, the emitting address as `eth_getLogs` would return it | | `Topics` | The raw indexed topics; topic0 is the signature hash | | `Arguments` | Decoded, typed values (`address`, `bigInteger`, `string`, `hex`, `bool`, `integer`) with names | | `Transaction` | Hash, `From`, `To`, value, gas and fee fields | | `Call` | The internal call that emitted the log, with its signature and success flags | | `Receipt` | `GasUsed`, `CumulativeGasUsed`, deployed `ContractAddress` | | `Block` | `Number`, `Time` | Hash fields (`SignatureHash`, `Topics.Hash`) are hex strings **without** a `0x` prefix. ### Example addresses on this page | Item | Address | | --- | --- | | Uniswap v4 PoolManager | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | | Uniswap v3 factory seen at launch | `0xf0db7b58379503491d857db50ac9ece64c653918` | | Uniswap v2 factory seen at launch | `0x89e5db8b5aa49aa85ac63f691524311aeb649eba` | | USDC (ERC-20) | `0x3600000000000000000000000000000000000000` | | EURC | `0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1` | --- ## Stream all events ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-stream-all-events) One socket, every event on the chain. Good for building an indexer; heavy for anything else, so use the filtered streams below in production. ```graphql subscription { EVM(network: arc) { Events { Block { Number Time } Transaction { Hash From To } LogHeader { Address } Log { Index Signature { Name Signature SignatureHash } } Topics { Hash } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` --- ## Events from one contract ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-events-from-a-contract) `LogHeader.Address` is the `address` filter of `eth_getLogs`. This reads the latest events of the ERC-20 USDC contract. ```graphql { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x3600000000000000000000000000000000000000"}} } ) { Block { Time } Transaction { Hash } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## One event across all contracts ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-swap-events) Filter by decoded signature name to watch one event type from every contract that emits it. This catches every `Swap`, from Uniswap v2 pairs, v3 pools and the v4 PoolManager alike. ```graphql { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "Swap"}}}} ) { Block { Time } Transaction { Hash } LogHeader { Address } Log { Signature { Signature } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` --- ## Filter by raw topic0 ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-events-by-topic0) When you have the signature hash rather than the name, filter on `Log.Signature.SignatureHash`. This is the ERC-20 `Transfer(address,address,uint256)` hash, written without `0x`. ```graphql { EVM(network: arc) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: { Log: { Signature: { SignatureHash: {is: "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"} } } } ) { Block { Time } Transaction { Hash } LogHeader { Address } Topics { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## Filter by a decoded argument ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-events-by-argument) Server-side filtering on decoded values is what a node cannot do. This finds every event whose argument named `to` equals a wallet, across all contracts and signatures. ```graphql { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { Arguments: { includes: { Name: {is: "to"} Value: {Address: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}} } } } ) { Block { Time } Transaction { Hash } LogHeader { Address } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## New Uniswap v4 pools ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-new-uniswap-v4-pools) Uniswap v4 carried most launch-day swaps. A new pool is an `Initialize` event on the PoolManager; its arguments give the pool `id`, the two currencies, the fee tier, tick spacing, hook address and opening price. ```graphql { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} } ) { Block { Time Number } Transaction { Hash From } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` Change `query` to `subscription` and drop `limit` and `orderBy` to get each new pool the moment it is created. --- ## New Uniswap v3 and v2 pools ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-new-v3-v2-pools) Several v3 and v2 factory deployments appeared on Arc, so filter on the event name rather than one factory address. `PoolCreated` is v3, `PairCreated` is v2; both carry the two tokens and the new pool address in their arguments. ```graphql { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {in: ["PoolCreated", "PairCreated"]}}}} ) { Block { Time } Transaction { Hash } LogHeader { Address } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } } } } } } ``` --- ## Busiest contracts and signatures ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-busiest-event-contracts) Which contracts and event types dominate the log stream over 24 hours. Run this first on any network you have not explored yet. ```graphql { EVM(network: arc) { contracts: Events( limit: {count: 10} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) { LogHeader { Address } count } signatures: Events( limit: {count: 10} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Log { Signature { Name Signature } } count } } } ``` --- ## Undecoded events ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-undecoded-events) Events whose ABI is not registered arrive with an empty `Signature.Name` and no `Arguments`, but the raw `Topics` and `Log.SmartContract` are still there. This lists the contracts emitting the most undecoded events; if one matters to you, ask support to register its ABI. ```graphql { EVM(network: arc) { Events( limit: {count: 10} orderBy: {descendingByField: "count"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Log: {Signature: {Name: {is: ""}}} } ) { LogHeader { Address } Topics { Hash } count } } } ``` --- ## FAQ **How do I map my `eth_getLogs` filter?** `address` becomes `LogHeader.Address`, `topics[0]` becomes `Log.Signature.SignatureHash` (without `0x`), and a fixed block range becomes a `Block.Number` filter. Everything else on this page is extra: decoded arguments, argument filters and joined transaction context. **`LogHeader.Address` or `Log.SmartContract`?** `LogHeader.Address` is the emitting address. `Log.SmartContract` is the code that produced the log, which differs behind proxies. Filter on `LogHeader.Address` to watch a deployed address. **Why do some events have an empty name?** Their ABI is not registered yet. The raw topics and data are still delivered. See [Undecoded events](#undecoded-events). **Can I get history beyond the realtime window?** Not yet. Only the realtime path answered on 16 September 2026. Retry `archive` and `combined` before using them. **How do I follow one Uniswap v4 pool?** Take the pool `id` from its `Initialize` event and filter `Swap` events on the PoolManager whose first argument (`id`) matches it, using the [argument filter](#filter-by-a-decoded-argument) with `Value: {Bytes: ...}`, or read the pool's trades through the [DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) by its two currencies. --- ## Arc Launchpads API & Streams URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/ Find and stream token launches from verified Arc launchpads with Bitquery GraphQL, then query trades, prices and OHLCV for each launched token. # Arc Launchpads API & Streams Find and stream **new token launches on Arc**, then follow each token into its first trades. Use `EVM.Events` for launch events, `Trading.Trades` for recent trades and live streams, and `Trading.Tokens` for prices and candles. This page covers six launchpads whose own sites publish Arc contracts or contract interfaces and whose launch events were found through Bitquery: [Argus](https://argus.world/docs), [RadarDEX](https://www.radardex.pro/), [Tolly](https://tollylabs.com/guide), [Warp](https://circlewarp.fun/), [Archemist](https://archemist.fun/docs), and [PEGD](https://pegd.fun/docs). Every query on this page was executed against the production endpoint before publishing. For platform-specific launch feeds and Trading cube examples, use the [Argus Launchpad API](/docs/blockchain/arc-mainnet/argus-launchpad-api/), [Tolly Launchpad API](/docs/blockchain/arc-mainnet/tolly-launchpad-api/) and [RadarDEX Launchpad API](/docs/blockchain/arc-mainnet/radardex-launchpad-api/). For Minara.fun, use the separate [Minara Launchpad API](/docs/blockchain/arc-mainnet/minara-launchpad-api/). It includes verified strategy and fee-hook contracts, token/pool/creator checks, and Trading cube examples. Minara is outside the six-platform queries below. :::info Availability checked 16 September 2026 The realtime path returned live launch events and trades. Leave the `dataset` argument out until `combined` and `archive` are enabled for Arc. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Blockchain API overview](/docs/blockchain/arc-mainnet/) - [Arc DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) - [Arc Events API](/docs/blockchain/arc-mainnet/arc-mainnet-events-api/) - [EVM Events schema](/docs/schema/evm/events/) - [Trading.Trades reference](/docs/trading/crypto-trades-api/trades-api/) - [Trading token candles](/docs/trading/crypto-price-api/tokens/) ::: **On this page:** [Launchpad contracts](#verified-launchpad-contracts) · [Event topics](#read-the-launched-token-address) · [Stream launches](#stream-launches) · [Latest launches](#latest-launches) · [Launch counts](#launch-count-by-platform) · [Token trades](#trades-for-a-launched-token) · [OHLCV](#ohlcv-for-a-launched-token) --- ## Verified launchpad contracts The contract and event pair is the stable ID for each launchpad. Display names can change; contracts and event hashes do not. | Launchpad | Arc launch contract | Launch event | Signature hash | | --- | --- | --- | --- | | Argus | `0xb021be536808f551b31789422fd28a6c9c6e97da` | `TokenCreated` | `1d8917231579f8ce39407f0d616f36f357b07329b0ce5164d0754ac15145ce0a` | | RadarDEX Classic | `0x4b638c1502a07a8e1a26112ee98f51a3f34bc93a` | `TokenLaunched` | `851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66` | | RadarDEX Reflection | `0x2d933ce4bde6f3d99540b5d7886b383e59b2b2f8` | `TokenLaunched` | `851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66` | | Tolly | `0xcad7ee36ac193bf2eddb7b3e2736c5bdb8269c8b` | `TokenCreated` | `875522b092d9e19a1de359e4bd218090d582fa521c9733889acf1a5ff1941255` | | Warp | `0x0dcad158e98bc24455f9e94f46709d8a5f6d1255` | `TokenCreated` | `0b4cfda446fdf9ec5a85855f088c154869eb62e3e723d7d80319b680f90e0cfd` | | Archemist V2 | `0x297cebc4de347347205cd08667b56ee951dd8810` | `TokenCreated` | `8e83c293b82cf6e864a90c1ccffea5e0f1ec23b271eff78e78f1dbd5e32a9c7d` | | PEGD V4 | `0xd0aa679ec263e8f9bc929426eb9eab2e061d2c5f` | `KeyLaunched` | `4b5a1abdb5ebec3e01fa29e6e1f5e3095f8b3cfaed9ffcd46ad35e7ebc58039e` | Sources: [Argus contract reference](https://github.com/arguspad/argus-world), [RadarDEX launch page](https://www.radardex.pro/), [Tolly guide](https://tollylabs.com/guide), [Warp contracts](https://circlewarp.fun/), [Archemist protocol reference](https://archemist.fun/docs), and [PEGD developer API](https://pegd.fun/docs#developer-api). The table lists current contracts observed on 17 September 2026. Keep old addresses in your index if you need launches from earlier contract versions. Launches are concentrated. In a sample hour on 17 September 2026, Argus emitted 2,983 launch events against 10 from Tolly and 2 from Archemist; the [launch count query](#launch-count-by-platform) reproduces this split for any window, and it is the figure to trust over any count quoted here, since the chain keeps moving. Argus also runs older and forked deployments that emit the same hash, including `0xa5628a11c412596e1f63b75a2c0284f843c549d6` and `0x629c9592c88788b6b31e377e34f7884de9d81ffd`. The portal in the table carried 99.9% of all launches recorded against that hash on both 17 and 18 September 2026, so filtering on it alone is enough for almost every use. Add the others to the address list only if you need those rows. --- ## Read the launched token address Bitquery exposes the raw indexed values in `Topics`: - `Topics[0]` is the event signature hash. - For Argus, RadarDEX, Tolly, Warp, and Archemist, `Topics[1]` contains the launched token address. - For PEGD, `Topics[2]` contains the launched token address; `Topics[1]` is the launch ID. - The address is left-padded to 32 bytes. Take its final 40 hex characters and add `0x`. For example, this topic: ```text 00000000000000000000000091dbd2d6cfe189bea443a9aaab5019d432f7fd99 ``` maps to this token: ```text 0x91dbd2d6cfe189bea443a9aaab5019d432f7fd99 ``` Custom launch events may have an empty decoded `Name`. Filter on `SignatureHash` and read `Topics`; both are present even when the ABI is not in the decoder. --- ## Stream launches Change nothing else to receive launches from all six platforms over one WebSocket. Add or remove contract and signature pairs as launchpads deploy new versions. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-launchpads-stream-launches) ```graphql subscription { EVM(network: arc) { Events( where: { LogHeader: { Address: { in: [ "0xb021be536808f551b31789422fd28a6c9c6e97da" "0x4b638c1502a07a8e1a26112ee98f51a3f34bc93a" "0x2d933ce4bde6f3d99540b5d7886b383e59b2b2f8" "0xcad7ee36ac193bf2eddb7b3e2736c5bdb8269c8b" "0x0dcad158e98bc24455f9e94f46709d8a5f6d1255" "0x297cebc4de347347205cd08667b56ee951dd8810" "0xd0aa679ec263e8f9bc929426eb9eab2e061d2c5f" ] } } Log: { Signature: { SignatureHash: { in: [ "1d8917231579f8ce39407f0d616f36f357b07329b0ce5164d0754ac15145ce0a" "851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66" "875522b092d9e19a1de359e4bd218090d582fa521c9733889acf1a5ff1941255" "0b4cfda446fdf9ec5a85855f088c154869eb62e3e723d7d80319b680f90e0cfd" "8e83c293b82cf6e864a90c1ccffea5e0f1ec23b271eff78e78f1dbd5e32a9c7d" "4b5a1abdb5ebec3e01fa29e6e1f5e3095f8b3cfaed9ffcd46ad35e7ebc58039e" ] } } } } ) { Block { Number Time } Transaction { Hash From } LogHeader { Address } Log { Signature { SignatureHash } } Topics { Hash } } } } ``` Map `LogHeader.Address` to the contract table to name the launchpad. --- ## Latest launches Use the same filters with `query`, a row limit, and descending block time to fetch the newest launches. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-launchpads-latest-launches) ```graphql { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { LogHeader: { Address: { in: [ "0xb021be536808f551b31789422fd28a6c9c6e97da" "0x4b638c1502a07a8e1a26112ee98f51a3f34bc93a" "0x2d933ce4bde6f3d99540b5d7886b383e59b2b2f8" "0xcad7ee36ac193bf2eddb7b3e2736c5bdb8269c8b" "0x0dcad158e98bc24455f9e94f46709d8a5f6d1255" "0x297cebc4de347347205cd08667b56ee951dd8810" "0xd0aa679ec263e8f9bc929426eb9eab2e061d2c5f" ] } } Log: { Signature: { SignatureHash: { in: [ "1d8917231579f8ce39407f0d616f36f357b07329b0ce5164d0754ac15145ce0a" "851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66" "875522b092d9e19a1de359e4bd218090d582fa521c9733889acf1a5ff1941255" "0b4cfda446fdf9ec5a85855f088c154869eb62e3e723d7d80319b680f90e0cfd" "8e83c293b82cf6e864a90c1ccffea5e0f1ec23b271eff78e78f1dbd5e32a9c7d" "4b5a1abdb5ebec3e01fa29e6e1f5e3095f8b3cfaed9ffcd46ad35e7ebc58039e" ] } } } } ) { Block { Number Time } Transaction { Hash From } LogHeader { Address } Log { Signature { SignatureHash } } Topics { Hash } } } } ``` --- ## Launch count by platform Group launch events by emitting contract to compare activity during the last hour. The result uses contract addresses, so map them to the table above in your app. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-docs-launchpads-launch-count-by-platform) ```graphql { EVM(network: arc) { Events( limit: {count: 10} orderBy: {descendingByField: "count"} where: { Block: {Time: {since_relative: {hours_ago: 1}}} LogHeader: { Address: { in: [ "0xb021be536808f551b31789422fd28a6c9c6e97da" "0x4b638c1502a07a8e1a26112ee98f51a3f34bc93a" "0x2d933ce4bde6f3d99540b5d7886b383e59b2b2f8" "0xcad7ee36ac193bf2eddb7b3e2736c5bdb8269c8b" "0x0dcad158e98bc24455f9e94f46709d8a5f6d1255" "0x297cebc4de347347205cd08667b56ee951dd8810" "0xd0aa679ec263e8f9bc929426eb9eab2e061d2c5f" ] } } Log: { Signature: { SignatureHash: { in: [ "1d8917231579f8ce39407f0d616f36f357b07329b0ce5164d0754ac15145ce0a" "851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66" "875522b092d9e19a1de359e4bd218090d582fa521c9733889acf1a5ff1941255" "0b4cfda446fdf9ec5a85855f088c154869eb62e3e723d7d80319b680f90e0cfd" "8e83c293b82cf6e864a90c1ccffea5e0f1ec23b271eff78e78f1dbd5e32a9c7d" "4b5a1abdb5ebec3e01fa29e6e1f5e3095f8b3cfaed9ffcd46ad35e7ebc58039e" ] } } } } ) { LogHeader { Address } count } } } ``` --- ## Trades for a launched token Read the token address from the [launch event topics](#read-the-launched-token-address), then use it in `Trading.Trades`. Most listed launchpads put the address in `Topics[1]`; PEGD uses `Topics[2]`. Match both `Pair.Token` and `Pair.QuoteToken` to catch the token on either side of the pair. This example follows DUKE, launched through Argus. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-launchpads-trades-for-a-launched-token) · [Run stream](https://ide.bitquery.io/arc-mainnet-trading-launchpads-trades-for-a-launched-token-stream) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Pair: {Market: {Network: {is: "Arc"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0x41358defd0dedc90528b3f1835715e907b686e6a"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0x41358defd0dedc90528b3f1835715e907b686e6a"}}}} ] } ) { Block { Time } TransactionHeader { Hash } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Quote } PriceInUsd Pair { Token { Id Address Symbol } QuoteToken { Id Address Symbol } Market { Network Protocol } Pool { Address Id } } } } } ``` Change `{` to `subscription {` to receive the same trades live. :::caution Example tokens go quiet Launched tokens stop trading quickly. An empty list means this token has gone quiet, not that the query is wrong — take a current address from [Latest launches](#latest-launches). ::: ## OHLCV for a launched token `Trading.Tokens` returns USD candles across the token's markets. `Volume.Usd` is USD volume and `Volume.Base` is token volume. The candle cube carries no trade count, so use `Trading.Trades` when you need one. ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-trading-launchpads-ohlcv-for-a-launched-token) · [Run stream](https://ide.bitquery.io/arc-mainnet-trading-launchpads-ohlcv-for-a-launched-token-stream) ```graphql { Trading { Tokens( limit: {count: 12} orderBy: {descending: Block_Time} where: { Token: { Network: {is: "Arc"} Address: {is: "0x41358defd0dedc90528b3f1835715e907b686e6a"} } Interval: {Time: {Duration: {eq: 300}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Token { Id Symbol Network } Interval { Time { Start End Duration } } Price { Ohlc { Open High Low Close } } Volume { Base Usd } } } } ``` Some launchpads create Uniswap v3 pools, while others use v4 or a bonding curve before moving liquidity. Keeping the token filter on `Trading` follows the token across those routes. Use `EVM.DEXTrades` or `EVM.DEXTradeByTokens` only for history older than 30 days, after confirming Arc archive support. --- ## Arc Testnet API: Circle's Stablecoin L1 via GraphQL, WebSocket and Kafka URL: https://docs.bitquery.io/docs/blockchain/arc-testnet/ Arc testnet API (chain ID 5042002): trades, transfers, balances, events, calls, transactions and blocks on Circle's USDC-gas Layer 1 via Bitquery GraphQL, WebSocket streams and Kafka topics. # Arc Testnet API: Circle's Stablecoin L1 via GraphQL, WebSocket and Kafka :::tip Arc mainnet is live Most production integrations should use the [Arc Mainnet API](/docs/blockchain/arc-mainnet/) with `EVM(network: arc)`. Use this page only for Arc testnet data. ::: **Arc** is Circle's EVM-compatible Layer 1 built for stablecoin finance: **USDC is the native gas token**, blocks finalize in well under a second on the Malachite BFT consensus, and the chain carries USDC, EURC and a growing set of DeFi deployments led by Uniswap v4. Bitquery indexes the **Arc testnet** as `EVM(network: arc_testnet)` and publishes it as Kafka topics under `arc-testnet.*`, so you can test before deploying the same queries to mainnet, Ethereum, Base or Robinhood Chain. This page is the map. Use it to pick the cube that answers your question, then jump to the linked guide. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ## Arc testnet at a glance {#network-facts} | Property | Value | | --- | --- | | Bitquery network name | `arc_testnet` in `EVM(network: arc_testnet)` | | Kafka topic prefix | `arc-testnet.` | | Chain ID | `5042002` | | Stack | EVM, Circle Arc Layer 1, Malachite BFT consensus | | Gas token | USDC, tracked as `Currency.Native: true` | | USDC (ERC-20 interface, 6 decimals) | `0x3600000000000000000000000000000000000000` | | EURC (6 decimals) | `0x89b50855aa3be2f677cd6303cec089b5f319d72a` | | Uniswap v4 PoolManager | `0x1d70945634f618eefdf9edaadb59b9a183cef929` | | Public explorer | [testnet.arcscan.app](https://testnet.arcscan.app). Bitquery is an indexed data API, not an explorer or an RPC node | | GraphQL endpoint | `https://streaming.bitquery.io/graphql` for queries and subscriptions | --- ## What is different on a testnet {#testnet-limits} Arc testnet is indexed with the same EVM schema as every other chain, with four differences you should know before writing queries. | Difference | What it means for your query | | --- | --- | | **USD values are 0** | Every `...InUSD` field (`AmountInUSD`, `PriceInUSD`, `ValueInUSD`, `CostInUSD`) returns 0. There is no token price index on a testnet. Native prices such as `Trade.Price` work, and since most pairs quote in USDC they are effectively dollar prices. | | **Realtime dataset only** | There is no archive for the testnet. Leave the `dataset` argument out; `archive` and `combined` return errors. The realtime window is a rolling range of recent blocks; measure it with `Block { Time(minimum: Block_Time) }`. | | **No `Trading` cubes** | `Trading.Trades`, `Tokens` and `Pairs` cover mainnet chains with USD pricing. Use the chain-level `DEXTrades` and `DEXTradeByTokens` cubes. | | **Some cubes are unavailable** | `Holders` needs the archive and is not served. `DEXPoolEvents` and `DEXPoolSlippages` have no data yet. `Balances` and `TransactionBalances` work. | Arc **mainnet** is indexed with USD pricing, the `Trading` cubes and the `Holders` cube. Use the [Arc Mainnet API](/docs/blockchain/arc-mainnet/) for production data. Its `archive` and `combined` datasets are not enabled yet. --- ## Quick start: stream every swap on Arc testnet {#quick-start} Paste this into the [Bitquery IDE](https://ide.bitquery.io) to watch the network trade in real time. Uniswap v4 carries most of the volume, with v3, v2, Curve and Aerodrome deployments behind it. ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-stream-dex-trades) ```graphql subscription { EVM(network: arc_testnet) { DEXTrades { Block { Number Time } Transaction { Hash From } Trade { Dex { ProtocolFamily ProtocolName SmartContract } Buy { Amount Buyer Seller Price Currency { Name Symbol SmartContract } } Sell { Amount Buyer Seller Price Currency { Name Symbol SmartContract } } } } } } ``` Change `subscription` to `query`, add `limit: {count: 10}` and `orderBy: {descending: Block_Time}`, and the same selection set returns the latest trades instead. OHLCV candles, token prices, top tokens and trader activity are on the [Arc Testnet DEX Trades API](/docs/blockchain/arc-testnet/arc-testnet-trades-api) page. --- ## Pick the right API {#pick-the-right-api} | What you want | Use this | Guide | | --- | --- | --- | | Live swaps, OHLCV, token prices, top tokens, DEX breakdown, trader activity | `DEXTrades`, `DEXTradeByTokens` | [Arc Testnet DEX Trades API](/docs/blockchain/arc-testnet/arc-testnet-trades-api) | | Who sent what to whom, wallet ledgers, large transfers, most-transferred tokens | `Transfers` | [Arc Testnet Transfers API](/docs/blockchain/arc-testnet/arc-testnet-transfers-api) | | Any decoded contract event, new Uniswap v4/v3/v2 pools, an `eth_getLogs` replacement | `Events` | [Arc Testnet Events API](/docs/blockchain/arc-testnet/arc-testnet-events-api) | | Method calls, internal traces, contract deployments, reverts | `Calls` | [Arc Testnet Calls & Traces API](/docs/blockchain/arc-testnet/arc-testnet-calls-api) | | Transactions, receipts, blocks, USDC gas fees | `Transactions`, `Blocks` | [Arc Testnet Transactions, Blocks & Fees API](/docs/blockchain/arc-testnet/arc-testnet-transactions-api) | | A wallet's portfolio, balance history, active holders, token total supply | `Balances`, `TransactionBalances` | [Arc Testnet Balances & Token Supply API](/docs/blockchain/arc-testnet/arc-testnet-balances-api) | --- ## USDC on Arc: native and ERC-20 {#usdc} USDC is both the gas token and an ERC-20 on Arc, and Bitquery tracks the two as separate currencies. | Form | How it appears | Decimals | | --- | --- | --- | | Native USDC | `Currency.Native: true` with `SmartContract: "0x"` in `Transfers` and `Balances`; the zero address with name `USD Coin` in `DEXTrades` and `DEXTradeByTokens` | 18 | | ERC-20 USDC | `SmartContract: "0x3600000000000000000000000000000000000000"`, symbol `USDC` | 6 | | System ledger | `0xfffffffffffffffffffffffffffffffffffffffe`, no symbol, raw 18-decimal integers mirroring native movements | 0 | Filter on `Native: true` for gas-token value transfers and on the `0x3600...` contract for the ERC-20 interface. Exclude the system ledger from token rankings. Transaction fees are in native USDC, so `Fee.SenderFee` on the [Transactions API](/docs/blockchain/arc-testnet/arc-testnet-transactions-api#gas-fees-in-usdc) is already a dollar figure. --- ## DEXes on Arc testnet {#dexes} | Protocol | `Dex.ProtocolName` | Notes | | --- | --- | --- | | Uniswap v4 | `uniswap_v4` | Most swaps on the testnet. Pools live in the PoolManager singleton, so `Dex.SmartContract` is `0x1d70945634f618eefdf9edaadb59b9a183cef929` and new pools are `Initialize` events. | | Uniswap v3 | `uniswap_v3` | Several factory deployments; `Dex.SmartContract` is the pool. | | Uniswap v2 | `uniswap_v2` | Several factory deployments; `Dex.SmartContract` is the pair. | | Curve | `curve_v1` | Stablecoin pools. | | Aerodrome | `aerodrome_v1` | Light activity. | The [DEX Trades API](/docs/blockchain/arc-testnet/arc-testnet-trades-api#trade-count-by-dex-protocol) has a live breakdown by protocol, and the [Events API](/docs/blockchain/arc-testnet/arc-testnet-events-api#new-uniswap-v4-pools) streams new pools as they are created. --- ## Real-time streams: WebSocket and Kafka {#streaming} - **WebSocket.** Every query on every page above runs as a subscription: swap `query` for `subscription` and keep the same selection set. See [WebSocket subscriptions](/docs/subscriptions/websockets/) and [authorizing a WebSocket connection](/docs/authorization/websocket/). - **Kafka.** For firehose-scale workloads, Arc testnet is published as protobuf topics under the `arc-testnet.` prefix: `arc-testnet.transactions.proto` (transactions, calls, events), `arc-testnet.tokens.proto` (transfers, balances), `arc-testnet.dextrades.proto` (DEX trades) and `arc-testnet.raw.proto` (raw blocks). The message schemas are the same as every other EVM chain; USD fields in the messages are 0 on the testnet. See [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/) and the [EVM protobuf streams](/docs/streams/protobuf/chains/EVM-protobuf/). --- ## Datasets and history {#datasets} Only the **`realtime`** dataset exists for Arc testnet. It holds a rolling window of recent blocks, and its depth is not fixed, so measure it before relying on a time range: ```graphql { EVM(network: arc_testnet) { Blocks { count earliest: Block { Time(minimum: Block_Time) } latest: Block { Time(maximum: Block_Time) } } } } ``` `dataset: archive` and `dataset: combined` return errors on the testnet. Arc mainnet serves the `Holders` cube, but its `archive` and `combined` datasets are not enabled yet. --- --- ## Arc Testnet Balances & Token Supply API URL: https://docs.bitquery.io/docs/blockchain/arc-testnet/arc-testnet-balances-api/ Query wallet balances, balance history and token total supply on Circle's Arc testnet with Bitquery GraphQL: full portfolios, multi-wallet batches, per-token balance changes and TransactionBalances supply. # Arc Testnet Balances & Token Supply API :::tip Arc mainnet is live Most production integrations should use the [Arc Mainnet Balances & Token Supply API](/docs/blockchain/arc-mainnet/arc-mainnet-balances-api/) with `EVM(network: arc)`. Use this page only for Arc testnet data. ::: Query **wallet balances and token supply on Arc testnet** with Bitquery GraphQL. Two cubes on `network: arc_testnet` cover it: | Cube | What it returns | | --- | --- | | `Balances` | Computed current balance per address and currency, with first and last change time and update count | | `TransactionBalances` | Per-transaction pre- and post-balances, and the token's `TotalSupply` | For the net flow over a time window, the page also uses `Transfers`. Every query on this page was executed against the production endpoint before publishing. :::warning Testnet limits - `...InUSD` fields are **0**. Value holdings with the [latest price query](/docs/blockchain/arc-testnet/arc-testnet-trades-api/#latest-price-of-a-token) if you need a dollar figure. - Only `dataset: realtime` exists; leave the `dataset` argument out. - The token-centric **`Holders`** cube is not available on Arc testnet because it is served from the archive dataset. Rank `Balances` rows by amount, as in [top holders of a token](#top-holders-of-a-token), for holder rankings within the realtime window. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Testnet API overview](/docs/blockchain/arc-testnet/) — network facts, every cube and stream in one place - [Arc Testnet Transfers API](/docs/blockchain/arc-testnet/arc-testnet-transfers-api/) - [Arc Testnet DEX Trades API](/docs/blockchain/arc-testnet/arc-testnet-trades-api/) - [EVM Balances schema](/docs/schema/evm/balances/) - [EVM Token Supply API](/docs/blockchain/Ethereum/token-supply/evm-token-supply/) ::: **On this page:** [Portfolio](#portfolio-of-a-wallet) · [One token](#balance-of-one-token) · [Batch](#balances-of-several-wallets) · [Top holders](#top-holders-of-a-token) · [History](#balance-history-of-a-wallet) · [Stream](#stream-balance-changes) · [Supply](#total-supply-of-a-token) · [Supply stream](#stream-supply-changes) · [FAQ](#faq) --- ## Portfolio of a wallet ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-wallet-portfolio) Every currency an address holds, with the computed balance and when it last changed. Native USDC has `Native: true`; the ERC-20 interface at `0x3600...` is listed separately. ```graphql { EVM(network: arc_testnet) { Balances( where: {Balance: {Address: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} orderBy: {descending: Balance_Amount} ) { Currency { Name Symbol SmartContract Native } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Balance of one token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-balance-of-one-token) The `balanceOf` equivalent for ERC-20 USDC. For the gas token use `Currency: {Native: true}` instead of a contract filter. ```graphql { EVM(network: arc_testnet) { Balances( where: { Balance: {Address: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}} Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } ) { Currency { Symbol Decimals } Balance { Amount LastChangeTime } } } } ``` --- ## Balances of several wallets ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-balances-of-several-wallets) One call for a batch of addresses, grouped by address and currency. ```graphql { EVM(network: arc_testnet) { Balances( where: { Balance: { Address: { in: [ "0x2de8906a641d65d490bc60a4179d961d59742bcb" "0x73742278c31a76dbb0d2587d03ef92e6e2141023" "0x49f9636fe15883e16d5e356a4ea08c9fe6bc219b" ] } } Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } orderBy: {descending: Balance_Amount} ) { Balance { Address Amount } Currency { Symbol } } } } ``` --- ## Top holders of a token Addresses ranked by their current balance of one token, from `Balances`. On the testnet this covers balances inside the realtime window rather than a full-chain snapshot, so treat it as a leaderboard of active holders. The top row is usually the Uniswap v4 PoolManager, which holds pool reserves. ```graphql { EVM(network: arc_testnet) { Balances( where: { Currency: {SmartContract: {is: "0xe2cfd2893ad90e8a5b4f87c5cad22d150b1e12a0"}} } orderBy: {descending: Balance_Amount} limit: {count: 20} ) { Balance { Address Amount(selectWhere: {gt: "0"}) UpdateCount LastChangeTime } Currency { Symbol } } } } ``` --- ## Balance history of a wallet Each change to a wallet's ERC-20 USDC balance, newest first, with the transaction behind it. `TransactionBalances` gives the balance before (`PreBalance`) and after (`PostBalance`) each transaction. ```graphql { EVM(network: arc_testnet) { TransactionBalances( limit: {count: 20} orderBy: {descending: Block_Time} where: { TokenBalance: { Address: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"} Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } } ) { Block { Number Time } Transaction { Hash } TokenBalance { PreBalance PostBalance Currency { Symbol } } } } } ``` ### Net change per currency over a window Sum the wallet's transfers per currency to see what it gained or lost over the last 24 hours. `inflow` counts transfers received, `outflow` counts transfers sent. ```graphql { EVM(network: arc_testnet) { Transfers( where: { any: [ {Transfer: {Sender: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} {Transfer: {Receiver: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} ] Block: {Time: {since_relative: {hours_ago: 24}}} } orderBy: {descendingByField: "transfers"} ) { Transfer { Currency { Symbol SmartContract Native } } inflow: sum(of: Transfer_Amount, if: {Transfer: {Receiver: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}}) outflow: sum(of: Transfer_Amount, if: {Transfer: {Sender: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}}) netChange: calculate(expression: "$inflow - $outflow") transfers: count } } } ``` --- ## Stream balance changes Every balance change of a wallet as it happens, from `TransactionBalances`. Widen the filter to a list of addresses or a single token to build alerts. ```graphql subscription { EVM(network: arc_testnet) { TransactionBalances( where: { TokenBalance: {Address: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}} } ) { Block { Number Time } Transaction { Hash } TokenBalance { PreBalance PostBalance Currency { Symbol SmartContract Native } } } } } ``` --- ## Total supply of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-token-total-supply) `TransactionBalances` records the token's total supply after each transaction that touched it. The latest row is the current supply, already adjusted for decimals. ```graphql { EVM(network: arc_testnet) { TransactionBalances( limit: {count: 1} orderBy: {descending: Block_Time} where: { TokenBalance: { Currency: {SmartContract: {is: "0xe2cfd2893ad90e8a5b4f87c5cad22d150b1e12a0"}} } } ) { Block { Time } TokenBalance { Currency { Symbol SmartContract } TotalSupply } } } } ``` --- ## Stream supply changes ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-stream-token-supply) A new row arrives whenever a mint or burn changes the supply of the token. ```graphql subscription { EVM(network: arc_testnet) { TransactionBalances( where: { TokenBalance: { Currency: {SmartContract: {is: "0xe2cfd2893ad90e8a5b4f87c5cad22d150b1e12a0"}} } } ) { Block { Time } Transaction { Hash } TokenBalance { Currency { Symbol } TotalSupply } } } } ``` --- ## FAQ **Why is the `Holders` cube missing?** `Holders` is built from the archive dataset, and the testnet has none. Rank holders by ordering `Balances` by amount within the realtime window, as shown above. The [Arc mainnet balances guide](/docs/blockchain/arc-mainnet/arc-mainnet-balances-api/) uses the full `Holders` cube. **Why does the same wallet show USDC twice?** Native USDC (`Native: true`, 18 decimals) and the ERC-20 USDC interface (`0x3600...`, 6 decimals) are tracked as two currencies. Sum them yourself if you want one USDC figure. A third row with contract `0xfff...fffe` and no symbol is a system ledger mirror and can be ignored. **Are USD values available?** No. Every `...InUSD` field is 0 on the testnet. Because most balances are dollar stablecoins, `Amount` is usually the figure you want anyway. **Is `TotalSupply` raw or decimal-adjusted?** Decimal-adjusted. A token with a billion supply reads `1000000000.000000000000000000`. --- ## Arc Testnet Calls & Traces API URL: https://docs.bitquery.io/docs/blockchain/arc-testnet/arc-testnet-calls-api/ Query and stream smart contract calls and internal traces on Circle's Arc testnet with Bitquery GraphQL: method calls by selector, internal calls of a transaction, contract deployments, reverts and top methods. # Arc Testnet Calls & Traces API :::tip Arc mainnet is live Most production integrations should use the [Arc Mainnet Calls & Traces API](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/) with `EVM(network: arc)`. Use this page only for Arc testnet data. ::: Query and stream **smart contract calls on Arc testnet** with Bitquery GraphQL. The `EVM.Calls` cube on `network: arc_testnet` holds every call in every transaction, including internal calls, with the decoded method signature, the call path, value, gas, success and revert flags, and the enclosing transaction. It returns what `debug_traceTransaction` and `trace_filter` return, without running a node, and the same query runs as a subscription. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows. :::warning Testnet: realtime only, USD fields are 0 Only `dataset: realtime` exists for Arc testnet; leave the `dataset` argument out. `Call.ValueInUSD` and the transaction `...InUSD` fields return 0. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Testnet API overview](/docs/blockchain/arc-testnet/) — network facts, every cube and stream in one place - [Arc Testnet Events API](/docs/blockchain/arc-testnet/arc-testnet-events-api/) - [Arc Testnet Transactions API](/docs/blockchain/arc-testnet/arc-testnet-transactions-api/) - [EVM Calls schema](/docs/schema/evm/calls/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) ::: **On this page:** [Call anatomy](#what-one-call-row-contains) · [Stream](#stream-calls-to-a-contract) · [Latest](#latest-calls) · [By method](#calls-of-one-method) · [By selector](#calls-by-4-byte-selector) · [Internal calls of a transaction](#internal-calls-of-a-transaction) · [Deployments](#contract-deployments) · [Reverts](#reverted-calls) · [Top methods](#most-called-methods) · [Value-carrying calls](#calls-that-move-native-usdc) · [FAQ](#faq) --- ## What one call row contains | Group | What it gives you | | --- | --- | | `Call` | `From`, `To`, `Value`, `Input`, `Output`, `Gas`, `GasUsed`, `Success`, `Reverted`, `Error`, `Create`, `Delegated`, `SelfDestruct`, `CallPath`, `Index`, `Depth` | | `Call.Signature` | `Name`, full `Signature`, `SignatureHash` (the 4-byte selector, without `0x`) | | `Arguments` | Decoded, typed inputs for registered ABIs | | `Transaction` | Hash, `From`, `To`, value, gas and fee fields | | `Receipt` | `Status`, `GasUsed`, deployed `ContractAddress` | | `Block` | `Number`, `Time` | A transaction's top-level call has `Call.Index` 0 and an empty `CallPath`; internal calls have deeper paths. Filter `Call: {Index: {eq: 0}}` when you want one row per transaction. ### Example addresses on this page | Item | Address | | --- | --- | | Uniswap v4 PoolManager | `0x1d70945634f618eefdf9edaadb59b9a183cef929` | | USDC (ERC-20) | `0x3600000000000000000000000000000000000000` | --- ## Stream calls to a contract ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-stream-calls-to-contract) Every call into the Uniswap v4 PoolManager, internal or top-level, as it happens. ```graphql subscription { EVM(network: arc_testnet) { Calls( where: {Call: {To: {is: "0x1d70945634f618eefdf9edaadb59b9a183cef929"}}} ) { Block { Number Time } Transaction { Hash From } Call { From To Value Success CallPath Signature { Name Signature SignatureHash } } } } } ``` --- ## Latest calls ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-latest-calls) The most recent top-level calls, one per transaction. ```graphql { EVM(network: arc_testnet) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Index: {eq: 0}}} ) { Block { Number Time } Transaction { Hash } Call { From To Value Success Gas GasUsed Signature { Name SignatureHash } } } } } ``` --- ## Calls of one method ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-calls-of-a-method) Filter on the decoded method name and the contract. This reads `transfer` calls into the ERC-20 USDC contract with their decoded arguments. ```graphql { EVM(network: arc_testnet) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: { Call: { To: {is: "0x3600000000000000000000000000000000000000"} Signature: {Name: {is: "transfer"}} } } ) { Block { Time } Transaction { Hash } Call { From Success Signature { Signature } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## Calls by 4-byte selector ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-calls-by-selector) When the ABI is not registered, filter on the selector in `Call.Input` instead. This matches `approve(address,uint256)` by its `0x095ea7b3` prefix on any contract. ```graphql { EVM(network: arc_testnet) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Input: {startsWith: "0x095ea7b3"}}} ) { Block { Time } Transaction { Hash } Call { From To Input Success Signature { Name } } } } } ``` --- ## Internal calls of a transaction ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-internal-calls-of-transaction) The full call tree of one transaction, ordered by call index. Replace the hash with any recent transaction from the [Transactions API](/docs/blockchain/arc-testnet/arc-testnet-transactions-api/). ```graphql { EVM(network: arc_testnet) { Calls( orderBy: {ascending: Call_Index} where: { Transaction: { Hash: {is: "0x9be99a14a7db15fae9b78c68c3bfb41cfd67654a7b8cdf499f56e712d8349fe1"} } } ) { Call { Index Depth CallPath From To Value Gas GasUsed Success Reverted Delegated Signature { Name Signature } } } } } ``` --- ## Contract deployments ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-contract-deployments) `Call.Create: true` marks a call that deployed a contract. The new address is in `Receipt.ContractAddress` for top-level deployments; for factory deployments read `Call.To` on the create call. ```graphql { EVM(network: arc_testnet) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Create: true}} ) { Block { Time Number } Transaction { Hash From } Call { From To Success CallPath } Receipt { ContractAddress } } } } ``` --- ## Reverted calls ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-reverted-calls) Calls that reverted, with the error string when the EVM returned one. Useful for debugging a contract under test. ```graphql { EVM(network: arc_testnet) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Reverted: true}} ) { Block { Time } Transaction { Hash From } Call { From To Error CallPath Signature { Name } } } } } ``` --- ## Most called methods ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-most-called-methods) Method signatures ranked by call count over 24 hours. ERC-20 `transfer`, `balanceOf` and `approve` dominate, followed by Uniswap v4 hook callbacks. ```graphql { EVM(network: arc_testnet) { Calls( limit: {count: 20} orderBy: {descendingByField: "count"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Call: {Signature: {Name: {not: ""}}} } ) { Call { Signature { Name Signature SignatureHash } } count contracts: uniq(of: Call_To) } } } ``` --- ## Calls that move native USDC ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-calls-with-value) Internal calls that carried native USDC value. This is how value moves between contracts shows up, since those movements are not ERC-20 `Transfer` events. ```graphql { EVM(network: arc_testnet) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: {Call: {Value: {gt: "10"}}} ) { Block { Time } Transaction { Hash } Call { From To Value Index Signature { Name } } } } } ``` --- ## FAQ **How do I get one row per transaction?** Filter `Call: {Index: {eq: 0}}`. Every other row is an internal call. **Why is `Signature.Name` empty on some calls?** The ABI is not registered. The raw `Input` and the selector prefix are still there, so filter with `Input: {startsWith: ...}`, and ask support to register the ABI if you need decoded arguments. **Is `Call.Value` in USDC?** Yes. The gas token on Arc is USDC, so `Call.Value` and `Transaction.Value` are native USDC amounts. `ValueInUSD` is 0 on testnet even though the value is dollar-denominated. **Does this replace `debug_traceTransaction`?** For call trees, yes: `CallPath`, `Depth`, `Index`, gas per call and revert reasons are all here. Opcode-level traces are not. **Can I read calls older than the realtime window?** Not on the testnet; only `dataset: realtime` exists. --- ## Arc Testnet DEX Trades API & Streams URL: https://docs.bitquery.io/docs/blockchain/arc-testnet/arc-testnet-trades-api/ Query and stream Uniswap v2, v3, v4 and Curve trades on Circle's Arc testnet with Bitquery GraphQL: live swaps, latest trades, OHLCV candles, top tokens, DEX breakdown and trader activity. # Arc Testnet DEX Trades API & Streams :::tip Arc mainnet is live Most production integrations should use the [Arc Mainnet DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) with `EVM(network: arc)`. Use this page only for Arc testnet data. ::: Query and stream **DEX trades on Arc testnet** with Bitquery GraphQL. Arc is Circle's EVM Layer 1 for stablecoin finance, and its testnet is exposed as `EVM(network: arc_testnet)`. The `DEXTrades` and `DEXTradeByTokens` cubes carry every swap on **Uniswap v4, v3 and v2, Curve and Aerodrome** with buy and sell sides, native-unit prices, the DEX contract, the trader and the transaction. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows over WebSocket. :::warning Testnet: no USD values, no Trading cube, realtime only - Every `...InUSD` field (`AmountInUSD`, `PriceInUSD`, `ValueInUSD`) returns **0** on Arc testnet. There is no token price index for a testnet. Prices in `Trade.Price` and `Trade.PriceInUSD` are ratios of the two sides and work normally. - The multi-chain `Trading` cubes (`Trading.Trades`, `Tokens`, `Pairs`) do **not** include Arc testnet. Use the chain-level `DEXTrades` and `DEXTradeByTokens` cubes on this page. - Only `dataset: realtime` (the default) is served. There is no archive for the testnet, so leave the `dataset` argument out. For live data with USD pricing, use the [Arc Mainnet DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/). The mainnet `archive` and `combined` datasets are not enabled yet. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Testnet API overview](/docs/blockchain/arc-testnet/) — network facts, every cube and stream in one place - [Arc Testnet Transfers API](/docs/blockchain/arc-testnet/arc-testnet-transfers-api/) - [Arc Testnet Events API](/docs/blockchain/arc-testnet/arc-testnet-events-api/) — Uniswap v4 `Initialize`, v3 `PoolCreated`, v2 `PairCreated` - [Arc Testnet Balances API](/docs/blockchain/arc-testnet/arc-testnet-balances-api/) - [DEXTrades vs DEXTradeByTokens vs Trading.Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades/) - [EVM DEXTrades schema](/docs/schema/evm/dextrades/) ::: **On this page:** [Identifiers](#network-and-example-addresses) · [Stream](#stream-real-time-trades) · [Latest](#latest-trades) · [By token](#trades-of-a-token) · [By DEX](#trades-on-one-dex) · [By pool](#trades-in-one-pool) · [By trader](#trades-of-a-wallet) · [OHLCV](#ohlcv-candles-for-a-token) · [Latest price](#latest-price-of-a-token) · [Top tokens](#most-traded-tokens) · [DEX breakdown](#trade-count-by-dex-protocol) · [Top traders](#most-active-traders) · [FAQ](#faq) --- ## Network and example addresses | Item | Value | | --- | --- | | Network argument | `EVM(network: arc_testnet)` | | Chain ID | `5042002` | | Native gas token | USDC. Appears as `SmartContract: "0x0000000000000000000000000000000000000000"` with symbol `USDC` and name `USD Coin` in `DEXTrades` and `DEXTradeByTokens`; as `"0x"` with `Currency.Native: true` in `Transfers` and `Balances` | | USDC (ERC-20 interface, 6 decimals) | `0x3600000000000000000000000000000000000000` | | EURC (6 decimals) | `0x89b50855aa3be2f677cd6303cec089b5f319d72a` | | USDT (testnet mock, 18 decimals) | `0x175cdb1d338945f0d851a741ccf787d343e57952` | | ARCFOMO (busiest meme token at the time of writing) | `0xe2cfd2893ad90e8a5b4f87c5cad22d150b1e12a0` | | Uniswap v4 PoolManager | `0x1d70945634f618eefdf9edaadb59b9a183cef929`, the `Dex.SmartContract` on every v4 trade | | Uniswap v3 USDC/USDT pool | `0x715f78de0cea7428a5ede4a0c491b05e7a8caff2` | | Uniswap v3 EURC/USDT pool | `0x66a038f2f6000cf42d34c3ccd6c97ccfa16443bd` | These are live examples. Testnet tokens come and go, so swap in any token, pool or trader you care about. :::info Uniswap v4 pools have no address On v4 every pool lives inside the singleton PoolManager, so `Trade.Dex.SmartContract` is the PoolManager and `Trade.Dex.Pair.SmartContract` is the zero address. Identify a v4 pool by its two currencies, or by the `id` argument of the `Initialize` event on the [Events API](/docs/blockchain/arc-testnet/arc-testnet-events-api/#new-uniswap-v4-pools). ::: --- ## Stream real-time trades ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-stream-dex-trades) One WebSocket delivers every swap on the network as blocks are indexed, with both sides, the protocol and the trader. ```graphql subscription { EVM(network: arc_testnet) { DEXTrades { Block { Number Time } Transaction { Hash From } Trade { Dex { ProtocolFamily ProtocolName SmartContract } Buy { Amount Buyer Seller Price Currency { Name Symbol SmartContract } } Sell { Amount Buyer Seller Price Currency { Name Symbol SmartContract } } } } } } ``` --- ## Latest trades ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-latest-dex-trades) The most recent swaps on the network. `Trade.Buy` is the currency the trader received and `Trade.Sell` is what they paid. ```graphql { EVM(network: arc_testnet) { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} ) { Block { Number Time } Transaction { Hash From } Trade { Dex { ProtocolName SmartContract } Buy { Amount Currency { Symbol SmartContract } Price } Sell { Amount Currency { Symbol SmartContract } } } } } } ``` --- ## Trades of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-trades-of-a-token) `DEXTradeByTokens` returns one row per token side of every trade, so a token filter catches it whether it was bought or sold. `Side.Type` says which direction the trade was from the token's point of view. ```graphql { EVM(network: arc_testnet) { DEXTradeByTokens( limit: {count: 20} orderBy: {descending: Block_Time} where: { Trade: { Currency: {SmartContract: {is: "0xe2cfd2893ad90e8a5b4f87c5cad22d150b1e12a0"}} } } ) { Block { Time } Transaction { Hash } Trade { Amount Price Currency { Symbol } Side { Type Amount Currency { Symbol SmartContract } } Dex { ProtocolName } } } } } ``` --- ## Trades on one DEX ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-uniswap-v4-trades) Filter by `Dex.ProtocolName`. Values seen on Arc testnet are `uniswap_v4`, `uniswap_v3`, `uniswap_v2`, `curve_v1` and `aerodrome_v1`. ```graphql { EVM(network: arc_testnet) { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v4"}}}} ) { Block { Time } Transaction { Hash } Trade { Dex { ProtocolName SmartContract } Buy { Amount Currency { Symbol SmartContract } } Sell { Amount Currency { Symbol SmartContract } } } } } } ``` --- ## Trades in one pool ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-trades-in-a-pool) For Uniswap v2 and v3 the pool has its own address in `Trade.Dex.SmartContract`. This example reads the v3 USDC/USDT pool. ```graphql { EVM(network: arc_testnet) { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Trade: { Dex: {SmartContract: {is: "0x715f78de0cea7428a5ede4a0c491b05e7a8caff2"}} } } ) { Block { Time } Transaction { Hash From } Trade { Buy { Amount Currency { Symbol } Price } Sell { Amount Currency { Symbol } } } } } } ``` --- ## Trades of a wallet ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-trades-of-a-wallet) `Transaction.From` is the externally owned account that signed the swap. `Trade.Buy.Buyer` and `Trade.Sell.Seller` are the addresses that received and paid the tokens, which can be a router rather than the signer. ```graphql { EVM(network: arc_testnet) { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Transaction: {From: {is: "0x47262d76684b071ba33304e5aa8b424035f3e06c"}} } ) { Block { Time } Transaction { Hash } Trade { Dex { ProtocolName } Buy { Amount Currency { Symbol } Buyer } Sell { Amount Currency { Symbol } Seller } } } } } ``` --- ## OHLCV candles for a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-ohlcv-candles) Hourly candles for ARCFOMO priced in native USDC. `Block.Time(interval: ...)` buckets the trades; `open` and `close` take the price at the lowest and highest block in the bucket. Change `count` and `in` for other intervals. ```graphql { EVM(network: arc_testnet) { DEXTradeByTokens( limit: {count: 24} orderBy: {descendingByField: "Block_Time"} where: { Trade: { Currency: {SmartContract: {is: "0xe2cfd2893ad90e8a5b4f87c5cad22d150b1e12a0"}} Side: { Currency: {SmartContract: {is: "0x0000000000000000000000000000000000000000"}} } } } ) { Block { Time(interval: {in: hours, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } count } } } ``` --- ## Latest price of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-latest-token-price) The price of the most recent trade against native USDC. Because the quote is a dollar stablecoin, `Trade.Price` here is effectively a USD price even though `PriceInUSD` is 0 on testnet. ```graphql { EVM(network: arc_testnet) { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: { Trade: { Currency: {SmartContract: {is: "0xe2cfd2893ad90e8a5b4f87c5cad22d150b1e12a0"}} Side: { Currency: {SmartContract: {is: "0x0000000000000000000000000000000000000000"}} } } } ) { Block { Time } Trade { Price Currency { Symbol } Side { Currency { Symbol } } Dex { ProtocolName } } } } } ``` --- ## Most traded tokens ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-most-traded-tokens) Tokens ranked by trade count over the last 24 hours. Native USDC is the quote on most pools, so it tops the list; the rows under it are the tokens people actually trade. ```graphql { EVM(network: arc_testnet) { DEXTradeByTokens( limit: {count: 20} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Trade { Currency { Symbol Name SmartContract } } count volume: sum(of: Trade_Amount) traders: uniq(of: Transaction_From) } } } ``` --- ## Trade count by DEX protocol ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-trades-by-dex) Which DEXes carry the testnet's volume. Uniswap v4 dominates at the time of writing. ```graphql { EVM(network: arc_testnet) { DEXTrades( limit: {count: 10} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Trade { Dex { ProtocolFamily ProtocolName } } count pools: uniq(of: Trade_Dex_SmartContract) traders: uniq(of: Transaction_From) } } } ``` --- ## Most active traders ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-most-active-traders) Signers ranked by swap count. On a testnet the top rows are usually bots and routers; drop the first few addresses to find real wallets. ```graphql { EVM(network: arc_testnet) { DEXTrades( limit: {count: 20} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Transaction { From } count tokens: uniq(of: Trade_Buy_Currency_SmartContract) } } } ``` --- ## FAQ **Why is every `AmountInUSD` and `PriceInUSD` zero?** Arc testnet has no token price index, so USD fields are 0 by design. `Trade.Price` is the ratio between the two sides and is correct. When the quote is USDC or another dollar stablecoin, that ratio is a dollar price. **Can I use `Trading.Trades` with `bid:arc_testnet`?** No. The `Trading` cubes cover mainnet chains with USD pricing. Arc testnet is served only through `EVM(network: arc_testnet)`. **How far back does the data go?** Only the `realtime` dataset exists for the testnet, and it holds a rolling window of recent blocks. Measure it with `Block { Time(minimum: Block_Time) }` rather than assuming a depth. `dataset: archive` and `dataset: combined` return errors. **Why does native USDC show two different contract addresses?** The native gas token is USDC. The trade cubes report it as the zero address with name `USD Coin`; `Transfers` and `Balances` report it as `"0x"` with `Currency.Native: true`. The ERC-20 interface at `0x3600000000000000000000000000000000000000` is a separate currency with 6 decimals and name `USDC`. **Do Solidity selectors and topic hashes work the same as on Ethereum?** Yes. Arc is EVM-compatible, so ABIs, 4-byte selectors and topic0 hashes carry over unchanged. --- ## Arc Testnet Events API & WebSocket Streams URL: https://docs.bitquery.io/docs/blockchain/arc-testnet/arc-testnet-events-api/ Stream every smart contract event on Circle's Arc testnet with Bitquery GraphQL: decoded logs by contract, signature, topic0 or argument, plus Uniswap v4 Initialize, v3 PoolCreated and v2 PairCreated feeds. # Arc Testnet Events API & WebSocket Streams :::tip Arc mainnet is live Most production integrations should use the [Arc Mainnet Events API](/docs/blockchain/arc-mainnet/arc-mainnet-events-api/) with `EVM(network: arc)`. Use this page only for Arc testnet data. ::: Stream **every smart contract event on Arc testnet** with Bitquery GraphQL. The `EVM.Events` cube on `network: arc_testnet` returns each log with decoded, typed arguments for known signatures, the raw topics, and the transaction, internal call and receipt that produced it. It covers what `eth_getLogs` and `eth_subscribe("logs")` return, and adds server-side filtering on decoded values. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows. :::warning Testnet: realtime only, USD fields are 0 Only `dataset: realtime` exists for Arc testnet; leave the `dataset` argument out. `Transaction.ValueInUSD`, `Call.ValueInUSD` and the gas `...InUSD` fields return 0. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Testnet API overview](/docs/blockchain/arc-testnet/) — network facts, every cube and stream in one place - [Arc Testnet Calls API](/docs/blockchain/arc-testnet/arc-testnet-calls-api/) - [Arc Testnet DEX Trades API](/docs/blockchain/arc-testnet/arc-testnet-trades-api/) - [Arc Testnet Transfers API](/docs/blockchain/arc-testnet/arc-testnet-transfers-api/) - [EVM Events schema](/docs/schema/evm/events/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) ::: **On this page:** [Event anatomy](#what-one-event-row-contains) · [Firehose](#stream-all-events) · [By contract](#events-from-one-contract) · [By signature](#one-event-across-all-contracts) · [By topic0](#filter-by-raw-topic0) · [By argument](#filter-by-a-decoded-argument) · [New v4 pools](#new-uniswap-v4-pools) · [New v3 and v2 pools](#new-uniswap-v3-and-v2-pools) · [Busiest contracts](#busiest-contracts-and-signatures) · [Undecoded events](#undecoded-events) · [FAQ](#faq) --- ## What one event row contains | Group | What it gives you | | --- | --- | | `Log` | `SmartContract` (the code that produced the log), log `Index`, and `Signature` (`Name`, full `Signature`, `SignatureHash`) | | `LogHeader` | `Address`, the emitting address as `eth_getLogs` would return it | | `Topics` | The raw indexed topics; topic0 is the signature hash | | `Arguments` | Decoded, typed values (`address`, `bigInteger`, `string`, `hex`, `bool`, `integer`) with names | | `Transaction` | Hash, `From`, `To`, value, gas and fee fields | | `Call` | The internal call that emitted the log, with its signature and success flags | | `Receipt` | `GasUsed`, `CumulativeGasUsed`, deployed `ContractAddress` | | `Block` | `Number`, `Time` | Hash fields (`SignatureHash`, `Topics.Hash`) are hex strings **without** a `0x` prefix. ### Example addresses on this page | Item | Address | | --- | --- | | Uniswap v4 PoolManager | `0x1d70945634f618eefdf9edaadb59b9a183cef929` | | Uniswap v3 factory (busiest `PoolCreated` emitter) | `0x0fb6eeda6e90e90797083861a75d15752a27f59c` | | Uniswap v2 factory (busiest `PairCreated` emitter) | `0xd67f63a4f26a497b364d1c82e6747aec8b5743a5` | | USDC (ERC-20) | `0x3600000000000000000000000000000000000000` | | EURC | `0x89b50855aa3be2f677cd6303cec089b5f319d72a` | --- ## Stream all events ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-stream-all-events) One socket, every event on the chain. Good for building an indexer; heavy for anything else, so use the filtered streams below in production. ```graphql subscription { EVM(network: arc_testnet) { Events { Block { Number Time } Transaction { Hash From To } LogHeader { Address } Log { Index Signature { Name Signature SignatureHash } } Topics { Hash } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` --- ## Events from one contract ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-events-from-a-contract) `LogHeader.Address` is the `address` filter of `eth_getLogs`. This reads the latest events of the ERC-20 USDC contract. ```graphql { EVM(network: arc_testnet) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x3600000000000000000000000000000000000000"}} } ) { Block { Time } Transaction { Hash } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## One event across all contracts ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-swap-events) Filter by decoded signature name to watch one event type from every contract that emits it. This catches every `Swap`, from Uniswap v2 pairs, v3 pools and the v4 PoolManager alike. ```graphql { EVM(network: arc_testnet) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "Swap"}}}} ) { Block { Time } Transaction { Hash } LogHeader { Address } Log { Signature { Signature } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` --- ## Filter by raw topic0 ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-events-by-topic0) When you have the signature hash rather than the name, filter on `Log.Signature.SignatureHash`. This is the ERC-20 `Transfer(address,address,uint256)` hash, written without `0x`. ```graphql { EVM(network: arc_testnet) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: { Log: { Signature: { SignatureHash: {is: "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"} } } } ) { Block { Time } Transaction { Hash } LogHeader { Address } Topics { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## Filter by a decoded argument ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-events-by-argument) Server-side filtering on decoded values is what a node cannot do. This finds every event whose argument named `to` equals a wallet, across all contracts and signatures. ```graphql { EVM(network: arc_testnet) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { Arguments: { includes: { Name: {is: "to"} Value: {Address: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}} } } } ) { Block { Time } Transaction { Hash } LogHeader { Address } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## New Uniswap v4 pools ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-new-uniswap-v4-pools) Uniswap v4 carries most of the testnet's swaps. A new pool is an `Initialize` event on the PoolManager; its arguments give the pool `id`, the two currencies, the fee tier, tick spacing, hook address and opening price. `currency0` of the zero address means native USDC. ```graphql { EVM(network: arc_testnet) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x1d70945634f618eefdf9edaadb59b9a183cef929"}} Log: {Signature: {Name: {is: "Initialize"}}} } ) { Block { Time Number } Transaction { Hash From } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` Change `query` to `subscription` and drop `limit` and `orderBy` to get each new pool the moment it is created. --- ## New Uniswap v3 and v2 pools ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-new-v3-v2-pools) Several v3 and v2 factory deployments exist on the testnet, so filter on the event name rather than one factory address. `PoolCreated` is v3, `PairCreated` is v2; both carry the two tokens and the new pool address in their arguments. ```graphql { EVM(network: arc_testnet) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {in: ["PoolCreated", "PairCreated"]}}}} ) { Block { Time } Transaction { Hash } LogHeader { Address } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } } } } } } ``` --- ## Busiest contracts and signatures ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-busiest-event-contracts) Which contracts and event types dominate the log stream over 24 hours. Run this first on any network you have not explored yet. ```graphql { EVM(network: arc_testnet) { contracts: Events( limit: {count: 10} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) { LogHeader { Address } count } signatures: Events( limit: {count: 10} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Log { Signature { Name Signature } } count } } } ``` --- ## Undecoded events ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-undecoded-events) Events whose ABI is not registered arrive with an empty `Signature.Name` and no `Arguments`, but the raw `Topics` and `Log.SmartContract` are still there. This lists the contracts emitting the most undecoded events; if one matters to you, ask support to register its ABI. ```graphql { EVM(network: arc_testnet) { Events( limit: {count: 10} orderBy: {descendingByField: "count"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Log: {Signature: {Name: {is: ""}}} } ) { LogHeader { Address } Topics { Hash } count } } } ``` --- ## FAQ **How do I map my `eth_getLogs` filter?** `address` becomes `LogHeader.Address`, `topics[0]` becomes `Log.Signature.SignatureHash` (without `0x`), and a fixed block range becomes a `Block.Number` filter. Everything else on this page is extra: decoded arguments, argument filters and joined transaction context. **`LogHeader.Address` or `Log.SmartContract`?** `LogHeader.Address` is the emitting address. `Log.SmartContract` is the code that produced the log, which differs behind proxies. Filter on `LogHeader.Address` to watch a deployed address. **Why do some events have an empty name?** Their ABI is not registered yet. The raw topics and data are still delivered. See [Undecoded events](#undecoded-events). **Can I get history beyond the realtime window?** Not on the testnet; only `dataset: realtime` exists. **How do I follow one Uniswap v4 pool?** Take the pool `id` from its `Initialize` event and filter `Swap` events on the PoolManager whose first argument (`id`) matches it, using the [argument filter](#filter-by-a-decoded-argument) with `Value: {Bytes: ...}`, or read the pool's trades through the [DEX Trades API](/docs/blockchain/arc-testnet/arc-testnet-trades-api/) by its two currencies. --- ## Arc Testnet Transactions, Blocks & Fees API URL: https://docs.bitquery.io/docs/blockchain/arc-testnet/arc-testnet-transactions-api/ Query and stream transactions, receipts, blocks and USDC gas fees on Circle's Arc testnet with Bitquery GraphQL: transaction by hash, address history, failed transactions, block stats and fee analytics. # Arc Testnet Transactions, Blocks & Fees API :::tip Arc mainnet is live Most production integrations should use the [Arc Mainnet Transactions, Blocks & Fees API](/docs/blockchain/arc-mainnet/arc-mainnet-transactions-api/) with `EVM(network: arc)`. Use this page only for Arc testnet data. ::: Query and stream **transactions, receipts and blocks on Arc testnet** with Bitquery GraphQL. The `EVM.Transactions` and `EVM.Blocks` cubes on `network: arc_testnet` cover what a block explorer shows for a hash, an address or a block, with fees in **USDC** because USDC is the chain's gas token. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows. :::warning Testnet: realtime only, USD fields are 0 Only `dataset: realtime` exists for Arc testnet; leave the `dataset` argument out. `ValueInUSD`, `CostInUSD`, `GasPriceInUSD` and the other `...InUSD` fields return 0. Fee fields such as `Fee.SenderFee` are native USDC and populated. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Testnet API overview](/docs/blockchain/arc-testnet/) — network facts, every cube and stream in one place - [Arc Testnet Calls API](/docs/blockchain/arc-testnet/arc-testnet-calls-api/) — the call tree inside a transaction - [Arc Testnet Transfers API](/docs/blockchain/arc-testnet/arc-testnet-transfers-api/) - [EVM Transactions schema](/docs/schema/evm/transactions/) - [EVM Blocks schema](/docs/schema/evm/blocks/) ::: **On this page:** [Stream](#stream-transactions) · [Latest](#latest-transactions) · [By hash](#transaction-by-hash) · [By address](#transactions-of-an-address) · [Failed](#failed-transactions) · [Fees](#gas-fees-in-usdc) · [Latest blocks](#latest-blocks) · [Block by number](#block-by-number) · [Block stats](#block-and-throughput-statistics) · [FAQ](#faq) --- ## Stream transactions ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-stream-transactions) Every transaction as blocks are indexed. Arc produces a block well under every second, so expect a steady feed. ```graphql subscription { EVM(network: arc_testnet) { Transactions { Block { Number Time } Transaction { Hash From To Value Gas Type Nonce } Receipt { Status GasUsed ContractAddress } Fee { SenderFee EffectiveGasPrice } } } } ``` --- ## Latest transactions ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-latest-transactions) ```graphql { EVM(network: arc_testnet) { Transactions( limit: {count: 20} orderBy: {descending: Block_Time} ) { Block { Number Time } Transaction { Hash From To Value Type } Receipt { Status GasUsed } Fee { SenderFee } } } } ``` --- ## Transaction by hash ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-transaction-by-hash) The equivalent of `eth_getTransactionByHash` plus `eth_getTransactionReceipt` in one call. The example hash is a live USDC value transfer; replace it with any recent hash. ```graphql { EVM(network: arc_testnet) { Transactions( where: { Transaction: { Hash: {is: "0x9be99a14a7db15fae9b78c68c3bfb41cfd67654a7b8cdf499f56e712d8349fe1"} } } ) { Block { Number Time Hash } Transaction { Hash From To Value Gas GasPrice GasFeeCap GasTipCap Nonce Type Index } Receipt { Status GasUsed CumulativeGasUsed ContractAddress } Fee { SenderFee EffectiveGasPrice PriorityFeePerGas Burnt } } } } ``` --- ## Transactions of an address ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-transactions-of-an-address) Sent and received transactions of one address, newest first. This is the explorer's address page. ```graphql { EVM(network: arc_testnet) { Transactions( limit: {count: 20} orderBy: {descending: Block_Time} where: { any: [ {Transaction: {From: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} {Transaction: {To: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} ] } ) { Block { Number Time } Transaction { Hash From To Value } Receipt { Status } Fee { SenderFee } } } } ``` --- ## Failed transactions ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-failed-transactions) Transactions whose receipt status is 0. Join the [reverted calls](/docs/blockchain/arc-testnet/arc-testnet-calls-api/#reverted-calls) query on the hash to see the revert reason. ```graphql { EVM(network: arc_testnet) { Transactions( limit: {count: 20} orderBy: {descending: Block_Time} where: {TransactionStatus: {Success: false}} ) { Block { Time } Transaction { Hash From To Gas } Receipt { GasUsed } Fee { SenderFee } } } } ``` --- ## Gas fees in USDC ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-gas-fee-statistics) Because gas is paid in USDC, `Fee.SenderFee` is already a dollar amount. This gives the average, median and total fee per hour along with the average effective gas price. ```graphql { EVM(network: arc_testnet) { Transactions( orderBy: {descendingByField: "Block_Time"} limit: {count: 24} ) { Block { Time(interval: {in: hours, count: 1}) } count totalFees: sum(of: Fee_SenderFee) avgFee: average(of: Fee_SenderFee) medianFee: median(of: Fee_SenderFee) avgGasPrice: average(of: Fee_EffectiveGasPrice) avgGasUsed: average(of: Receipt_GasUsed) } } } ``` --- ## Latest blocks ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-latest-blocks) ```graphql { EVM(network: arc_testnet) { Blocks( limit: {count: 20} orderBy: {descending: Block_Number} ) { Block { Number Time Hash TxCount GasUsed GasLimit BaseFee Coinbase } } } } ``` Change `query` to `subscription` and drop `limit` and `orderBy` to receive each block header as it is indexed. --- ## Block by number ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-block-by-number) ```graphql { EVM(network: arc_testnet) { Blocks(where: {Block: {Number: {eq: "61696399"}}}) { Block { Number Time Hash ParentHash TxCount GasUsed GasLimit BaseFee Coinbase Difficulty } } } } ``` --- ## Block and throughput statistics ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-block-statistics) Blocks, transactions, average transactions per block and average gas per block for each of the last 24 hours. Divide the block count by 3600 to get blocks per second. ```graphql { EVM(network: arc_testnet) { Blocks( orderBy: {descendingByField: "Block_Time"} limit: {count: 24} ) { Block { Time(interval: {in: hours, count: 1}) } blocks: count transactions: sum(of: Block_TxCount) avgTxPerBlock: average(of: Block_TxCount) avgGasUsed: average(of: Block_GasUsed) medianGasUsed: median(of: Block_GasUsed) } } } ``` --- ## FAQ **What unit is `Fee.SenderFee` in?** Native USDC. Arc pays gas in USDC, so a fee of `0.0025` is a quarter of a cent. `CostInUSD` and `GasPriceInUSD` are still 0 on testnet because there is no price index, even though the native unit is a dollar. **Why is `Transaction.GasPrice` 0 while the fee is not?** Arc transactions are EIP-1559 type 2. Read `Fee.EffectiveGasPrice`, `Transaction.GasFeeCap` and `Transaction.GasTipCap`; the legacy `GasPrice` field is 0 for these. **How fast are blocks?** Well under a second on average. Measure the current rate with the [block statistics](#block-and-throughput-statistics) query rather than assuming a fixed interval. **Can I get a transaction's internal calls and logs from here?** Use the same hash on the [Calls API](/docs/blockchain/arc-testnet/arc-testnet-calls-api/#internal-calls-of-a-transaction) for the call tree and the [Events API](/docs/blockchain/arc-testnet/arc-testnet-events-api/) for the logs. **Is there a block explorer?** Circle's testnet explorer is at [testnet.arcscan.app](https://testnet.arcscan.app). Bitquery is an indexed data API rather than an explorer, and every explorer lookup on this page can be run in bulk or streamed. --- ## Arc Testnet Transfers API & Streams URL: https://docs.bitquery.io/docs/blockchain/arc-testnet/arc-testnet-transfers-api/ Query and stream token transfers on Circle's Arc testnet with Bitquery GraphQL: native USDC, ERC-20 USDC, EURC, wallet ledgers, large transfers, most-transferred tokens and daily volume. # Arc Testnet Transfers API & Streams :::tip Arc mainnet is live Most production integrations should use the [Arc Mainnet Transfers API](/docs/blockchain/arc-mainnet/arc-mainnet-transfers-api/) with `EVM(network: arc)`. Use this page only for Arc testnet data. ::: Query and stream **token transfers on Arc testnet** with Bitquery GraphQL. This is the shared **EVM `Transfers`** cube scoped to `network: arc_testnet`, so a query written for Ethereum or Base runs here by changing the network name. Arc's native gas token is **USDC**, and the chain carries an ERC-20 USDC interface, **EURC**, a testnet **USDT** and thousands of test tokens. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows over WebSocket. :::warning Testnet: USD fields are 0 and only the realtime dataset exists `Transfer.AmountInUSD` is always **0** on Arc testnet. Filter and rank by `Transfer.Amount` instead. Leave the `dataset` argument out; `archive` and `combined` return errors on the testnet. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Testnet API overview](/docs/blockchain/arc-testnet/) — network facts, every cube and stream in one place - [Arc Testnet DEX Trades API](/docs/blockchain/arc-testnet/arc-testnet-trades-api/) - [Arc Testnet Balances API](/docs/blockchain/arc-testnet/arc-testnet-balances-api/) - [Arc Testnet Events API](/docs/blockchain/arc-testnet/arc-testnet-events-api/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) - [EVM Transfers schema](/docs/schema/evm/transfers/) ::: **On this page:** [Currencies](#how-usdc-appears-in-transfers) · [Stream](#stream-real-time-transfers) · [Latest](#latest-transfers) · [Native USDC](#native-usdc-transfers) · [By token](#transfers-of-a-token) · [By address](#transfers-of-an-address) · [Between two addresses](#transfers-between-two-addresses) · [Large transfers](#large-transfers) · [Top tokens](#most-transferred-tokens) · [Hourly volume](#hourly-transfer-volume-of-a-token) · [FAQ](#faq) --- ## How USDC appears in Transfers USDC exists in three forms on Arc testnet. Check which one a row is before you sum or rank anything. | Currency | `SmartContract` | `Native` | Decimals | What it is | | --- | --- | --- | --- | --- | | USDC (native) | `0x` | `true` | 18 | The gas token. Value transfers and gas fees. | | USDC (ERC-20) | `0x3600000000000000000000000000000000000000` | `false` | 6 | The ERC-20 interface most contracts and wallets call. Symbol `USDC`, name `USDC`. | | System ledger | `0xfffffffffffffffffffffffffffffffffffffffe` | `false` | 0 | A system address that emits a raw `Transfer` event mirroring native USDC movements as 18-decimal integers with no symbol. Exclude it from token rankings. | Other stablecoins seen on the testnet: | Token | Address | Decimals | | --- | --- | --- | | EURC | `0x89b50855aa3be2f677cd6303cec089b5f319d72a` | 6 | | USDT (testnet mock) | `0x175cdb1d338945f0d851a741ccf787d343e57952` | 18 | | WUSDC (Wrapped USDC) | `0x911b4000d3422f482f4062a913885f7b035382df` | 18 | --- ## Stream real-time transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-stream-transfers) Every transfer on the network as it is indexed. Filter inside `where` to narrow the socket to a token, an address or a size floor. ```graphql subscription { EVM(network: arc_testnet) { Transfers { Block { Number Time } Transaction { Hash From To } Transfer { Amount Sender Receiver Type Currency { Name Symbol SmartContract Native Decimals } } } } } ``` --- ## Latest transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-latest-transfers) ```graphql { EVM(network: arc_testnet) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} ) { Block { Number Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol SmartContract Native } } } } } ``` --- ## Native USDC transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-native-usdc-transfers) `Currency: {Native: true}` selects value transfers of the gas token. The floor of 100 USDC keeps dust and fee movements out. ```graphql { EVM(network: arc_testnet) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { Transfer: { Currency: {Native: true} Amount: {gt: "100"} } } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Native } } } } } ``` --- ## Transfers of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-erc20-usdc-transfers) Filter on the token contract. This example reads the ERC-20 USDC interface; swap in EURC or any test token. ```graphql { EVM(network: arc_testnet) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { Transfer: { Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Decimals } } } } } ``` --- ## Transfers of an address ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-transfers-of-an-address) Incoming and outgoing transfers in one list. Replace the address with any wallet or contract. ```graphql { EVM(network: arc_testnet) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { any: [ {Transfer: {Sender: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} {Transfer: {Receiver: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} ] } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol SmartContract Native } } } } } ``` ### Sent and received totals per token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-address-sent-received) Two aliased selections give the outbound and inbound sums per currency for a wallet. ```graphql { EVM(network: arc_testnet) { sent: Transfers( where: {Transfer: {Sender: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} orderBy: {descendingByField: "amount"} limit: {count: 10} ) { Transfer { Currency { Symbol SmartContract } } amount: sum(of: Transfer_Amount) count } received: Transfers( where: {Transfer: {Receiver: {is: "0x2de8906a641d65d490bc60a4179d961d59742bcb"}}} orderBy: {descendingByField: "amount"} limit: {count: 10} ) { Transfer { Currency { Symbol SmartContract } } amount: sum(of: Transfer_Amount) count } } } ``` --- ## Transfers between two addresses ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-transfers-between-addresses) Flows from one address to another, in either direction. Useful for tracing a faucet, a bridge or a counterparty. ```graphql { EVM(network: arc_testnet) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { any: [ { Transfer: { Sender: {is: "0xe72f8175ab0991dbb778f6de62009c5bf97c17f7"} Receiver: {is: "0x1d70945634f618eefdf9edaadb59b9a183cef929"} } } { Transfer: { Sender: {is: "0x1d70945634f618eefdf9edaadb59b9a183cef929"} Receiver: {is: "0xe72f8175ab0991dbb778f6de62009c5bf97c17f7"} } } ] } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Native } } } } } ``` --- ## Large transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-large-usdc-transfers) With USD values at 0 on testnet, size filters go on `Transfer.Amount` for one currency at a time. This catches ERC-20 USDC moves above 10,000. ```graphql { EVM(network: arc_testnet) { Transfers( limit: {count: 20} orderBy: {descending: Transfer_Amount} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Transfer: { Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} Amount: {gt: "10000"} } } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol } } } } } ``` --- ## Most transferred tokens ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-most-transferred-tokens) Tokens ranked by transfer count over 24 hours, with distinct senders and receivers. The system ledger address is excluded. ```graphql { EVM(network: arc_testnet) { Transfers( limit: {count: 20} orderBy: {descendingByField: "count"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Transfer: { Currency: {SmartContract: {not: "0xfffffffffffffffffffffffffffffffffffffffe"}} } } ) { Transfer { Currency { Symbol Name SmartContract Native } } count amount: sum(of: Transfer_Amount) senders: uniq(of: Transfer_Sender) receivers: uniq(of: Transfer_Receiver) } } } ``` --- ## Hourly transfer volume of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-testnet-hourly-transfer-volume) Transfer volume of ERC-20 USDC bucketed by hour, for charts and alerts. ```graphql { EVM(network: arc_testnet) { Transfers( orderBy: {descendingByField: "Block_Time"} limit: {count: 24} where: { Transfer: { Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } } ) { Block { Time(interval: {in: hours, count: 1}) } amount: sum(of: Transfer_Amount) count senders: uniq(of: Transfer_Sender) } } } ``` --- ## FAQ **Why does `AmountInUSD` return 0?** Arc testnet has no token price index, so every USD field is 0. Rank and filter by `Transfer.Amount`, one currency at a time. **Which USDC address should I filter on?** For gas-token value transfers use `Currency: {Native: true}`. For the ERC-20 interface that wallets and contracts call, use `0x3600000000000000000000000000000000000000`. Do not filter on `0xfffffffffffffffffffffffffffffffffffffffe`; it is a system ledger that duplicates native movements as raw integers. **Why are native amounts 18 decimals when USDC has 6?** The EVM represents the gas token in wei-style 18-decimal units regardless of what the token is called. Bitquery applies those 18 decimals to native rows and the contract's own 6 decimals to ERC-20 rows, so `Amount` is a whole-token value in both cases. **Can I read history older than the realtime window?** Not on the testnet. Only `dataset: realtime` exists; `archive` and `combined` return errors. Check the window with `Block { Time(minimum: Block_Time) }`. **How do I stream transfers for one wallet?** Take the [transfers of an address](#transfers-of-an-address) query, change `query` to `subscription` and drop `limit` and `orderBy`. --- ## Arc Transactions, Blocks & Fees API URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/arc-mainnet-transactions-api/ Query and stream Arc transactions, blocks and USDC gas fees with Bitquery GraphQL, including hashes, address history, failures and fee analytics. # Arc Transactions, Blocks & Fees API Query and stream **transactions, receipts and blocks on Arc** with Bitquery GraphQL. The `EVM.Transactions` and `EVM.Blocks` cubes on `network: arc` cover what a block explorer shows for a hash, an address or a block, with fees in **USDC** because USDC is the chain's gas token. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows. :::info Availability checked 16 September 2026 The realtime path returned transactions and blocks. `CostInUSD`, `GasPriceInUSD` and `Fee.SenderFeeInUSD` were populated. Leave the `dataset` argument out until `combined` and `archive` are enabled. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Blockchain API overview](/docs/blockchain/arc-mainnet/) — network facts, every cube and stream in one place - [Arc Calls API](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/) — the call tree inside a transaction - [Arc Transfers API](/docs/blockchain/arc-mainnet/arc-mainnet-transfers-api/) - [EVM Transactions schema](/docs/schema/evm/transactions/) - [EVM Blocks schema](/docs/schema/evm/blocks/) ::: **On this page:** [Stream](#stream-transactions) · [Latest](#latest-transactions) · [By hash](#transaction-by-hash) · [By address](#transactions-of-an-address) · [Failed](#failed-transactions) · [Fees](#gas-fees-in-usdc) · [Latest blocks](#latest-blocks) · [Block by number](#block-by-number) · [Block stats](#block-and-throughput-statistics) · [FAQ](#faq) --- ## Stream transactions ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-stream-transactions) Every transaction as blocks are indexed. Arc produces a block well under every second, so expect a steady feed. ```graphql subscription { EVM(network: arc) { Transactions { Block { Number Time } Transaction { Hash From To Value Gas Type Nonce } Receipt { Status GasUsed ContractAddress } Fee { SenderFee EffectiveGasPrice } } } } ``` --- ## Latest transactions ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-latest-transactions) ```graphql { EVM(network: arc) { Transactions( limit: {count: 20} orderBy: {descending: Block_Time} ) { Block { Number Time } Transaction { Hash From To Value Type } Receipt { Status GasUsed } Fee { SenderFee } } } } ``` --- ## Transaction by hash ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-transaction-by-hash) The equivalent of `eth_getTransactionByHash` plus `eth_getTransactionReceipt` in one call. The example hash is a live USDC value transfer; replace it with any recent hash. ```graphql { EVM(network: arc) { Transactions( where: { Transaction: { Hash: {is: "0x3fb2f3f18ae8ef86dbf6d25f268c861d2982f67308031df45574b5a7fcc02b9f"} } } ) { Block { Number Time Hash } Transaction { Hash From To Value Gas GasPrice GasFeeCap GasTipCap Nonce Type Index } Receipt { Status GasUsed CumulativeGasUsed ContractAddress } Fee { SenderFee EffectiveGasPrice PriorityFeePerGas Burnt } } } } ``` --- ## Transactions of an address ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-transactions-of-an-address) Sent and received transactions of one address, newest first. This is the explorer's address page. ```graphql { EVM(network: arc) { Transactions( limit: {count: 20} orderBy: {descending: Block_Time} where: { any: [ {Transaction: {From: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} {Transaction: {To: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} ] } ) { Block { Number Time } Transaction { Hash From To Value } Receipt { Status } Fee { SenderFee } } } } ``` --- ## Failed transactions ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-failed-transactions) Transactions whose receipt status is 0. Join the [reverted calls](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/#reverted-calls) query on the hash to see the revert reason. ```graphql { EVM(network: arc) { Transactions( limit: {count: 20} orderBy: {descending: Block_Time} where: {TransactionStatus: {Success: false}} ) { Block { Time } Transaction { Hash From To Gas } Receipt { GasUsed } Fee { SenderFee } } } } ``` --- ## Gas fees in USDC ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-gas-fee-statistics) Because gas is paid in USDC, `Fee.SenderFee` is already a dollar amount. This gives the average, median and total fee per hour along with the average effective gas price. ```graphql { EVM(network: arc) { Transactions( orderBy: {descendingByField: "Block_Time"} limit: {count: 24} ) { Block { Time(interval: {in: hours, count: 1}) } count totalFees: sum(of: Fee_SenderFee) avgFee: average(of: Fee_SenderFee) medianFee: median(of: Fee_SenderFee) avgGasPrice: average(of: Fee_EffectiveGasPrice) avgGasUsed: average(of: Receipt_GasUsed) } } } ``` --- ## Latest blocks ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-latest-blocks) ```graphql { EVM(network: arc) { Blocks( limit: {count: 20} orderBy: {descending: Block_Number} ) { Block { Number Time Hash TxCount GasUsed GasLimit BaseFee Coinbase } } } } ``` Change `query` to `subscription` and drop `limit` and `orderBy` to receive each block header as it is indexed. --- ## Block by number ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-block-by-number) ```graphql { EVM(network: arc) { Blocks(where: {Block: {Number: {eq: "21124027"}}}) { Block { Number Time Hash ParentHash TxCount GasUsed GasLimit BaseFee Coinbase Difficulty } } } } ``` --- ## Block and throughput statistics ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-block-statistics) Blocks, transactions, average transactions per block and average gas per block for each of the last 24 hours. Divide the block count by 3600 to get blocks per second. ```graphql { EVM(network: arc) { Blocks( orderBy: {descendingByField: "Block_Time"} limit: {count: 24} ) { Block { Time(interval: {in: hours, count: 1}) } blocks: count transactions: sum(of: Block_TxCount) avgTxPerBlock: average(of: Block_TxCount) avgGasUsed: average(of: Block_GasUsed) medianGasUsed: median(of: Block_GasUsed) } } } ``` --- ## FAQ **What unit is `Fee.SenderFee` in?** Native USDC. Arc pays gas in USDC, so a fee of `0.0025` is a quarter of a cent. The USD fee fields were also populated in the launch-day check. **Which gas-price field should I use?** For EIP-1559 type 2 transactions, use `Fee.EffectiveGasPrice` for the price paid. `Transaction.GasFeeCap` and `Transaction.GasTipCap` show the sender's limits. **How fast are blocks?** Well under a second on average. Measure the current rate with the [block statistics](#block-and-throughput-statistics) query rather than assuming a fixed interval. **Can I get a transaction's internal calls and logs from here?** Use the same hash on the [Calls API](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/#internal-calls-of-a-transaction) for the call tree and the [Events API](/docs/blockchain/arc-mainnet/arc-mainnet-events-api/) for the logs. **Is there a block explorer?** Arc's mainnet explorer is [explorer.arc.io](https://explorer.arc.io). Bitquery is an indexed data API rather than an explorer, and every explorer lookup on this page can be run in bulk or streamed. --- ## Arc Transfers API & Streams URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/arc-mainnet-transfers-api/ Query and stream Arc token transfers with Bitquery GraphQL, including native USDC, ERC-20 USDC, EURC, wallet history, large transfers and daily volume. # Arc Transfers API & Streams Query and stream **token transfers on Arc** with Bitquery GraphQL. This is the shared **EVM `Transfers`** cube scoped to `network: arc`, so a query written for Ethereum or Base runs here by changing the network name. Arc's native gas token is **USDC**, and the chain carries an ERC-20 USDC interface, EURC, USYC and user-issued assets. Every query on this page was executed against the production endpoint before publishing. Change `query` to `subscription` on any of them to stream the same rows over WebSocket. :::info Availability checked 16 September 2026 `Transfer.AmountInUSD` returned populated values. Only the realtime path answered, so leave the `dataset` argument out until `archive` and `combined` are enabled. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Arc Blockchain API overview](/docs/blockchain/arc-mainnet/) — network facts, every cube and stream in one place - [Arc DEX Trades API](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/) - [Arc Balances API](/docs/blockchain/arc-mainnet/arc-mainnet-balances-api/) - [Arc Events API](/docs/blockchain/arc-mainnet/arc-mainnet-events-api/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) - [EVM Transfers schema](/docs/schema/evm/transfers/) ::: **On this page:** [Currencies](#how-usdc-appears-in-transfers) · [Stream](#stream-real-time-transfers) · [Latest](#latest-transfers) · [Native USDC](#native-usdc-transfers) · [By token](#transfers-of-a-token) · [By address](#transfers-of-an-address) · [Between two addresses](#transfers-between-two-addresses) · [Large transfers](#large-transfers) · [Top tokens](#most-transferred-tokens) · [Hourly volume](#hourly-transfer-volume-of-a-token) · [FAQ](#faq) --- ## How USDC appears in Transfers USDC exists in three forms on Arc. Check which one a row is before you sum or rank anything. | Currency | `SmartContract` | `Native` | Decimals | What it is | | --- | --- | --- | --- | --- | | USDC (native) | `0x` | `true` | 18 | The gas token and native value-transfer form. Read transaction fee fields for gas fees. | | USDC (ERC-20) | `0x3600000000000000000000000000000000000000` | `false` | 6 | The ERC-20 interface most contracts and wallets call. Symbol `USDC`, name `USDC`. | | System ledger | `0xfffffffffffffffffffffffffffffffffffffffe` | `false` | 0 | A system address that emits a raw `Transfer` event mirroring native USDC movements as 18-decimal integers with no symbol. Exclude it from token rankings. | Official tokens on Arc: | Token | Address | Decimals | | --- | --- | --- | | EURC | `0xbef5f6d51cb62b58e6a8f77868681825c6fe21c1` | 6 | | USYC | `0x8a5d989bbb96929f689b0200f435f53da42bf490` | 6 | --- ## Stream real-time transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-stream-transfers) Every transfer on the network as it is indexed. Filter inside `where` to narrow the socket to a token, an address or a size floor. ```graphql subscription { EVM(network: arc) { Transfers { Block { Number Time } Transaction { Hash From To } Transfer { Amount Sender Receiver Type Currency { Name Symbol SmartContract Native Decimals } } } } } ``` --- ## Latest transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-latest-transfers) ```graphql { EVM(network: arc) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} ) { Block { Number Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol SmartContract Native } } } } } ``` --- ## Native USDC transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-native-usdc-transfers) `Currency: {Native: true}` selects value transfers of the gas token. The floor of 100 USDC keeps dust and fee movements out. ```graphql { EVM(network: arc) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { Transfer: { Currency: {Native: true} Amount: {gt: "100"} } } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Native } } } } } ``` --- ## Transfers of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-erc20-usdc-transfers) Filter on the token contract. This example reads the ERC-20 USDC interface; swap in EURC or any test token. ```graphql { EVM(network: arc) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { Transfer: { Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Decimals } } } } } ``` --- ## Transfers of an address ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-transfers-of-an-address) Incoming and outgoing transfers in one list. Replace the address with any wallet or contract. ```graphql { EVM(network: arc) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { any: [ {Transfer: {Sender: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} {Transfer: {Receiver: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} ] } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol SmartContract Native } } } } } ``` ### Sent and received totals per token ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-address-sent-received) Two aliased selections give the outbound and inbound sums per currency for a wallet. ```graphql { EVM(network: arc) { sent: Transfers( where: {Transfer: {Sender: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} orderBy: {descendingByField: "amount"} limit: {count: 10} ) { Transfer { Currency { Symbol SmartContract } } amount: sum(of: Transfer_Amount) count } received: Transfers( where: {Transfer: {Receiver: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"}}} orderBy: {descendingByField: "amount"} limit: {count: 10} ) { Transfer { Currency { Symbol SmartContract } } amount: sum(of: Transfer_Amount) count } } } ``` --- ## Transfers between two addresses ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-transfers-between-addresses) Flows from one address to another, in either direction. Useful for tracing a faucet, a bridge or a counterparty. ```graphql { EVM(network: arc) { Transfers( limit: {count: 20} orderBy: {descending: Block_Time} where: { any: [ { Transfer: { Sender: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"} Receiver: {is: "0xb92fe925dc43a0ecde6c8b1a2709c170ec4fff4f"} } } { Transfer: { Sender: {is: "0xb92fe925dc43a0ecde6c8b1a2709c170ec4fff4f"} Receiver: {is: "0xada5bb90d0de0bd1b6f3938708f49295a8d1f7cb"} } } ] } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Native } } } } } ``` --- ## Large transfers ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-large-usdc-transfers) This catches ERC-20 USDC moves above 10,000 and returns both token and USD amounts. ```graphql { EVM(network: arc) { Transfers( limit: {count: 20} orderBy: {descending: Transfer_Amount} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Transfer: { Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} Amount: {gt: "10000"} } } ) { Block { Time } Transaction { Hash } Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol } } } } } ``` --- ## Most transferred tokens ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-most-transferred-tokens) Tokens ranked by transfer count over 24 hours, with distinct senders and receivers. The system ledger address is excluded. ```graphql { EVM(network: arc) { Transfers( limit: {count: 20} orderBy: {descendingByField: "count"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Transfer: { Currency: {SmartContract: {not: "0xfffffffffffffffffffffffffffffffffffffffe"}} } } ) { Transfer { Currency { Symbol Name SmartContract Native } } count amount: sum(of: Transfer_Amount) senders: uniq(of: Transfer_Sender) receivers: uniq(of: Transfer_Receiver) } } } ``` --- ## Hourly transfer volume of a token ▶️ [Run in IDE](https://ide.bitquery.io/arc-mainnet-hourly-transfer-volume) Transfer volume of ERC-20 USDC bucketed by hour, for charts and alerts. ```graphql { EVM(network: arc) { Transfers( orderBy: {descendingByField: "Block_Time"} limit: {count: 24} where: { Transfer: { Currency: {SmartContract: {is: "0x3600000000000000000000000000000000000000"}} } } ) { Block { Time(interval: {in: hours, count: 1}) } amount: sum(of: Transfer_Amount) count senders: uniq(of: Transfer_Sender) } } } ``` --- ## FAQ **Does `AmountInUSD` work?** Yes. It returned populated values in the production check on 16 September 2026. **Which USDC address should I filter on?** For gas-token value transfers use `Currency: {Native: true}`. For the ERC-20 interface that wallets and contracts call, use `0x3600000000000000000000000000000000000000`. Do not filter on `0xfffffffffffffffffffffffffffffffffffffffe`; it is a system ledger that duplicates native movements as raw integers. **Why are native amounts 18 decimals when USDC has 6?** The EVM represents the gas token in wei-style 18-decimal units regardless of what the token is called. Bitquery applies those 18 decimals to native rows and the contract's own 6 decimals to ERC-20 rows, so `Amount` is a whole-token value in both cases. **Should I add native and ERC-20 USDC transfers together?** No. Arc's ERC-20 interface acts on the native USDC balance, so the two views can describe linked activity. Choose the form that matches the action you track and guard against double counting. **Can I read history older than the realtime window?** Not yet. Only the realtime path answered on 16 September 2026. Check the window with `Block { Time(minimum: Block_Time) }` and retry `archive` or `combined` before using them. **How do I stream transfers for one wallet?** Take the [transfers of an address](#transfers-of-an-address) query, change `query` to `subscription` and drop `limit` and `orderBy`. --- ## Argmax Selectors: maximum and minimum URL: https://docs.bitquery.io/docs/trading/query-operators/argmax-selectors/ Field(maximum: Key) returns a field's value on the row where Key is maximal — the argmax primitive behind first-value, last-value and peak queries on the Bitquery Trading cube. # Argmax Selectors: `maximum:` and `minimum:` `Field(maximum: Key)` returns **the value of `Field` on the row where `Key` is maximal**. It compiles to ClickHouse `argMax(Field, Key)`; `minimum:` is `argMin`. This is the primitive behind almost every "first", "last" and "at the peak" question: ```graphql Price { Ohlc { Open(minimum: Interval_Time_Start) # first value in the window Close(maximum: Interval_Time_Start) # last value in the window } } ``` :::caution It returns the field, not the key `Number(maximum: Block_GasUsed)` returns the block **number** of the highest-gas block — not the gas figure. Reading it as "the maximum of the argument" is the single most common mistake. ::: ## Where it works Every **non-aggregate leaf path** in a Trading cube accepts both `maximum:` and `minimum:`. Only the 23 aggregate functions (`sum`, `count`, `uniq`, `median`, `calculate`, `correlation`, `gini`, …) do not. That gives a large surface on every cube — on the order of 30 to 60 paths each, across `Trading.Trades`, `Trading.Pairs`, `Trading.Tokens` and `Trading.Currencies`. **You can argmax *into* a string, but never *by* one.** The key must be a comparable column, so `side`-style string columns are rejected at GraphQL validation rather than failing at runtime. `Block_Date` and `Block_Timestamp` are string-typed but comparable, so they *are* valid keys. ```graphql # valid — the value is a string, the key is numeric TransactionHeader { Hash(maximum: Amounts_Base) } ``` `calculate` cannot substitute here: its column is typed `Float64`, so `calculate(expression: "argMax(TransactionHeader_Hash, Amounts_Base)")` fails. Use the field-level selector. ## Row coherence — the rule that makes this useful **All selectors sharing one key resolve to the same underlying row.** So this returns a genuine, internally consistent snapshot of the largest trade: ```graphql Trader { Address(maximum: AmountsInUsd_Quote) } Pair { Pool { Address(maximum: AmountsInUsd_Quote) } } TransactionHeader { Hash(maximum: AmountsInUsd_Quote) } ``` :::danger Mixing keys silently fabricates a row Selectors keyed on **different** columns come from **different rows**. Combining them produces a composite that never existed on chain — no error, no warning: ```graphql # these two are from different rows Open(minimum: Block_Time) Trader { Address(maximum: AmountsInUsd_Quote) } ``` That is fine when you intend it (an OHLC bar is built exactly this way). It is a bug when you meant "one row". ::: ## Ties are resolved non-deterministically When several rows tie on the key, the winner varies between identical runs — even over a frozen window. The choice is made **once per response**, so fields sharing that key stay coherent with each other; it is *which* tied row you get that moves. `Block_Time` is second-resolution and ties readily on busy pools. Break ties with a second, finer key — `Block_Timestamp` is nanosecond-resolution — or accept that any tied row is representative. ## Making it per-group Argmax becomes per-group when you **select a dimension**, which introduces the GROUP BY: ```graphql Token { Id } # <- this makes it per-token peak: Price { Ohlc { High(maximum: Price_Ohlc_High) } } ``` `limitBy` is orthogonal — it caps how many result rows survive per key and composes fine with argmax, but it is **not** what makes the argmax per-group. Select `limitBy` with no dimension and you get one global argmax. ## Combining with other arguments - **`if:`** turns the selector into `argMaxIf`, and takes the full cube filter type — any `where`-shape the cube accepts. - **`selectWhere:`** applies HAVING semantics to the argmax result: groups whose result fails the predicate are dropped **before** ordering and limiting, so lower-ranked groups get pulled into the limit window. The predicate is `Metric_filter_Float` for numeric paths and `Metric_filter_String` for string paths. ## Two footguns :::warning `maximum:` and `minimum:` on one field — only the first applies Supplying both on a single field occurrence is **silently accepted**, and only the first-listed argument takes effect. The other is dropped with no error. To get both ends of a range, use two aliased selections: ```graphql first: Price { Ohlc { Open(minimum: Block_Time) } } last: Price { Ohlc { Close(maximum: Block_Time) } } ``` ::: :::warning An empty set returns type-zeros, not an empty result If an `if:` filter matches nothing, the cube still emits a row and the selector returns a type-zero — `0`, or `""`. That is **indistinguishable from a genuine zero**. Pair the selector with `count(if: )` to tell the two apart. ::: ## Related - [Calculations and Expressions](/docs/graphql/calculations/) - [Conditions with `if`](/docs/graphql/metrics/if/) - [Screeners with `selectWhere`](/docs/trading/query-operators/selectwhere-screeners/) - [OHLC candles](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/) --- ## Argus Launchpad API on Arc: Launches, Dev Buys and Trades URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/argus-launchpad-api/ Track Argus token launches on Circle Arc with Bitquery. Decoded TokenCreated, FeeConfigured and DevBuy events, launch calls, Trading cube swaps, USD prices and OHLCV. # Argus Launchpad API on Arc: Launches, Dev Buys and Trades [Argus](https://argus.world/docs) is a token launchpad on Arc, Circle's EVM chain. Launches go through a portal contract that deploys the token, opens a Uniswap v4 curve and sets the fee split in one transaction. Bitquery decodes the portal's launch events and its `launch` call, so you get token name, symbol, creator, taxes and social links as named arguments. Use `EVM.Events` and `EVM.Calls` to find launches. All trading examples below use `Trading.Trades`, `Trading.Pairs`, or `Trading.Tokens`. Argus carries most of the launch activity on Arc. In a sample hour on 17 September 2026 it emitted 2,983 launch events against 10 from Tolly and 2 from Archemist, and 94,843 of the 94,968 launches recorded against its `TokenCreated` signature came from the portal contract below. :::note API access Run the saved examples in the Bitquery IDE, or create an [API access token](/docs/authorization/how-to-generate/) for `https://streaming.bitquery.io/graphql`. For streams, use `wss://streaming.bitquery.io/graphql` with [WebSocket authorization](/docs/authorization/websocket/). ::: ## Find the latest Argus token launches Filter by the portal address and the `TokenCreated` event. `Arguments` returns the token, creator, name, symbol, pool id, image URI, website, Twitter and Telegram. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-latest-launches) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { TransactionStatus: {Success: true} LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}, Removed: false} Log: {Signature: {Name: {is: "TokenCreated"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {Name Signature}} Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg {address} ... on EVM_ABI_String_Value_Arg {string} ... on EVM_ABI_BigInt_Value_Arg {bigInteger} ... on EVM_ABI_Integer_Value_Arg {integer} ... on EVM_ABI_Bytes_Value_Arg {hex} } } } } } ``` ## Contracts and decoded events | Contract | Arc address | | --- | --- | | Argus launch portal | `0xb021be536808f551b31789422fd28a6c9c6e97da` | | Event | Signature | Key arguments | | --- | --- | --- | | `TokenCreated` | `TokenCreated(address,address,string,string,bytes32,string,string,string,string)` | `token`, `creator`, `name`, `symbol`, `poolId`, `imageURI`, `website`, `twitter`, `telegram` | | `CurveOpened` | `CurveOpened(address,bytes32,address,uint256,uint128,int24,int24)` | `token`, `poolId`, `locker`, `positionId`, `liquidity`, `tickLower`, `tickUpper` | | `FeeConfigured` | `FeeConfigured(address,address,uint16,uint16,uint16,uint16,uint16,uint16,uint16,uint16)` | `token`, `hook`, `lpFeeBps`, `buyTaxBps`, `sellTaxBps`, `treasuryBps`, `creatorBps`, `burnBps`, `dividendBps`, `liquidityBps` | | `PartsDeployed` | `PartsDeployed(address,address,address,address)` | `token`, `locker`, `hook`, `splitter` | | `DevBuy` | `DevBuy(address,address,uint256,uint256)` | `token`, `creator`, `quoteIn`, `tokensOut` | Each event's signature hash is its `Topics[0]`. Filter on these when you need rows the decoder has not named: | Event | Signature hash | | --- | --- | | `TokenCreated` | `1d8917231579f8ce39407f0d616f36f357b07329b0ce5164d0754ac15145ce0a` | | `PartsDeployed` | `a54419a494ae20a1807712ab7a33ff0928b9a0e6e03e4562885aedb8e8fcd4da` | | `CurveOpened` | `55e45784ac0f1201c142dd0d2119dd11980e98f34cb682c49340d5c28c3a9aa0` | | `FeeConfigured` | `abe14607f311bb63e5b35c469f88100e8fb2ff250876e2364a402e2f2679e8aa` | | `DevBuy` | `84d429ed8af1c9cfe8bb07b556e4120e976c9f4c9232a7f50a15d31d83e232a9` | The first four fire together on every launch. `DevBuy` fires only when the creator buys in the launch transaction, which was 10% of launches on 17 September 2026. The `locker`, `hook` and `splitter` in `PartsDeployed` are deployed **per token**, so they differ on every launch. Read them from the event rather than caching them as protocol constants. Contract and events were checked against Arc data on 17 September 2026. See the [Argus docs](https://argus.world/docs) and the [Arc launchpad contract list](/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/#verified-launchpad-contracts). :::caution Decoding start Decoded names and arguments are available from 17 September 2026, 12:48 UTC. Earlier rows have an empty `Signature.Name`, so the queries on this page do not return them. At the time of writing that is 450,457 undecoded rows against 48,249 decoded. To reach the earlier launches, filter on `Topics` instead — see [Launches from before the decoding cutover](#launches-from-before-the-decoding-cutover). ::: To query Trading, take the `token` argument, lowercase it and prefix it with `bid:arc:`. For example, PERP's token ID is `bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e`. These examples use two tokens whose `TokenCreated` events came from the Argus portal: | Sample token | Contract | | --- | --- | | PERP | `0x4389b473460474d68533bde2f873b5a2819f308e` | | GROKBOOK | `0xf25bed776bc17192fbc0630913888d8d1b9bbc1c` | They are user-created examples. Symbols are not unique on a launchpad, so always identify a token by its address. Replace the addresses with a token returned by the launch query. :::tip Build a launchpad token list The Trading cubes do not attach an Argus label to each token. Build that list from launch events, then pass the token IDs into Trading queries. Argus pools are Uniswap v4: `Pair.Market.Address` can be empty and several pools share `Pair.Pool.Address`, so include `Pair.Pool.Id` to select one pool. It matches the `poolId` argument of `TokenCreated`. ::: ## Stream new Argus launches Subscribe with the same portal and event filters. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-launch-stream) ```graphql subscription { EVM(network: arc) { Events( where: { TransactionStatus: {Success: true} LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}, Removed: false} Log: {Signature: {Name: {is: "TokenCreated"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {Name Signature}} Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg {address} ... on EVM_ABI_String_Value_Arg {string} ... on EVM_ABI_BigInt_Value_Arg {bigInteger} ... on EVM_ABI_Integer_Value_Arg {integer} ... on EVM_ABI_Bytes_Value_Arg {hex} } } } } } ``` Append new token IDs to your application's list. A Trading subscription has fixed filters: resubscribe with the updated list when a new launch arrives. Keep a time checkpoint and query recent events after reconnecting. Deduplicate launch records by transaction hash and log index. ## Argus launches by creator wallet Filter on the decoded `creator` argument to list every token one wallet launched. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-launches-by-creator) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { TransactionStatus: {Success: true} LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}, Removed: false} Log: {Signature: {Name: {is: "TokenCreated"}}} Arguments: {includes: {Name: {is: "creator"}, Value: {Address: {is: "0x01af73b21b0efcd0716577c27fd6a267448db999"}}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {Name Signature}} Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg {address} ... on EVM_ABI_String_Value_Arg {string} ... on EVM_ABI_BigInt_Value_Arg {bigInteger} ... on EVM_ABI_Integer_Value_Arg {integer} ... on EVM_ABI_Bytes_Value_Arg {hex} } } } } } ``` ## Launch fees, curve and deployed contracts Filter on the decoded `token` argument to get the three setup events for one launch. `FeeConfigured` carries buy and sell tax and the fee split in basis points. `CurveOpened` has the v4 position and tick range. `PartsDeployed` lists the hook, locker and splitter contracts. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-launch-config) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { TransactionStatus: {Success: true} LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}, Removed: false} Log: {Signature: {Name: {in: ["FeeConfigured", "CurveOpened", "PartsDeployed"]}}} Arguments: {includes: {Name: {is: "token"}, Value: {Address: {is: "0x4389b473460474d68533bde2f873b5a2819f308e"}}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {Name Signature}} Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg {address} ... on EVM_ABI_String_Value_Arg {string} ... on EVM_ABI_BigInt_Value_Arg {bigInteger} ... on EVM_ABI_Integer_Value_Arg {integer} ... on EVM_ABI_Bytes_Value_Arg {hex} } } } } } ``` ## Creator dev buys `DevBuy` records the creator's first buy in the launch transaction. `quoteIn` is the quote asset amount in its smallest unit (USDC uses 6 decimals) and `tokensOut` is the token amount in 18-decimal units. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-dev-buys) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { TransactionStatus: {Success: true} LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}, Removed: false} Log: {Signature: {Name: {is: "DevBuy"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {Name Signature}} Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg {address} ... on EVM_ABI_String_Value_Arg {string} ... on EVM_ABI_BigInt_Value_Arg {bigInteger} ... on EVM_ABI_Integer_Value_Arg {integer} ... on EVM_ABI_Bytes_Value_Arg {hex} } } } } } ``` ### Stream dev buys [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-dev-buy-stream) ```graphql subscription { EVM(network: arc) { Events( where: { TransactionStatus: {Success: true} LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}, Removed: false} Log: {Signature: {Name: {is: "DevBuy"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {Name Signature}} Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg {address} ... on EVM_ABI_String_Value_Arg {string} ... on EVM_ABI_BigInt_Value_Arg {bigInteger} ... on EVM_ABI_Integer_Value_Arg {integer} ... on EVM_ABI_Bytes_Value_Arg {hex} } } } } } ``` ## Argus launch calls The `launch` call carries inputs that the events do not: total supply, curve targets, the quote asset and the metadata URI. Struct members arrive as repeated rows in declaration order; `Path.Name` tells you whether a row belongs to the launch parameters (`p`) or the token metadata (`meta`). [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-launch-calls) ```graphql query { EVM(network: arc) { Calls( limit: {count: 10} orderBy: {descending: Block_Time} where: { TransactionStatus: {Success: true} Call: { To: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"} Signature: {Name: {is: "launch"}} Success: true } } ) { Block {Number Time} Transaction {Hash From} Call {From To Signature {Name Signature}} Arguments { Name Type Path {Name} Value { ... on EVM_ABI_Address_Value_Arg {address} ... on EVM_ABI_String_Value_Arg {string} ... on EVM_ABI_BigInt_Value_Arg {bigInteger} ... on EVM_ABI_Integer_Value_Arg {integer} ... on EVM_ABI_Bytes_Value_Arg {hex} } } } } } ``` ## Launches from before the decoding cutover `Topics` is populated whether or not the decoder has named an event, so it reaches the whole history. `Topics[0]` is the signature hash from the [table above](#contracts-and-decoded-events); the indexed `token` and `creator` follow, each left-padded to 32 bytes. This returns every Argus event for one token, including rows that predate the cutover and so carry an empty `Signature.Name` and no `Arguments`. [Run in Bitquery IDE](https://ide.bitquery.io/arc-argus-launches-by-topic) ```graphql { EVM(network: arc) { Events( limit: {count: 10} where: { LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}} Topics: {includes: [{Hash: {is: "0x00000000000000000000000041358defd0dedc90528b3f1835715e907b686e6a"}}]} } ) { Block { Time } Transaction { Hash From } Log { Signature { Name SignatureHash } } Topics { Hash } } } } ``` Take the final 40 hex characters of a padded topic and prefix `0x` to recover an address. Swap the padded token for a signature hash to pull one event type across every token instead. On undecoded rows, match `SignatureHash` against the table above and decode the unindexed fields from the log data in your own client using the full signatures. ## Launch rate per hour Bucket launches by hour and count distinct creators beside them, which separates a real crowd from one wallet minting in a loop. [Run in Bitquery IDE](https://ide.bitquery.io/arc-argus-launch-rate) ```graphql { EVM(network: arc) { Events( orderBy: {descendingByField: "launches"} where: { LogHeader: {Address: {is: "0xb021be536808f551b31789422fd28a6c9c6e97da"}} Log: {Signature: {SignatureHash: {is: "1d8917231579f8ce39407f0d616f36f357b07329b0ce5164d0754ac15145ce0a"}}} Block: {Time: {since_relative: {hours_ago: 6}}} } ) { Block { Time(interval: {in: hours, count: 1}) } launches: count uniqueCreators: count(distinct: Transaction_From) } } } ``` On 17 September 2026 this returned roughly 1,500 to 3,000 launches per hour from 450 to 740 distinct creators. Filtering on `SignatureHash` rather than the event name keeps the count correct across the decoding cutover. ## Recent trades for an Argus token Match the token on either side of the pair. This includes trades where it is the quote asset. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-recent-trades) ```graphql query { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}}}} ] } ) { Block {Time} TransactionHeader {Hash Index} Trader {Address} Side Amounts {Base Quote} AmountsInUsd {Quote} PriceInUsd Pair { Token {Id Symbol} QuoteToken {Id Symbol} Market {Network Protocol} Pool {Address Id} } } } } ``` `Side` is relative to `Pair.Token`. If the selected token is `Pair.QuoteToken`, reverse Buy/Sell when describing that token's direction. `PriceInUsd` also refers to `Pair.Token` and is an indexed reference price; use the amount ratio when you need the executed price. Use `AmountsInUsd.Quote` for quoted USD turnover. Do not add base and quote USD amounts from the same row. One transaction can contain several swaps; use a distinct transaction hash count for transaction totals. ## Stream trades for an Argus token The same token filters work as a Trading subscription. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-trade-stream) ```graphql subscription { Trading { Trades( where: { Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}}}} ] } ) { Block {Time} TransactionHeader {Hash Index} Trader {Address} Side Amounts {Base Quote} AmountsInUsd {Quote} PriceInUsd Pair { Token {Id Symbol} QuoteToken {Id Symbol} Market {Network Protocol} Pool {Address Id} } } } } ``` For several tokens, replace each `is` token filter with an `in` list. Keep both the base-token and quote-token branches. ## Rank an Argus token watchlist by volume This sample ranks PERP and GROKBOOK over the last 24 hours. It includes only rows where a listed token is `Pair.Token`, so the Buy/Sell counts have a consistent meaning. Extend the list from launch events to cover more tokens. It is not a total for the whole launchpad. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-watchlist-volume) ```graphql query { Trading { Trades( limit: {count: 20} orderBy: {descendingByField: "volumeUsd"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: { Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}} Token: {Id: {in: [ "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e" "bid:arc:0xf25bed776bc17192fbc0630913888d8d1b9bbc1c" ]}} } } ) { Pair {Token {Id Symbol}} trades: count transactions: count(distinct: TransactionHeader_Hash) traders: count(distinct: Trader_Address) volumeUsd: sum(of: AmountsInUsd_Quote) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) } } } ``` :::caution Counts and volume These server aggregates count the indexed rows. The [Trading Trades field notes](/docs/trading/crypto-trades-api/trades-api/#before-you-aggregate-three-things-about-a-trades-row) describe duplicate rows that can affect exact totals. For audited figures, fetch the underlying rows and check duplicates before summing. Wallet counts refer to addresses, not people. ::: ## Most active traders for an Argus token Rank wallets by quoted USD turnover across both pair orientations. This measures activity, not profit. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-top-traders) ```graphql query { Trading { Trades( limit: {count: 10} orderBy: {descendingByField: "volumeUsd"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}}}} ] } ) { Trader {Address} trades: count transactions: count(distinct: TransactionHeader_Hash) volumeUsd: sum(of: AmountsInUsd_Quote) } } } ``` ## Latest price from the top market Use `Trading.Pairs` with rank 1 to retrieve the token's most recent one-minute price interval from its top market. Inspect `Interval.Time.End`: a quiet token can return an old interval, or no row at all. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-top-market-price) ```graphql query { Trading { Pairs( limit: {count: 1} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}} Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}} Block: {Time: {since_relative: {hours_ago: 24}}} Interval: {Time: {Duration: {eq: 60}}} Ranking: {Position: {eq: 1}} Price: {IsQuotedInUsd: true} } ) { Token {Id Symbol} QuoteToken {Id Symbol} Pool {Address Id} Market {Network Protocol} Interval {Time {Start End Duration}} Price {IsQuotedInUsd Ohlc {Close}} Ranking {Position Weight} Volume {Usd} } } } ``` ## One-minute OHLCV candles `Trading.Tokens` combines indexed pools for the token. This query returns up to 120 one-minute intervals within the last 24 hours, newest first. Plot from oldest to newest. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-argus-ohlcv-candles) ```graphql query { Trading { Tokens( limit: {count: 120} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:arc:0x4389b473460474d68533bde2f873b5a2819f308e"}, NetworkBid: {is: "bid:arc"}} Block: {Time: {since_relative: {hours_ago: 24}}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } ) { Token {Id Symbol} Interval {Time {Start End Duration}} Price {IsQuotedInUsd Ohlc {Open High Low Close}} Volume {Base Usd} } } } ``` `Volume.Usd` is USD volume and `Volume.Base` is token units. Empty intervals may be absent; treat a missing interval as missing data unless your chart has an explicit fill rule. The current interval may still change. The same `Token.Id` and `Interval.Time.Start` can appear more than once; see the [Tokens field notes](/docs/trading/crypto-price-api/tokens/#field-notes). To stream candles, change `query` to `subscription`, remove `limit`, `orderBy`, and the historical `Block.Time` filter, and keep the token and interval filters. ## Related APIs - [Tolly Launchpad API](/docs/blockchain/arc-mainnet/tolly-launchpad-api/) - [RadarDEX Launchpad API](/docs/blockchain/arc-mainnet/radardex-launchpad-api/) - [Minara Launchpad API](/docs/blockchain/arc-mainnet/minara-launchpad-api/) - [Arc Launchpads API](/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/) - [Arc Blockchain API](/docs/blockchain/arc-mainnet/) - [Trading Trades API](/docs/trading/crypto-trades-api/trades-api/) - [Trading Tokens OHLCV API](/docs/trading/crypto-price-api/tokens/) --- ## Array Intersection URL: https://docs.bitquery.io/docs/graphql/capabilities/array-intersect/ Array Intersection in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. See examples in the Bitquery IDE. # Array Intersection The `array_intersect` feature is an advanced query format that generates an intersection of addresses from specified datasets. You can use the `where` clause to introduce filters that refine your results according to desired criteria. The output is a list of addresses that share a common link to the two datasets. ![Array intersect operation diagram](/img/diagrams/array_intersect.png) In the following section, we'll explore how to use `array_intersect` to reveal the associations between pairs of addresses or contracts. ### Syntax ``` array_intersect(side1: side1, side2: side2, intersectWith: array) ``` where - `side1`: The first array that you want to compare. - `side2`: The second array that you want to compare. - `intersectWith`: The array containing elements to be used for intersection with the first two arrays. Constraints: - Applicable only to fields with a string data type. - Any string-typed field works, not only addresses — DEX market names and protocol families intersect just as well, and `intersectWith` likewise accepts non-address strings. - Other response fields **are** supported in the output. Metrics (`count`, `uniq`, `sum`, `median`) and dimensions (for example `Pair { Market { Name } }` or `Block { Date }`) can be selected alongside the intersection and come back populated — which is what makes per-group intersections useful. :::caution `where` must admit every member of `intersectWith` The intersection is computed over rows the `where` clause already admits. If the filter excludes any member of `intersectWith`, that member contributes nothing and the result silently shrinks rather than erroring. Make sure the `where` clause spans every element you are intersecting on. ::: ### Example Suppose you have an array of two addresses ( A and B ) and want to identify which addresses have engaged in transactions with both Contract A and Contract B. By passing these arrays to array_intersect, the function will return an array of addresses that interacted with both contracts. ```graphql query($addresses: [String!]) { EVM(dataset: archive){ Transfers( where: { any: [ { Transfer: {Sender: {in: $addresses} Receiver: {notIn: $addresses}} }, { Transfer: {Receiver: {in: $addresses} Sender: {notIn: $addresses}} }, ] } ) { array_intersect( side1: Transfer_Sender side2: Transfer_Receiver intersectWith: $addresses ) } } } { "addresses": ["0x21743a2efb926033f8c6e0c3554b13a0c669f63f","0x107f308d85d5481f5b729cfb1710532500e40217"] } ``` This query will return a response in this format ; as an array consisting of elements found in both side1 and side2 that have interacted with **all the addresses** in the intersectWith array. If no common elements are detected, the result will be an empty array. ```json { "EVM": { "Transfers": [ { "array_intersect": [ "0xba5a64df95acba7c0f43e830f5622cbd389cfc4d", "0x74374f95e4630df9b7f70b2d45e64da6437885c7", "0x3f1f6f2537d095b6f5650b371c11dcc8bc90b0f3"] } ] } } ``` --- ## AsterDEX API: Deposits, Withdrawals and 1001x Trade History URL: https://docs.bitquery.io/docs/examples/futures-dexs/asterdex-api/ AsterDEX on-chain data: deposits and withdrawals through the Aster Deposit Bridge on BNB Chain, Ethereum and Arbitrum, plus Simple Mode (1001x) trade history. # AsterDEX API: Deposits, Withdrawals and Simple Mode Trade History AsterDEX records two kinds of activity on chains that Bitquery indexes. Deposits and withdrawals on BNB Chain, Ethereum and Arbitrum pass through the Aster Deposit Bridge, and Bitquery returns each one as a token transfer and as a decoded `Deposit` or `Withdraw` event. Order-book trading runs on Aster Chain, Aster's own Layer 1, and Bitquery does not index Aster Chain. Orders, fills, positions, funding and liquidations from the order book are therefore not available through Bitquery. The Simple Mode (1001x) contract on BNB Chain recorded every trade on-chain until it stopped opening new trades in May 2026, and its history stays available in the `archive` dataset. :::info Perp DEX data on other venues For venues whose orders, fills, positions, funding and liquidations are on-chain, see the [Perp DEX API](/docs/perpetuals/) section. It covers Hyperliquid and Solana perpetuals. ::: ## What AsterDEX puts on-chain | Activity | Where Aster records it | In Bitquery | | --- | --- | --- | | Deposits | Aster Deposit Bridge on BNB Chain, Ethereum, Arbitrum, Solana and Sui | Yes for BNB Chain, Ethereum and Arbitrum, in `Transfers` and `Events` | | Withdrawals | The same bridge contracts, sent by Aster's own wallets | Yes, in `Transfers` and `Events` | | Order-book orders, fills, positions, funding and liquidations | Aster Chain | No | | Simple Mode (1001x) opens, closes, fees, take-profit, stop-loss and liquidations | Simple Mode contract on BNB Chain | Yes, as history in the `archive` dataset | | ALP pool mints, burns and staking | Simple Mode contract on BNB Chain | Yes | Aster's documentation says that traders who turn on Account Privacy send their orders through stealth addresses, so those trades do not link back to the wallet that deposited. A deposit on BNB Chain shows the wallet and the amount. It does not show what that money traded afterwards. ## AsterDEX contract addresses | Contract | Chain | Address | `network` value | | --- | --- | --- | --- | | Aster Deposit Bridge | BNB Chain | `0x128463A60784c4D3f46c23Af3f65Ed859Ba87974` | `bsc` | | Aster Deposit Bridge | Ethereum | `0x604DD02d620633Ae427888d41bfd15e38483736E` | `eth` | | Aster Deposit Bridge | Arbitrum | `0x9E36CB86a159d479cEd94Fa05036f235Ac40E1d5` | `arbitrum` | | Simple Mode (1001x) contract | BNB Chain | `0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0` | `bsc` | Aster lists the bridge addresses, including Solana and Sui, on its [smart contracts page](https://docs.asterdex.com/overview/smart-contracts). The Ethereum and Arbitrum bridges emit the same `Deposit` and `Withdraw` events as the BNB Chain bridge, and Bitquery decodes them with the same names. Every bridge query below works on Ethereum or Arbitrum once you change `network` and the address. ## Deposit Bridge events The bridge's verified source code defines `Deposit`, `Withdraw`, `ReceiveETH`, `DepositFailed`, `WithdrawCanceled` and `WithdrawFee`, plus admin events such as `AddToken` and `RemoveToken`. Most deposits are sent by the trader's own wallet. The `depositFor` function lets another address deposit on a trader's behalf, and the event then names the trader as `payer` while the transaction comes from the other address. Withdrawals are sent by a small set of Aster wallets, which pay out to the wallet the trader named. Bitquery decodes `Deposit` and `Withdraw` with argument names borrowed from another contract that has the same event signature. The values are right and the names are wrong. Read each argument by its position: | Event | Name in Bitquery | Name in Aster's source | What it holds | | --- | --- | --- | --- | | `Deposit` | `payer` | `account` | Wallet credited with the deposit | | `Deposit` | `receiver` | `currency` | Token contract that was deposited | | `Deposit` | `isBaseToken` | `isNative` | `true` for a deposit in the chain's native coin | | `Deposit` | `amount` | `amount` | Raw amount, before token decimals | | `Deposit` | `lpTokenAmount` | `broker` | Broker (referral) ID | | `Withdraw` | `curTime` | `id` | Aster's withdrawal ID | | `Withdraw` | `token` | `to` | Wallet that receives the funds | | `Withdraw` | `user` | `currency` | Token contract that was withdrawn | | `Withdraw` | `amount` | `amount` | Raw amount, before the fee | | `Withdraw` | `balance` | `fee` | Fee Aster keeps, in the same token | The receiving wallet gets `amount` minus `fee`. When `isBaseToken` is `true`, the deposit is native BNB on BNB Chain or ETH on Ethereum and Arbitrum. Use the `Transfers` queries below to get symbols, decimal amounts and USD values without decoding raw integers. ## Latest AsterDEX deposits and withdrawals This query returns the 10 newest deposits and the 10 newest withdrawals on the BNB Chain bridge from the last hour. A deposit is a transfer whose receiver is the bridge, and a withdrawal is a transfer whose sender is the bridge. `Amount` is already adjusted for decimals, and native BNB shows `SmartContract` as `0x`. ```graphql query AsterVaultLatestFlows { EVM(network: bsc, dataset: realtime) { deposits: Transfers( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Transfer: { Receiver: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } } orderBy: { descending: Block_Time } limit: { count: 10 } ) { Block { Time } Transaction { Hash } Transfer { Sender Amount AmountInUSD Currency { Symbol SmartContract } } } withdrawals: Transfers( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Transfer: { Sender: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } } orderBy: { descending: Block_Time } limit: { count: 10 } ) { Block { Time } Transaction { Hash } Transfer { Receiver Amount AmountInUSD Currency { Symbol SmartContract } } } } } ``` ## AsterDEX net flows by token This query totals deposits and withdrawals per token over the last 24 hours, with the number of distinct depositing and receiving wallets. Compare `usd_in` with `usd_out` for each token to see net flow. ```graphql query AsterVaultNetFlowsByToken { EVM(network: bsc, dataset: realtime) { deposits: Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Receiver: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } } orderBy: { descendingByField: "usd_in" } limit: { count: 10 } ) { Transfer { Currency { Symbol SmartContract } } deposits: count depositors: uniq(of: Transfer_Sender) amount_in: sum(of: Transfer_Amount) usd_in: sum(of: Transfer_AmountInUSD) } withdrawals: Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Sender: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } } orderBy: { descendingByField: "usd_out" } limit: { count: 10 } ) { Transfer { Currency { Symbol SmartContract } } withdrawals: count recipients: uniq(of: Transfer_Receiver) amount_out: sum(of: Transfer_Amount) usd_out: sum(of: Transfer_AmountInUSD) } } } ``` Some transfers are Aster moving its own funds rather than a trader deposit or withdrawal. For example, the bridge sends USDT to the USDF Minting contract `0xC271fc70dD9E678ac1AB632f797894fe4BE2C345`. Exclude the contracts on Aster's [smart contracts page](https://docs.asterdex.com/overview/smart-contracts) when you need trader flows only. ## Deposit and Withdraw events with broker IDs and fees The `Transfers` cube gives amounts and symbols. The decoded events add what transfers lack: the broker ID on each deposit, and the withdrawal ID and fee on each withdrawal. Read the arguments with the table in [Deposit Bridge events](#deposit-bridge-events). ```graphql query AsterVaultEvents { EVM(network: bsc, dataset: realtime) { Events( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } LogHeader: { Address: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } Log: { Signature: { Name: { in: ["Deposit", "Withdraw"] } } } } orderBy: { descending: Block_Time } limit: { count: 20 } ) { Block { Time } Transaction { Hash From } Log { Signature { Name } } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` If you filter on one of these names, such as `payer`, test the query again after Bitquery schema updates. A fix to the decoding would rename the argument, and the filter would stop matching. ## One wallet's AsterDEX deposits and withdrawals Pass a wallet in `$wallet` to list its transfers into and out of the bridge over the last 24 hours. For a longer window, switch to `dataset: combined` and filter `Block: { Date: { since: "YYYY-MM-DD" } }`. A transfer shows the address that moved the tokens. When another contract deposits for the wallet through `depositFor`, the transfer comes from that contract, and the wallet appears only as `payer` in the `Deposit` event. ```graphql query AsterWalletFlows($wallet: String = "0x909c245327e82f37a4a68edb7c5bb2910f18bdc8") { EVM(network: bsc, dataset: realtime) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } any: [ { Transfer: { Sender: { is: $wallet } Receiver: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } } { Transfer: { Sender: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } Receiver: { is: $wallet } } } ] } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Block { Time } Transaction { Hash } Transfer { Sender Receiver Amount AmountInUSD Currency { Symbol SmartContract } } } } } ``` ## Stream AsterDEX deposits and withdrawals This subscription pushes every transfer into or out of the BNB Chain bridge as soon as Bitquery indexes the block. Run it over WebSocket at `wss://streaming.bitquery.io/graphql`. ```graphql subscription AsterVaultLiveFlows { EVM(network: bsc) { Transfers( where: { any: [ { Transfer: { Receiver: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } } { Transfer: { Sender: { is: "0x128463a60784c4d3f46c23af3f65ed859ba87974" } } } ] } ) { Block { Time } Transaction { Hash } Transfer { Sender Receiver Amount AmountInUSD Currency { Symbol SmartContract } } } } } ``` ## Simple Mode (1001x) trade history on BNB Chain Simple Mode ran every trade through the contract `0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0`, and each step emitted a decoded event. The contract stopped opening new trades in May 2026, and the last closes ran in August 2026. It still emits ALP pool exits (`BurnAlp`, `BurnRemoveLiquidity`, `BurnFee`) and `UnStake`. Query Simple Mode history with `dataset: archive` and a date range that ends before June 2026. The `realtime` dataset returns no trades for this contract. ### How a Simple Mode trade appears on-chain | Step | Events | Sent by | | --- | --- | --- | | Order placed | `MarketPendingTrade` for a market order, `OpenLimitOrder` for a limit order | The trader's wallet | | Order filled | `OpenMarketTrade`, plus `ExecuteLimitOrderSuccessful` when a limit order fills | An Aster keeper wallet | | Stop-loss or take-profit changed | `UpdateTradeSl`, `UpdateTradeTp`, `UpdateOrderSl`, `UpdateOrderTp` | The trader's wallet | | Margin changed | `UpdateMargin` | The trader's wallet | | Closed by the trader | `CloseTradeSuccessful`, `CloseTradeReceived` | An Aster keeper wallet | | Closed by take-profit, stop-loss or liquidation | `ExecuteCloseSuccessful` | An Aster keeper wallet | | Fees and funding | `OpenFee`, `CloseFee`, `FundingFeeAddLiquidity`, `UpdatePairAccFundingFeePerShare` | Emitted with the trade | | Pair totals | `UpdatePairPositionInfo` | Emitted with the trade | Keeper wallets send most of the transactions, so `Transaction.From` is often an Aster wallet and not the trader. The trader is the `user` argument of each event. `ExecuteCloseSuccessful` carries an `executionType` argument: `0` is take-profit, `1` is stop-loss and `2` is liquidation. A close the trader asks for emits `CloseTradeSuccessful` instead. Both close events carry a `CloseInfo` tuple, which Bitquery returns as five `CloseInfo` arguments in this order: close price, funding fee, close fee, PnL and holding fee. The values are raw integers. The `archive` and `combined` datasets are not part of the free trial, so the queries in this section need a paid plan. ### Simple Mode event counts This query counts every event the contract emitted in a month, grouped by event name. Change the dates to cover any period before June 2026. ```graphql query AsterSimpleModeEventCounts { EVM(network: bsc, dataset: archive) { Events( where: { Block: { Date: { since: "2026-04-01", till: "2026-04-30" } } LogHeader: { Address: { is: "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0" } } } orderBy: { descendingByField: "count" } limit: { count: 50 } ) { Log { Signature { Name Signature } } count } } } ``` ### Simple Mode liquidations This query returns liquidations: `ExecuteCloseSuccessful` events with `executionType` equal to `2`. Use `0` for take-profit closes and `1` for stop-loss closes. ```graphql query AsterSimpleModeLiquidations { EVM(network: bsc, dataset: archive) { Events( where: { Block: { Date: { since: "2026-04-01", till: "2026-04-30" } } LogHeader: { Address: { is: "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0" } } Log: { Signature: { Name: { is: "ExecuteCloseSuccessful" } } } Arguments: { includes: { Name: { is: "executionType" }, Value: { UnsignedInteger: { eq: 2 } } } } } orderBy: { descending: Block_Time } limit: { count: 20 } ) { Block { Time } Transaction { Hash } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` ### One trader's Simple Mode history Filter on the `user` argument to get every event for one trader, whoever sent the transaction. ```graphql query AsterSimpleModeTrader($trader: String = "0x37f05b741793b869f26277df5620bcd805a06afe") { EVM(network: bsc, dataset: archive) { Events( where: { Block: { Date: { since: "2026-04-01", till: "2026-04-30" } } LogHeader: { Address: { is: "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0" } } Arguments: { includes: { Name: { is: "user" }, Value: { Address: { is: $trader } } } } } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Block { Time } Transaction { Hash From } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ### Full lifecycle of one Simple Mode trade Every Simple Mode order and trade has a hash. Pass it in `$tradeHash` to get each event that carries it as `tradeHash` or `orderHash`, in time order. Argument filters scan values that are not indexed, so keep the date range as narrow as you can. ```graphql query AsterSimpleModeTradeLifecycle($tradeHash: String = "0x4eabfc07d7e193076a8deb00dae378092f6ed701b62df06357f3e7d97a103526") { EVM(network: bsc, dataset: archive) { Events( where: { Block: { Date: { since: "2026-04-01", till: "2026-04-30" } } LogHeader: { Address: { is: "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0" } } Arguments: { includes: { Name: { in: ["tradeHash", "orderHash"] }, Value: { Bytes: { is: $tradeHash } } } } } orderBy: { ascending: Block_Time } limit: { count: 50 } ) { Block { Time } Transaction { Hash } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ### Simple Mode trading and pool events This table lists the trading, fee, funding, pool and prediction events the contract emitted. The contract also emits admin events, such as `DiamondCut`, `UpdateFeeConfig`, `RoleGranted` and `Paused`. Its oracle events, such as `PriceUpdated`, `RequestPrice` and `RequestPriceV2`, are not decoded by Bitquery and appear with an empty `Name`. | Event name | Signature | | --- | --- | | `AddMarginPoolBalance` | `AddMarginPoolBalance(address,address,uint256)` | | `BurnAlp` | `BurnAlp(address,address,address,uint256,uint256)` | | `BurnFee` | `BurnFee(address,address,uint256,uint256,uint256,uint256)` | | `BurnRemoveLiquidity` | `BurnRemoveLiquidity(address,address,uint256)` | | `CancelLimitOrder` | `CancelLimitOrder(address,bytes32)` | | `CloseFee` | `CloseFee(address,uint256,uint256,uint24,uint256,uint256)` | | `CloseTradeAddLiquidity` | `CloseTradeAddLiquidity(address,uint256)` | | `CloseTradeReceived` | `CloseTradeReceived(address,bytes32,address,uint256)` | | `CloseTradeRemoveLiquidity` | `CloseTradeRemoveLiquidity(address,uint256)` | | `CloseTradeSuccessful` | `CloseTradeSuccessful(address,bytes32,(uint64,int96,uint96,int96,uint96))` | | `ExecuteCloseRejected` | `ExecuteCloseRejected(address,bytes32,uint8,uint64,uint64)` | | `ExecuteCloseSuccessful` | `ExecuteCloseSuccessful(address,bytes32,uint8,(uint64,int96,uint96,int96,uint96))` | | `ExecuteLimitOrderRejected` | `ExecuteLimitOrderRejected(address,bytes32,uint8)` | | `ExecuteLimitOrderSuccessful` | `ExecuteLimitOrderSuccessful(address,bytes32)` | | `FundingFeeAddLiquidity` | `FundingFeeAddLiquidity(address,uint256)` | | `LimitOrderRefund` | `LimitOrderRefund(address,bytes32,uint8)` | | `MarketPendingTrade` | `MarketPendingTrade(address,bytes32,(address,bool,address,uint96,uint80,uint64,uint64,uint64,uint24))` | | `MintAddLiquidity` | `MintAddLiquidity(address,address,uint256)` | | `MintAlp` | `MintAlp(address,address,uint256,uint256)` | | `MintFee` | `MintFee(address,address,uint256,uint256,uint256,uint256)` | | `OpenFee` | `OpenFee(address,uint256,uint256,uint24,uint256,uint256)` | | `OpenLimitOrder` | `OpenLimitOrder(address,bytes32,(address,bool,address,uint96,uint80,uint64,uint64,uint64,uint24))` | | `OpenMarketTrade` | `OpenMarketTrade(address,bytes32,(address,uint32,uint64,address,address,uint96,uint64,uint64,uint24,bool,uint96,int256,uint96,uint40,uint80,uint40,uint256))` | | `PendingPredictionRefund` | `PendingPredictionRefund(address,uint256,uint8)` | | `PendingTradeRefund` | `PendingTradeRefund(address,bytes32,uint8)` | | `PredictAndBet` | `PredictAndBet(address,uint256,(address,uint96,address,uint96,address,uint96,uint32,uint64,uint40,uint24,bool,uint8))` | | `PredictAndBetPending` | `PredictAndBetPending(address,uint256,(address,uint96,address,uint96,address,uint64,uint24,bool,uint128,uint8))` | | `PredictionCloseFee` | `PredictionCloseFee(address,uint256,uint256,uint24,uint256,uint256)` | | `SettlePredictionReject` | `SettlePredictionReject(uint256,uint8,uint256)` | | `SettlePredictionSuccessful` | `SettlePredictionSuccessful(uint256,bool,uint256,address,uint256,uint256)` | | `Stake` | `Stake(address,uint256)` | | `UnStake` | `UnStake(address,uint256)` | | `UpdateMargin` | `UpdateMargin(address,bytes32,uint256,uint256)` | | `UpdateOrderSl` | `UpdateOrderSl(address,bytes32,uint256,uint256)` | | `UpdateOrderTp` | `UpdateOrderTp(address,bytes32,uint256,uint256)` | | `UpdatePairAccFundingFeePerShare` | `UpdatePairAccFundingFeePerShare(address,uint256,int256,uint256)` | | `UpdatePairPositionInfo` | `UpdatePairPositionInfo(address,uint256,uint256,uint256,int256,uint64,uint64)` | | `UpdateSlippageConfig` | `UpdateSlippageConfig(uint16,uint8,uint256,uint256,uint16,uint16,uint256,uint256)` | | `UpdateTradeSl` | `UpdateTradeSl(address,bytes32,uint256,uint256)` | | `UpdateTradeTp` | `UpdateTradeTp(address,bytes32,uint256,uint256)` | | `WithdrawRevenue` | `WithdrawRevenue(address,address,uint256)` | ## API key, free trial and pricing Create an access token at [account.bitquery.io](https://account.bitquery.io/) and follow [how to generate a token](/docs/authorization/how-to-generate/). The free trial runs for seven days and includes 1,000 API points, 100 MCP credits and two simultaneous streams, on real-time data only. The bridge queries and the subscription on this page work in the trial. The Simple Mode history queries use `archive` and need a paid plan. Subscriptions need streams, which the trial and the Pro, Scale and Enterprise plans include and the Personal plan does not. Request rate limits by plan are 30 a minute on Personal, 90 on Pro and 240 on Scale, with custom limits on Enterprise; see [rate limits](/docs/plans/rate-limits/). Points and streams are explained on [how billing works](/docs/plans/how-billing-works/), and plan prices are on the [pricing page](https://bitquery.io/pricing). ## Related documentation - [Perp DEX API](/docs/perpetuals/) - [Hyperliquid API](/docs/perpetuals/hyperliquid/) - [BSC Transfers API](/docs/blockchain/BSC/bsc-transfers/) - [BSC Events API](/docs/blockchain/BSC/bsc-events-api/) - [Data coverage and retention](/docs/graphql/data-coverage-retention/) - [API Authorization](/docs/authorization/how-to-use/) ## Support For technical support, contact the Bitquery team on Telegram or open a ticket on the [Bitquery support portal](https://support.bitquery.io/). --- ## Authenticate Bitquery WebSockets URL: https://docs.bitquery.io/docs/authorization/websocket/ Authenticate Bitquery WebSockets in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Authenticating Websockets When it comes to authenticating websockets the token can be included only in the following manner: `wss://streaming.bitquery.io/graphql?token=ory*at*..` with the token attached to the URL. The request should include only two headers: ``` Sec-WebSocket-Protocol: graphql-ws Content-Type: application/json ``` Refer this [this](https://www.postman.com/interstellar-eclipse-270749/workspace/bitquery/ws-raw-request/659811c95188ca95c7b9e569?action=share&creator=27392958&ctx=documentation) link for postman example of how to use OAuth with websockets. ## Example: connecting with graphql-ws (JavaScript) Pass the OAuth token in the connection URL and use the `graphql-ws` subprotocol: ```javascript const client = createClient({ url: "wss://streaming.bitquery.io/graphql?token=ory_at_YOUR_TOKEN", // Bitquery expects the token in the URL (not an Authorization header) for WebSockets. }); ``` - Generate the token in [Account → API Access Tokens](https://account.bitquery.io/user/api_v2/access_tokens); see [how to generate a token](/docs/authorization/how-to-generate/). - Revoking a token does **not** close an already-open socket — terminate running subscriptions from the account panel. ## Next steps - [WebSocket subscriptions](/docs/subscriptions/websockets/) - [Rate limits & concurrency](/docs/plans/rate-limits/) --- ## Automated Trading Ethereum Volume Surge Bot URL: https://docs.bitquery.io/docs/usecases/automated-trading-ethereum-volume-surge-bot/ Build Automated Trading Ethereum Volume Surge Bot: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Automated Trading on Ethereum: How To Build a Volume Surge Detection Bot In this tutorial, we will build a Python bot that monitors token trading volume on Ethereum and automatically executes buy orders when volume surges by 10% or more. For real-time price data with volume metrics, use our [Crypto Price API](/docs/trading/crypto-price-api/). We’ll leverage the Bitquery APIs with Python to monitor activities and automatically execute trades in real-time. We’ll explore how to access and use Bitquery APIs to fetch real-time trading volume data, calculate volume changes, and perform automated transactions on the Ethereum Sepolia testnet. > Note: This material is for educational and informational purposes only and is not intended as investment advice. The content reflects the author's personal research and understanding. While specific investments and strategies are mentioned, no endorsement or association with these entities is implied. Readers should conduct their own research and consult with qualified professionals before making any investment decisions. Bitquery is not liable for any losses or damages resulting from the application of this information. ## Why Bitquery? [Bitquery](https://bitquery.io) is a blockchain data provider that offers suites of tools and APIs to access blockchain data easily. It enables developers, analysts, and researchers to query and retrieve historical and real-time data from over 40 blockchains and protocols with GraphQL. ## Building a Simple Volume Surge Detection MEV Bot in Python In this section, we’ll build an MEV bot that detects a surge in trade volume for a specific token and automatically executes a buy order when all conditions are met. This tutorial will guide you through creating a Python script that detects a surge in trading volume for a specific token and executes a buy order on the Ethereum Sepolia testnet. We'll use the Bitquery API to fetch trading volume data and Web3.py to interact with the Ethereum blockchain. This bot uses the [Bitquery API](/docs/intro/) to fetch real-time trading data and Web3.py to interact with the Ethereum blockchain, demonstrating a practical application of Python in blockchain trading automation using the Bitquery API. - Here is the [link](https://github.com/bitquery/volume-surge-trading-bot/tree/main) to the GitHub Repository for the volume surge detection MEV bot - Here is also a [step-by-step video tutorial](https://www.youtube.com/watch?v=2sK-dtYF2-k) for the project. Here is the step-by-step tutorial on how to build this MEV bot. ### Setting Up Your Programming Environment To build this MEV Bot, set up your programming environment by installing Python, downloading the necessary libraries (requests, web3 os), and setting up Infura and Bitquery APIs. Follow the steps below to set up your environment and the APIs you need for the project. 1. By running the query below, you can download the libraries needed for the project without any issues. ```bash pip install requests web3 os ``` The requests library is used for making Https requests in python while the web3 library is used for interacting with the Ethereum blockchain network. And the os library lets you use the operating system dependent functionality in python. It allows you to interface with the underlying system in several ways like creating, removing, and manipulating directories and libraries. 2. Once you’ve set up your python environment and download the necessary library for the project as we’ve done in the previous step, you need to set up the API keys needed to retrieve the data from Bitquery. - Follow [this link](/docs/authorization/how-to-generate/) to learn how to generate the tokens either programmatically or manually to use for this project. - Visit the alchemy website, and follow the necessary instructions to generate the URL needed to connect with your Sepolia Testnet through the Infura environment. ### Step1: Importing Required Libraries Once you’ve set up your programming environment, you have to import all the necessary libraries needed to build the MEV bot. These includes the libraries for fetching web pages or API data (requests), connecting to Ethereum nodes (web3), creating directories and files (OS), and manipulating time (datetime and time module) ```python from datetime import datetime, timedelta, timezone from web3 import Web3 ``` ### Step 2: Script Configurations Here, you need to configure your scripts by setting up all the necessary variables and API keys. As seen in the query below, you set up the: - BITQUERY_AUTH_TOKEN: generated from Bitquery. Learn how to generate an API token here - TOKEN_ADDRESS: is the address of the token you want the MEV bot to track - TESTNET_URL: URL gotten from alchemy needed to connect to the Ethereum Sepolia testnet - PRIVATE_KEY: is the private key of the wallet address where the transaction will be executed - ADDRESS: is your the wallet address you’ll be using - VOLUME_SURGE_THRESHOLD: is the volume percentage that triggers the MEV bot to execute a trade - TIME_WINDOW_MINUTES: is the time-frequency to check the data for executing a trade ```python # Configuration BITQUERY_AUTH_TOKEN = "ory_at_" TOKEN_ADDRESS = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' # Address of the token to track TESTNET_URL = 'https://eth-sepolia.g.alchemy.com/v2/YOUR_ALCHEMY_API_KEY' # Sepolia testnet URL PRIVATE_KEY = 'YOUR_PRIVATE_KEY' # Never commit a real private key ADDRESS = 'YOUR_WALLET_ADDRESS' # Address from which transactions will originate VOLUME_SURGE_THRESHOLD = 0.1 # Threshold for volume surge detection (0.1% increase) TIME_WINDOW_MINUTES = 60 # Time window in minutes for historical data fetching ``` ### Step 3: Setting Up the Predefined Time Range The script sets up and prints the start (PREDEFINED_SINCE_DATE) and end (PREDEFINED_TILL_DATE) timestamps for a historical data query. These timestamps are in ISO 8601 format and represent the range from the current time minus a predefined number of minutes (specified by TIME_WINDOW_MINUTES) to the current time. This time range can then be used to fetch historical data from a database or an API, ensuring that the data falls within the specified period. ```python # Predefined time range for historical data query PREDEFINED_SINCE_DATE = (datetime.now(timezone.utc) - timedelta(minutes=TIME_WINDOW_MINUTES)).strftime("%Y-%m-%dT%H:%M:%SZ") PREDEFINED_TILL_DATE = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") print(f"PREDEFINED_SINCE_DATE: {PREDEFINED_SINCE_DATE}") print(f"PREDEFINED_TILL_DATE: {PREDEFINED_TILL_DATE}") ``` ### Step 4: Fetch the Historical Volume Data At this step, you create the fetch_volume_data function to fetch historical trading volume data from Bitquery. The fetch_volume_data function below takes the token_address parameter and uses the [DEXTradeByTokens API](/docs/schema/evm/dextrades/) to retrieve the count of trade, sell, and buy amounts from the blockchain using the variables you set up in Step2 (Script configuration) above. ```python # Function to fetch historical volume data from Bitquery def fetch_volume_data(token_address): print("Fetching volume data...") query = """ { EVM(dataset: realtime, network: eth) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "%s"}}, Side: {Currency: {SmartContract: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}}}}, Block: {Time: {since: "%s", till: "%s"}}} ) { buy: sum(of: Trade_AmountInUSD) sell: sum(of: Trade_Side_AmountInUSD) count } } } """ % (token_address, PREDEFINED_SINCE_DATE, PREDEFINED_TILL_DATE) ``` The function also send the POST request, which includes an authorization header to the Bitquery API. ```python print("Querying Bitquery API...") try: response = requests.post( 'https://streaming.bitquery.io/graphql', json={'query': query}, headers={'Authorization': f'Bearer {BITQUERY_AUTH_TOKEN}'} ) if response.status_code == 200: print("Data successfully fetched.") data = response.json() trades = data['data']['EVM']['DEXTradeByTokens'] if not trades: print("No trades found.") else: print("Fetched trades:") for trade in trades: print(f" Buy Volume: {trade['buy']} USD, Sell Volume: {trade['sell']} USD") return trades else: raise Exception(f"Failed to fetch data: {response.text}") except Exception as e: print(f"Error in fetch_volume_data: {str(e)}") return None ``` ### Step 5: Calculate the Total Volume Traded Create a get_volume() function to calculate the total volume traded for the specified token. This function calculates the total trading volume for the specified token by summing up the buy and sell volumes retrieved from the Bitquery API. If there are no trades or an error occurs, it returns 0. ```python # Function to calculate total volume traded for the token def get_volume(): try: print("Calculating token volume...") trades = fetch_volume_data(TOKEN_ADDRESS) if trades is None: return 0 # No trades, so volume is 0 total_volume = sum(float(trade['buy']) + float(trade['sell']) for trade in trades) print(f"Total volume: {total_volume}") return total_volume except Exception as e: print(f"Error in get_volume: {str(e)}") return 0 # Return 0 volume on error ``` ### Step 6: Check for Volume Surge In this step, you’ll create the check_volume_surge function to check if there is a surge in trading volume. The function determines if there is a significant surge in the trading volume of the specified token by comparing the initial volume to the current volume. If the increase in volume exceeds a predefined threshold, it indicates a volume surge. In the case of this demo, if the increase in volume is equal to or greater than the VOLUME_SURGE_THRESHOLD (which in this case is 0.1), it indicates the volume surge or otherwise returns FALSE. ```python # Function to check if there is a volume surge def check_volume_surge(initial_volume, current_volume): print("Checking volume surge condition...") if initial_volume > 0: increase_percentage = ((current_volume - initial_volume) / initial_volume) * 100 print(f"For Time: {PREDEFINED_SINCE_DATE}" + " the " + f"increase percentage is: {increase_percentage}%") return increase_percentage >= VOLUME_SURGE_THRESHOLD return False ``` ### Step 7: Execute a Buy Order This execute_buy_order function is designed to execute a buy order for the token address specified as the parameter on the Ethereum Sepolia test network. It creates and executes a transaction using the provided Ethereum address, Private Key, and Token address. 1. Initialize Web3 and Fetch the Transaction Nonce The function initializes web3 by creating an instance of Web3 connected to the Ethereum Sepolia test network using the testnet URL you provided above. It also retrieves the transaction nonce for the wallet address the transaction will be executed. ```python # Function to execute a buy order on the testnet def execute_buy_order(token_address): try: print("Executing buy order...") web3 = Web3(Web3.HTTPProvider(TESTNET_URL)) nonce = web3.eth.get_transaction_count(ADDRESS) ``` 2. Define the Transaction Parameter This block of code defines the parameter needed to execute the transactions. For the case of this demo, the transaction value, 0.1 ETH was converted to wei (the smallest unit of ETH). The gas price of 50gwei was converted to wei. A transaction dictionary, which contains parameters to execute the transactions : - the nonce of the originating address (nonce), - the smart contract address of the token you want to buy(to), - The amount of ETH to send(value), the gas limit for the transaction(gas), - and the gas price for the transaction (gasPrice). ``` value = Web3.to_wei(0.1, 'ether') gas_price = Web3.to_wei('50', 'gwei') # Convert 50 Gwei to Wei transaction = { 'nonce': nonce, 'to': token_address, 'value': value, 'gas': 2000000, 'gasPrice': gas_price } ``` 3. Sign and Send the Transaction This section of the execute_buy_order function signs the transaction with the private key of the originating address. In the case of this demo, the private key you provided in the script configuration step above. The transaction signed above with the private key will be sent to the Ethereum Sepolia Testnet network. The transaction hash for the executed transaction will be printed and returned as a hexadecimal string for confirmation. ```python signed_tx = web3.eth.account.sign_transaction(transaction, PRIVATE_KEY) tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f"Transaction sent. Hash: {web3.toHex(tx_hash)}") return web3.toHex(tx_hash) except Exception as e: print(f"Error in execute_buy_order: {str(e)}") return None ``` ### Step 8: Setting Up the Main Function to Run the Bot The main function code snippet below is the entry point for running the Volume surge detection MEV bot. This bot continuously monitors the trading volume for the specified token and executes a buy order if a significant volume surge is detected. In the case of this demo, a buy order will be executed if the surge is greater than 10% of the previous trade volume. According to this demo: - The main function initializes the trading bot by fetching the initial trading volume of the specified token. - It then enters an infinite loop where it continuously fetches the current trading volume, checks for significant volume surges, and executes buy orders if a surge is detected. - The loop runs every minute, ensuring the bot operates in real time. Any exceptions during the execution are caught and logged to avoid crashes. ```python # Main function to run the bot def main(): try: initial_volume = get_volume() print("Initial Volume:", initial_volume) while True: current_volume = get_volume() print("Current Volume:", current_volume) if check_volume_surge(initial_volume, current_volume): print(f"Volume surge detected. Executing buy order.") tx_hash = execute_buy_order(TOKEN_ADDRESS) if tx_hash: print(f"Transaction hash: {tx_hash}") time.sleep(60 * 1) # Check every 1 minute except Exception as e: print(f"Error occurred: {str(e)}") if __name__ == "__main__": main() ``` By following this tutorial, you have created an MEV bot in Python that detects trading volume surges for a specific token and executes buy orders automatically. --- ## BNB Chain DEX Trades API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-dextrades/ BNB Chain DEX trades API: get BNB Chain DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Built for traders and analytics teams. # BNB Chain DEX Trades API :::tip Need real-time BNB / BSC DEX data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API** (filter with `Pair.Market.Network: Binance Smart Chain`). Use this page when you need **historical BNB / BSC data older than ~30 days** (with `dataset: combined` or `archive`), raw per-swap detail, or call / event context. ::: Bitquery provides BSC DEX trade data through APIs, Streams, and Data Dumps. The examples below show how to access real-time and historical trade data across BSC-based DEXs using GraphQL APIs and subscriptions. Read [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) to get a better understanding on when to use which cube. If you're looking for other data points or have integration questions, reach out to [support](https://t.me/Bloxy_info). Need zero-latency BSC trade data? [Explore our Kafka Streams and request a trial ➤](/docs/streams/protobuf/chains/EVM-protobuf/) You may also be interested in: - [FourMeme APIs ➤](/docs/blockchain/BSC/four-meme-api/) - [BNB Uniswap API ➤](/docs/blockchain/BSC/bsc-uniswap-api/) - [BNB DEX Trades API ➤](/docs/blockchain/BSC/bsc-dextrades/) :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you must generate an API access token. Follow these steps: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Live DEX swap stream (BNB Chain) {#crypto-trades-live-stream} [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api): one row per swap, with USD and supply. Filter **`Pair.Market.Network: Binance Smart Chain`**. [When to use this vs chain DEX APIs](/docs/cubes/dextrades-dextradebytokens-trading-trades). Run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-BNB-Trade-Stream). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Binance Smart Chain" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` ## Subscribe to Latest BSC Trades This example uses the chain-specific **DEXTrades** cube via `EVM(network: bsc) { DEXTrades }` (pool-side Buy/Sell; see [DEXTrades cube](/docs/cubes/dextrades)). USD fields can be empty on thin pools. For swap rows with trader + USD, use the [stream at the top](#crypto-trades-live-stream) of this page. You can find the query [here](https://ide.bitquery.io/subscribe-to-bsc-dex-trades) ```graphql subscription { EVM(network: bsc) { DEXTrades { Block { Time } Trade { Dex { ProtocolName ProtocolFamily SmartContract } Buy { Amount Buyer Seller Currency { Decimals Fungible HasURI Name ProtocolName SmartContract Symbol } OrderId } Sell { Buyer Seller Currency { Decimals Fungible HasURI Name ProtocolName SmartContract Symbol } } } } } } ``` ## Latest Trades of a Token This query will fetch you latest trades for a token for the BSC network. You can test the query [here](https://ide.bitquery.io/latest-trades-of-a-token-on-bsc). ```graphql query LatestTrades($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descending: Block_Time} limit: {count: 50} where: {Trade: {Currency: {SmartContract: {is: $token}}, Price: {gt: 0}}} ) { Block { allTime: Time } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } AmountInUSD Buyer Seller Side { Type Buyer Seller } Price Amount Side { Currency { Symbol SmartContract Name } AmountInUSD Amount } } } } } { "network": "bsc", "token": "0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c" } ``` ![image](https://github.com/user-attachments/assets/160fa16e-1c75-49f2-a9ac-f3eeccf84276) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/token/0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c#last_trades). ## Total Bought, Total Sold, Avg Sell price, Last Active Trade of a specific token by an Address Get total bought, total sold, average sell price, and last active trade time for a specific token by a trader. Test the query [here](https://ide.bitquery.io/Total-buy-total-sell-avg-sell-last-active_1) ```graphql query MyQuery($trader: String, $token: String) { EVM(dataset: realtime, network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $token } } } any: [ { Trade: { Buyer: { is: $trader } } } { Trade: { Seller: { is: $trader } } } ] } ) { Block { last_active_time: Time(maximum: Block_Time) } total_buy: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) total_sell: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) avg_sell_price_usd: average( of: Trade_PriceInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ``` ```json { "trader": "0xc5C2653d38E241D62F96A4fB8f8497b6126F21dC", "token": "0x49d870B1d21D00c775DD03110Ef4c8FeF4Fd4444" } ``` ## Top Traders of a token This query will fetch you top traders of a token for the BSC network. You can test the query [here](https://ide.bitquery.io/top-traders--token-bsc_3). ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}}} ) { Trade { Buyer Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "bsc", "token": "0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c" } ``` ![image](https://github.com/user-attachments/assets/a6a09516-c36a-4e2f-b658-5c218a5d998b) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/token/0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c#top_traders). ## Top Traders by profit in last 7 days This query will fetch you top traders by profit in the last 7 days for the BSC network. You can test the query [here](https://ide.bitquery.io/top-traders-in-last-7-days-by-profit_2). ```graphql query TopTraders($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "profit"} limit: {count: 100} where: {Trade: {Side: {Amount: {gt: "0"}}} Block:{Time:{since_relative:{days_ago:7}}}} ) { Trade { Buyer } profit: calculate(expression:"$sold-$bought") bought: sum(of: Trade_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "bsc" } ``` ## Get all Trading Pairs data of a specific token This query will fetch you all the trading pairs of a token for the BSC network. You can test the query [here](https://ide.bitquery.io/trading-pairs-of-a-token). ```graphql query tokenTrades($network: evm_network, $token: String, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "usd"} where: {Trade: {Currency: {SmartContract: {is: $token}}}, Block: {Time: {after: $time_3h_ago}}} limit: {count: 200} ) { Trade { Currency { Symbol Name SmartContract Fungible } Side { Currency { Symbol Name SmartContract } } price_usd: PriceInUSD(maximum: Block_Number) price_last: Price(maximum: Block_Number) price_10min_ago: Price( maximum: Block_Number if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: Price( maximum: Block_Number if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Number) } usd: sum(of: Trade_AmountInUSD) count } } } { "network": "bsc", "token": "0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c", "time_10min_ago": "2024-09-22T14:36:55Z", "time_1h_ago": "2024-09-22T13:46:55Z", "time_3h_ago": "2024-09-22T11:46:55Z" } ``` ![image](https://github.com/user-attachments/assets/9042c5a4-dc95-40d1-a723-fad43edc70fe) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/token/0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c#token_trades). ## Get First 500 Buyers of a specific token Below API gets you the first 500 buyers of a specific BSC token, here as example we have taken this token `0x031b41e504677879370e9DBcF937283A8691Fa7f`. Try the API [here](https://ide.bitquery.io/first-500-buyers-of-a-specific-BSC-chain-token_2#). ```graphql query MyQuery { EVM(network: bsc, dataset: combined) { DEXTrades( limit: { count: 500 } orderBy: { ascending: Block_Time } limitBy: { count: 1, by: Trade_Sell_Buyer } where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x031b41e504677879370e9DBcF937283A8691Fa7f" } } } } } ) { Block { Time } Trade { Sell { Buyer } } Transaction { From Hash } } } } ``` ## Get all DEXs where a specific token is listed This query will fetch you all the DEXs where a token is listed for the BSC network. You can test the query [here](https://ide.bitquery.io/get-all-dex-markets-for-a-token). ```graphql query tokenDexMarkets($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "amount"} where: {Trade: {Currency: {SmartContract: {is: $token}}}} ) { Trade { Dex { ProtocolFamily ProtocolName } } amount: sum(of: Trade_Amount) pairs: uniq(of: Trade_Side_Currency_SmartContract) trades: count } } } { "network": "bsc", "token": "0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c" } ``` ![image](https://github.com/user-attachments/assets/0fb63784-d6cc-42ad-b222-3c6d5da7b1e8) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/token/0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c#token_dex_list). ## Get Price Change 5min, 1h, 6h and 24h of a specific token Use below query to get price change 5min, 1h, 6h and 24h of a specific token. Change the `Currency{SmartContract}` and `Dex{SmartContract}` according to your needs. Test the query [here] (https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_3). ```graphql query MyQuery { EVM(dataset: combined network:bsc) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0x85E92213fcA84aA99AdbAC5049D8426984D64444"}}, Dex: {SmartContract: {is: "0x2450f7D9A146cc7180C2e28f9bdF6Bcd5E28eF0A"}}}, TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ){ Trade { Price_5min_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{minutes_ago:5}}}}) Price_1h_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{hours_ago:1}}}}) Price_6h_ago: PriceInUSD(minimum: Block_Number if:{Block:{Time:{since_relative:{hours_ago:6}}}}) Price_24h_ago: PriceInUSD(minimum: Block_Number) CurrentPrice: PriceInUSD(maximum: Block_Number) } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum( of: Trade_Side_AmountInUSD ) Price_Change_5min: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100") Price_Change_1h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100") Price_Change_6h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100") Price_Change_24h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100") } } } ``` ## Top 10 BSC Tokens by Price Change in last 1h Use below query to get top 10 BSC Tokens by Price Change in last 1h. Test the query [here] (https://ide.bitquery.io/Top-10-bsc-tokens-by-price-change-in-last-1-hr). ```graphql query MyQuery { EVM(dataset: combined network:bsc) { DEXTradeByTokens( limit:{count:10} orderBy:{descendingByField:"Price_Change_1h"} where: {TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Trade { Currency { Name Symbol SmartContract } Price_5min_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) Price_1h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) Price_6h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) Price_24h_ago: PriceInUSD(minimum: Block_Number) CurrentPrice: PriceInUSD(maximum: Block_Number) Side { Currency { Name Symbol SmartContract } } Dex{ SmartContract } } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum(of: Trade_Side_AmountInUSD) Price_Change_5min: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100" ) Price_Change_1h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100" ) Price_Change_6h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100" ) Price_Change_24h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100" ) } } } ``` ## Get OHLC data of a token This query will fetch you the OHLC of a token for the BSC network. You can test the query [here](https://ide.bitquery.io/OHLC-for-a-token-on-bsc_1). ```graphql query tradingView($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {ascendingByField: "Block_Time"} where: {Trade: {Currency: {SmartContract: {is: $token}}, PriceAsymmetry: {lt: 0.1}}} ) { Block { Time(interval: {count: 5, in: minutes}) } Trade { open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) max: PriceInUSD(maximum: Trade_PriceInUSD) min: PriceInUSD(minimum: Trade_PriceInUSD) } volume: sum(of: Trade_Side_AmountInUSD, selectWhere: {gt: "0"}) } } } { "network": "bsc", "token": "0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c" } ``` ![image](https://github.com/user-attachments/assets/c884565c-fbd3-4900-8939-6461ebad52cd) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/token/0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c). ## Latest Trades of a Token pair This query will fetch you latest trades for a token pair for the BSC network. You can test the query [here](https://ide.bitquery.io/Latest-price-of-a-token-on-bsc). ```graphql query LatestTrades($network: evm_network, $token: String, $base: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descending: Block_Time} limit: {count: 50} where: {Trade: {Side: {Amount: {gt: "0"}, Currency: {SmartContract: {is: $base}}}, Currency: {SmartContract: {is: $token}}, Price: {gt: 0}}} ) { Block { allTime: Time } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } Currency { Symbol SmartContract Name } Price AmountInUSD Amount Side { Type Currency { Symbol SmartContract Name } AmountInUSD Amount } } } } } { "network": "bsc", "token": "0x711bfe972465a1e9182766ad67aff3c80a0cf308", "base": "0x55d398326f99059ff775485246999027b3197955" } ``` ![image](https://github.com/user-attachments/assets/e9ab60ae-d2d3-4da9-95b0-bb1c79b97550) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/pair/0x711bfe972465a1e9182766ad67aff3c80a0cf308/0x55d398326f99059ff775485246999027b3197955#pair_latest_trades). ## Get OHLC Data For a Particular Token Pair This query will fetch you the OHLC of a token pair for the BSC network. You can test the query [here](https://ide.bitquery.io/BSC-OHLC-API-For-Token-Pair). ```graphql query tradingViewPairs { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( orderBy: {ascendingByField: "Block_Time"} where: {TransactionStatus: {Success: true}, Trade: {Side: {Amount: {gt: "0"}, Currency: {SmartContract: {is: "0x55d398326f99059ff775485246999027b3197955"}}}, Currency: {SmartContract: {is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"}}, Success: true}} limit: {count: 10} ) { Block { Time(interval: {count: 60, in: seconds}) } min: quantile(of: Trade_PriceInUSD, level: 0.1) max: quantile(of: Trade_PriceInUSD, level: 0.9) close: average(of: Trade_PriceInUSD) open: average(of: Trade_PriceInUSD) volume: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Top Traders of a token pair This query will fetch you top traders of a token pair for the BSC network. You can test the query [here](https://ide.bitquery.io/pair-top-traders_2). ```graphql query pairTopTraders($network: evm_network, $token: String, $base: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}, Side: {Amount: {gt: "0"}, Currency: {SmartContract: {is: $base}}}}} ) { Trade { Buyer Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "bsc", "token": "0x711bfe972465a1e9182766ad67aff3c80a0cf308", "base": "0x55d398326f99059ff775485246999027b3197955" } ``` ![image](https://github.com/user-attachments/assets/c7227a7b-eb1d-40e8-80e7-4412fb069c7f) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/pair/0x711bfe972465a1e9182766ad67aff3c80a0cf308/0x55d398326f99059ff775485246999027b3197955#pair_top_traders). ## Get Latest Trades on a specific DEX Use the **[Crypto Trades API](/docs/trading/crypto-trades-api/trades-api)** to stream **live swaps** on BNB Chain. The example below only shows **PancakeSwap v3**: set **`Pair.Market.Network`** to **`Binance Smart Chain`** and **`Pair.Market.Protocol`** to **`pancake_swap_v3`**. Each event is one swap, with price in USD and the trader address. See [all BSC swaps](/docs/trading/crypto-trades-api/trades-api#how-do-i-stream-all-dex-trades-on-bsc-bnb-chain) in the Trades API doc, or open [every BSC swap in the IDE](https://ide.bitquery.io/All-BNB-Trade-Stream). For pool-level queries on PancakeSwap using **`EVM { DEXTrades }`**, use the [PancakeSwap API](/docs/blockchain/BSC/pancake-swap-api). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Binance Smart Chain" } Protocol: { is: "pancake_swap_v3" } } } } ) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` To stream **a token on that DEX**, keep the same **`Pair.Market`** filters and add **`Pair.Token`** / **`Pair.QuoteToken`** (e.g. contract or **`Pair.Token.Id`**) — same patterns as token streams in the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api). For a **DEXTrades**-style example keyed on factory + token, see this [IDE query](https://ide.bitquery.io/latest-trades-of-a-token-on-a-DEX). ## Get all DEXs where a specific token pair is listed This query will fetch you all the DEXs where a token pair is listed for the BSC network. You can test the query [here](https://ide.bitquery.io/pair-dex-list_5). ```graphql query pairDexList($network: evm_network, $token: String, $base: String, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "amount"} where: {Trade: {Currency: {SmartContract: {is: $token}}, Side: {Amount: {gt: "0"}, Currency: {SmartContract: {is: $base}}}}, Block: {Time: {after: $time_3h_ago}}} ) { Trade { Dex { ProtocolFamily ProtocolName } price_last: PriceInUSD(maximum: Block_Number) price_10min_ago: PriceInUSD( maximum: Block_Number if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: PriceInUSD( maximum: Block_Number if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Number) } amount: sum(of: Trade_Side_Amount) pairs: uniq(of: Trade_Side_Currency_SmartContract) trades: count } } } { "network": "bsc", "token": "0x711bfe972465a1e9182766ad67aff3c80a0cf308", "base": "0x55d398326f99059ff775485246999027b3197955", "time_10min_ago": "2024-09-22T14:55:14Z", "time_1h_ago": "2024-09-22T14:05:14Z", "time_3h_ago": "2024-09-22T12:05:14Z" } ``` ![image](https://github.com/user-attachments/assets/9c48a155-6cce-4d14-b3ef-3cd32f77d66f) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/pair/0x711bfe972465a1e9182766ad67aff3c80a0cf308/0x55d398326f99059ff775485246999027b3197955#pair_dex_list). ## Top Gainers This query will fetch you top gainers for the BSC network. You can test the query [here](https://ide.bitquery.io/bsc-top-gainers). ```graphql query ($network: evm_network) { EVM(network: $network) { DEXTradeByTokens(orderBy: {descendingByField: "usd"}, limit: {count: 100}) { Trade { Currency { Symbol Name SmartContract } Side { Currency { Symbol Name SmartContract } } price_last: PriceInUSD(maximum: Block_Number) price_1h_ago: PriceInUSD(minimum: Block_Number) } dexes: uniq(of: Trade_Dex_OwnerAddress) amount: sum(of: Trade_Side_Amount) usd: sum(of: Trade_Side_AmountInUSD) buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) count(selectWhere: {ge: "100"}) } } } { "network": "bsc" } ``` ![image](https://github.com/user-attachments/assets/09a64034-a323-44c5-ab35-e21bde6a6fba) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc). ## Top Bought tokens This query will fetch you top bought tokens for the BSC network. Arranged in descending order of `bought - sold`. You can test the query [here](https://ide.bitquery.io/top-bought-bsc). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens(orderBy: {descendingByField: "buy"}, limit: {count: 100}) { Trade { Currency { Symbol Name SmartContract } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) } } } { "network": "bsc" } ``` ![image](https://github.com/user-attachments/assets/46f1ea39-902b-4e84-850b-9575791964e7) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc). ## Top Sold tokens This query will fetch you top sold tokens for the BSC network. Arranged in descending order of `sold - bought`. You can test the query [here](https://ide.bitquery.io/top-sold-bsc). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens(orderBy: {descendingByField: "sell"}, limit: {count: 100}) { Trade { Currency { Symbol Name SmartContract } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) } } } { "network": "bsc" } ``` ![image](https://github.com/user-attachments/assets/87e94f6a-cb15-4315-bb60-f72718548b2e) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc). ## Get all DEXs on BSC Network This query retrieves all the DEXes operating on BSC network and gives info such as `ProtocolName` , `ProtocolVersion` and `ProtocolFamily`. Find the query [here](https://ide.bitquery.io/Get-all-the-DEXs-on-BSC-network). ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { DEXTrades { Trade { Dex { ProtocolName ProtocolVersion ProtocolFamily } } count } } } ``` ## Subscribe to Latest Price of a Token in Real-time on BSC This query provides real-time updates on price of ETH `0x2170Ed0880ac9A755fd29B2688956BD959F933F8` in terms of WBNB `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c`, including details about the DEX, market, and order specifics. Find the query [here](https://ide.bitquery.io/realtime-price-of-a-ETH-in-terms-of-WBNB) ```graphql subscription { EVM(network: bsc) { DEXTrades( where: {Trade: {Sell: {Currency: {SmartContract: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}}}, Buy: {Currency: {SmartContract: {is: "0x2170Ed0880ac9A755fd29B2688956BD959F933F8"}}}}} ) { Block { Time } Trade { Buy { Amount AmountInUSD Buyer Seller Price_in_terms_of_sell_currency: Price PriceInUSD Currency { Name Symbol SmartContract } OrderId } Sell { Amount Buyer Seller Price_in_terms_of_buy_currency: Price Currency { Symbol SmartContract Name } OrderId } Dex { ProtocolFamily ProtocolName SmartContract ProtocolVersion } } } } } ``` ## Latest USD Price of a Token The below query retrieves the USD price of a token on BSC by setting `{Trade: {Buy: {Currency: {SmartContract: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}}}}}` . Check the field `PriceInUSD` for the USD value. You can access the query [here](https://ide.bitquery.io/realtime-usd-price-of-a-WBNB). ```graphql subscription { EVM(network: bsc) { DEXTrades( where: {Trade: {Buy: {Currency: {SmartContract: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}}}}} ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } Sell { Amount Buyer Currency { Name SmartContract Symbol } Seller Price } PriceAsymmetry(selectWhere: {lt: 1}) } } } } ``` ## Stablecoin Peg Health (Latest Price Across All DEXs) Get the **latest price of a stablecoin across all BSC DEXs**. Returns one row per DEX protocol with the most recent trade price. Useful for monitoring peg health and identifying which exchanges have the stablecoin trading closest to its target peg (e.g., $1.00 for USD-pegged stablecoins). Browse multi-chain stablecoin DEX prices on [DEXrabbit's Stablecoins category](https://dexrabbit.bitquery.io/categories/stablecoins). [Run in Bitquery IDE](https://ide.bitquery.io/evm-peg-health_1) ```graphql { EVM(network: bsc) { DEXTradeByTokens( orderBy: {descending: Block_Time} limitBy: {count: 1 by:Trade_Dex_SmartContract} where: {Trade: { Currency: {SmartContract: {is: "CZzgUBvxaMLwMhVSLgqJn3npmxoTo6nzMNQPAnwtHF3s"}}}} ) { Block { Time } Transaction { Hash } Trade { Amount AmountInUSD Price PriceInUSD Currency { Name SmartContract Symbol } Dex { ProtocolName ProtocolFamily SmartContract } Side { Type Currency { Name SmartContract Symbol } AmountInUSD Amount } } } } } ``` ## Get all the DEXs on BSC network This query will fetch you all the DEXs info for the BSC network. You can test the query [here](https://ide.bitquery.io/all-dexs-info-on-bsc). ```graphql query DexMarkets($network: evm_network) { EVM(network: $network) { DEXTradeByTokens { Trade { Dex { ProtocolFamily } } buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Sender) count(if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "bsc" } ``` ![image](https://github.com/user-attachments/assets/ec575065-8546-4831-9529-22ade580f1f5) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/dex_market). ## Get a specific DEX statistics This query will fetch you a specific DEX stats for the BSC network. You can test the query [here](https://ide.bitquery.io/particular-dex-stats). ```graphql query DexMarkets($network: evm_network, $market: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {ascendingByField: "Block_Time"} where: {Trade: {Dex: {ProtocolFamily: {is: $market}}}} ) { Block { Time(interval: {count: 1, in: hours}) } trades: count buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Sender) tokens: uniq(of: Trade_Currency_SmartContract) } } } { "market": "Uniswap", "network": "bsc" } ``` ![image](https://github.com/user-attachments/assets/e48eeb0e-24e6-4865-8010-3616f384c309) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/dex_market/Uniswap). ## Get All Trading Pairs on a particular DEX This query will fetch you all trading pairs on a particular DEX for the BSC network. You can test the query [here](https://ide.bitquery.io/trading-pairs-on-a-specific-dex_1). ```graphql query DexMarkets($network: evm_network, $market: String, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "usd"} where: {Trade: {Dex: {ProtocolFamily: {is: $market}}}, Block: {Time: {after: $time_3h_ago}}} limit: {count: 200} ) { Trade { Currency { Symbol Name SmartContract Fungible } Side { Currency { Symbol Name SmartContract } } price_usd: PriceInUSD(maximum: Block_Number) price_last: Price(maximum: Block_Number) price_10min_ago: Price( maximum: Block_Number if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: Price( maximum: Block_Number if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Number) } usd: sum(of: Trade_AmountInUSD) count } } } { "market": "Uniswap", "network": "bsc", "time_10min_ago": "2024-09-22T15:11:25Z", "time_1h_ago": "2024-09-22T14:21:25Z", "time_3h_ago": "2024-09-22T12:21:25Z" } ``` ![image](https://github.com/user-attachments/assets/e12bd461-3092-43d5-b579-acf8fc435671) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/dex_market/Uniswap). ## Top Traders on a DEX This query will fetch you Top Traders on a particular DEX for the BSC network. You can test the query [here](https://ide.bitquery.io/top-traders-on-a-specific-dex_1). ```graphql query DexMarkets($network: evm_network, $market: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Dex: {ProtocolFamily: {is: $market}}}} ) { Trade { Buyer Dex { OwnerAddress ProtocolFamily ProtocolName } Currency { SmartContract Symbol Name } Side { Currency { SmartContract Symbol Name } } } volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "market": "Uniswap", "network": "bsc" } ``` ![image](https://github.com/user-attachments/assets/390ff5a1-8ff3-4385-9461-76de2d650eb9) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/dex_market/Uniswap#traders). ## Latest Trades on a DEX This query will fetch you latest trades on a particular DEX for the BSC network. You can test the query [here](https://ide.bitquery.io/latest-trades-on-a-particular-dex). ```graphql query LatestTrades($network: evm_network, $market: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descending: Block_Time} limit: {count: 50} where: {Trade: {Dex: {ProtocolFamily: {is: $market}}}} ) { Block { Time } Transaction { Hash } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } AmountInUSD Price Amount Side { Type Currency { Symbol SmartContract Name } AmountInUSD Amount } Currency { Symbol SmartContract Name } } } } } { "market": "Uniswap", "network": "bsc" } ``` ![image](https://github.com/user-attachments/assets/4dd6bae1-10a2-4528-9f34-77808c594c5f) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/bsc/dex_market/Uniswap#trades). ## Aggregated Token Data (Volume & Price, Last 24h) Get up to 100 tokens with aggregated USD volume and average price over the last 24 hours, plus volume and price for 1h, 4h, and 24h via conditional metrics (Trading API; includes BSC and other chains). ▶️ [Aggregated Token Data](https://ide.bitquery.io/aggregated-data) ```graphql { Trading { Tokens( limit: { count: 100 } limitBy: { count: 1, by: Token_Id } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Volume { Usd H1VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 1 } } } }) H4VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 4 } } } }) H24VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 24 } } } }) } Price { Average { currentPrice: Mean(maximum: Block_Time) H1Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) H4Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 4 } } } } ) H24Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) } } } } } ``` ## Volume of Multiple Tokens Across Different Chains Get volume and price change data for multiple tokens trading on different chains (Solana, Ethereum, BSC, Tron) in a single query using the Trading API. Returns volume for 1h, 4h, and 24h periods, plus price change percentages for the same intervals. :::note EVM address format For **EVM chains** (Ethereum, BSC, etc.) in the Trading API, use **all lowercase addresses** in the token ID format (e.g., `bid:eth:0x...` with lowercase hex). Mixed-case addresses may not match. ::: [Run in Bitquery IDE](https://ide.bitquery.io/volume-of-a-token_1) ```graphql query { TokenAsBase: Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } Price: { IsQuotedInUsd: true } Token: { Id: { in: [ "bid:solana:CZzgUBvxaMLwMhVSLgqJn3npmxoTo6nzMNQPAnwtHF3s", "bid:eth:0xfaf0cee6b20e2aaa4b80748a6af4cd89609a3d78", "bid:bsc:0xfaf0cee6b20e2aaa4b80748a6af4cd89609a3d78", "bid:tron:TXL6rJbvmjD46zeN1JssfgxvSo99qC8MRT" ] } } Market: { Protocol: { notIn: ["jupiter", "dex_solana_v3"] } } } ) { Token { Name Symbol Id } Price { Average { currentPrice: Mean(maximum: Block_Time) H1Ago: Mean( maximum: Block_Time if: { Block: { Time: { till_relative: { hours_ago: 1 } } } } ) H4Ago: Mean( maximum: Block_Time if: { Block: { Time: { till_relative: { hours_ago: 4 } } } } ) H24Ago: Mean( minimum: Block_Time if: { Block: { Time: { after_relative: { hours_ago: 24 } } } } ) } } Price_change_1h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H1Ago ) / $Price_Average_H1Ago ) * 100" ) Price_change_4h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H4Ago ) / $Price_Average_H4Ago ) * 100" ) Price_change_24h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H24Ago ) / $Price_Average_H24Ago ) * 100" ) v1h: sum(of: Volume_Usd, if: { Block: { Time: { since_relative: { hours_ago: 1 } } } }) v4h: sum(of: Volume_Usd, if: { Block: { Time: { since_relative: { hours_ago: 4 } } } }) v24h: sum(of: Volume_Usd) } } } ``` --- ## Trader-Focused Trade APIs (with USD Price, Market Cap & Supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get All DEX Trades on BSC With Price, Market Cap, and Supply Stream **all BSC DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Network: Binance Smart Chain`** to capture every swap across all BSC DEXs in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-BSC-with-Price-Marketcap-supply).
Click to expand GraphQL query ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Binance Smart Chain" } } } } ) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
### Top Traders by PnL for a Specific Pool (Last 30 Minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-bsc-pool).
Click to expand GraphQL query ```graphql { Trading { Trades( limit: { count: 10 } orderBy: { descendingByField: "PnL" } where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
--- ## Video Tutorial on BSC DEXTrades API | How to get BSC Decentralized Exchange Data with DEX Trades API --- ## BNB Chain Gra Fun API URL: https://docs.bitquery.io/docs/blockchain/BSC/gra-fun-api/ GRA.fun on BNB Chain: new token creations, transfers, buys, sells and redeems, transaction details, and token trades on PancakeSwap v3 including first trades. # GRA.fun API :::tip Need real-time GRA.fun data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered GRA.fun swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical GRA.fun data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section we'll have a look at some examples using the BSC Transfers API. ## New Token Created Retrieve newly created tokens on the gra.fun platform using [query below](https://ide.bitquery.io/grafun-new-token-created-api). ```graphql { EVM(network: bsc) { Events( where: {Transaction: {To: {is: "0x8341b19a2a602eae0f22633b6da12e1b016e6451"}}, Call: {Signature: {Name: {is: "createPool"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Block { Number Time } Transaction { Hash To From } Log { Index Signature { Name } } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } } Call { Signature { Name } From To } } } } ``` ## GRA fun All Transfers/Trades Retrieve all transfer and trade events related to the GRA fun using [this query](https://ide.bitquery.io/gra-fun-all-transfers). ```graphql { EVM(network: bsc) { Transfers( orderBy: {descending: Block_Time} limit: {count: 10} where: {Transaction: {To: {is: "0x8341b19a2a602eae0f22633b6da12e1b016e6451"}}} ) { Transaction { Hash From To } Call { Signature { Signature Name SignatureHash } } Transfer { Amount AmountInUSD Currency { Name Symbol SmartContract } Receiver Sender } } } } ``` ## GRA fun Redeem Transactions Retrieve all redeemed transactions using [this query](https://ide.bitquery.io/Gra-fun-redeem-transactions). ```graphql { EVM(network: bsc) { Events( orderBy: {descending: Block_Time} limit: {count: 100} where: {Transaction: {To: {is: "0x8341b19a2a602eae0f22633b6da12e1b016e6451"}}, Call: {Signature: {SignatureHash: {is: "1e9a6950"}}}} ) { Transaction { Hash From To } Call { CallPath CallerIndex Create Delegated Error From Gas GasUsed Index InternalCalls Reverted SelfDestruct Signature { Name SignatureHash } Success To Value } Log { Signature { Name Signature SignatureHash } } Arguments { Name Index Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## GRA fun Buy Transactions Retrieve all buy transactions from GRA.fun using [this query](https://ide.bitquery.io/Gra-fun-buy-transactions). ```graphql { EVM(network: bsc) { Events( orderBy: {descending: Block_Time} limit: {count: 100} where: {Transaction: {To: {is: "0x8341b19a2a602eae0f22633b6da12e1b016e6451"}}, Call: {Signature: {SignatureHash: {is: "db61c76e"}}}} ) { Transaction { Hash From To } Call { CallPath CallerIndex Create Delegated Error From Gas GasUsed Index InternalCalls Reverted SelfDestruct Signature { Name SignatureHash } Success To Value } Log { Signature { Name Signature SignatureHash } } Arguments { Name Index Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## GRA fun Sell Transactions Retrieve all sell transactions on GRA fun using [this query](https://ide.bitquery.io/Gra-fun-sell-transactions). ```graphql { EVM(network: bsc) { Events( orderBy: {descending: Block_Time} limit: {count: 100} where: {Transaction: {To: {is: "0x8341b19a2a602eae0f22633b6da12e1b016e6451"}}, Call: {Signature: {SignatureHash: {is: "2dc8f867"}}}} ) { Transaction { Hash From To } Call { CallPath CallerIndex Create Delegated Error From Gas GasUsed Index InternalCalls Reverted SelfDestruct Signature { Name SignatureHash } Success To Value } Log { Signature { Name Signature SignatureHash } } Arguments { Name Index Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## GRA fun Transaction Details Retrieve detailed information about a specific transaction using [this query](https://ide.bitquery.io/gra-fun-detailed-transfer-of-a-transaction). You can check Sender and Receiver of Transfers to understand what bought and sold. ```graphql { EVM(network: bsc, dataset: combined) { Transfers( orderBy: {descending: Block_Time} limit: {count: 10} where: {Transaction: {Hash: {is: "0xcf6b5a0789dacbf9fadffe0c00d208b5df39fadfef21302fe382cf6f6b433d3c"}}} ) { Transaction { Hash From To } Call { Signature { Signature Name SignatureHash } } Transfer { Amount AmountInUSD Currency { Name Symbol SmartContract } Receiver Sender } } } } ``` To get all transfers of on GRA.fun, please check [this query](https://ide.bitquery.io/gra-fun-all-transfers). ## Trades of a token on pancake v3 Use this API to get Pancake V3 APIs using [this api](https://ide.bitquery.io/Trades-of-token-on-pancake-v3) ```graphql { EVM(dataset: archive, network: bsc) { DEXTrades( orderBy: {descending: Block_Time} limit: {count: 100} where: {Block: {Date: {since: "2024-08-01"}}, any: [{Trade: {Buy: {Currency: {SmartContract: {is: "0xcac007926755e2675e201223f7d4d68c74fd3439"}}}}}, {Trade: {Sell: {Currency: {SmartContract: {is: "0xcac007926755e2675e201223f7d4d68c74fd3439"}}}}}]} ) { Trade { Dex { SmartContract ProtocolName ProtocolVersion } Buy { Amount AmountInUSD Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } Sell { Amount AmountInUSD Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } } } } } ``` ## First trade of a token on pancake v3 Get 1st trade of token on Pancake v3 using [this api](https://ide.bitquery.io/Trades-of-token-on-pancake-v3_5). ```graphql { EVM(dataset: combined, network: bsc) { DEXTrades( orderBy: [{ascending: Block_Time}{ascending:Transaction_Index}] limit: {count: 1} where: {Block: {Date: {since: "2024-07-01"}}, any: [{Trade: {Buy: {Currency: {SmartContract: {is: "0xcac007926755e2675e201223f7d4d68c74fd3439"}}}}}, {Trade: {Sell: {Currency: {SmartContract: {is: "0xcac007926755e2675e201223f7d4d68c74fd3439"}}}}}]} ) { Trade { Dex { SmartContract ProtocolName ProtocolVersion } Buy { Amount AmountInUSD Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } Sell { Amount AmountInUSD Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } } } } } ``` --- ## BNB Chain Liquidity API: PancakeSwap Pool Reserves in Real Time URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-liquidity-api/ BNB Chain pool reserves and spot prices with Bitquery GraphQL: PancakeSwap v2, v3 and Infinity pools, one pool now or streamed, every pool holding CAKE. # BNB Chain Liquidity API: PancakeSwap Pool Reserves in Real Time The `DEXPoolEvents` cube under `EVM(network: bsc)` emits one row every time a pool's reserves change, whether by a swap, a deposit or a withdrawal. Each row carries the reserves of both tokens after the change, in token units and in USD, the spot price in both directions, the pool and its protocol, and the transaction that moved it. BNB Chain is PancakeSwap territory, and the cube reports its three pool types under their own names: v2 pairs as `uniswap_v2`, the name shared by every Uniswap v2 fork, v3 pools as `pancake_swap_v3`, and Infinity pools as `pancakeswap_infinity`, alongside `uniswap_v3` and `uniswap_v4` pools. The cube holds the recent realtime window only and has no archive dataset: to keep a history, record the stream. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked pool is the PancakeSwap v3 USDT/WBNB pool, `0x172fcd41e0913e95784454622d1c3724f546f849`, the busiest pool on the chain. ## What the pool holds right now Ten rows, newest first, each a snapshot taken after one change. Read `AmountCurrencyA` and `AmountCurrencyB` for the two reserves, their `InUSD` twins for the dollar value, and `AtoBPrice` for the spot rate of A in B at that moment. Saved query [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_2). ```graphql { EVM(network: bsc) { DEXPoolEvents( limit: { count: 10 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { SmartContract: { is: "0x172fcd41e0913e95784454622d1c3724f546f849" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Dex { ProtocolName } } Transaction { Hash } } } } ``` ## Follow the pool as it moves Subscribe with the same pool filter and a row arrives on every reserve change; on this pool that is many rows a second, so batch them on your side. Saved stream [here](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_1). ```graphql subscription { EVM(network: bsc) { DEXPoolEvents( where: { PoolEvent: { Pool: { SmartContract: { is: "0x172fcd41e0913e95784454622d1c3724f546f849" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { SmartContract CurrencyA { Symbol } CurrencyB { Symbol } } } Transaction { Hash } } } } ``` ## Every PancakeSwap Infinity pool Infinity pools live inside one manager contract, like Uniswap v4, so `Pool.SmartContract` repeats on every row and `Pool.PoolId` identifies the pool. Filter on the protocol name to follow all of them; swap in `uniswap_v4` for the Uniswap v4 pools on BNB Chain. Saved stream [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4). ```graphql subscription { EVM(network: bsc) { DEXPoolEvents( where: { PoolEvent: { Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } } ) { Block { Time } PoolEvent { Pool { PoolId SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } Transaction { Hash } } } } ``` ## Where a token sits To see every pool that holds CAKE, `0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82`, keep the newest row per pool with `limitBy` and ask for pools that list CAKE as `CurrencyA` inside the window; a second run with CAKE under `CurrencyB` catches the pools that list it second. The PancakeSwap v2 CAKE/WBNB pair comes out on top by a wide margin. Rank the rows by the USD reserve in your code. Saved query [here](https://ide.bitquery.io/Realtime-Liquidity-Stream_2). ```graphql { EVM(network: bsc) { DEXPoolEvents( limit: { count: 20 } limitBy: { by: PoolEvent_Pool_SmartContract, count: 1 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { CurrencyA: { SmartContract: { is: "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time } PoolEvent { Dex { ProtocolName } Pool { SmartContract PoolId CurrencyB { Symbol SmartContract } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } } } } } ``` ## How to read a row - Reserves after the change: `Liquidity.AmountCurrencyA` and `AmountCurrencyB` in token units, `AmountCurrencyAInUSD` and `AmountCurrencyBInUSD` in dollars. - Spot rate after the change: `AtoBPrice` and `BtoAPrice`. - Which pool: `Pool.SmartContract` for v2 and v3 pools; for Infinity and Uniswap v4 the manager address plus `Pool.PoolId`. - Which protocol: `Dex.ProtocolName`, one of `uniswap_v2` (every v2 fork, PancakeSwap v2 included), `pancake_swap_v3`, `pancakeswap_infinity`, `uniswap_v3` or `uniswap_v4`. - Which transaction: `Transaction.Hash`. ## Kafka instead of WebSocket The `bsc.dexpools.proto` topic delivers these rows as protobuf messages, which is the better fit for BNB Chain's volume: no socket to keep alive and consumers can be scaled out. Kafka credentials are separate from the IDE token; the [Kafka streams hub](/docs/category/kafka-streams) explains how to get them. ## Related pages - [BNB Chain DEX trades API](/docs/blockchain/BSC/bsc-dextrades) - [PancakeSwap Infinity API](/docs/blockchain/BSC/bsc-pancakeswap-infinity-api) - [DEXPools cube](/docs/cubes/evm-dexpool/) - [Arbitrum liquidity API](/docs/blockchain/Arbitrum/arbitrum-liquidity-api) - [Base liquidity API](/docs/blockchain/Base/base-liquidity-api) --- ## BNB Chain NFT API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-nft/ Track BNB Chain NFT trades, ownership, and metadata with Bitquery GraphQL queries, filters, and real-time streaming options. # BSC NFT API In this section we'll have a look at some examples using the BSC NFT API. ## Track Transfers of a specific NFT on BSC in Realtime This query subscribes you to the real time non-fungible token (NFT) transfers of a specific nft contract on the BSC network. You can find the query [here](https://ide.bitquery.io/Track-realtime-NFT-Transfers-of-a-specific-NFT-on-BSC-chain) ```graphql subscription { EVM(network: bsc) { Transfers( where: {Transfer: {Currency: {Fungible: false, SmartContract: {is: "0x3d2c83bbbbfb54087d46b80585253077509c21ae"}}}} ) { Block { Hash Number } Transfer { Amount Currency { Name SmartContract Symbol Native } Sender Receiver } } } } ``` --- ## BNB Chain Pancake Swap API URL: https://docs.bitquery.io/docs/blockchain/BSC/pancake-swap-api/ Query and stream PancakeSwap trades on BNB Chain with Bitquery GraphQL: latest swaps, live subscriptions, token prices, OHLC and trader activity. # Pancake Swap API For coverage, plans and streaming options on BNB Chain, see the [Binance Smart Chain API](https://bitquery.io/products/binance-smart-chain-api-post) page. :::tip Need real-time PancakeSwap data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview): [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered PancakeSwap swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use the `EVM` queries on this page for raw per-swap detail or call and event context. An `EVM` query without a `dataset` argument runs on the realtime dataset, which holds only the last few days; add `dataset: combined` or `dataset: archive` for **historical PancakeSwap data**. ::: In this section we will use APIs from Bitquery to get the on-chain trade related data, trade metrics, trades for a token or a trader on the Pancake Swap DEX. To get the trade activities of the Pancake Swap exclusively we have added a filter out trades based on `Factory Contract` address, `0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865` for the case of Pancake Swap V3. To get the trades and trade related data for Pancake Swap V1 or V2 you would need their respective addresses. Create your account and get started by following the [Quickstart instructions](/docs/start/first-query/). ## Bitquery DEX Data Access Options - **GraphQL APIs**: Query historical and real-time EVM data with flexible filtering and aggregation - **Real-time Streams**: Subscribe to live EVM blockchain events via WebSocket subscriptions - **Data Store exports**: parsed Parquet you download from S3 or Cloudflare R2; custom exports can go to your own bucket or warehouse. See the [Bitquery Data Store](https://bitquery.io/datastore). - **Kafka Streams**: High-throughput data streaming for enterprise applications ## Getting Started with Bitquery: - [BSC DEX Trades](/docs/blockchain/BSC/bsc-dextrades/): Real time DEX Trading data via examples. - [BSC Uniswap APIs](/docs/blockchain/BSC/bsc-uniswap-api/): Uniswap Trades on BSC network with the help of examples. - [BSC Four Meme APIs](/docs/blockchain/BSC/four-meme-api/): Four Meme Trades on BSC network with the help of examples. - [Trade APIs](/docs/trading/crypto-price-api/examples/): Multi-chain Trade API Examples. ## Get Latest Trades on Pancake Swap This API returns the [most recent trades on PancakeSwap v3](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades).
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: bsc) { DEXTrades( orderBy: [ { descending: Block_Time } { descending: Transaction_Index } { descending: Trade_Index } ] where: { TransactionStatus: { Success: true } Trade: { Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } } } limit: { count: 20 } ) { Block { Time Number } Receipt { ContractAddress Status } TransactionStatus { Success } Log { Signature { Name } SmartContract } Call { From InternalCalls Signature { Name Signature } To Value } Transaction { Value ValueInUSD Hash From To } Trade { Buy { Amount AmountInUSD Buyer Seller Currency { Decimals Name Symbol SmartContract } Price PriceInUSD } Sell { Amount AmountInUSD Buyer Seller Currency { Name Symbol SmartContract } Price PriceInUSD } Dex { ProtocolName SmartContract OwnerAddress } } } } } ```
## Streaming Latest Trades on Pancake Swap This subscription [streams the latest trades on PancakeSwap v3](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades---Stream_2).
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { DEXTrades( where: { TransactionStatus: { Success: true } Trade: { Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } } } ) { Block { Time Number } Receipt { ContractAddress Status } TransactionStatus { Success } Log { Signature { Name } SmartContract } Call { From InternalCalls Signature { Name Signature } To Value } Transaction { Value ValueInUSD Hash From To } Trade { Buy { Amount AmountInUSD Buyer Seller Currency { Decimals Name Symbol SmartContract } Price PriceInUSD } Sell { Amount AmountInUSD Buyer Seller Currency { Name Symbol SmartContract } Price PriceInUSD } Dex { ProtocolName SmartContract OwnerAddress } } } } } ```
## Subscribe to Mempool Trades on Pancake Swap This subscription [streams PancakeSwap v3 trades from the mempool](https://ide.bitquery.io/Mempool---Latest-BSC-PancakeSwap-v3-dextrades---Stream_1), before they are confirmed.
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades( where: { TransactionStatus: { Success: true } Trade: { Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } } } ) { Block { Time Number } Receipt { ContractAddress Status } TransactionStatus { Success } Log { Signature { Name } SmartContract } Call { From InternalCalls Signature { Name Signature } To Value } Transaction { Value ValueInUSD Hash From To } Trade { Buy { Amount AmountInUSD Buyer Seller Currency { Decimals Name Symbol SmartContract } Price PriceInUSD } Sell { Amount AmountInUSD Buyer Seller Currency { Name Symbol SmartContract } Price PriceInUSD } Dex { ProtocolName SmartContract OwnerAddress } } } } } ```
## Latest Trades of a Token on Pancake Swap This returns the [latest trades of one token on PancakeSwap v3](https://ide.bitquery.io/BSC-PancakeSwap-v3-Trades-for-a-token), CAKE (`0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82`) in this example. You can also [stream the same trades live](https://ide.bitquery.io/Stream---BSC-PancakeSwap-v3-Trades-for-a-token).
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: bsc) { DEXTradeByTokens( limit: { count: 20 } orderBy: [ { descending: Block_Time } { descending: Transaction_Index } { descending: Trade_Index } ] where: { Trade: { Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } Currency: { SmartContract: { is: "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } } } ) { Block { Time Number } TransactionStatus { Success } Log { Signature { Name Signature } SmartContract } Receipt { ContractAddress } Call { From Gas GasUsed InternalCalls Signature { Name Signature } To Value } Trade { Amount AmountInUSD Buyer Price PriceInUSD Buyer Seller Sender Success URIs Fees { Amount AmountInUSD Payer Recipient } Dex { ProtocolName ProtocolFamily } Currency { Name Symbol SmartContract } Side { Amount AmountInUSD Buyer Currency { Name Symbol SmartContract } Ids OrderId Seller Type URIs } } Transaction { Hash From To } } } } ```
Also, checkout the [Four Meme](/docs/blockchain/BSC/four-meme-api/) documentation for APIs related to Four Meme tokens and Four Meme Exchange. ## Get Top Traders of a Token on Pancake Swap Returns the [top 100 traders of CAKE on PancakeSwap v3](https://ide.bitquery.io/top-traders-of-a-token-on-pancakeswap-bsc) by USD volume. It ranks `Transaction.From`, the account that sent each swap, since on a sale `Trade.Buyer` is the pool or a router. `Side.Type` describes the counter-side of each trade, so `bought` sums the rows where `Side.Type` is `sell`. `PriceAsymmetry: { lt: 0.1 }` leaves out trades whose two sides disagree on value ([PriceAsymmetry reference](/docs/graphql/metrics/priceAsymmetry/)). > Note: This queries the `realtime` database by default. To query `archive` data, change the `dataset` parameter and add a date period as a filter
Click to expand GraphQL query ```graphql { EVM(network: bsc) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Currency: { SmartContract: { is: "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } PriceAsymmetry: { lt: 0.1 } } } ) { Transaction { From } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) sold: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ```
## Get Trading Volume, Buy Volume, Sell Volume of a Token Returns the [traded, buy and sell volume of CAKE](https://ide.bitquery.io/trade_volume_bsc_pancakeswap) on PancakeSwap v3 over the last 24 hours. `PriceAsymmetry: { lt: 0.1 }` drops mispriced trades, which would otherwise skew the USD sums.
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } PriceAsymmetry: { lt: 0.1 } } TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract Decimals } } traded_volume_in_usd: sum(of: Trade_Side_AmountInUSD) sell_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ```
## Get Metadata of a Token Returns a [token's metadata](https://ide.bitquery.io/get-metadata-pancakeswap): `Name`, `Symbol`, `SmartContract` and `Decimals`.
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { SmartContract: { is: "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } } } ) { Trade { Currency { Name Symbol SmartContract ProtocolName HasURI Fungible Decimals } } } } } ```
## OHLC of a Token on Pancake Swap This returns [OHLC (K-line) data for one token against another](https://ide.bitquery.io/bsc-pancakeswap-ohlc-using-trading-api). This query uses the `Trading` cube from the [Crypto Price APIs](/docs/trading/crypto-price-api/)
Click to expand GraphQL query ```graphql { Trading(dataset: realtime) { Pairs( where: { Price: { IsQuotedInUsd: false } Interval: { Time: { Duration: { eq: 1 } } } Currency: { Id: { is: "bid:eth" } } QuoteCurrency: { Id: { is: "usdc" } } Market: { Protocol: { is: "pancake_swap_v3" } } } limit: { count: 10 } orderBy: { descending: Interval_Time_End } ) { Token { Id Symbol Address NetworkBid Network Name } QuoteToken { Id Symbol Address Name NetworkBid } Interval { Time { Start End Duration } } Volume { Usd Quote Base } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ```
## Price Change Percentage for a Token on Pancake Swap This returns the [price change percentage of a PancakeSwap token](https://ide.bitquery.io/Percentage-price-change-for-a-pancake-swap-token) over `24hr`, `1hr` and `5 min`, using the [calculate expression](/docs/graphql/capabilities/expression/) feature.
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } } Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract } price_24hr: PriceInUSD(minimum: Block_Time) price_1hr: PriceInUSD( if: { Block: { Time: { is_relative: { hours_ago: 1 } } } } ) price_5min: PriceInUSD( if: { Block: { Time: { is_relative: { minutes_ago: 1 } } } } ) current: PriceInUSD } change_24hr: calculate( expression: "( $Trade_current - $Trade_price_24hr ) / $Trade_price_24hr * 100" ) change_1hr: calculate( expression: "( $Trade_current - $Trade_price_1hr ) / $Trade_price_1hr * 100" ) change_5min: calculate( expression: "( $Trade_current - $Trade_price_5min ) / $Trade_price_5min * 100" ) } } } ``` ```json { "currency": "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } ```
## New Liquidity Pools Created on Pancake Swap This returns the [latest pool creation events on PancakeSwap v3](https://ide.bitquery.io/New-pools-created-on-PancakeSwap-v3). You can also [stream new pools as they are created](https://ide.bitquery.io/Stream---New-pools-created-on-PancakeSwap-v3). To make sure that we are only getting newly created liquidity pools on Pancake Swap, we are applying the conditon that the `LogHeader` is `0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865`.
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: bsc) { Events( orderBy: [ { descending: Block_Time } { descending: Transaction_Index } { descending: Log_Index } ] where: { LogHeader: { Address: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } Log: { Signature: { Name: { is: "PoolCreated" } } } } ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ```
## Subscribe the Liquidity Addition Event on Pancake Swap Liquidity addition is an important event related to any liquidity pool. This subscription [streams liquidity additions to PancakeSwap v3 pools](https://ide.bitquery.io/Stream---Liqiidity-add-for-all-tokens-on-PancakeSwap-v3) in real time. To make sure that we are only getting liquidity addition events for Pancake Swap we are placing condition that the transaction is sent to `0x46A15B0b27311cedF172AB29E4f4766fbE7F4364` address.
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { Events( orderBy: [ { descending: Block_Time } { descending: Transaction_Index } { descending: Log_Index } ] where: { Log: { Signature: { Name: { is: "Mint" } } } Transaction: { To: { is: "0x46A15B0b27311cedF172AB29E4f4766fbE7F4364" } } } ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ```
## Subscribe the Liquidity Removal Event on Pancake Swap This subscription [streams liquidity removals from PancakeSwap v3 pools](https://ide.bitquery.io/Stream---Liquidity-remove-for-all-tokens-on-PancakeSwap-v3).
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { Events( orderBy: [ { descending: Block_Time } { descending: Transaction_Index } { descending: Log_Index } ] where: { Log: { Signature: { Name: { is: "Burn" } } } Transaction: { To: { is: "0x46A15B0b27311cedF172AB29E4f4766fbE7F4364" } } } ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ```
## Get the Latest Pool Reserves for a Pair on Pancake Swap This returns the latest reserves of one PancakeSwap v3 pool, given its address (`0xafb2da14056725e3ba3a30dd846b6bbbd7886c56` in this example).
Click to expand GraphQL query ```graphql { EVM(dataset: combined, network: bsc) { Balances( where: { Currency: { SmartContract: { in: [ "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" ] } } Balance: { Address: { is: "0xafb2da14056725e3ba3a30dd846b6bbbd7886c56" } } } ) { Balance { Amount(selectWhere: { gt: "0" }) } Currency { Name Symbol SmartContract Decimals } } } } ```
## All Pairs of a Token on Pancake Swap This returns [every pair of a token on PancakeSwap v3](https://ide.bitquery.io/All-pools-of-a-token-on-pancake-swap_2). The result contains info of the liquidity pool such as currency details, trade amount, number of trades and price of token in USD in various time frames.
Click to expand GraphQL query ```graphql query pairDexList( $network: evm_network $base: String $time_10min_ago: DateTime $time_1h_ago: DateTime $time_3h_ago: DateTime $time_ago: DateTime $owner: String ) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "amount" } where: { TransactionStatus: { Success: true } Trade: { Currency: { SmartContract: { is: $base } } Side: { Amount: { gt: "0" } } Dex: { OwnerAddress: { is: $owner } } } Block: { Time: { after: $time_ago } } } ) { Trade { Currency { Name SmartContract } Side { Currency { Name SmartContract } } Dex { SmartContract } price_last: PriceInUSD(maximum: Block_Number) price_10min_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_10min_ago } } } ) price_1h_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_1h_ago } } } ) price_3h_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_3h_ago } } } ) } amount: sum(of: Trade_Side_AmountInUSD) trades: count } } } ``` ```json { "network": "bsc", "owner": "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865", "base": "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82", "time_10min_ago": "2025-04-10T09:03:33Z", "time_1h_ago": "2025-04-10T08:13:33Z", "time_3h_ago": "2025-04-10T06:13:33Z", "time_ago": "2025-04-07T09:13:33Z" } ```
## Video Tutorials ### Get Pancakeswap Token Trade Metrics using Bitquery API ### How to get PancakeSwap trades in realtime --- ## BNB Chain Slippage API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-slippage-api/ BNB Chain Slippage API: measure BNB Chain DEX price impact and slippage with Bitquery GraphQL pool metrics. Covers archive history and realtime data. # BSC Slippage API In this section we will see how to get BSC DEX pool slippage information using our API. The slippage API helps you understand price impact and liquidity depth for token swaps on BSC DEX pools. ## Understanding Slippage and Price Impact Slippage refers to the difference between the expected price of a trade and the actual execution price. When swapping tokens in a DEX pool, larger trades can move the price due to limited liquidity, resulting in slippage. The DEXPoolSlippages API provides detailed information about: - Maximum input amounts that can be swapped at different slippage tolerances - Minimum output amounts guaranteed at each slippage level - Average execution prices for different trade sizes - Price impact calculations for both swap directions (A to B and B to A) For a comprehensive explanation of how DEX pools work, liquidity calculations, and price tables, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/). ## Realtime Slippage Monitoring This subscription query returns real-time slippage data for all DEX pools on BSC. You can monitor price impact and liquidity depth as trades occur. You can find the query [here](https://ide.bitquery.io/realtime-slippage-on-bsc) ```graphql subscription { EVM(network: bsc) { DEXPoolSlippages { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` ## Latest Slippage for a Specific Pool This query retrieves the latest slippage data for a specific DEX pool on BSC. Use this to check current liquidity depth and price impact for a particular token pair. You can find the query [here](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Pancakeswap) ```graphql query { EVM(network: bsc) { DEXPoolSlippages( where: {Price: {Pool: {SmartContract: {is: "0x42161084d0672e1d3f26a9b53e653be2084ff19c"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` > **Note:** This query can be converted to a subscription to monitor in real-time. Simply replace `query` with `subscription` to receive live updates whenever the pool's liquidity changes. ## Realtime Slippage Data via Kafka Streams Slippage data can also be obtained via Kafka streams for lower latency and better reliability. The Kafka topic for BSC DEX pools is: **`bsc.dexpools.proto`** Kafka streams provide the same slippage data as GraphQL subscriptions but with several advantages: - Lower latency due to shorter data pipeline - Better reliability with persistent connections - Ability to read from latest offset without gaps - Better scalability with multiple consumers For detailed information on how to connect to Kafka streams, subscribe to topics, and parse messages, refer to the [Kafka Streaming Concepts documentation](/docs/streams/kafka-streaming-concepts/). > **Note:** IDE credentials will not work with Kafka Streams. You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## Understanding the Response The `DEXPoolSlippages` API response contains the following information: - **`Price`**: Price information for swaps at a specific slippage tolerance - **`AtoB`**: Price data for swapping CurrencyA to CurrencyB - `Price`: Average execution price for swaps at this slippage level - `MinAmountOut`: Minimum output amount guaranteed at this slippage level - `MaxAmountIn`: Maximum input amount that can be swapped at this slippage level - **`BtoA`**: Price data for swapping CurrencyB to CurrencyA (same structure as AtoB) - **`SlippageBasisPoints`**: Slippage tolerance in basis points (100 = 1%) - **`Pool`**: Pool information including token pair details - **`Dex`**: DEX protocol information (Uniswap V2, V3, V4, etc.) - **`Block`**: Block information when the slippage data was recorded - `Time`: Timestamp of the block - `Number`: Block number For more details on how slippage is calculated and when new pool records are emitted, see the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#when-is-a-new-dexpool-record-emitted-in-the-apis--streams). ## Use Cases ### Liquidity Depth Analysis Use the slippage API to analyze which pools can handle large trades without significant price impact. By examining `MaxAmountIn` values at different slippage levels, you can: - Identify pools with sufficient liquidity for your trade size - Determine optimal slippage tolerance settings - Estimate price impact before executing trades ### Multi-Pool Price Comparison Compare execution prices across different pools and slippage scenarios to: - Find the best pool for your specific trade size - Understand price differences between DEX protocols - Optimize trade execution strategies ### Trading Applications #### Live Execution Testing Use the slippage API to test and validate trade execution strategies in real-time: - **Pre-trade validation**: Check if your intended trade size can be executed within acceptable slippage bounds before submitting - **Execution simulation**: Calculate expected price impact and minimum output amounts for different trade sizes - **Strategy backtesting**: Monitor historical slippage data to validate trading algorithms and optimize entry/exit points - **Risk assessment**: Evaluate maximum position sizes that can be entered without exceeding your slippage tolerance #### Detecting Liquidity Shocks and Toxic Order Flow The slippage API helps identify temporary price dislocations and liquidity shocks that can be exploited or avoided: - **Flow toxicity detection**: Monitor sudden changes in `MaxAmountIn` values to detect when pools experience large outflows or inflows - **Price impact analysis**: Track how `MinAmountOut` changes relative to `MaxAmountIn` to identify when pools become less liquid - **Mean reversion opportunities**: Identify pools where large swaps have created temporary price dislocations that may revert - **Toxic order flow avoidance**: Use slippage data to avoid entering positions when liquidity is thin or when large trades are likely to move price against you For a practical implementation example of using slippage data for automated trading strategies, including flow toxicity detection and mean-reversion trading, see the [AMM Flow Toxicity Alpha Engine](https://github.com/Divyn/amm-flow-toxicity-alpha-engine) repository. This system demonstrates how to: - Detect large swaps that move price significantly (50-500 basis points) - Verify isolation from trending markets - Execute fade trades against temporary price impacts - Manage positions with dynamic stop losses and take profits based on slippage data For more advanced use cases, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#advanced-use-cases-and-processing-patterns). --- ## BNB Chain Transfers API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-transfers/ BNB Chain Transfers API: monitor BNB Chain native and token transfers in real time with Bitquery GraphQL APIs. Includes filters and field selection tips. # BSC Transfers API In this section we'll have a look at some examples using the BSC Transfers API. ## Subscribe to Recent Whale Transactions of a particular currency The subscription query below fetches the whale transactions on the BSC network. We have used WBNB address `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c`. You can find the query [here](https://ide.bitquery.io/Whale-transfers-of-USDC-on-BSC) ```graphql subscription{ EVM(network: bsc) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}}, Amount: {ge: "10000"}}} ) { Transaction { From Hash } Transfer { Amount Sender Receiver Currency { SmartContract Symbol Name Fungible Native } Id } } } } ``` ## Sender is a particular address This websocket retrieves transfers where the sender is a particular address `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c`. For this subscription query we use `where` keyword and in that we specify `{Transfer: {Sender: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}}}` to get the desired data. You can find the query [here](https://ide.bitquery.io/Transfers-where-sender-is-a-particular-address) ```graphql subscription { EVM(network: bsc) { Transfers( where: {Transfer: {Sender: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}}} ) { Transfer { Amount AmountInUSD Currency { Name SmartContract Native Symbol Fungible } Receiver Sender } Transaction { Hash } } } } ``` ## Transactions From/To An Address with Transfer Details [Run Query](https://ide.bitquery.io/Sender-OR-Receiver-Transfer-Example-BSC) ```graphql query MyQuery { EVM(dataset: archive, network: bsc) { Transfers( where: {any: [{Transaction: {From: {is: "0x2b9dfb290ad7b54a5b86da25c3a629bfc7152167"}}}, {Transaction: {To: {is: "0x2b9dfb290ad7b54a5b86da25c3a629bfc7152167"}}}], Transfer: {}, Block: {Date: {since: "2025-08-10", till: "2025-08-29"}}} limit: {count: 10000} orderBy: {descending: Block_Time} ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol Name } Index } Transaction { Hash } Block { Number Time } } } } ``` ## Subscribe to the latest NFT token transfers on BSC Let's see an example of NFT token transfers using GraphQL Subscription (Webhook). In the following NFT Token Transfers API, we will be subscribing to all NFT token transfers on BSC network. You can run the query [here](https://ide.bitquery.io/Track-realtime-NFT-Transfers-on-BSC-chain) ```graphql subscription { EVM(network: bsc) { Transfers( where: { Transfer: { Currency: { Fungible: false } } } ) { Block { Hash Number } Transfer { Amount Currency { Name SmartContract Symbol Native } Sender Receiver } } } } ``` ## Check if an address ever interacted with predict.fun (USDT → protocol receivers) Predict.fun flows on BSC often show up as USDT (`0x55d398326f99059fF775485246999027B3197955`) transfers **from** the user's wallet **to** one of the protocol contract addresses listed below. `limit: { count: 1 }` is enough for a historic “has this wallet interacted?” probe. **Try it:** [IDE — predict.fun interaction check](https://ide.bitquery.io/check-if-an-address-interacted-with-predictfun-ever) ```graphql query ($address: String) { EVM(dataset: realtime, network: bsc) { Transfers( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Transfer: { Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } Sender: { is: $address } Receiver: { in: [ "0x8BC070BEdAB741406F4B1Eb65A72bee27894B689" "0x6bEb5a40C032AFc305961162d8204CDA16DECFa5" "0x365fb81bd4A24D6303cd2F19c349dE6894D8d58A" "0x8A289d458f5a134bA40015085a8F50Ffb681B41d" "0xF1f8F5C641F20C48526269EF7DFF19172Efa9783" "0xFbC2259aBB3F01c019ECE1d0200Ee673BB7BA34F" "0xF2311C668aAA8dEc48D5da577d3018eb94b3132F" "0xD172f3FBabe763Ee8E52D8b32421574236dA6057" ] } } } ) { Block { Time } Transaction { Hash } Transfer { Sender Receiver Amount } } } } ``` **Variables:** ```json { "address": "0x75b976434245E1Fc037f9c7645C5aCdDdA6b00A4" } ``` ## Deterministic Pagination for Backfilling Transfers When backfilling BSC transfer data or building a historical index, use deterministic pagination to guarantee no records are missed or duplicated. **Try it live:** [Deterministic Transfer API](https://ide.bitquery.io/Reliable-transfer-api) ```graphql { EVM(dataset: combined, network: bsc) { Transfers( where: { Transfer: { Success: true } } orderBy: { ascending: [ Block_Number, Transaction_Index, Call_Index, Log_Index, Transfer_Index, Transfer_Type ] } limit: { count: 10, offset: 0 } ) { Block { Time Number } Transaction { Hash From Index } Transfer { Amount AmountInUSD Sender Receiver Index Currency { Symbol Name SmartContract Decimals Native } } Call { Index } Log { LogAfterCallIndex Index } Transfer { Type } } } } ``` The composite `orderBy` across `Block_Number`, `Transaction_Index`, `Call_Index`, `Log_Index`, `Transfer_Index`, and `Transfer_Type` uniquely positions every transfer, making offset-based pagination safe for backfilling. Increment `offset` by the `count` value on each request. You can pull up to **25,000 records in a single request** by setting `count: 25000`. ## Why does my wallet inflow/outflow query miss some transactions on BSC? {#why-does-my-wallet-inflowoutflow-query-miss-some-transactions-on-bsc} Bitquery indexes all transactions from the blockchain. If you're missing inflow/outflow records in your query, first verify you're using the correct dataset—either `realtime` or `combined`—based on your needs. If your query still appears to miss transactions, please report the issue to the Bitquery team via [Telegram](https://t.me/bloxy_info). --- ## BNB Chain Uniswap API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-uniswap-api/ BNB Chain Uniswap API: GraphQL examples for v3 trades, top traders, hourly OHLC, 24-hour volume and top tokens, filtered to Uniswap's own factory. Most uniswap_v2 trades there are PancakeSwap V2. # BSC Uniswap API :::tip Real-time data or the last 30 days? Use the Trading cube For real-time trades and anything from the last 30 days, use the [Trading cube](/docs/trading/trading-data-overview): [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns MEV-filtered swaps with a USD price on every row. Use the `EVM` queries on this page for raw per-swap detail or call and event context. An `EVM` query without a `dataset` argument runs on the realtime dataset, which holds only the last few days; add `dataset: combined` or `dataset: archive` for older history. ::: ## Filter by factory to exclude forks `Trade.Dex.ProtocolName` records which code a pool runs. Forks of v2 and v3 run the same code, so their trades carry the same `uniswap_v2` and `uniswap_v3` labels. On BNB Chain the forks dominate. In Bitquery's trade data for 17 and 18 September 2026, more than 99% of transactions labelled `uniswap_v2` went through other factories' pools, about 96% through PancakeSwap V2 alone. For `uniswap_v3` the share was more than a quarter. To keep only Uniswap's own pools, filter on the contract that owns them, as every example on this page now does. | Version | Filter field | Address on BNB Chain | | --- | --- | --- | | v2 | `Trade.Dex.OwnerAddress` | `0x8909dc15e40173ff4699343b6eb8132c65e18ec6` | | v3 | `Trade.Dex.OwnerAddress` | `0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7` | | v4 | `Trade.Dex.SmartContract` | `0x28e2ea090877bf75740558f6bfb36a5ffee9e9df` | `OwnerAddress` is the factory that deployed the pool. A v4 pool has no factory: its `OwnerAddress` is the zero address, and the PoolManager is its `SmartContract`. In the Trading cube, filter `Pair.Market.Address` to the v2 or v3 factory, or `Pair.Market.Program` to the v4 PoolManager. Addresses are from the official [deployments list](https://developers.uniswap.org/deployments). The link in each example's description opens an earlier copy saved in the Bitquery IDE, which may still filter by `ProtocolName` or use older conditions and time windows. Use the code on this page when you need Uniswap's own pools only. ## Live Uniswap v3 Trades on BSC (Trading API, recommended) This subscription streams every Uniswap v3 trade on BSC in real time with **USD price and USD amounts on every row**, MEV-filtered. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Uniswap-v3-Trades-BSC). ```graphql subscription { Trading { Trades( where: {Pair: {Market: {Network: {is: "Binance Smart Chain"}, Address: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}}} ) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` ## Get Latest Trades on Uniswap v3 The query below returns the [latest DEX trades on BSC Uniswap v3](https://ide.bitquery.io/uniswap-v3-trades-bsc). ```graphql query MyQuery { EVM(dataset: realtime, network: bsc) { DEXTrades( where: {Trade: {Dex: {OwnerAddress: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}}} limit: {count: 10} orderBy:{descending:Block_Time} ) { Transaction { From To } Trade { Dex { ProtocolName SmartContract } Buy { Currency { Name } Price Amount } Sell { Amount Currency { Name } Price } } Block { Time } } } } ``` ## Get Top Traders of a token on uniswap v3 This query returns the [top traders of a token](https://ide.bitquery.io/top-traders-of-a-token-on-uniswapv3-bsc) on the selected network. It ranks `Transaction.From`, the account that sent each swap, since on a sale `Trade.Buyer` is the pool or a router. `Side.Type` describes the counter-side of each trade, so `bought` sums the rows where `Side.Type` is `sell`. `PriceAsymmetry: {lt: 0.1}` drops trades whose two sides disagree badly on value ([PriceAsymmetry reference](/docs/graphql/metrics/priceAsymmetry/)), which would otherwise inflate the USD totals. ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}, Dex: {OwnerAddress: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}, PriceAsymmetry: {lt: 0.1}}} ) { Transaction { From } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "bsc", "token": "0x55d398326f99059ff775485246999027b3197955" } ``` ## OHLC in USD of a Token This query retrieves [hourly open, high, low and close prices in USD](https://ide.bitquery.io/OHLC-on-BSC-Uniswap-v3) for one token traded on Uniswap v3. ```graphql { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( orderBy: {descendingByField: "Block_testfield"} where: {Trade: {Currency: {SmartContract: {is: "0x55d398326f99059ff775485246999027b3197955"}}, PriceAsymmetry: {lt: 0.1}, Dex: {OwnerAddress: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}, Side: {Currency: {SmartContract: {is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"}}, Type: {is: buy}}}} limit: {count: 10} ) { Block { testfield: Time(interval: {in: hours, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) } count } } } ``` ## Get trading volume, buy volume, sell volume of a token This query returns the [traded, buy and sell volume](https://ide.bitquery.io/trade_volume_bsc_uniswapv3) of token `0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c` on Uniswap v3 over the last 24 hours. `PriceAsymmetry: {lt: 0.1}` drops mispriced trades, which would otherwise skew the USD sums. ```graphql query MyQuery { EVM(network: bsc) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"}}, Dex: {OwnerAddress: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}, PriceAsymmetry: {lt: 0.1}}, TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Trade { Currency { Name Symbol SmartContract Decimals } } traded_volume_in_usd: sum(of: Trade_Side_AmountInUSD) sell_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) buy_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) } } } ``` ## Get top bought tokens on uniswap v3 This query returns the [top bought tokens on Uniswap v3](https://ide.bitquery.io/top-bought-tokens-on-bsc-uniswap-v3). Buys are the rows where `Side.Type`, the counter-side, is `sell`. The `PriceAsymmetry` filter keeps mispriced trades out of the totals. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {OwnerAddress: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "bsc" } ``` ## Get top sold tokens on uniswap v3 This query returns the [top sold tokens on Uniswap v3](https://ide.bitquery.io/top-sold-tokens-on-bsc-uniswap-v3). Sales are the rows where `Side.Type`, the counter-side, is `buy`. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {OwnerAddress: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "bsc" } ``` ## Get Metadata of a token The query below returns a [token's metadata](https://ide.bitquery.io/get-metadata_1): `Name`, `symbol`, `SmartContract Address` and `Decimals`. ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Currency: {SmartContract: {is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"}}, Dex: {OwnerAddress: {is: "0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7"}}}} ) { Trade { Currency { Name Symbol SmartContract ProtocolName HasURI Fungible Decimals } } } } } ``` --- ## BNB Chain Uniswap v4 API: Stablecoin Pools, Swaps, Traders and Reserves URL: https://docs.bitquery.io/docs/blockchain/BSC/uniswap-v4-api/ Uniswap v4 on BNB Chain with Bitquery GraphQL: live swaps, the v4 pools of USDT by PoolId, the USDT/USDC pool's daily stats, top traders and reserves. # BNB Chain Uniswap v4 API: Stablecoin Pools, Swaps, Traders and Reserves On BNB Chain, Uniswap v4 is above all a stablecoin venue: the USDT/USDC pools inside its PoolManager, `0x28e2ea090877bf75740558f6bfb36a5ffee9e9df`, turn over tens of millions of dollars a day, while meme launches route a long tail of smaller pools through the same contract. Because v4 keeps every pool inside the PoolManager, pools are told apart by `PoolId`, a hash of the two tokens, the fee, the tick spacing and the hook, and on swap rows the buyer and seller fields both show the PoolManager, so the trader is `Transaction.From`. PancakeSwap Infinity uses the same singleton design on BNB Chain and has [its own page](/docs/blockchain/BSC/bsc-pancakeswap-infinity-api). Every example runs in the [IDE](https://ide.bitquery.io) on a free account; the worked token is USDT, `0x55d398326f99059ff775485246999027b3197955`, and the worked pool is the busiest USDT/USDC pool, `PoolId 0x628ea54a6450645d2bb7b2911c8c6f3d7f3944c2f4703c259a1b85bf5569870b`. ## Which v4 pools trade USDT Start here to get a `PoolId`. Grouping `DEXTradeByTokens` by `PoolId` with USDT in `Currency` lists every v4 pool of the token, its counter token, and the trades and USD volume in the window. Saved query [here](https://ide.bitquery.io/get-virtual-pool-address-for-a-token-on-uniswap-v4-bsc). ```graphql { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "count" } limit: { count: 20 } ) { Trade { PoolId Side { Currency { Symbol SmartContract } } } count volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Daily stats of the USDT/USDC pool Trades, distinct buyers and sellers, and USD volume split by direction, for the pool and the token you name. Saved query [here](https://ide.bitquery.io/trade-stats-for-a-token-pair-on-uniswap-v4-bsc_1). ```graphql { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x628ea54a6450645d2bb7b2911c8c6f3d7f3944c2f4703c259a1b85bf5569870b" } Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol } Side { Currency { Symbol } } } trades: count buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) volumeUsd: sum(of: Trade_Side_AmountInUSD) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) } } } ``` ## Latest swaps in the pool Filter `DEXTrades` on the `PoolId`. Saved query [here](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-bsc). ```graphql { EVM(network: bsc) { DEXTrades( where: { Trade: { PoolId: { is: "0x628ea54a6450645d2bb7b2911c8c6f3d7f3944c2f4703c259a1b85bf5569870b" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Currency { Symbol } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Live swaps across every v4 pool on BNB Chain The protocol filter as a subscription. On BNB Chain this stream is busy, so filter on `PoolId` or on a token when you only need part of it. Saved stream [here](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-bsc). ```graphql subscription { EVM(network: bsc) { DEXTrades(where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } } }) { Block { Time } Trade { PoolId Buy { Currency { Symbol SmartContract } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol SmartContract } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Top traders of the pool The PoolManager settles both sides of every v4 swap, so `Trade.Buyer` and `Trade.Seller` on `DEXTrades` are the PoolManager; rank accounts by `Transaction.From` instead. `bought` sums the token the trader received and `sold` the token it paid; `Side.Type` describes the counter-side, which is why the conditions look swapped. Saved query [here](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-bsc); the [top sellers](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-pool-bsc) query is the same sorted on `sold`. ```graphql { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x628ea54a6450645d2bb7b2911c8c6f3d7f3944c2f4703c259a1b85bf5569870b" } Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 20 } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Reserves of the pool `DEXPoolEvents` rows carry the reserves the PoolManager holds for the pool after each change, in token units and USD. For v4 they are rebuilt from the concentrated positions around the current price. Filter on `PoolId`, or keep only the protocol name to stream every v4 pool. Saved queries [by pool](https://ide.bitquery.io/uniswap-v4-pool-liquidity-by-poolid-bsc) and [all pools](https://ide.bitquery.io/uniswap-v4-pool-liquidity-bsc). ```graphql subscription { EVM(network: bsc) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0x628ea54a6450645d2bb7b2911c8c6f3d7f3944c2f4703c259a1b85bf5569870b" } } } } ) { Block { Time } PoolEvent { Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } } } } ``` ## Related pages - [BNB Chain liquidity API](/docs/blockchain/BSC/bsc-liquidity-api) - [BNB Chain DEX trades API](/docs/blockchain/BSC/bsc-dextrades) - [PancakeSwap Infinity API](/docs/blockchain/BSC/bsc-pancakeswap-infinity-api) - [Uniswap v4 on Ethereum](/docs/blockchain/Ethereum/dextrades/uniswap-v4-api) - [Uniswap v4 on Arbitrum](/docs/blockchain/Arbitrum/uniswap-v4-api) --- ## BSC API Documentation URL: https://docs.bitquery.io/docs/blockchain/BSC/ BSC API overview: BNB Chain DEX trades, slippage, liquidity, balances and pending transactions, plus how the API compares with RPC and Kafka streams. # BSC API Documentation :::tip Building a trading app or DEX UI on BNB Chain (BSC)? For **real-time trades and prices on BNB Chain (BSC)** (and the last ~30 days), use the curated [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. For **historical BNB Chain (BSC) data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: In this section we will see how to fetch data on different tokens, transactions, DEXs like Uniswap, Pancakeswap, Four Meme, liquidity pools, and slippage data etc via APIs and Streams. If you need help getting data on Binance Smart Chain,reach out to [support](https://t.me/Bloxy_info) #### What is BSC API? Bitquery BSC APIs help you fetch onchain data like trades, transactions, balances, liquidity pools, and slippage data by writing a graphQL query. ### What are capabilities of Bitquery BSC API? Bitquery BSC APIs are very flexible, you can fetch trade, transaction, balance, liquidity, and slippage information for a specific wallet and join with other information. ### Difference between BSC RPC, Bitquery BSC API and Bitquery Kafka Stream? | BSC RPC | Bitquery BSC API | Bitquery Kafka Stream | | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | JSON-RPC endpoint exposing raw EVM on-chain state and transactions | GraphQL endpoint over pre-indexed, parsed BSC chain data (token transfers, DEX trades, logs, calls, etc.) | Provides fully managed Kafka topics (bsc.dextrades.proto, bsc.tokens.proto, bsc.transactions.proto) | | No built-in history or analytics—any indexing/aggregation you build or outsource | Historical data, joins, aggregations & real-time subscriptions | Delivers pre-parsed, enriched Protocol-Buffers events (DEX trades, token transfers and transactions) | | Ideal for submitting transactions | Great for real-time data and historical backtesting without running your own indexer | Great for Enterprise usage with built-in replication/failover and no node ops or custom parsing needed | Read more about Kafka streams [here](/docs/streams/protobuf/chains/EVM-protobuf/) and contact sales via [Telegram](https://t.me/Bloxy_info) or [form](https://bitquery.io/forms/api) for a **Trial**. ### Does Bitquery support BSC Websocket and BSC Webhooks? Bitquery supports websocket and webhooks, you can convert most of the graphQL APIs into graphQL streams by changing the word `query` to `subscription`. You can monitor this data via a websocket. More [code samples available here](/docs/subscriptions/websockets/) ## Can I monitor BSC pending transactions using Bitquery? {#can-i-monitor-bsc-pending-transactions-using-bitquery} **Yes.** Use **GraphQL subscriptions** with **`EVM(network: bsc, mempool: true)`** on the shapes documented for mempool (see [mempool subscriptions](/docs/subscriptions/mempool-subscriptions/) and the [Ethereum mempool API](/docs/blockchain/Ethereum/mempool/mempool-api/)—the same patterns apply to **BSC**). For **lower-latency** broadcast data, use **Kafka** streams as described on the **[BSC mempool stream](/docs/blockchain/BSC/bsc-mempool-stream/)** page. You need a valid **V2 OAuth token** for requests outside the IDE ([authorization](/docs/authorization/how-to-generate/)). ## BSC DEX APIs - [BSC Dex Trades](./bsc-dextrades) - [BSC NFT Trade API](./bsc-nft) - [Uniswap Trades API](./bsc-uniswap-api) - [Pancakeswap Trades API](./pancake-swap-api) - [Four Meme Trade API](./four-meme-api) · [DEXrabbit Four.meme tokens](https://dexrabbit.bitquery.io/categories/four-meme-ecosystem) - [GRA Fun API](./gra-fun-api) - [Building Four Meme Trading Bot](../../streams/sniper-trade-using-bitquery-kafka-stream) ## BSC Slippage API - [BSC Slippage API](./bsc-slippage-api) Get slippage and price impact data for BSC DEX pools. Understand price impact and liquidity depth for token swaps, calculate maximum input amounts at different slippage tolerances, and monitor real-time slippage data across all DEX pools on BSC. ## BSC Liquidity API - [BSC Liquidity API](./bsc-liquidity-api) Monitor real-time liquidity changes, track pool reserves, and analyze liquidity depth for token pairs on BSC DEX pools. Track when liquidity is added or removed, monitor pool health and depth, and analyze liquidity patterns across different pools. ## BSC Balance APIs - [BSC Balance API](./bsc-balance-updates) — `EVM.Balances` for current and historical token balances - [BSC Transaction Balance Tracker](./transaction-balance-tracker/) — Real-time balance changes with reason codes (`EVM.TransactionBalances`) ## Other BSC APIs - [BSC Mempool API](./bsc-mempool-stream) - [BSC Transfers API](./bsc-transfers) - [BSC Events API](./bsc-events-api) - [BSC Calls API](./bsc-calls-api) - [Binance Exchange Wallet Monitoring](../../usecases/binance-exchange-wallet-monitoring) ## Videos ### Four Meme | How to Get Top Traders of a Token on BSC Four Meme DEX ### Track Newly Created Tokens and Liquidity Pools on BSC ### Video Tutorial on Getting Real Time BSC DEXTrades ### Video Tutorial on BSC Protobuf Streams | Building BSC Sniper Trading Bot Using Bitquery Protobuf Kafka Streams ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## BSC Balance API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-balance-updates/ BSC Balance API: fetch current and historical BNB Chain balances with Bitquery GraphQL balance queries. Scale further with WebSocket subscriptions or Kafka streams. # BSC Balance API The **Balances** API returns current and historical token balances for an address on BSC. To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | | -------------- | ------------------------------------------------------------------------------------------- | | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | ## Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. [Run in IDE](https://ide.bitquery.io/BSC-Balance-of-an-Address) ```graphql query { EVM(network: bsc, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xf9D48e42d0FEb477a0286B206eDbafefA3577F63" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` **Parameters** - `network: bsc`: BNB Smart Chain mainnet. - `dataset: combined`: Merges realtime and archive data for the latest balance state. - `Balance.Address`: Wallet address to query. **Returned fields** - `Currency.Symbol`, `Currency.SmartContract`: Token metadata. - `Balance.Amount`, `Balance.AmountInUSD`: Token balance and USD value (use `selectWhere` to filter non-zero amounts). ## Balance on a Specific Date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. [Run in IDE](https://ide.bitquery.io/BSC-Balances-by-Date) ```graphql { EVM(network: bsc, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xf9D48e42d0FEb477a0286B206eDbafefA3577F63" } } Block: { Date: { till: "2026-04-01" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` ## Balance for a Specific Token Add a `Currency.SmartContract` filter. Always use the contract address, not the token name. [Run in IDE](https://ide.bitquery.io/BSC-Balances-Specific-Token) ```graphql query { EVM(network: bsc, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xf9D48e42d0FEb477a0286B206eDbafefA3577F63" } } Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Balance History by Date Returns balance snapshots over time for an address. Use `dataset: archive`. Order by `Block_Date` descending and use `limit` to paginate. Add `Currency.SmartContract` under `Currency` to filter by a specific token. [Run in IDE](https://ide.bitquery.io/BSC-Balances-History) ```graphql query { EVM(network: bsc, dataset: archive) { Balances( where: { Balance: { Address: { is: "0xf9D48e42d0FEb477a0286B206eDbafefA3577F63" } } Currency: {} } orderBy: { descending: Block_Date } limit: { count: 100 } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } Block { Date } } } } ``` ## Wallet Balance for a Specific Token on a Date Use `dataset: archive`, `Block.Date.till`, `orderBy: { descending: Block_Date }`, and `limit: { count: 1 }` to get the balance as of that date. [Run in IDE](https://ide.bitquery.io/BSC-Wallet-Balance-Token-at-Date) ```graphql query { EVM(network: bsc, dataset: archive) { Balances( where: { Block: { Date: { till: "2026-05-05" } } Balance: { Address: { is: "0xf9D48e42d0FEb477a0286B206eDbafefA3577F63" } } Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } limit: { count: 1 } orderBy: { descending: Block_Date } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Top Holders of a Token Use the **Holders** API (`EVM.Holders`) to get the top holders of a token. Use `dataset: combined` for the latest holder data. [Run in IDE](https://ide.bitquery.io/BSC-Top-Holders) ```graphql { EVM(network: bsc, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } orderBy: { descending: Balance_Amount } limit: { count: 10 } ) { Holder { Address } Balance { Amount(selectWhere: { gt: "0" }) } } } } ``` ## Token Holder Count Get the number of unique holders for a BEP-20 token using `uniq(of: Holder_Address)`. [Run in IDE](https://ide.bitquery.io/BSC-Token-Holder-Count) ```graphql query { EVM(network: bsc, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } ) { uniq(of: Holder_Address) } } } ``` ## Holder Count with Balance Above a Threshold Count holders whose balance exceeds a minimum threshold. Use `if` condition on the aggregate. [Run in IDE](https://ide.bitquery.io/BSC-Holders-Threshold) ```graphql query { EVM(network: bsc, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } ) { uniq(of: Holder_Address, if: { Balance: { Amount: { gt: "1000" } } }) } } } ``` ## Get Token Holdings and Holding Time of an Address Get the token holdings of an address and calculate the holding time using `FirstChangeTime` and `LastChangeTime` from the `Holders` API. [Run in IDE](https://ide.bitquery.io/BSC-Holdings-Holding-Time) ```graphql query ($trader: String, $token: String) { EVM(network: bsc, dataset: combined) { Holders( where: { Holder: { Address: { is: $trader } } Currency: { SmartContract: { is: $token }, Fungible: true } Balance: { Amount: { gt: "0" } } } ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime } Currency { Symbol Name SmartContract Decimals } } } } ``` ```json { "trader": "0xc5C2653d38E241D62F96A4fB8f8497b6126F21dC", "token": "0x49d870B1d21D00c775DD03110Ef4c8FeF4Fd4444" } ``` :::warning Important: Rebasing Token Limitations **Rebasing tokens are not supported for accurate balance calculations.** Rebasing tokens (like Mountain Protocol's USDM) automatically adjust their total supply and individual balances through mechanisms other than traditional transfer transactions. This means: - **Balance calculations may be inaccurate** - Our balance tracking doesn't capture rebasing adjustments - **Balance updates may be missing** - Individual holder balances change without visible transactions - **Historical balance data will be incorrect** - Past balances don't reflect rebasing adjustments **Before calculating balances for any token, verify it's not a rebasing token by:** 1. Checking the token's official documentation 2. Looking for rebasing mechanisms in the smart contract 3. Consulting token issuer resources **Example of rebasing token:** Mountain Protocol USDM (`0x59d9356e565ab3a36dd77763fc0d87feaf85508c` on Arbitrum) - [Documentation](https://docs.mountainprotocol.com/legacy-docs/usdm-token) **Supported chains:** This limitation applies to all EVM chains (Ethereum, Arbitrum, BSC, Base, etc.) ::: --- ## BSC Data - BNB Chain Export for Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/bsc/ BNB Chain blocks, transactions, transfers, balance updates, DEX trades, calls and events as Parquet, with a free sample and DuckDB and Python examples. # BSC Data - BNB Chain Bitquery provides **BSC (BNB Chain) blockchain data** as **Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), designed for large-scale analytics, historical backfills, and data lake integrations. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, etc**. ## Available BSC Topics For BSC (BNB Chain), Bitquery currently provides the following datasets: - **Blocks** – Block-level metadata - **Transactions** – Full transaction-level data - **Transfers** – Native BNB and token transfers (BEP-20) - **Balance Updates** – Account balance changes per block - **DEX Trades** – Executed trades on BSC DEXs (PancakeSwap, etc.) - **DEX Pools** – Decentralized exchange pool metadata - **Smart Contract Calls** – Function calls and contract interactions - **Events** – BSC event logs and emissions - **Miner Rewards** – Block rewards and transaction fees ## Sample BSC Cloud Dataset You can explore schemas and validate your tooling using the **public BSC sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/bsc](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/bsc) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bsc/balance_updates/.parquet ``` ## BSC Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── bsc/ ├── balance_updates/ │ ├── _.parquet │ ├── _.parquet │ └── ... ├── blocks/ │ ├── _.parquet │ ├── _.parquet │ └── ... ├── calls/ │ ├── _.parquet │ └── ... ├── dex_pools/ │ ├── _.parquet │ └── ... ├── dex_trades/ │ ├── _.parquet │ └── ... ├── events/ │ ├── _.parquet │ └── ... ├── miner_rewards/ │ ├── _.parquet │ └── ... ├── transactions/ │ ├── _.parquet │ └── ... └── transfers/ ├── _.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Example: ``` 77611000_77611049.parquet ``` ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets?network=bsc) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). Datasets you can buy on the Data Store: - [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) — every native BNB and token transfer, with sender, receiver and USD value This listing is not the full catalogue. Other topics, chains and date ranges are available on request from **sales@bitquery.io**. ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bsc/dex_trades/77611000_77611049.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bsc/transfers/77611000_77611049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access Data Store exports are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming BSC data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - **GraphQL subscriptions** --- ## BSC Gas Balance Tracker: Gas Bought, Refunded and Collected on BNB Chain URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/bsc-gas-balance-tracker/ Gas on BNB Chain from balance changes with Bitquery GraphQL: gas bought and refunded per transaction for an address, the busiest payers, and a stream. # BSC Gas Balance Tracker: Gas Bought, Refunded and Collected on BNB Chain BNB Chain reports gas the way Ethereum does, in three balance changes per transaction: the sender's BNB drops by the gas limit times the gas price before execution, reason code 6; whatever gas was not used comes back after execution, reason code 7; and the fee for the gas that was used is credited to the block producer, reason code 5. The `TransactionBalances` cube records all three with the balance before and after, so the gas an address paid is the code 6 debit minus the code 7 refund, transaction by transaction. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; the cube holds the recent realtime window only. The example address is a bot that sends transactions every few seconds, `0x10168749958f03a7c95432bd934058c77be787b0`; swap in any sender. ## Gas bought per transaction for one address Code 6 rows for the sender over the last hour; the time window keeps the scan small on a chain this busy. `gasBought` is the balance before minus the balance after, which equals `Gas` times `GasPrice` on the transaction. `calculate` only sees fields that are selected, so keep both balances in the query. Saved query [here](https://ide.bitquery.io/Latest-balance-and-gas-fee-paid-for-an-address-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 6 } Address: { is: "0x10168749958f03a7c95432bd934058c77be787b0" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time Number } TokenBalance { PreBalance PostBalance PostBalanceInUSD } Transaction { Hash Gas GasPrice } gasBought: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance" ) } } } ``` ## Gas refunded to the same address Code 7 rows are the unused gas coming back; a transaction that used its whole gas limit has none. Subtract this from the code 6 debit of the same hash to get the gas the transaction really cost. Saved query [here](https://ide.bitquery.io/Latest-balance-after-unused-gas-fee-returned--for-an-address-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 7 } Address: { is: "0x10168749958f03a7c95432bd934058c77be787b0" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } TokenBalance { PreBalance PostBalance } Transaction { Hash } refund: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## The busiest gas payers right now Group code 6 rows by address over a short window and count them. The top of the list is bots and exchange hot wallets. Saved query [here](https://ide.bitquery.io/top-gas-fee-collectors-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 6 } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } orderBy: { descendingByField: "transactions" } limit: { count: 20 } ) { TokenBalance { Address } transactions: count } } } ``` ## Several addresses at once `in` takes a list, and `limitBy` on the address keeps the newest row per address, so one query returns the latest gas debit of every wallet you watch. Saved query [here](https://ide.bitquery.io/Latest-balance-and-gas-fee-paid-for-multiple-addresses-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 6 } Address: { in: [ "0x10168749958f03a7c95432bd934058c77be787b0" "0x42d73da3daca18374ee1ab8d700351350a3b0064" ] } } Block: { Time: { since_relative: { hours_ago: 1 } } } } limitBy: { by: TokenBalance_Address, count: 1 } orderBy: { descending: Block_Time } ) { Block { Time } TokenBalance { Address PreBalance PostBalance } Transaction { Hash Gas GasPrice } gasBought: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance" ) } } } ``` ## Stream the gas one address pays The code 6 filter as a subscription delivers a message for every transaction the address sends, as it is indexed. Saved stream [here](https://ide.bitquery.io/Monitor-balance-and-gas-fee-paid-for-an-address-using-stream-bsc). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 6 } Address: { is: "0x10168749958f03a7c95432bd934058c77be787b0" } } } ) { Block { Time } TokenBalance { PreBalance PostBalance } Transaction { Hash GasPrice } gasBought: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance" ) } } } ``` ## Where the fees go The fee for used gas is credited with reason code 5 to BNB Chain's fee holder, `0xfffffffffffffffffffffffffffffffffffffffe`, and moved to the ValidatorSet contract at the end of each block. The [BSC MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker) streams those credits and shows fee income per block and per validator. ## Related pages - [BSC transaction balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) - [BSC MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker) - [Base gas balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-gas-balance-tracker) - [Balance change reason codes](/docs/blockchain/BSC/transaction-balance-tracker/#balance-change-reason-codes) --- ## BSC MEV Balance Tracker: Priority Fees and Block Producer Income URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker/ Track MEV on BNB Chain from balance changes with Bitquery GraphQL: stream fee credits, rank the largest tips, follow one bot and see fee income per block. # BSC MEV Balance Tracker: Priority Fees and Block Producer Income MEV on BNB Chain leaves one clean trace in balance data: the fee a transaction pays to be included ahead of others. The `TransactionBalances` cube records that credit as a balance change with reason code 5, `BalanceIncreaseRewardTransactionFee`, with the balance before and after it, so the tip is the difference between the two. This page streams those credits, ranks the largest, follows what one bot pays and shows how the fees reach the validator that produced the block. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The cube holds the recent realtime window only, so queries need a time filter and history has to be collected as it streams. ## Where the fee credit lands on BNB Chain On Ethereum a code 5 credit goes to the block builder's own address. On BNB Chain it goes to one fixed address, `0xfffffffffffffffffffffffffffffffffffffffe`, the fee holder that the Parlia consensus uses as the coinbase while a block's transactions execute. At the end of the block the validator moves the collected fees into the ValidatorSet system contract, `0x0000000000000000000000000000000000001000`, with a system transaction whose `Value` is the block's fee income. Two consequences for your filters: - Every code 5 row carries the fee holder as `TokenBalance.Address`; the transaction that paid the tip is in `Transaction`. - Rows on the ValidatorSet contract with `Transaction.Value` above zero are one per block; `Transaction.From` is the validator that earned them. ## Stream every priority fee The `tip` field subtracts the balance before from the balance after, so each message carries the fee in BNB. Saved stream [here](https://ide.bitquery.io/Track-MEV-Related-Balance-Updates-bsc). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Number Time } TokenBalance { Address PreBalance PostBalance Currency { Symbol } } Transaction { Hash From To GasPrice } tip: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## Largest tips in the last ten minutes Sort by the computed field to find the transactions that paid most for their position. `calculate` can only reference fields that are selected, so keep `PreBalance` and `PostBalance` in the query. Saved query [here](https://ide.bitquery.io/Track-Large-MEV-Transactions-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 20 } orderBy: { descendingByField: "tip" } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } ) { Block { Number Time } TokenBalance { PreBalance PostBalance } Transaction { Hash From To GasPrice } tip: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## What one bot pays Filter on `Transaction.From` to follow a single sender. The example address is a bot that pays some of the largest tips on the network; put any sender in its place. Saved query [here](https://ide.bitquery.io/Filter-by-MEV-Bot-or-Builder-Address-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 20 } orderBy: { descending: Block_Time } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Transaction: { From: { is: "0x4848489f0b2bedd788c696e2d79b6b69d7484848" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Number Time } TokenBalance { PreBalance PostBalance } Transaction { Hash To } tip: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` Change `query` to `subscription` and drop `limit`, `orderBy` and the time filter to get an alert each time the address pays a tip. ## Fee income per block and per validator The validator's deposit into the ValidatorSet contract closes each block. `limitBy` on the transaction hash keeps one row per block, `Transaction.Value` is the block's fee income and `Transaction.From` is the validator. Saved query [here](https://ide.bitquery.io/Aggregate-MEV-Rewards-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 20 } limitBy: { by: Transaction_Hash, count: 1 } orderBy: { descending: Block_Number } where: { TokenBalance: { Address: { is: "0x0000000000000000000000000000000000001000" } Currency: { Native: true } } Transaction: { Value: { gt: "0" } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } ) { Block { Number Time } Transaction { Hash From Value } } } } ``` Group the same rows by `Transaction.From` with `uniq(of: Transaction_Hash)` to count the blocks each validator produced in the window; the [BSC miner balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-miner-balance-tracker) shows that query. ## Related pages - [BSC transaction balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) - [BSC miner balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-miner-balance-tracker) - [BSC validator balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-validator-balance-tracker) - [Ethereum MEV balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-mev-balance-tracker) - [Balance change reason codes](/docs/blockchain/BSC/transaction-balance-tracker/#balance-change-reason-codes) --- ## BSC Mempool Stream - Real-Time Transaction Monitoring URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-mempool-stream/ BSC Mempool Stream - Real-Time Transaction Monitoring: watch BNB Chain pending transactions before confirmation with Bitquery GraphQL subscriptions. # BSC Mempool Stream - Real-Time Transaction Monitoring Monitor BSC (BNB Smart Chain) mempool transactions in real-time before they are confirmed on-chain. Track pending DEX trades, token creations, transfers, and detect opportunities early with Bitquery's Mempool APIs and Streams. Any Bitquery GraphQL stream can be converted to a mempool monitoring stream by setting `mempool: true`. We also provide low-latency Kafka streams to monitor broadcasted data, which are much faster than GraphQL mempool streams. Read more about Kafka streams [here](/docs/streams/protobuf/chains/EVM-protobuf/). :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ## How do I stream BSC pending transactions (mempool) using Bitquery? {#how-do-i-stream-bsc-pending-transactions-mempool-using-bitquery} Use a **GraphQL `subscription`** on the Bitquery streaming **WebSocket** [`wss://streaming.bitquery.io/graphql`](/docs/subscriptions/websockets/) with root **`EVM(network: bsc, mempool: true)`**. The **`mempool: true`** flag switches the stream to **broadcast / simulated pending** traffic instead of only confirmed blocks. Under that root, subscribe to the same APIs you use on-chain—**`Transactions`**, **`Transfers`**, **`DEXTrades`**, **`Events`**, and others—with `where` filters as needed. Authenticate the socket per [WebSocket authorization](/docs/authorization/websocket/). For mempool semantics (ordering, time window, vs confirmed subscriptions), read [Subscribing to mempool updates](/docs/subscriptions/mempool-subscriptions/). For lower latency at scale, consider **Kafka** [EVM protobuf streams](/docs/streams/protobuf/chains/EVM-protobuf/). Minimal example—pending transaction headers on BSC: ```graphql subscription BscMempoolTransactions { EVM(network: bsc, mempool: true) { Transactions { Block { Time } Transaction { Hash Cost To From } } } } ``` Try it in the IDE: [BSC mempool transactions](https://ide.bitquery.io/bsc-mempool-txs). Richer **`Transfers`** and **DEX** mempool patterns are in [Mempool Streaming Examples](#mempool-streaming-examples) below. --- ## Table of Contents ### 1. [How do I stream BSC pending transactions (mempool) using Bitquery?](#how-do-i-stream-bsc-pending-transactions-mempool-using-bitquery) ### 2. [How Mempool Simulation Works](#how-do-we-simulate-txs-for-bitquery-mempool-apis--streams) ### 3. Mempool Streaming Examples - [Stream Four Meme Trades in Mempool ➤](#stream-four-meme-trades-in-mempool---detect-them-early) - [Stream Four Meme Token Creation in Mempool ➤](#stream-four-meme-token-creation-in-mempool---detect-them-first) - [Stream All Transactions in Mempool ➤](#streaming-transactions-in-mempool-on-bsc) - [Stream DEX Trades in Mempool ➤](#streaming-trades-in-mempool-on-bsc) --- ## How do we simulate txs for Bitquery Mempool APIs & Streams? When a transaction is received by the node but not yet included in a block, Bitquery uses the following context to send mempool data: - The transaction is executed in the EVM (using the current pending block context). - The system captures the simulated receipt and trace. For each batch of simulated transactions, Bitquery records the block header used as the execution context. ``` message BroadcastedTransactionsMessage { Chain Chain = 1; BlockHeader Header = 2; repeated Transaction Transactions = 3; } ``` ## Mempool Streaming Examples ### Stream Four Meme Trades in Mempool - Detect Them Early Monitor Four Meme DEX trades in real-time as they appear in the mempool, before they are confirmed on-chain. This allows you to detect trading opportunities early and front-run or back-run trades. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-mempool-trades)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades(where: {Trade: {Dex: {ProtocolName: {is: "fourmeme_v1"}}}}) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount } Sell { Seller Currency { Name Symbol SmartContract } Amount } } Transaction { Hash } } } } ```
### Stream Four Meme Token Creation in Mempool - Detect Them First Track new Four Meme token creations in the mempool instantly. Be the first to know when a new token is being created, before it's confirmed on-chain. [Run Stream ➤](https://ide.bitquery.io/track-Four-meme-token-creation-in-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { Events( where: {Transaction: {To: {is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b"}}, Log: {Signature: {Name: {is: "TokenCreate"}}}} ) { Log { Signature { Name Signature } } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } Name Type } Transaction { Hash To From } } } } ```
### Streaming Transactions in Mempool on BSC Monitor all pending transactions and transfers on BSC in real-time. Track transaction details including sender, receiver, gas, amounts, and token information before blocks are mined. [Run Stream ➤](https://ide.bitquery.io/bsc-mempool-txs)
Click to expand GraphQL query ```graphql subscription { EVM(mempool: true, network: bsc) { Transfers { Log { Index } Transaction { Time Type To Gas From Cost Hash } Transfer { Amount Currency { Name } Type } TransactionStatus { Success FaultError EndError } Block { Time } Call { Signature { Name } } } } } ```
### Streaming Trades in Mempool on BSC Stream all DEX trades happening in the BSC mempool in real-time. Monitor buy/sell activity, prices, volumes, and trading pairs across all DEXs before transactions are confirmed. [Run Stream ➤](https://ide.bitquery.io/monitor-mempool-trades-bsc)
Click to expand GraphQL query ```graphql subscription { EVM(mempool: true, network: bsc) { DEXTradeByTokens { Block { Number } Transaction { Hash } Trade { Price PriceInUSD Currency { Name } Amount Buyer Dex { ProtocolName } Side { Seller Buyer AmountInUSD Amount Currency { Name Symbol } } } } } } ```
--- ## Related Resources You may also be interested in: - [Four Meme API Documentation ➤](/docs/blockchain/BSC/four-meme-api/) - [BSC DEX Trades API ➤](/docs/schema/evm/dextrades/) - [Kafka Protobuf Streams for EVM ➤](/docs/streams/protobuf/chains/EVM-protobuf/) - [WebSocket Subscriptions ➤](/docs/authorization/websocket/) ## Need Help? If you have any questions or need assistance with BSC mempool streams, reach out to our [Telegram support](https://t.me/Bloxy_info). --- ## BSC Miner Balance Tracker: Block Producer Rewards on BNB Chain URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/bsc-miner-balance-tracker/ BNB Chain has validators, not miners, so mining codes never fire. Track block producer income with Bitquery GraphQL: fees per transaction, block and validator. # BSC Miner Balance Tracker: Block Producer Rewards on BNB Chain BNB Chain has never had miners. Blocks are produced by a fixed set of validators under the Parlia consensus, so the two mining codes in the balance schema, 1 for an uncle reward and 2 for a block reward, never appear in BNB Chain data. A filter on them returns nothing, and the last query on this page shows that. What a block producer earns instead is the gas paid by the transactions in its block, and the `TransactionBalances` cube shows that income in two places: as a code 5 credit for each transaction, and as one deposit per block into the ValidatorSet contract. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; the cube covers the recent realtime window only. ## How block producer income shows up 1. While a block executes, each transaction's fee is credited to the fee holder `0xfffffffffffffffffffffffffffffffffffffffe` with reason code 5. 2. At the end of the block, the validator sends the collected total to the ValidatorSet system contract `0x0000000000000000000000000000000000001000`. `Transaction.From` on that deposit is the validator and `Transaction.Value` is the block's income. 3. Validators withdraw their share from the contract later; those withdrawals are ordinary transfers. ## Fee income per block One row per block, newest first. Saved query [here](https://ide.bitquery.io/Track-Block-Mining-Rewards-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 20 } limitBy: { by: Transaction_Hash, count: 1 } orderBy: { descending: Block_Number } where: { TokenBalance: { Address: { is: "0x0000000000000000000000000000000000001000" } Currency: { Native: true } } Transaction: { Value: { gt: "0" } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } ) { Block { Number Time } Transaction { Hash From Value } } } } ``` The deposit rows do not stream well as a subscription on BNB Chain because the filter has to scan every balance row on the network; poll this query, or stream the code 5 credits below, which are keyed by the fee holder and arrive at once. ## Blocks produced per validator Group the deposits by the validator address; `uniq` on the transaction hash counts blocks. Saved query [here](https://ide.bitquery.io/Historical-Miner-Balance-Data-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 50 } orderBy: { descendingByField: "blocks" } where: { TokenBalance: { Address: { is: "0x0000000000000000000000000000000000001000" } Currency: { Native: true } } Transaction: { Value: { gt: "0" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Transaction { From } blocks: uniq(of: Transaction_Hash) } } } ``` ## Income of one validator Add the validator to `Transaction.From`. The example is one of the validators with the most blocks; take any address from the query above. Validators rotate, so a quiet hour is normal for a single address and the window here is a day. Saved query [here](https://ide.bitquery.io/Filter-by-Miner-Address-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 20 } limitBy: { by: Transaction_Hash, count: 1 } orderBy: { descending: Block_Number } where: { TokenBalance: { Address: { is: "0x0000000000000000000000000000000000001000" } Currency: { Native: true } } Transaction: { Value: { gt: "0" } From: { is: "0x9bb56c2b4dbe5a06d79911c9899b6f817696acfc" } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Number Time } Transaction { Hash Value } } } } ``` ## Fee credits per transaction The per-transaction view is reason code 5 on the fee holder. The [BSC MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker) streams these with the tip computed per row and ranks the largest. Saved stream [here](https://ide.bitquery.io/Track-Transaction-Fee-Rewards-bsc). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Number Time } TokenBalance { Address PreBalance PostBalance } Transaction { Hash From } } } } ``` ## Why the mining codes return nothing Codes 1 and 2 exist in the schema because the same cube serves chains with a proof-of-work past. On BNB Chain the count is zero in any window. Saved query [here](https://ide.bitquery.io/Track-Uncle-Block-Rewards-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [1, 2] } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { count } } } ``` ## Related pages - [BSC MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker) - [BSC validator balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-validator-balance-tracker) - [BSC transaction balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) - [Balance change reason codes](/docs/blockchain/BSC/transaction-balance-tracker/#balance-change-reason-codes) --- ## BSC Self-Destruct Balance Tracker: Destroyed Contracts and Who Gets the BNB URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/bsc-self-destruct-balance-api/ Self-destructs on BNB Chain with Bitquery GraphQL: the contract that empties (code 13), the recipient of its BNB (code 12), the SELFDESTRUCT calls, a stream. # BSC Self-Destruct Balance Tracker: Destroyed Contracts and Who Gets the BNB When a contract on BNB Chain runs `selfdestruct`, its BNB moves to the address it names in one step, and the `TransactionBalances` cube records both ends: the destroyed contract's balance falling to zero with reason code 13, and the recipient's balance rising with reason code 12. On BNB Chain almost all of it is one pattern: an MEV bot deploys a helper contract with CREATE2, runs its trade through it and destroys it inside the same transaction, sweeping the leftover BNB back. A few hundred destructions a day, most of them into the same handful of recipients. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; the cube covers the recent realtime window only. The third code in this family, 14, marks BNB sent to an account that was already destroyed in the same transaction and does not occur in live data. ## The destroyed contracts Code 13 rows: `TokenBalance.Address` is the contract that destroyed itself, `PreBalance` is what it held, `PostBalance` is zero. `Transaction.From` is usually the bot that deployed it. Saved query [here](https://ide.bitquery.io/Self-Destruct-Balance-Decrease-API-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 13 } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time Number } TokenBalance { Address PreBalance PostBalance PostBalanceInUSD } Transaction { Hash From To } } } } ``` ## Who received the BNB Code 12 rows are the other side of the same transactions: the recipient named in the `selfdestruct` call, with its balance before and after. Saved query [here](https://ide.bitquery.io/Self-Destruct-Balance-Increase-API-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 12 } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time Number } TokenBalance { Address PreBalance PostBalance PostBalanceInUSD } Transaction { Hash From To } received: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` Group the same rows by `TokenBalance.Address` with `count` to see which recipients collect most often; in live data a few MEV addresses dominate. ## One recipient's self-destruct inflow Filter code 12 on the recipient. The example is one of the busiest MEV recipients on the chain, which collects from freshly destroyed helpers many times an hour; put any address in its place. Saved query [here](https://ide.bitquery.io/Track-Self-Destruct-Balance-Changes-for-Specific-Address-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 12 } Address: { is: "0xc6acbee42e9e323140c1ed060c2f6ea9cc3b4b75" } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } TokenBalance { PreBalance PostBalance } Transaction { Hash To } received: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## The SELFDESTRUCT calls themselves The `Calls` cube records the opcode, so you can list destructions even when the contract held nothing and no balance row exists. `Call.From` is the contract that died and `Call.To` the recipient. Saved query [here](https://ide.bitquery.io/Track-recent-ephemeral-contract-patterns-bsc). ```graphql { EVM(network: bsc) { Calls( where: { Call: { Opcode: { Name: { is: "SELFDESTRUCT" } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Call { From To Value } Transaction { Hash From } } } } ``` ## Stream every self-destruct Both codes in one subscription; each destruction produces one row of each. Self-destructs run to a few hundred a day on BNB Chain, so expect minutes between messages; the queries above are the quicker way to look. Saved stream [here](https://ide.bitquery.io/All-Self-Destruct-Event-Balances-Stream-bsc). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [12, 13] } } } ) { Block { Time Number } TokenBalance { Address BalanceChangeReasonCode PreBalance PostBalance PostBalanceInUSD } Transaction { Hash From To } } } } ``` ## Totals for a window `count` and `uniq` over code 13 rows give how many contracts died and how many distinct bots were behind them; the same over code 12 gives the recipients. Saved query [here](https://ide.bitquery.io/Aggregate-Self-Destruct-Statistics-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 13 } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { destroyed: count senders: uniq(of: Transaction_From) recipients: uniq(of: Transaction_To) } } } ``` ## Related pages - [BSC transaction balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) - [BSC MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker) - [BSC smart contract calls API](/docs/blockchain/BSC/bsc-calls-api) - [Balance change reason codes](/docs/blockchain/BSC/transaction-balance-tracker/#balance-change-reason-codes) --- ## BSC Smart Contract Calls API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-calls-api/ BSC smart contract calls: track the latest calls on BNB Chain and newly created tokens in real time, with GraphQL examples and a video walkthrough. # BSC Smart Contract Calls API In this section we will see how to get BSC Smart contract calls information using our API. ## Track Latest Calls on BNB The below query retrieves the latest successful smart contract calls on the BNB Smart Chain (BSC). It fetches details about contract interactions, transaction metadata, and associated block information. You can run it [here](https://ide.bitquery.io/Latest-Calls-on-BSC-network) ```graphql { EVM(network: bsc) { Calls( where: {Arguments: {length: {ne: 0}}, TransactionStatus: {Success: true}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Arguments { Name Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } } } Transaction { Hash To Type From } Receipt { ContractAddress } Block { Time } } } } ``` ## Track Latest Created Tokens on BSC This subscription websocket lets you track the newly created tokens on BSC network. You will find the newly created token contract address in the response under `Receipt: ContractAddress` field. You can find the query [here](https://ide.bitquery.io/Newly-Created-Tokens-on-BSC-network_2#) ```graphql subscription { EVM(network: bsc) { Calls( where: {Call: {Create: true}, Arguments: {length: {ne: 0}}, Receipt: {ContractAddress: {not: "0x0000000000000000000000000000000000000000"}}, TransactionStatus: {Success: true}} ) { Arguments { Name Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } } } Transaction { Hash } Receipt { ContractAddress } Block { Time } } } } ``` ## Video Tutorial on BSC API | How to Track Newly Created Tokens & Pools in Realtime on BSC --- ## BSC Smart Contract Events API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-events-api/ BSC smart contract events: track newly created liquidity pools on BNB Chain from factory events, with a GraphQL example and a video walkthrough. # BSC Smart Contract Events API In this section we will see how to get BSC Smart Contract Events information using our API. ## Track Newly Created Pools on BSC This subscription websocket lets you track the newly created pools on Uniswap V3 `0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7`. And we are listening for a particular event here named as `PoolCreated` because whenever a new pool is created on Uniswap V3 this event is fired. You can get the newly created pool address in the response in `arguments`. You can find the query [here](https://ide.bitquery.io/Newly-Created-Pools-on-Uniswap-v3-on-BSC-network_3#) ```graphql subscription { EVM(network: bsc) { Events( where: {Log: {SmartContract: {is: "0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7"}, Signature: {Name: {is: "PoolCreated"}}}, TransactionStatus: {Success: true}} ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } Name } } } } ``` ## Video Tutorial on BSC API | How to Track Newly Created Tokens & Pools in Realtime on BSC --- ## BSC Token Market Cap API: Market Cap, FDV and Supply of BNB Chain Tokens URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-token-marketcap-api/ Market cap, FDV, supply and price for BNB Chain tokens with Bitquery GraphQL: one token now, a watchlist, hourly history, a chain stream and an alert. # BSC Token Market Cap API: Market Cap, FDV and Supply of BNB Chain Tokens The `Tokens` cube of the Trading API keeps, for every token that trades on BNB Chain, a rolling set of candles with price, USD volume, circulating and total supply, market cap and fully diluted valuation. Market cap is circulating supply times the trade-weighted price, computed from on-chain trades, so it follows the market with a delay of a block rather than an hour. Tokens are addressed by id, `bid:bsc:` followed by the lowercase contract, and the chain is `Token.Network: "Binance Smart Chain"`. The cube keeps about a month; the [BSC transaction balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) gives on-chain total supply at any recent transaction if you only need supply. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; the worked token is CAKE, `0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82`. ## Market cap of one token now Match the id exactly, keep one candle size and a short window, and take the newest row. Without the window the query scans the whole cube and times out; without the duration it returns one row per candle size. Saved query [here](https://ide.bitquery.io/specific-bsc-token-latest-marketcap_1). ```graphql { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { is: "bid:bsc:0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } Interval: { Time: { Duration: { eq: 60 } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time } Token { Name Symbol Address Network } Price { Ohlc { Close } Average { Mean } } Supply { CirculatingSupply TotalSupply MarketCap FullyDilutedValuationUsd } Volume { Usd } } } } ``` ## A watchlist in one query `in` takes a list of ids and `limitBy` on the token id keeps the newest row per token. The example is CAKE, WBNB and USDT. ```graphql { Trading { Tokens( limitBy: { by: Token_Id, count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { in: [ "bid:bsc:0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" "bid:bsc:0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" "bid:bsc:0x55d398326f99059ff775485246999027b3197955" ] } } Interval: { Time: { Duration: { eq: 60 } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time } Token { Symbol Id } Price { Ohlc { Close } } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply } Volume { Usd } } } } ``` ## Hourly market cap over the last day One-hour candles carry the market cap at the close of each hour, with open and close price and the hour's USD volume, which is enough for a chart or a change-over-24-hours figure. Saved query [here](https://ide.bitquery.io/top-bsc-tokens-by-Market-Cap-Change-1h). ```graphql { Trading { Tokens( limit: { count: 24 } orderBy: { descending: Block_Time } where: { Token: { Id: { is: "bid:bsc:0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Interval { Time { Start } } Price { Ohlc { Open Close } } Supply { MarketCap } Volume { Usd } } } } ``` ## Stream market cap updates for every BNB Chain token Filter `Currency.Id` on the chain prefix and subscribe. Each message is a candle closing for some token; `Duration` above one second skips the tick-level candles. Saved stream [here](https://ide.bitquery.io/bsc-token-marketcap-stream). ```graphql subscription { Trading { Tokens( where: { Currency: { Id: { includes: "bsc" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Block { Time } Token { Symbol Id } Interval { Time { Duration } } Price { Ohlc { Close } } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } Volume { Usd } } } } ``` ## Alert when a token crosses a market cap Add a `Supply.MarketCap` bound to the stream and only tokens above it arrive, which is a launch screener in one filter. Saved stream [here](https://ide.bitquery.io/realtime-stream-bsc-tokens-with-marketcap-above-1-million_1). ```graphql subscription { Trading { Tokens( where: { Token: { Network: { is: "Binance Smart Chain" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 1000000 } } } ) { Block { Time } Token { Symbol Id } Supply { MarketCap TotalSupply } Price { Ohlc { Close } } } } } ``` ## Why some market caps look absurd Market cap here is on-chain supply times an on-chain price. A token with a huge minted supply and a few dollars of trades in a thin pool can show a market cap in the billions, and a plain "top tokens by market cap" ranking of the cube is led by those. Rank inside a list you trust, as in the watchlist query, or bound the ranking with `Volume: { Usd: { gt: ... } }` and `Supply: { MarketCap: { lt: ... } }` and treat the result as a screen rather than a league table. The saved [top tokens by market cap](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-bsc) query shows the bounded form. ## Related pages - [Base token market cap API](/docs/blockchain/Base/base-token-marketcap-api) - [Ethereum token market cap API](/docs/blockchain/Ethereum/token-supply/ethereum-token-marketcap-api) - [Tokens cube](/docs/trading/crypto-price-api/tokens) - [Supply fields](/docs/trading/crypto-price-api/supply-fields) - [BSC transaction balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) --- ## BSC Transaction Balance Tracker API: Balance Changes With a Reason Code URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/ How the BNB Chain balance tracker works: one row per balance change with pre and post balance and a reason code, which codes occur, and the tracker pages. # BSC Transaction Balance Tracker API: Balance Changes With a Reason Code The `TransactionBalances` cube under `EVM(network: bsc)` writes one row for every balance that a transaction changes: the address, the currency, the balance before and after, the USD value, and for BNB a reason code that says why it moved. A transfer, a gas charge, a gas refund, a fee credit to the block producer and a self-destruct each carry their own code, so one filter separates them without decoding calls. The same rows serve as a live stream and as a query over the recent realtime window; the cube has no archive dataset, so keep what you need by recording the stream. Every example on the tracker pages runs in the [IDE](https://ide.bitquery.io) on a free account. ## The reason codes that occur on BNB Chain Native BNB rows carry one of these in live data. The rest of the schema, listed further down, belongs to other chains' history and returns nothing here. | Code | Name | What it marks | Page | |---|---|---|---| | 10 | BalanceChangeTransfer | BNB moved by a transaction or an internal call | [Transaction tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) | | 6 | BalanceDecreaseGasBuy | Gas limit charged to the sender before execution | [Gas tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-gas-balance-tracker) | | 7 | BalanceIncreaseGasReturn | Unused gas refunded after execution | [Gas tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-gas-balance-tracker) | | 5 | BalanceIncreaseRewardTransactionFee | Fee for used gas credited to the fee holder, then deposited to the ValidatorSet contract per block | [MEV tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker), [Miner tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-miner-balance-tracker) | | 12, 13 | BalanceIncreaseSelfdestruct, BalanceDecreaseSelfdestruct | Recipient and contract of a `selfdestruct` | [Self-destruct tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-self-destruct-balance-api) | | 0 | BalanceChangeUnspecified | Everything without a more specific reason, and every token row | [Transaction tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker) | Codes 1 and 2, the mining rewards, never appear because BNB Chain has validators, not miners; code 3, consensus-layer withdrawals, never appears because withdrawals are not transactions; code 14 has no live occurrences. The [miner tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-miner-balance-tracker) shows the count query that proves it and what block producers earn instead. ## The tracker pages - [BSC transaction balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker): stream one address, latest BNB or BEP-20 balance of a wallet, pool reserves, token supply and market cap. - [BSC gas balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-gas-balance-tracker): gas bought and refunded per transaction for an address, the busiest gas payers, a live gas stream. - [BSC MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker): every priority fee as it is paid, the largest tips, one bot's spending, fee income per block. - [BSC miner balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-miner-balance-tracker): what block producers earn on a chain without miners, per block and per validator. - [BSC validator balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-validator-balance-tracker): the staking side of validator balances. - [BSC self-destruct balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-self-destruct-balance-api): contracts that destroy themselves and the addresses that collect their BNB. - [BSC transfer balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-transfer-balance-tracker): balance changes caused by transfers. ## One row, three shapes The fields a row carries depend on the currency. - **BNB:** `BalanceChangeReasonCode`, `PreBalance`, `PostBalance`, `PostBalanceInUSD`. - **BEP-20 tokens:** `PostBalance`, `PostBalanceInUSD`, `TotalSupply`, `TotalSupplyInUSD`; no pre-balance and no reason code. - **NFTs:** `PostBalance` and `TokenOwnership`; no USD values. ## The smallest useful query The newest balance changes of one address, any currency, which is the shape most of the tracker pages build on. ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 10 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x238a358808379702088667322f80ac48bad5e6c4" } } } ) { Block { Time } TokenBalance { BalanceChangeReasonCode PreBalance PostBalance PostBalanceInUSD Currency { Symbol Native } } Transaction { Hash } } } } ``` Change `query` to `subscription` and drop `limit` and `orderBy` to follow the address live. Kafka carries the same rows on the `bsc.tokens.proto` topic; see the [Kafka streams hub](/docs/category/kafka-streams). ## The full code list {#balance-change-reason-codes} Defined for every EVM chain the cube serves; only the codes in the first table occur on BNB Chain. | Code | Reason | Description | |---|---|---| | 0 | BalanceChangeUnspecified | No specific reason recorded | | 1 | BalanceIncreaseRewardMineUncle | Uncle block reward (proof-of-work chains) | | 2 | BalanceIncreaseRewardMineBlock | Block mining reward (proof-of-work chains) | | 3 | BalanceIncreaseWithdrawal | Consensus-layer validator withdrawal | | 4 | BalanceIncreaseGenesisBalance | Balance allocated at genesis | | 5 | BalanceIncreaseRewardTransactionFee | Fee for used gas credited to the block producer | | 6 | BalanceDecreaseGasBuy | Gas limit charged before execution | | 7 | BalanceIncreaseGasReturn | Unused gas refunded after execution | | 8 | BalanceIncreaseDaoContract | DAO refund contract credit (Ethereum, 2016) | | 9 | BalanceDecreaseDaoAccount | DAO account debit (Ethereum, 2016) | | 10 | BalanceChangeTransfer | Value moved by a call | | 11 | BalanceChangeTouchAccount | Zero-value transfer that creates an account | | 12 | BalanceIncreaseSelfdestruct | Recipient of a self-destructed contract's balance | | 13 | BalanceDecreaseSelfdestruct | Contract emptied by self-destruct | | 14 | BalanceDecreaseSelfdestructBurn | Value sent to an account already destroyed in the same transaction | | 15 | BalanceChangeRevert | Balance restored after a failed call | --- ## BSC Transaction Balance Tracker: Balances Before and After a Transaction URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/bsc-transaction-balance-tracker/ Stream and query BNB Chain balance changes with Bitquery GraphQL: every address a transaction touched, one wallet's BNB and USDT, pool reserves and supply. # BSC Transaction Balance Tracker: Balances Before and After a Transaction The `TransactionBalances` cube records, for each transaction on BNB Chain, every address whose balance changed and the balance before and after, in BNB, BEP-20 tokens and NFTs. A wallet tracker, a fee monitor and a pool reserve feed all come from the same rows. Native rows carry a reason code that says why the balance moved: 10 for a transfer, 6 and 7 for gas bought and returned, 5 for the fee credited to the block producer, 12 and 13 for self-destructs, 0 when no specific reason applies. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The cube covers the recent realtime window only, so queries carry a `limit` and, for wide filters, a time window. ## Stream one address BNB Chain produces so many balance rows that a stream over the whole network, one token or a broad reason code does not deliver in practice; filter on an address, or use the reason code 5 stream on the [MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker), which is keyed to one address. The example is a busy exchange wallet, so rows arrive within seconds; a quiet wallet streams only when it transacts. Saved stream [here](https://ide.bitquery.io/Subscribe-to-Transaction-Balances-for-a-Specific-Address-bsc). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { Address: { is: "0x238a358808379702088667322f80ac48bad5e6c4" } } } ) { Block { Number Time } TokenBalance { BalanceChangeReasonCode PreBalance PostBalance PostBalanceInUSD Currency { Symbol SmartContract Native } } Transaction { Hash From To } } } } ``` ## Latest BNB balance of an address The newest native row for the address; `PostBalance` is the balance after that transaction. Saved query [here](https://ide.bitquery.io/latest-native-balance-of-an-address-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x238a358808379702088667322f80ac48bad5e6c4" } Currency: { Native: true } } } ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD BalanceChangeReasonCode } Transaction { Hash } } } } ``` ## Latest balance of an address in one token The same query with the token contract in place of the native flag. The example is USDT on BNB Chain, `0x55d398326f99059fF775485246999027B3197955`. Saved query [here](https://ide.bitquery.io/latest-balance-of-an-address-for-a-specific-token-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x238a358808379702088667322f80ac48bad5e6c4" } Currency: { SmartContract: { is: "0x55d398326f99059fF775485246999027B3197955" } } } } ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD Currency { Symbol Name } } Transaction { Hash } } } } ``` An address that has not moved the token inside the realtime window has no row here; use the [Balances cube](/docs/cubes/balances-cube) for a balance that does not depend on recent activity. ## Latest reserves of a pool A pool is an address like any other, so its token balances are its reserves. `limitBy` on the token contract keeps the newest row per token, and the time window keeps the query fast on a busy pool. The example is the PancakeSwap v3 WBNB/USDT pool. Saved query [here](https://ide.bitquery.io/latest-liquidity-of-a-bsc-pool). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 2 } limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x36696169C63e42cd08ce11f5deeBbCeBae652050" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time } TokenBalance { Currency { Symbol SmartContract } PostBalance PostBalanceInUSD } } } } ``` ## Latest supply and market cap of a token Token rows carry `TotalSupply` and `TotalSupplyInUSD` as of that transaction, so the newest row for a token gives its supply and on-chain market cap. The example is CAKE. Saved query [here](https://ide.bitquery.io/Total-Supply-and-onchain-Marketcap-of-a-specific-token-bsc). ```graphql { EVM(network: bsc) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Currency: { SmartContract: { is: "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82" } } } } ) { Block { Time } TokenBalance { Currency { Symbol Name } TotalSupply TotalSupplyInUSD } } } } ``` ## Which fields each currency type carries - **BNB:** `BalanceChangeReasonCode`, `PreBalance`, `PostBalance`, `PostBalanceInUSD`. - **BEP-20:** `PostBalance`, `PostBalanceInUSD`, `TotalSupply`, `TotalSupplyInUSD`; no pre-balance or reason code. - **NFTs:** `PostBalance` and `TokenOwnership`; no USD values. ## Related pages - [BSC transaction balance tracker overview](/docs/blockchain/BSC/transaction-balance-tracker/) - [BSC gas balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-gas-balance-tracker) - [BSC MEV balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-mev-balance-tracker) - [Balances and Holders cubes](/docs/cubes/balances-cube) --- ## BSC Transfer Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/bsc-transfer-balance-tracker/ BSC Transfer Balance Tracker: monitor BNB Chain native and token transfers in real time with Bitquery GraphQL APIs. Keep queries fast with indexed filters. # BSC Transfer Balance Tracker The BSC Transfer Balance Tracker API provides real-time balance updates for all addresses involved in Transfers on the BSC blockchain, and provides option to filter out based on the direction of transfer you want to target. The BSC Transfer Balance is tracked by marking the the `BalanceUpdateReason` equals `10`. :::note The queries covered this section are only valid for the Native Currency Transfer. ::: ## Get Balance Info for an Address after Transfer [This](https://ide.bitquery.io/balance-update-from-transfer-for-an-address-bsc) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a particular address after a transfer, irrespective of the direction of transfer.
Click here to expand ```graphql query MyQuery { EVM(network: bsc) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xYourAddressInput"}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Stream Balance Info for Transfer in Real Time [This](https://ide.bitquery.io/balance-update-from-transfer-for-an-address--stream-bsc) subscription allows us to stream Balance Updates for an address due to transfer in Real Time.
Click here to expand ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xYourAddressInput"}}} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Get Balance Info for Multiple Addresses after Transfer [This](https://ide.bitquery.io/balance-update-from-transfer-for-multiple-addresses-bsc_1) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a list of addresses after a transfer, irrespective of the direction of transfer.
Click here to expand ```graphql query MyQuery { EVM(network: bsc) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {in: ["0xYourAddressInput1", "0xYourAddressInput2"]}}} orderBy: {descending: Block_Time} limitBy: {by:TokenBalance_Address count: 1} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Stream Balance Update due to Transfer for Multiple Addresses in Real Time [This](https://ide.bitquery.io/balance-update-from-transfer-for-multiple-addresses--stream-bsc) subscription allows us to stream Balance Updates for a list of addresses due to transfer in Real Time.
Click here to expand ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {in: ["0xYourAddressInput", "0xYourAddressInput"]}}} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Get Balance Info for an Address after Transfer Sent [This](https://ide.bitquery.io/Balance-update-after-transfer-sent-bsc) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a particular address after it sends a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {is: "0xYourAddressInput"}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Transfer Sent in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-sent--stream-bsc) subscription allows us to stream Balance Updates for a transfer sent by an address in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {is: "0xYourAddressInput"}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Info for Multiple Addresses after Transfer Sent [This](https://ide.bitquery.io/Balance-update-after-transfer-sent-from-multiple-addresses-bsc) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a list of addresses after they send a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {in: ["0xYourAddressInput1", "0xYourAddressInput2"]}}} orderBy: {descending: Block_Time} limitBy: {by:Transaction_From count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Multiple Addresses for Transfer Sent in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-sent-from-multiple-addresses--stream-bsc) subscription allows us to stream Balance Updates for a list of addresses due to transfer sent in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {in: ["0xYourAddressInput1", "0xYourAddressInput2"]}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Info for an Address after Transfer Recieved [This](https://ide.bitquery.io/Balance-update-after-transfer-received-bsc) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a particular address after it recieves a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {is: "0xYourAddressInput"}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Transfer Recieved in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-received--stream-bsc) subscription allows us to stream Balance Updates for a transfer recieved by an address in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {is: "0xYourAddressInput"}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Info for Multiple Addresses after Transfer Recieved [This](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses-bsc) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a list of addresses after they recieve a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {in: ["0xYourAddressInput1", "0xYourAddressInput2"]}}} orderBy: {descending: Block_Time} limitBy: {by:Transaction_To count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Multiple Addresses for Transfer Recieved in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses--stream-bsc) subscription allows us to stream Balance Updates for a list of addresses due to transfer recieved in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {in: ["0xYourAddressInput1", "0xYourAddressInput2"]}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Updates for the Last 24 hours Use [this](https://ide.bitquery.io/Balance-Updates-for-transfer-in-last-24-hours-bsc) API endpoint for getting Balance Updates due to Transfers for a particular address irrespective of the direction of Transfer. This could be used in applications that maintains a record for a wallet.
Click here to expand ```graphql query MyQuery { EVM(network: bsc) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xYourAddressInput"}}, Block: {Time: {since_relative: {hours_ago: 24}}}} orderBy: {descending: Block_Time} ) { Block { Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction { From To Hash } transfer_amount: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) transfer_amount_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ```
## Get Balance Updates for the Last 24 hours Use [this](https://ide.bitquery.io/Balance-Updates-for-multiple-addresses-transfer-in-last-24-hours-bsc) API endpoint for getting Balance Updates due to Transfers for a list of addresses irrespective of the direction of Transfer. This could be used in Dashboard Applications that shows record for multiple wallets.
Click here to expand ```graphql query MyQuery { EVM(network: bsc) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {in: ["0xYourAddressInput1", "0xYourAddressInput2"]}}, Block: {Time: {since_relative: {hours_ago: 24}}}} orderBy: {descending: Block_Time} ) { Block { Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction { From To Hash } transfer_amount: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) transfer_amount_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ```
--- ## BSC Validator Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/BSC/transaction-balance-tracker/bsc-validator-balance-tracker/ BSC Validator Balance Tracker: stream BNB Chain balance changes with reason codes using Bitquery GraphQL subscriptions. See examples in the Bitquery IDE. # BSC Validator Balance Tracker The BSC Validator Balance Tracker API provides real-time balance updates for BSC validators, tracking their staking rewards, withdrawals, and balance changes. ## Track Validator Balance Updates Monitor balance changes for BSC validators, including staking rewards and withdrawals from the beacon chain. Try the API [here](https://ide.bitquery.io/Track-Validator-Balance-Updates-bsc_1). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [211, 5] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` **Note:** BalanceChangeReasonCode 3 corresponds to `BalanceIncreaseWithdrawal` - ETH withdrawn from the beacon chain. ## Track Validator Rewards Track validator rewards and balance increases from staking activities. Try the API [here](https://ide.bitquery.io/Track-Validator-Rewards-bsc_1). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 211 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` **Balance Change Reason Codes for Validators:** - **Code 211**: `BalanceIncreaseRewardMineBlock` - BalanceChangeCode when BSC is distributing rewards to validator. ## Filter by Validator Address Track balance changes for a specific validator address: Try the API [here](https://ide.bitquery.io/Filter-by-Validator-Address-bsc_1). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xValidatorAddressHere" } BalanceChangeReasonCode: { eq: 211 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Top Validators by Total Tips earned in last 24 hrs Ranks validators by cumulative priority fees (reason code 5) received in the last 24 hours. Test the query [here](https://ide.bitquery.io/top-validators-by-total-tips-in-last-24-hrs-bsc). ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { TransactionBalances( limit: { count: 10 } orderBy: { descendingByField: "Total_tip_native" } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { TokenBalance { Address BalanceChangeReasonCode Currency { Name Symbol SmartContract } } Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count } } } ``` ## Total Tips earned by a Validator in last 24 hrs Returns the total priority fees (native and USD) earned by a specific validator over the last 24 hours. Test the query [here](https://ide.bitquery.io/total-tips-received-by-a-validator-in-last-24-hrs-bsc). ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } Address: { is: "0xValidatorAddressHere" } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { TokenBalance { Address BalanceChangeReasonCode Currency { Name Symbol SmartContract } } Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count } } } ``` ## Avg Tip in last 10 Blocks Calculates the average tip for each of the last 10 blocks. Test the query [here](https://ide.bitquery.io/last-10-blocks-avg-tip-in-native-bnb). ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { TransactionBalances( limit: { count: 10 } orderBy: { descending: Block_Number } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Number } TokenBalance { BalanceChangeReasonCode Currency { Name Symbol SmartContract } } Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count avg_tip_in_this_block: calculate( expression: "$Total_tip_native / $number_of_tips" ) avg_tip_usd_in_this_block: calculate( expression: "$Total_tip_usd / $number_of_tips" ) } } } ``` ## Avg Tip given in terms of Avg Gas Fees in last 10 blocks Compares average user tip to average total gas fee per block across the last 10 blocks. Test the query [here](https://ide.bitquery.io/Average-Tip-in-terms-of-avg-gas-Fee-bsc). ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { TransactionBalances( limit: { count: 10 } orderBy: { descending: Block_Number } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Number } TokenBalance { BalanceChangeReasonCode Currency { Name Symbol SmartContract } } avg_gasfees_in_this_block: average(of: Fee_SenderFee) Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count avg_tip_in_this_block: calculate( expression: "$Total_tip_native / $number_of_tips" ) avg_tip_usd_in_this_block: calculate( expression: "$Total_tip_usd / $number_of_tips" ) tip_in_terms_of_gasfees: calculate( expression: "( $avg_gasfees_in_this_block - $avg_tip_in_this_block ) / $avg_gasfees_in_this_block" ) } } } ``` --- ## Backfill Data After WebSocket Disconnect - Python Tutorial URL: https://docs.bitquery.io/docs/subscriptions/backfilling-subscription/ Backfill Data After WebSocket Disconnect - Python Tutorial using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # How to Backfill Data After a WebSocket Disconnection in Python In this section, we'll discuss potential approaches to backfill data when stream disconnects. We will write code to receive live data, handles potential errors and disconnections, backfills any missing data during downtime, and ensures a graceful closure of connections. ## Overview In this tutorial, we'll build a system that: 1. **Subscribes to a live data stream via WebSocket.** 2. **Handles errors and detects disconnections.** 3. **Backfills any missing data during downtime by querying historical data.** 4. **Ensures the WebSocket connection is gracefully closed when necessary.** ![flow](/img/diagrams/backfill.png) We'll use Python's `asyncio` for asynchronous operations, the `gql` library for GraphQL interactions, and the `requests` library for HTTP requests. ## Prerequisites Before diving into the implementation, ensure you have the following: - **Python 3.7 or higher** installed. - **Familiarity with WebSocket and GraphQL**. - **API access to the Bitquery**. ### Installing Required Libraries Use `pip` to install the necessary Python libraries: ```bash pip install asyncio gql requests ``` ## System Architecture The system's workflow can be summarized as follows: 1. **Live Subscription**: Connect to the Bitquery Ethereum Subscription to receive real-time data. 2. **Error Handling**: Monitor the connection for any issues or disconnections. 3. **Backfilling**: Upon detecting a disconnection, query historical data to fill in any gaps. 4. **Graceful Closure**: Properly close the WebSocket connection when done or when an error occurs. Let's delve into each component in detail. ## Step-by-Step Implementation ### 1. Live Subscription **Objective**: Establish a live connection to the WebSocket API to receive real-time data. **Implementation Details**: - **WebsocketsTransport**: Used from the `gql` library to handle WebSocket connections. - **GraphQL Subscription**: Defines the query to subscribe to live data. **Code Explanation**: ```python from gql import Client, gql from gql.transport.websockets import WebsocketsTransport ``` We start by importing the necessary libraries. `asyncio` facilitates asynchronous operations, `gql` handles GraphQL queries and subscriptions, `requests` is used for HTTP requests during backfilling, and `datetime` manages time-related operations. ```python # Bitquery streaming URL and OAuth token url = "https://streaming.bitquery.io/graphql" token = "ory_at_...4" ``` Set up the streaming URL and your oAuth token. Replace `"ory_at_...4"` with your actual Bitquery token. **Live Subscription Function**: ```python async def subscribe(): transport = WebsocketsTransport( url="wss://streaming.bitquery.io/graphql?token=" + token, headers={"Sec-WebSocket-Protocol": "graphql-ws"} ) await transport.connect() print("connected") try: async for result in transport.subscribe( gql(""" subscription MyQuery { EVM(network: eth) { DEXTrades { Block { Time } Transaction { Hash } Trade { Buy { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } Dex { SmartContract ProtocolName ProtocolVersion } Sell { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } """) ): # Processing incoming data print("Live Data:", result) except Exception as e: print(f"Error during subscription: {e}") finally: await transport.close() ``` **Explanation**: 1. **Establish Connection**: Create a `WebsocketsTransport` instance with the WebSocket URL and necessary headers. Connect to the WebSocket using `await transport.connect()`. 2. **Subscription**: Use `transport.subscribe()` with a GraphQL subscription query to listen for live data (`DEXTrades` in this case). 3. **Data Handling**: As live data comes in, it's printed out. In a real-world scenario, you'd process or store this data as needed. 4. **Error Handling**: If any exception occurs during subscription, it's caught and printed. 5. **Graceful Closure**: Regardless of success or failure, the WebSocket connection is closed using `await transport.close()`. ### 2. Error Handling **Objective**: Detect and handle any network issues or exceptions that may disrupt the WebSocket connection. **Implementation Details**: - **Try-Except Blocks**: Used to catch and handle exceptions during the subscription. - **Logging Errors**: Errors are printed for debugging purposes. **Code Explanation**: In the `subscribe` function, the `try-except-finally` block ensures that any exceptions during the subscription process are caught. If an error occurs, it's printed, and the connection is closed gracefully in the `finally` block. Additionally, the `main` function is designed to catch exceptions from the `subscribe` function and trigger the backfilling process. ```python def handle_disconnection(start_time, end_time): print(f"Connection lost. Backfilling data from {start_time} to {end_time}.") asyncio.run(backfill_data(start_time, end_time)) ``` The `handle_disconnection` function is invoked when a disconnection is detected. It logs the disconnection and triggers the backfilling process for the time range between `start_time` and `end_time`. ### 3. Backfilling Missing Data **Objective**: Retrieve any data that was missed during the disconnection period to ensure data completeness. **Implementation Details**: - **Historical Data Query**: In backfilling, the GraphQL query is essentially the same as the live subscription query, but instead of listening to real-time updates, we perform a **query** (instead of a **subscription**) for historical data. The query includes an additional time filter to specify the period for which we want to retrieve the missing data. - **Time Filter**: The query uses a `where` clause to filter data by a specific time range. The parameters `since` and `till` are added to ensure only data from the disconnected period is queried. This allows us to target the exact time window for which we need to backfill data. - **Time Range Calculation**: The `start_time` (when the disconnection began) and `end_time` (when the connection is restored) are used to define the missing data period. This time range is passed into the backfill query to retrieve the missing trades or data. **Code Explanation**: ```python # Function to backfill data for a given time range async def backfill_data(start_time, end_time): query = """ { EVM(network: eth) { DEXTrades(where: {Block: {Time: {since: "%s", till: "%s"}}}) { Block { Time } Transaction { Hash } Trade { Buy { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } Dex { SmartContract ProtocolName ProtocolVersion } Sell { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } """ % (start_time, end_time) # Make an HTTP request to backfill missing data headers = { 'Content-Type': 'application/json', 'Authorization': "Bearer "+token } response = requests.post(url, json={"query": query}, headers=headers) if response.status_code == 200: result = response.json() print("Backfilled Data:", result) else: print("Failed to backfill data:", response.status_code, response.text) ``` **Explanation**: 1. **GraphQL Query**: The query fetches `DEXTrades` within the specified `start_time` and `end_time`. 2. **HTTP Request**: Sends the query to the Bitquery API using an HTTP POST request with the necessary headers, including the authorization token. 3. **Response Handling**: If the request is successful (`status_code == 200`), the backfilled data is printed. Otherwise, an error message with the status code and response text is displayed. **Note**: In a production environment, instead of printing the data, you'd likely store it in a database or process it further. ### 4. Graceful Closure **Objective**: Ensure that the WebSocket connection is properly closed when it's no longer needed or when an error occurs. **Implementation Details**: - **Finally Block**: Ensures the connection is closed regardless of success or failure. - **Explicit Closure**: Uses `await transport.close()` to terminate the WebSocket connection. **Code Explanation**: Within the `subscribe` function, the `finally` block guarantees that the WebSocket connection is closed even if an error occurs during data streaming. This prevents resource leaks and ensures that the connection state is cleanly managed. ```python finally: await transport.close() ``` Additionally, the `handle_disconnection` function ensures that any necessary cleanup or data retrieval occurs when a disconnection is detected. ### Putting It All Together **Main Function**: ```python # Main function to run the subscription and detect disconnection async def main(): start_time = datetime.datetime.now(datetime.timezone.utc) try: await subscribe() except Exception as e: print(f"Disconnection detected: {e}") end_time = datetime.datetime.now(datetime.timezone.utc) # Call backfill function to handle missing data handle_disconnection(start_time.isoformat(), end_time.isoformat()) ``` **Explanation**: 1. **Start Time**: Records the current UTC time before initiating the subscription. 2. **Subscription**: Awaits the `subscribe` function to start receiving live data. 3. **Exception Handling**: If an exception occurs (indicating a disconnection), it captures the current time as `end_time` and calls `handle_disconnection` to backfill data for the period between `start_time` and `end_time`. **Running the Event Loop**: ```python # Run the asyncio event loop asyncio.run(main()) ``` This line starts the asynchronous event loop, executing the `main` function. ## Complete Code Here's the complete code assembled from the components discussed: ```python from gql import Client, gql from gql.transport.websockets import WebsocketsTransport # Bitquery streaming URL and API token url = "https://streaming.bitquery.io/graphql" token = "ory_at_...4" # Function to backfill data for a given time range async def backfill_data(start_time, end_time): query = """ { EVM(network: eth) { DEXTrades(where: {Block: {Time: {since: "%s", till: "%s"}}}) { Block { Time } Transaction { Hash } Trade { Buy { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } Dex { SmartContract ProtocolName ProtocolVersion } Sell { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } """ % (start_time, end_time) # Make an HTTP request to backfill missing data headers = { 'Content-Type': 'application/json', 'Authorization': "Bearer "+token } response = requests.post(url, json={"query": query}, headers=headers) if response.status_code == 200: result = response.json() print("Backfilled Data:", result) else: print("Failed to backfill data:", response.status_code, response.text) # Function to subscribe to live data stream async def subscribe(): transport = WebsocketsTransport( url="wss://streaming.bitquery.io/graphql?token=" + token, headers={"Sec-WebSocket-Protocol": "graphql-ws"} ) await transport.connect() print("connected") try: async for result in transport.subscribe( gql(""" subscription MyQuery { EVM(network: eth) { DEXTrades { Block { Time } Transaction { Hash } Trade { Buy { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } Dex { SmartContract ProtocolName ProtocolVersion } Sell { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } """) ): # Processing incoming data print("Live Data:", result) except Exception as e: print(f"Error during subscription: {e}") finally: await transport.close() # Function to calculate time range and trigger backfill def handle_disconnection(start_time, end_time): print(f"Connection lost. Backfilling data from {start_time} to {end_time}.") asyncio.run(backfill_data(start_time, end_time)) # Main function to run the subscription and detect disconnection async def main(): start_time = datetime.datetime.now(datetime.timezone.utc) try: await subscribe() except Exception as e: print(f"Disconnection detected: {e}") end_time = datetime.datetime.now(datetime.timezone.utc) # Call backfill function to handle missing data handle_disconnection(start_time.isoformat(), end_time.isoformat()) # Run the asyncio event loop asyncio.run(main()) ``` ## Running the System 1. **Configure OAuth Token**: Replace `"ory_at_...4"` with your actual Bitquery token. 2. **Execute the Script**: Run the script using Python. ```bash python your_script_name.py ``` 3. **Monitor Output**: The console will display messages indicating successful connections, live data, any errors, and backfilled data as needed. **Example Output**: ``` connected Live Data: {...} # Real-time data received Error during subscription: Connection closed unexpectedly Disconnection detected: Connection closed unexpectedly Connection lost. Backfilling data from 2024-10-14T12:00:00+00:00 to 2024-10-14T12:05:00+00:00. Backfilled Data: {...} # Historical data fetched to fill the gap ``` ## Alternative Approach: Using Block Heights to Backfill Data You can implement an alternative approach that uses block heights instead of relying on time periods. 1. **Track the Last Processed Block Height**: Continuously update and save the latest block height received from the live data stream. 2. **Detect Disconnections**: Monitor the WebSocket connection for any interruptions. 3. **Backfill Missing Data**: Using historical query, use the last saved block height to query and retrieve data from the missed blocks. 4. **Update the Last Processed Block Height**: After successful backfilling, update the saved block height to reflect the latest processed block. ## Conclusion In this tutorial, we built a resilient real-time data streaming system using Python. The system effectively manages live data subscriptions, handles errors and disconnections, backfills any missing data to maintain data integrity, and ensures that connections are gracefully closed when necessary. --- ## Bags FM API - Bitquery URL: https://docs.bitquery.io/docs/blockchain/Solana/bags-fm-api/ Bags FM on Solana: new token creations, USD and quote prices, all trades, latest trades by token and token transfers, with GraphQL queries and streams. # Bags FM API Documentation :::tip Need real-time Bags FM data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Bags FM data older than ~30 days**, raw per-swap detail, or call / event context. ::: Welcome to the **Bags FM API documentation**, powered by **Bitquery blockchain data APIs**. This guide covers how to use Bitquery to fetch and analyze **Bags FM token data** on Solana, including **token creation, supply, transfers, trades, and prices**. You can use these APIs to integrate **real-time Bags FM data** into your applications. The **Bitquery Bags FM API** provides comprehensive access to **Bags FM launchpad data**, including **Bags FM token creation API**, **Bags FM token transfers**, **Bags FM token trades**, and **real-time Bags FM price API** streams. :::note Bags FM tokens are launched on Meteora DBC. ::: ## Table of Contents ### [API Endpoints](#api-endpoints) 1. **[New Bags FM Token Created (Instructions API v1)](#1-new-bags-fm-token-created-instructions-api-v1)** 2. **[New Bags FM Token Created (Instructions API v2)](#2-new-bags-fm-token-created-instructions-api-v2)** 3. **[New Bags FM Token Created (TokenSupply API)](#3-new-bags-fm-token-created-tokensupply-api)** 4. **[USD Price of All Bags FM Tokens (Stream API)](#4-usd-price-of-all-bags-fm-tokens-stream-api)** 5. **[Price of Bags FM Tokens vs Quote Tokens (Stream API)](#5-price-of-bags-fm-tokens-vs-quote-tokens-stream-api)** 6. **[All Trades of Bags FM Tokens (DEXTrades API)](#6-all-trades-of-bags-fm-tokens-dextrades-api)** 7. **[Latest Trades of Bags FM Tokens (DEXTradeByToken API)](#7-latest-trades-of-bags-fm-tokens-dextradebytoken-api)** 8. **[All Transfers of Bags FM Tokens (Token Transfers API)](#8-all-transfers-of-bags-fm-tokens-token-transfers-api)** ## Key Features - **Real-time Bags FM token creation tracking** via **Solana token creation API** - **Solana token supply updates** for Bags FM tokens - **Live USD price streams** for Bags FM tokens with **Bags FM token USD price stream** - **Price feeds against quote tokens** for comprehensive market data - **Historical and latest trades** from DEXs using **Bags FM token trades** endpoints - **Complete token transfer history** with **Bags FM token transfers** tracking --- ## Endpoints & Queries ### 1. New Bags FM Token Created (Instructions API v1) Track **new Bags FM token creation** events on Solana using the **Instructions API**. This **Bags token creation API** endpoint provides real-time data on token launches by tracking the Bags.FM Creator program. To convert this API into a stream, simply add `subscription` in front of the query. Check out [this example](https://ide.bitquery.io/of-Bagsfm-token-creation-using-instructions-stream-v1). 🔗 [Try Query](https://ide.bitquery.io/Bagsfm-token-creation-using-instructions-api-v1_2) ```graphql { Solana { Instructions( orderBy: { descending: Block_Time } where: { Instruction: { Program: { Method: { is: "mintTo" } } } Transaction: { Result: { Success: true } Signer: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } } limit: { count: 10 } ) { Instruction { Program { Arguments { Name Value { __typename ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method AccountNames Json Name } Accounts { Address } BalanceUpdatesCount CallPath CallerIndex Data Depth ExternalSeqNumber Index InternalSeqNumber Logs TokenBalanceUpdatesCount } Transaction { Signature FeePayer Signer } } } } ``` --- ### 2. New Bags FM Token Created (Instructions API v2) Fetch Bags FM token creation using the **Instructions API**. In this version, we track Meteora DBC's instructions. To convert this API into a stream, simply add `subscription` in front of the query. Check out [this example](https://ide.bitquery.io/Bagsfm-token-creation-using-instructions-stream-v2_4). 🔗 [Try Query](https://ide.bitquery.io/Bagsfm-token-creation-using-instructions-stream-v2_5) ```graphql query { Solana { Instructions( limit: { count: 100 } orderBy: { descending: Block_Time } where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { is: "initialize_virtual_pool_with_spl_token" } } Accounts: { includes: { Address: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } } } Transaction: { Result: { Success: true } } } ) { Instruction { Program { Arguments { Name Value { __typename ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method AccountNames Json Name } Accounts { Address } BalanceUpdatesCount CallPath CallerIndex Data Depth ExternalSeqNumber Index InternalSeqNumber Logs TokenBalanceUpdatesCount } Transaction { Signature FeePayer Signer } } } } ``` --- ### 3. New Bags FM Token Created (TokenSupply API) Track Bags FM token creation using the **Solana TokenSupply API**. This endpoint provides **Bags FM token data** including supply information and creation timestamps. For the same API as a WebSocket stream, [try this](https://ide.bitquery.io/Bagsfm-token-creation-stream-using-Solana-token-supply-updates). 🔗 [Try Query](https://ide.bitquery.io/Bagsfm-token-creation-using-Solana-token-supply-updates) ```graphql { Solana { TokenSupplyUpdates( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { is: "initialize_virtual_pool_with_spl_token" } } } Transaction: { Signer: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } TokenSupplyUpdate: { Amount: { ne: "0" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Instruction { Program { Method } } TokenSupplyUpdate { Currency { Name Symbol MintAddress Decimals } Amount AmountInUSD PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD Account { Address Owner Token { Owner } } } Block { Time Height } Instruction { Program { Address Method } } Transaction { Signature Signer } } } } ``` --- ### 4. USD Price of All Bags FM Tokens (Stream API) Get **real-time USD prices** of all Bags FM tokens with the **Bitquery Price Index Stream API**. This **Bags FM token USD price WebSocket stream** provides continuous price updates. 🔗 [Try Stream](https://ide.bitquery.io/USD-Price-of-all-BAGs-token-in-Stream) If you want to use it as a regular API, simply remove `subscription` from the front of the query. ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true } Token: { Address: { endsWith: "BAGS" } } } ) { Token { Id Symbol Address Name } Interval { Time { Start End Duration } } Volume { Usd Quote Base } Price { Average { Mean } Ohlc { Open High Low Close } } } } } ``` --- ### 5. Price of Bags FM Tokens vs Quote Tokens (Stream API) Fetch **token-to-token prices** for all Bags FM tokens against their **quote tokens**. This **real-time Bags FM price WebSocket stream** provides comprehensive market data. 🔗 [Try Query](https://ide.bitquery.io/Price-of-all-Bags-FM-token-against-their-relevant-quote-token-in-Stream) ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: false } Token: { Address: { endsWith: "BAGS" } } } ) { Token { Id Symbol Address Name } QuoteToken { Name Symbol Address } Interval { Time { Start End Duration } } Volume { Usd Quote Base } Price { Average { Mean } Ohlc { Open High Low Close } } } } } ``` --- ### 6. All Trades of Bags FM Tokens (DEXTrades API) Get **all trades of Bags FM tokens** from Meteora and other DEXs. This **Bags FM token trades** WebSocket provides comprehensive trading data. 🔗 [Try Query](https://ide.bitquery.io/All-Trade-for-Bagsfm-tokens) ```graphql subscription { Solana { DEXTrades( where: { any: [ { Trade: { Buy: { Currency: { UpdateAuthority: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } } } } { Trade: { Sell: { Currency: { UpdateAuthority: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } } } } ] } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Trade { Dex { ProtocolName ProtocolFamily } Buy { Amount AmountInUSD Currency { MetadataAddress ProgramAddress TokenCreator { Address } UpdateAuthority Symbol Name MintAddress } Price } Sell { Amount AmountInUSD Currency { Symbol Name MintAddress } Price } } Block { Time Height } Transaction { Signature FeePayer } } } } ``` --- ### 7. Latest Trades of Bags FM Tokens (DEXTradeByToken API) Fetch the **latest trades of Bags FM tokens** with the **DEXTradeByToken API**. This endpoint provides real-time **Bags FM token trades** data. 🔗 [Try Query](https://ide.bitquery.io/Latest-trades-of-Bags-FM-token-using-Dextradebytoken-api_1) ```graphql query LatestTrades { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Trade: { Currency: { UpdateAuthority: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } Side: { Currency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN" "EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm" ] } } } } } ) { Block { Time } Transaction { Signature Signer FeePayer } Trade { Market { MarketAddress } Dex { ProtocolName ProtocolFamily ProgramAddress } AmountInUSD PriceInUSD Price Amount Currency { Symbol MintAddress Name } Side { Type Currency { Symbol MintAddress Name } AmountInUSD Amount } } } } } ``` --- ### 8. All Transfers of Bags FM Tokens (Token Transfers API) Track **all transfers of Bags FM tokens** across wallets. This **Bags FM token transfers** endpoint provides complete transfer history. 🔗 [Try Query](https://ide.bitquery.io/Solana-token-transfers-of-Bags-fm-tokens) ```graphql { Solana { Transfers( orderBy: { descending: Block_Time } limit: { count: 10 } where: { Transfer: { Currency: { UpdateAuthority: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } } } ) { Block { Time Height Slot } Transfer { Amount AmountInUSD Authority { Address } Currency { UpdateAuthority Name Symbol MintAddress } Index Receiver { Address Owner } Sender { Address Owner } } } } } ``` ## Video Tutorials ### Get Unlimited Bags FM Token Data Using Bitquery API ## Use Cases - **Trading Platforms** – Integrate **Bags FM price feeds**, **Bags FM token trades**, and liquidity data using the **Bitquery Bags FM API** - **Analytics Dashboards** – Track creation, **Bags FM token transfers**, supply, and prices with comprehensive **Bags FM token data** - **Arbitrage Bots** – Monitor **Bags FM token USD price stream** differences in real time ## Why Use Bitquery for Bags FM API? - **Low-latency blockchain data** (sub-400ms, moving to <100ms) for **real-time Bags FM price API** - **Comprehensive Solana coverage** with real-time streams for **Bags FM token data** - **Unified price index** for accurate token valuations via **Bags FM token USD price stream** - **Historical + real-time queries** for flexible use cases with **Bags FM token trades** and **Bags FM token transfers** ## Multi-Exchange Data The **Bags FM token trades** endpoints aggregate data from multiple Solana DEXs: - [Meteora API](/docs/blockchain/Solana/Meteora-DAMM-v2-API/) - [Raydium API](/docs/blockchain/Solana/Solana-Raydium-DEX-API/) - [Orca API](/docs/blockchain/Solana/solana-orca-dex-api/) - [Jupiter API](/docs/blockchain/Solana/solana-jupiter-api/) - [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [Letsbonk API](/docs/blockchain/Solana/letsbonk-api/) ## 🔗 Related Solana APIs - **[Solana Instructions API](/docs/blockchain/Solana/solana-instructions/)** - Track token creation and burn instructions - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Monitor trading activities across all DEXs - **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** - Track token transfers and movements - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor balance changes from trades and transfers - **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** - Track token supply and creation events ## Conclusion The **Bags FM API (via Bitquery)** delivers **complete blockchain data access** for Bags FM tokens. From **token creation** and **supply updates** to **real-time USD prices** through [crypto price API](/docs/trading/crypto-price-api/), **DEX trades**, and **transfers**, it provides everything you need to build apps, dashboards, and trading systems. The **Bitquery Bags FM API** is your comprehensive solution for accessing **Bags FM token data**, **Bags FM token transfers**, **Bags FM token trades**, and **real-time Bags FM price API** streams on the Solana blockchain. --- ## Bags.fm API on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/bags-fm-api/ Bags.fm API on Robinhood Chain: bags_v2 trades, prices, OHLCV, market cap, whale trades, top traders and bonding-curve events via Bitquery GraphQL. # Bags.fm API on Robinhood Chain **[Bags.fm](https://bags.fm/)** is a token launchpad on the **Robinhood** network where tokens trade on a bonding-curve AMM. This guide focuses on **Bags.fm trading data** — live and historical trades, USD prices, OHLCV/K-line candles, market cap, whale trades, top traders, and the raw bonding-curve `TokensBought`/`TokensSold` events — using Bitquery's `Trading` and `EVM(network: robinhood)` APIs. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) - [Flap.sh API on Robinhood](/docs/blockchain/robinhood/flap-sh-api) - [Pons Launchpad API on Robinhood Chain](/docs/blockchain/robinhood/pons-api) — bonding-curve launchpad, graduations, Uniswap v4 pools - [Pools.trade API on Robinhood](/docs/blockchain/robinhood/pools-trade-api) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers) - [WebSocket subscriptions](/docs/subscriptions/websockets/) ::: --- ## Bags.fm identifiers Bags trades are indexed in the `Trading` cube under the **Bags** protocol family. Filter with `ProtocolFamily` (or `Protocol`) — you do **not** need a per-token contract address, since every Bags token trades under the same family. | Field | Value | Notes | | --- | --- | --- | | `Pair.Market.ProtocolFamily` | `Bags` | Selects all Bags markets across tokens | | `Pair.Market.Protocol` | `bags_v2` | Current Bags protocol version | | `Network` / `NetworkBid` | `Robinhood` / `bid:robinhood` | Robinhood network | | **Per-token Bags AMM** (beacon proxy, one per token) | `0xfa925c0589e98f564cd7456a0e7cd80722724ac5` (example: the MERRY AMM) | Each launch gets its own AMM proxy; it is the `Pair.Market.Program` of that token's `bags_v2` trades and the `LogHeader.Address` of its `TokensBought` / `TokensSold` / `FeesSplit` events. An AMM goes quiet when its token does, so look the address up from a recent trade rather than hard-coding it | | **Bags AMM logic contract** (beacon implementation) | `0x419890a21711c3d3af46b58548376420b9723275` | Shared implementation behind every per-token AMM; appears as `Log.SmartContract` | | **Bags factory (launch)** | `0xe8cc4431adf8b5a847c113ef0c6af9043219cb37` | Mints new Bags tokens — see [launches](/docs/blockchain/robinhood/robinhood-meme-coin-launches#bagsfm) | :::note Per-token `Market.Program` Each Bags token exposes its own `Pair.Market.Program` (the token's bonding-curve/pool contract). To scope trades to a single token, filter by `Pair.Token.Address` rather than `Program`; to get **all** Bags trading activity, filter by `ProtocolFamily: {is: "Bags"}`. ::: --- ## New Bags Token Launches To detect **newly created** Bags tokens (before or alongside their first trades), use the mint-transfer pattern on the Bags factory contract — covered in detail on the [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches#bagsfm) page. ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0xe8cc4431adf8b5a847c113ef0c6af9043219cb37"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time } Transaction { Hash From } Transfer { Amount Receiver Currency { Name Symbol SmartContract } } } } } ``` --- ## Real-Time Bags Trades Stream every Bags trade as it is indexed via a GraphQL `subscription` on `Trading.Trades`, scoped to the Bags protocol family on Robinhood. Includes side (buy/sell), trader, base/quote amounts (native and USD), market cap, and full transaction header. ▶️ [Run in IDE](https://ide.bitquery.io/bags-amm-trade-websocket) ```graphql subscription { Trading { Trades( where: {Pair: {Market: {ProtocolFamily: {is: "Bags"}, Network: {is: "Robinhood"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network Protocol ProtocolFamily } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ```
Sample response ```json { "Side": "Sell", "Amounts": { "Base": 73809640, "Quote": 0.1017578 }, "AmountsInUsd": { "Base": 190.31902, "Quote": 190.31883 }, "Block": { "Date": "2026-07-16", "Time": "2026-07-16T17:25:21Z", "Timestamp": "1784222721000000000" }, "Supply": { "CirculatingSupply": 0, "MarketCap": 2578.51 }, "Trader": { "Address": "0x00a60b9760a4aa1a2fd6388b5cb6295f4c90cee0" }, "Pair": { "Currency": { "Name": "Stud", "Symbol": "Stud", "Id": "bid:robinhood:0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a" }, "Market": { "Program": "0xfa925c0589e98f564cd7456a0e7cd80722724ac5", "Protocol": "bags_v2", "ProtocolFamily": "Bags", "Network": "Robinhood" }, "QuoteCurrency": { "Name": "Ethereum", "Symbol": "ETH", "Id": "bid:eth" }, "Token": { "Address": "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a", "Symbol": "Stud", "IsNative": false }, "QuoteToken": { "Symbol": "ETH", "IsNative": true, "Id": "bid:robinhood" } } } ```
--- ## Latest Bags Trades The query counterpart to the stream above — the most recent Bags trades across all tokens, newest first. ▶️ [Run in IDE](https://ide.bitquery.io/bags-trade) ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: {Pair: {Market: {ProtocolFamily: {is: "Bags"}, Network: {is: "Robinhood"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network Protocol ProtocolFamily } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` :::tip Query ⇄ Stream Every query on this page can be turned into a live stream — switch the operation type from `query` to `subscription` in the Bitquery IDE (and drop `orderBy`/`limit`, which don't apply to subscriptions). Over WebSocket, connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol — see [WebSocket authentication](/docs/authorization/websocket/). ::: --- ## Trades for a Specific Bags Token Scope trades to a single Bags token with `Pair.Token.Address`. This example uses the `MERRY` token (`0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a`). ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: { Pair: { Token: {Address: {is: "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a"}} Market: {ProtocolFamily: {is: "Bags"}} } } ) { Side Block { Time } Trader { Address } Amounts { Base Quote } AmountsInUsd { Base } Supply { MarketCap } Pair { Token { Name Symbol Address } QuoteToken { Name Symbol } } TransactionHeader { Hash } } } } ``` --- ## Trades by a Trader on Bags Track all Bags trades made by a specific wallet by filtering on `Trader.Address`. Replace the example with any wallet address. ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: { Trader: {Address: {is: "0x7906d5e4a10fbb07f5491018ab29df072a76eb3d"}} Pair: {Market: {ProtocolFamily: {is: "Bags"}}} } ) { Side Block { Time } Amounts { Base Quote } AmountsInUsd { Base } Pair { Token { Name Symbol Address } QuoteToken { Symbol } } TransactionHeader { Hash } } } } ``` --- ## Whale Trades on Bags Surface large Bags trades by filtering on USD value. This example returns trades of at least `$500` — raise or lower the `AmountsInUsd.Base` threshold to match current Bags liquidity. ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: AmountsInUsd_Base} where: { Pair: {Market: {ProtocolFamily: {is: "Bags"}}} AmountsInUsd: {Base: {ge: 500}} } ) { Side Block { Time } Trader { Address } AmountsInUsd { Base } Amounts { Base Quote } Supply { MarketCap } Pair { Token { Name Symbol Address } } TransactionHeader { Hash } } } } ``` --- ## First Buyers of a Bags Token Get the earliest trades for a token, ordered oldest first, to find the first buyers after launch. Filtered to `Buy` here; remove the `Side` filter for the first trades of any side. ```graphql { Trading { Trades( limit: {count: 50} orderBy: {ascending: [Block_Time, TransactionHeader_Index]} where: { Pair: { Token: {Address: {is: "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a"}} Market: {ProtocolFamily: {is: "Bags"}} } Side: {is: "Buy"} } ) { Block { Time } Trader { Address } Amounts { Base Quote } AmountsInUsd { Base } Side TransactionHeader { Hash } } } } ``` --- ## Top Traders of a Bags Token Rank the biggest traders of a specific Bags token by total USD volume, with a buy/sell split and trade count. Aggregates `Trading.Trades` grouped by trader. ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descendingByField: "volume_usd"} where: { Pair: { Token: {Address: {is: "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a"}} Market: {ProtocolFamily: {is: "Bags"}} } } ) { Trader { Address } volume_usd: sum(of: AmountsInUsd_Base) bought_usd: sum(of: AmountsInUsd_Base, if: {Side: {is: "Buy"}}) sold_usd: sum(of: AmountsInUsd_Base, if: {Side: {is: "Sell"}}) trades: count } } } ``` --- ## Latest Price of a Bags Token Get the latest USD-normalised price of a Bags token using `Trading.Tokens` with the `bid:robinhood` network filter. The price is the pool-weighted average across the token's markets. ```graphql { Trading { Tokens( limit: {count: 1} orderBy: {descending: Interval_Time_End} where: { Token: {Address: {is: "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a"}, NetworkBid: {is: "bid:robinhood"}} Interval: {Time: {Duration: {eq: 1}}} } ) { latest_price: Price { Ohlc { Close } } } } } ``` --- ## Market Cap, FDV and Supply of a Bags Token Get the latest market cap, fully-diluted valuation, supply, price, and USD volume for a single Bags token in one row. ```graphql { Trading { Tokens( limit: {count: 1} orderBy: {descending: Interval_Time_Start} where: { Token: {Address: {is: "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a"}, NetworkBid: {is: "bid:robinhood"}} Interval: {Time: {Duration: {eq: 1}}} } ) { Token { Name Symbol Address } Price { Ohlc { Close } } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply } Volume { Usd } } } } ```
Sample response ```json { "Token": { "Name": "Stud", "Symbol": "Stud", "Address": "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a" }, "Price": { "Ohlc": { "Close": 2.3498699e-06 } }, "Supply": { "MarketCap": 2451.49, "FullyDilutedValuationUsd": 2451.49, "CirculatingSupply": 0, "TotalSupply": 1000000000 }, "Volume": { "Usd": 44.038837 } } ```
--- ## OHLCV / K-Line Candles for a Bags Token Token-level OHLCV candles (USD-normalised, weighted across all pools) for charting. This example uses 1-minute candles (`Duration: 60`); use `1` (1s), `300` (5m), or `3600` (1h — the maximum) as needed. ```graphql { Trading { Tokens( limit: {count: 100} orderBy: {descending: Interval_Time_Start} where: { Token: {Address: {is: "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a"}, NetworkBid: {is: "bid:robinhood"}} Interval: {Time: {Duration: {eq: 60}}} } ) { Interval { Time { Start End } } Price { Ohlc { Open High Low Close } } Volume { Base Quote Usd } Supply { MarketCap } } } } ``` --- ## Top Bags Tokens by Volume Rank the most actively traded Bags tokens by USD volume over the last 24 hours. This aggregates `Trading.Trades` grouped by token — the `Trading.Tokens` cube doesn't expose a protocol-family filter, so scope by `ProtocolFamily` on the trades and group by `Pair.Token`. ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descendingByField: "volume_usd"} where: { Pair: {Market: {ProtocolFamily: {is: "Bags"}}} Block: {Time: {since_relative: {days_ago: 1}}} } ) { Pair { Token { Name Symbol Address } } volume_usd: sum(of: AmountsInUsd_Base) trades: count } } } ```
Sample response ```json { "Pair": { "Token": { "Name": "Crypto Cats", "Symbol": "CRYPTOCATS", "Address": "0x366c07ef29f06c7e9e6d0078eb7e31186f87605c" } }, "trades": "238", "volume_usd": "17691.63" } ```
:::note Getting per-token market cap This aggregation gives volume and trade counts per token. To add the latest market cap / FDV for any token in the results, pass its `Token.Address` to the [Market Cap, FDV and Supply](#market-cap-fdv-and-supply-of-a-bags-token) query above. ::: --- ## Raw Bonding-Curve Trades (`TokensBought` / `TokensSold`) For the lowest-level view, read Bags trades directly from the AMM's decoded logs. The Bags bonding-curve logic contract (`0x419890a21711c3d3af46b58548376420b9723275`, proxied by `0xfa925c0589e98f564cd7456a0e7cd80722724ac5`) emits **`TokensBought`** and **`TokensSold`** with full fee breakdown and virtual reserves — data that isn't exposed by the higher-level `Trading.Trades` cube. ### Bags buys (`TokensBought`) ```graphql { EVM(network: robinhood) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "TokensBought"}}, SmartContract: {is: "0x419890a21711c3d3af46b58548376420b9723275"}}} ) { Block { Time } Transaction { Hash From } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } } } } } } ``` `TokensBought` arguments: `buyer`, `recipient`, `grossQuoteIn`, `netQuoteIn`, `tokensOut`, `feeQuote`, `vaultFeeQuote`, `creatorFeeWETH`, `refundQuote`, `price`, `virtualTokenReserves`, `virtualQuoteReserves`. ### Bags sells (`TokensSold`) Swap the signature name to stream sells. Arguments: `seller`, `recipient`, `tokensIn`, `grossQuoteOut`, `netQuoteToRecipient`, `feeQuote`, `vaultFeeQuote`, `creatorFeeWETH`, `price`, `virtualTokenReserves`, `virtualQuoteReserves`. ```graphql { EVM(network: robinhood) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "TokensSold"}}, SmartContract: {is: "0x419890a21711c3d3af46b58548376420b9723275"}}} ) { Block { Time } Transaction { Hash From } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` :::note Raw integers vs normalized amounts `TokensBought` / `TokensSold` arguments are **raw on-chain integers** (WETH-style quote amounts are `1e18`-scaled; `tokensOut`/`tokensIn` use the token's own decimals). Use `Trading.Trades` (above) when you want decimal-normalized and USD-priced amounts; use these events when you need the exact fee split, `price`, and `virtualTokenReserves`/`virtualQuoteReserves` from the bonding curve. ::: --- ## All Bags AMM Events Enumerate the event signatures emitted through one token's Bags AMM proxy (the MERRY AMM here; swap in the `Pair.Market.Program` of any live Bags token) to discover what else you can index (fee splits, initialization, role/ownership changes). ```graphql { EVM(network: robinhood) { Events( limit: {count: 100} where: {LogHeader: {Address: {is: "0xfa925c0589e98f564cd7456a0e7cd80722724ac5"}}} ) { count Log { Signature { Name } SmartContract } } } } ``` Observed signatures include `TokensBought`, `TokensSold`, `FeesSplit`, `Initialized`, `RoleGranted`, `OwnershipTransferred`, and `BeaconUpgraded` (most emitted by the logic contract `0x419890a21711c3d3af46b58548376420b9723275`). --- ## FAQ ### How do I get all Bags.fm trades? Query `Trading.Trades` filtered by `Pair.Market.ProtocolFamily: {is: "Bags"}` (optionally with `Network: {is: "Robinhood"}`). This returns trades across every Bags token — no per-token address needed. ### How do I stream Bags trades in real time? Run a GraphQL `subscription` on `Trading.Trades` with the same `ProtocolFamily: "Bags"` filter, or open the [WebSocket IDE link](https://ide.bitquery.io/bags-amm-trade-websocket). Any query on this page can be converted to a stream by switching the operation to `subscription`. ### What's the difference between `Trading.Trades` and the `TokensBought`/`TokensSold` events? `Trading.Trades` gives decimal-normalized, USD-priced trades with market cap and a unified buy/sell `Side` — best for analytics and charts. The `TokensBought`/`TokensSold` events are the raw bonding-curve logs with the exact fee breakdown (`feeQuote`, `vaultFeeQuote`, `creatorFeeWETH`), execution `price`, and virtual reserves — best when you need on-chain-exact values. ### How do I get the price, market cap, or OHLCV of a Bags token? Use `Trading.Tokens` with `Token.Address` and `NetworkBid: {is: "bid:robinhood"}`. Set `Interval.Time.Duration` (seconds) for OHLCV candles, or read `Supply.MarketCap` / `Supply.FullyDilutedValuationUsd` for valuations. ### Which protocol value does Bags use? Bags markets report `Protocol: "bags_v2"` under `ProtocolFamily: "Bags"`. Filter on `ProtocolFamily` so your queries keep working across protocol versions. ### How do I detect a newly launched Bags token? Use the mint-transfer pattern on the Bags factory (`0xe8cc4431adf8b5a847c113ef0c6af9043219cb37`) — a transfer from the zero address with `Amount` `1000000000`. See the [launches page](/docs/blockchain/robinhood/robinhood-meme-coin-launches#bagsfm). --- ## Next steps - Stream Bags trades live with the [WebSocket query](https://ide.bitquery.io/bags-amm-trade-websocket) for real-time dashboards and alerts. - Detect new Bags tokens the moment they launch with the [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches#bagsfm). - Compare against other Robinhood launchpads with the [Flap.sh API](/docs/blockchain/robinhood/flap-sh-api). - Explore network-wide prices, OHLCV, and top traders in the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades). --- ## Balances & Holders Cubes URL: https://docs.bitquery.io/docs/cubes/balances-cube/ Query current token and native balances per address with the Balances cube, and rank a token's holders with the Holders cube, on EVM chains and Tron. # Balances & Holders Cubes :::caution These cubes are query-only `Balances` and `Holders` are derived views that answer "what is true now", so there is no underlying event to push. A subscription against either is a valid document and the socket stays open, but **no message is ever delivered** — on EVM or Tron. For live balances, read the balance once and then keep it current from a stream that does fire: `EVM.TransactionBalances` or `EVM.Transfers` (and `Tron.Transfers` on Tron). See [which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/). ::: Two cubes answer balance questions, and picking the right one matters more than the fields you select: | Cube | Question it answers | Shape | | --- | --- | --- | | **`Balances`** | *What does this address hold?* | Current balance per address, live — no snapshot date | | **`Holders`** | *Who holds this token?* | A token's holders ranked by balance, as a dated snapshot | Both read from aggregate-state tables (`balances_by_address` / `balances_by_currency`), so they return the current state directly instead of replaying every change. :::note Availability `Balances` and `Holders` exist on **EVM networks** (`EVM(network: …)`) and **Tron** (`Tron`). They do **not** exist on Solana. Solana balance changes are queried with [`Solana.BalanceUpdates`](/docs/blockchain/Solana/solana-balance-updates) and `Solana.InstructionBalanceUpdates`. ::: ## Balances — what an address holds `Balances` returns one row per address/currency pair with the current amount. `Balance` fields: `Address`, `Amount`, `AmountInUSD`, `UpdateCount`, `FirstChangeTime`, `LastChangeTime`. Its `where` filter accepts **`Balance.Address`** plus `Currency` and `Block`. Note there is **no amount filter** on `Balances` — see [Holders](#holders) if you need to filter or rank by balance size. ### Token balance for one or more addresses ```graphql query TokenBalances($addresses: [String!], $token: String!) { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { in: $addresses } } Currency: { SmartContract: { is: $token } } } orderBy: { descending: Balance_Amount } ) { Balance { Address Amount AmountInUSD UpdateCount LastChangeTime } Currency { Symbol Name SmartContract } } } } ``` ```json { "addresses": [ "0x28C6c06298d514Db089934071355E5743bf21d60", "0x21a31Ee1afC51d94C2eFcCAa2092aD1028285549" ], "token": "0xdac17f958d2ee523a2206206994597c13d831ec7" } ``` To exclude zero balances, apply the filter on the field rather than in `where`: `Amount(selectWhere: { gt: "0" })`. ### Native balance Filter on `Currency: { Native: true }` to get the chain's native asset instead of a token: ```graphql { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x28C6c06298d514Db089934071355E5743bf21d60" } } Currency: { Native: true } } ) { Balance { Address Amount AmountInUSD } Currency { Symbol Native } } } } ``` The same query works on Tron by swapping the selector for `Tron` and using a Tron address. ### Classifying an address from its balance metadata `UpdateCount` with `LastChangeTime` separates wallet types without any labelling data: - **Very high `UpdateCount`, `LastChangeTime` seconds ago** — exchange hot wallet or payment processor; the balance churns continuously. - **Single-digit `UpdateCount` on a large balance** — cold storage, treasury or custody. Funded once, rarely touched. :::caution `FirstChangeTime` is not the address's first-ever activity `FirstChangeTime` reflects the earliest change **within the balances table's retention window**, not the first time the address ever moved funds. For true first-activity, query [Transfers](/docs/cubes/transfers-cube) with an ascending time order instead. ::: ## Holders — who holds a token {#holders} `Holders` lists a token's holders, ranked. It takes a **`date`** argument for the snapshot day, and unlike `Balances` it **does** accept a balance filter — which is what makes large tokens tractable. ```graphql query TopHolders($token: String!, $floor: String!, $date: String!) { EVM(network: eth) { Holders( limit: { count: 100 } orderBy: { descending: Balance_Amount } date: $date where: { Currency: { SmartContract: { is: $token } } Balance: { Amount: { ge: $floor } } } ) { Holder { Address } Balance { Amount } Currency { Symbol Name } } } } ``` ```json { "token": "0x514910771AF9Ca656af840dff83E8264EcF986CA", "floor": "1000000", "date": "2026-07-29" } ``` :::caution Set a balance floor on large tokens An unbounded top-N ranking across every holder of a very large token **times out server-side** — this is a dataset-size limit, not a syntax error. Ethereum USDT times out even with a 50,000,000 floor; Tron USDT behaves the same way. The fix is a `Balance: { Amount: { ge: … } }` floor high enough to shrink the working set. For a *complete* holder distribution rather than the top of it, use [Data Store exports](https://bitquery.io/datastore) or [Kafka streams](/docs/streams/protobuf/kafka-protobuf-python) rather than a synchronous GraphQL query. ::: ## Choosing a dataset | Dataset | When to use | | --- | --- | | **`combined`** | Latest balances. Queries realtime and archive and merges the results. | | **`archive`** | Historical snapshots, and balances for addresses that have not been active recently. | | **`realtime`** | Recent state only. Some aggregates are unavailable here — if you see *"no table can query … consider use archive dataset"*, switch to `combined` or `archive`. | ## Daily balance history `Balances` in the `archive` dataset gives you **one row per address per day**, exposed as `Block.Date`. A 30-day balance history is one query returning 30 rows. ```graphql query DailyBalanceHistory { EVM(network: eth, dataset: archive) { Balances( where: { Balance: { Address: { is: "0x28c6c06298d514db089934071355e5743bf21d60" } } } orderBy: { descending: Block_Date } limit: { count: 30 } ) { Block { Date } Balance { Amount AmountInUSD } Currency { Symbol } } } } ``` Always order by `Block_Date`. Without it you get an arbitrary day and the query still succeeds, which makes the mistake silent. | You need | Use | |---|---| | Current balance per address | `Balances` (latest row) | | Balance on a past date, or a daily series | `Balances` with `Block.Date` — or `Holders(date: …)`, which agrees exactly | | A token's holders, ranked | `Holders` | | When a position first or last moved | `Balances` — `FirstChangeTime`, `LastChangeTime`, `UpdateCount` | | The individual transfers behind a change | [`Transfers`](/docs/cubes/transfers-cube) | The daily aggregate does not say *why* a balance moved. For that, use [`Transfers`](/docs/cubes/transfers-cube) plus transaction context, or `TransactionBalances` for per-transaction balance changes. ## Related - [Address Labels API](/docs/labels/address-labels-api) — identify which of those addresses are exchanges, contracts, or known entities - [Transfers cube](/docs/cubes/transfers-cube) — the transfers that drive most balance changes - [Token Holders API (Ethereum)](/docs/blockchain/Ethereum/token-holders/token-holder-api) — worked `EVM.Holders` examples - [TRC20 USDT API](/docs/blockchain/Tron/usdt-trc20-api) — `Tron.Balances` and `Tron.Holders` in practice --- ## Balances API Documentation URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/ Balances API Documentation: fetch current and historical Ethereum balances with Bitquery GraphQL balance queries. Great for bots, dashboards, and alerts. # Balances API Documentation This section covers how to fetch balance-related data on Ethereum via **Bitquery GraphQL APIs** and **Streams**. To get started, [signup](https://account.bitquery.io/user/account) with Bitquery and get your [Access Token](https://account.bitquery.io/user/api_v2/access_tokens) by following [these](/docs/authorization/how-to-generate/) steps. If you need help getting balance data, reach out to [support](https://t.me/Bloxy_info). ## Modes Supported - GraphQL API - GraphQL Stream - Kafka Stream ## Primary APIs | API | Documentation | Description | |-----|---------------|-------------| | **Balances** | [Address Balance API](/docs/blockchain/Ethereum/balances/balance-api/) | Current and historical token balances for wallet addresses (`EVM.Balances`). | | **Holders** | [Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api) | Top holders, holder counts, and holder activity (`EVM.Holders`). | | **TransactionBalances** | [Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) | Per-transaction balance updates with supply, market cap, reason codes, and streams (`EVM.TransactionBalances`). | ## What is the Balance API? On Ethereum, use the **Balances** cube for address-level balances and the **Holders** cube for token holder lists and counts. Both support `dataset: combined` (realtime + archive) and `dataset: archive` (historical and inactive addresses). See the [Address Balance API](/docs/blockchain/Ethereum/balances/balance-api/), [Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api), and [Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) for queries and IDE examples. The [Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) section also covers validator, miner, MEV, gas, NFT, and self-destruct balance tracking. ## When to Use Which API or Stream? | Use Case | API/Stream | Description | |----------|------------|-------------| | **Latest wallet balances** | [Balances API](/docs/blockchain/Ethereum/balances/balance-api/#balance-of-an-address) | Token balances for an address (`dataset: combined`; use `Amount(selectWhere: { gt: "0" })` for non-zero). | | **Balance on a date** | [Balances API](/docs/blockchain/Ethereum/balances/balance-api/#balance-on-a-specific-date) | Point-in-time snapshot with `Block.Date.till` (`dataset: archive`). | | **Wallet balance for one token on a date** | [Balances API](/docs/blockchain/Ethereum/balances/balance-api/#wallet-balance-for-a-specific-token-on-a-date) | `Block.Date`, `limit: 1`, `orderBy: Block_Date`. | | **Balance history over time** | [Balances API](/docs/blockchain/Ethereum/balances/balance-api/#balance-history-by-date) | Snapshots ordered by `Block_Date`. | | **Top token holders** | [Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api#top-holders-of-a-currency-current) | `orderBy: Balance_Amount`, `limit`. | | **Token holder count** | [Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api#token-holder-count-for-an-erc-20-token) | `uniq(of: Holder_Address)` with `dataset: combined`. | | **Holders above a threshold** | [Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api#holder-count-with-balance-above-a-threshold) | `uniq` with `if: { Balance: { Amount: { gt: "..." } } } }`. | | **Token balance with supply and market cap** | [Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) | `EVM.TransactionBalances` — post balance, supply, USD value per transaction. | | **Real-time balance change streams** | [Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) | Subscribe to balance updates with reason codes. | | **Validator / miner / MEV balance tracking** | [Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) | Specialized trackers for rewards and MEV. | --- ## Banana Gun Users Affected: Tracing Unauthorized Transfers with MoneyFlow URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/banana-gun-incident/ Investigation video: tracing the unauthorized transfers from Banana Gun bot users' wallets with Bitquery MoneyFlow. # Banana Gun Users Affected: Tracing Unauthorized Transfers with MoneyFlow This investigation traces the ETH drained from Banana Gun trading bot users in September 2024 and shows where the attacker moved it. --- ## Bar continuity (OHLC stitching) URL: https://docs.bitquery.io/docs/usecases/tradingview-subscription-realtime/bar-continuity/ Build Bar continuity (OHLC stitching): a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Bar continuity (OHLC stitching) TradingView draws each candle from the **open, high, low, close** you supply. If the next bar’s **open** does not equal the previous bar’s **close**, the bodies can look disconnected or “floating,” even when the underlying stream is correct. That mismatch is common with **aggregated** OHLC from APIs: interval boundaries, late trades, or how the backend rounds bars are not always the same as a strict “open = prior close” rule. This tutorial addresses continuity in two places: | Path | What we do | |------|------------| | **Historical** | After sorting bars from the REST/GraphQL response, run `connectBarContinuity` on the array so each bar’s open (and high/low envelope) lines up with the previous close. See [Getting Historical Data](/docs/usecases/tradingview-subscription-realtime/historical_OHLC/#bar-continuity-historical). | | **Real-time** | Track the last emitted bar’s time and close; when the stream advances to a new candle timestamp, set the new bar’s open to that close and expand high/low. See [Fetching Real-time OHLC](/docs/usecases/tradingview-subscription-realtime/realtime_OHLC/#subscribing-to-the-stream). | ## What changes, what does not - **Adjusted:** `open`, and possibly `high` / `low`, so the candle **touches** the prior close visually. - **Unchanged:** `close`, `volume`, and time—so the **last price** and **volumes** stay as returned by Bitquery. This is a **presentation** normalization for the chart, not a change to exchange-reported economics. ## Placeholder / missing bars Padding the series with synthetic bars (for example zero OHLC) only fills **time slots** so TradingView has enough points. It does **not** fix continuity between **real** API bars. Always run continuity on the real bars first, then prepend placeholders if your app still needs them. ## Reference implementation The sample repo includes: - [`barContinuity.js`](https://github.com/bitquery/tradingview-subscription-realtime/blob/main/src/barContinuity.js) — `connectBarContinuity(bars)` - [`histOHLC.js`](https://github.com/bitquery/tradingview-subscription-realtime/blob/main/src/histOHLC.js) — calls it after sorting - [`webSocketOHLC.js`](https://github.com/bitquery/tradingview-subscription-realtime/blob/main/src/webSocketOHLC.js) — live stitching across candle boundaries --- ## Base API Documentation URL: https://docs.bitquery.io/docs/blockchain/Base/ Base chain data: DEX and protocol trades, slippage, liquidity, tokens, transfers, balances and NFTs, with WebSocket and webhook support. # Base API Documentation :::tip Building a trading app or DEX UI on Base? For **real-time trades and prices on Base** (and the last ~30 days), use the curated [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. For **historical Base data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: ## Overview In this section we will see how to fetch data on tokens, transactions, DEXs like Aerodrome and Uniswap, liquidity pools, and slippage data on Base via APIs and Streams. If you need help getting data on Base, reach out to [support](https://t.me/Bloxy_info). ### What is Base API? Bitquery Base APIs help you fetch onchain data like trades, transactions, balances, token holders, liquidity pools, and slippage data etc using graphQL query. ### What are capabilities of Bitquery Base API? Bitquery Base APIs are very flexible; you can fetch trade, transaction, balance, liquidity, and slippage information for a period, for a specific wallet, and join with other information. ### Difference between Base RPC and Bitquery Base API? | Base RPC | Bitquery Base API | | --- | --- | | JSON-RPC endpoint exposing raw EVM on-chain state and transactions | GraphQL endpoint over pre-indexed, parsed Base chain data (token transfers, DEX trades, logs, calls, etc.) | | No built-in history or analytics—any indexing/aggregation you build or outsource | Historical data, joins, aggregations & real-time subscriptions | | Ideal for submitting transactions | Great for real-time data and historical backtesting without running your own indexer | ### Does Bitquery support Base Websocket and Webhooks? Bitquery supports websocket and webhooks; you can convert most GraphQL APIs into GraphQL streams by changing the word `query` to `subscription`. You can monitor this data via a websocket. More docs and code samples are available [here](/docs/subscriptions/websockets/). ## Quick start Run this minimal GraphQL query to fetch the latest 5 DEX trades on Base: ```graphql query LatestBaseTrades { EVM(network: base) { DEXTrades(limit: { count: 5 }, orderBy: { descending: Block_Time }) { Block { Time } Trade { Dex { ProtocolName } Buy { AmountInUSD Currency { Symbol } } Sell { AmountInUSD Currency { Symbol } } } Transaction { Hash } } } } ``` ## DEX and Protocol APIs - [Aerodrome API](./aerodrome-base-api) - [Uniswap v3 on Base API](./base-uniswap-api) - [Base Dex Trades](./base-dextrades) - [ApeStore API](./apestore-base-api) - [Clanker API](./base-clanker-api) · [DEXrabbit Clanker tokens](https://dexrabbit.bitquery.io/categories/clanker-ecosystem) - [Jump (Base) API](./base-jump-base-api) - Solidly v3 on Base: swaps are in [Base Dex Trades](./base-dextrades) with `ProtocolName: "solidly_v3"` and `ProtocolFamily: "Solidly"`. ## Base Slippage API - [Base Slippage API](./base-slippage-api) Get slippage and price impact data for Base DEX pools. Understand price impact and liquidity depth for token swaps, calculate maximum input amounts at different slippage tolerances, and monitor real-time slippage data across all DEX pools on Base. ## Base Liquidity API - [Base Liquidity API](./base-liquidity-api) Monitor real-time liquidity changes, track pool reserves, and analyze liquidity depth for token pairs on Base DEX pools. Track when liquidity is added or removed, monitor pool health and depth, and analyze liquidity patterns across different pools. ## Tokens, Transfers, Balances - [Base Coins API](./base-coins-api) - [Base Transfers](./base-transfers) - [Base Address Balance API](./base-balance-updates) ## NFTs - [Base NFT](./base-nft) - [Zora on Base API](./base-zora-api) ## AI Agent - [Building an AI Trading Agent on Base](./ai-agent-base-data) ## Videos ### Video Tutorial | Aerodrome: Latest Trades & Most Purchased Tokens ### Video Tutorial | Aerodrome: Latest Liquidity Pools & Pool Liquidity ### Video Tutorial | Base DEX Trades API ### Video Tutorial | Base Transfers in Realtime ### Video Tutorial | Latest Memecoins on Base Browse live Base memecoin DEX prices on [DEXrabbit's Base Meme Coins category](https://dexrabbit.bitquery.io/categories/base-meme-coins). ### Video Tutorial | Base Balance Updates ### Video Tutorial | Build AI Trading Agent on Base ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Base Address Balance API URL: https://docs.bitquery.io/docs/blockchain/Base/base-balance-updates/ Base Address Balance API: fetch current and historical Base balances with Bitquery GraphQL balance queries. Great for bots, dashboards, and alerts. # Base Address Balance API To rank a token's holders, see the [Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api) (`EVM.Holders`). The **Balances** API returns current and historical token balances for an address on Base. To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | | -------------- | ------------------------------------------------------------------------------------------- | | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | Examples: [All Token Balances](#balance-of-an-address) · [Native ETH (Base)](#native-eth-base-balance) · [Balance on a Date](#balance-on-a-specific-date) · [Specific Token](#balance-for-a-specific-token) · [Holder Snapshot](#token-holder-snapshot) ## Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. [Run in IDE](https://ide.bitquery.io/base-balances-address) ```graphql { EVM(network: base, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xbaed383ede0e5d9d72430661f3285daa77e9439f" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) Address } } } } ``` ## Native ETH (Base) Balance Returns the native ETH balance for a wallet on Base (not ERC-20 tokens). Filter with `Currency: { Native: true }` instead of a token contract address. [Run in IDE](https://ide.bitquery.io/base-native-balances-address) ```graphql { EVM(network: base, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xbaed383ede0e5d9d72430661f3285daa77e9439f" } } Currency: { Native: true } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) Address } } } } ``` **Parameters** - `network: base`: Base mainnet. - `dataset: combined`: Merges realtime and archive data for the latest balance state. - `Balance.Address`: Wallet address to query. - `Currency.Native: true`: Native ETH on Base only (see [Native ETH (Base) Balance](#native-eth-base-balance)). **Returned fields** - `Currency.Symbol`, `Currency.SmartContract`: Token metadata. - `Balance.Amount`, `Balance.AmountInUSD`: Token balance and USD value (use `selectWhere` to filter non-zero amounts). ## Balance on a Specific Date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. [Run in IDE](https://ide.bitquery.io/base-balances-by-date) ```graphql query { EVM(network: base, dataset: archive) { Balances( where: { Block: { Date: { till: "2026-05-01" } } Balance: { Address: { is: "0xbaed383ede0e5d9d72430661f3285daa77e9439f" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Balance for a Specific Token Add a `Currency.SmartContract` filter. Always use the contract address, not the token name. Use `0x` for native ETH on Base, or the ERC-20 contract address for a token. [Run in IDE](https://ide.bitquery.io/base-balances-specific-token) ```graphql query { EVM(network: base, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xbaed383ede0e5d9d72430661f3285daa77e9439f" } } Currency: { SmartContract: { is: "0x09403da25c27024c7418fc942dda8ffa70bc7c62" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Token Holder Snapshot The number of unique holders, token supply, and Gini coefficient for the balance amount before a specific timestamp can be derived using the query below. These stats provide a useful holder snapshot for any given time. [Run in IDE](https://ide.bitquery.io/token-holder-snapshot-base)
Click to expand GraphQL query ```graphql query MyQuery($network: evm_network!, $address: String!) { EVM(network: $network, dataset: combined) { Holders( where: {Currency: {SmartContract: {is: $address}}, Balance: {Amount: {gt: "0"}, LastChangeTime: {till: "2026-06-30T00:00:00Z"}}} ) { Balance { LastChangeTime(maximum: Balance_LastChangeTime) } holders: uniq(of: Holder_Address) supply: sum(of: Balance_Amount) gini(of: Balance_Amount) } } } ``` ```json { "network": "base", "address": "0x940181a94A35A4569E4529A3CDfB74e38FD98631" } ```
## Balance History by Date Returns balance snapshots over time for an address. Use `dataset: archive`. Order by `Block_Date` descending and use `limit` to paginate. Add `Currency.SmartContract` under `Currency` to filter by a specific token. [Run in IDE](https://ide.bitquery.io/base-balances-history) ```graphql query { EVM(network: base, dataset: archive) { Balances( where: { Balance: { Address: { is: "0xbaed383ede0e5d9d72430661f3285daa77e9439f" } } Currency: {} } orderBy: { descending: Block_Date } limit: { count: 100 } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } Block { Date } } } } ``` ## Wallet Balance for a Specific Token on a Date Get a wallet's balance for a specific token with `Balance.Address` and `Currency.SmartContract`. This example uses native ETH (`SmartContract: "0x"`) with `dataset: combined`. For a balance on a calendar date, use [Balance on a Specific Date](#balance-on-a-specific-date) with `dataset: archive` and `Block.Date.till`. [Run in IDE](https://ide.bitquery.io/base-wallet-balance-token-at-date) ```graphql query { EVM(network: base, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xbaed383ede0e5d9d72430661f3285daa77e9439f" } } Currency: { SmartContract: { is: "0x" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` --- ## Base Bankr (Doppler) API URL: https://docs.bitquery.io/docs/blockchain/Base/base-bankr-api/ Bankr (Doppler) tokens on Base: new launches, market cap and FDV, OHLC candles, real-time swaps, V4 pools, and top buyers and sellers. # Base Bankr (Doppler) API This page provides a set of queries to track tokens launched by **[Bankr](https://bankr.bot/)** on Base. Bankr deploys tokens using the **[Doppler Protocol](https://docs.doppler.lol/)** (canonical contracts maintained by Whetstone Research). Each token is minted into the Doppler **Airlock** orchestrator, seeded into a **Uniswap V4** multicurve pool via an initializer contract, and traded on V4 from the moment it launches. Bankr uses Doppler's `NoOpMigrator`, which means **liquidity never migrates** — the multicurve LP stays in the same V4 pool forever and fees stream out through `StreamableFeesLockerV2` to the creator and Doppler. Because of this, there is **no on-chain `Graduated` event** for Bankr tokens; "graduation" is inferred from curve exhaustion (initializer's token balance reaching zero, or the pool tick crossing the final curve segment). For the broader DEX schema, see: - [Crypto Trades API ➤](/docs/trading/crypto-trades-api/trades-api) - [Crypto Price API ➤](/docs/trading/crypto-price-api/) - [Base DEX Trades API ➤](/docs/blockchain/Base/base-dextrades) - [Uniswap V4 API ➤](/docs/blockchain/Base/uniswap-v4-api) - [Base Token Market Cap API ➤](/docs/blockchain/Base/base-token-marketcap-api) :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/). ::: ## Bankr / Doppler Contract Map (Base) | Component | Address | Role | | ---------------------------------- | -------------------------------------------- | ------------------------------------------------------------------- | | **Airlock** | `0x660eAaEdEBc968f8f3694354FA8EC0b4c5Ba8D12` | Orchestrator — emits `Create` per launch, receives the initial mint | | **DecayMulticurveInitializer** | `0xd59ce43…` | Holds the V4 LP position (current default) | | **ScheduledMulticurveInitializer** | `0xA36715d…` | Holds the V4 LP position (original Feb 2025 deployment) | | **Uniswap V4 PoolManager** | `0x498581fF718922c3f8e6A244956aF099B2652b2b` | Singleton where swaps actually clear | | **NoOpMigrator** | (reverts on call) | Bankr's migrator slot — disables migration by design | ## Latest Tokens Launched via Bankr Every Bankr launch emits a `Create(address,address,address,address)` event on the Airlock contract. This query returns the most recent launches with the new token address and deployer. [ Try it in the IDE ](https://ide.bitquery.io/Latest-Bankr-launches-Doppler-Airlock-Base) ```graphql { EVM(network: base) { Events( limit: { count: 25 } orderBy: { descending: Block_Time } where: { LogHeader: { Address: { is: "0x660eAaEdEBc968f8f3694354FA8EC0b4c5Ba8D12" } } Log: { Signature: { Name: { is: "Create" } } } } ) { Block { Time } Transaction { Hash From } Arguments { Name Value { __typename ... on EVM_ABI_Address_Value_Arg { address } } } } } } ``` The four positional arguments are typically `(asset, numeraire, initializer, migrator)`. The first address is the newly created token; the third is the multicurve initializer holding its LP; the fourth identifies whether the launch uses `NoOpMigrator` or a real migrator. ## Recent Bankr Tokens Created by a Deployer Filter `Create` events on the Airlock by **`Transaction.From`** to list every Bankr token launched by a specific wallet. Replace the deployer address with the wallet you want to track. [ Try it in the IDE ](https://ide.bitquery.io/All-bankers-tokens-created-by-a-deployer) ```graphql { EVM(network: base, dataset: realtime) { Events( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Log: { SmartContract: { is: "0x660eaaedebc968f8f3694354fa8ec0b4c5ba8d12" } Signature: { Name: { is: "Create" } } } Transaction: { From: { is: "0x36d4f6cddca1219440a5983f4d4459b20682e103" } } } ) { Block { Time } Transaction { Hash From } Arguments { Name Value { __typename ... on EVM_ABI_Address_Value_Arg { address } } } } } } ``` The first address in `Arguments` is the newly minted token contract. ## Real-time Stream of Bankr Launches Convert the above query into a subscription to be notified of every new token the moment it lands on Base. [ Try it in the IDE ](https://ide.bitquery.io/Realtime-stream-Bankr-launches-Base) ```graphql subscription { EVM(network: base) { Events( where: { LogHeader: { Address: { is: "0x660eAaEdEBc968f8f3694354FA8EC0b4c5Ba8D12" } } Log: { Signature: { Name: { is: "Create" } } } } ) { Block { Time } Transaction { Hash From } Arguments { Name Value { __typename ... on EVM_ABI_Address_Value_Arg { address } } } } } } ``` ## Latest Market Cap, FDV, Price for a Bankr Token `Trading.Tokens` returns the latest 1-second interval row with USD price, OHLC, supply, market cap, and FDV. Filter by `Token.Address` + `Token.Network: "Base"`. Example uses OSAURUS (`0xa739D3728C13ad5a0d480525A6B9618863AA5bA3`). [ Try it in the IDE ](https://ide.bitquery.io/Bankr-token-latest-marketcap-OHLC) ```graphql query { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "0xa739d3728c13ad5a0d480525a6b9618863aa5ba3" } Network: { is: "Base" } } Interval: { Time: { Duration: { eq: 1 } } } } ) { Token { Address Symbol Name } Block { Time } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean SimpleMoving ExponentialMoving WeightedSimpleMoving } } Supply { TotalSupply CirculatingSupply MarketCap FullyDilutedValuationUsd } Volume { Base Quote Usd } } } } ``` ## Real-time Market Cap & OHLC Stream Subscribe to live 1-second OHLC + market cap updates for a specific Bankr token. [ Try it in the IDE ](https://ide.bitquery.io/Bankr-token-realtime-marketcap-OHLC-stream) ```graphql subscription { Trading { Tokens( where: { Token: { Address: { is: "0xa739d3728c13ad5a0d480525a6b9618863aa5ba3" } Network: { is: "Base" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Token { Address Symbol Name } Block { Time } Price { Ohlc { Open High Low Close } Average { Mean } } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } Volume { Usd } } } } ``` ## OHLC Candles (1-Minute) for a Bankr Token Build candlestick charts directly from `Trading.Tokens` using 60-second intervals. [ Try it in the IDE ](https://ide.bitquery.io/Bankr-token-1min-OHLC-candles) ```graphql query { Trading { Tokens( limit: { count: 100 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "0xa739d3728c13ad5a0d480525a6b9618863aa5ba3" } Network: { is: "Base" } } Interval: { Time: { Duration: { eq: 60 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time } Interval { Time { Start End Duration } } Price { Ohlc { Open High Low Close } } Volume { Base Quote Usd } } } } ``` ## Real-time DEX Swaps for a Bankr Token Bankr trades clear on the Uniswap V4 singleton. Use the **[Crypto Trades API](/docs/trading/crypto-trades-api/trades-api)** (`Trading.Trades`) to stream swap-level rows with **USD price**, **market cap**, **supply**, **trader**, and **V4 pool id**. Filter by **`Pair.Market.Network: "Base"`**, **`Pair.Market.Protocol: "uniswap_v4"`**, and **`Pair.Token.Id`** (use **`base:`** + lowercase contract, e.g. `base:0xa739d3728c13ad5a0d480525a6b9618863aa5ba3`). [ Try it in the IDE ](https://ide.bitquery.io/Bankr-token-V4-swaps-realtime) ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Base" }, Protocol: { is: "uniswap_v4" } } Token: { Id: { is: "base:0xa739d3728c13ad5a0d480525a6b9618863aa5ba3" } } } } ) { Side Supply { CirculatingSupply MarketCap FullyDilutedValuationUsd } Trader { Address } TransactionHeader { Hash Sender } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Time } Price PriceInUsd Pair { Market { Network Protocol Program } Token { Address Symbol } QuoteToken { Address Symbol } Pool { Id Address } } } } } ``` ## All Pools for a Bankr Token (V4 PoolIds) A Bankr token can have multiple V4 multicurve pools (e.g., one against WETH and one against USDC). List them with trade counts. [ Try it in the IDE ](https://ide.bitquery.io/Bankr-token-all-V4-pools) ```graphql { EVM(network: base) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } Currency: { SmartContract: { is: "0xa739d3728c13ad5a0d480525a6b9618863aa5ba3" } } } } ) { Trade { PoolId Side { Currency { Symbol SmartContract } } } trades: count } } } ``` ## Top Buyers of a Bankr Token (Last 24h) Rank wallets by USD spent on a specific Bankr token over the last 24 hours. [ Try it in the IDE ](https://ide.bitquery.io/Bankr-token-top-buyers-24h) ```graphql { EVM(network: base) { DEXTradeByTokens( limit: { count: 25 } orderBy: { descendingByField: "spentUsd" } where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } Currency: { SmartContract: { is: "0xa739d3728c13ad5a0d480525a6b9618863aa5ba3" } } Side: { Type: { is: buy } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Buyer } spentUsd: sum(of: Trade_Side_AmountInUSD) buys: count } } } ``` ## Top Sellers of a Bankr Token (Last 24h) Same shape as above, but for sells. [ Try it in the IDE ](https://ide.bitquery.io/Bankr-token-top-sellers-24h) ```graphql { EVM(network: base) { DEXTradeByTokens( limit: { count: 25 } orderBy: { descendingByField: "receivedUsd" } where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } Currency: { SmartContract: { is: "0xa739d3728c13ad5a0d480525a6b9618863aa5ba3" } } Side: { Type: { is: sell } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Seller } receivedUsd: sum(of: Trade_Side_AmountInUSD) sells: count } } } ``` ## Base Tokens Above a Market Cap Threshold Stream every Base token currently above $100k FDV. Useful as a high-mcap or "graduated by mcap" alert. [ Try it in the IDE ](https://ide.bitquery.io/Base-tokens-above-100k-marketcap-stream) ```graphql subscription { Trading { Tokens( where: { Token: { Network: { is: "Base" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { FullyDilutedValuationUsd: { gt: 100000 } } } ) { Token { Address Symbol Name } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } Price { Ohlc { Close } } Volume { Usd } } } } ``` To narrow strictly to Bankr-deployed tokens, intersect with the list of token addresses emitted by `Airlock.Create` (first query on this page). ## Newly Launched Bankr Tokens With Trades (Last Hour) Combine the launch feed with trading data to surface tokens that launched in the last hour and already have on-chain volume. [ Try it in the IDE ](https://ide.bitquery.io/Bankr-tokens-last-hour-with-trades) ```graphql { Trading { Tokens( limit: { count: 50 } limitBy: { by: Token_Address, count: 1 } orderBy: { descending: Block_Time } where: { Token: { Network: { is: "Base" } } Interval: { Time: { Duration: { eq: 1 } } } Block: { Time: { since_relative: { minutes_ago: 60 } } } Volume: { Usd: { gt: 100 } } } ) { Token { Address Symbol Name } Block { Time } Price { Ohlc { Open Close } } Volume { Usd } Supply { FullyDilutedValuationUsd MarketCap } } } } ``` --- ## Base Chain DEX Trades API URL: https://docs.bitquery.io/docs/blockchain/Base/base-dextrades/ Query and stream Base chain DEX trades with Bitquery GraphQL: live swap streams, real-time token prices, USD pricing and per-pair trade history. # Base Chain DEX Trades API :::tip Need real-time Base DEX data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API** (filter with `Pair.Market.Network: Base`). Use this page when you need **historical Base data older than ~30 days** (with `dataset: combined` or `archive`), raw per-swap detail, or call / event context. For full-chain coverage — Aerodrome and Uniswap trades, transfers, balances and bridge flows — see the [Base API](https://bitquery.io/blockchains/base-blockchain-api) page. ::: In this section we will see how to get Base DEX trades information using our API. ## Live DEX swap stream (Base) {#crypto-trades-live-stream} [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api): one row per swap, with USD and supply. Filter **`Pair.Market.Network: Base`**. [When to use this vs chain DEX APIs](/docs/cubes/dextrades-dextradebytokens-trading-trades). Run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-Base-Trade-Stream). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Base" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` ## Subscribe to Latest Base Trades This example uses the chain-specific **DEXTrades** cube via `EVM(network: base) { DEXTrades }` (pool-side Buy/Sell; see [DEXTrades cube](/docs/cubes/dextrades)). USD can be weak on small tokens. For trader + USD swap rows, use the [stream at the top](#crypto-trades-live-stream). Read [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) to get a better understanding on when to use which cube. You can find the query [here](https://ide.bitquery.io/subscribe-to-dex-trades-on-base) ```graphql subscription MyQuery { EVM(network: base) { DEXTrades { Block { Time Number } Transaction { Hash } Call { Signature { Name Signature } } Log { Index SmartContract Signature { Signature Name } } Trade { Sender Buy { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } Dex { SmartContract ProtocolName ProtocolVersion } Sell { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } ``` ## Subscribe to Latest Price of a Token in Real-time This query provides real-time updates on price of USDC `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` in terms of DAI `0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb`, including details about the DEX, market, and order specifics. Find the query [here](https://ide.bitquery.io/Price-of-USDC-in-terms-of-DAI-on-Base-network#) ```graphql subscription { EVM(network: base) { DEXTrades( where: {Trade: {Sell: {Currency: {SmartContract: {is: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"}}}, Buy: {Currency: {SmartContract: {is: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb"}}}}} ) { Block { Time } Trade { Buy { Amount Buyer Seller Price_in_terms_of_sell_currency: Price Currency { Name Symbol SmartContract } } Sell { Amount Buyer Seller Price_in_terms_of_buy_currency: Price Currency { Symbol SmartContract Name } } } } } } ``` ## Latest USD Price of a Token The below query retrieves the USD price of a token on Base chain by setting `SmartContract: {is: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb"}` . Check the field `PriceInUSD` for the USD value. You can access the query [here](https://ide.bitquery.io/Get-latest-price-of-DAI-in-USD-on-Base#). ```graphql subscription { EVM(network: base) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb"}}}} ) { Transaction { Hash } Trade { Buyer AmountInUSD Amount Price PriceInUSD Seller Currency { Name Symbol SmartContract } Dex { ProtocolFamily SmartContract ProtocolName } Side { Amount AmountInUSD Buyer Seller Currency { Name SmartContract Symbol } } } } } } ``` ## Get First 500 Buyers of a specific token Below API gets you the first 500 buyers of a specific Base chain token, here as example we have taken this token `0x58538e6A46E07434d7E7375Bc268D3cb839C0133`. Try the API [here](https://ide.bitquery.io/first-500-buyers-of-a-specific-base-token#). ```graphql query MyQuery { EVM(network: base, dataset: combined) { DEXTrades( limit: { count: 500 } orderBy: { ascending: Block_Time } limitBy: { count: 1, by: Trade_Sell_Buyer } where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x58538e6A46E07434d7E7375Bc268D3cb839C0133" } } } } } ) { Block { Time } Trade { Sell { Buyer } } Transaction { From Hash } } } } ``` ## Get Price Change 5min, 1h, 6h and 24h of a specific token Use below query to get price change 5min, 1h, 6h and 24h of a specific token. Change the `Currency{SmartContract}` and `Dex{SmartContract}` according to your needs. Test the query [here] (https://ide.bitquery.io/Price-change-5min-1hr-6hr-24h-precentage-of-a-specific-token). ```graphql query MyQuery { EVM(dataset: combined network:base) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0x1111111111166b7FE7bd91427724B487980aFc69"}}, Dex: {SmartContract: {is: "0xEdc625B74537eE3a10874f53D170E9c17A906B9c"}}}, TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ){ Trade { Price_5min_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{minutes_ago:5}}}}) Price_1h_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{hours_ago:1}}}}) Price_6h_ago: PriceInUSD(minimum: Block_Number if:{Block:{Time:{since_relative:{hours_ago:6}}}}) Price_24h_ago: PriceInUSD(minimum: Block_Number) CurrentPrice: PriceInUSD(maximum: Block_Number) } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum( of: Trade_Side_AmountInUSD ) Price_Change_5min: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100") Price_Change_1h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100") Price_Change_6h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100") Price_Change_24h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100") } } } ``` ## Top 10 Base Tokens by Price Change in last 1h Use below query to get top 10 Base Tokens by Price Change in last 1h. Test the query [here] (https://ide.bitquery.io/Top-10-base-tokens-by-price-change-in-last-1-hr). ```graphql query MyQuery { EVM(dataset: combined network:base) { DEXTradeByTokens( limit:{count:10} orderBy:{descendingByField:"Price_Change_1h"} where: {TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Trade { Currency { Name Symbol SmartContract } Price_5min_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) Price_1h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) Price_6h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) Price_24h_ago: PriceInUSD(minimum: Block_Number) CurrentPrice: PriceInUSD(maximum: Block_Number) Side { Currency { Name Symbol SmartContract } } Dex{ SmartContract } } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum(of: Trade_Side_AmountInUSD) Price_Change_5min: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100" ) Price_Change_1h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100" ) Price_Change_6h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100" ) Price_Change_24h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100" ) } } } ``` ## Aggregated Token Data (Volume & Price, Last 24h) Get up to 100 tokens with aggregated USD volume and average price over the last 24 hours, plus volume and price for 1h, 4h, and 24h via conditional metrics (Trading API; includes Base and other chains). ▶️ [Aggregated Token Data](https://ide.bitquery.io/aggregated-data) ```graphql { Trading { Tokens( limit: { count: 100 } limitBy: { count: 1, by: Token_Id } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Volume { Usd H1VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 1 } } } }) H4VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 4 } } } }) H24VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 24 } } } }) } Price { Average { currentPrice: Mean(maximum: Block_Time) H1Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) H4Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 4 } } } } ) H24Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) } } } } } ``` --- ## Trader-Focused Trade APIs (with USD Price, Market Cap & Supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get All DEX Trades on Base With Price, Market Cap, and Supply Stream **all Base DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Network: Base`** to capture every swap across all Base DEXs in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Base-with-Price-Marketcap-supply).
Click to expand GraphQL query ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Base" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
### Top Traders by PnL for a Specific Pool (Last 30 Minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-base-pool_1).
Click to expand GraphQL query ```graphql { Trading { Trades( limit: { count: 10 } orderBy: { descendingByField: "PnL" } where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
--- ## Video Tutorial | How to get Base Decentralized Exchange Data with DEX Trades API --- ## Base Chain Token Transfers API URL: https://docs.bitquery.io/docs/blockchain/Base/base-transfers/ Base Chain Token Transfers API: monitor Base native and token transfers in real time with Bitquery GraphQL APIs. Run it in the IDE, then ship in your app. # Base Chain Token Transfers API In this section we'll have a look at some examples using the Base Transfers API. ## Subscribe to Recent Whale Transactions of a particular currency The subscription query below fetches the whale transactions on the Base network. We have used USDC address `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. You can find the query [here](https://ide.bitquery.io/Whale-transfers-of-USDC-on-base#) ```graphql subscription { EVM(network: base) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"}}, Amount: {ge: "10000"}}} ) { Transaction { From Hash } Transfer { Amount Sender Receiver Currency { SmartContract Symbol Name Fungible Native } Id } } } } ``` ## Sender is a particular address This websocket retrieves transfers where the sender is a particular address `0x3304E22DDaa22bCdC5fCa2269b418046aE7b566A`. For this subscription query we use `where` keyword and in that we specify `{Transfer: {Sender: {is: "0x3304E22DDaa22bCdC5fCa2269b418046aE7b566A"}}}` to get the desired data. You can find the query [here](https://ide.bitquery.io/Sender-is-a-particular-address_3#) ```graphql subscription { EVM(network: base) { Transfers( where: {Transfer: {Sender: {is: "0x3304E22DDaa22bCdC5fCa2269b418046aE7b566A"}}} ) { Transfer { Amount AmountInUSD Currency { Name SmartContract Native Symbol Fungible } Receiver Sender } Transaction { Hash } } } } ``` ## Subscribe to the latest NFT token transfers on Base Chain Let's see an example of NFT token transfers using GraphQL Subscription (Webhook). In the following NFT Token Transfers API, we will be subscribing to all NFT token transfers on Base network. You can run the query [here](https://ide.bitquery.io/NFT-Token-Transfers-API_4#) ```graphql subscription { EVM(network: base) { Transfers(where: {Transfer: {Currency: {Fungible: false}}}) { Transfer { Amount AmountInUSD Currency { Name SmartContract Symbol Fungible HasURI Decimals } URI Sender Receiver } Transaction { Hash } } } } ``` ## Get all transfers of a particular NFT This below query will give you all the transfers of a particular NFT `0xb68CA010776B4584cf49893E75b66583eb884948`. You can test out the query [here](https://ide.bitquery.io/get-all-transfers-of-a-specific-nft). ```graphql query MyQuery { EVM(network: base, dataset: realtime) { Transfers( where: {Transfer: {Currency: {Fungible: false, SmartContract: {is: "0xb68CA010776B4584cf49893E75b66583eb884948"}}}} ) { Transfer { Amount AmountInUSD Currency { Name Native SmartContract Symbol } Id Sender Receiver } Transaction { From Hash } } } } ``` ## Transactions From or To an address We use the `any` filter [ OR condition] to get transactions from or to a wallet. [Run Query](https://ide.bitquery.io/tx-from-to-base-address) ```graphql query MyQuery { EVM(dataset: archive, network: base) { Transfers( limit: {count: 100, offset: 0} where: { any: [ {Transaction: {From: {is: "0x0b2a7f1c6b7fae642a20434be47359e19bfadf4d"}, To: {is: "0x0b2a7f1c6b7fae642a20434be47359e19bfadf4d"}}} {Block: {Date: {after: "2025-08-01"}}} ] } ) { Block { Time Number Date } Transfer { Receiver Sender Currency { Decimals Name SmartContract Symbol ProtocolName } Amount AmountInUSD } Transaction { Hash From To } } } } ``` ## Video Tutorial | How to get Token Transfers data on Base in Realtime ## Deterministic Pagination for Backfilling Transfers When backfilling Base transfer data or building a historical index, use deterministic pagination to guarantee no records are missed or duplicated. **Try it live:** [Deterministic Transfer API](https://ide.bitquery.io/Reliable-transfer-api) ```graphql { EVM(dataset: combined, network: base) { Transfers( where: { Transfer: { Success: true } } orderBy: { ascending: [ Block_Number, Transaction_Index, Call_Index, Log_Index, Transfer_Index, Transfer_Type ] } limit: { count: 10, offset: 0 } ) { Block { Time Number } Transaction { Hash From Index } Transfer { Amount AmountInUSD Sender Receiver Index Currency { Symbol Name SmartContract Decimals Native } } Call { Index } Log { LogAfterCallIndex Index } Transfer { Type } } } } ``` The composite `orderBy` across `Block_Number`, `Transaction_Index`, `Call_Index`, `Log_Index`, `Transfer_Index`, and `Transfer_Type` uniquely positions every transfer, making offset-based pagination safe for backfilling. Increment `offset` by the `count` value on each request. You can pull up to **25,000 records in a single request** by setting `count: 25000`. --- ## Base Clanker API URL: https://docs.bitquery.io/docs/blockchain/Base/base-clanker-api/ Clanker tokens on Base: latest launches from the Clanker v4 factory and tokens launched by a specific wallet, with token, paired token, hook and locker fields. # Base Clanker API Clanker launches ERC-20 tokens on Base from its v4 factory, `0xE85A59c628F7d27878ACeB4bf3b35733630083a9`. Every launch emits a `TokenCreated` event from the factory and opens a Uniswap v4 pool that uses a Clanker hook. The event carries the new token's address, name, symbol, image and metadata, the `tokenAdmin` that controls it, the `pairedToken` it trades against (such as WETH or USDC), the `poolHook`, the `locker` that holds the pool's liquidity position, the `mevModule` and the `startingTick`. `tokenContext` names the interface that sent the launch, for example `clanker.world`. The factory's events are matched on their `SignatureHash`, `9299d1d1a88d8e1abdc591ae7a167a6bc63a8f17d695804e9091ee33aa89fb67`; a filter on the event name `TokenCreated` returns no rows for this contract. The older Clanker factory `0x375C15db32D28cEcdcAB5C03Ab889bf15cbD2c5E` no longer emits launches. Use it only with `dataset: archive` for tokens created before the v4 factory. To get trades, top traders, OHLCV and token metadata for Clanker tokens, use the [Base Uniswap API](/docs/blockchain/Base/base-uniswap-api/). For live DEX prices across Clanker-launched tokens, see [DEXrabbit's Clanker category](https://dexrabbit.bitquery.io/categories/clanker-ecosystem). ## Latest tokens created using Clanker Returns the 10 most recent Clanker v4 launches with every `TokenCreated` argument. [Run it in the IDE ➤](https://ide.bitquery.io/Clanker-v4-latest-tokens-on-Base) ```graphql query ClankerLatestTokens { EVM(network: base) { Events( limit: {count: 10} orderBy: [{descending: Block_Time}, {descending: Transaction_Index}] where: {Log: {Signature: {SignatureHash: {is: "9299d1d1a88d8e1abdc591ae7a167a6bc63a8f17d695804e9091ee33aa89fb67"}}}, LogHeader: {Address: {is: "0xE85A59c628F7d27878ACeB4bf3b35733630083a9"}}} ) { Block { Time } Transaction { From Hash } Arguments { Name Value { ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` ## Latest tokens created by a specific user using Clanker Filters launches on the wallet that sent the launch transaction. Replace the address with the wallet you want. Launches sent through a third-party app or bot have that app as the sender; read `msgSender` and `tokenAdmin` in the arguments to see who owns the token. [Run it in the IDE ➤](https://ide.bitquery.io/Clanker-v4-tokens-by-admin-on-Base) ```graphql query ClankerTokensByAdmin { EVM(network: base) { Events( limit: {count: 10} orderBy: [{descending: Block_Time}, {descending: Transaction_Index}] where: {Log: {Signature: {SignatureHash: {is: "9299d1d1a88d8e1abdc591ae7a167a6bc63a8f17d695804e9091ee33aa89fb67"}}}, LogHeader: {Address: {is: "0xE85A59c628F7d27878ACeB4bf3b35733630083a9"}}, Transaction: {From: {is: "0x03276f24921df2a96330b8d107a9c289e6c669da"}}} ) { Block { Time } Transaction { From Hash } Arguments { Name Value { ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` --- ## Base Gas Balance Tracker: Fees Paid by Senders and Collected by Vaults URL: https://docs.bitquery.io/docs/blockchain/Base/transaction-balance-tracker/base-gas-balance-tracker/ Track gas on Base from balance changes with Bitquery GraphQL: the three fee vaults, the largest fee credits, what one address paid, and a live fee stream. # Base Gas Balance Tracker: Fees Paid by Senders and Collected by Vaults Base reports gas differently from Ethereum in the `TransactionBalances` cube. Ethereum splits a fee into a gas purchase, a refund and a tip, with reason codes 6, 7 and 5. Base emits two codes only: - **Code 0** for every ordinary balance change: the sender's ETH goes down by the value sent plus the gas paid, and the receiver's goes up by the value. - **Code 5** for the fee credited to the three OP Stack fee vaults: `0x4200000000000000000000000000000000000011` (SequencerFeeVault), `0x4200000000000000000000000000000000000019` (BaseFeeVault) and `0x420000000000000000000000000000000000001a` (L1FeeVault). So the gas a sender paid is read from its own code 0 row, and the fees the network collected are read from the vaults' code 5 rows. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; the cube covers the recent realtime window only, so queries carry a time filter. ## Fee vault balances now `limitBy` on the address keeps the newest row per vault; `PostBalance` is the balance after the latest credit. Saved query [here](https://ide.bitquery.io/top-gas-fee-collectors-base). ```graphql { EVM(network: base) { TransactionBalances( limitBy: { by: TokenBalance_Address, count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) { Block { Time } TokenBalance { Address PostBalance PostBalanceInUSD } } } } ``` ## Largest fee credits in the last ten minutes Each code 5 row is one transaction's contribution to one vault; `fee` is the balance after minus the balance before. Sort on it to find the transactions that paid most. ```graphql { EVM(network: base) { TransactionBalances( limit: { count: 20 } orderBy: { descendingByField: "fee" } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } ) { Block { Number Time } TokenBalance { Address PreBalance PostBalance } Transaction { Hash From To } fee: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## What one address paid in gas The sender's own code 0 row holds the balance before and after; subtracting the value sent leaves the gas. Filter on the address as both the balance owner and the transaction sender. If the address also received ETH inside the same transaction, for example from a swap, the result goes negative, so read it alongside `Transaction.Value`. Saved query [here](https://ide.bitquery.io/Latest-balance-and-gas-fee-paid-for-an-address-base_1). ```graphql { EVM(network: base) { TransactionBalances( limit: { count: 10 } orderBy: { descending: Block_Time } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 0 } Currency: { Native: true } Address: { is: "0x6c8ab6bd67d4df8d131e952edcb00b7e77183b60" } } Transaction: { From: { is: "0x6c8ab6bd67d4df8d131e952edcb00b7e77183b60" } } } ) { Block { Time } TokenBalance { PreBalance PostBalance PostBalanceInUSD } Transaction { Hash Value } gas: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance - $Transaction_Value" ) } } } ``` ## Stream fee income live Every fee credit as it lands, with the sender that paid it. ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Number Time } TokenBalance { Address PreBalance PostBalance } Transaction { Hash From To } fee: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` To watch one wallet's spending instead, stream code 0 rows with `Currency: { Native: true }` and the wallet in both `TokenBalance.Address` and `Transaction.From`, the same filter as the query above. ## Related pages - [Base transaction balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker) - [Base MEV balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-mev-balance-tracker) - [Ethereum gas balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-gas-balance-tracker) - [Balance change reason codes](/docs/blockchain/Base/transaction-balance-tracker/#balance-change-reason-codes) --- ## Base Jump API: Trace a Launchpad Token on Base from Mint to First Trades URL: https://docs.bitquery.io/docs/blockchain/Base/base-jump-base-api/ Base Jump is no longer active on-chain. Its token is a worked example of tracing any Base launchpad with Bitquery GraphQL: the contract, launch trades, methods. # Base Jump API: Trace a Launchpad Token on Base from Mint to First Trades Base Jump was a token launchpad on Base. Its contract, `0x31C0282Fa6D0A82aD22ab63BbaCd87F62B2a9bfD`, receives no calls in the current realtime window, and the token the original guide used, SIBU at `0xEfC79f30b56f36bc49Bf47e8Dccf969fFF214EeD`, was minted, distributed and traded within a few minutes on 28 October 2024 and has not moved since. The launch still makes a clean worked example, because the steps are the same for any launchpad on Base: find the launchpad contract from the token's first transfers, pull the launch trades, and read the contract's methods while it is live. Every query runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. For launchpads active on Base today see the [Clanker](/docs/blockchain/Base/base-clanker-api), [Zora](/docs/blockchain/Base/base-zora-api), [Bankr](/docs/blockchain/Base/base-bankr-api) and [APE Store](/docs/blockchain/Base/apestore-base-api) pages. One coverage fact shapes the page. On Base the `Transfers` and `DEXTradeByTokens` cubes reach years back on the `combined` dataset, while `Calls` and `Events` cover the realtime window only. So the mint and the trades of a 2024 launch are still queryable, but method-level analysis of a contract only works while it is active. ## Step 1: find the launchpad contract from the token The first transfers of a token show where it was minted and who distributed it. The `Transaction.To` on those rows is the contract the deployer called. For SIBU the mint from the zero address went to the Base Jump contract, which then sent the supply on in the same transaction. Saved query [here](https://ide.bitquery.io/base-jump-token-event). ```graphql { EVM(network: base, dataset: combined) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xEfC79f30b56f36bc49Bf47e8Dccf969fFF214EeD" } } } } limit: { count: 10 } orderBy: { ascending: Block_Time } ) { Block { Time } Transfer { Sender Receiver Amount Currency { Symbol Name } } Transaction { Hash From To } } } } ``` ## Step 2: pull the launch trades `DEXTradeByTokens` on the `combined` dataset returns every trade of the token with the venue and the other side. For SIBU that is a short burst of Uniswap v3 trades against WETH. Saved query [here](https://ide.bitquery.io/base-jump-buys). ```graphql { EVM(network: base, dataset: combined) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xEfC79f30b56f36bc49Bf47e8Dccf969fFF214EeD" } } } } limit: { count: 50 } orderBy: { ascending: Block_Time } ) { Block { Time } Trade { Dex { ProtocolName } Amount Side { Amount Currency { Symbol } } } Transaction { Hash From } } } } ``` Replace the selection with `count`, `uniq(of: Transaction_From)` and `Block { first: Time(minimum: Block_Time) last: Time(maximum: Block_Time) }` to size a launch in one row: trades, distinct traders, first and last trade. ## Step 3: read a live contract's methods For a launchpad that is active, group the `Calls` into its contract by signature to see what it exposes and which methods carry the volume. The example is the Clanker contract that emits `TokenCreated` on Base; put the Base Jump contract in its place and the result is empty, which is how you confirm a launchpad has gone quiet. Saved query [here](https://ide.bitquery.io/methods-for-base-jump). ```graphql { EVM(network: base) { Calls( where: { Transaction: { To: { is: "0x375C15db32D28cEcdcAB5C03Ab889bf15cbD2c5E" } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "count" } limit: { count: 20 } ) { Call { Signature { Name Signature } } count } } } ``` From there, filter `Calls` on one signature name and select `Arguments` to decode the parameters of each call; the [Clanker page](/docs/blockchain/Base/base-clanker-api) shows that shape for token creation events. ## Related pages - [Base API hub](/docs/blockchain/Base/) - [Base Clanker API](/docs/blockchain/Base/base-clanker-api) - [Base DEX trades API](/docs/blockchain/Base/base-dextrades) - [Base transfers API](/docs/blockchain/Base/base-transfers) --- ## Base Liquidity API: Uniswap and PancakeSwap Pool Reserves in Real Time URL: https://docs.bitquery.io/docs/blockchain/Base/base-liquidity-api/ Base pool reserves and spot prices with Bitquery GraphQL: one pool now or streamed, every Uniswap v4 pool by PoolId, pools holding cbBTC. Aerodrome excluded. # Base Liquidity API: Uniswap and PancakeSwap Pool Reserves in Real Time The `DEXPoolEvents` cube under `EVM(network: base)` emits one row every time a pool's reserves change, whether by a swap, a deposit or a withdrawal. Each row carries the reserves of both tokens after the change, in token units and in USD, the spot price in both directions, the pool and its protocol, and the transaction that moved it. On Base the rows come from Uniswap v2, v3 and v4 pools and from PancakeSwap v3 and Infinity pools. Aerodrome, the largest DEX on Base by volume, is not in this cube: its swaps are in the [Base DEX trades API](/docs/blockchain/Base/base-dextrades) and its pool balances in the [balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker). The cube holds the recent realtime window only and has no archive dataset: to keep a history, record the stream. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked pool is the Uniswap v3 WETH/USDC pool, `0xb4cb800910b228ed3d0834cf79d697127bbb00e5`. ## Current reserves of a pool The last ten changes to the pool, newest first. Each row is the state after that change: `AmountCurrencyA` and `AmountCurrencyB` are the reserves, `AmountCurrencyAInUSD` and `AmountCurrencyBInUSD` their dollar value, and `AtoBPrice` the spot rate of A in B. Saved query [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_4). ```graphql { EVM(network: base) { DEXPoolEvents( limit: { count: 10 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { SmartContract: { is: "0xb4cb800910b228ed3d0834cf79d697127bbb00e5" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Dex { ProtocolName } } Transaction { Hash } } } } ``` ## The same pool, live As a subscription the filter yields a row per reserve change, a few per minute on this pool. Saved stream [here](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_3). ```graphql subscription { EVM(network: base) { DEXPoolEvents( where: { PoolEvent: { Pool: { SmartContract: { is: "0xb4cb800910b228ed3d0834cf79d697127bbb00e5" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { SmartContract CurrencyA { Symbol } CurrencyB { Symbol } } } Transaction { Hash } } } } ``` ## Every Uniswap v4 pool on Base Uniswap v4 is the busiest source of pool events on Base. All v4 pools live in the PoolManager, `0x498581ff718922c3f8e6a244956af099b2652b2b`, so `Pool.SmartContract` repeats on every row and `Pool.PoolId` is the field that tells pools apart; for v2 and v3 pools `PoolId` is empty. Saved stream [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4_5). ```graphql subscription { EVM(network: base) { DEXPoolEvents( where: { PoolEvent: { Dex: { ProtocolName: { is: "uniswap_v4" } } } } ) { Block { Time } PoolEvent { Pool { PoolId SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } Transaction { Hash } } } } ``` Other protocol names that report on Base: `uniswap_v3`, `uniswap_v2`, `pancake_swap_v3` and `pancakeswap_infinity`. ## Every pool of a token Which pools hold cbBTC, `0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf`, and how much? Ask for pools with cbBTC as `CurrencyA` in the window and keep only the newest row of each with `limitBy` on the pool address; a second run with cbBTC as `CurrencyB` covers the pools that list it second. Because Aerodrome is outside this cube, the answer covers Uniswap and PancakeSwap pools only. Rank by the USD reserve in your code. Saved query [here](https://ide.bitquery.io/top-liquidity-pools-of-cbBTC). ```graphql { EVM(network: base) { DEXPoolEvents( limit: { count: 20 } limitBy: { by: PoolEvent_Pool_SmartContract, count: 1 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { CurrencyA: { SmartContract: { is: "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf" } } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time } PoolEvent { Dex { ProtocolName } Pool { SmartContract PoolId CurrencyB { Symbol SmartContract } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } } } } } ``` ## Row anatomy A row is one reserve change. `Liquidity` holds the two reserves after it, in token units and in USD; `AtoBPrice` and `BtoAPrice` hold the spot rate both ways; `Pool` names the contract, or for Uniswap v4 and PancakeSwap Infinity the manager plus a `PoolId`; `Dex.ProtocolName` is one of `uniswap_v4`, `uniswap_v3`, `uniswap_v2`, `pancake_swap_v3` and `pancakeswap_infinity`; and `Transaction.Hash` points at the swap, deposit or withdrawal behind it. ## Kafka and slippage The `base.dexpools.proto` topic streams these rows as protobuf with lower latency than WebSocket and needs its own credentials; start at the [Kafka streams hub](/docs/category/kafka-streams). The [Base slippage API](/docs/blockchain/Base/base-slippage-api) turns the same pool states into how much each pool can absorb at a given tolerance. ## Related pages - [Base slippage API](/docs/blockchain/Base/base-slippage-api) - [Base DEX trades API](/docs/blockchain/Base/base-dextrades) - [Uniswap v4 on Base](/docs/blockchain/Base/uniswap-v4-api) - [DEXPools cube](/docs/cubes/evm-dexpool/) - [Arbitrum liquidity API](/docs/blockchain/Arbitrum/arbitrum-liquidity-api) --- ## Base MEV Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Base/transaction-balance-tracker/base-mev-balance-tracker/ Base MEV Balance Tracker: stream Base balance changes with reason codes using Bitquery GraphQL subscriptions. Copy GraphQL snippets for production apps. # Base MEV Balance Tracker The Base MEV (Maximal Extractable Value) Balance Tracker API provides real-time balance updates related to MEV activities, including transaction fee rewards, block builder rewards, and other MEV-related balance changes. ## Track MEV-Related Balance Updates Monitor balance changes related to MEV activities, including transaction fee rewards and block builder rewards. Try the API [here](https://ide.bitquery.io/Track-MEV-Related-Balance-Updates-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` **Balance Change Reason Code for MEV:** - **Code 5**: `BalanceIncreaseRewardTransactionFee` - Transaction tip increasing block builder's balance (MEV-related) ## Track Block Builder Rewards Monitor transaction fee rewards received by block builders (MEV extractors): Try the API [here](https://ide.bitquery.io/Track-Block-Builder-Rewards-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Number: { gt: "0" } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash GasPrice } } } } ``` ## Filter by MEV Bot or Builder Address Track balance changes for specific MEV bots or block builders: Try the API [here](https://ide.bitquery.io/Filter-by-MEV-Bot-or-Builder-Address-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xMEVBotOrBuilderAddressHere" } BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash GasPrice } } } } ``` ## Track Large MEV Transactions Monitor large transaction fee rewards that may indicate significant MEV extraction: Try the API [here](https://ide.bitquery.io/Track-Large-MEV-Transactions-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } PostBalanceInUSD: { gt: "1000" } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash GasPrice } } } } ``` --- ## Base Miner Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Base/transaction-balance-tracker/base-miner-balance-tracker/ Base Miner Balance Tracker: stream Base balance changes with reason codes using Bitquery GraphQL subscriptions. Copy GraphQL snippets for production apps. # Base Miner Balance Tracker The Base Miner Balance Tracker API provides real-time balance updates for Base miners, tracking their mining rewards, uncle block rewards, and transaction fee rewards. ## Track Miner Balance Updates Monitor balance changes for Base miners, including block rewards, uncle block rewards, and transaction fee rewards. Try the API [here](https://ide.bitquery.io/Track-Miner-Balance-Updates-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [1, 2, 5] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` **Balance Change Reason Codes for Miners:** - **Code 1**: `BalanceIncreaseRewardMineUncle` - Reward for mining an uncle block - **Code 2**: `BalanceIncreaseRewardMineBlock` - Reward for mining a block - **Code 5**: `BalanceIncreaseRewardTransactionFee` - Transaction tip increasing block builder's balance ## Track Block Mining Rewards Track rewards received by miners for successfully mining blocks: Try the API [here](https://ide.bitquery.io/Track-Block-Mining-Rewards-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 2 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Track Uncle Block Rewards Monitor rewards for mining uncle blocks: Try the API [here](https://ide.bitquery.io/Track-Uncle-Block-Rewards-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 1 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Track Transaction Fee Rewards Monitor transaction fee rewards received by miners: Try the API [here](https://ide.bitquery.io/Track-Transaction-Fee-Rewards-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Filter by Miner Address Track balance changes for a specific miner address: Try the API [here](https://ide.bitquery.io/Filter-by-Miner-Address-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xMinerAddressHere" } BalanceChangeReasonCode: { in: [1, 2, 5] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` --- ## Base NFT Trades and Metadata API URL: https://docs.bitquery.io/docs/blockchain/Base/base-nft/ Base NFT API: track Base NFT trades, ownership, and metadata with Bitquery GraphQL and streams. Includes filters and field selection tips. # Base Chain NFT API In this section we'll have a look at some examples on how to get NFT information on Base using the NFT API. ## Track transfers of an NFT This query subscribes you to the real time transfers of a specific non-fungible token (NFT) on the Base network. You can find the query [here](https://ide.bitquery.io/Transfers-of-a-particular-NFT_1#) ```graphql subscription { EVM(network: base) { Transfers( where: { Transfer: { Currency: { Fungible: false SmartContract: { is: "0x1195Cf65f83B3A5768F3C496D3A05AD6412c64B7" } } } } ) { Block { Hash Number } Transfer { Amount Currency { Name Symbol Native } Sender Receiver } } } } ``` --- ## Base Network Coins API URL: https://docs.bitquery.io/docs/blockchain/Base/base-coins-api/ Base coins: latest coins created on Base, plus an AERO walkthrough covering DEX trades, top ten holders, AERO/USDC OHLC data and total supply. # Base Network Coins API In the recent times, base network has seen rise of many Memecoins and token based ecosystems. In this guide, we will see some queries that could provide beneficial information about these coins, for people to take informed investment decisions. ## Latest Coins Created on Base [This](https://ide.bitquery.io/Latest-Coin-on-Base-Coin_3) query returns the details of all the tokens and Memecoins created on the Base Network for a particular day. ```graphql query LatestCoins { EVM(network: base) { Calls( where: { Call: { Create: true } Arguments: { length: { ne: 0 } } Receipt: { ContractAddress: { not: "0x0000000000000000000000000000000000000000" } } } orderBy: { descending: Block_Time } ) { Arguments { Name Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } } } Transaction { Hash } Receipt { ContractAddress } Block { Time } } } } ``` The `Receipt{ ContractAddress }` field returns the contract address of the newly created token or Memecoin. ## Analysis of AERO Coin In this section, we have a list of queries that returns data that affects investment decisions. For this part, we have chosen AERO token as the token is currently trending and have high trade volume. ### Latest DEX Trades with AERO coin [This](https://ide.bitquery.io/Subscription-for-Latest-Trades-for-AERO_1) subscription returns the information on latest trades involving AERO coins like `timestamp`, `PriceInUSD`, `buyer`, `seller` and details about `side currency`, where `0x940181a94A35A4569E4529A3CDfB74e38FD98631` is the smart contract address of AERO Coin. ```graphql subscription { EVM(network: base) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x940181a94A35A4569E4529A3CDfB74e38FD98631" } } AmountInUSD: { gt: "0" } Success: true } } ) { Block { Time } Trade { AmountInUSD Buyer Currency { Name Symbol SmartContract } PriceInUSD Seller Side { Currency { Name Symbol SmartContract } } Dex { ProtocolFamily ProtocolName } } Transaction { Hash } } } } ``` ### Top Ten Holders of AERO Coin Using the following query on the `Holders` cube we can get the top 10 holders of AERO, where `0x940181a94A35A4569E4529A3CDfB74e38FD98631` is the contract address of the AERO coin. `date` sets the snapshot day, and the `Balance.Amount` floor keeps the ranking fast. ```graphql query MyQuery { EVM(network: base) { Holders( date: "2026-09-30" where: { Currency: { SmartContract: { is: "0x940181a94A35A4569E4529A3CDfB74e38FD98631" } } Balance: { Amount: { ge: "1000000" } } } orderBy: { descending: Balance_Amount } limit: { count: 10 } ) { Holder { Address } Balance { Amount } Currency { Name Symbol SmartContract } } } } ``` ### OHLC Data for AERO/USDC Pair [This](https://ide.bitquery.io/OHLC-of-AERO-Coin_1) query returns the OHLC parameters and `volume` for the AERO/USDC trade pair for a one hour window. ```graphql { EVM(network: base, dataset: combined) { DEXTradeByTokens( orderBy: { descendingByField: "Block_testfield" } where: { Trade: { Currency: { SmartContract: { is: "0x940181a94A35A4569E4529A3CDfB74e38FD98631" } } Side: { Currency: { SmartContract: { is: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" } } Type: { is: buy } } PriceAsymmetry: { lt: 0.1 } } } limit: { count: 10 } ) { Block { testfield: Time(interval: { in: hours, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } count } } } ``` ### Total Supply of AERO Coin [This](https://ide.bitquery.io/Total-supply-of-a-AERO-on-Base) query returns the total supply of a token, which is an important parameter to consider from the investment perspective. Also, it is an important parameter for Market Cap calculation. ```graphql query MyQuery { EVM(network: base, dataset: combined) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x940181a94A35A4569E4529A3CDfB74e38FD98631" } } Success: true } } ) { minted: sum( of: Transfer_Amount if: { Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } } } ) burned: sum( of: Transfer_Amount if: { Transfer: { Receiver: { is: "0x0000000000000000000000000000000000000000" } } } ) } } } ``` You can checkout more queries related to tokens and token trades [here](/docs/blockchain/Ethereum/dextrades/token-trades-apis/#ohlc-in-usd-of-a-token). ## Video Tutorial to Get Latest Memecoins on Base --- ## Base PancakeSwap Infinity API URL: https://docs.bitquery.io/docs/blockchain/Base/pancakeswap-infinity-api/ PancakeSwap Infinity on Base: live trades, token price, top traders, OHLC in USD, buy and sell volume, top bought and sold tokens, and token metadata. # Base PancakeSwap Infinity API Bitquery provides PancakeSwap Infinity (Base) data through APIs, Streams and Data Dumps. The GraphQL APIs and streams below show the data Bitquery has for PancakeSwap Infinity on Base. ## Live PancakeSwap Infinity Trades on Base (Trading API, recommended) This subscription streams every PancakeSwap Infinity trade on Base in real time with **USD price and USD amounts on every row**, MEV-filtered. Run it [in the IDE](https://ide.bitquery.io/Trading-API-PancakeSwap-Infinity-Trades-Base). ```graphql subscription { Trading { Trades( where: {Pair: {Market: {Network: {is: "Base"}, Protocol: {is: "pancakeswap_infinity"}}}} ) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` If you have any question on other data points reach out to [support](https://t.me/Bloxy_info) Need zero-latency Base data? [Read about our Kafka Streams and Contact us for a Trial](/docs/streams/kafka-streaming-concepts/). You may also be interested in: - [Clanker APIs ➤](/docs/blockchain/Base/base-clanker-api/) - [Base DEX Trade APIs ➤](/docs/blockchain/Base/base-dextrades/) :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Get Latest Trades on PancakeSwap Infinity Returns the [latest DEX trades on PancakeSwap Infinity](https://ide.bitquery.io/pancakeswap-infinity-trades). ```graphql query MyQuery { EVM(dataset: realtime, network: base) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transaction { From To } Trade { Dex { ProtocolName SmartContract } Buy { Currency { Name } Price Amount } Sell { Amount Currency { Name } Price } } Block { Time } } } } ``` ## Get Latest Price of a token on PancakeSwap Infinity Returns the [latest price of cbBTC on PancakeSwap Infinity](https://ide.bitquery.io/Get-Latest-Price-of-a-token-on-PancakeSwap-Infinity) from its 10 most recent trades. ```graphql query MyQuery { EVM(dataset: realtime, network: base) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transaction { From To } Block { Time } Trade { Price PriceInUSD Amount AmountInUSD Currency { Name Symbol SmartContract } Dex { ProtocolName SmartContract } Side { Amount AmountInUSD Currency { Name Symbol SmartContract } } } } } } ``` ## Get Top Traders of a token on PancakeSwap Infinity Returns the [top 100 traders of cbBTC on PancakeSwap Infinity](https://ide.bitquery.io/top-traders-of-a-token-on-pancakeswap) by USD volume. It ranks `Transaction.From`, the account that sent each swap, since on a sale `Trade.Buyer` is the pool or a router. `Side.Type` describes the counter-side of each trade, so `bought` sums the rows where `Side.Type` is `sell`. `PriceAsymmetry: {lt: 0.1}` leaves out trades whose two sides disagree on value ([PriceAsymmetry reference](/docs/graphql/metrics/priceAsymmetry/)). ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}, Dex: {ProtocolName: {is: "pancakeswap_infinity"}}, PriceAsymmetry: {lt: 0.1}}} ) { Transaction { From } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "base", "token": "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf" } ``` ## OHLC in USD of a Token Returns [hourly open, high, low and close prices in USD](https://ide.bitquery.io/OHLC-on-BASE-pancakeswap-infinity) for cbBTC traded against ETH on PancakeSwap Infinity. ```graphql { EVM(network: base, dataset: realtime) { DEXTradeByTokens( orderBy: { descendingByField: "Block_testfield" } where: { Trade: { Currency: { SmartContract: { is: "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf" } } Side: { Currency: { SmartContract: { is: "0x0000000000000000000000000000000000000000" } } Type: { is: buy } } PriceAsymmetry: { lt: 0.1 } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } } limit: { count: 10 } ) { Block { testfield: Time(interval: { in: hours, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) } count } } } ``` ## Get trading volume, buy volume, sell volume of a token Returns the [traded, buy and sell volume of cbBTC](https://ide.bitquery.io/trade_volume_base_pancakeswap_infinity) (`0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf`) on PancakeSwap Infinity over the last 24 hours. `PriceAsymmetry: { lt: 0.1 }` drops mispriced trades, which would otherwise skew the USD sums. ```graphql query MyQuery { EVM(network: base) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } PriceAsymmetry: { lt: 0.1 } } TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract Decimals } } traded_volume_in_usd: sum(of: Trade_Side_AmountInUSD) sell_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ``` ## Get top bought tokens on PancakeSwap Infinity Returns the [top bought tokens on PancakeSwap Infinity](https://ide.bitquery.io/top-bought-tokens-on-pancakeswap_infinity). Buys are the rows where `Side.Type`, the counter-side, is `sell`, and the `PriceAsymmetry` filter keeps mispriced trades out of the totals. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "pancakeswap_infinity"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "base" } ``` ## Get top sold tokens on PancakeSwap Infinity Returns the [top sold tokens on PancakeSwap Infinity](https://ide.bitquery.io/top-sold-tokens-on-pancake-infinty). Sales are the rows where `Side.Type` is `buy`. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "pancakeswap_infinity"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "base" } ``` ## Get Metadata of a token Returns a [token's metadata](https://ide.bitquery.io/get-metadata-for-base-pancakeswap-infnity-token), here cbBTC's: `Name`, `Symbol`, `SmartContract` and `Decimals`. ```graphql query MyQuery { EVM(network: base, dataset: realtime) { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { SmartContract: { is: "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } } ) { Trade { Currency { Name Symbol SmartContract ProtocolName HasURI Fungible Decimals } } } } } ``` --- ## Base Self-Destruct Balance Tracker: Why Base Shows None, and What to Watch URL: https://docs.bitquery.io/docs/blockchain/Base/transaction-balance-tracker/base-self-destruct-balance-api/ Self-destruct codes never fire on Base and live data shows no SELFDESTRUCT calls, because the opcode only deletes same-transaction contracts. Proof queries. # Base Self-Destruct Balance Tracker: Why Base Shows None, and What to Watch The balance schema has three reason codes for `selfdestruct`: 13 for the contract whose balance empties, 12 for the address that receives it, and 14 for value sent to an account already destroyed in the same transaction. On Base none of them fire. Since the Cancun rules reached the OP Stack, `SELFDESTRUCT` only deletes a contract created in the same transaction; in every other case it just moves the balance, and Base's balance cube reports every native movement as reason code 0 or, for fees, code 5. On top of that, live Base data shows no `SELFDESTRUCT` calls at all in the `Calls` cube over a day. This page gives you the two queries that prove it, so an empty result is a fact rather than a bug, and the queries that catch the patterns people are usually looking for. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. ## Confirm it: the codes are empty A count over the last day. Change the network to `bsc` and the same query returns a few hundred rows, which is the quickest way to see that the schema is shared and the behaviour is the chain's. Saved query [here](https://ide.bitquery.io/Aggregate-Self-Destruct-Statistics-base). ```graphql { EVM(network: base) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [12, 13, 14] } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { count } } } ``` ## Confirm it: no SELFDESTRUCT calls The `Calls` cube keeps the opcode of every internal call, so it would show a destruction even for a contract that held nothing. Saved query [here](https://ide.bitquery.io/Track-recent-ephemeral-contract-patterns-base). ```graphql { EVM(network: base) { Calls( where: { Call: { Opcode: { Name: { is: "SELFDESTRUCT" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Call { From To Value } Transaction { Hash From } } } } ``` Leave this one running as a subscription if you want to be told the moment a destruction does happen: drop `limit`, `orderBy` and the time filter and change `query` to `subscription`. ## What people are usually looking for on Base - **Short-lived helper contracts.** On BNB Chain and Ethereum, MEV bots destroy their helpers; on Base they simply leave them. Find them with the `Calls` cube: filter `Call.Opcode.Name` on `CREATE` or `CREATE2` and group by `Transaction.From` to see who deploys contracts in bulk, then query the [transaction balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker) for the balances those contracts hold. - **A contract being emptied.** Filter `TransactionBalances` on the contract as `TokenBalance.Address` with `Currency: { Native: true }`; a code 0 row whose `PostBalance` is zero is the sweep. - **Fees and sequencer income.** Reason code 5 rows on the fee vaults, covered on the [Base gas balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-gas-balance-tracker). ## The self-destruct queries, ready for other chains Both blocks below run unchanged on `bsc` and `eth`, where the codes do fire. Code 13 rows are the contracts that emptied, code 12 rows the recipients. Saved stream [here](https://ide.bitquery.io/All-Self-Destruct-Event-Balances-Stream-base). ```graphql subscription { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [12, 13] } } } ) { Block { Time Number } TokenBalance { Address BalanceChangeReasonCode PreBalance PostBalance PostBalanceInUSD } Transaction { Hash From To } } } } ``` The [BSC self-destruct balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-self-destruct-balance-api) walks through the full set on a chain where the pattern is live. ## Related pages - [Base transaction balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker) - [Base gas balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-gas-balance-tracker) - [BSC self-destruct balance tracker](/docs/blockchain/BSC/transaction-balance-tracker/bsc-self-destruct-balance-api) - [Balance change reason codes](/docs/blockchain/Base/transaction-balance-tracker/#balance-change-reason-codes) --- ## Base Slippage API URL: https://docs.bitquery.io/docs/blockchain/Base/base-slippage-api/ Base Slippage API: measure Base DEX price impact and slippage with Bitquery GraphQL pool metrics. Scale further with WebSocket subscriptions or Kafka streams. # Base Slippage API In this section we will see how to get Base DEX pool slippage information using our API. The slippage API helps you understand price impact and liquidity depth for token swaps on Base DEX pools. ## Understanding Slippage and Price Impact Slippage refers to the difference between the expected price of a trade and the actual execution price. When swapping tokens in a DEX pool, larger trades can move the price due to limited liquidity, resulting in slippage. The DEXPoolSlippages API provides detailed information about: - Maximum input amounts that can be swapped at different slippage tolerances - Minimum output amounts guaranteed at each slippage level - Average execution prices for different trade sizes - Price impact calculations for both swap directions (A to B and B to A) For a comprehensive explanation of how DEX pools work, liquidity calculations, and price tables, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/). ## Realtime Slippage Monitoring This subscription query returns real-time slippage data for all DEX pools on Base. You can monitor price impact and liquidity depth as trades occur. You can find the query [here](https://ide.bitquery.io/realtime-slippage-on-base) ```graphql subscription { EVM(network: base) { DEXPoolSlippages { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` ## Latest Slippage for a Specific Pool This query retrieves the latest slippage data for a specific DEX pool on Base. Use this to check current liquidity depth and price impact for a particular token pair. You can find the query [here](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Uniswap-v3) ```graphql query { EVM(network: base) { DEXPoolSlippages( where: {Price: {Pool: {SmartContract: {is: "0x42161084d0672e1d3f26a9b53e653be2084ff19c"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` > **Note:** This query can be converted to a subscription to monitor in real-time. Simply replace `query` with `subscription` to receive live updates whenever the pool's liquidity changes. ## Realtime Slippage Data via Kafka Streams Slippage data can also be obtained via Kafka streams for lower latency and better reliability. The Kafka topic for Base DEX pools is: **`base.dexpools.proto`** Kafka streams provide the same slippage data as GraphQL subscriptions but with several advantages: - Lower latency due to shorter data pipeline - Better reliability with persistent connections - Ability to read from latest offset without gaps - Better scalability with multiple consumers For detailed information on how to connect to Kafka streams, subscribe to topics, and parse messages, refer to the [Kafka Streaming Concepts documentation](/docs/streams/kafka-streaming-concepts/). > **Note:** IDE credentials will not work with Kafka Streams. You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## Understanding the Response The `DEXPoolSlippages` API response contains the following information: - **`Price`**: Price information for swaps at a specific slippage tolerance - **`AtoB`**: Price data for swapping CurrencyA to CurrencyB - `Price`: Average execution price for swaps at this slippage level - `MinAmountOut`: Minimum output amount guaranteed at this slippage level - `MaxAmountIn`: Maximum input amount that can be swapped at this slippage level - **`BtoA`**: Price data for swapping CurrencyB to CurrencyA (same structure as AtoB) - **`SlippageBasisPoints`**: Slippage tolerance in basis points (100 = 1%) - **`Pool`**: Pool information including token pair details - **`Dex`**: DEX protocol information (Uniswap V2, V3, V4, etc.) - **`Block`**: Block information when the slippage data was recorded - `Time`: Timestamp of the block - `Number`: Block number For more details on how slippage is calculated and when new pool records are emitted, see the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#when-is-a-new-dexpool-record-emitted-in-the-apis--streams). ## Use Cases ### Liquidity Depth Analysis Use the slippage API to analyze which pools can handle large trades without significant price impact. By examining `MaxAmountIn` values at different slippage levels, you can: - Identify pools with sufficient liquidity for your trade size - Determine optimal slippage tolerance settings - Estimate price impact before executing trades ### Multi-Pool Price Comparison Compare execution prices across different pools and slippage scenarios to: - Find the best pool for your specific trade size - Understand price differences between DEX protocols - Optimize trade execution strategies ### Trading Applications #### Live Execution Testing Use the slippage API to test and validate trade execution strategies in real-time: - **Pre-trade validation**: Check if your intended trade size can be executed within acceptable slippage bounds before submitting - **Execution simulation**: Calculate expected price impact and minimum output amounts for different trade sizes - **Strategy backtesting**: Monitor historical slippage data to validate trading algorithms and optimize entry/exit points - **Risk assessment**: Evaluate maximum position sizes that can be entered without exceeding your slippage tolerance #### Detecting Liquidity Shocks and Toxic Order Flow The slippage API helps identify temporary price dislocations and liquidity shocks that can be exploited or avoided: - **Flow toxicity detection**: Monitor sudden changes in `MaxAmountIn` values to detect when pools experience large outflows or inflows - **Price impact analysis**: Track how `MinAmountOut` changes relative to `MaxAmountIn` to identify when pools become less liquid - **Mean reversion opportunities**: Identify pools where large swaps have created temporary price dislocations that may revert - **Toxic order flow avoidance**: Use slippage data to avoid entering positions when liquidity is thin or when large trades are likely to move price against you For a practical implementation example of using slippage data for automated trading strategies, including flow toxicity detection and mean-reversion trading, see the [AMM Flow Toxicity Alpha Engine](https://github.com/Divyn/amm-flow-toxicity-alpha-engine) repository. This system demonstrates how to: - Detect large swaps that move price significantly (50-500 basis points) - Verify isolation from trending markets - Execute fade trades against temporary price impacts - Manage positions with dynamic stop losses and take profits based on slippage data For more advanced use cases, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#advanced-use-cases-and-processing-patterns). --- ## Base Sniper Bot URL: https://docs.bitquery.io/docs/usecases/base-sniper-bot/ Build Base Sniper Bot: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. Keep queries fast with indexed filters. # Tutorial : Building a Base Sniper Bot Using Bitquery Base Events API and Uniswap SDK This tutorial will guide you through building a Base sniper bot using Bitquery Events API and the Uniswap SDK for executing swaps. Sniping depends on seeing transactions before they confirm — the [Mempool API](https://bitquery.io/products/mempool-api) page covers pending transactions and MEV data feeds. > Note: This material is for educational and informational purposes only and is not intended as investment advice. The content reflects the author's personal research and understanding. While specific investments and strategies are mentioned, no endorsement or association with these entities is implied. Readers should conduct their own research and consult with qualified professionals before making any investment decisions. Bitquery is not liable for any losses or damages resulting from the application of this information. ## Tutorial Video ## Tutorial Github Code Repository - [Repository Link](https://github.com/Akshat-cs/Base-sniper-bot) ### Prerequisites 1. **Node.js** and **npm** installed on your system. 2. **Bitquery Free Developer Account** with OAuth token (follow instructions [here](/docs/authorization/how-to-generate/)). 3. **Any Base Chain supported Wallet** with some Base ETH for transaction fees and also some WETH as I have used WETH in the video tutorial to make swap. I have used the Bitquery Base Events API to get the latest created pool which has Token A as WETH with Token Addres `0x4200000000000000000000000000000000000006`. - If you want to conduct the swap using different Token then you can change the address in this `Arguments: {startsWith: {Value: {Address: {is: "0x4200000000000000000000000000000000000006"}}}}` in tokens.ts file to your Token Address that you want to conduct swaps with. ### Step 1: Setting Up the Environment 1. **Initialize a new Node.js project:** ```bash mkdir base-sniper-bot cd base-sniper-bot npm init -y ``` 2. **Install the necessary dependencies:** ```bash npm install @types/node @uniswap/sdk-core @uniswap/smart-order-router @uniswap/v3-sdk axios dotenv ethers ts-node tslib typescript ``` ### Step 2: Creating the Bot 1. **Create a `.env` file :** This file will contain all the environment variables. Put in your Wallet private key that you are using to conduct swap. And also put in the Bitquery OAuth Token, follow the instructions on how to get it [here](/docs/authorization/how-to-generate/). ```javascript # BASE MAINNET RPC=https://mainnet.base.org WALLET_PRIVATE_KEY= CHAIN_ID=8453 SWAP_ROUTER_ADDRESS=0x2626664c2603336E57B271c5C0b26F421741e481 SLIPPAGE_TOLERANCE=5 DEADLINE_IN_MINUTES=30 BITQUERY_TOKEN= ``` 2. **Create a `config.ts` file:** This is a basic configuration file which helps us to expose our environment variables to our application and we are also using Ethers to set provider and signer. ```javascript import { Percent } from "@uniswap/sdk-core"; import { ethers, providers, Wallet } from "ethers"; import { config as loadEnvironmentVariables } from "dotenv"; loadEnvironmentVariables(); export const WALLET_PRIVATE_KEY = process.env.WALLET_PRIVATE_KEY || ""; export const SWAP_ROUTER_ADDRESS = process.env.SWAP_ROUTER_ADDRESS || ""; export const CHAIN_ID = parseInt(process.env.CHAIN_ID || "1"); export const DEADLINE = Math.floor( (Date.now() / 1000) _ (parseInt(process.env.DEADLINE_IN_MINUTES || "30") _ 60) ); export const SLIPPAGE_TOLERANCE = new Percent( process.env.SLIPPAGE_TOLERANCE || 5, 100 ); const RPC = process.env.RPC; export const provider = ethers.providers.getDefaultProvider(RPC); export const signer = new Wallet(WALLET_PRIVATE_KEY, provider); ``` 3. **Create a `tokens.ts` file:** In this step we are importing necessary modules then loading environment variables and also setting ERC20 ABI as we are going to need it to make the token contract instance from token address. ```javascript loadEnvironmentVariables(); const ERC20_ABI = [ "function name() view returns (string)", "function symbol() view returns (string)", "function decimals() view returns (uint8)", "function allowance(address, address) external view returns (uint256)", "function approve(address, uint) external returns (bool)", "function balanceOf(address) external view returns(uint256)", ]; ``` We are going to need Token Contract to call different functions like `balanceOf`, `decimals` and `symbol`. So we are building Token Contract using `buildERC20TokenWithContract` function by providing the token address and the provider. ```javascript type TokenWithContract = { contract: Contract, walletHas: (signer: Signer, requiredAmount: BigNumberish) => Promise, token: Token, }; const buildERC20TokenWithContract = async ( address: string, provider: Provider ): Promise => { try { const contract = new Contract(address, ERC20_ABI, provider); const [name, symbol, decimals] = await Promise.all([ contract.name(), contract.symbol(), contract.decimals(), ]); return { contract: contract, walletHas: async (signer, requiredAmount) => { const signerBalance = await contract .connect(signer) .balanceOf(await signer.getAddress()); return signerBalance.gte(BigNumber.from(requiredAmount)); }, token: new Token(CHAIN_ID, address, decimals, symbol, name), }; } catch (error) { console.error( `Failed to fetch token details for address ${address}:`, error ); return null; } }; ``` Setting provider and type of Tokens here as we are using Typescript. Then we built a function `getTokens` which makes an API call and gets the address of Tokens 0 and 1 in the latest created liquidity pool. This function finally returns the Token Contract for the fetched Token 0 and Token 1 addresses using `buildERC20TokenWithContract`. Keep in mind we have set the Token 0 address as WETH token address. In the `index.ts` file we are going to swap this WETH with the other token i.e token 1 in the pool. ```javascript // Example usage for BASE const provider = new providers.JsonRpcProvider(process.env.RPC); type Tokens = { Token0: TokenWithContract | null, Token1: TokenWithContract | null, }; export const getTokens = async (): Promise => { try { let data = JSON.stringify({ query: 'query {\n EVM(network: base) {\n Events(\n limit: {count: 1}\n orderBy: {descending: Block_Time}\n where: {Log: {Signature: {Name: {is: "PoolCreated"}}, SmartContract: {is: "0x33128a8fC17869897dcE68Ed026d694621f6FDfD"}}, Arguments: {startsWith: {Value: {Address: {is: "0x4200000000000000000000000000000000000006"}}}}}\n ) {\n Transaction {\n Hash\n }\n Block {\n Time\n }\n Log {\n Signature {\n Name\n }\n }\n Arguments {\n Name\n Type\n Value {\n ... on EVM_ABI_Integer_Value_Arg {\n integer\n }\n ... on EVM_ABI_String_Value_Arg {\n string\n }\n ... on EVM_ABI_Address_Value_Arg {\n address\n }\n ... on EVM_ABI_BigInt_Value_Arg {\n bigInteger\n }\n ... on EVM_ABI_Bytes_Value_Arg {\n hex\n }\n ... on EVM_ABI_Boolean_Value_Arg {\n bool\n }\n }\n }\n }\n }\n}\n', variables: "{}", }); const axiosConfig: AxiosRequestConfig = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.BITQUERY_TOKEN}`, // put your oauth token here }, data: data, }; const response = await axios.request(axiosConfig); const token0Address = response.data.data.EVM.Events[0].Arguments[0].Value.address; const token1Address = response.data.data.EVM.Events[0].Arguments[1].Value.address; console.log(token0Address); console.log(token1Address); const Token0 = await buildERC20TokenWithContract(token0Address, provider); const Token1 = await buildERC20TokenWithContract(token1Address, provider); return { Token0, Token1 }; } catch (error) { console.error("Error fetching tokens:", error); return { Token0: null, Token1: null }; } }; ``` For the sake of the demo we have used a query, to **track new tokens in real-time** use the below subscriptions ([link](https://ide.bitquery.io/Subscription-Latest-created-pool-on-uniswap-V3-on-Base-chain-with-Token0-as-WETH)). ```javascript subscription { EVM(network: base) { Events( orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "PoolCreated"}}, SmartContract: {is: "0x33128a8fC17869897dcE68Ed026d694621f6FDfD"}}, Arguments: {startsWith: {Value: {Address: {is: "0x4200000000000000000000000000000000000006"}}}}} ) { Transaction { Hash } Block { Time } Log { Signature { Name } } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` 4. **Create a `index.ts` file:** a. **Doing the necessary imports** ```javascript import { BigNumber, ethers } from "ethers"; import { AlphaRouter, SwapType, SwapRoute, } from "@uniswap/smart-order-router"; import { CurrencyAmount, TradeType } from "@uniswap/sdk-core"; import type { TransactionRequest } from "@ethersproject/abstract-provider"; import { getTokens } from "./tokens"; import { provider, signer, CHAIN_ID, SWAP_ROUTER_ADDRESS, SLIPPAGE_TOLERANCE, DEADLINE, } from "./config"; ``` b. **Building the main function** All of the code covered under this section b is going to be in the main function. 1. Firstly it calls the `getTokens` function and fetches the Token0 and Token1 token contracts. And then set `tokenFrom` and `tokenTo` tokens and `tokenFromContract` to call functions on tokenFrom token. ```javascript // Wait for the getTokens function to resolve const { Token0, Token1 } = await getTokens(); // Ensure tokens are not null if (!Token0 || !Token1) { throw new Error("Tokens are not initialized."); } const tokenFrom = Token0.token; const tokenFromContract = Token0.contract; const tokenTo = Token1.token; ``` 2. Then we check if we have passed the argument in the terminal while running the bot. This means that if we have not passed the amount of WETH we want to swap with then throw error. Then we are checking if we have enough amount of the TokenFrom token or not. It must be grater than the passed argument in the terminal. ```javascript if (typeof process.argv[2] === "undefined") { throw new Error(`Pass in the amount of ${tokenFrom.symbol} to swap.`); } const walletAddress = await signer.getAddress(); const amountIn = ethers.utils.parseUnits( process.argv[2], tokenFrom.decimals ); const balance = await tokenFromContract.balanceOf(walletAddress); if (!(await Token0.walletHas(signer, amountIn))) { throw new Error( `Not enough ${tokenFrom.symbol}. Needs ${amountIn}, but balance is ${balance}.` ); } ``` 3. We are using `AlphaRouter` here from Uniswap to swap tokens on Uniswap efficiently. Then we use this router object to create a route which takes the specific details of our swap. If no route is found then it throws error. ```javascript const router = new AlphaRouter({ chainId: CHAIN_ID, provider }); const route = await router.route( CurrencyAmount.fromRawAmount(tokenFrom, amountIn.toString()), tokenTo, TradeType.EXACT_INPUT, { recipient: walletAddress, slippageTolerance: SLIPPAGE_TOLERANCE, deadline: DEADLINE, type: SwapType.SWAP_ROUTER_02, } ); if (!route) { throw new Error("No route found for the swap."); } console.log( `Swapping ${amountIn} ${tokenFrom.symbol} for ${route.quote.toFixed( tokenTo.decimals )} ${tokenTo.symbol}.` ); ``` 4. Then we check the allowance. We are just defining here `buildSwapTransaction` and then also using `swapTransaction` to populate the `buildSwapTransaction`. Then we have also defined `attemptSwapTransaction` which sends the transaction to the network. ```javascript const allowance: BigNumber = await tokenFromContract.allowance( walletAddress, SWAP_ROUTER_ADDRESS ); const buildSwapTransaction = ( walletAddress: string, routerAddress: string, route: SwapRoute ): TransactionRequest => { return { data: route.methodParameters?.calldata, to: routerAddress, value: BigNumber.from(route.methodParameters?.value), from: walletAddress, gasLimit: BigNumber.from("2000000"), // Set your desired gas limit here // Optionally, you can specify gasPrice here if needed // gasPrice: YOUR_GAS_PRICE_IN_WEI }; }; const swapTransaction = buildSwapTransaction( walletAddress, SWAP_ROUTER_ADDRESS, route ); const attemptSwapTransaction = async ( signer: ethers.Wallet, transaction: TransactionRequest ) => { const signerBalance = await signer.getBalance(); if (!signerBalance.gte(transaction.gasLimit || "0")) { throw new Error(`Not enough ETH to cover gas: ${transaction.gasLimit}`); } // Send the transaction with the specified gas-related parameters signer.sendTransaction(transaction).then((tx) => { tx.wait().then((receipt) => { console.log("Completed swap transaction:", receipt.transactionHash); }); }); }; ``` 5. Here we finally call the before defined functions. Firstly we check if there is enough WETH allowance. And if there is not then we send an approve transaction to the network with the `AmountIn` amount of WETH. Then we call the `attemptSwapTransaction` which des the actual swap. ```javascript if (allowance.lt(amountIn)) { console.log(`Requesting ${tokenFrom.symbol} approval…`); const approvalTx = await tokenFromContract .connect(signer) .approve( SWAP_ROUTER_ADDRESS, ethers.utils.parseUnits(amountIn.mul(1000).toString(), 18) ); approvalTx.wait(3).then(() => { attemptSwapTransaction(signer, swapTransaction); }); } else { console.log( `Sufficient ${tokenFrom.symbol} allowance, no need for approval.` ); attemptSwapTransaction(signer, swapTransaction); } ``` c. **Calling the main function with some error handling** ```javascript main().catch((error) => { console.error(error); process.exit(1); }); ``` ### Step 3: Running the Bot 1. **Check the .env:** - Make sure that you have replace `PRIVATE_KEY` with your actual BASE account public key. - Make sure that you have replace `BITQUERY_TOKEN` with your actual Bitquery OAuth token. 2. **Run the bot:** 0.001 in the below script is the amount of WETH that I want to use for the swap. ```bash ts-node index.ts 0.001 ``` ### Conclusion You've successfully set up a Base sniper bot using Bitquery for Base Events API and Uniswap SDK for executing swaps. You need to change the query in tokens.ts file into subscription if you want to use it to listen for on-chain events and then buy the token B from each new pool that gets created on Uniswap. But you will need to make some necessary changes before that. This tutorial just shows you how you can get the recently created pool on uniswap and which token B it has as token A we have already set as WETH in the query and swap a token in that pool. Ensure your bot is monitored and managed appropriately, as we are running on the mainnet with real funds. --- ## Base Token Market Cap API: Market Cap, FDV and Supply for Tokens on Base URL: https://docs.bitquery.io/docs/blockchain/Base/base-token-marketcap-api/ Market cap, FDV, supply and price for Base tokens with Bitquery GraphQL: AERO or cbBTC now, a watchlist, hourly history, a live stream and a threshold alert. # Base Token Market Cap API: Market Cap, FDV and Supply for Tokens on Base Base tokens trade against ETH and USDC on Aerodrome, Uniswap and the launchpads, and the `Tokens` cube of the Trading API turns those trades into candles that carry price, USD volume, circulating and total supply, market cap and fully diluted valuation, refreshed every block. Address a token by id, `bid:base:` plus its lowercase contract, and the chain by `Token.Network: "Base"`. The cube keeps about a month of candles; the [Base transaction balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker) gives total supply at any recent transaction if supply alone is enough. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; the worked tokens are AERO, `0x940181a94a35a4569e4529a3cdfb74e38fd98631`, and cbBTC, `0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf`. ## Market cap of one token now Exact id, one candle size, a short window, newest row first. The window matters: without it the query scans the whole cube and times out. Saved query [here](https://ide.bitquery.io/specific-base-token-latest-marketcap). ```graphql { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { is: "bid:base:0x940181a94a35a4569e4529a3cdfb74e38fd98631" } } Interval: { Time: { Duration: { eq: 60 } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time } Token { Name Symbol Address Network } Price { Ohlc { Close } Average { Mean } } Supply { CirculatingSupply TotalSupply MarketCap FullyDilutedValuationUsd } Volume { Usd } } } } ``` For AERO the market cap and the FDV differ by about half, because only part of the supply is in circulation; for cbBTC they are equal, since every minted coin circulates. ## A watchlist in one query List the ids and keep the newest row per token with `limitBy`. The example is AERO, cbBTC and WETH on Base. ```graphql { Trading { Tokens( limitBy: { by: Token_Id, count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { in: [ "bid:base:0x940181a94a35a4569e4529a3cdfb74e38fd98631" "bid:base:0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf" "bid:base:0x4200000000000000000000000000000000000006" ] } } Interval: { Time: { Duration: { eq: 60 } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time } Token { Symbol Id } Price { Ohlc { Close } } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply } Volume { Usd } } } } ``` ## A day of hourly market cap One-hour candles hold the market cap at each close with the hour's open, close and USD volume; the difference between the first and last row is the 24-hour change. Saved query [here](https://ide.bitquery.io/top-base-tokens-by-Market-Cap-Change-1h). ```graphql { Trading { Tokens( limit: { count: 24 } orderBy: { descending: Block_Time } where: { Token: { Id: { is: "bid:base:0x940181a94a35a4569e4529a3cdfb74e38fd98631" } } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Interval { Time { Start } } Price { Ohlc { Open Close } } Supply { MarketCap } Volume { Usd } } } } ``` ## Stream every Base token's market cap Filter on the chain prefix in `Currency.Id` and subscribe; each message is a candle closing for some Base token. `Duration` above one second leaves out the tick-level candles. Saved stream [here](https://ide.bitquery.io/base-token-marketcap-stream). ```graphql subscription { Trading { Tokens( where: { Currency: { Id: { includes: "base" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Block { Time } Token { Symbol Id } Interval { Time { Duration } } Price { Ohlc { Close } } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } Volume { Usd } } } } ``` ## Alert on tokens above a market cap A `Supply.MarketCap` bound on the stream turns it into a screener for launches that crossed a size. Saved stream [here](https://ide.bitquery.io/realtime-stream-base-tokens-with-marketcap-above-1-million). ```graphql subscription { Trading { Tokens( where: { Token: { Network: { is: "Base" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 1000000 } } } ) { Block { Time } Token { Symbol Id } Supply { MarketCap TotalSupply } Price { Ohlc { Close } } } } } ``` ## Why rankings need bounds Market cap here is on-chain supply times an on-chain price, and Base has thousands of launchpad tokens with enormous supplies and a few dollars of trades in one thin pool. A raw "top tokens by market cap" over the cube is led by them. Rank inside a list you trust, as the watchlist query does, or bound the ranking with `Volume: { Usd: { gt: ... } }` and `Supply: { MarketCap: { lt: ... } }`; the saved [top tokens by market cap](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Base) query shows the bounded form. ## Related pages - [BSC token market cap API](/docs/blockchain/BSC/bsc-token-marketcap-api) - [Ethereum token market cap API](/docs/blockchain/Ethereum/token-supply/ethereum-token-marketcap-api) - [Tokens cube](/docs/trading/crypto-price-api/tokens) - [Supply fields](/docs/trading/crypto-price-api/supply-fields) - [Base transaction balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker) --- ## Base Transaction Balance Tracker API URL: https://docs.bitquery.io/docs/blockchain/Base/transaction-balance-tracker/ Base Transaction Balance Tracker API: stream Base balance changes with reason codes using Bitquery GraphQL subscriptions. # Base Transaction Balance Tracker API - Complete Guide ## What is Transaction Balance Tracker? The **Base Transaction Balance Tracker API** provides real-time balance updates for all addresses involved in transactions on the Base blockchain. Unlike traditional balance APIs that only show current balances, our Transaction Balance Tracker captures every balance change with detailed information about the reason for each change, making it perfect for building comprehensive transaction monitoring, portfolio tracking, and blockchain analytics applications. Our Transaction Balance Tracker APIs track balance changes across different scenarios including regular transactions, miner rewards, MEV activities, and contract self-destruct events. Each balance change is enriched with reason codes, pre/post balances, USD values, and transaction context. ## Key Features - **Real-time Balance Updates**: Stream balance changes as they happen via GraphQL subscriptions - **Balance Change Reason Codes**: Understand why each balance changed (transfers, rewards, gas, self-destruct, etc.) - **Comprehensive Coverage**: Track native ETH, ERC-20 tokens, ERC-721, and ERC-1155 NFTs - **Recent History**: The API holds a recent realtime window for this cube. For older balance changes, record the stream or ask about a [Data Store export](https://bitquery.io/datastore) - **USD Values**: Get balance values in USD for portfolio tracking and analytics - **Multiple Use Cases**: Monitor miners, MEV bots, self-destruct events, and more ## Getting Started New to Transaction Balance Tracker? Here's how to get started: 1. **[Create a free account](https://ide.bitquery.io/)** - Get instant access to our GraphQL IDE 2. **[Generate your API key](/docs/authorization/how-to-generate/)** - Required for API access 3. **[Run your first query](/docs/start/first-query/)** - Learn the basics in 5 minutes 4. **[Explore examples](#base-transaction-balance-tracker-apis)** - Copy-paste ready queries below Need help crafting a query or subscription? Message us on [support](https://t.me/Bloxy_info). ## How is it different from regular Balance APIs? - Real-time streaming of all balance changes - Pre/post balance values for every change - Balance change reason codes explain why balance changed - Track all addresses in transactions automatically - A recent realtime window via the API; older changes by recording the stream or through a Data Store export - Support for native currency, tokens, and NFTs ## Real-time Data & Streaming Get live Base balance updates through our streaming solutions: - **GraphQL Subscriptions**: Convert any query to a live stream by changing `query` to `subscription` - **Kafka Streaming**: High-throughput streaming for enterprise applications See examples and code snippets [here](/docs/subscriptions/websockets/) for GraphQL subscription implementation, and learn about [Kafka streaming](/docs/streams/kafka-streaming-concepts/) for high-volume use cases. ## Base Transaction Balance Tracker APIs ### [Base Transaction Balance Tracker](/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker) The core Transaction Balance Tracker API provides real-time balance updates for all addresses involved in transactions on the Base network, including detailed information about the reason for each balance change. Track native ETH, ERC-20 tokens, and NFTs with pre/post balances, USD values, and balance change reason codes. **Key Features:** - Subscribe to all transaction balances in real-time - Filter by specific addresses or tokens - Get balance change reason codes for native currency - Track ERC-20, ERC-721, and ERC-1155 tokens - Access pre and post balance values ### [Base Miner Balance Tracker](/docs/blockchain/Base/transaction-balance-tracker/base-miner-balance-tracker) Monitor Base miner balances, mining rewards, uncle block rewards, and transaction fee rewards. Track historical and real-time mining activity across the Base network. **Key Features:** - Track block mining rewards (Code 2) - Monitor uncle block rewards (Code 1) - Track transaction fee rewards (Code 5) - Filter by specific miner addresses - Historical mining reward data ### [Base MEV Balance Tracker](/docs/blockchain/Base/transaction-balance-tracker/base-mev-balance-tracker) Track MEV (Maximal Extractable Value) related balance changes including transaction fee rewards, block builder rewards, and other MEV extraction activities. Monitor MEV bots and block builders in real-time. **Key Features:** - Track transaction fee rewards (Code 5) - Monitor block builder rewards - Filter by MEV bot or builder addresses - Track large MEV transactions - Aggregate MEV reward statistics ### [Base Self-Destruct Balance Tracker](/docs/blockchain/Base/transaction-balance-tracker/base-self-destruct-balance-api) Monitor contract self-destruct events, ephemeral contracts (like MEV bots), and security incidents. Track contracts that self-destruct and addresses that receive funds from self-destructed contracts. **Key Features:** - Track contract self-destruct events (Codes 12, 13, 14) - Monitor ephemeral MEV contracts - Track MEV builder payments - Security incident monitoring - Aggregate self-destruct statistics ## Balance Change Reason Codes The Transaction Balance Tracker API uses numeric codes to indicate why a balance changed. These codes are only available for native currency (ETH) transactions, not for fungible tokens or NFTs. | **Code** | **Reason** | **Description** | | -------- | ----------------------------------- | ------------------------------------------------------------------------------- | | 0 | BalanceChangeUnspecified | Unspecified balance change reason | | 1 | BalanceIncreaseRewardMineUncle | Reward for mining an uncle block | | 2 | BalanceIncreaseRewardMineBlock | Reward for mining a block | | 3 | BalanceIncreaseWithdrawal | ETH withdrawn from the beacon chain | | 4 | BalanceIncreaseGenesisBalance | ETH allocated at the genesis block | | 5 | BalanceIncreaseRewardTransactionFee | Transaction tip increasing block builder's balance | | 6 | BalanceDecreaseGasBuy | ETH spent to purchase gas for transaction execution | | 7 | BalanceIncreaseGasReturn | ETH returned for unused gas at the end of execution | | 8 | BalanceIncreaseDaoContract | ETH sent to the DAO refund contract | | 9 | BalanceDecreaseDaoAccount | ETH taken from a DAO account to be moved to the refund contract | | 10 | BalanceChangeTransfer | ETH transferred via a call | | 11 | BalanceChangeTouchAccount | Transfer of zero value to touch-create an account | | 12 | BalanceIncreaseSelfdestruct | Balance added to the recipient as indicated by a self-destructing account | | 13 | BalanceDecreaseSelfdestruct | Balance deducted from a contract due to self-destruct | | 14 | BalanceDecreaseSelfdestructBurn | ETH sent to an already self-destructed account within the same transaction | | 15 | BalanceChangeRevert | Balance reverted back to a previous value due to call failure | ## Field Availability by Currency Type The availability of fields in the `TokenBalance` object depends on the type of currency being tracked: ### Native Currency (ETH) - **Available**: `BalanceChangeReasonCode`, `PreBalance`, `PostBalance`, `PostBalanceInUSD` - **Not Provided**: `TotalSupply`, `TokenOwnership` ### Fungible Tokens (ERC-20) - **Available**: `PostBalance`, `PostBalanceInUSD`, `TotalSupply`, `TotalSupplyInUSD` - **Not Provided**: `PreBalance`, `BalanceChangeReasonCode`, `TokenOwnership` ### NFTs (ERC-721 / ERC-1155) - **Available**: `PostBalance`, `TokenOwnership` - **Not Provided**: `PreBalance`, `BalanceChangeReasonCode`, `TotalSupply`, `TotalSupplyInUSD`, `PostBalanceInUSD` --- ## Base Transaction Balance Tracker: Balances Before and After a Transaction URL: https://docs.bitquery.io/docs/blockchain/Base/transaction-balance-tracker/base-transaction-balance-tracker/ Stream and query Base balance changes with Bitquery GraphQL: every address a transaction touched, one wallet's ETH and USDC, pool reserves and token supply. # Base Transaction Balance Tracker: Balances Before and After a Transaction The `TransactionBalances` cube records, for each transaction on Base, every address whose balance changed and the balance before and after, in ETH, ERC-20 tokens and NFTs. A wallet tracker, a fee monitor and a pool reserve feed all come from the same rows. Native rows carry a reason code; on Base that is 0 for ordinary changes and 5 for fee credits to the fee vaults, and no other code appears. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The cube covers the recent realtime window only, so queries carry a `limit` and, for wide filters, a time window. ## Stream one address Base produces too many balance rows for an unfiltered stream to be practical, so subscribe with a filter: an address, as here, or a reason code, as on the [gas balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-gas-balance-tracker). The example is the Uniswap v4 PoolManager, whose token balances change on every swap, so rows arrive within seconds; a wallet streams only when it transacts. Saved stream [here](https://ide.bitquery.io/Subscribe-to-Transaction-Balances-for-a-Specific-Address-base). ```graphql subscription { EVM(network: base) { TransactionBalances( where: { TokenBalance: { Address: { is: "0x498581ff718922c3f8e6a244956af099b2652b2b" } } } ) { Block { Number Time } TokenBalance { BalanceChangeReasonCode PreBalance PostBalance PostBalanceInUSD Currency { Symbol SmartContract Native } } Transaction { Hash From To } } } } ``` ## Latest ETH balance of an address The newest native row for the address; `PostBalance` is the balance after that transaction. Saved query [here](https://ide.bitquery.io/latest-native-balance-of-an-address-base). ```graphql { EVM(network: base) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x238a358808379702088667322f80ac48bad5e6c4" } Currency: { Native: true } } } ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD BalanceChangeReasonCode } Transaction { Hash } } } } ``` ## Latest balance of an address in one token The same query with the token contract in place of the native flag. The example is USDC on Base, `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. Saved query [here](https://ide.bitquery.io/latest-balance-of-an-address-for-a-specific-token-base). ```graphql { EVM(network: base) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x238a358808379702088667322f80ac48bad5e6c4" } Currency: { SmartContract: { is: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" } } } } ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD Currency { Symbol Name } } Transaction { Hash } } } } ``` An address that has not moved the token inside the realtime window has no row here; use the [Balances cube](/docs/cubes/balances-cube) for a balance that does not depend on recent activity. ## Latest reserves of a pool A pool is an address like any other, so its token balances are its reserves. `limitBy` on the token contract keeps the newest row per token. The example is the Uniswap v3 WETH/USDC 0.05% pool. Saved query [here](https://ide.bitquery.io/latest-liquidity-of-a-base-pool). ```graphql { EVM(network: base) { TransactionBalances( limit: { count: 2 } limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0xd0b53D9277642d899DF5C87A3966A349A798F224" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time } TokenBalance { Currency { Symbol SmartContract } PostBalance PostBalanceInUSD } } } } ``` ## Latest supply and market cap of a token Token rows carry `TotalSupply` and `TotalSupplyInUSD` as of that transaction, so the newest row for a token gives its supply and on-chain market cap. The example is AERO. Saved query [here](https://ide.bitquery.io/Total-Supply-and-onchain-Marketcap-of-a-specific-token-base). ```graphql { EVM(network: base) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Currency: { SmartContract: { is: "0x940181a94A35A4569E4529A3CDfB74e38FD98631" } } } } ) { Block { Time } TokenBalance { Currency { Symbol Name } TotalSupply TotalSupplyInUSD } } } } ``` ## Which fields each currency type carries - **ETH:** `BalanceChangeReasonCode`, `PreBalance`, `PostBalance`, `PostBalanceInUSD`. - **ERC-20:** `PostBalance`, `PostBalanceInUSD`, `TotalSupply`, `TotalSupplyInUSD`; no pre-balance or reason code. - **NFTs:** `PostBalance` and `TokenOwnership`; no USD values. ## Related pages - [Base transaction balance tracker overview](/docs/blockchain/Base/transaction-balance-tracker/) - [Base gas balance tracker](/docs/blockchain/Base/transaction-balance-tracker/base-gas-balance-tracker) - [Base transfers API](/docs/blockchain/Base/base-transfers) - [Balances and Holders cubes](/docs/cubes/balances-cube) --- ## Base Transfer Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Base/transaction-balance-tracker/base-transfer-balance-tracker/ Base Transfer Balance Tracker: monitor Base native and token transfers in real time with Bitquery GraphQL APIs. Copy GraphQL snippets for production apps. # Base Transfer Balance Tracker The Base Transfer Balance Tracker API provides real-time balance updates for all addresses involved in Transfers on the Base blockchain, and provides option to filter out based on the direction of transfer you want to target. The Base Transfer Balance is tracked by marking the the `BalanceUpdateReason` equals `10`. :::note The queries covered this section are only valid for the Native Currency Transfer. ::: ## Get Balance Info for an Address after Transfer [This](https://ide.bitquery.io/balance-update-from-transfer-for-an-address-base) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a particular address after a transfer, irrespective of the direction of transfer.
Click here to expand ```graphql query MyQuery { EVM(network: base) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xYourAddressInput"}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Stream Balance Info for Transfer in Real Time [This](https://ide.bitquery.io/balance-update-from-transfer-for-an-address--stream-base) subscription allows us to stream Balance Updates for an address due to transfer in Real Time.
Click here to expand ```graphql subscription { EVM(network: base) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xYourAddressInput"}}} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
--- ## Base Uniswap API URL: https://docs.bitquery.io/docs/blockchain/Base/base-uniswap-api/ Base Uniswap API: a v2, v3 and v4 trade stream plus GraphQL examples for v3 trades, top traders, hourly OHLC, 24-hour volume and top tokens, each filtered to Uniswap's own contracts on Base. # Base Uniswap API :::tip Need real-time Base Uniswap data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview): [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Base Uniswap swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use the `EVM` queries on this page for raw per-swap detail or call and event context. An `EVM` query without a `dataset` argument runs on the realtime dataset, which holds only the last few days; add `dataset: combined` or `dataset: archive` for **historical Base Uniswap data**. ::: Bitquery provides Uniswap data through APIs, Streams and Data Dumps. ## Filter by factory to exclude forks `Trade.Dex.ProtocolName` records which code a pool runs. Forks of v2 and v3 run the same code, so their trades carry the same `uniswap_v2` and `uniswap_v3` labels. In Bitquery's trade data for Base on 18 September 2026, pools from more than 100 other factories carried the `uniswap_v2` label and more than 30 carried `uniswap_v3`. They made up about one in five transactions under the first label and one in seven under the second. To keep only Uniswap's own pools, filter on the contract that owns them, as every example on this page now does. | Version | Filter field | Address on Base | | --- | --- | --- | | v2 | `Trade.Dex.OwnerAddress` | `0x8909dc15e40173ff4699343b6eb8132c65e18ec6` | | v3 | `Trade.Dex.OwnerAddress` | `0x33128a8fc17869897dce68ed026d694621f6fdfd` | | v4 | `Trade.Dex.SmartContract` | `0x498581ff718922c3f8e6a244956af099b2652b2b` | `OwnerAddress` is the factory that deployed the pool. A v4 pool has no factory: its `OwnerAddress` is the zero address, and the PoolManager is its `SmartContract`. In the Trading cube, filter `Pair.Market.Address` to the v2 or v3 factory, or `Pair.Market.Program` to the v4 PoolManager. Addresses are from the official [deployments list](https://developers.uniswap.org/deployments). The link in each example's description opens an earlier copy saved in the Bitquery IDE, which may still filter by `ProtocolName` or use older conditions and time windows. Use the code on this page when you need Uniswap's own pools only. ## Stream Base Uniswap trades Every query on this page also works as a subscription: change `query` to `subscription` and drop the `orderBy`, since a stream already arrives in block order. ```graphql subscription BaseUniswapTrades { EVM(network: base) { DEXTrades( where: { any: [ { Trade: { Dex: { OwnerAddress: { in: ["0x8909dc15e40173ff4699343b6eb8132c65e18ec6", "0x33128a8fc17869897dce68ed026d694621f6fdfd"] } } } } { Trade: { Dex: { SmartContract: { is: "0x498581ff718922c3f8e6a244956af099b2652b2b" } } } } ] } ) { Block { Time } Transaction { Hash } Trade { Dex { ProtocolName SmartContract } Buy { Amount Buyer Currency { Symbol SmartContract } } Sell { Amount Seller Currency { Symbol SmartContract } } } } } } ``` The two conditions cover the v2, v3 and v4 pools listed above. To narrow to one version, keep only that version's address. For a single pool, use `Trade: { Dex: { SmartContract: { is: "" } } }` on v2 and v3, or `Trade: { PoolId: { is: "" } }` on v4. If you have any question on other data points reach out to [support](https://t.me/Bloxy_info) Need zero-latency Base data? [Read about our Kafka Streams and Contact us for a Trial](/docs/streams/kafka-streaming-concepts/). You may also be interested in: - [Clanker APIs ➤](/docs/blockchain/Base/base-clanker-api/) - [Base DEX Trade APIs ➤](/docs/blockchain/Base/base-dextrades/) :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Get Latest Trades on Uniswap v3 The query below returns the [latest DEX trades on Uniswap v3](https://ide.bitquery.io/uniswap-v3-trades_2). ```graphql query MyQuery { EVM(dataset: realtime, network: base) { DEXTrades( where: { Trade: { Dex: { OwnerAddress: { is: "0x33128a8fc17869897dce68ed026d694621f6fdfd" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transaction { From To } Trade { Dex { ProtocolName SmartContract } Buy { Currency { Name } Price Amount } Sell { Amount Currency { Name } Price } } Block { Time } } } } ``` ## Get Top Traders of a token on uniswap v3 This query returns the [top traders of a token](https://ide.bitquery.io/top-traders-of-a-token-on-uniswapv3_4) on the selected network. It ranks `Transaction.From`, the account that sent each swap, since on a sale `Trade.Buyer` is the pool or a router. `Side.Type` describes the counter-side of each trade, so `bought` sums the rows where `Side.Type` is `sell`. `PriceAsymmetry: {lt: 0.1}` drops trades whose two sides disagree badly on value ([PriceAsymmetry reference](/docs/graphql/metrics/priceAsymmetry/)), which would otherwise inflate the USD totals. ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}, Dex: {OwnerAddress: {is: "0x33128a8fc17869897dce68ed026d694621f6fdfd"}}, PriceAsymmetry: {lt: 0.1}}} ) { Transaction { From } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "base", "token": "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } ``` ## OHLC in USD of a Token This query retrieves [hourly open, high, low and close prices in USD](https://ide.bitquery.io/OHLC-on-BASE-Uniswap-v3) for one token traded on Uniswap v3. ```graphql { EVM(network: base, dataset: realtime) { DEXTradeByTokens( orderBy: { descendingByField: "Block_testfield" } where: { Trade: { Currency: { SmartContract: { is: "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } } Side: { Currency: { SmartContract: { is: "0x4200000000000000000000000000000000000006" } } Type: { is: buy } } PriceAsymmetry: { lt: 0.1 } Dex: { OwnerAddress: { is: "0x33128a8fc17869897dce68ed026d694621f6fdfd" } } } } limit: { count: 10 } ) { Block { testfield: Time(interval: { in: hours, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) } count } } } ``` ## Get trading volume, buy volume, sell volume of a token This query returns the [traded, buy and sell volume](https://ide.bitquery.io/trade_volume_base_uniswapv3) of token `0x22af33fe49fd1fa80c7149773dde5890d3c76f3b` on Uniswap v3 over the last 24 hours. `PriceAsymmetry: {lt: 0.1}` drops mispriced trades, which would otherwise skew the USD sums. ```graphql query MyQuery { EVM(network: base) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } } Dex: { OwnerAddress: { is: "0x33128a8fc17869897dce68ed026d694621f6fdfd" } } PriceAsymmetry: { lt: 0.1 } } TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract Decimals } } traded_volume_in_usd: sum(of: Trade_Side_AmountInUSD) sell_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ``` ## Get top bought tokens on uniswap v3 This query returns the [top bought tokens on Uniswap v3](https://ide.bitquery.io/top-bought-tokens-on-uniswap-v3). Buys are the rows where `Side.Type`, the counter-side, is `sell`. The `PriceAsymmetry` filter keeps mispriced trades out of the totals. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {OwnerAddress: {is: "0x33128a8fc17869897dce68ed026d694621f6fdfd"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "base" } ``` ## Get top sold tokens on uniswap v3 This query returns the [top sold tokens on Uniswap v3](https://ide.bitquery.io/top-sold-tokens-on-uniswap-v3). Sales are the rows where `Side.Type`, the counter-side, is `buy`. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {OwnerAddress: {is: "0x33128a8fc17869897dce68ed026d694621f6fdfd"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "base" } ``` ## Get Metadata of a token The query below returns a [token's metadata](https://ide.bitquery.io/get-metadata-for-base-uniswap-token): `Name`, `symbol`, `SmartContract Address` and `Decimals`. ```graphql query MyQuery { EVM(network: base, dataset: realtime) { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { SmartContract: { is: "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } } Dex: { OwnerAddress: { is: "0x33128a8fc17869897dce68ed026d694621f6fdfd" } } } } ) { Trade { Currency { Name Symbol SmartContract ProtocolName HasURI Fungible Decimals } } } } } ``` ## Building with Bitquery and Uniswap API Start with the [Base Sniper Bot guide](/docs/usecases/base-sniper-bot/) to build a working project on these APIs. --- ## Base Uniswap V4 API URL: https://docs.bitquery.io/docs/blockchain/Base/uniswap-v4-api/ Base Uniswap V4 API: query Base Uniswap trades, pools, and prices with Bitquery GraphQL DEX APIs. Scale further with WebSocket subscriptions or Kafka streams. # Uniswap V4 API - Track Trader Activities, Token Trades and Market Behavior Uniswap v4 introduces a major shift in protocol architecture. Instead of deploying a separate smart contract for each liquidity pool, Uniswap v4 uses a singleton PoolManager contract that manages all pools internally as structured state. Each pool in Uniswap v4 is uniquely identified by a `PoolId`, which is derived from the pool configuration (token pair, fee, tick spacing, and optional hooks), rather than a dedicated contract address. Using Bitquery's Uniswap v4 APIs, you can track: - DEX trades across all v4 pools - Trades by specific traders - Token-level trade activity - Real-time trade metrics The Uniswap v4 PoolManager contract emits all pool-related events, including pool initialization, swaps, and liquidity modifications, and serves as the single on-chain source of truth for Uniswap v4 activity on Base. ## Real time Trades on Uniswap V4 [This](https://ide.bitquery.io/Real-time-trades-on-uniswap-v4-base) subscription allows user to stream trades on Uniswap V4 in real time on Base. ```graphql subscription { EVM(network: base) { DEXTrades(where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v4"}}}}) { Block{ Time } Trade { PoolId Buy { Currency { Name Symbol SmartContract Decimals } Buyer Amount AmountInUSD Price PriceInUSD Seller } Sell { Currency { Name Symbol SmartContract Decimals } Buyer Amount AmountInUSD Price PriceInUSD Seller } } Transaction { From To Hash } } } } ``` ## Get All Pool Ids for a Currency Using [this](https://ide.bitquery.io/virtual-pool-addresses-for-a-token-on-uniswap-v4-base) API we can get all the virtual pool addresses (`PoolId`) for a currency on Base. For this example we are getting virtual Pool IDs for WETH(`0x4200000000000000000000000000000000000006`). ```graphql query MyQuery { EVM(network: base) { DEXTradeByTokens( where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v4"}}, Currency: {SmartContract: {is: "0x4200000000000000000000000000000000000006"}}}} ) { Trade { PoolId } count } } } ``` ## Latest Trades for a Specific Currencies Pair [This](https://ide.bitquery.io/Latest-trades-for-a-token-pair-on-uniswap-v4-base) API endpoint allows us to filter out the latest trades for a specific pair on Base, using `PoolId` as a filter option. ```graphql { EVM(network: base) { DEXTrades( orderBy: {descending: Block_Time} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v4"}}, PoolId: {is: "0x7c76fa7f6d64061837c3e03002f6362daa51ff9cc3c0ebbed69f140ca3844f30"}}} ) { Block { Time } Trade { PoolId Buy { Currency { Name Symbol SmartContract Decimals } Amount AmountInUSD Price PriceInUSD Seller } Sell { Currency { Name Symbol SmartContract Decimals } Buyer Amount AmountInUSD Price PriceInUSD } } Transaction { From To Hash } } } } ``` ## Uniswap V4 Pair Trade Stats Using [this](https://ide.bitquery.io/trade-stats-for-a-currency-pair-on-uniswap-v4-base) query get pool stats (volume, bought, sold) for a specific Uniswap V4 pool on Base. ```graphql query pairTopTraders { EVM(network: base, dataset: realtime) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } where: { Block:{ Time: {since_relative: {days_ago: 1}} } Trade: { Dex: { ProtocolName: {is: "uniswap_v4"} } PoolId: {is: "0x7c76fa7f6d64061837c3e03002f6362daa51ff9cc3c0ebbed69f140ca3844f30"} } } ) { Trade { Currency{ Name Symbol SmartContract } } bought: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) sold: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Top Buyers of a Token on Uniswap V4 [This](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-pool-base) API returns the top buyers of a token on Uniswap V4 virtual pool on Base, along with the amount bought in token denominations and USD. ```graphql { EVM(network: base) { DEXTrades( orderBy: {descendingByField: "bought_in_usd"} limit: {count: 100} where: { Trade: { Dex: {ProtocolName: {is: "uniswap_v4"}}, Buy: {Currency: {SmartContract: {is: "0x4200000000000000000000000000000000000006"}}} PoolId: {is: "0x7c76fa7f6d64061837c3e03002f6362daa51ff9cc3c0ebbed69f140ca3844f30"} } } ) { Trade { Sell { Currency { Name Symbol SmartContract Decimals } Buyer } } bought:sum(of: Trade_Buy_Amount) bought_in_usd:sum(of: Trade_Buy_AmountInUSD) } } } ``` ## Top Sellers of a Token on Uniswap V4 [This](https://ide.bitquery.io/top-sellers-of-a-currency-on-uniswap-v4-pool-base) API returns the top sellers of a token on Uniswap V4 virtual pool on Base, along with the amount sold in token denominations and USD. ```graphql { EVM(network: base) { DEXTrades( orderBy: {descendingByField: "sold_in_usd"} limit: {count: 10} where: { Trade: { Dex: {ProtocolName: {is: "uniswap_v4"}}, Sell: {Currency: {SmartContract: {is: "0x4200000000000000000000000000000000000006"}}} PoolId: {is: "0x7c76fa7f6d64061837c3e03002f6362daa51ff9cc3c0ebbed69f140ca3844f30"} } } ) { Trade { Buy { Currency { Name Symbol SmartContract Decimals } Seller } } sold:sum(of: Trade_Buy_Amount) sold_in_usd:sum(of: Trade_Buy_AmountInUSD) } } } ``` ## Get Uniswap V4 Pool Liquidity Liquidity for v4 pools is reconstructed by stepping through each price range where liquidity is concentrated , so `AmountCurrencyA` / `AmountCurrencyB` reflect the actual PoolManager balances for that `PoolId`. See the [Base Liquidity API](/docs/blockchain/Base/base-liquidity-api) for the full `DEXPoolEvents` schema. Stream live liquidity for all Uniswap v4 pools on Base. [Run in the Bitquery IDE](https://ide.bitquery.io/uniswap-v4-pool-liquidity-base). ```graphql subscription MyQuery { EVM(network: base) { DEXPoolEvents( where: {PoolEvent: {Dex: {ProtocolName: {is: "uniswap_v4"}}}} ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } Transaction { Hash } } } } ``` Filter to a specific pool by `PoolId`. [Run in the Bitquery IDE](https://ide.bitquery.io/uniswap-v4-pool-liquidity-by-poolid-base). ```graphql subscription MyQuery { EVM(network: base) { DEXPoolEvents( where: { PoolEvent: { Dex: { ProtocolName: { is: "uniswap_v4" } } Pool: { PoolId: { is: "0x7c76fa7f6d64061837c3e03002f6362daa51ff9cc3c0ebbed69f140ca3844f30" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } Transaction { Hash } } } } ``` > In Uniswap v4 all pools live in the singleton PoolManager, so `Pool.SmartContract` is the same across pools — use `Pool.PoolId` to identify each pool. --- ## Base Zora API URL: https://docs.bitquery.io/docs/blockchain/Base/base-zora-api/ Zora on Base: track newly created Zora tokens, latest Zora trades, trades of a specific token, and a wallet's Zora trades up to a block height. # Base Zora API Bitquery provides comprehensive Zora data through APIs, Streams and Data Dumps. This section provides you with a set of GraphQL APIs and streams that offer insights into the Zora protocol on Base blockchain. The below GraphQL APIs and Streams are examples of data points you can get with Bitquery for Zora on Base. If you have any questions on other data points, reach out to [support](https://t.me/Bloxy_info). Need zero-latency Base data? [Read about our Kafka Streams and Contact us for a Trial](/docs/streams/kafka-streaming-concepts/). You may also be interested in: - [Base DEX Trade APIs ➤](/docs/blockchain/Base/base-dextrades/) - [Base Uniswap APIs ➤](/docs/blockchain/Base/base-uniswap-api/) :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Get Newly Created Zora Tokens Every Zora coin is created by the Zora factory, `0x777777751622c0d3258f214F9DF38E35BF45baF3`, which emits `CoinCreatedV4`. The event carries the `coin` address, `name`, `symbol` and metadata `uri`, the `caller`, the `payoutRecipient` that earns creator rewards, the `platformReferrer`, the `currency` the coin is paired with, the Uniswap v4 `PoolKey` and the factory `version`. The factory created about 530 coins in the 24 hours to 2026-10-26. The query filters on the event's `SignatureHash` because a filter on the event name does not match every stored row. [Run it in the IDE ➤](https://ide.bitquery.io/Zora-coins-created-CoinCreatedV4) ```graphql query ZoraCoinsCreated { EVM(network: base) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: {LogHeader: {Address: {is: "0x777777751622c0d3258f214F9DF38E35BF45baF3"}}, Log: {Signature: {SignatureHash: {is: "2de436107c2096e039c98bbcc3c5a2560583738ce15c234557eecb4d3221aa81"}}}} ) { Block { Time } Transaction { From Hash } Arguments { Name Value { ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` To stream new coins as they are created, change `query` to `subscription` and remove `limit` and `orderBy`. ## Latest Trades on Zora This query fetches the latest DEX trades on the Zora protocol (`zora_v4`) on Base blockchain. Try out the API [here](https://ide.bitquery.io/Latest-Zora-Trades-on-Base) in the Bitquery IDE. ```graphql { EVM(dataset: realtime, network: base) { DEXTrades( limit: { count: 20 } orderBy: { descending: Block_Time } where: { Trade: { Dex: { ProtocolName: { is: "zora_v4" } } } } ) { Block { Time Number } Fee { Burnt BurntInUSD EffectiveGasPrice EffectiveGasPriceInUSD GasRefund MinerReward MinerRewardInUSD PriorityFeePerGas PriorityFeePerGasInUSD Savings SavingsInUSD SenderFee SenderFeeInUSD } Receipt { ContractAddress Status } TransactionStatus { Success } Log { Signature { Name } SmartContract } Call { From InternalCalls Signature { Name Signature } To Value } Transaction { Gas Cost CostInUSD GasFeeCap GasFeeCapInUSD GasPrice GasPriceInUSD GasTipCap GasTipCapInUSD Index Nonce Protected Time Type Value ValueInUSD Hash From To } Trade { Buy { Amount AmountInUSD Buyer Seller Currency { Decimals Name Symbol SmartContract } Price PriceInUSD } Sell { Amount AmountInUSD Buyer Seller Currency { Name Symbol SmartContract } Price PriceInUSD } Dex { ProtocolName SmartContract OwnerAddress } } } } } ``` ## All Zora trades for a wallet up to a block height Return **`zora_v4`** trades on Base where the wallet is **Buyer** or **Seller** on the trade, with **`Block.Number` ≤** your chosen ceiling. Uses **`dataset: combined`** for history plus **`limit: 1000`** and **`orderBy: { ascending: Block_Time }`** for chronological pages. The `any` group also matches trades in transactions the wallet sent (**`Transaction.From`**), which catches swaps routed through a contract where the wallet is neither buyer nor seller. [Run in Bitquery IDE](https://ide.bitquery.io/Zora-trades-for-a-wallet-up-to-block) ```graphql query ($address: String) { EVM(dataset: combined, network: base) { DEXTrades( limit: { count: 1000 } orderBy: { ascending: Block_Time } where: { Block: { Number: { le: "36453721" } }, any: [ { Trade: { Buy: { Buyer: { is: $address } } } }, { Trade: { Buy: { Seller: { is: $address } } } }, { Transaction: { From: { is: $address } } } ], Trade: { Dex: { ProtocolName: { is: "zora_v4" } } } } ) { Block { Time Number } Transaction { Hash From To } Trade { Buy { Amount AmountInUSD Buyer Seller Currency { Decimals Name Symbol SmartContract } Price PriceInUSD } Sell { Amount AmountInUSD Buyer Seller Currency { Name Symbol SmartContract } Price PriceInUSD } Dex { ProtocolName SmartContract OwnerAddress } } } } } ``` **Variables:** ```json { "address": "0xa9ce7310c6d68b0e08df6de6fc79fc572f882bb1" } ``` ## Latest Trades of a Token on Zora [Run Query](https://ide.bitquery.io/Latest-Trades-of-a-Token-on-Zora-Base) ```graphql { EVM(dataset: realtime, network: base) { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolName: {is: "zora_v4"}}, Buy: {Currency: {SmartContract: {is: "0x1111111111166b7fe7bd91427724b487980afc69"}}}}} ) { Block { Time Number } Fee { Burnt BurntInUSD EffectiveGasPrice EffectiveGasPriceInUSD GasRefund MinerReward MinerRewardInUSD PriorityFeePerGas PriorityFeePerGasInUSD Savings SavingsInUSD SenderFee SenderFeeInUSD } Receipt { ContractAddress Status } TransactionStatus { Success } Log { Signature { Name } SmartContract } Call { From InternalCalls Signature { Name Signature } To Value } Transaction { Gas Cost CostInUSD GasFeeCap GasFeeCapInUSD GasPrice GasPriceInUSD GasTipCap GasTipCapInUSD Index Nonce Protected Time Type Value ValueInUSD Hash From To } Trade { Buy { Amount AmountInUSD Buyer Seller Currency { Decimals Name Symbol SmartContract } Price PriceInUSD } Sell { Amount AmountInUSD Buyer Seller Currency { Name Symbol SmartContract } Price PriceInUSD } Dex { ProtocolName SmartContract OwnerAddress } } } } } ``` --- ## Believe Launchpad API URL: https://docs.bitquery.io/docs/blockchain/Solana/Believe-API/ Believe Launchpad on Solana: track token creation on Meteora DBC in real time, creation time, graduated tokens and creator fee claims. # Believe Launchpad API :::tip Need real-time Believe data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Believe data older than ~30 days**, raw per-swap detail, or call / event context. ::: ## 🎯 What is Believe Launchpad? The Believe Launchpad is a decentralized token launchpad built on the Solana blockchain that simplifies token creation and trading. It allows users to mint tokens directly through social media interactions (especially X/Twitter), making token creation accessible to everyone, even without technical expertise. ## Related APIs - **[Meteora Dynamic Bonding Curve API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/)** - Core DBC functionality - **[Moonshot APIs](/docs/blockchain/Solana/Moonshot-API/)** - Alternative launchpad - **[FourMeme APIs](/docs/blockchain/BSC/four-meme-api/)** - BSC-based token creation ## Pro Tips - **Use the IDE**: The Bitquery IDE provides autocomplete and validation - **Start Simple**: Begin with basic queries and gradually add complexity - **Test Incrementally**: Build queries step by step, testing each addition - **Contact Support**: Get help on [Telegram](https://t.me/Bloxy_info) for specific issues :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: If you want fastest data without any latency, we can provide Kafka streams, please [fill this form](https://bitquery.io/forms/api) for it. Our Team will reach out. ## Track Token creation using Believe Launchpad on Meteora DBC in realtime Use the stream: [Track Believe token creations on Meteora DBC (realtime) ➤](https://ide.bitquery.io/track-Token-creation-using-Believe-Protocol-on-Meteora-DBC-in-realtime_2). `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` is the address of Meteora DBC and `5qWya6UjwWnGVhdSBL3hyZ7B45jbk6Byt1hwd7ohEGXE` is the Believe Token Authority address, the address which is responsible for calling the instructions on Meteora DBC Program. ```graphql subscription MyQuery { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { is: "initialize_virtual_pool_with_spl_token" } } Accounts: { includes: { Address: { is: "5qWya6UjwWnGVhdSBL3hyZ7B45jbk6Byt1hwd7ohEGXE" } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } ``` ## Check when a Believe Launchpad token was created on Meteora DBC Using below query, you can check when was a Believe Launchpad token created. Here we have taken the example of checking creation time and transaction signature of this token `GsVr8GdT57gBa6GxujrtAeRGmYbFfABGFk2eaG2DzBLV`. Note: we only have the last 12 hours of Solana Instructions data so this query will not return anything for the Believe Launchpad token which was created more than 12 hours ago. Run the query: [Get a Believe token's creation time and dev address? ➤](https://ide.bitquery.io/check-when-a-Believe-protocol-token-was-created-on-Meteora-DBC_1). ```graphql query MyQuery($tokenAddress: String!) { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {is: "initialize_virtual_pool_with_spl_token"}}, Accounts: {includes: {Address: {is: $tokenAddress }}}}, Transaction: {Result: {Success: true}, Signer: {is: "5qWya6UjwWnGVhdSBL3hyZ7B45jbk6Byt1hwd7ohEGXE"}}} ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } { "tokenAddress": "GsVr8GdT57gBa6GxujrtAeRGmYbFfABGFk2eaG2DzBLV" } ``` ## Get the Believe Launchpad tokens which are graduated to Meteora For checking which Believe tokens graduated, we need to get all the tokens created by Believe on Meteora DBC using this [Get All Token Creations by Believe - API](/docs/blockchain/Solana/Believe-API/#get-latest-meteora-dbc-token-creations-using-believe-launchpad) and then after getting all the token addresses put them in [Check if the Believe Tokens has Graduated - API](https://ide.bitquery.io/Check-if-the-tokens-have-migrated-from-Meteora-DBC_1) to check which of them graduated to Meteora. ```graphql query MyQuery { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { is: "initialize_virtual_pool_with_spl_token" } } } Transaction: { Result: { Success: true } Signer: { is: "5qWya6UjwWnGVhdSBL3hyZ7B45jbk6Byt1hwd7ohEGXE" } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } ``` Then put all the token addresses in the `$tokenAddresses` variable in the following query. Run it here: [Check if the tokens have migrated from Meteora DBC ➤](https://ide.bitquery.io/Check-if-the-tokens-have-migrated-from-Meteora-DBC_1). ```graphql query MyQuery($tokenAddresses: [String!]) { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["migrate_meteora_damm", "migration_damm_v2"]}}, Accounts: {includes: {Address: {in: $tokenAddresses}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } { "tokenAddresses":["3EX4yHYs25RXaNMBgaNtpGxPKvX73P9QWVw8fpNEhnow","2bzXpTCu3faGocjBKZvxv63yV3gnWDZYfH6mRVfGzbh8","Dpz6knqUSTfV2ESXqQvbiWVznzRPYSYivUtXT3TVpWkA"] } ``` ## Get latest Meteora DBC Token Creations using Believe Launchpad Check this API: [Latest Believe token creations ➤](https://ide.bitquery.io/Token-creation-using-Believe-Protocol-on-Meteora-DBC#) to get the 10 latest Believe Launchpad created Tokens. ```graphql query MyQuery { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { is: "initialize_virtual_pool_with_spl_token" } } } Transaction: { Result: { Success: true } Signer: { is: "5qWya6UjwWnGVhdSBL3hyZ7B45jbk6Byt1hwd7ohEGXE" } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } ``` ## Get latest Claims of Creator Fees using Believe Launchpad Check this query: [Latest creator trading fee claims (Believe) ➤](https://ide.bitquery.io/Claim-creator-trading-fee-using-Believe-Protocol-on-Meteora-DBC#) to get the most recent claims of creator trading fees via Believe Launchpad. ```graphql query MyQuery { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { is: "claim_creator_trading_fee" } } } Transaction: { Result: { Success: true } Signer: { is: "5qWya6UjwWnGVhdSBL3hyZ7B45jbk6Byt1hwd7ohEGXE" } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } ``` --- ## Best Practices for Solana gRPC Streams URL: https://docs.bitquery.io/docs/grpc/solana/best_practices/ Best Practices for Solana gRPC Streams for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Best Practices for Solana gRPC Streams When building applications with Bitquery's Solana gRPC streams, follow these best practices to ensure your application is reliable, efficient, and handles data effectively. This guide covers filtering, connection management, error handling, and monitoring. ## Filter Configuration Use specific filters that cover your usecase to reduce amount of data consumed. There is no limit on the number of filters you can use. ```yaml # config.yaml server: address: "corecast.bitquery.io" authorization: "" insecure: false stream: type: "dex_trades" filters: # Filter by specific programs programs: - "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM" # Raydium # Filter by specific tokens tokens: - "So11111111111111111111111111111111111111112" # WSOL # Filter by minimum trade amount min_amount: 1000000 # 1 USDC (6 decimals) ``` ## Connection Management ### Automatic Reconnection Always implement automatic reconnection with exponential backoff to handle network interruptions: ```javascript let currentStream = null; let reconnectAttempts = 0; const MAX_RECONNECT_ATTEMPTS = 10; const INITIAL_RECONNECT_DELAY = 1000; // 1 second const MAX_RECONNECT_DELAY = 60000; // 60 seconds function calculateReconnectDelay(attempt) { const delay = Math.min( INITIAL_RECONNECT_DELAY * Math.pow(2, attempt), MAX_RECONNECT_DELAY ); return delay + Math.random() * 1000; // Add jitter } function attemptReconnection() { if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) { console.error("Max reconnection attempts reached"); return; } reconnectAttempts++; const delay = calculateReconnectDelay(reconnectAttempts - 1); setTimeout(() => { console.log(`Reconnecting... (attempt ${reconnectAttempts})`); listenToStream(); }, delay); } ``` ### Error Handling Handle different types of gRPC errors appropriately: ```javascript currentStream.on("error", (error) => { console.error("Stream error:", error); // Handle connection drops (code 14) if (error.code === 14 || error.details === "Connection dropped") { console.log("Connection dropped, attempting to reconnect..."); attemptReconnection(); } else { console.error("Non-recoverable error:", error); process.exit(1); } }); currentStream.on("end", () => { console.log("Stream ended"); if (!isReconnecting) { attemptReconnection(); } }); ``` ## Performance Optimization ### Efficient Message Processing Process messages efficiently to avoid blocking the event loop: ```javascript let messageCount = 0; const BATCH_SIZE = 100; let messageBatch = []; currentStream.on("data", (message) => { messageBatch.push(message); messageCount++; // Process in batches to avoid blocking if (messageBatch.length >= BATCH_SIZE) { processBatch(messageBatch); messageBatch = []; } }); function processBatch(batch) { // Process messages asynchronously setImmediate(() => { batch.forEach((message) => { if (message.Trade) { handleTrade(message.Trade); } else if (message.Transaction) { handleTransaction(message.Transaction); } // Handle other message types... }); }); } ``` ### Memory Management Implement proper cleanup to prevent memory leaks: ```javascript function cleanupStream() { if (currentStream) { try { currentStream.cancel(); } catch (error) { // Stream might already be closed } currentStream = null; } } // Handle graceful shutdown process.on("SIGINT", () => { cleanupStream(); process.exit(0); }); ``` ## Client Configuration Use appropriate gRPC client options for production: ```javascript const client = new solanaCorecast.CoreCast( config.server.address, grpc.credentials.createSsl(), { // Keep-alive settings "grpc.keepalive_time_ms": 30000, "grpc.keepalive_timeout_ms": 5000, "grpc.keepalive_permit_without_calls": true, // Message size limits "grpc.max_receive_message_length": 4 * 1024 * 1024, // 4MB "grpc.max_send_message_length": 4 * 1024 * 1024, // 4MB // Connection management "grpc.enable_retries": 1, "grpc.max_connection_idle_ms": 30000, } ); ``` ## Monitoring and Logging ### Performance Monitoring Track key metrics for monitoring: ```javascript let stats = { messagesProcessed: 0, errors: 0, lastMessageTime: null, startTime: Date.now(), }; function logStats() { const uptime = Date.now() - stats.startTime; const rate = stats.messagesProcessed / (uptime / 1000); console.log( `Stats: ${stats.messagesProcessed} messages, ${rate.toFixed(2)} msg/sec` ); } // Log stats every 30 seconds setInterval(logStats, 30000); ``` ### Error Tracking Implement comprehensive error tracking: ```javascript function trackError(error, context) { console.error(`Error in ${context}:`, { message: error.message, code: error.code, details: error.details, timestamp: new Date().toISOString(), }); stats.errors++; } ``` ### Health Checks Implement health checks for monitoring: ```javascript function healthCheck() { return { status: currentStream ? "connected" : "disconnected", reconnectAttempts: reconnectAttempts, messagesProcessed: stats.messagesProcessed, uptime: Date.now() - stats.startTime, }; } ``` ## Common Pitfalls 1. **Not handling connection drops**: Always implement reconnection logic 2. **Blocking the event loop**: Process messages asynchronously 3. **Memory leaks**: Clean up streams and timers properly 4. **Missing error handling**: Handle all gRPC error codes 5. **Inefficient filtering**: Use server-side filters to reduce bandwidth 6. **No monitoring**: Track key metrics for production deployments --- ## BigQuery Blockchain Data Intro URL: https://docs.bitquery.io/docs/subscriptions/google-bigquery/intro/ Getting Started using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. Run it in the IDE, then ship in your app. # Getting Started In this section, we will see how to set up a pipeline using Bitquery real-time GraphQL subscriptions. We will use a subscription query, integrate Google Pub/Sub, create subscribers, and then set up a BigQuery table to receive data from one of those Pub/Sub subscribers. This is just a sample setup—you can use any intermediary to feed data into Google BigQuery or any other cloud database. ![Bitquery to Google BigQuery data pipeline](/img/diagrams/bigquery.png) ## Architecture - Pub/Sub acts as a messaging intermediary, allowing your Bitquery data pipeline to be independent of downstream consumers. - You can later process or store the data in different systems (e.g., BigQuery, Cloud Functions) without modifying the Bitquery integration. ## Prerequisities - Enable billing on your Google Cloud Account ( Free-tier allowed), needed for APIs - Setup Access for Service Accounts to access Pub-Sub Subscription and Google Bigquery Table ## Video Tutorial ### Scalability - Pub/Sub scales automatically, ensuring that your system can handle spikes in Bitquery traffic without worrying about overloading downstream systems. ### Reliability Pub/Sub guarantees delivery "at least once," so you don't lose data even if there are temporary processing failures. ### Flexibility Pub/Sub supports multiple subscribers for the same topic, so you can fan out data to different systems (e.g., analytics, monitoring, alerts). --- ## Binance Exchange Wallet Monitoring URL: https://docs.bitquery.io/docs/usecases/binance-exchange-wallet-monitoring/ Build Binance Exchange Wallet Monitoring: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Monitoring Withdrawals and Deposits for 1000s of Binance Exchange Wallets In this guide we will utilize the [Protobuf Kafka streams](/docs/streams/protobuf/kafka-protobuf-python/) provided by Bitquery to monitor withdrawals and deposits for a large number of Binance Exchange Wallets on BSC network. You can read more about Kafka solution by Bitquery [here](/docs/streams/kafka-streaming-concepts/). Checkout the complete [codebase](https://github.com/bitquery/binance-exchange-wallets-monitoring) for any issues in the tutorial. ## Prerequisites 1. Create a project folder with the given command. ```shell mkdir bsc-exchange-wallet-monitoring ``` 2. Install the dependencies using the command line. ```shell pip install bitquery-pb2-kafka-package ``` 3. Create the file structure with the following commands. ```shell touch main.py mkdir helpers cd helpers touch convert_bytes.py ``` ## Helper Functions In this section we will discuss the code written inside the helpers folder. ### Convert Bytes This functions takes the base58 encoded bytes as parameter and returns readable string values. ```python def convert_bytes(value, encoding='hex'): if encoding == 'base58': return base58.b58encode(value).decode() else: return value.hex() ``` ## Imports ```python from confluent_kafka import Consumer, KafkaError, KafkaException from google.protobuf.message import DecodeError from evm import token_block_message_pb2 from helpers.convert_bytes import convert_bytes from helpers.print_protobuf_message import print_protobuf_message ``` ## Creating Kafka Configuration The credentials such as `username` and `password` could be received by contacting the Bitquery team via - sales@bitquery.io ```python group_id_suffix = uuid.uuid4().hex conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092', 'group.id': f'{username}-group-{group_id_suffix}', 'session.timeout.ms': 30000, 'security.protocol': 'SASL_PLAINTEXT', 'ssl.endpoint.identification.algorithm': 'none', 'sasl.mechanisms': 'SCRAM-SHA-512', 'sasl.username': username, 'sasl.password': password, 'auto.offset.reset': 'latest', } ``` ## Creating Consumer and Subcribing to Topic The topic to subscribe should be selected based on the usecase. In this case we are looking to track the deposits and withrawls of tokens for a list of Binance Exchange Wallets, thus `bsc.tokens.proto` would be the best choice. ```python consumer = Consumer(conf) topic = 'bsc.tokens.proto' consumer.subscribe([topic]) ``` ## Creating Set of Binance Exchange Wallets For the purpose of tutorial we have directly created a set containing a bunch of Binance exchange wallet addresses. When building an enterprise grade solution where the number of wallets are in thousands or millions, the set could be saved in a separate file. The wallets are stored in a set instead of list due to fast lookup in sets. ```python wallets = { '0xf977814e90da44bfa03b6295a0616a897441acec', '0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8', '0x5a52e96bacdabb82fd05763e25335261b270efcb', '0x3c783c21a0383057d128bae431894a5c19f9cf06', '0xdccf3b77da55107280bd850ea519df3705d1a75a', '0x8894e0a0c962cb723c1976a4421c95949be2d4e3', '0x515b72ed8a97f42c568d6a143232775018f133c8', '0xbd612a3f30dca67bf60a39fd0d35e39b7ab80774', '0x01c952174c24e1210d26961d456a77a39e1f0bb0', '0x29bdfbf7d27462a2d115748ace2bd71a2646946c', '0x73f5ebe90f27b46ea12e5795d16c4b408b19cc6f', '0x161ba15a5f335c9f06bb5bbb0a9ce14076fbb645', '0x1fbe2acee135d991592f167ac371f3dd893a508b', '0xeb2d2f1b8c558a40207669291fda468e50c8a0bb', '0xa180fe01b906a1be37be6c534a3300785b20d947' } ``` ## Proccess Message Function This function receives the message from the stream as a parameter. The message contains a list of token transfers and the function checks if either of the `sender` or `receiver` are present in the set defined earlier. If either of the condition is satisfied then it prints the message displayed in the [Final Results](#final-result) section. ```python def process_message(message): try: buffer = message.value() parsed_message = token_block_message_pb2.TokenBlockMessage() parsed_message.ParseFromString(buffer) transfers = parsed_message.Transfers for transfer in transfers: sender = '0x' + convert_bytes(transfer.Sender) receiver = '0x' + convert_bytes(transfer.Receiver) amount = int.from_bytes(transfer.Amount, byteorder='big')/10e18 currency = transfer.Currency symbol = currency.Symbol if sender in wallets: print(receiver, "has withdrawn", amount, symbol, "from the", sender, "Exchange Wallet") elif receiver in wallets: print(sender, "has deposited", amount, symbol, "to the", receiver, "Exchange Wallet") except DecodeError as err: print(f"Protobuf decoding error: {err}") except Exception as err: print(f"Error processing message: {err}") ``` ## Poll and Monitor Activities in Real Time This is the main loop for consuming Kafka messages and monitoring the exchange wallets activities in real time. ```python try: while True: msg = consumer.poll(timeout=1.0) if msg is None: continue if msg.error(): if msg.error().code() == KafkaError._PARTITION_EOF: continue else: raise KafkaException(msg.error()) process_message(msg) except KeyboardInterrupt: print("\nStopping consumer...") finally: consumer.close() ``` ## Running the Script Run this command line to run the `main.py` script. ```shell python main.py ``` ## Final Result ![Final Results of Project](/img/usecases/kafka-examples/result.png) --- ## Binance Meme Rush API URL: https://docs.bitquery.io/docs/blockchain/BSC/binance-memerush-api/ Binance Meme Rush tokens on BNB Chain: track migrations to PancakeSwap, bonding curve progress, token creations, trades, top traders and market cap. # Binance Meme Rush API Binance has launched Meme Rush, a new discovery feature inside the Binance Wallet that gives users early access to trending meme-coins from external launch platforms. Through a partnership with Four.Meme on the BNB Smart Chain, users can create and launch their own meme coins directly via Binance Wallet. Tokens launched in this way typically have contract addresses that start with `0x4444…`. Get ultra low latency Binance Meme Rush memecoin data on BNB Chain: live trades, bonding curve progress, newly created tokens, prices, OHLC, liquidity, migrations, top traders and more. The below GraphQL APIs and Streams are examples of data points you can get with Bitquery. If you have questions on other data points, reach out to [support](https://t.me/Bloxy_info). Need zero-latency BSC data via Kafka? Read about our [Kafka Streams](/docs/streams/kafka-streaming-concepts/) and contact us for a trial. You may also be interested in: - [Crypto Price API ➤](/docs/trading/crypto-price-api/) - [BSC Pancake Swap APIs ➤](/docs/blockchain/BSC/pancake-swap-api/) - [BSC DEX Trades ➤](/docs/blockchain/BSC/bsc-dextrades/) - [Pump.fun API ➤](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) ::::note To query or stream data via GraphQL outside the Bitquery IDE, you need to generate an API access token. Follow the steps here to create one: /docs/authorization/how-to-generate/ :::: --- ### Table of Contents ### 1. Token Lifecycle, Migrations & Bonding Curve - [Track All Binance Meme Rush Tokens That Have Migrated to Pancakeswap ➤](#track-all-binance-meme-rush-tokens-that-have-migrated-to-pancakeswap) - [Check if a Binance Meme Rush token has migrated or not ➤](#check-if-a-binance-meme-rush-token-has-migrated-or-not) - [Bonding Curve Progress API for Binance Meme Rush token ➤](#bonding-curve-progress-api-for-binance-meme-rush-token) - [Get Binance Meme Rush Tokens which are above 95% Bonding Curve Progress ➤](#get-binance-meme-rush-tokens-which-are-above-95-bonding-curve-progress) - [Get Binance Meme Rush token creations on Four Meme ➤](#get-binance-meme-rush-token-creations-on-four-meme) - [Get Meme Rush Tokens created by a specific Dev ➤](#get-meme-rush-tokens-created-by-a-specific-dev) - [Get Dev Address of a Meme Rush token ➤](#get-dev-address-of-a-meme-rush-token) ### 2. Trading & Market Data - [Subscribe the Latest Trades of Meme Rush tokens on Four Meme ➤](#subscribe-the-latest-trades-of-meme-rush-tokens-on-four-meme) - [Get Latest Buys and Sells for a Meme Rush Token ➤](#get-latest-buys-and-sells-for-a-meme-rush-token) - [Get Trade Metrics of a Meme Rush Token ➤](#get-trade-metrics-of-a-meme-rush-token) - [Get latest price of a Meme Rush token ➤](#get-latest-price-of-a-meme-rush-token) - [Get ATH price of a Meme Rush Token ➤](#get-ath-price-of-a-meme-rush-token) - [Get Price Change Percentage for a Meme Rush Token ➤](#get-price-change-percentage-for-a-meme-rush-token) - [Get OHLCV data of a Meme Rush Token ➤](#get-ohlcv-data-of-a-meme-rush-token) - [Get Trade Volume and Number of Trades for a Meme Rush Token ➤](#get-trade-volume-and-number-of-trades-for-a-meme-rush-token) ### 3. Trader Insights & Analytics - [Monitor Meme Rush trades of traders on Four.Meme ➤](#monitor-meme-rush-trades-of-traders-on-fourmeme) - [Track Meme Rush Tokens in 14k to 18k Marketcap ➤](#track-meme-rush-tokens-in-14k-to-18k-marketcap) - [Top Buyers for a Meme Rush Token on Four Meme ➤](#top-buyers-for-a-meme-rush-token-on-four-meme) - [Top Traders of a Meme Rush token ➤](#top-traders-of-a-meme-rush-token) ### 4. Market Cap, Liquidity & Metadata - [Get Realtime Market Cap and Price of a Meme Rush Token ➤](#get-realtime-market-cap-and-price-of-a-meme-rush-token) - [Metadata for a Newly Created Meme Rush Token ➤](#metadata-for-a-newly-created-meme-rush-token) - [Get liquidity of a Meme Rush token ➤](#get-liquidity-of-a-meme-rush-token) ### 5. Getting Started - [Bitquery DEX Data Access Options ➤](#bitquery-dex-data-access-options) - [Getting Started with Bitquery ➤](#getting-started-with-bitquery) ## Bitquery DEX Data Access Options - **GraphQL APIs**: Query historical and real-time EVM data with flexible filtering and aggregation - **Real-time Streams**: Subscribe to live EVM blockchain events via WebSocket subscriptions - **Data Store exports**: parsed Parquet you download from S3 or Cloudflare R2; custom exports can go to your own bucket or warehouse. See the [Bitquery Data Store](https://bitquery.io/datastore). - **Kafka Streams**: High-throughput data streaming for enterprise applications ## Getting Started with Bitquery: - [Learning Track](/docs/start/learning-path/): Learning track to get started with Bitquery GraphQL APIs and streams. - [BSC DEX Trades](/docs/blockchain/BSC/bsc-dextrades/): Real time DEX Trading data via examples. - [BSC Uniswap APIs](/docs/blockchain/BSC/bsc-uniswap-api/): Uniswap Trades on BSC network with the help of examples. - [BSC Pancake Swap APIs](/docs/blockchain/BSC/pancake-swap-api/): Pancake swap Trades on BSC network with the help of examples. - [Trade APIs](/docs/trading/crypto-price-api/examples/): Multi-chain Trade API Examples. ## Track All Binance Meme Rush Tokens That Have Migrated to Pancakeswap This query tracks Binance Meme Rush token migrations to Pancakeswap in realtime by monitoring transactions sent to the Four Meme factory address (`0x5c952063c7fc8610ffdb798152d69f0b9550762b`) and filtering for `PairCreated` and `PoolCreated` events. These events are emitted when a meme rush token graduates from Four Meme and migrates to Pancakeswap. Test it [here](https://ide.bitquery.io/binance-meme-rush-migration-to-pancakeswap).
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { Events( where: { Log: { Signature: { Name: { in: ["PairCreated", "PoolCreated"] } } } Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Arguments: { includes: { Value: { Address: { startsWith: "0x4444" } } } } } ) { Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } } } Transaction { Hash } } } } ```
## Check if a Binance Meme Rush token has migrated or not Below query will only show response if a the mentioned meme rush tokens have migrated to Pancakeswap. Note: Please use a `Block{Date}` filter to minimize the data processing and hence the query processing time and get fast responses. Try the query [here](https://ide.bitquery.io/if-meme-rush-token-migrated-from-four-meme-or-not#).
Click to expand GraphQL query ```graphql { EVM(network: bsc, dataset: combined) { DEXTradeByTokens( where: {Block: {Date: {since: "2025-10-10"}}, Trade: {Dex: {OwnerAddress: {in: ["0xca143ce32fe78f1f7019d7d551a6402fc5350c73"]}}, Currency: {SmartContract: {in: ["0x4444ab6a517216ee356dc899b6f28a62249446b5", "0x44443eed3477fe8de8696e0b6021ff72cc6624ef"]}}}} ) { count Trade { Currency { SmartContract } } } } } ```
## Bonding Curve Progress API for Binance Meme Rush token Below query will give you amount of `left tokens` put it in the below given simplied formulae and you will get Bonding Curve progress for the meme rush token. ### Bonding Curve Progress Formula - **Formula**: BondingCurveProgress = 100 - ((leftTokens \* 100) / initialRealTokenReserves) Where: - leftTokens = realTokenReserves - reservedTokens - initialRealTokenReserves = totalSupply - reservedTokens - **Definitions**: - `initialRealTokenReserves` = `totalSupply` - `reservedTokens` - `totalSupply`: 1,000,000,000 (Binance Meme Rush Token) - `reservedTokens`: 200,000,000 - Therefore, `initialRealTokenReserves`: 800,000,000 - `leftTokens` = `realTokenReserves` - `reservedTokens` - `realTokenReserves`: Token balance at the market address. :::note **Simplified Formula**: BondingCurveProgress = 100 - (((balance - 200000000) \* 100) / 800000000) :::
Click to expand GraphQL query ```graphql query MyQuery($token: String) { EVM(dataset: combined, network: bsc) { Balances( where: {Balance: {Address: {is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b"}}, Currency: {SmartContract: {is: $token}}} ) { Currency { Name } Balance { Address balance: Amount } Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Balance_balance - 200000000) * 100) / 800000000)" ) } } } ````
Click to expand Query Varibles (Paste this in variables section on IDE) ```json { "token": "0x444478624cb7c53abe549d6449e024f4d8b51bec" } ````
## Get Binance Meme Rush Tokens which are above 95% Bonding Curve Progress Using the above Bonding Curve formula, we can calculate the token balances for the Four Meme Proxy contract (0x5c952063c7fc8610FFDB798152D69F0B9550762b) corresponding to approximately 95% to 100% progress along the bonding curve, that comes out to be `200,000,000` to `240,000,000`. The Binance Meme Rush tokens in the response are arranged in the ascending order of Bonding Curve Percentage, i.e., 95% to 100%.
Click to expand GraphQL query ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { Balances( limit: { count: 10 } where: { Balance: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } Currency: { SmartContract: { startsWith: "0x4444" } } } orderBy: { descending: Balance_Amount } ) { Currency { SmartContract Name } Balance { Address balance: Amount(selectWhere: { ge: "200000000", le: "240000000" }) } Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Balance_balance - 200000000) * 100) / 800000000)" ) } } } ```
## Get Binance Meme Rush token creations on Four Meme [Run Query](https://ide.bitquery.io/track-Binance-Meme-Rush-token-creations-on-Four-meme-token) Binance Meme Rush is a new feature launched by Binance Wallet in collaboration with Four.Meme, aimed at enabling users to access meme tokens early in their initial stages, before they are listed on decentralized exchang This query retrieves newly created Binance Meme Rush tokens on Four Meme by listening to the `TokenCreate` event and specifically filtering for event transactions which includes address value in arguments `0x4444`. The response provides: **Token Information:** - **creator**: Wallet address of the token creator - **token**: Contract address of the newly created token - **name**: Token name - **symbol**: Token symbol/ticker - **totalSupply**: Total supply (always 1 billion tokens) **Launch Details:** - **requestId**: Unique identifier for the token creation - **launchTime**: Unix timestamp of when the token launched - **launchFee**: Fee paid
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: bsc) { Events( where: { Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Log: { Signature: { Name: { is: "TokenCreate" } } } Arguments: { includes: { Value: { Address: { startsWith: "0x4444" } } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Log { Signature { Name Signature } } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } Name Type } Transaction { Hash To From } } } } ```
## Get Meme Rush Tokens created by a specific Dev This API fetches Binance Meme Rush tokens created by a specific dev on BSC by tracking token minting transfers signed by a particular dev. `Dev Address` here in example is `0xF4f3eb591c47d14614D3A54aCBA28019e2041066`. Use a date filter based on your needs — shorter time ranges mean faster execution and reduced query time. [Run Query](https://ide.bitquery.io/meme-rush-tokens-created-by-specific-dev)
Click to expand GraphQL query ```graphql { EVM(network: bsc, dataset: combined) { Transfers( where: { Block: { Date: { since: "2025-08-01" } } Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } Currency: { SmartContract: { startsWith: "0x4444" } } } Transaction: { From: { in: ["0xF4f3eb591c47d14614D3A54aCBA28019e2041066"] } } } ) { Transaction { From To } Transfer { Sender Receiver Amount Currency { Name Symbol SmartContract } } } } } ```
## Get Dev Address of a Meme Rush token Fetches the developer address that created a specific Meme Rush token on BSC by tracing the minting transfer (from the zero address) of that token’s smart contract. Use a date filter based on your needs — shorter time ranges make the query execute faster and return results more efficiently. Token Address in this example is `0x44442f6b816d4308859470573cb32652c8eee0bb`. [Run Query](https://ide.bitquery.io/check-who-created-this-meme-rush-token)
Click to expand GraphQL query ```graphql { EVM(network: bsc, dataset: combined) { Transfers( where: { Block: { Date: { since: "2025-08-01" } } Transfer: { Currency: { SmartContract: { is: "0x44442f6b816d4308859470573cb32652c8eee0bb" } } Sender: { is: "0x0000000000000000000000000000000000000000" } } } ) { Transaction { From To } Transfer { Sender Receiver Amount Currency { Name Symbol SmartContract } } } } } ```
## Subscribe the Latest Trades of Meme Rush tokens on Four Meme Using subscriptions you can subscribe to the latest trades of Meme Rush tokens on Four Meme as shown in this [example](https://ide.bitquery.io/Latest-trades-of-meme-rush-tokens-on-fourmeme). The subscription returns latest trade info such as buyers and sellers, buy and sell currency details and amount of currency.
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } } any: [ { Trade: { Buy: { Currency: { SmartContract: { startsWith: "0x4444" } } } } } { Trade: { Sell: { Currency: { SmartContract: { startsWith: "0x4444" } } } } } ] } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount } Sell { Seller Currency { Name Symbol SmartContract } Amount } } Transaction { Hash } } } } ```
## Get Latest Buys and Sells for a Meme Rush Token [This](https://ide.bitquery.io/Latest-buys-and-sells-for-a-meme-rush-coin-on-four-meme-dex) query retrieves the most recent token buy and sell trades of a specific Meme Rush token on Four Meme Exchange.
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc, dataset: combined) { buys: DEXTrades( where: { Trade: { Buy: { Currency: { SmartContract: { is: $currency } } } Success: true Dex: { ProtocolName: { is: "fourmeme_v1" } } } } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Amount Buyer Price PriceInUSD Seller } Sell { Currency { Name Symbol SmartContract } } } } sells: DEXTrades( where: { Trade: { Sell: { Currency: { SmartContract: { is: $currency } } } Success: true Dex: { ProtocolName: { is: "fourmeme_v1" } } } } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Currency { Name Symbol SmartContract } } Sell { Amount Buyer Price PriceInUSD Seller } } } } } ``` ```json { "currency": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } ```
You can also check if the token is listed on other DEX using this [example](/docs/blockchain/BSC/bsc-dextrades/#get-all-dexs-where-a-specific-token-is-listed). ## Get Trade Metrics of a Meme Rush Token Use the below query to get trade metrics like volume and trades for a token in different time frames, such as `24 hours`, `1 hour` and `5 minutes`. Test it [here](https://ide.bitquery.io/volume-and-trades-for-a-meme-rush-token-in-different-time-frames).
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } }, Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract } } volume_24hr: sum(of: Trade_Side_AmountInUSD) volume_1hr: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) trades_24hr: count trades_1hr: count( if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) trades_5min: count( if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) } } } ``` ```json { "currency": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } ```
## Get latest price of a Meme Rush token We launched the [Price Index](/docs/trading/crypto-price-api/) in August 2025, allowing you to track price of any token trading onchain. Here's an example of [tracking Meme Rush token prices](https://ide.bitquery.io/latest-meme-rush-token-price-on-four-meme-dex#).
Click to expand GraphQL query ```graphql { Trading { Pairs( where: {Price: {IsQuotedInUsd: false}, Market: {Network: {is: "Binance Smart Chain"}, Program: {is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b"}}, Token: {Address: {is: "0x44442202ff27ee2297c128d0c1ae43a0fbb35701"}}, Interval: {Time: {Duration: {eq: 60}}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { Market { Address Network Program Protocol ProtocolFamily } Price { Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } Ohlc { Close High Low Open } } Token { Address Name Symbol } QuoteToken { Address Name Symbol } Volume { Base Usd } } } } ```
## Get ATH price of a Meme Rush Token Fetches the All-Time High (ATH) price of a specific Meme Rush token on BSC, using the `DEXTradeByTokens` dataset to calculate the 98th percentile of trade prices (approximate ATH). Use a date filter suited to your needs — a shorter duration will make the query run faster and return results more efficiently. Try the API [here](https://ide.bitquery.io/meme-rush-token-ATH-price).
Click to expand GraphQL query ```graphql query tradingView( $network: evm_network $dataset: dataset_arg_enum $token: String ) { EVM(network: $network, dataset: $dataset) { DEXTradeByTokens( limit: { count: 1 } where: { Block: { Date: { since: "2025-10-10" } } TransactionStatus: { Success: true } Trade: { Side: { Currency: { SmartContract: { is: "0x" } } } Currency: { SmartContract: { is: $token } } Success: true } } ) { max: quantile(of: Trade_PriceInUSD, level: 0.98) Block { Time } } } } ``` ```json { "network": "bsc", "token": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701", "dataset": "combined", "local": "EVM", "interval": 60 } ```
## Get Price Change Percentage for a Meme Rush Token Use the below query to get the price change in percentage for various time fields including `24 hours`, `1 hour` and `5 minutes`. Try it [here](https://ide.bitquery.io/Percentage-price-change-for-a-meme-rush-token).
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } }, Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract } price_24hr: PriceInUSD(minimum: Block_Time) price_1hr: PriceInUSD( if: { Block: { Time: { is_relative: { hours_ago: 1 } } } } ) price_5min: PriceInUSD( if: { Block: { Time: { is_relative: { minutes_ago: 1 } } } } ) current: PriceInUSD } change_24hr: calculate( expression: "( $Trade_current - $Trade_price_24hr ) / $Trade_price_24hr * 100" ) change_1hr: calculate( expression: "( $Trade_current - $Trade_price_1hr ) / $Trade_price_1hr * 100" ) change_5min: calculate( expression: "( $Trade_current - $Trade_price_5min ) / $Trade_price_5min * 100" ) } } } ``` ```json { "currency": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } ```
## Get OHLCV data of a Meme Rush Token Use the below query to get meme rush token OHLCV data. Test it [here](https://ide.bitquery.io/OHLC-for-a-meme-rush-token).
Click to expand GraphQL query ```graphql query tradingView($network: evm_network, $token: String) { EVM(network: $network, dataset: combined) { DEXTradeByTokens( limit: { count: 10 } orderBy: { descendingByField: "Block_Time" } where: { Trade: { Currency: { SmartContract: { is: $token } } PriceAsymmetry: { lt: 0.1 } Dex: { ProtocolName: { is: "fourmeme_v1" } } } } ) { Block { Time(interval: { count: 5, in: minutes }) } Trade { open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) max: PriceInUSD(maximum: Trade_PriceInUSD) min: PriceInUSD(minimum: Trade_PriceInUSD) } volumeUSD: sum(of: Trade_Side_AmountInUSD, selectWhere: { gt: "0" }) } } } ``` ```json { "network": "bsc", "token": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } ```
## Monitor Meme Rush trades of traders on Four.Meme You can use our streams to monitor real time trades of a trader on Four Meme, for example run [this stream](https://ide.bitquery.io/monitor-meme-rush-token-trades-of-a-trader-on-four-meme_1).
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } }, Success: true } Transaction: { From: { is: "0x7db00d1f5b8855d40827f34bb17f95d31990306e" } } any: [ { Trade: { Buy: { Currency: { SmartContract: { startsWith: "0x4444" } } } } } { Trade: { Sell: { Currency: { SmartContract: { startsWith: "0x4444" } } } } } ] } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount Price PriceInUSD } Sell { Seller Currency { Name Symbol SmartContract } Amount } } Transaction { Hash } } } } ```
You can also get the trade activities of a user on Pancake Swap using our [Pancake Swap](/docs/blockchain/BSC/pancake-swap-api/) APIs. ## Track Meme Rush Tokens in 14k to 18k Marketcap Tracks live Meme Rush tokens on BSC with a market cap between $14K–$18K, filtered by 14k to 18k Marketcap. Useful for spotting emerging small-cap meme tokens in real time. Try the query [here](https://ide.bitquery.io/meme-rush-tokens-in-14K-to-17K-Marketcap).
Click to expand GraphQL query ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true Average: { Mean: { gt: 0.000014, le: 0.000018 } } } Market: { Protocol: { is: "fourmeme_v1" } Network: { is: "Binance Smart Chain" } } Volume: { Usd: { gt: 5 } } Token: { Address: { startsWith: "0x4444" } } } ) { Token { Name Symbol Address } Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } marketcap: calculate(expression: "$Price_Average_Mean * 1000000000") Price { Average { Mean } Ohlc { Close High Low Open } } } } } ```
## Top Buyers for a Meme Rush Token on Four Meme [This](https://ide.bitquery.io/Top-buyers-of-a-meme-rush-token) query returns top buyers of a particular Meme Rush token on Four Meme, with currency smart contract as `0x44442202ff27ee2297c128d0c1ae43a0fbb35701` for this example.
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc, dataset: combined) { DEXTrades( where: { Trade: { Buy: { Currency: { SmartContract: { is: $currency } } } Success: true Dex: { ProtocolName: { is: "fourmeme_v1" } } } } limit: { count: 100 } ) { Trade { Buy { Buyer } } trades: count bought: sum(of: Trade_Buy_Amount) } } } ``` ```json { "currency": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } ```
## Get Trade Volume and Number of Trades for a Meme Rush Token [This](https://ide.bitquery.io/volume-and-trades-for-a-token-in-different-time-frames_4) query returns the traded volume and number of trades for a particular Meme Rush token in different time frames, namely 24 hours, 1 hour and 5 minutes.
Click to expand GraphQL query ```graphql query MyQuery( $currency: String $time_24hr_ago: DateTime $time_1hr_ago: DateTime $time_5min_ago: DateTime ) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } }, Success: true } Block: { Time: { since: $time_24hr_ago } } } ) { Trade { Currency { Name Symbol SmartContract } } volume_24hr: sum(of: Trade_Side_AmountInUSD) volume_1hr: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since: $time_1hr_ago } } } ) volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since: $time_5min_ago } } } ) trades_24hr: count trades_1hr: count(if: { Block: { Time: { since: $time_1hr_ago } } }) trades_5min: count(if: { Block: { Time: { since: $time_5min_ago } } }) } } } ``` ```json { "currency": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701", "time_24hr_ago": "2025-10-23T15:00:00Z", "time_1hr_ago": "2025-10-24T14:00:00Z", "time_5min_ago": "2025-10-24T15:55:00Z" } ```
## Get Realtime Market Cap and Price of a Meme Rush Token To get the market cap of a token we need two things, the latest `PriceInUSD` and `total supply` of the token. Total Supply is 1,000,000,000 (1B) for four meme tokens so we just need to get price and multiply it with 1B. [This](https://ide.bitquery.io/Real-Time-Marektcap-and-price-of-a-meme-rush-token) query helps with getting the latest USD price of a token and hence its latest Marketcap. ``` Market Cap = Total Supply * PriceInUSD ```
Click to expand GraphQL query ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true } Market: { Protocol: { is: "fourmeme_v1" } Network: { is: "Binance Smart Chain" } } Volume: { Usd: { gt: 5 } } Token: { Address: { is: "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } } } ) { Token { Name Symbol Address } Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } marketcap: calculate(expression: "$Price_Average_Mean * 1000000000") Price { Average { Mean } Ohlc { Close High Low Open } } } } } ```
## Metadata for a Newly Created Meme Rush Token This query will fetch you trade metrics, such as marketcap, trade volume, token holders and creation time for a newly created Meme Rush token on BSC network.
Click to expand GraphQL query ```graphql query MyQuery($token: String!) { EVM(network: bsc, dataset: combined) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $token } } } } ) { Block { createdAt: Time(minimum: Block_Time) } volume: sum(of: Trade_Side_AmountInUSD) } Holders( date: "2026-09-30" where: { Currency: { SmartContract: { is: $token } } } ) { holders: uniq(of: Holder_Address) } } marketCap: Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Market: { Network: { is: "Binance Smart Chain" } } Volume: { Usd: { gt: 5 } } Token: { Address: { is: $token } } } orderBy: { descending: Interval_Time_Start } limit: { count: 1 } ) { Price { Average { Mean } } marketcap: calculate(expression: "Price_Average_Mean * 1000000000") } } } ``` ```json { "token": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } ```
## Top Traders of a Meme Rush token This query will fetch you top traders of a meme rush token for the BSC network. You can test the query [here](https://ide.bitquery.io/top-traders-of-a-meme-rush-token).
Click to expand GraphQL query ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network, dataset: combined) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}, Dex: {ProtocolName: {is: "fourmeme_v1"}}}} ) { Trade { Buyer Dex { OwnerAddress ProtocolFamily ProtocolName } } buyVolume: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sellVolume: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ```json { "network": "bsc", "token": "0x44442202ff27ee2297c128d0c1ae43a0fbb35701" } ```
## Get liquidity of a Meme Rush token Using below API you can get the liquidity of a meme rush token. Subtract `200000000` from the Balance that this query returns because 200M tokens are reserved which gets transferred to pancakeswap when this meme rush token graduates.
Click to expand GraphQL query ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { Balances( where: {Balance: {Address: {is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b"}}, Currency: {SmartContract: {is: "0x44442202ff27ee2297c128d0c1ae43a0fbb35701"}}} orderBy: { descending: Balance_Amount } ) { Currency { Name } Balance { Address Amount } } } } ```
--- ## BingX Exchange Hack Investigation Using MoneyFlow URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/bingx-exchange-hack/ Investigation video: tracing the funds drained from the BingX exchange hot wallets with Bitquery MoneyFlow. # BingX Exchange Hack Investigation Using MoneyFlow This investigation traces the funds drained from BingX hot wallets in September 2024, from the exchange addresses to the consolidation and swap addresses used by the attacker. --- ## Bitcoin API Documentation URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/ Bitcoin data: blocks, transactions, inputs and outputs, address balances, fees, Omni Layer USDT, Coinpath fund tracing and real-time feeds. # Bitcoin API Documentation ## Overview Bitquery's Bitcoin APIs cover the chain end-to-end through GraphQL — blocks, transactions, addresses, UTXO-level inputs and outputs, fees in BTC and USD, miner rewards, Omni Layer transactions (USDT-on-Bitcoin and other Omni tokens), and multi-hop fund flow tracing. Every query carries the historical USD value at the time of the transaction, which makes it easy to build wallet history feeds, tax / accounting tools, compliance dashboards, and mining analytics. If you need a data point that isn't covered here, reach out on [Telegram](https://t.me/Bloxy_info). :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. For real-time data, see the [Bitcoin Kafka stream](/docs/streams/protobuf/chains/Bitcoin-protobuf). ::: ### What you can do with the Bitcoin API - Pull blocks by height, hash, or time window with difficulty, size, and transaction counts. - Get transactions with input and output totals, fees in BTC and USD, and per-tx pagination. - Compute address balances from raw UTXOs — including balance at a historical block height. - List individual UTXOs received and spent by an address inside any date range. - Aggregate fees paid by an address or across the network for fee analytics. - Track miner activity, daily block rewards, and first-active timestamps for mining pools. - Query Omni Layer transactions and transfers (USDT on Bitcoin and other Omni tokens). - Trace inbound and outbound fund flows across multiple hops with Coinpath. ### How the Bitcoin API differs from running your own node | `bitcoind` / Bitcoin RPC | Bitquery Bitcoin API | | --- | --- | | Raw chain state — you build the indexer | Pre-indexed and parsed: blocks, txs, UTXOs, addresses, Omni Layer | | No historical analytics out of the box | History, joins, aggregations, USD conversion at trade time | | Re-scan the chain to compute balances | One query for current balance, balance at a height, or activity stats | | Best for submitting transactions and full validation | Best for analytics, dashboards, wallet UIs, compliance, and mining stats | ### Real-time Bitcoin data For live, low-latency Bitcoin data, use Bitquery's **[Bitcoin Kafka stream](/docs/streams/protobuf/chains/Bitcoin-protobuf)** (`btc.transactions.proto`). It delivers every block and transaction as soon as it lands on-chain, with full input/output detail, script and address parsing, and miner data. GraphQL subscriptions are not available for Bitcoin — Kafka is the real-time path. For polling or historical pulls, the GraphQL queries below work the same way you'd expect on any other Bitquery chain. ## Quick start This query returns the 5 most recent Bitcoin blocks with height, difficulty, transaction count, and timestamp. ```graphql { bitcoin(network: bitcoin) { blocks(options: {desc: "height", limit: 5}) { height difficulty transactionCount blockSizeBigInt timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } } } ``` ## API reference ### Core data - [Bitcoin Blocks API](/docs/blockchain/Bitcoin/bitcoin-blocks-api) — block lookups by height or time, difficulty, size, and transaction counts. - [Bitcoin Transactions API](/docs/blockchain/Bitcoin/bitcoin-transactions-api) — transaction-level data with fees, inputs/outputs totals, and pagination patterns. - [Bitcoin Inputs and Outputs API](/docs/blockchain/Bitcoin/bitcoin-inputs-outputs) — UTXO-level data, historical BTC price, balance at a block height, and miner rewards. ### Addresses and balances - [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api) — balances from UTXOs (current and at a height), `addressStats` aggregates, first/last-active. ### Fees - [Bitcoin Fee API](/docs/blockchain/Bitcoin/bitcoin-fee-api) — per-transaction and aggregate fee queries in BTC and USD. ### Omni Layer (USDT on Bitcoin) - [Bitcoin Omni Transactions & Transfers API](/docs/blockchain/Bitcoin/bitcoin-omni-transactions) — Omni transactions and per-address transfers for tokens like USDT-on-Bitcoin. ### Fund tracing - [Bitcoin Coinpath API](/docs/blockchain/Bitcoin/bitcoin-coinpath-api) — multi-hop fund flow tracing between Bitcoin addresses. ### Real-time - [Bitcoin Kafka stream](/docs/streams/protobuf/chains/Bitcoin-protobuf) — `btc.transactions.proto` topic for sub-block-time delivery. ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Bitcoin Address API - Get BTC Balance URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/bitcoin-address-api/ Bitcoin address balance from UTXOs or addressStats, balance at a block height, multi-address totals, first and last activity, and inputs and outputs by date. # Bitcoin Address API Bitcoin doesn't store account balances on-chain — there is no `getBalance` call. The reliable way to get an address balance is to sum every UTXO the address received (outputs) and subtract every UTXO it has spent (inputs). Bitquery indexes that UTXO data and pairs every value with the BTC/USD price at the time of the transaction, so you can pull current balances, historical balances at a specific block, or full activity timelines in a single request. :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get a Bitcoin address balance from UTXOs (recommended) Returns total BTC sent (inputs) and received (outputs) for an address, along with USD-equivalent values and first / last activity dates. Subtract `inputs.value` from `outputs.value` to get the current balance. ```graphql { bitcoin(network: bitcoin) { inputs( inputAddress: {is: "bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq"} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } outputs( outputAddress: {is: "bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq"} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } } } ``` ## Get a Bitcoin address balance via addressStats `addressStats` is a pre-aggregated view — fast, but it can lag the chain. Use it for quick lookups and dashboards; use the UTXO sum above when you need exact, up-to-the-block accuracy. [Run query](https://ide.bitquery.io/Bitcoin-balance_5). :::caution `addressStats` is pre-aggregated and may occasionally be out of date. For precise balance math, use the inputs / outputs query above. ::: ```graphql { bitcoin(network: bitcoin) { addressStats(address: {is: "bc1q6xra3s8c5c4vr8m5f9htkuc3neyn4zykv5seua"}) { address { balance inboundTransactions firstActive { time } address annotation outflows lastActive { time } uniqueSenders uniqueReceivers } } } } ``` ## Get a Bitcoin balance at a specific block height Need to know what a wallet held at a particular point in time? The `height` filter caps inputs and outputs at a given block number, which is exactly what you need for audits, tax reporting, and point-in-time portfolio snapshots. Balance at that height equals `outputs.value - inputs.value`. [Run query](https://ide.bitquery.io/bitcoin-balance-at-a-given-height). ```graphql { bitcoin(network: bitcoin) { inputs( inputAddress: {is: "bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq"} height: {lteq: 944000} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } outputs( outputAddress: {is: "bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq"} height: {lteq: 944000} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } } } ``` ## Aggregate balances for multiple Bitcoin addresses in one call Pass an array of addresses to `inputAddress` and `outputAddress` with `{in: [...]}` to get per-wallet totals in a single request. Useful for exchanges, custodians, and portfolio dashboards that monitor many wallets at once. [Run query](https://ide.bitquery.io/BTC-balance-API-for-multiple-addresses). ```graphql { bitcoin(network: bitcoin) { inputs( inputAddress: {in: ["bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq", "bc1p2gel5e7ny42epalps3vddqrwedqh8ca4v6fdjem3pa3930ltl90s2cfg6e"]} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) inputAddress { address } } outputs( outputAddress: {in: ["bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq", "bc1p2gel5e7ny42epalps3vddqrwedqh8ca4v6fdjem3pa3930ltl90s2cfg6e"]} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) outputAddress { address } } } } ``` ## Get a Bitcoin address's first and last active timestamps Quick way to find when a wallet first appeared on-chain and the last time it transacted. Useful for wallet age analysis, dormant-address screening, and compliance checks. :::caution `addressStats` is pre-aggregated and may occasionally be inaccurate. For precise timestamps, query inputs and outputs directly with `minimum(of: date)` and `maximum(of: date)`. ::: ```graphql query ($network: BitcoinNetwork!) { bitcoin(network: $network) { addressStats(address: {is: "ADDRESS_HERE"}) { address { firstActive { year month dayOfMonth } lastActive { year month dayOfMonth } } } } } ``` Replace `ADDRESS_HERE` with the Bitcoin address you want to inspect. ## List inputs and outputs for an address over a date range Returns every UTXO an address spent or received inside a time window, with block height, timestamp, transaction hash, output index, BTC value, and USD-equivalent. Use it for transaction reports, payment reconciliation, and per-period wallet activity feeds. [Run query](https://ide.bitquery.io/Input-and-outputs-of-a-bitcoin-address). ```graphql { bitcoin(network: bitcoin) { outputs( date: {since: "2024-03-19", till: "2024-03-26"} outputAddress: {is: "bc1p2gel5e7ny42epalps3vddqrwedqh8ca4v6fdjem3pa3930ltl90s2cfg6e"} options: {desc: ["block.height", "outputIndex"], limit: 10, offset: 0} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } transaction { hash } outputIndex outputDirection value value_usd: value(in: USD) } inputs( date: {since: "2024-03-19", till: "2024-03-26"} inputAddress: {is: "bc1p2gel5e7ny42epalps3vddqrwedqh8ca4v6fdjem3pa3930ltl90s2cfg6e"} options: {desc: ["block.height", "transaction.index"], limit: 10, offset: 0} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } outputTransaction { hash index } transaction { hash index } inputIndex value value_usd: value(in: USD) } } } ``` ## Video Tutorial | How to Look Up Any Bitcoin Address History? Balance, Payments, Fund Trace ## Video Tutorial | Can Bitcoin Be Traced? One Payment Followed Hop by Hop ## Related resources - [Bitcoin Inputs and Outputs API](/docs/blockchain/Bitcoin/bitcoin-inputs-outputs) — more UTXO patterns, miner rewards, and historical BTC price - [Bitcoin Transactions API](/docs/blockchain/Bitcoin/bitcoin-transactions-api) — per-tx detail and pagination - [Bitcoin Coinpath API](/docs/blockchain/Bitcoin/bitcoin-coinpath-api) — multi-hop fund tracing --- ## Bitcoin Blocks API URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/bitcoin-blocks-api/ Bitcoin blocks: get the 10 most recent blocks and find the busiest Bitcoin blocks by transaction count, with GraphQL queries you can run in the IDE. # Bitcoin Blocks API The Blocks API returns block-level data on Bitcoin: height, difficulty, size, transaction count, and timestamp. Use it to drive explorer front-ends, monitor chain progression, or pull historical block context for mining and network analytics. :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get the 10 most recent Bitcoin blocks Returns blocks ordered by height descending, with the timestamp formatted for display. Add a `date` filter to constrain the window. ```graphql query { bitcoin(network: bitcoin) { blocks(options: {desc: "height", limit: 10}, date: {after: "2023-10-10"}) { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } height difficulty transactionCount blockSizeBigInt } } } ``` Use `height: {is: N}` to look up a single block, or `height: {in: [N1, N2, ...]}` for several at once. The same query shape works on other UTXO networks supported here by swapping `network: bitcoin` for `litecoin`, `dogecoin`, and others. ## Find the busiest Bitcoin blocks by transaction count Sort blocks by `transactionCount` descending to surface the busiest blocks on-chain — useful for network congestion studies and block utilization analysis. ```graphql query { bitcoin(network: bitcoin) { blocks(options: {limit: 10, desc: "transactionCount"}) { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } difficulty maximum(of: transaction_count, get: transaction_count) transactionCount } } } ``` Swap the sort to `desc: "difficulty"` or `desc: "blockSizeBigInt"` for different angles. Add `date: {since: ..., till: ...}` to search inside a specific window, or use `average(of: transaction_count)` for average transactions per block. ## Related resources - [Bitcoin Transactions API](/docs/blockchain/Bitcoin/bitcoin-transactions-api) — per-block transaction details and fees - [Bitcoin Inputs and Outputs API](/docs/blockchain/Bitcoin/bitcoin-inputs-outputs) — UTXO data and miner rewards - [Bitcoin Kafka stream](/docs/streams/protobuf/chains/Bitcoin-protobuf) — real-time block and transaction delivery --- ## Bitcoin Coinpath API - Trace BTC Fund Flows Across Addresses URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/bitcoin-coinpath-api/ Bitcoin fund tracing with Coinpath: follow outbound and inbound BTC flows from an address and verify a path between two specific addresses. # Bitcoin Coinpath API Coinpath walks Bitcoin fund flows between addresses — forward to see where funds went, backward to see where they came from. Use it for AML investigations, source-of-funds verification, exchange deposit tracing, and mapping transaction paths across wallets. ## Video Tutorial | Investigate Bitcoin Address Fund flow Visually | Bitquery Coinpath API :::tip Trace Bitcoin funds with AI — no queries needed Connect the [Bitquery MCP server](https://mcp.bitquery.io/) to Claude, Cursor, or ChatGPT and ask in plain English: _"Trace where BTC from bc1q... went over the last 30 days, 3 hops deep, and flag any exchange deposits."_ The agent walks the fund flow for you. See [AI Investigations](https://bitquery.io/solutions/ai-investigations) and the [Tracing MCP guide](/docs/mcp/Tracing/overview). ::: :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Trace outbound fund flow from a Bitcoin address Returns direct recipients of an address with USD amounts, block heights, and transaction hashes. The `seed` option controls the starting point for repeated runs when you want consistent samples. [Run query](https://ide.bitquery.io/Destination-of-Funds-from-a-Specific-Address-on-Bitcoin). ```graphql { bitcoin(network: bitcoin) { coinpath( initialAddress: {is: "bc1p4kufll9uhnpkgzuc65slcxd2qaw2hl9xecket3h8yyu4awglcsqslqaztd"} date: {after: "2023-10-10"} options: {limit: 10, asc: "block.height", seed: 10} ) { amount(in: USD) block { height } sender { address } receiver { address } transaction { hash } currency { name address } } } } ``` For multi-hop tracing, add `depth: {lteq: N}` (typically 3–5; deeper for forensic work). Switch direction with `options: {direction: inbound}` to walk backward instead. ## Track all incoming fund paths to a Bitcoin address Use the `receiver` filter to see who sent BTC to a specific wallet. Returns sender addresses, USD amounts, and transaction hashes — the standard "who funded this wallet?" query. ```graphql query ($network: BitcoinNetwork!) { bitcoin(network: $network) { coinpath( date: {after: "2023-10-10"} options: {limit: 10, desc: "block.height"} receiver: {is: "bc1p4kufll9uhnpkgzuc65slcxd2qaw2hl9xecket3h8yyu4awglcsqslqaztd"} ) { amount(in: USD) block { height } sender { address } receiver { address } transaction { hash } } } } ``` Swap `receiver` for `sender` to trace outflows instead, or add `initialAddress` to find paths between two specific addresses. ## Verify a path between two specific Bitcoin addresses Combine `initialAddress` and `receiver` to check whether BTC moved from address A to address B — useful for chain-of-custody verification and direct flow auditing. ```graphql query ($network: BitcoinNetwork!) { bitcoin(network: $network) { coinpath( date: {after: "2023-10-10"} options: {limit: 10, desc: "block.height"} receiver: {is: "bc1p4kufll9uhnpkgzuc65slcxd2qaw2hl9xecket3h8yyu4awglcsqslqaztd"} initialAddress: {is: "bc1pu349c0fvmqnv5s0aj3aracrsvn696hzhuyyukn6r5c9h03y88plql53h5h"} ) { amount(in: USD) block { height } sender { address } receiver { address } transaction { hash } } } } ``` Raise `limit` for more rows and add `depth: {lteq: N}` to follow multi-hop paths between the two addresses. ## Related resources - [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api) — balances and activity stats - [Bitcoin Inputs and Outputs API](/docs/blockchain/Bitcoin/bitcoin-inputs-outputs) — UTXO-level inflows and outflows - [Bitcoin Transactions API](/docs/blockchain/Bitcoin/bitcoin-transactions-api) — per-tx detail --- ## Bitcoin Data - Snowflake, AWS S3, GCP BigQuery URL: https://docs.bitquery.io/docs/cloud/bitcoin/ Bitcoin blocks, transactions, inputs, outputs and Omni Layer data as Parquet files, with a free sample, the file layout and DuckDB and Python examples. # Bitcoin Data Bitquery provides **Bitcoin blockchain data** as **Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), designed for large-scale analytics, historical backfills, and data lake integrations. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, etc**. ## How do I get Bitcoin address balance history block by block? Bitcoin is **UTXO-based**, not account-based: an “address balance” at height *H* is the sum of **unspent outputs** paying that address with **block height ≤ H**. In Bitquery’s **Bitcoin Parquet dumps**, join **outputs** to **inputs** to mark spends, aggregate per address per block (or use your warehouse’s window functions). For interactive GraphQL wallet history, see **[V1 Bitcoin documentation](https://docs.bitquery.io/v1/docs/Examples/bitcoin/bitcoin-address-api)** if your use case is supported there. ## Available Bitcoin Topics For Bitcoin, Bitquery currently provides the following datasets: - **Blocks** – Block-level metadata - **Transactions** – Full transaction-level data - **Inputs** – Transaction input data - **Outputs** – Transaction output data - **OMNI Transactions** – OMNI Layer protocol transactions - **OMNI Transfers** – OMNI Layer token transfers ## Sample Bitcoin Cloud Dataset You can explore schemas and validate your tooling using the **public Bitcoin sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/bitcoin](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/bitcoin) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bitcoin/blocks/.parquet ``` ## Bitcoin Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── bitcoin/ ├── blocks/ │ ├── _.parquet │ ├── _.parquet │ └── ... ├── transactions/ │ ├── _.parquet │ └── ... ├── inputs/ │ ├── _.parquet │ └── ... ├── outputs/ │ ├── _.parquet │ └── ... ├── omni_transactions/ │ ├── _.parquet │ └── ... └── omni_transfers/ ├── _.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Example: ``` 932100_932149.parquet ``` ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets?network=bitcoin) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). Datasets you can buy on the Data Store: - [Bitcoin](https://bitquery.io/datastore/datasets/bitcoin) — blocks, transactions, inputs, outputs and Omni Layer data since genesis This listing is not the full catalogue. Other topics, chains and date ranges are available on request from **sales@bitquery.io**. ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bitcoin/transactions/932100_932149.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bitcoin/blocks/932100_932149.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access Data Store exports are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming Bitcoin data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - **GraphQL subscriptions** --- ## Bitcoin Fee API URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/bitcoin-fee-api/ Bitcoin Fee API: analyze Bitcoin transaction fees and costs with Bitquery GraphQL queries and streams. Great for bots, dashboards, and alerts. # Bitcoin Fee API Query Bitcoin transaction fees at the per-transaction level or aggregated across an address or time window — in BTC and USD. Use it for fee estimation, wallet expense tracking, and historical fee trend analysis. :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## List Bitcoin transactions with per-tx fees in BTC and USD Pulls transactions for a specific address on a given day with per-transaction fee amounts (BTC and USD), input/output values, and counts. [Run query](https://ide.bitquery.io/bitcoin-trxn-fees-for-a-account_2). ```graphql query MyQuery { bitcoin(network: bitcoin) { transactions( options: {limit: 10, desc: ["block.height"]} date: {is: "2025-05-08"} inputAddress: {is: "bc1qrtjvr4d8qtstw5334mspp7rmrzl55uj3dcwj09"} ) { block { timestamp { iso8601 } height } feeValue feeInUSD: feeValue(in: USD) feeValueDecimal hash index inputValue inputCountBigInt inputCount outputValueDecimal outputValue outputCountBigInt outputCount inputValueDecimal } } } ``` Drop the `inputAddress` filter to see fees across all transactions, add `date: {since: ..., till: ...}` for a window, or sort by `feeValue` to surface the highest-fee transactions first. ## Sum total Bitcoin fees paid by an address on a single day Aggregate total fees paid by an address with `feeValue(calculate: sum)` in both BTC and USD. [Run query](https://ide.bitquery.io/Get-Total-fees-paid-by-an-account-on-Bitcoin-network). ```graphql query MyQuery { bitcoin(network: bitcoin) { transactions( date: {is: "2025-05-08"} inputAddress: {is: "bc1qrtjvr4d8qtstw5334mspp7rmrzl55uj3dcwj09"} ) { total_fees_in_usd: feeValue(calculate: sum, in: USD) total_fees: feeValue(calculate: sum) } } } ``` Change `date` to a range for multi-day totals, drop `inputAddress` for a network-wide aggregate, or add `feeValue(calculate: average)` for average fee per transaction. ## Video tutorial: getting Bitcoin transaction fee data ## Related resources - [Bitcoin Transactions API](/docs/blockchain/Bitcoin/bitcoin-transactions-api) — full transaction query patterns - [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api) — address balances and activity - [Bitcoin Inputs and Outputs API](/docs/blockchain/Bitcoin/bitcoin-inputs-outputs) — UTXO-level detail --- ## Bitcoin Inputs Outputs URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/bitcoin-inputs-outputs/ Bitcoin inputs and outputs: BTC price on a date, balance at a block height, UTXO inputs and outputs for an address, daily miner rewards and miner activity. # Bitcoin Inputs and Outputs API Bitcoin runs on an unspent-transaction-output (UTXO) model — every transaction consumes previous outputs (inputs) and creates new ones (outputs). These APIs give you direct access to that UTXO data with BTC and USD values, block context, transaction hashes, and per-address filtering. They're the foundation for balance reconstruction, miner reward tracking, historical price lookups, and detailed wallet activity feeds. :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get the BTC price on a given date Pulls the BTC/USD price implied by any output on a given date — Bitquery stores the spot value at the time of each transaction, so you can derive a historical price by dividing USD value by BTC value. [Run query](https://ide.bitquery.io/btc-price-in-2016). ```graphql query MyQuery { bitcoin { outputs(date: {is: "2016-01-01"}) { value usd: value(in: USD) expression(get: "usd/value") } } } ``` ## Get a Bitcoin balance at a specific block height Sum outputs and subtract inputs with a `height: {lteq: N}` cap to get the wallet's balance at a specific point on-chain. Useful for audits, tax snapshots, and point-in-time portfolio reporting. [Run query](https://ide.bitquery.io/bitcoin-balance-on-a-given-block-height). ```graphql { bitcoin(network: bitcoin) { inputs( height: {lteq: 919195} inputAddress: {is: "bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq"} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } outputs( height: {lteq: 919195} outputAddress: {is: "bc1ppu6akjngyvpxwz0w38n4evcygwh08tjtmcc0dx6ft2zzgkxtd97stwehcq"} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } } } ``` ## List UTXO inputs and outputs for an address inside a block range Returns spent and received UTXOs for a specific address between two block heights, with date, transaction hash, block height, address annotation, and value. [Run query](https://ide.bitquery.io/bitcoin-inputs-and-outputs-for-address). ```graphql { bitcoin(network: bitcoin) { spendvolumes: inputs( inputAddress: {is: "bc1p4kufll9uhnpkgzuc65slcxd2qaw2hl9xecket3h8yyu4awglcsqslqaztd"} height: {between: [822372, 822376]} ) { date { date } any(of: amount) block { height } transaction { hash } inputAddress { annotation address } value } recievevolumes: outputs( height: {between: [822372, 822376]} outputAddress: {is: "bc1p4kufll9uhnpkgzuc65slcxd2qaw2hl9xecket3h8yyu4awglcsqslqaztd"} ) { date { date } any(of: amount) transaction { hash } block { height } outputAddress { annotation address } value } } } ``` The same shape works with `date: {since: ..., till: ...}` instead of `height: {between: [...]}` when you want to filter by time rather than block range. ## Get daily miner block rewards on Bitcoin Mining rewards live in coinbase outputs (the first transaction in every block, `txIndex: 0`) with `outputDirection: mining`. This query returns daily reward totals per miner address along with the number of unique blocks they mined — the standard view for tracking mining pool activity and reward distribution. [Run query](https://ide.bitquery.io/bitcoin-miners-rewards). ```graphql query ($network: BitcoinNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) { bitcoin(network: $network) { outputs( options: {asc: "date.date"} date: {since: $from, till: $till} txIndex: {is: 0} outputDirection: {is: mining} outputScriptType: {notIn: ["nulldata", "nonstandard"]} ) { address: outputAddress { address annotation } date { date(format: $dateFormat) } reward: value count(uniq: blocks) } } } ``` ## Count miner activity in a time window Pulls the activity count per miner address inside a date range. Drop or extend the date window to size the cohort however you need. [Run query](https://ide.bitquery.io/get-miners-activity-in-a-specific-timeframe). ```graphql query MyQuery { bitcoin(network: bitcoin) { outputs( outputDirection: {is: mining} date: {since: "2025-01-01", till: "2025-01-10"} outputScriptType: {notIn: ["nulldata", "nonstandard"]} ) { outputAddress { address } count } } } ``` ## Find a miner's first mining activity For a specific set of miner addresses, this query returns the first block each one mined. Useful for cohort analysis, miner onboarding studies, or building "first seen" timelines. [Run query](https://ide.bitquery.io/get-miners-first-activity). ```graphql query MyQuery { bitcoin(network: bitcoin) { outputs( outputDirection: {is: mining} options: {asc: "block.timestamp.iso8601", limitBy: {each: "outputAddress.address", limit: 1}} outputAddress: {in: ["1K6KoYC69NnafWJ7YgtrpwJxBLiijWqwa6", "1KGG9kvV5zXiqyQAMfY32sGt9eFLMmgpgX"]} outputScriptType: {notIn: ["nulldata", "nonstandard"]} ) { outputAddress { address } block { timestamp { iso8601 } } } } } ``` ## Video tutorial: daily miner rewards ## Related resources - [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api) — balances and activity stats per address - [Bitcoin Coinpath API](/docs/blockchain/Bitcoin/bitcoin-coinpath-api) — multi-hop fund flow tracing - [Bitcoin Transactions API](/docs/blockchain/Bitcoin/bitcoin-transactions-api) — transaction-level totals and fees - [Bitcoin Kafka stream](/docs/streams/protobuf/chains/Bitcoin-protobuf) — real-time UTXO delivery --- ## Bitcoin Kafka Protobuf Streams URL: https://docs.bitquery.io/docs/streams/protobuf/chains/Bitcoin-protobuf/ Bitcoin Streams with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. See examples in the Bitquery IDE. # Bitcoin Streams This section provides details about Bitquery's Bitcoin Streams via Kafka. The top-level Kafka section explains how we use Kafka Streams to deliver data. You can find the schema [here](https://github.com/bitquery/streaming_protobuf/tree/main/utxo). Remember that Bitcoin blocks are produced with an average gap of 10 minutes per block. ## Topic Details - `btc.transactions.proto` : streams all transactions details described below. - **Data Sample of Transaction Data**: You can view a sample of the Bitcoin stream data [here](https://github.com/bitquery/kafka-data-sample/blob/main/utxo/btc_transactions.json). ## Structure of On-Chain Data ### Block-Level Data Each block in the stream includes a `Header` with fields such as `Hash`, `Height`, `Time`, `MerkleRoot`, `Nonce`, and `Bits`. These fields correspond directly to the components of a standard Bitcoin block header. ### Transaction-Level Data Transactions are represented with their own `Header`, `Inputs`, and `Outputs`. - **Inputs** reference previous transaction outputs (UTXOs). - **Outputs** specify recipient addresses and amounts. ### Script and Address Details The stream provides detailed script information, including `ScriptPubKey` and `ScriptSig`, along with address representations. The meaning of these opcodes can be found in the official [Bitcoin Developer Documentation](https://developer.bitcoin.org/reference/transactions.html#opcodes). ### Using This Stream in Python, JavaScript, and Go The same Python, JavaScript, and Go code samples can be used with this stream by simply changing the topic to `btc.transactions.proto` and using the `ParsedBlockMessage` schema, which can be found in the [Parsed Block Message Schema](https://github.com/bitquery/streaming_protobuf/blob/main/utxo/parsed_block_message.proto). The Python package [bitquery-pb2-kafka-package](https://pypi.org/project/bitquery-pb2-kafka-package/) includes all schema and is up to date so you don't have to manually install schema files. --- ## Bitcoin Omni Transactions URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/bitcoin-omni-transactions/ Bitcoin Omni Layer data: query the latest Omni transactions on Bitcoin and list Omni transfers for a specific address, with GraphQL examples to run in the IDE. # Bitcoin Omni Layer API The Omni Layer is a protocol built on top of Bitcoin for issuing and trading custom tokens — most famously the original Bitcoin-issued USDT. These APIs return Omni-specific transaction and transfer data so you can track issuance, redemptions, and per-address Omni token activity directly on the Bitcoin chain. :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get the latest Omni transactions on Bitcoin Returns the 10 most recent Omni Layer transactions with block height, timestamp, fee in USD, transaction hash, and sender address — ordered by block height descending. ```graphql query ($network: BitcoinNetwork!) { bitcoin(network: $network) { omniTransactions( options: {desc: "block.height", limit: 10} date: {after: "2023-11-20"} ) { block { height } blockHash date { date } feeValue(in: USD) hash index txSender } } } ``` Filter by sender with `txSender: {is: "..."}`, narrow with a different `date` window, or add `limit` / `offset` for pagination. ## List Omni transfers for a specific address Returns every Omni token transfer originating from a given Bitcoin address — block hash, sender (`transferFrom`), and receiver (`transferTo`). Replace `ADDRESS_HERE` with the wallet you want to inspect. ```graphql query ($network: BitcoinNetwork!) { bitcoin(network: $network) { omniTransfers(options: {desc: "block.height"}, txSender: {is: "ADDRESS_HERE"}) { block { height } blockHash transferFrom transferTo } } } ``` Filter incoming transfers with `transferTo: {is: "..."}` instead, add a `date` window to scope a period, or extend the query with currency / amount fields to identify which Omni token moved. ## Related resources - [Bitcoin Transactions API](/docs/blockchain/Bitcoin/bitcoin-transactions-api) — base-layer Bitcoin transactions - [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api) — address balances and activity - [Bitcoin Coinpath API](/docs/blockchain/Bitcoin/bitcoin-coinpath-api) — multi-hop BTC fund tracing --- ## Bitcoin Transactions API URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/bitcoin-transactions-api/ Bitcoin transactions: latest transactions with fees and transfer values, daily transaction count and average fee, and transactions sent from an address. # Bitcoin Transactions API The Transactions API returns transaction-level data on Bitcoin: input and output totals in BTC and USD, fees, input/output counts, block context, and per-address transaction history. Use it for paginated transaction feeds, daily activity dashboards, fee trend analysis, and wallet history widgets. :::info Endpoint Bitcoin GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get the latest Bitcoin transactions with fees and transfer values A reusable query that takes `limit`, `offset`, and a date range as variables. Returns input value (BTC and USD), output count, input count, fees (BTC and USD), and block context — the standard shape for paginated transaction feeds. ```graphql query ($network: BitcoinNetwork!, $limit: Int!, $offset: Int!, $from: ISO8601DateTime, $till: ISO8601DateTime) { bitcoin(network: $network) { transactions( options: {desc: ["block.height", "index"], limit: $limit, offset: $offset} time: {since: $from, till: $till} ) { block { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } height } inputValue input_value_usd: inputValue(in: USD) outputCount inputCount index hash feeValue fee_value_usd: feeValue(in: USD) } } } ``` Adjust `limit` and `offset` for pagination, narrow with `inputAddress` or `outputAddress` for a single wallet, or add `hash: {is: "..."}` for a single-transaction lookup. ## Daily Bitcoin transaction count and average fee Aggregate transactions by day to track network throughput and fee trends over time. Returns one row per day with the total transaction count, total fees, and average fee per transaction. ```graphql query ($network: BitcoinNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) { bitcoin(network: $network) { transactions(options: {asc: "date.date"}, date: {since: $from, till: $till}) { date: date { date(format: $dateFormat) } count: countBigInt feeValue avgFee: feeValue(calculate: average) } } } ``` Use `feeValue(calculate: median)` for median fees, or add `count(uniq: addresses)` to get daily active address counts alongside the fee stats. ## List Bitcoin transactions sent from a specific address Returns every transaction where a given address appears on the input side — the standard query for an outbound wallet history. ```graphql query ($network: BitcoinNetwork!) { bitcoin(network: $network) { transactions( options: {desc: ["block.height"]} inputAddress: {is: "bc1p4kufll9uhnpkgzuc65slcxd2qaw2hl9xecket3h8yyu4awglcsqslqaztd"} ) { block { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } height } inputValue hash feeValue outputValue } } } ``` Swap `inputAddress` for `outputAddress` to see received transactions instead. Add `date` for a window, `limit` / `offset` for pagination, and `inputValue(in: USD)` / `outputValue(in: USD)` for USD-equivalent amounts. ## Related resources - [Bitcoin Blocks API](/docs/blockchain/Bitcoin/bitcoin-blocks-api) — block-level lookups and stats - [Bitcoin Inputs and Outputs API](/docs/blockchain/Bitcoin/bitcoin-inputs-outputs) — UTXO-level transaction detail - [Bitcoin Fee API](/docs/blockchain/Bitcoin/bitcoin-fee-api) — focused fee queries and aggregates - [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api) — wallet balances and activity stats --- ## Bitquery API Common Errors URL: https://docs.bitquery.io/docs/start/errors/ Bitquery API Common Errors: practical Bitquery setup guidance with examples for authentication, endpoints, and first queries. # Common Errors and What to Do This section will guide you through the interpretation of common error messages encountered within Bitquery APIs. It will help you decide when to escalate issues by filing a ticket at [Bitquery Support](https://support.bitquery.io/). ## Why am I getting a 403 Forbidden error when making a GraphQL request in Python? {#why-am-i-getting-a-403-forbidden-error-when-making-a-graphql-request-in-python} For **API v2**, Bitquery expects a valid **OAuth token** on the right host: send `Authorization: Bearer ` to **`https://streaming.bitquery.io/graphql`** (see [how to use a token](/docs/authorization/how-to-use/)). A **403** often means the gateway rejected the request—wrong URL, missing/expired token, or headers not passed exactly as in the Python example. For **legacy v1** (`graphql.bitquery.io`), check **IP allowlists and referrers** in your [account dashboard](/docs/ide/account/). If it still fails, open a ticket with the response body and request URL (redact secrets). ### ClickHouse Error: 400 Bad Request #### Error Message: ```plaintext clickhouse return status 400 [400 Bad request] response

400 Bad request

\nYour browser sent an invalid request.\n\n" ``` #### Probable Cause: This error typically arises due to incorrect query construction involving limits, sorting, or filtering parameters. #### Resolution Steps: - **Review Query Parameters:** Ensure that the query adheres to the specified limits, sorting criteria, and filters as required in a standard [query](/docs/start/first-query/). - **Validate Syntax:** Double-check the syntax of the query to identify any mistakes or discrepancies. - **Consult Documentation:** Refer to Bitquery documentation for similar examples. - **Escalation:** If the issue persists or requires further assistance, consider filing a detailed ticket on [Bitquery Support](https://support.bitquery.io/) for help and resolution. --- ### Too Many Sessions: 429 Error #### Error Message: "Too Many Sessions: 429" #### Probable Cause: This error occurs when you exceed certain limits set by ClickHouse or the Bitquery API. These limits may include: - **Rate Limit**: The maximum number of queries allowed per minute (the exact value depends on your plan — see [Rate Limits & Concurrency](/docs/plans/rate-limits/)). - **Session Limit**: The maximum number of active sessions allowed at any given time. - **Streams Limit**: The maximum number of streams you can open simultaneously. #### Resolution Steps: If the error persists or you believe it is occurring in error, contact the support team for further assistance. --- ### Empty Response Returned {#empty-response-returned} If no trades/transfers are found for the queried period, compare with public explorers. Verify **network**, **dataset** (`realtime` vs `combined` / `archive`), **time filters**, and **contract or mint addresses**. If issues persist, contact support through the public Telegram group. ### Error in Name, Error in Symbol on Explorer ![symbol](/img/ide/symbol_error.png) This is an issue with indexing the token, please create a ticket at [support.bitquery.io](https://support.bitquery.io/hc/en-us) ### ActiveRecordError : Memory Exceeded #### Error Message: "message": "ActiveRecord::ActiveRecordError: Response code: 500:\nCode: 241, e.displayText() = DB::Exception: Received from ..... DB::Exception: Memory limit (for query) exceeded: would use 29.87 GiB (attempt to allocate chunk of 134740784 bytes), maximum: 29.80 GiB: .... #### Resolution Steps: This error occurs due to excessive data retrieved in a single query. Limit results using 'limit' option or narrow the query range using 'since' and 'till' on `time` field. Read more on limits [here](/docs/graphql/limits) and on filters [here](/docs/graphql/filters). ### Too many simultaneous queries This happens when you hit the number of requests for your plan. Please contact the support team. Contact support via Telegram for assistance. ### Error Status 500 #### Probable Cause: The error with status 500 is a generic internal server error that could result from various issues within the system. #### Resolution Steps: - **Review Query and Syntax:** Double-check the query and its syntax for any errors or discrepancies. - **Check Server Status:** Verify the [server status](https://app-status.bitquery.io/) to ensure it is operational and not experiencing downtime. - **Escalation:** Contact support on the [telegram channel](https://t.me/Bloxy_info). ### ActiveRecord::ActiveRecordError: Response code: 500 DB::Exception: Too many simultaneous queries If you see this text `DB::Exception: Too many simultaneous queries`, this happens when you hit the number of requests for your plan. Please contact the support team. ### DB::Exception : Memory limit (total) exceeded `"message":"ActiveRecord::ActiveRecordError: Response code: 500:\nCode: 241, e.displayText() = DB::Exception: Memory limit (total) exceeded: would use 78.01 GiB (attempt to allocate chunk of 134658600 bytes), maximum: 78.01 GiB: ...` This error occurs when a query lacks a limit or requests an excessive number of records. To resolve it, consider adding filters to refine the query parameters. If issue still persists, please contact the support team on telegram with your query. ### Timeout TCP socket {#timeout-tcp-socket} \[\{"message":"Net::ReadTimeout ..."\}\] This error occurs when the query is complex and takes too long to respond to a request. Check if you can optimize the query, if not please contact the support team on telegram with your query. **Points:** If your client times out, Bitquery may still have **started work** on the server; see [Why does a Net::ReadTimeout error consume my API credits?](/docs/ide/points/#why-does-net-readtimeout-consume-api-credits) on the Points page. ### Error: Failed to fetch ERROR http 424 Please retry the query in a few minutes, this is a temporary issue. If repeats please create a ticket at [support.bitquery.io](https://support.bitquery.io/hc/en-us) --- ### WebSocket Errors: 1009, Message Too Big, PayloadTooBig, etc. #### Probable Cause: These errors typically occur due to how the WebSocket client is configured in `websockets.client.connect()`. In Python, the default maximum size for incoming messages is set to `2**20` (1048576 bytes). When this limit is exceeded, errors like `1009`, `message too big`, or `PayloadTooBig` may occur. #### Resolution Steps: - **Adjust WebSocket Client Settings:** You can either pass `None` to disable the limit or increase the default value to accommodate larger payloads. `websockets.client.WebSocketClientProtocol(_*_, _origin=None_, _extensions=None_, _subprotocols=None_, _extra_headers=None_, _**kwargs_)` - **Memory Usage Consideration:** Since Python can use up to 4 bytes of memory to represent a single character, each connection may use up to `4 * max_size * max_queue` bytes of memory to store incoming messages. By default, this can amount to 128 MiB. Depending on your application’s requirements, you may want to lower these limits to optimize performance. Read more [here](https://websockets.readthedocs.io/en/9.1/api/client.html#using-a-connection_ --- ## Billing, quota & access errors These are the most common runtime errors and their fixes. Each heading is the literal error string so you can search for it. ### `No active billing period` (HTTP 402) {#no-active-billing-period} A `402` with **`No active billing period`** (or `access restricted by points limit`) means the account has no active plan/points for this request. Common causes: - Your 7-day trial expired, or no plan is active yet. - A payment is still provisioning (there can be a short delay after paying). - You're calling a **paid-only interface** (for example gRPC/Kafka) your plan doesn't include. **Fix:** confirm an active plan at [Account → Billing](https://account.bitquery.io/user/upgrade); see [How Billing Works](/docs/plans/how-billing-works/). If you just paid, wait a few minutes and retry. ### `points limit exceeded: usage quota reached` {#points-limit-exceeded} You've consumed your point allowance for the period, **or** you're using a token minted under a previous (smaller) plan. **Fix:** top up / upgrade at [Account → Billing](https://account.bitquery.io/user/upgrade). **If you just upgraded and still see this, generate a new access token** — a token created under the old plan can keep enforcing the old limit. See [How Billing Works](/docs/plans/how-billing-works/). ### `too many concurrent subscriptions` / `exceeded the maximum number of subscriptions per user id` {#too-many-concurrent-subscriptions} You've hit your plan's concurrent-subscription cap. Two gotchas: - Over the cap, a subscription may **connect but deliver no data** instead of erroring clearly. - **Revoking a token does not stop already-open sockets.** **Fix:** view and terminate running subscriptions at [Account → Subscriptions](https://account.bitquery.io/user/api_v2/subscriptions). See [WebSocket subscriptions](/docs/subscriptions/websockets/) and [Rate Limits & Concurrency](/docs/plans/rate-limits/). ### `no table can query ... consider use realtime dataset` / `Missing columns` {#dataset-not-available} The cube isn't deployed on the **dataset** you selected for that **chain** (for example, `combined` Holders on a chain that only has `realtime` Holders), or a column doesn't exist on that chain. **Fix:** switch dataset (often to `realtime`), or choose a chain/cube combination that exists. See the [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/). ### `response too large to compose; split this into separate single-network queries` {#response-too-large-to-compose} The server builds one response for the whole request. When one request holds many aliased cubes (`a0: Trading { ... } a1: Trading { ... } ...`) that each ask for thousands of rows, or mixes several networks, the combined response is too big to build and the whole request fails, even though each part would run on its own. **Fix:** send one cube per request, for one network, and keep `limit` to the rows you need. Page through larger results with `offset` or by moving the `Block.Time` window. For example, the trades of one Solana liquidity pool over a short time window: [Run this query in the IDE](https://ide.bitquery.io/trading-trades-of-one-solana-liquidity-pool-in-a-time-window) ```graphql query { Trading { Trades( limit: { count: 100 } orderBy: { descending: Block_Time } where: { Pair: { Market: { Network: { is: "Solana" } Address: { is: "58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2" } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time } Price PriceInUsd Side Pair { Token { Address Symbol } QuoteToken { Address Symbol } } } } } ``` Run one request like this per liquidity pool and time window instead of putting them all under aliases in one request. If you need data from several networks, send one request per network. ### `Table doesn't exist` (v1) {#v1-table-does-not-exist} A v1 query is hitting a table retired during the v1 → v2 migration. Move the query to the v2 endpoint and schema — see [Getting started](/docs/start/first-query/). ### gRPC `16 UNAUTHENTICATED` vs `7 PERMISSION_DENIED` {#grpc-auth-errors} - **`16 UNAUTHENTICATED`** — the credential is missing, malformed, or expired. Regenerate and re-send it. - **`7 PERMISSION_DENIED`** — the credential is valid but not entitled (wrong plan, rate-limited, or no active billing period). See [Solana gRPC](/docs/grpc/solana/introduction/). ### Kafka authentication / connection failures {#kafka-auth-errors} If your Kafka client can't authenticate or reach the brokers, check the connection recipe: port 9092, `SASL_PLAINTEXT` with your Kafka username/password (SASL/PLAIN), and no client TLS certs. See the [Kafka Operations Cookbook](/docs/streams/kafka-operations/). ### Empty results despite data existing — full checklist {#empty-results-checklist} 1. **Dataset/retention** — is the date range within the window for that cube? See the [coverage matrix](/docs/graphql/data-coverage-retention/). 2. **EVM address case** — filters with `is:` are case-sensitive; lowercase the address or use `caseInsensitive`. 3. **Ordering pitfall** — ordering by a non-indexed timestamp field can silently drop rows; order by `Block_Time` instead. 4. **Filters** — verify network, DEX/program, and token/mint address against an explorer. --- ## Limits ### Default Limit By default, if you do not specify a limit in your query, there is an implicit limit applied. This default limit restricts the number of records returned to 10,000. This is a safeguard to prevent excessive resource usage and to ensure that queries are processed efficiently. ### Setting Custom Limits To specify a custom limit in your query, you can use the `limit` parameter. This parameter allows you to define the maximum number of records you want to retrieve. When you set a custom limit, the query will return the specified number of records based on your criteria. ### Example Query Here's an example query demonstrating the use of the `limit` parameter: ```graphql { EVM(network: eth) { Blocks( limit: { count: 30000 } orderBy: { descending: Block_Time } where: { Block: { Date: { after: "2023-01-03" } } } ) { Block { Number Date } } } } ``` ### Important Notes - **Resource Consideration**: Be cautious when setting high limits, as large queries might consume significant resources and impact performance. - **Pagination**: For large datasets, consider implementing pagination with `offset` to retrieve data in smaller chunks for better efficiency. Read more on limits and offsets [here](/docs/graphql/limits) - **Optimization**: Always aim to optimize your queries to retrieve the necessary data efficiently without exceeding resource limits. ## Why am I getting a 500 error — query is taking too long? {#why-am-i-getting-a-500-error-query-is-taking-too-long} A **500** from Bitquery is often tied to **query cost**: the engine may hit **memory limits**, **timeouts**, or **too many simultaneous queries** for your plan. Narrow **time range**, add **`limit`**, filter on **indexed fields**, and avoid huge scans—see [limits](/docs/graphql/limits/), [filters](/docs/graphql/filters/), and [indexed fields](/docs/graphql/indexed-fields-reference/). Check [Bitquery status](https://app-status.bitquery.io/). If the query is minimal and 500s persist, contact [support](https://support.bitquery.io/) or [Telegram](https://t.me/Bloxy_info) with the operation text. ## Why does my DEX trade query return zero results even though trades happened today? {#why-does-my-dex-trade-query-return-zero-results-even-though-trades-happened-today} **Dataset and time window** are the usual cause: **`dataset: realtime`** only covers a **rolling recent window** (hours—not full history), while **`combined`** / **`archive`** backfill older blocks. Wrong **DEX/program filter**, **pair or token address**, or **network** also returns empty rows. Confirm the same trade in an explorer, then align **`Block.Time`** / **`since`** with the dataset you chose. Solana-specific field gaps on **`combined`** are covered [here](/docs/graphql/dataset/combined#why-does-dataset-combined-return-fewer-fields-than-dataset-realtime-on-solana). See also [Empty Response Returned](#empty-response-returned) below. ## Why does the ISO8601DateTime vs ISO8601Date type mismatch error occur? {#why-does-the-iso8601datetime-vs-iso8601date-type-mismatch-error-occur} GraphQL is strict about **variable types**. If a filter expects a **date only**, declare the variable as **`ISO8601Date`** and pass values like **`2024-01-15`**. If it expects a **full timestamp**, use **`ISO8601DateTime`** and pass **`2024-01-15T12:00:00Z`**. Mismatch triggers a schema validation error before the query runs. Match each argument to the type shown in the IDE schema for that field, and keep **time zones** explicit (`Z` or offset). --- ## Bitquery API Documentation - Blockchain Data Platform URL: https://docs.bitquery.io/docs/intro/ Start here for Bitquery's blockchain data platform: GraphQL query and WebSocket subscription APIs, the IDE, Kafka streams and cloud data delivery. # Overview Bitquery 's infrastructure provides you access to historical and real-time blockchain data through four routes: the GraphQL API, streams (WebSocket, Kafka, and gRPC on Solana), Parquet exports from the Bitquery Data Store, and the raw Blockchain Data Lake. ## GraphQL Query API Get started with our APIs in a minute by building **[your first query](/docs/start/first-query)**. You can query [archive](/docs/graphql/dataset/archive), [real-time](/docs/graphql/dataset/realtime) or [combined](/docs/graphql/dataset/combined) dataset based on your requirements. After the query is built you can [save](/docs/ide/private) it and embed it in your application using [pre-cooked code snippet](/docs/ide/code) in any popular programming language. ```graphql query { EVM(dataset: archive network: bsc) { Transactions { Block { Date } count } } } ``` ## Integrated Development Environment (IDE) Integrated Development Environment (**[IDE](https://ide.bitquery.io/)**) helps you to manage your query, share them with other developers and generate a code to use the queries in your applications. ![IDE screen](/img/ide/ide_screen.png) ## GraphQL Subscription (WebSocket) API Subscription (WebSocket) is an extension of GraphQL API. It allows to subscribe on the updates in the data in real-time and receive the new data changes using WebSocket protocol. Protocols subscriptions-transport-ws and graphql-transport-ws are supported. ```graphql subscription { EVM { Transactions { Block { Hash Number Date } count } } } ``` ## Ways to Get Data ### API GraphQL queries and WebSocket subscriptions. You get both realtime and historical data. How far back it goes depends on the chain. See [Data Coverage & Retention](/docs/graphql/data-coverage-retention/). ### Streams Live data over WebSocket subscriptions, Kafka, or gRPC on Solana. See [Streams](/docs/streams/) and [Solana gRPC (CoreCast)](/docs/grpc/solana/introduction). ### Data Store Exports Parsed Parquet datasets, including history older than the API window. You download them from S3 or Cloudflare R2, or get them delivered to your own bucket or warehouse as a custom export. Buy them on the [Bitquery Data Store](https://bitquery.io/datastore). See [Data Store exports](/docs/cloud/). ### Data Lake Raw Protobuf blocks over S3. You decode them and parse them your own way. See [Blockchain Data Lake](/docs/data-lake/). ## SQL Like Interface We also provide SQL like interface on our Enterprise plan, if you want to explore that, please send us email at [hello@bitquery.io](mailto:hello@bitquery.io) ## Bitquery Support Channels We highly encourage you to dig into our docs first; however, you can contact us on the following platforms if you still have any queries. 1. [Telegram](https://t.me/bloxy_info) - For quick questions and doubts 2. [Community Forum](https://community.bitquery.io/) - For how to questions, features requests that can also help wider community 3. [Support Desk](https://support.bitquery.io/) - For data problems, bugs --- ## Bitquery API Endpoints and Regions URL: https://docs.bitquery.io/docs/start/endpoints/ Find Bitquery GraphQL, streaming, and regional API endpoints with base URLs, auth notes, and which service to use for each workload. # Endpoints and Regions Bitquery provides multiple regional endpoints to optimize latency and performance. Choose the endpoint closest to your geographic location for the best experience. ## Overview Bitquery offers two API versions: - **V1**: GraphQL API for historical blockchain data - **V2**: Streaming GraphQL API with real-time and historical data (varies from blockchain to blockchain) :::tip For optimal performance, use the endpoint closest to your application's deployment region. ::: :::info WebSocket Endpoints (WSS) For WebSocket connections, use the same endpoints but replace `https` with `wss`. For example: - `https://asia.streaming.bitquery.io/graphql` becomes `wss://asia.streaming.bitquery.io/graphql` ::: ## Europe and Nearby ### V1 - Historical Data API ``` https://graphql.bitquery.io ``` ### V2 - Streaming API The following chains are available via the Europe regional endpoint: | Blockchain | Endpoint | |------------|----------| | Ethereum | `https://streaming.bitquery.io/graphql` | | BSC (Binance Smart Chain) | `https://streaming.bitquery.io/graphql` | | Base | `https://streaming.bitquery.io/graphql` | | Solana | `https://streaming.bitquery.io/graphql` | | Arbitrum | `https://streaming.bitquery.io/graphql` | | Optimism | `https://streaming.bitquery.io/graphql` | | Tron | `https://streaming.bitquery.io/graphql` | | Matic (Polygon) | `https://streaming.bitquery.io/graphql` | | Robinhood | `https://streaming.bitquery.io/graphql` | | Arc Mainnet | `https://streaming.bitquery.io/graphql` | | Arc Testnet | `https://streaming.bitquery.io/graphql` | | Hyperliquid (Perpetuals API, `Hyperliquid` root) | `https://streaming.bitquery.io/graphql` | ## Asia ### V1 - Historical Data API ``` https://asia.graphql.bitquery.io ``` ### V2 - Streaming API The following chains are available via the Asia regional endpoint: | Blockchain | Endpoint | |------------|----------| | Ethereum | `https://asia.streaming.bitquery.io/graphql` | | BSC (Binance Smart Chain) | `https://asia.streaming.bitquery.io/graphql` | | Base | `https://asia.streaming.bitquery.io/graphql` | | Solana | `https://asia.streaming.bitquery.io/graphql` | | Arbitrum | `https://asia.streaming.bitquery.io/graphql` | | Optimism | `https://asia.streaming.bitquery.io/graphql` | | Tron | `https://asia.streaming.bitquery.io/graphql` | | Matic (Polygon) | `https://asia.streaming.bitquery.io/graphql` | ## United States ### V1 - Historical Data API ``` https://us.graphql.bitquery.io ``` ### V2 - Streaming API The following chains are available via the United States regional endpoint: | Blockchain | Endpoint | |------------|----------| | Ethereum | `https://us.streaming.bitquery.io/graphql` | | BSC (Binance Smart Chain) | `https://us.streaming.bitquery.io/graphql` | | Base | `https://us.streaming.bitquery.io/graphql` | | Solana | `https://us.streaming.bitquery.io/graphql` | | Arbitrum | `https://us.streaming.bitquery.io/graphql` | | Optimism | `https://us.streaming.bitquery.io/graphql` | | Tron | `https://us.streaming.bitquery.io/graphql` | | Matic (Polygon) | `https://us.streaming.bitquery.io/graphql` | ## Next Steps - Learn about [API authentication](/docs/authorization/how-to-generate/) - Explore the [GraphQL IDE](https://ide.bitquery.io/) - Check [API examples](/docs/blockchain/introduction/) --- ## Bitquery API Product Comparison URL: https://docs.bitquery.io/docs/api-comparison/ Bitquery GraphQL queries, WebSocket subscriptions and Kafka streams compared: when to use each, plus how to pick realtime vs archive datasets in API v1. # API Comparison :::tip Looking specifically for trading / DEX data? This page compares **delivery methods** (GraphQL Query vs Subscription vs Kafka). For the **trading-data product choice** (chain-level `DEXTrades` / `DEXTradeByTokens` vs the curated `Trading` cube), see the dedicated [**Trading Data Overview**](/docs/trading/trading-data-overview). ::: To choose the right Bitquery API offering, it helps to understand their differences. The table below summarizes key features and capabilities of GraphQL Query vs GraphQL Subscription vs Kafka Streams: | Feature / Method | GraphQL Query | GraphQL Subscription (WebSocket) | Kafka Streams (Protobuf) | | --------------------------------- | -------------------------------------------- | ---------------------------------------------- | --------------------------------------------------------- | | **Use case** | On‑demand historical + real‑time via polling | Real-time pushes for new on-chain events | High‑throughput, event-driven pipelines | | **Data model** | Flexible GraphQL with filtering, aggregation | Same GraphQL query syntax, live updates | Topic-based structured streams with JSON or Protobuf | | **Latency** | ~1 sec | ~1 sec latency | Sub‑second; streamed within 500 ms, supports HFT | | **Delivery model** | Pull via REST/GraphQL | Push over WebSocket (GraphQL subscription) | Consumer‑driven pull from Kafka broker | | **Schema granularity** | Customizable projections | Customizable projection | Kafka topics per type (e.g., dextrades, transactions) | | **Ordering & duplication** | Strong consistency in query response | No guaranteed order; WebSocket delivery | Consumer logic needed | | **Authentication** | OAuth/API‑Key | OAuth token over WebSocket | SASL username, password | | **Ideal Implementation Language** | Any language | Any language except curl | Go, Java, Python, Rust | | **Best for** | Interactive apps, ad-hoc querying | Monitoring, alerts, dashboards, mempool events | Streaming pipelines, HFT, data lakes, analytics workloads | On Solana you can also stream over [gRPC (CoreCast)](/docs/grpc/solana/introduction). For bulk history beyond the API window, use a [Data Store export](/docs/cloud/) (parsed Parquet) or the [Data Lake](/docs/data-lake/) (raw Protobuf). ## When to Use Each API ### GraphQL Queries **Best for on-demand, ad-hoc, and historical data needs:** - When you need to fetch past blockchain activity (trades, transfers, balances) - For dashboards, reports, and analytics that rely on filtering, sorting, and pagination - When requests are driven by user actions or scheduled jobs - Ideal for combining historical + near-real-time data via polling ### GraphQL Subscriptions (WebSocket) **Ideal for lightweight real-time updates and UI integration:** - When you want push-based delivery of live on-chain events (e.g., swaps, transfers, new blocks) - For wallet trackers, price alerts, or monitoring dashboards - When you need low-latency updates (~500 ms) but don’t require ultra-high throughput - Perfect for embedding live feeds into web or mobile interfaces ### Kafka Streams (JSON / Protobuf) **Perfect for high-throughput, fault-tolerant streaming pipelines:** - When you need sub-second end-to-end latency for trades, mempool events, or order books - For building scalable data lakes, HFT bots, or real-time analytics systems - When you require integration with Kafka-based ecosystems Pick Queries for flexibility and history, Subscriptions for easy real-time UI feeds, and Kafka Streams when you need industrial-scale, ultra-low-latency pipelines. ## How do I specify dataset: realtime vs archive in an API v1 query? This site documents **API V2** GraphQL, where you set **`dataset`** on the root field (for example **`EVM(dataset: archive)`** or **`Solana(dataset: combined)`**)—see [Dataset options](/docs/graphql/dataset/options). **API V1** uses a **different endpoint and schema**; realtime/archive semantics are **not** expressed the same way. For V1 query shapes and examples, use **[Bitquery V1 documentation](https://docs.bitquery.io/v1/)** and the [V1 examples catalog](https://docs.bitquery.io/v1/docs/category/examples). --- ## Bitquery Glossary: EVM and Solana Terms Used in the Docs URL: https://docs.bitquery.io/docs/category/glossary/ Definitions for the arguments, cubes and fields that appear in Bitquery queries, split into EVM terms and Solana terms, with the sections readers look up most. # Bitquery Glossary: EVM and Solana Terms Used in the Docs The glossary explains every argument, cube and field name a Bitquery query can contain, in two pages: one for the EVM chains and one for Solana. Each page walks the same order: the dataset, network and filter arguments on the root, then the terms of each cube (balance updates, blocks, calls or instructions, DEX trades, events, transactions, rewards, transfers), then the attributes of the `Currency` object that appears in most of them. Use it when a field name in an example is unclear, or when the IDE autocompletes something you have not seen before. ## The two pages | Page | Covers | |---|---| | [EVM builder terms](/docs/glossary/EVM) | `dataset`, `mempool` and `network` arguments, filter parameters, and the terms of the Balances, Holders, Blocks, Calls, DEXTradeByTokens, DEXTrades, Events, Transactions, MinerRewards and Transfers cubes, plus `Currency` attributes | | [Solana builder terms](/docs/glossary/solana) | `dataset` and filter arguments, and the terms of the BalanceUpdates, Blocks, DEXOrders, DEXTradeByTokens, DEXTrades, Instructions, Rewards, Transactions and Transfers cubes, plus `Currency` attributes | ## Most looked-up sections | Term | Where | |---|---| | `dataset: realtime`, `archive`, `combined` | [EVM dataset parameters](/docs/glossary/EVM#dataset-parameters), [Solana dataset parameters](/docs/glossary/solana#dataset-parameters) | | `mempool` argument | [EVM mempool parameter](/docs/glossary/EVM#mempool-parameter) | | `network` argument | [EVM network parameter](/docs/glossary/EVM#network-parameter) | | `where`, `orderBy`, `limit`, `limitBy` | [EVM filter parameters](/docs/glossary/EVM#filter-parameters), [Solana filter parameters](/docs/glossary/solana#filter-parameters) | | DEX trade fields: `Buy`, `Sell`, `Dex`, `Side`, `PriceInUSD` | [EVM DEXTrades terms](/docs/glossary/EVM#dextrades-api-terms), [Solana DEXTrades terms](/docs/glossary/solana#dextrades-api) | | Per-token trade aggregates | [EVM DEXTradeByTokens terms](/docs/glossary/EVM#dextradebytokens-api-terms), [Solana DEXTradeByTokens terms](/docs/glossary/solana#dextradebytokens-api) | | Decoded calls and instructions | [EVM Calls terms](/docs/glossary/EVM#calls-api-terms), [Solana Instructions terms](/docs/glossary/solana#instructions-api) | | `Currency` attributes: `Native`, `Fungible`, `SmartContract`, `MintAddress`, `Decimals` | [EVM currency attributes](/docs/glossary/EVM#currency-field-attributes-explained), [Solana currency terms](/docs/glossary/solana#currency-field-terms-explained) | ## Two terms in one query `dataset: combined` on the root reaches history and the realtime tail together; `Currency.Native` marks the chain's own coin (ETH here) as opposed to a token. Run it in the [Bitquery IDE](https://ide.bitquery.io); because it reads history, it needs an archive add-on (the free trial is real-time only). ```graphql { EVM(network: eth, dataset: combined) { Transfers( limit: { count: 3 } orderBy: { descending: Block_Time } where: { Transfer: { Currency: { Native: true } } } ) { Block { Time } Transfer { Amount Currency { Symbol Native } } } } } ``` ## Related pages - [Understanding cubes](/docs/category/understanding-cubes) - [GraphQL query capabilities](/docs/category/capabilities) - [Crypto Price API](/docs/trading/crypto-price-api/) --- ## Bitquery GraphQL Query Limits URL: https://docs.bitquery.io/docs/graphql/limits/ Bitquery GraphQL Query Limits in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Limits Results are limited by using attributes ```limit``` and ```limitBy``` ## limit ```limit``` just does what is says: limits the results to pre-defined size. :::note If you do not specify `limit`, a system default is applied. **GraphQL v2** uses a default of **25,000** rows per query result. You can override this by setting `limit` explicitly in your query filters. This is another argument to use aggregation when you need larger result sets. ::: ```limit``` attribute has a structure: * ```count``` is the maximum count of results returned * ```offset``` is the offset (0-based) of the results (default is 0) :::danger do not use ```offset``` for pagination of the result, unless you sure that the results are not modified or added between the queries and also have strong ordering ::: ## limitBy ```limitBy``` limits the result size for every value of the supplied attribute The following query returns just top 2 blocks by transaction count, **per every day** ```graphql { EVM (dataset: archive){ Transactions( where: {Block: {Date: {after: "2022-11-11"}}} orderBy: { descendingByField: "txCount" } limitBy: {count: 2 by: Block_Date} ) { Block { Date Number } txCount: count } } } ``` ```limitBy: {count: 2 by: Block_Date}``` here says: _"take just 2 records for every ```Block_Date``` the result has"_. :::tip ```limitBy``` is a good tool to do data sampling ::: --- ## Bitquery GraphQL in Postman URL: https://docs.bitquery.io/docs/graphql/postman/ Bitquery GraphQL in Postman in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Accessing Queries on Postman You can run Bitquery queries in Postman. The public workspace has one collection per chain: [Bitquery Postman Workspace](https://www.postman.com/interstellar-eclipse-270749/bitquery) ![Using the Bitquery GraphQL API in Postman](/img/postman.png) Every request in the workspace was executed against the live API before publishing. ## Setup 1. [Generate an access token](/docs/authorization/how-to-generate/). 2. Open the collection for the chain you want and set the `ACCESS_TOKEN` variable to your `ory_at_...` token. That is the only change you need to make — each collection ships with the right `BASE_URL` already set, and every request sends `Authorization: Bearer {{ACCESS_TOKEN}}`. ## Which endpoint a chain uses | Endpoint | Chains | | --- | --- | | `https://streaming.bitquery.io/graphql` | Solana, Ethereum, BSC, Base, Arbitrum, Polygon, Optimism, Tron, Robinhood Chain, Arc mainnet, Arc testnet, plus the Trading APIs, Perpetuals, Stablecoins, Prediction Markets and Cross-chain collections | | `https://graphql.bitquery.io` | Bitcoin, Litecoin, Bitcoin Cash, Dogecoin, Dash, Zcash, Ripple, Stellar, Cardano, Algorand | Protocol-specific examples live inside their chain — Pump.fun, Raydium and Meteora are in the **Solana** collection. ## Subscriptions The collections contain HTTP queries. For real-time streams use `wss://streaming.bitquery.io/graphql` and pass the token in the URL rather than a header — see [how to use a token](/docs/authorization/how-to-use/) and the [WebSocket guide](/docs/authorization/websocket/). >Remember that a websocket can be opened only on desktop version of Postman --- ## Bitquery IDE Account Settings URL: https://docs.bitquery.io/docs/ide/account/ Bitquery IDE Account Settings in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Manage Account After you sign in at [account.bitquery.io](https://account.bitquery.io/), the first screen is the **Dashboard** ([`/user/dashboard`](https://account.bitquery.io/user/dashboard)). It summarizes your plan, usage, profile, tokens, shortcuts to apps (including the GraphQL **IDE**), and support links. ![Bitquery account dashboard — landing page after login](/img/ide/user-dashboard.png) ## Top navigation The main menu is a single row at the top. A few items are direct links; the rest are **dropdowns** that group related pages (the old flat sidebar has been trimmed and reorganized). | Item | Notes | | --- | --- | | **Dashboard** | Home after login; overview cards (plan, usage, account, tokens, apps). | | **Billing** | Plans, payments, self-serve upgrades — [Billing](https://account.bitquery.io/user/billing) → [Select Plan](https://account.bitquery.io/user/upgrade). | | **Authorization** | Dropdown — **Applications** ([manage apps](https://account.bitquery.io/user/api_v2/applications)) and **Tokens** ([generate tokens](https://account.bitquery.io/user/api_v2/access_tokens)). | | **API V1** | Dropdown — v1 API usage and tools. | | **API V2** | Dropdown — v2 queries, streams, subscriptions, and related reports. | | **System Status** | Dropdown — service health and blockchain pipeline status. | | **Apps** | Dropdown — links to products such as the IDE, DEX dashboards, and other tools. | | **Help** | Dropdown — documentation, community, and support. | Use **Apps → IDE** (or the **IDE** card on the dashboard) to open the GraphQL IDE at [ide.bitquery.io](https://ide.bitquery.io/). ## Billing — self-serve upgrades You are in full control of your plan. From **Billing → [Select Plan](https://account.bitquery.io/user/upgrade)** you can: - ⚡ Pick a plan and upgrade instantly - 🔢 Choose **Monthly** or **Annual** billing (annual saves 30% or more) - 💳 Pay by card, cancel anytime - 🔢 Optionally **top up credits** (API points, stream-minutes, stream data) at checkout ![Select plan](/img/selfservice/select-plan.png) Plans on self-serve: **Personal** (100K API points/mo, 3 concurrent requests), **Pro** (1M points/mo, 100 streams), **Scale** ⭐ (5M points/mo, 1,000 streams), and **Enterprise** (custom limits, dedicated SLA & support — [contact sales](https://bitquery.io/forms/api)). See [full plans](https://bitquery.io/pricing), the [Upgrade to Paid Plan](/docs/ide/paid/) guide, or [Manage Your Subscription](/docs/plans/manage-subscription/) for video walkthroughs of paying, upgrading, downgrading and cancelling. Billing questions: [support@bitquery.io](mailto:support@bitquery.io). ## What you see on the Dashboard - **Plan** — Current tier, points allowance, and stream limits (with upgrade or sales contact where applicable). - **Usage** — Recent API usage (for example v1 / v2 queries and streams); links to more detailed reports where available. - **Account** — Profile, company, role, 2FA; links to password and security settings — [Account settings](https://account.bitquery.io/user/account). - **Access tokens** — Active tokens and applications; [generate or manage tokens](https://account.bitquery.io/user/api_v2/access_tokens) and [applications](https://account.bitquery.io/user/api_v2/applications). - **Bitquery Apps** — Quick entry to the IDE and other Bitquery products. - **Docs & Support** — Documentation, forum, blog, and contact options. - **System status** — Shortcuts to overall and per-service status (full detail also under **System Status** in the top menu). Deeper pages (detailed API statistics, referrers, error logs, messages, and similar) are reached from the **API V1**, **API V2**, or **Authorization** menus instead of a long static sidebar. --- ## Bitquery IDE Paid Plans URL: https://docs.bitquery.io/docs/ide/paid/ Bitquery IDE Paid Plans in Bitquery docs with practical setup steps, examples, and guidance for secure API access. Keep queries fast with indexed filters. # Upgrade to Bitquery Paid Plan You are now in full control of your plan. You can upgrade yourself from your account — no sales call required — or contact sales for custom/Enterprise volumes. 👉 [Upgrade now](https://account.bitquery.io/user/upgrade) · [See full plans](https://bitquery.io/pricing) ## Self-service upgrade Go to [Account → Billing → Select Plan](https://account.bitquery.io/user/upgrade). The checkout is a 4-step flow: **Choose plan → Plan configuration → Review & pay → Done**. ![Select plan](/img/selfservice/select-plan.png) On the **Choose plan** step you can: - ⚡ Pick a plan and upgrade instantly - 🔢 Switch between **Monthly** and **Annual** billing (annual saves 30% or more) - 💳 Pay by card, cancel anytime ### Plans available on self-serve | Plan | Monthly | Annual (per mo) | API points / mo | Requests / min | Concurrent requests | Simultaneous streams | Streaming time | Traffic | Team size | | -------------------------- | ------- | --------------- | --------------- | -------------- | ------------------- | -------------------- | -------------- | --------- | --------- | | **Personal** | $49 | $29 | 100,000 | 30 | 3 | — | — | — | 1 | | **Pro** | $99 | $69 | 1,000,000 | 90 | 6 | 100 | 100,000 min | 5 GB | 2 | | **Scale** ⭐ (recommended) | $299 | $199 | 5,000,000 | 240 | 12 | 1,000 | 2,000,000 min | 50 GB | 5 | | **Enterprise** | Custom | Custom | Custom | Custom | Custom | Unlimited | Custom | Unlimited | Custom | Streaming is **off on Personal** — it starts at Pro. Annual billing saves 30% or more and locks the price for 12 months. Self-serve plans query the `realtime` dataset by default. To query history — the `archive` and `combined` datasets — add the **historical data add-on** to your plan; see the [pricing page](https://bitquery.io/pricing) for the chains it covers. Without it, a query using `dataset: archive` or `dataset: combined` will be rejected. **Enterprise** includes all datasets (Archive, Realtime, Combined), volume pricing, and dedicated support & SLA — [contact sales](https://bitquery.io/forms/api) for a quote. For which cube has how much history on each chain, see [Data Coverage & Retention](/docs/graphql/data-coverage-retention/). Current pricing is always on the [pricing page](https://bitquery.io/pricing). ## Top up credits (add-ons) Step 2 of the checkout is **Plan configuration** — optional. Add-ons are billed together with your plan each period; skip the step if you don't need any. ![Top up credits](/img/selfservice/top-up-credits.png) | Add-on | What you get | Monthly | Annual (per mo) | | ------------------- | -------------------------- | ------- | --------------- | | **API points** | +1,000,000 API points | $50 | $35 | | **Stream-minutes** | +200,000 streaming minutes | $50 | $35 | | **Stream data** | +5 GB of stream traffic | $50 | $35 | | **MCP credits** | Credits for MCP / AI agent requests | from $13/mo | — | Top-ups are **recurring** — they refill each billing period. A one-time, non-recurring top-up of 1M points is also available at $100. Volume packs lower the unit rate as you scale: the largest pack cuts it by 70% for stream-minutes and 80% for stream data. ### Historical data add-ons Self-serve plans query the `realtime` dataset. To run `dataset: archive` or `dataset: combined`, add the historical add-on for the chain you need: | Chain | Add-ons | Indicative price (billed yearly) | | --- | --- | --- | | Ethereum, BNB Chain (BSC), Base, Arbitrum, Optimism, Polygon, Tron, Robinhood, Arc | **Historical Trading Data** · **Historical Transfers + Balances + Holders** | from $70/mo per chain, per pack | | Solana | **Historical OHLCV & Token Price** (`DEXTradeByTokens` and `DEXTrades`) · **Historical Token Transfers & Balances** (`Transfers` and `Transactions`) | $210/mo · $350/mo | | Bitcoin, Bitcoin Cash, Litecoin, Dogecoin, Dash, Zcash | **Chain Data (historical included)** | $175/mo per chain | | Cardano, Ripple, Stellar, Filecoin | **Chain Data (historical included)** | $175/mo per chain | | Avalanche, Algorand, Celo, Cronos, Klaytn | **Chain Data (historical included)** | $105/mo per chain | | Polymarket | **Historical Data** (from 1 September 2025) | $105/mo | | All chains | **Address Label Data (multi-chain)** | $69/mo | Bundles cover the eight EVM chains in one purchase, and all six UTXO chains in another — cheaper than buying the chains individually. Tron and Solana are sold per chain. Use the ⓘ on any add-on in checkout to see exactly which datasets, cubes and time scope it unlocks. Prices above are indicative and vary by monthly vs yearly billing — checkout and the [pricing page](https://bitquery.io/pricing) are the source of truth. Cardano, Ripple, Stellar, Algorand, Filecoin, Avalanche, Celo, Cronos and Klaytn are sold the same way as the UTXO chains: one pack per chain, history included. There is no bundle for these nine. You can add multiple units of each add-on using the quantity selector. Prices per unit are shown in the checkout and on the [pricing page](https://bitquery.io/pricing). ## Additional Points If you are on a paid plan and your points run out, you can either **top up API points** (add-on above) or **upgrade to a higher plan** — both from [Account → Billing](https://account.bitquery.io/user/billing). ## Contacting sales For **Enterprise**, custom limits, or an invoice-based purchase, [contact sales](https://bitquery.io/forms/api) using the official form, email [sales@bitquery.io](mailto:sales@bitquery.io), or reach the Bitquery team on Telegram at [https://t.me/bloxy_info](https://t.me/bloxy_info) (please be cautious about potential scammers — only trust official channels and double-check the admins). ## How to change the plan? You can change your plan any time from [Account → Billing](https://account.bitquery.io/user/billing) — **Change Plan** to move tier, or **Manage Add-Ons** to add capacity or data access without changing tier. - **Upgrades** apply immediately and are charged **pro rata** — only for the days left in your current period. The full amount bills from your next renewal. - **Downgrades** take effect at your **next renewal**, so you keep what you have already paid for until the period ends. Nothing is charged at the time of the downgrade. - **Cancelling** stops the renewal. Your current period and any remaining points stay available until the period end date; no refund is issued for the current period. For a walkthrough of all three, see [Manage Your Subscription](/docs/plans/manage-subscription/). ## What will happen if I upgrade the plan in the middle of the month? Your billing cycle starts on the date you pay — it is not tied to the calendar month. Whatever date you upgrade on, your points run month-on-month from that date. For example, if you pay on the **19th**, your points are available until the **19th of the next month**, when the plan renews and your allowance resets. ## Will response times improve if I upgrade to a paid plan? {#will-response-times-improve-if-i-upgrade-to-a-paid-plan} Paid plans have higher rate limits — more requests per minute and more concurrent requests (see the [plan table](#plans-available-on-self-serve) above). Per-query response time is driven by the query itself, so also [optimize your queries](/docs/graphql/optimizing-graphql-queries). If that doesn't help, ask the team on [Telegram](https://t.me/bloxy_info). ## When do API credits (points) reset — monthly or rolling? {#when-do-api-credits-points-reset-monthly-or-rolling} Points refresh on your **billing cycle**, which is anchored to the date you paid — not to the 1st of the calendar month. If you pay on the 19th, your points renew on the 19th of each following month. Your exact renewal date and usage appear in your [account billing](https://account.bitquery.io/user/billing). If your contract differs, use the dates on your invoice or ask [sales@bitquery.io](mailto:sales@bitquery.io). ## Can I buy points without contacting sales? {#can-i-only-buy-points-by-contacting-sales} Yes. Points and other credits are available **self-serve**: go to [Account → Billing → Select Plan](https://account.bitquery.io/user/upgrade), pick your plan, and add **Top Up Credits** (API points, stream-minutes, or stream data) at step 2 of checkout. Sales contact is only needed for **Enterprise**, custom volumes, or invoice-based billing. See also [Points](/docs/ide/points/). ## Need help? Questions about billing? Reach us at [support@bitquery.io](mailto:support@bitquery.io) or [support.bitquery.io](https://support.bitquery.io). > **WARNING** > Please do not send money or pay outside the official checkout unless you receive an invoice from [bitquery.io](https://bitquery.io). Beware of scammers. --- ## Bitquery IDE Points and Usage URL: https://docs.bitquery.io/docs/ide/points/ Bitquery IDE Points and Usage in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Points Bitquery indexes more than 1 Petabyte of structured blockchain data and exposes it through a single GraphQL interface. Using one endpoint, you can get a chain’s latest block height, follow money trails, pull DEX trades across supported blockchains, and more. Not every query uses the same resources: some need a small set of records, others scan billions; some are served from cache, others may use large amounts of memory. Charging only by number of API calls would be unfair, because each call has a different cost. **Points** solve this by tying cost to actual resource usage: **Points = Resources consumed × Price per unit** So you pay in proportion to what your queries consume. The exact algorithm and resource prices may change over time, but pricing is based on Points (not raw API call count). At Bitquery we use the points system to calculate the cost for each query. Each query consumes a different number of points based on its complexity and the amount of data requested. **For a comprehensive understanding of the points system, please see this [video](https://youtu.be/L5QOTnvUwkg).** Every paid plan starts with a 7-day free trial, with full WebSocket streaming included and no card required. After that, you can [upgrade yourself in a few clicks](https://account.bitquery.io/user/upgrade) — no sales call needed — or contact our sales team for Enterprise/custom volumes. For every query you run, you can check the points consumed in real time. ![points](/img/ide/points.png) Different plans have different limits for points available. ## Running out of points? Top up or upgrade (self-serve) Points are now **self-serve**. Go to [Account → Billing → Select Plan](https://account.bitquery.io/user/upgrade) and either: - **Upgrade your plan** — Personal (100K points/mo), Pro (1M points/mo), or Scale (5M points/mo, recommended). Monthly or annual billing (annual saves 30% or more), pay by card, cancel anytime. - **Top up credits** — at step 2 of checkout, add **1 Million API points**, **200k Stream-minutes**, or **5 GB Stream Data** add-ons. Add-ons are billed together with your plan each period. ![Top up credits](/img/selfservice/top-up-credits.png) For Enterprise or custom volumes, [contact sales](mailto:sales@bitquery.io). Check pricing [here](https://bitquery.io/pricing). See the full billing walkthrough on the [Upgrade to Paid Plan](/docs/ide/paid/) page. > **WARNING** > Please do not send money or pay unless you receive an invoice from [bitquery.io](https://bitquery.io). Beware of scammers. ## How are points calculated? The number of points can vary for various reasons. Even the same query can produce different results. These points are dynamically calculated based on the following factors: - The quantity of records being queried, either through the count of records in limit or the date range. - The level of complexity of the query. For instance, if you include additional addresses, the points will be calculated considering the resources occupied by those addresses. To optimize this query, there are a few approaches you can consider. Firstly, narrowing down the date range can help to refine the results. Secondly, reducing the list of addresses may also be beneficial. However, the effectiveness of these strategies will depend on your specific goal. ## Why does a Net::ReadTimeout error consume my API credits? {#why-does-net-readtimeout-consume-api-credits} Bitquery **points** reflect **work the backend performs** (see [how points are calculated](#how-are-points-calculated)), not whether your HTTP client waited long enough. If the server **executes** your GraphQL operation before the client hits **Net::ReadTimeout**, that run can still **deduct points**. Reduce cost by **narrowing filters**, lowering **`limit`**, and fixing slow patterns—see [Common errors — timeout](/docs/start/errors/#timeout-tcp-socket). For billing edge cases, check usage in your [account](https://account.bitquery.io/) or ask [support](https://support.bitquery.io/). ## How are points calculated for the realtime dataset? Queries on `dataset: realtime` are priced by **query complexity**, the same way as other queries. There is no longer a flat 5 points per cube. A simple query costs fewer points, and a heavy one costs more. What makes a realtime query cheaper: - **Fewer records.** A lower `limit`, or a narrower time range, means less data to read. - **Fewer fields.** Select only the fields you use. - **Tight filters.** Filter on a specific address, token or block instead of scanning the whole cube. - **Fewer cubes.** Each cube in a query is priced on its own work, so drop cubes you don't need. Aggregations, sorting on large result sets and wide time ranges cost more. ### Example ```graphql { EVM(network: eth, dataset: realtime) { Transactions(limit: {count: 10}) { Block { Hash } } } } ``` This query reads one cube, asks for one field and returns 10 rows, so it sits at the low end of the scale. Adding more fields, a bigger `limit` or an aggregation raises its points. Check the points used by any query in the [IDE](https://ide.bitquery.io) after you run it. ## Streaming Data — Points and Pricing Bitquery offers two streaming interfaces for real-time blockchain data. Each has a different pricing model: ### 1. WebSocket Subscriptions (GraphQL) WebSocket-based [GraphQL subscriptions](/docs/subscriptions/subscription) deliver real-time blockchain data through the same API you use for queries. **Important:** Streams do not count towards points in paid plans. Streams are sold separately as a number of concurrent streams with no data or rate limits. **How pricing works:** - Under [paid plans](https://bitquery.io/pricing), you purchase a number of **concurrent streams** — and Bitquery adds enough points to keep those streams running 24/7 for the entire billing period. - **As a paid customer, you don't need to worry about points for streaming.** Simply tell us how many concurrent streams you need and we handle the rest. **What counts as one stream?** Each data cube (e.g., Transfers, DEXTrades, Blocks) activated counts as a **separate stream**. If you use multiple cubes within a single WebSocket connection, each one is billed individually. #### Example — Single Stream ```graphql subscription { EVM(network: eth) { Transactions { Block { Hash } } } } ``` This counts as **1 stream** (one cube: `Transactions`). #### Example — Multiple Streams Using the same method twice with different filters results in two separate streams: ```graphql subscription { EVM(network: eth) { Cube1: Transactions(where: {#filters A}) { Block { Hash } } Cube2: Transactions(where: {#filters B}) { Block { Hash } } } } ``` This counts as **2 streams**. #### Points Calculation (Internal Reference) - **One stream for 10 minutes** = 400 points (10 min × 40 points/min) - **Two streams for 10 minutes** = 800 points (2 streams × 10 min × 40 points/min) On paid plans this is handled automatically — you just pick the number of concurrent streams you need. For more details on subscriptions, see the [subscriptions documentation](/docs/subscriptions/subscription). ### 2. Kafka Streams [Kafka streams](/docs/streams/kafka-streaming-concepts) provide high-throughput, low-latency blockchain data delivery via Apache Kafka. **Kafka pricing is completely separate from the points system.** There are no point deductions, no bandwidth caps, and no per-minute charges. - Access is granted directly as part of your plan. - There are no limitations on bandwidth or data volume. - Kafka streams are ideal for high-throughput use cases such as trading bots, real-time indexers, and large-scale analytics pipelines. To get started with Kafka streams, [contact our sales team](mailto:sales@bitquery.io) or visit the [Kafka streaming documentation](/docs/streams/kafka-streaming-concepts). ## How do you check points for your account? You can check points consumed via streams under your [account](https://account.bitquery.io/user/api_v2/subscriptions). ![stream_points](/img/ide/stream_points.png) ## Need help? If you still have questions about points or pricing, you can reach out to [support.bitquery.io](https://support.bitquery.io) or [sales@bitquery.io](mailto:sales@bitquery.io). --- ## Bitquery IDE Teams URL: https://docs.bitquery.io/docs/ide/team/ Bitquery IDE Teams in Bitquery docs with practical setup steps, examples, and guidance for secure API access. Built for traders and analytics teams. # Develop in Team Bitquery IDE is built for Teams. You can invite team members and share the same billing account. You can invite up to 3 members for free, then $30 per team member. To invite your team, use the dropdown menu in our IDE. ![IDE Query Share](/img/ide/invite_to_team.png) ![IDE Query Share](/img/ide/invite_new_member.png) You can view your team from your [account dashboard](/docs/ide/account/): sign in at [account.bitquery.io](https://account.bitquery.io/), then use the **Authorization** menu in the top bar (or the equivalent entry under account settings). ![IDE Query Share](/img/ide/view_team.png) You can also check your team member's points consumption and, if needed also, remove them from the Team window. ![IDE Query Share](/img/ide/points_consumption.png) --- ## Bitquery Learning Path URL: https://docs.bitquery.io/docs/start/learning-path/ Follow a guided Bitquery learning path from your first GraphQL query through streaming, cubes, and production-ready apps. # Learning Path: From Beginner to Advanced Read these pages in order. The four stages run from a first query in 5 minutes to tuning queries for production, and each heading gives the time a stage takes. ## Quick Start (5 minutes) 1. **[Your First Query](/docs/start/first-query)** - Create and run your first GraphQL query 2. **[IDE Basics](/docs/ide/query)** - Learn to use the Bitquery IDE 3. **[Starter Queries](/docs/start/starter-queries)** - Try pre-built queries for common use cases ## Foundation (30 minutes) 1. **[Mental Model: Transfers, Events, Calls, and DexTrades](/docs/start/mental-model-transfers-events-calls)** - Understand when to use each data primitive 2. **[Understanding Datasets](/docs/graphql/dataset/archive)** - Learn about archive, real-time, and combined datasets 3. **[Basic GraphQL Concepts](/docs/graphql/query/)** - How a query is built 4. **[Authorization](/docs/authorization/how-to-generate)** - Set up your access outside our IDE ## Intermediate (1-2 hours) 1. **[Building Complex Queries](/docs/graphql/query)** - Learn advanced query techniques 2. **[Real-time Subscriptions](/docs/start/starter-subscriptions)** - Set up live data streams 3. **[Error Handling](/docs/start/errors)** - Fix common errors ## Advanced (2-4 hours) 1. **[Platform-Specific APIs](/docs/blockchain/Solana/)** - APIs for each chain, such as Solana and Ethereum 2. **[Integration Examples](/docs/category/how-to-guides/)** - Worked examples from real apps 3. **[Performance Optimization](/docs/graphql/optimizing-graphql-queries/)** - Optimize your queries for production ## Choose Your Path ### For Traders - Start with **[Crypto Price APIs](/docs/trading/crypto-price-api/)** - Learn **[Real-time Subscriptions](/docs/subscriptions/subscription)** - Explore **[DEX Trading APIs](/docs/blockchain/Solana/solana-dextrades)** ### For Developers - Begin with **[Your First Query](/docs/start/first-query)** - Master **[GraphQL Basics](/docs/graphql/query/)** - Build **[Custom Applications](/docs/category/how-to-guides/)** ### For Analysts - Start with **[Historical Data](/docs/graphql/dataset/archive)** - Learn **[Aggregation Queries](/docs/graphql/capabilities/aggregated_metrics/)** - Explore **[Analytics Examples](/docs/category/how-to-guides/)** ## Getting Help - **Documentation**: Search the docs first - **IDE Examples**: Try the pre-built queries in the IDE - **Community**: Ask questions on [Telegram](https://t.me/Bloxy_info) - **Support**: Contact [support](https://support.bitquery.io/) for technical issues --- ## Bitquery MCP Server for AI Agents URL: https://docs.bitquery.io/docs/mcp/mcp-server/ Connect Claude, Cursor, or ChatGPT to Bitquery MCP to query DEX trades, OHLC prices, wallet analytics, fund tracing, Polymarket and Hyperliquid perpetuals in plain English. # Bitquery MCP Server: Blockchain Data for AI Agents Point your AI client at [https://mcp.bitquery.io](https://mcp.bitquery.io) and ask Bitquery's blockchain dataset questions in plain English. Works with Claude, Cursor, ChatGPT, Claude Code, and anything else that speaks [MCP](https://modelcontextprotocol.io/). You get outlier-filtered DEX trades, transfers, OHLC candles, market cap, and wallet history across Solana, Ethereum, BSC, Base, Arbitrum, Optimism, Polygon, Tron, Robinhood Chain and Arc. It also covers Polymarket prediction markets and the Hyperliquid exchange (perpetuals and spot markets) with their own tools. Same data behind the tracing side: origin of funds, cross-chain movement, wallet clusters. | | | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | | **Endpoint** | [https://mcp.bitquery.io](https://mcp.bitquery.io) | | **Auth** | OAuth 2.1, browser sign-in, no manual tokens | | **Pricing** | Every 7-day trial includes 100 free credits. MCP plans are separate from API plans: Trading MCP from $19/mo, AI Investigation MCP $149/mo. See [pricing](https://bitquery.io/products/bitquery-mcp-server). | | **Support** | [Telegram](https://t.me/Bloxy_info) · [support.bitquery.io](https://support.bitquery.io/) · [support@bitquery.io](mailto:support@bitquery.io) | ## Install in one minute - **Claude Code:** `claude mcp add bitquery -- npx -y mcp-remote https://mcp.bitquery.io/mcp` - **Claude Desktop and Web, ChatGPT, VS Code, Windsurf:** add a custom connector or MCP server with the URL [https://mcp.bitquery.io](https://mcp.bitquery.io), then sign in with your Bitquery account when the first tool runs. - **Cursor:** Settings, MCP, Add new MCP server, URL [https://mcp.bitquery.io](https://mcp.bitquery.io); or put the `mcp-remote` command in `.cursor/mcp.json`. - **Codex app:** add the server with an `Authorization: Bearer` header, then ask it to load the Bitquery tools in each new chat. See [Codex app](#codex-app). No API key is pasted anywhere; OAuth 2.1 handles sign-in and a 7-day trial account works. Client-by-client steps with screenshots are in [Install](#install). --- ## What It Is A hosted [Model Context Protocol](https://modelcontextprotocol.io/) endpoint sitting in front of Bitquery's production trading and transfers dataset. It's the same data that powers the GraphQL APIs, the IDE, the Kafka streams, and the TradingView feeds. You ask a question. The agent does the lookup. You get structured rows back. You never write a query, sync a schema, or think about rate limits. What your agent can actually reach: - Billions of swap-level trade rows across Solana, Ethereum, BSC, Base, Arbitrum, Optimism, Polygon, and Tron. - Transfer-level data for tracing origin of funds, following money across chains, and pulling apart wallet clusters. - Tracing and forensics workflows: AML/KYC scoring, payment paths, phishing investigations, stablecoin and bridge monitoring, sanctions screening, forensic reports. - OHLC candles already built at 1-minute, 5-minute, hourly, and daily intervals. - Market cap, fully diluted valuation, and circulating supply attached to every row. - Bitquery's outlier filter, applied automatically, so wash-traded pools and noisy pairs drop down the ranking. - No ETL, no schema sync, no API client to write. --- ## How It Works ``` ┌──────────────────┐ MCP (JSON-RPC) ┌─────────────────────┐ queries ┌──────────────────────┐ │ Claude / Cursor │ ─────────────────► │ mcp.bitquery.io │ ────────► │ Bitquery production │ │ ChatGPT / Code │ ◄── tool results ── │ (OAuth 2.1) │ ◄── rows ──│ trading dataset │ └──────────────────┘ └─────────────────────┘ └──────────────────────┘ ``` 1. Your client connects to `https://mcp.bitquery.io` over the MCP transport. 2. OAuth 2.1 handles sign-in. A browser window opens once, then the client caches a refresh token for about 30 days and renews it quietly in the background. 3. The server exposes a small set of tools. The model uses them to figure out what's in the dataset and pull rows. 4. Access is read-only. The agent can't write, delete, or modify anything, even if you ask it to. 5. When you ask for "clean" volume, Bitquery's price-index ranking is applied for you. Because it's standard MCP, any compatible client works without special handling: Claude Desktop, Claude Code, Cursor, ChatGPT, VS Code, or something you built yourself. --- ## What Data You Get Two datasets are live. The agent picks between them based on what you ask. **Trading** covers all nine supported chains, with two views of the same underlying trades: 1. Per-trade rows: every swap, with price, USD amounts, supply snapshot, trader wallet, and transaction hash. 2. Pre-built candles: OHLC, volume, and price averages bucketed at 1-second, 1-minute, 5-minute, hourly, and daily intervals. **Tracing** handles fund-flow and compliance questions: 1. AML/KYC risk scoring, plus sanctions and OFAC screening. 2. Payment tracing from source to destination, including hops, DEX swaps, and bridges. 3. Investigations: phishing and fraud, money-laundering patterns, CEX deposit clustering. 4. Wallet clustering, stablecoin movement monitoring, and forensic or SAR-style reporting. More on trading: - [**Trading on the MCP: overview**](/docs/mcp/trading/overview/) covers chains, DEX coverage, and what lands on every trade. - [**What you can do with it**](/docs/mcp/trading/use-cases/) walks through eleven conversational patterns with prompts and best practices. - [**Worked examples with charts**](/docs/mcp/trading/examples/) shows six trader workflows against real data. More on tracing: - [**Tracing on the MCP: overview**](/docs/mcp/Tracing/overview/) covers AML, forensics, payment tracing, and wallet clustering. --- ## Under the Hood The server is built on the open-source [`mcp-clickhouse`](https://github.com/ClickHouse/mcp-clickhouse) project. Your agent's natural-language requests get turned into read-only queries against Bitquery's production cluster, and you never have to see, write, or debug one. Writes, deletes, and mutations are rejected at the server, so there's nothing you can break by poking around. --- ## Install ### Claude (Desktop & Web) 1. Open **Settings → Connectors → Add custom connector**. 2. Fill in: - **Name:** `Bitquery Trading Data` - **URL:** [https://mcp.bitquery.io](https://mcp.bitquery.io) 3. Click **Add**. ![Add custom connector: Name and Remote MCP server URL fields](/img/mcp/custom_connector.png) You don't need to pick tools by hand in the chat UI. Ask in plain language, for example _"get me the top Solana tokens by 24h volume"_, and Claude calls Bitquery when the request fits. ### ChatGPT 1. Settings → **Connectors** (requires Plus, Pro, or Business). 2. **Add connector → Custom connector**. 3. URL: [https://mcp.bitquery.io](https://mcp.bitquery.io). 4. Authenticate with your Bitquery account when prompted. ### Cursor Easiest path: 1. Settings → **MCP → Add new MCP server**. 2. URL: [https://mcp.bitquery.io](https://mcp.bitquery.io). Or add it to `.cursor/mcp.json` directly: ```json { "mcpServers": { "bitquery": { "command": "npx", "args": ["-y", "mcp-remote", "https://mcp.bitquery.io/mcp"] } } } ``` Restart Cursor, or reload the MCP configuration, so the server gets picked up. ### Codex app These steps are for the Codex desktop app, not the Codex CLI. You need a Bitquery API access token to use as the bearer token. Generate one on the [Access Tokens page](https://account.bitquery.io/user/api_v2/access_tokens) of your Bitquery account. Step-by-step instructions are in [Authorization](/docs/authorization/how-to-generate/). 1. Open **Plugins → MCPs → Add server**. 2. Fill in: - **URL:** [https://mcp.bitquery.io](https://mcp.bitquery.io) - **Bearer token env var:** leave empty 3. Under **Headers**, click **Add header**: - **Key:** `Authorization` - **Value:** `Bearer YOUR_BITQUERY_TOKEN` 4. Click **Save**. ![Codex MCP server settings with the Bitquery URL and an Authorization bearer header](/img/mcp/codex-mcp-bearer-header.png) Put the token in **Headers**, not in **Bearer token env var**. That field expects the name of an environment variable, not the token itself. 5. Start a **New chat** and ask Codex to load the tools before your first question: ``` Load all tools in bitquery mcp ``` ![Codex chat confirming all 173 Bitquery MCP tools are loaded](/img/mcp/codex-load-bitquery-tools.png) Codex keeps MCP tools hidden until they are searched for, so skipping this step can make it reply that no Bitquery tools are available. Send the load prompt once at the start of each new chat, then ask questions normally, for example _"get Solana trending tokens"_. ### Claude Code (terminal) ```bash claude mcp add bitquery -- npx -y mcp-remote https://mcp.bitquery.io/mcp ``` ### VS Code and other MCP clients Add a new MCP server with the URL [https://mcp.bitquery.io](https://mcp.bitquery.io). The client handles OAuth on its own. --- ## First Connection and Permissions Once it's configured, **Bitquery Trading Data** shows up in your client's connector list: ![Bitquery MCP listed among custom connectors](/img/mcp/mcp-connectors-bitquery-listed.png) The first time a tool runs, the client asks you to **connect** and approve: ![Tool run requesting Connect for Bitquery](/img/mcp/mcp-tool-connect-prompt.png) You're prompted to **sign in** to Bitquery. A 7-day trial account works: ![Bitquery sign-in to authorize the application](/img/mcp/mcp-bitquery-sign-in.png) Then **authorize** the client (Claude, Cursor, whatever you're using) to act on your account: ![Authorize Bitquery access for the requesting application](/img/mcp/mcp-bitquery-authorize-access.png) In Cursor and similar clients, you choose whether tool calls always need approval or run automatically: ![Tool permission options such as Always allow](/img/mcp/mcp-tool-permissions-dropdown.png) OAuth tokens are cached for roughly 30 days and refreshed for you, so re-authenticating is rare. ## What You Can Ask the Agent Most trader and investigator questions fall into one of these shapes. Type it into the chat and let the agent work out the rest. - **Token discovery and trending:** _"Top 10 Solana tokens by USD volume in the last 24h, skip wash-traded pools."_ - **Trader PnL and wallet analytics:** _"Pull every trade for wallet `7xKX…` in the last 7 days. Compute realised PnL per token."_ - **OHLC charts:** _"1-minute OHLC for the WIF/USDC pool on Raydium for the last 6 hours."_ - **Market cap and FDV monitoring:** _"Which Base tokens crossed $10M market cap in the last 24h?"_ - **Wash-trade filtering:** saying _"only clean volume"_ is enough to trigger Bitquery's outlier ranking. - **Launchpad pulse:** _"How many new tokens launched on Pump.fun in the last hour vs the 24h average?"_ - **Cross-chain market overview:** _"For each chain, show 24h DEX volume, trades, and unique traders."_ - **Sniping and copy-trading research:** prototype a signal here before you commit to a Kafka stream (any supported chain) or a gRPC stream (Solana only). - **Slippage and liquidity:** derive realised slippage and effective depth from per-trade rows. - **AML/KYC scoring:** _"Score wallet `0x…` for AML risk. Check wallet age, mixing signals, and compliance flags."_ - **Payment tracing:** _"Trace $500K USDT from this hot wallet to the final destination. Show every hop."_ - **Phishing and fraud:** _"2 ETH were stolen from this wallet. Trace where the funds went across swaps and bridges."_ - **Wallet clustering:** _"Cluster wallets that sent to or received from `0x…` by likely control."_ - **Sanctions and reporting:** _"Screen this wallet against OFAC and known-risk entities, then draft a forensic summary."_ - **Counterparties in USD:** _"Who did this wallet pay and get paid by in the last 90 days, in USD with labels? What share of its inflow came from exchanges?"_ See [Counterparties](/docs/mcp/counterparties/). - **Holder and balance exports:** _"Pull 10,000 Tron addresses holding more than 1 TRX and save them as a CSV."_ See [Holders and balances](/docs/mcp/holders-balances/). For end-to-end trading workflows, see the [worked examples](/docs/mcp/trading/examples/). For tracing patterns and prompting habits, see [Tracing on the MCP](/docs/mcp/Tracing/overview/). For more trading patterns, see [What you can do with it](/docs/mcp/trading/use-cases/). --- ## Compared with other crypto MCP servers | | CoinGecko MCP | CoinMarketCap MCP | Bitquery MCP | |---|---|---|---| | Sign-in | Keyless public endpoint with shared rate limits; API key for the Pro endpoint and the local server | API key from the developer dashboard; limits follow the API plan | OAuth 2.1 in the browser, no key to paste; the 7-day trial includes 100 free credits | | What the agent reads | Coin prices, market caps and volumes, exchange and trending data, plus token and pool data across DEXes | Market data, rankings, technical-analysis and on-chain metrics such as holder distribution; OHLCV on higher tiers | Per-trade rows with USD price, market cap and supply, built candles down to one second, balances, holders, transfers and fund tracing across ten chains, plus Polymarket and the Hyperliquid exchange | | Hosting | Remote endpoints and a local package | Remote endpoints | Hosted at mcp.bitquery.io, read-only | Both CoinGecko and CoinMarketCap answer market-level questions well. Reach for the Bitquery server when the question is about specific trades, wallets or pools, or when the token is not listed anywhere yet. ## References - [Model Context Protocol spec](https://modelcontextprotocol.io/), the standard this server implements. - [`mcp-clickhouse`](https://github.com/ClickHouse/mcp-clickhouse), the open-source server underneath. - [Crypto Price API](/docs/trading/crypto-price-api/) for GraphQL access to OHLC, market cap, and pre-aggregated token prices over the same data. - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api/) for swap-level GraphQL streams, real-time and historical. - [Traders API](/docs/trading/crypto-trades-api/traders-api/) for wallet-centric trade analytics. - [Price index algorithm](/docs/trading/crypto-price-api/price-index-algorithm/) explains how the outlier filter and ranking are computed. - [How to filter anomaly prices](/docs/usecases/how-to-filter-anomaly-prices/), a practical guide to the outlier ranking. - [How to generate Bitquery API credentials](/docs/authorization/how-to-generate/) for non-MCP clients. - [Bitquery Account](https://account.bitquery.io/) to sign up or manage your plan. --- ## Bitquery WebSocket Subscriptions URL: https://docs.bitquery.io/docs/subscriptions/websockets/ Bitquery WebSocket Subscriptions using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Accessing Streaming Data via WebSocket In the previous section, we learned how to get live data in Bitquery IDE by creating subscription queries. Now, let's take a closer look at how these live updates actually work and what happens behind the scenes to provide you with this real-time data. Bitquery makes real-time data available using WebSockets. We use a specific WebSocket protocol called the "GraphQL WebSocket" to make sure you receive real-time updates. To get data in real-time for your application, you can connect to the following WebSocket endpoint: ``` wss://streaming.bitquery.io/graphql ``` For a **live DEX trades** subscription example (GraphQL document plus BSC/Solana links), see [How do I subscribe to live DEX trades using Bitquery WebSocket?](/docs/subscriptions/examples#how-do-i-subscribe-to-live-dex-trades-using-bitquery-websocket). ### Limits You are charged for the number of subscriptions (aka streams) and not for the number of websockets. Read more on pricing for streams [here](/docs/ide/points/#1-websocket-subscriptions-graphql) ### Data Handling It's important to note that for committed blocks, data will come in portions (by block), and for the mempool, data will come by transactions (or set of transactions). You do not have control over the sequence in which this data will arrive. Therefore, ensure your application is designed to handle data in this manner. **Websockets using Bitquery graphQL streams cannot send "close" messages, only way to end the subscription/stream is to close the websocket** ## Authorising Websockets Read [here](/docs/authorization/websocket/) on how to use websockets with OAuth. Here is the link to a Postman collection with samples demonstrating how to use the wss endpoint: > [Postman Collection for Examples](https://www.postman.com/interstellar-eclipse-270749/workspace/bitquery) Continue reading about how to create and use websockets in this [section](/docs/subscriptions/subscription/) ## Supported Standards GraphQL supports 2 standards to deliver the data updates: - `graphql-transport-ws` - `graphql-ws` Essentially they are the same and differ only in details. Typically you use a client library that already implements one of them — we support both. We adhere to the standard logic for ping, pong, and disconnect actions. Once the socket is open, the server sends a `ka` message if you're using `graphql-ws`, or a `pong` message if you're using `graphql-transport-ws`. This keeps the connection active and healthy. You can find examples of how to use it in your code [here](/docs/subscriptions/examples/) ## Why do I get a failed WebSocket connection error when converting query to subscription? **How to Fix "Failed WebSocket Connection" When Converting a Query to a Subscription** When switching from a regular GraphQL query to a WebSocket subscription in Bitquery, follow these steps: 1. **Change Operation Type** - If your GraphQL starts with `query`, replace it with `subscription`. - If it doesn’t have `query` written, simply add `subscription` before your operation. **Example:** ```graphql # Original Query query { EVM(network: bsc) { ... } } # Subscription Version subscription { EVM(network: bsc) { ... } } ``` 2. **Test the Query** - Make sure your query runs successfully as a query before converting to a subscription. - If the query is not valid, the subscription will not work. 3. **WebSocket Endpoint** - Use `wss://streaming.bitquery.io/graphql` for all streaming subscriptions. - Do _not_ use the standard HTTP GraphQL API endpoint. 4. **Authentication** - You must authenticate using OAuth or provide your Bitquery API token over the WebSocket connection. - See [WebSocket authorization guide](/docs/authorization/websocket/) for details. 5. **Subprotocol** - Your WebSocket client must support either `graphql-ws` or `graphql-transport-ws` subprotocols. - We support both standards. Refer to the [standards section above](#supported-standards) for client libraries and usage. 6. **Compatibility Caveats** - Some fields or dataset combinations supported in queries are *not* yet available via streaming subscriptions. - If you get “subscription not valid” errors, check [this guide](/docs/subscriptions/subscription/) or Bitquery v2 query docs for compatibility information. 7. **Error Diagnosis** - _Connection failed_ errors usually indicate a transport or authentication problem. - _Parse errors_ and messages like “subscription not valid” are due to GraphQL or unsupported operation/spec. If you continue having issues, please reach out for help in our Telegram community: [https://t.me/bloxy_info](https://t.me/bloxy_info) --- ## Bitquery in One Page — Complete Context for AI Assistants URL: https://docs.bitquery.io/docs/start/bitquery-for-ai/ A single self-contained page describing the Bitquery API: endpoints, chains, cubes, datasets, query rules and worked examples. Paste it into an AI assistant and it can write correct Bitquery queries without reading anything else. # Bitquery in One Page This page is written to be handed to an AI assistant. It is deliberately self-contained: no navigation, no links to click through, every query written out in full. Paste the whole page into a model's context and it has enough to write correct Bitquery queries, pick the right endpoint, and avoid the mistakes that produce silently wrong answers. If you are a human, this also works as a one-screen reference. --- ## 1. What Bitquery is Bitquery indexes blockchain data — trades, transfers, balances, holders, transactions, events, contract calls, mempool — and serves it as GraphQL. You do not run nodes. You send a GraphQL document over HTTP for historical questions, or over WebSocket for a live stream. There are two generations of the API and **they are different products with different schemas**. Choosing the wrong one is the single most common mistake. --- ## 2. Endpoints and authentication | Purpose | Endpoint | | --- | --- | | V2 queries | `https://streaming.bitquery.io/graphql` | | V2 subscriptions | `wss://streaming.bitquery.io/graphql` | | V1 queries | `https://graphql.bitquery.io` | Authentication is the same token on both: ``` Authorization: Bearer ory_at_YOUR_TOKEN Content-Type: application/json ``` For WebSocket, use the `graphql-transport-ws` (or `graphql-ws`) subprotocol and pass the token either as an `Authorization` header or as `?token=...` on the URL. Send `connection_init`, wait for `connection_ack`, then send `subscribe`. **Subscriptions only work over WebSocket.** Posting a `subscription` document to the HTTP endpoint returns `subscriptions must be sent over a websocket connection, not HTTP`. --- ## 3. Which chain lives on which API **V2 covers exactly these chains and no others.** - EVM root, `network:` argument — `eth`, `bsc`, `base`, `arbitrum`, `optimism`, `matic`, `robinhood`, `arc`, `arc_testnet` - `Solana` root — Solana - `Tron` root — Tron - `Hyperliquid` root — Hyperliquid's exchange (HyperCore): perpetuals, HIP-3 perpetuals, spot pairs and outcome markets - `Trading` root — cross-chain prices and trades, no `network` argument Arc mainnet uses `EVM(network: arc)`; Arc testnet uses `EVM(network: arc_testnet)`. Leave the dataset argument out on both unless a fresh probe confirms `archive` or `combined`. The mainnet also appears in the `Trading` cubes as network name `Arc` and network id `bid:arc`. **Everything else is V1 only**: Bitcoin, Litecoin, Bitcoin Cash, Dogecoin, Dash, Zcash, Cardano, Ripple, Stellar, Algorand, Filecoin, Avalanche, Celo, Fantom, Cronos, Klaytn. V1 groups chains under a shared root with a `network` argument: - `bitcoin(network: bitcoin | litecoin | bitcash | dogecoin | dash | zcash)` - `ethereum(network: avalanche | celo_mainnet | celo_rc1 | fantom | cronos | klaytn)` - `cardano(network: cardano)`, `ripple(network: ripple)`, `stellar(network: stellar)`, `algorand(network: algorand)`, `filecoin(network: filecoin)`, `solana(network: solana)`, `tron(network: tron)` **Ethereum, BSC and Polygon are no longer in V1**: the V1 schema rejects them. Tron is still in V1, but **always query Tron on V2**. **Root names carry the version.** V1 roots are lowercase — `ethereum(`, `tron(`, `solana(`, `bitcoin(`. V2 roots are capitalised — `EVM(`, `Tron(`, `Solana(`, `Hyperliquid(`, `Trading`. If you see a lowercase root, it is a V1 document and belongs on the V1 endpoint. **Streaming is a V2 feature.** V1's schema does expose a subscription root, but only `ethereum(network: ...)`, and there is no documented V1 WebSocket endpoint — use V2 for anything live. Chains that exist only on V1 and are not in the V1 EVM family — Bitcoin and its relatives, Cardano, Ripple, Stellar, Algorand — have no GraphQL stream at all. --- ## 4. The cubes — which one answers which question A "cube" is a top-level dataset. Picking the right cube matters more than writing clever filters. **`Trading` (cross-chain, no `network` argument)** — the primary source for prices and trades: - `Trading.Pairs` — OHLC and volume for one trading pair on one market. **Use this to price a single token**, with a rank filter (see §6). - `Trading.Tokens` — OHLC and volume for a token, blended across every pool it trades in. - `Trading.Currencies` — a currency across all of its token representations and chains. - `Trading.Trades` — individual normalised trades across chains. **`EVM(network: ...)`** — `Balances`, `Blocks`, `Calls`, `DEXPoolEvents`, `DEXPoolSlippages`, `DEXTradeByTokens`, `DEXTrades`, `Events`, `Holders`, `MinerRewards`, `PredictionManagements`, `PredictionSettlements`, `PredictionTrades`, `TransactionBalances`, `Transactions`, `Transfers`, `Uncles`. **`Solana`** — `Blocks`, `DEXOrders`, `DEXPools`, `DEXTradeByTokens`, `DEXTrades`, `Instructions`, `PerpetualFills`, `PerpetualMarketSummaries`, `PerpetualOrders`, `PerpetualPositions`, `PerpetualPrices`, `Rewards`, `TokenSupplyUpdates`, `Transactions`, `Transfers`. Note: **Solana has no `Balances` cube.** Solana balances are derived from `Transfers`. **`Hyperliquid`** (`network: hyperliquid`, the default) — `BookUpdates`, `Candles`, `CurrentPositions`, `MarkPrices`, `Orders`, `PerpFundings`, `PerpLiquidations`, `PriceUpdates`, `SignedActions`, `TraderLeverageUpdates`, `Trades`, `Twaps`. Every market kind shares these cubes, and the market id is `Market.CoinRaw` (`BTC`, `xyz:NFLX`, `@107`), not `Symbol`. A fill is two rows, maker and taker, in `Trades` and in `PerpLiquidations`; inside a block, order fills by `Execution.Index`, never by `Tid`. Quick map from question to cube: | Question | Cube | | --- | --- | | What is this token worth right now? | `Trading.Pairs` with rank 1 | | Candles for a chart | `Trading.Pairs` (recent) or `DEXTradeByTokens` (older) | | Every swap on a chain | `EVM.DEXTrades` / `Solana.DEXTrades` | | Swaps grouped per token | `DEXTradeByTokens` | | Who holds this token | `EVM.Holders` | | What does this wallet hold | `EVM.Balances` | | Token movements | `Transfers` | | Raw transactions | `Transactions` | | Decoded logs / contract calls | `Events` / `Calls` | | Pool reserves, liquidity events | `DEXPoolEvents`, `DEXPools` | | Pending, not yet mined | any EVM cube with `mempool: true` | --- ## 5. Datasets and how far back data goes Every V2 root takes a `dataset` argument: - `realtime` — the recent window. This is the **default** if you omit `dataset`. - `archive` — deep history. - `combined` — archive and realtime stitched together. Retention on `realtime` is short and differs per cube: roughly 12 hours on Solana `DEXTrades`, about 7 days on Solana `DEXTradeByTokens`, a few days on EVM DEX and transfer cubes, and about 30 days on the `Trading` cubes. Hyperliquid has `realtime` only: about 30 days of trades, funding, liquidations and candles, about 7 days of `Orders`, `BookUpdates` and `SignedActions`. Two things about this cause most "the data is wrong" reports: 1. **`realtime` does not error when you ask beyond its window. It silently returns fewer rows.** A chart just starts late. Always check whether the window you asked for is inside retention. 2. **`archive` and `combined` are not deployed for every cube on every chain.** When they are not, you get a ClickHouse error like `no table can query ... consider use realtime dataset`. That is not a bug in your query, it means that table does not exist for that chain. Self-serve plans query `realtime`. Querying `archive` or `combined` needs the historical data add-on on the plan. For bulk history beyond the API, use a [Data Store export](https://bitquery.io/datastore). For raw blocks, use the [Data Lake](/docs/data-lake/). --- ## 6. Rules that keep answers correct These are the mistakes that produce a plausible-looking wrong number rather than an error. **Price one token with `Pairs` and rank 1, not with `Tokens`.** The `Tokens` price is volume-weighted across every pool, so a thin pool drags it away from the real market. Add `Ranking: {Position: {eq: 1}}` to take the token's top market only. Always pair it with `Price: {IsQuotedInUsd: true}` — the rank filter picks the market, not the denomination. **In the `Trading` cube, token addresses are stored lowercase and the filter is case-sensitive.** A checksummed EVM address returns **zero rows and no error**. Lowercase every address you put in a `Trading` filter. **Balances are cumulative, so they cannot be answered from `realtime` alone.** A balance read from the realtime window is the change over the last few hours, not the balance. Use `archive` or `combined` for anything balance- or holder-shaped. The same applies to holder counts, token ownership and net worth. **Use the `Trading` cube for recent data and `DEXTradeByTokens` for older.** The `Trading` cubes cover roughly the last 30 days. Beyond that, rebuild the same numbers from raw trades with `DEXTradeByTokens`. **A bare `EVM` root means Ethereum.** `EVM { ... }` without a `network` argument returns Ethereum data. Be explicit. **On V1, always bound a list query by date.** V1 sorts the whole table otherwise and the query dies with ClickHouse `Code: 241, memory limit exceeded`. V1 has no relative-date filter, so pass the date as a variable and move it as needed. **Solana `combined` works on `DEXTrades` and `DEXTradeByTokens` only.** The other Solana cubes have no archive or combined dataset. On `DEXTrades`, archive and combined need a `Block.Time`, `Block.Slot` or `Block.Date` bound and lists should be ordered by `Block_Slot`, not `Block_Time`. **On EVM and Tron, use `Balances` for current balances and `Holders` for holder rankings.** Both are query-only; for live balance changes use `TransactionBalances` or `Transfers`. On Solana, use `Solana.BalanceUpdates`. **Always filter `Interval.Time.Duration` on `Tokens` / `Pairs` / `Currencies`.** The cube stores ten bar durations simultaneously (1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600 seconds). Omitting the filter returns one row per duration and inflates any aggregate roughly **ten-fold**. An unsupported value returns `[]` with HTTP 200 and no error, so a typo looks like "no data". **On `Trading.Trades`, use `AmountsInUsd.Quote` for USD, not `.Base`.** `.Base` is `Amounts.Base x PriceInUsd`, and `PriceInUsd` is a smoothed reference price rather than the executed one, so it diverges on fast-moving tokens. **`Trading.Trades` emits some exact duplicate rows.** Deduplicate on `(TransactionHeader.Hash, Trader.Address, Side, Amounts.Base)` before reporting exact trade counts or volumes. A row is one **step** of a swap, not a transaction — count distinct tx hashes. **Network filters take the API's display names, case-sensitively.** Polygon is `"Matic"` and BSC is `"Binance Smart Chain"`. A wrong value returns zero rows and no error. **`maximum:` / `minimum:` are argmax, not max.** `Field(maximum: Key)` returns `Field`'s value on the row where `Key` is largest. Selectors sharing one key come from the same row; mixing keys silently composes a row that never existed. **The Trading cube has no liquidity, reserves or TVL.** No field, nothing in the filter surface. Pool depth comes from chain-level `DEXPools` (about 12 hours of history) or a cloud export. --- ## 7. Answering questions about a whole population The most common mistake when planning a large analysis is assuming you need one query per token or per wallet. You do not. `limitBy` returns **one row per entity across the entire filtered population** — not a top-N sample: ```graphql { Trading { Tokens( where: { Token: { Network: { is: "Solana" } } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since: "...", till: "..." } } } limit: { count: 25000, offset: 0 } limitBy: { by: Token_Id, count: 1 } ) { Token { Id Symbol } first: Price { Ohlc { Open(minimum: Block_Time) } } peak: Price { Ohlc { High(maximum: Price_Ohlc_High) } } Volume { Usd } Supply { MarketCap } } } } ``` One request covers every token on the chain for that hour. Page with `limit: {count: 25000, offset: N}` and **always supply `orderBy`** — offset paging without a sort order silently duplicates and drops rows. **Filter on computed aggregates server-side** with `selectWhere`, the cube's `HAVING`: ```graphql vol: sum(of: Volume_Usd, selectWhere: { gt: "1000000" }) ``` The pipeline is `where → GROUP BY → selectWhere → orderBy → limitBy → limit`. Attach `selectWhere` to a metric — on a bare leaf field it is a **silent no-op**. **What cannot be expressed server-side:** a window defined *relative to each row's own* event — "the 4th to 24th hour after each token's own first trade", for example. GraphQL filters absolute time ranges only. Pull per-interval rows for the whole population, then compute relative windows in your own store. That is a handful of requests, not one per token. Also unavailable server-side: HAVING on a ratio, `in`/`notIn` on aggregates, and anything on a subscription — streams drop `selectWhere`, `if` and most statistics. See [Query Operators](/docs/trading/query-operators/selectwhere-screeners/) for the full surface, including concentration statistics and wallet-overlap. --- ## 8. Worked examples Every query below was executed against the live API before being written down. ### Price of one token, from its top market ```graphql query ($token: String!, $network: String!) { Trading { Pairs( where: { Token: { Address: { is: $token }, Network: { is: $network } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 60 } } } Price: { IsQuotedInUsd: true } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Token { Symbol Name Address Network } QuoteToken { Symbol Address } Market { Name Address } Price { Ohlc { Open High Low Close } Average { Mean } IsQuotedInUsd } Volume { Usd Base Quote } Block { Time } } } } ``` Variables — note the lowercase address: ```json { "token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "network": "Ethereum" } ``` `Network` accepts `Ethereum`, `Base`, `Binance Smart Chain`, `Arbitrum`, `Optimism`, `Solana`. ### Latest DEX trades for a token on an EVM chain ```graphql { EVM(network: eth) { DEXTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } } ) { Block { Time } Transaction { Hash } Trade { Dex { ProtocolName ProtocolFamily } Buy { Amount Currency { Symbol SmartContract } Buyer } Sell { Amount Currency { Symbol SmartContract } } } } } } ``` ### What a wallet holds Balances are cumulative, so this uses `combined`: ```graphql query ($address: String!) { EVM(network: eth, dataset: combined) { Balances(where: { Balance: { Address: { is: $address } } }) { Currency { Symbol Name SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` ### Token transfers for a wallet ```graphql { EVM(network: eth) { Transfers( limit: { count: 25 } orderBy: { descending: Block_Time } where: { Transfer: { Sender: { is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549" } } } ) { Block { Time } Transaction { Hash } Transfer { Amount Currency { Symbol SmartContract } Sender Receiver } } } } ``` ### Solana trades for a token ```graphql { Solana { DEXTradeByTokens( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } ) { Block { Time } Trade { Currency { Symbol MintAddress } Side { Currency { Symbol MintAddress } } Dex { ProtocolName } Price PriceInUSD Amount } } } } ``` ### A live stream Same document shape, `subscription` instead of `query`, sent over WebSocket: ```graphql subscription { EVM(network: eth) { DEXTrades { Block { Time } Trade { Dex { ProtocolName } Buy { Amount Currency { Symbol } } Sell { Amount Currency { Symbol } } } } } } ``` ### A V1 chain — Bitcoin and its relatives ```graphql { bitcoin(network: dogecoin) { blocks(options: { limit: 10, desc: "height" }) { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } transactionCount } } } ``` Balance of a V1 UTXO address as of a date — received minus spent: ```graphql query ($address: String!, $asof: ISO8601DateTime) { bitcoin(network: bitcoin) { received: outputs(outputAddress: { is: $address }, date: { till: $asof }) { value(calculate: sum) count } spent: inputs(inputAddress: { is: $address }, date: { till: $asof }) { value(calculate: sum) count } } } ``` ### Pending transactions, before they are mined ```graphql { EVM(mempool: true, network: eth) { Transfers(limit: { count: 10 }) { Transaction { Hash From To } Transfer { Amount Currency { Symbol } Sender Receiver } } } } ``` --- ## 9. Errors and what they actually mean | Message | Meaning | | --- | --- | | `subscriptions must be sent over a websocket connection, not HTTP` | Send the document to `wss://streaming.bitquery.io/graphql` instead. | | `no table can query ... consider use realtime dataset` | `archive`/`combined` is not deployed for that cube on that chain. | | `access restricted: your plan only allows "realtime"` | The query asked for `archive` or `combined`; the plan needs the historical data add-on. | | `402 No active billing period` | No active plan or points on the account. | | `Code: 241 ... memory limit exceeded` | A V1 list query with no date bound. Add one. | | `context deadline exceeded` | The server gave up. Narrow the filter or the time window. | | Zero rows, no error | Either the window is outside `realtime` retention, or a `Trading` address filter was not lowercase. | --- ## 10. Choosing quickly 1. Is the chain on V2? If not, use V1 and expect no subscriptions. 2. Is the question about price? Use `Trading.Pairs` with rank 1. 3. Is it about balances, holders or ownership? Use `archive`/`combined` — never `realtime`. 4. Is it older than about 30 days? Use `DEXTradeByTokens`, not the `Trading` cubes. 5. Does it need to be live? Same document, `subscription`, over WebSocket. --- ## Blockchain Address Lookup API: Balance, Transfers and Activity for Any Address URL: https://docs.bitquery.io/docs/examples/address-lookup-api/ Blockchain address lookup API: get the balance, latest transfers in and out, first and last activity and token holdings of any wallet address on Ethereum, Tron, BSC, Base, Solana or Bitcoin with one GraphQL query, or ask the Bitquery MCP in plain English. # Blockchain Address Lookup API: Balance, Transfers and Activity for Any Address A blockchain address lookup answers four questions about a wallet: what it holds now, what it sent and received lately, when it was first and last active, and which tokens it owns. This page answers each question with one GraphQL query on Ethereum (an EVM chain) and on Tron. The same queries work on every EVM network Bitquery supports by changing `network`, and the [per-chain pages](#address-pages-for-other-chains) cover the rest. To ask the same questions in plain English, use the [Bitquery MCP](#look-up-an-address-in-plain-english-with-the-mcp). The examples use two well-known addresses: - Ethereum: `0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045` (vitalik.eth). - Tron: `TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv` (an OKX hot wallet). Replace them with the address you want to look up. Every query runs on the [v2 endpoint](/docs/start/endpoints/) `https://streaming.bitquery.io/graphql`. Balances and activity times come from the [`Balances` cube](/docs/cubes/balances-cube/), which stores the current state per address and currency, so the lookup is fast even for addresses with years of history. `dataset: combined` merges the realtime and archive data, so an address that has been quiet for years is found too. ## Current balance of an address The native coin balance (ETH on Ethereum, TRX on Tron) is the `Balances` row with `Currency: { Native: true }`. `AmountInUSD` gives its value in USD. ### Ethereum [Run this query in the IDE](https://ide.bitquery.io/ethereum-address-native-eth-balance) ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } Currency: { Native: true } } ) { Currency { Name Symbol Native } Balance { Address Amount AmountInUSD } } } } ``` ### Tron [Run this query in the IDE](https://ide.bitquery.io/tron-address-native-trx-balance) ```graphql query { Tron(dataset: combined) { Balances( where: { Balance: { Address: { is: "TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv" } } Currency: { Native: true } } ) { Currency { Name Symbol Native } Balance { Address Amount AmountInUSD } } } } ``` For the balance of one token, replace `Native: true` with `SmartContract: { is: "" }`. For the balance on a past date, see [Balance on a Specific Date](/docs/blockchain/Ethereum/balances/balance-api/#balance-on-a-specific-date). ## Latest transfers in and out Two aliases on the [`Transfers` cube](/docs/cubes/transfers-cube/) return the latest outgoing (`sent`) and incoming (`received`) transfers of the address in one request, native coin and tokens together. Each row has the time, the transaction hash, the counterparty, the amount, its USD value and the currency. The queries read the last 3 days of the realtime dataset; for older transfers add `dataset: combined` and set the time window you need. ### Ethereum [Run this query in the IDE](https://ide.bitquery.io/ethereum-address-latest-transfers-in-and-out) ```graphql query { EVM(network: eth) { sent: Transfers( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Transfer: { Sender: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } Block: { Time: { since_relative: { days_ago: 3 } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Transfer { Receiver Amount AmountInUSD Currency { Symbol SmartContract } } } received: Transfers( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Transfer: { Receiver: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } Block: { Time: { since_relative: { days_ago: 3 } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Transfer { Sender Amount AmountInUSD Currency { Symbol SmartContract } } } } } ``` ### Tron [Run this query in the IDE](https://ide.bitquery.io/tron-address-latest-transfers-in-and-out) ```graphql query { Tron { sent: Transfers( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Transfer: { Sender: { is: "TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv" } } Block: { Time: { since_relative: { days_ago: 3 } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Transfer { Receiver Amount AmountInUSD Currency { Symbol SmartContract } } } received: Transfers( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Transfer: { Receiver: { is: "TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv" } } Block: { Time: { since_relative: { days_ago: 3 } } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Transfer { Sender Amount AmountInUSD Currency { Symbol SmartContract } } } } } ``` To follow new transfers live, turn the query into a `subscription` and drop `limit`, `orderBy` and the time filter. More filters (one token, minimum amount, counterparty) are on the [ERC20 Token Transfers API](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api/) and [Tron Transfers API](/docs/blockchain/Tron/tron-transfers/) pages. ## First and last activity Every `Balances` row carries `FirstChangeTime` and `LastChangeTime`: the first and the latest time that currency's balance changed at the address. Sorting the rows by them gives the address's first activity (`first_activity`, usually the first deposit) and its latest activity (`last_activity`) in one request, with the currency that moved. ### Ethereum [Run this query in the IDE](https://ide.bitquery.io/ethereum-address-first-and-last-activity) ```graphql query { EVM(network: eth, dataset: combined) { first_activity: Balances( limit: { count: 1 } orderBy: { ascending: Balance_FirstChangeTime } where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } } ) { Currency { Symbol SmartContract } Balance { FirstChangeTime } } last_activity: Balances( limit: { count: 1 } orderBy: { descending: Balance_LastChangeTime } where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } } ) { Currency { Symbol SmartContract } Balance { LastChangeTime } } } } ``` ### Tron [Run this query in the IDE](https://ide.bitquery.io/tron-address-first-and-last-activity) ```graphql query { Tron(dataset: combined) { first_activity: Balances( limit: { count: 1 } orderBy: { ascending: Balance_FirstChangeTime } where: { Balance: { Address: { is: "TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv" } } } ) { Currency { Symbol SmartContract } Balance { FirstChangeTime } } last_activity: Balances( limit: { count: 1 } orderBy: { descending: Balance_LastChangeTime } where: { Balance: { Address: { is: "TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv" } } } ) { Currency { Symbol SmartContract } Balance { LastChangeTime } } } } ``` Add `UpdateCount` to `Balance` to see how many times each currency's balance changed at the address. ## Token holdings of an address Without a `Currency` filter, `Balances` returns one row per token the address holds. `Amount(selectWhere: { gt: "0" })` drops tokens it no longer holds, and ordering by `Balance_AmountInUSD` puts the largest positions first. ### Ethereum [Run this query in the IDE](https://ide.bitquery.io/ethereum-wallet-token-holdings) ```graphql query { EVM(network: eth, dataset: combined) { Balances( limit: { count: 20 } orderBy: { descending: Balance_AmountInUSD } where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } } ) { Currency { Name Symbol SmartContract Native } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` ### Tron [Run this query in the IDE](https://ide.bitquery.io/tron-wallet-token-holdings) ```graphql query { Tron(dataset: combined) { Balances( limit: { count: 20 } orderBy: { descending: Balance_AmountInUSD } where: { Balance: { Address: { is: "TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv" } } } ) { Currency { Name Symbol SmartContract Native } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` Anyone can send a token to any address, so a wallet's holdings often include airdropped spam tokens with a USD value. Check the `SmartContract` of a token before you trust its symbol. For NFT holdings, add `Currency: { Fungible: false }` (see [NFTs Tracking Across Chains](/docs/examples/cross-chain/cross-chain-api/)). ## Look up one address on several EVM chains An EVM address is the same on every EVM chain, so one request with GraphQL aliases looks it up on Ethereum, BSC, Base and Arbitrum at once. This query returns the native coin balance and the time it last changed on each chain. [Run this query in the IDE](https://ide.bitquery.io/evm-address-native-balance-on-ethereum-bsc-base-arbitrum) ```graphql query { ethereum: EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } Currency: { Native: true } } ) { Currency { Symbol } Balance { Amount AmountInUSD LastChangeTime } } } bsc: EVM(network: bsc, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } Currency: { Native: true } } ) { Currency { Symbol } Balance { Amount AmountInUSD LastChangeTime } } } base: EVM(network: base, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } Currency: { Native: true } } ) { Currency { Symbol } Balance { Amount AmountInUSD LastChangeTime } } } arbitrum: EVM(network: arbitrum, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } } Currency: { Native: true } } ) { Currency { Symbol } Balance { Amount AmountInUSD LastChangeTime } } } } ``` ## Address pages for other chains Each chain has its own page with more address queries (balance history, balance on a date, balance updates, transfers): | Chain | Balance and holdings | Transfers | | --- | --- | --- | | Ethereum | [Ethereum Balance API](/docs/blockchain/Ethereum/balances/balance-api/) | [ERC20 Token Transfers API](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api/) | | BSC | [BSC Balance API](/docs/blockchain/BSC/bsc-balance-updates/) | [BSC Transfers API](/docs/blockchain/BSC/bsc-transfers/) | | Base | [Base Address Balance API](/docs/blockchain/Base/base-balance-updates/) | [Base Transfers API](/docs/blockchain/Base/base-transfers/) | | Solana | [Solana Balances and Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/) | [Solana Transfers API](/docs/blockchain/Solana/solana-transfers/) | | Tron | [Tron Address Balance API](/docs/blockchain/Tron/tron-balance-updates/) | [Tron Transfers API](/docs/blockchain/Tron/tron-transfers/) | | Bitcoin | [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api/) | [Bitcoin Address API](/docs/blockchain/Bitcoin/bitcoin-address-api/) | Solana has no `Balances` cube: its balances come from `Solana.BalanceUpdates`, shown on the Solana page. ## Look up an address in plain English with the MCP The [Bitquery MCP server](/docs/mcp/mcp-server/) lets an AI client such as Claude, ChatGPT or Cursor answer "who is this address and what has it done" without writing a query. Three groups of tools do the address lookup: | Tool | What it answers | Inputs | | --- | --- | --- | | `labels_for_addresses` | Who owns a list of addresses: exchange deposit or hot wallet, mixer, scam, sanctioned entity and other labels | `addresses` (required; separated by commas, pipes, spaces or new lines), `chain` (leave empty to search every chain), `label_type`, `limit` (default 200, up to 10000) | | `address_labels` | Every label of one address, wallet or token contract | `address` (required), `chain` (leave empty to search every chain) | | `address_risk_report` | An AML risk score from 0 to 100 for a Tron, Bitcoin or Ethereum address, with the labelled entities it received from and sent to and its exposure by entity type | `chain` and `address` (required), `asset`, `after_time`, `before_time`, `direction` (`both`, `received`, `sent`), `view` (`all` or `direct`), `max_hops` (1 to 6, default 2), `min_amount_usd` (default 100), `weights`, `format` (`markdown` or `json`) | | `_address_profile` | Transfer counts in and out, distinct senders and receivers, and first and last activity of one address | See the table below | `labels_for_addresses` returns one row per labelled address with `Labels` (each written as `chain/label_type:label_value`), `Label_Types`, `Sources`, `Source_Count` and `Status`. An address that is missing from the answer has no label; when none of the addresses has one, the answer is a single row with `Status` `NO_LABELS_FOUND`. `address_risk_report` adds a band to the score (none at 0, low below 25, medium 25 to 49, elevated 50 to 74, high 75 and up). Its `view: all` traces funds up to `max_hops` hops on Tron; on Bitcoin and Ethereum the report is the direct view. ### The address profile tools by chain The address profile tools share the `address` and `format` (`rows` or `columnar`) inputs and differ in the period they cover and the filters they take: | Tools | Chains | Period | Filters | Returns | | --- | --- | --- | --- | --- | | `eth_address_profile`, `bsc_address_profile`, `base_address_profile`, `arbitrum_address_profile`, `optimism_address_profile`, `matic_address_profile`, `robinhood_address_profile` | Ethereum, BSC, Base, Arbitrum, Optimism, Polygon, Robinhood Chain | Whole history, or `after_time` / `before_time` | `contract` or `currency` (one token), `include_internal` (0 by default; 1 also counts native coin moved by contract code inside a transaction) | `Sent_Transfers`, `Received_Transfers`, `Distinct_Receivers`, `Distinct_Senders`, `First_Sent`, `Last_Sent`, `First_Received`, `Last_Received`; `Sent_Amount` and `Received_Amount` when one token is set | | `arc_address_profile` | Arc | Whole history, or `after_time` / `before_time` | `contract`, `currency`, `asset_type` (`all`, `native`, `token`, `usdc`), `include_internal` (1 by default) | Same as the EVM tools, plus `Sent_Assets` and `Received_Assets` | | `tron_address_profile` | Tron | Whole history, or `after_time` / `before_time` | `contract` or `currency` | Same as the EVM tools | | `solana_address_profile` | Solana | Last `days` days (default 90, up to 20000) | None | `Window_Days`, `Window_From`, `Sent_Transfers`, `Received_Transfers`, `Distinct_Receivers`, `Distinct_Senders` | | `xrp_address_profile` | XRP Ledger | Last `days` days (default 90, up to 20000) | None | Payments sent and received, distinct receivers and senders, destination tags, other value records, filled offers, transactions signed, fees paid in XRP, first and last activity | | `xlm_address_profile` | Stellar | Last `days` days (default 90, up to 20000) | None | Payments sent and received, distinct receivers and senders, accounts created, claimable balances, filled offers, transactions signed, fees paid in XLM, first and last activity, `Created_By` | | `btc_address_profile`, `bch_address_profile`, `ltc_address_profile`, `doge_address_profile`, `dash_address_profile`, `zec_address_profile` | Bitcoin, Bitcoin Cash, Litecoin, Dogecoin, Dash, Zcash (transparent addresses) | Whole history | None | Total received and sent in the chain's coin (received minus sent is the balance), distinct senders and receivers, receiving and spending counts, first and last activity | | `ada_address_profile` | Cardano | Whole history | `currency` (`ADA` by default; empty lists every asset), `limit` (default 20, up to 500) | One row per asset: received, sent and current balance, output and transaction counts, first and last activity, address type, `Is_Script`, `Stake_Key`, distinct senders and receivers | Example prompts: - "Look up `0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045`: first and last activity on Ethereum, and who it sends to." - "Who owns these Tron addresses? `TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv`, `TU4vEruvZwLLkSfV9bNw12EJTPvNr7Pvaa`" - "Give me a risk report for this Tron address." More on these tools: [Counterparties](/docs/mcp/counterparties/), [Holders and balances](/docs/mcp/holders-balances/), [Tracing MCP](/docs/mcp/Tracing/overview/) and [Solana MCP](/docs/mcp/solana/). --- ## Blockchain Data APIs Overview URL: https://docs.bitquery.io/docs/blockchain/introduction/ Which Bitquery API serves each blockchain, with links to the chain guides for V2 real-time data, V1 history, Kafka streams and cloud datasets. # Blockchain Data APIs Bitquery provides real-time and historical access to data across **40+ blockchains** including Bitcoin, Ethereum, Solana, BSC, Arbitrum, Base, Polygon, Tron and Arc. Thousands of developers use the APIs for DeFi apps, trading tools, analytics dashboards and blockchain infrastructure. ## Why Choose Bitquery's Blockchain Data APIs? Unlike traditional blockchain RPC providers that offer raw node data, Bitquery provides **pre-indexed, enriched, and analytics-ready** blockchain data through multiple interfaces: - **Real-time Streaming**: Live data via GraphQL subscriptions, gRPC and Kafka streams - **Pre-computed Analytics**: Real-time OHLC with 1-second aggregation, moving averages, volume metrics, and more - **Cross-chain Aggregation**: Unified view of tokens and currencies across chains - **High Performance**: Sub-second response times for complex queries - **Developer-Friendly**: GraphQL interface with comprehensive documentation ## Supported Blockchains **[Supported blockchains & networks (V1, V2, Kafka, gRPC, ClickHouse, cloud) →](/docs/blockchain/supported-chains/)** — See a single matrix of which chains are covered per interface (GraphQL versions, Kafka, CoreCast, ClickHouse warehouse, Parquet/datashares). Bitquery provides comprehensive blockchain data across **40+ blockchains** through two active API versions: ### **V2 APIs** Our V2 API version with enhanced features and real-time streaming: **EVM-Compatible Chains:** - **[Ethereum](/docs/blockchain/Ethereum/)** - **[BSC (Binance Smart Chain)](/docs/blockchain/BSC/)** - **[Arbitrum](/docs/blockchain/Arbitrum/)** - **[Base](/docs/blockchain/Base/)** - **[Polygon](/docs/blockchain/Matic/)** - **[Optimism](/docs/blockchain/Optimism/)** - **[Robinhood](/docs/blockchain/robinhood/)** - **[Arc Blockchain API](https://bitquery.io/blockchains/arc-blockchain-api)** (Circle Arc; live queries and WebSocket streams) - **[Arc Testnet](/docs/blockchain/arc-testnet/)** (Circle Arc, testnet; realtime dataset only) **Non-EVM Chains:** - **[Solana](/docs/blockchain/Solana/)** - **[Tron](/docs/blockchain/Tron/)** - **[Hyperliquid](/docs/perpetuals/hyperliquid/)** (HyperCore: perpetuals including HIP-3, spot and outcome markets) ### **V1 APIs** Our V1 API historically covered 40+ blockchains. Today it serves historical data for: **Supported Blockchains:** [Bitcoin](/docs/blockchain/Bitcoin/), Bitcoin Cash, Litecoin, Dash, Dogecoin, Zcash, Avalanche, Klaytn, Celo, Cronos, Tron, Solana, [Algorand](/docs/blockchain/Algorand/), [Cardano](/docs/blockchain/Cardano/), Filecoin, Ripple (XRP) and Stellar. Ethereum, BSC and Polygon are no longer in V1; query them through V2. **Documentation:** - **[Supported chains by interface](/docs/blockchain/supported-chains/)** — Coverage matrix: V1/V2, Kafka, gRPC, ClickHouse, cloud - **[V2 Documentation](/docs/intro/)** - Latest APIs with real-time streaming - **[V1 Documentation](https://docs.bitquery.io/v1/)** - APIs for the V1 chains above (historically 40+ blockchains) ## Bitquery's Core Blockchain Data Capabilities **Popular APIs:** [Arc Blockchain API](https://bitquery.io/blockchains/arc-blockchain-api) · [Solana API](/docs/blockchain/Solana/) (DEX trades, Pump.fun, Raydium) · [Polymarket API](/docs/examples/polymarket-api/) · [BSC API](/docs/blockchain/BSC/) · [Base API](/docs/blockchain/Base/) · [DEX API](/docs/blockchain/Ethereum/dextrades/dex-api) · [Crypto Price API](/docs/trading/crypto-price-api/) ### **Crypto Price API - Real-Time Multi-Chain Price Data** Bitquery's dedicated **[Crypto Price API](/docs/trading/crypto-price-api/)** provides real-time, aggregated cryptocurrency price data with ultra-low latency across multiple blockchains. This specialized API is designed specifically for trading applications, DeFi protocols, and financial analytics. **Key Features:** - **Real-time Streaming**: 1-second granularity via GraphQL subscriptions and Kafka streams - **Pre-aggregated Data**: OHLC, SMA, WMA, EMA, and mean prices calculated automatically - **Multi-chain Support**: Ethereum, Solana, BSC, Arbitrum, Base, Optimism, Polygon, and more - **Clean Data**: Automatic filtering of low-quality trades and outliers - **Cross-chain Aggregation**: Unified view of token prices across multiple ecosystems - **Three Data Cubes**: Tokens (chain-specific), Currencies (cross-chain), and Pairs (market-specific) - **TradingView Integration**: Ready-to-chart SDK for real-time price feeds **Available Endpoints:** - **Streaming Endpoint**: Real-time data via WebSocket subscriptions - **Kafka Topic**: `trading.prices` for high-volume streaming applications ### **Trading & DeFi Data** - **DEX Trades**: Real-time and historical trading data across all major DEXs - **Price Data**: Real-time OHLC, moving averages, volume metrics with 1-second aggregation that updates consistently as trades come in - **Liquidity Events**: Pool creation, liquidity additions/removals - **Cross-chain Arbitrage**: Price differences across chains and DEXs ### **Token & Balance Data** - **Token Transfers**: ERC-20, ERC-721, ERC-1155, SPL, TRC-20 transfers - **Balance Updates**: Real-time wallet balance changes - **Token Holders**: Distribution analysis and holder tracking - **Token Supply**: Circulating supply, total supply, and burn events ### **Smart Contract Data** - **Contract Events**: Decoded smart contract events and logs - **Contract Calls**: Detailed contract interaction data - **Contract Creation**: New contract deployments - **Gas Analytics**: Fee analysis and optimization insights ### **Block & Transaction Data** - **Block Information**: Headers, timestamps, gas usage, miner data - **Transaction Details**: Complete transaction data with receipts - **Mempool Monitoring**: Pending transactions and fee estimation - **Network Statistics**: Block production, network health metrics ### **NFT Data** - **NFT Transfers**: Ownership changes and marketplace trades - **Collection Analytics**: Floor prices, volume, holder distributions - **Metadata**: Token attributes, images, and rarity information - **Marketplace Integration**: OpenSea, LooksRare, and other platforms ### **Stablecoin APIs - Specialized Payment Infrastructure** Bitquery provides dedicated **[Stablecoin APIs](/docs/category/stablecoin-apis/)** for comprehensive stablecoin data across multiple blockchains, designed specifically for payment applications, compliance, and financial analytics. **Key Features:** - **Real-time Price Monitoring**: Track stablecoin [price deviations](/docs/stablecoin-APIs/stablecoin-price-api/) and arbitrage opportunities - **Payment Detection**: Instant identification of incoming [stablecoin transfers](/docs/stablecoin-APIs/stablecoin-payments-api/) - **Multi-chain Support**: USDT, USDC, DAI, and other stablecoins across all supported chains - **Compliance Tools**: AML/KYC support with transaction monitoring - **Cross-chain Analytics**: Unified view of stablecoin movements across ecosystems **Available APIs:** - **[Stablecoin Price API](/docs/stablecoin-APIs/stablecoin-price-api/)** - Real-time price tracking and deviation monitoring - **[Stablecoin Payments API](/docs/stablecoin-APIs/stablecoin-payments-api/)** - Payment detection and compliance tools - **[Stablecoin Trades API](/docs/stablecoin-APIs/stablecoin-trades-api/)** - Trading data and volume analytics - **USDT API** - Specialized Tether data across all chains ### **Mempool Monitoring - Pre-Confirmation Data** Access real-time data from the mempool before transactions are confirmed, enabling advanced trading strategies and MEV detection. **Key Features:** - **Pre-confirmation Visibility**: See transactions before they're included in blocks - **MEV Detection**: Identify arbitrage opportunities and sandwich attacks - **Fee Estimation**: Real-time gas price recommendations and market analysis - **Transaction Simulation**: Test transaction success before broadcasting - **Cross-chain Mempool**: Monitor pending transactions across multiple chains **Available Endpoints:** - **Ethereum Mempool**: Real-time pending transactions and events - **BSC Mempool**: High-speed mempool monitoring for Binance Smart Chain - **Tron Mempool**: TRX network pending transaction tracking - **Kafka Mempool Streams**: Ultra-low latency mempool data via Protocol Buffers **Learn More:** [Mempool Subscriptions](/docs/subscriptions/mempool-subscriptions/) ### **Advanced Features & Enterprise Capabilities** **Backfilling & Historical Data Recovery:** - **Gap-free Data**: Automatic backfilling of missing data during connection interruptions - **Historical Recovery**: Retrieve data from any point in blockchain history - **One application, both views**: Combine historical and real-time data in a single app **Connection Management:** - **Silent Disconnect/Reconnect**: Automatic connection recovery for production applications - **Connection Pooling**: Efficient resource management for high-volume applications - **Load Balancing**: Automatic traffic distribution across multiple endpoints **Advanced Analytics:** - **Custom Aggregations**: Build sophisticated analytics with custom time windows and metrics - **Cross-chain Analytics**: Unified analytics across multiple blockchain ecosystems **Learn More:** [Advanced Features](/docs/subscriptions/backfilling-subscription/) ## Developer Interfaces ### **GraphQL API** Our primary interface for querying blockchain data with powerful filtering, aggregation, and real-time capabilities. The GraphQL API provides a flexible, type-safe way to query exactly the data you need. **Key Features:** - **Type-safe queries** with comprehensive schema documentation - **Powerful filtering** with complex where clauses and nested conditions - **Aggregation support** for time-series data and statistical analysis - **Join capabilities** across different data types (transactions, events, transfers) - **Pagination** with cursor-based and offset-based options - **Field selection** - request only the data you need to optimize performance **Endpoints:** - **V2 Primary Endpoint**: `https://streaming.bitquery.io/graphql` - **V1 Endpoint**: `https://graphql.bitquery.io/` (for comprehensive blockchain support) ```graphql { EVM(network: eth) { DEXTrades( where: { Block: {Time: {after: "2024-01-01"}} Trade: {Amount: {gt: "1000"}} } limit: {count: 10} orderBy: {descending: Block_Time} ) { Block { Time Number } Transaction { Hash From To } Trade { Amount Price BuyAmount SellAmount } Protocol { Name Type } Currency { Symbol Name } } } } ``` **Advanced Query Features:** - **Nested filtering**: Filter by multiple criteria across related entities - **Time-based queries**: Query by specific time ranges, intervals, or relative periods - **Cross-chain queries**: Query data across multiple blockchains in a single request - **Expression support**: Use mathematical expressions and calculations in queries - **Custom aggregations**: Group and aggregate data by any field or time interval ### **Real-time Subscriptions (WebSocket)** Convert any query to a live stream by changing `query` to `subscription`. Our WebSocket implementation provides real-time blockchain data with sub-second latency. **Learn More:** [WebSocket Subscriptions](/docs/subscriptions/websockets/) **WebSocket Features:** - **Protocol Support**: Both `graphql-ws` and `subscriptions-transport-ws` protocols - **Automatic Reconnection**: Built-in reconnection logic with exponential backoff - **Connection Management**: Handle multiple subscriptions on a single connection - **Error Handling**: Comprehensive error reporting and recovery mechanisms - **Authentication**: Secure token-based authentication for WebSocket connections A subscription receives each block's data as soon as it arrives in the stream. See [What triggers a subscription update](/docs/subscriptions/trigger/). **WebSocket Endpoint**: `wss://streaming.bitquery.io/graphql` ```graphql subscription { EVM(network: eth) { DEXTrades( where: { Trade: {Buy: {AmountInUSD: {gt: "10000"}}} TransactionStatus: {Success: true} } ) { Block { Time Number } Transaction { Hash From To } Trade { Buy { Amount AmountInUSD Currency { Symbol Name } } Sell { Amount AmountInUSD Currency { Symbol } } Dex { ProtocolName ProtocolFamily } } } } } ``` **WebSocket Connection Example (JavaScript):** ```javascript const client = createClient({ url: 'wss://streaming.bitquery.io/graphql', connectionParams: { Authorization: 'Bearer YOUR_ACCESS_TOKEN', }, }); const unsubscribe = client.subscribe( { query: ` subscription { EVM(network: eth) { DEXTrades { Block { Time } Trade { Buy { Amount Currency { Symbol } } Dex { ProtocolName } } } } } `, }, { next: (data) => console.log('Received:', data), error: (err) => console.error('Error:', err), complete: () => console.log('Subscription completed'), } ); ``` **Use Cases:** - **Real-time trading bots**: Monitor live DEX trades and price movements - **Portfolio tracking**: Track wallet balance changes in real-time - **MEV detection**: Monitor mempool for arbitrage opportunities - **DeFi monitoring**: Track liquidity events and protocol interactions - **Alert systems**: Set up notifications for specific blockchain events ### **Kafka Streaming** High-throughput streaming for enterprise applications with pre-parsed Protocol Buffers. Our Kafka infrastructure provides enterprise-grade data streaming with guaranteed delivery and horizontal scalability. **Learn More:** [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) **Kafka Infrastructure:** - **Broker**: `streaming.bitquery.io:9092` - **Protocol**: Apache Kafka with Protocol Buffers serialization - **Latency**: Sub-second data delivery with guaranteed ordering - **Reliability**: Built-in replication, failover, and data retention policies - **Scalability**: Auto-scaling consumer groups and partition management **Available Topics by Blockchain:** **Ethereum Topics:** - `eth.dextrades.proto` - DEX trading data across all Ethereum DEXs - `eth.transactions.proto` - Complete transaction data with receipts - `eth.tokens.proto` - Token transfers and balance updates - `eth.blocks.proto` - Block headers and metadata - `eth.events.proto` - Smart contract events and logs - `eth.calls.proto` - Smart contract function calls **Solana Topics:** - `solana.dextrades.proto` - DEX trading data (Raydium, Orca, Jupiter, etc.) - `solana.transactions.proto` - Transaction data with instruction details - `solana.tokens.proto` - SPL token transfers and balance updates - `solana.instructions.proto` - Individual instruction data - `solana.blocks.proto` - Block data and slot information **BSC Topics:** - `bsc.dextrades.proto` - PancakeSwap and other BSC DEX data - `bsc.transactions.proto` - BSC transaction data - `bsc.tokens.proto` - BEP-20 token transfers **Other Chains:** - `arbitrum.dextrades.proto`, `base.dextrades.proto`, `polygon.dextrades.proto` - `tron.dextrades.proto`, `tron.transactions.proto` **Kafka Consumer Example (Python):** ```python from kafka import KafkaConsumer # Initialize consumer consumer = KafkaConsumer( 'eth.dextrades.proto', bootstrap_servers=['streaming.bitquery.io:9092'], security_protocol='SASL_SSL', sasl_mechanism='PLAIN', sasl_plain_username='YOUR_USERNAME', sasl_plain_password='YOUR_PASSWORD', value_deserializer=lambda m: bitquery_pb2.DEXTrade().ParseFromString(m) ) # Consume messages for message in consumer: trade = message.value print(f"Trade: {trade.amount} {trade.currency.symbol} on {trade.protocol.name}") print(f"Price: ${trade.price_usd}") print(f"Block: {trade.block.number}") ``` **Kafka Features:** - **Schema Evolution**: Backward and forward compatible Protocol Buffer schemas - **Consumer Groups**: Scale horizontally with multiple consumers - **Offset Management**: Automatic and manual offset management options - **Dead Letter Queues**: Handle failed message processing - **Monitoring**: Comprehensive metrics and alerting - **Data Retention**: Configurable retention policies (7 days to 1 year) **Enterprise Features:** - **Dedicated Clusters**: Isolated Kafka clusters for high-volume customers - **Custom Topics**: Create custom topics for specific data requirements - **Priority Support**: Dedicated support for Kafka infrastructure issues - **SLA Guarantees**: 99.9% uptime with performance SLAs - **Silent Disconnect/Reconnect**: Automatic connection management for production applications ### **Data Store Exports & Data Lake** Two bulk routes for machine learning, deep analysis, and history older than the API window. **Data Store Exports (parsed Parquet):** - **Parsed Datasets**: Parquet datasets sold through the [Bitquery Data Store](https://bitquery.io/datastore), downloaded from S3 or Cloudflare R2, or delivered to your own bucket or warehouse as a custom export - **Historical Data**: History older than the API window - **Custom Requests**: Other tables, chains and date ranges are available on request from sales@bitquery.io - **Docs**: See [Data Store exports](/docs/cloud/) **Data Lake (raw Protobuf):** - **Raw Blocks**: Protobuf block files over S3 that you decode and parse yourself - **Historical Data**: Complete blockchain history since genesis (Hyperliquid from 17 July 2026) - **Docs**: See [Blockchain Data Lake](/docs/data-lake/) **Data Store Export Capabilities:** **1. Bulk Data Export** - **Time Range Exports**: Export data for specific date ranges - **Blockchain Selection**: Choose specific blockchains or all chains - **Data Type Filtering**: Export specific data types (trades, transfers, events) - **Format Options**: JSON, CSV, Parquet, or Protocol Buffers - **Compression**: Optional compression for large exports **Data Formats Available:** **JSON Format:** A human-readable, nested format ideal for development, debugging, and small to medium datasets. **Parquet Format:** A columnar, highly compressed format optimized for analytics and fast queries, perfect for data science and machine learning. **CSV Format:** A simple tabular format compatible with spreadsheets and BI tools, suitable for reporting and visualization. **Protocol Buffers:** A compact binary format with schema evolution, offering minimal storage and fast serialization for high-performance applications. **Use Cases for Data Export:** - **Machine Learning**: Train models on historical blockchain data - **Business Intelligence**: Create dashboards and reports - **Compliance**: Generate audit reports and regulatory filings - **Research**: Academic research and blockchain analysis - **Backup**: Create local backups of critical data - **Migration**: Move data to other systems or databases ## Getting Started ### 1. **Create Your Account** - Visit [Bitquery IDE](https://ide.bitquery.io/) to get started - **Free trial**: 7 days and 1,000 API points, on real-time data only, no credit card required - Access to real-time data and streaming ### 2. **Generate API Key** - Navigate to [Applications](https://account.bitquery.io/user/api_v2/applications) - Create an application and generate your access token - Use OAuth2 for secure, programmatic access ### 3. **Run Your First Query** - Try our [starter queries](/docs/start/starter-queries/) for common use cases - Use the IDE's autocomplete (Ctrl+Space) for query building - Convert queries to subscriptions for real-time data ### 4. **Explore Blockchain-Specific APIs** - **[Ethereum APIs](/docs/blockchain/Ethereum/)** - Complete EVM ecosystem data - **[Solana APIs](/docs/blockchain/Solana/)** - High-speed blockchain analytics - **[BSC APIs](/docs/blockchain/BSC/)** - Binance Smart Chain data - **[Trading APIs](/docs/category/trading-apis/)** - Real-time price and trading data ## Use Cases & Applications ### **DeFi Applications** - **DEX Aggregators**: Best [price discovery](/docs/schema/evm/dextrades/) across multiple DEXs - **Yield Farming**: Track liquidity positions and rewards - **Lending Protocols**: Monitor collateral ratios and liquidations - **Cross-chain Bridges**: Track asset movements between chains ### **Trading & Analytics** - **Trading Bots**: Real-time price feeds with 1-second aggregation and market data via [Crypto Price API](/docs/trading/crypto-price-api/) - **Portfolio Trackers**: Multi-chain wallet monitoring - **Market Analytics**: Volume, liquidity, and price analysis - **Arbitrage Detection**: Cross-chain and cross-DEX opportunities - **Charting Applications**: TradingView integration with real-time OHLC data ### **Enterprise Solutions** - **Compliance Tools**: Transaction monitoring and reporting - **Risk Management**: Real-time exposure tracking - **Business Intelligence**: Custom dashboards and KPIs - **Audit & Forensics**: Complete transaction history analysis - **MEV Detection**: Identify arbitrage opportunities and sandwich attacks - **Stablecoin Payments**: Real-time payment detection and compliance monitoring ### **Consumer Applications** - **Wallet Apps**: Balance tracking and transaction history - **NFT Marketplaces**: Collection analytics and trading data - **Block Explorers**: Enhanced blockchain data presentation - **Gaming**: In-game asset tracking and trading - **Payment Apps**: Real-time stablecoin payment processing - **MEV Tools**: Advanced trading strategies and arbitrage detection ## Data Quality & Reliability ### **Data Processing Pipeline** 1. **Real-time Ingestion**: Direct from blockchain nodes 2. **Quality Filtering**: Automatic removal of low-quality trades and outliers 3. **Enrichment**: USD values, protocol identification, and metadata 4. **Aggregation**: Pre-computed metrics and time-series data 5. **Distribution**: Multiple interfaces for different use cases ### **Enterprise-Grade Infrastructure** - **99.9% Uptime SLA**: Redundant systems with automatic failover - **Enterprise Support**: Dedicated support with guaranteed response times - **Scalable Architecture**: Auto-scaling infrastructure that grows with your needs - **Data Retention**: Complete historical data archive for comprehensive analysis ## Support & Community ### **Documentation & Resources** - **[Complete API Documentation](/docs/intro/)** - Comprehensive guides for all features - **[Code Examples](/docs/category/how-to-guides/)** - Real-world implementation examples - **[Video Tutorials](/docs/blockchain/Ethereum/)** - Step-by-step guides - **[Postman Collection](https://www.postman.com/interstellar-eclipse-270749/workspace/bitquery)** - Ready-to-use API examples ### **Community Support** - **[Telegram](https://t.me/Bloxy_info)** - Quick questions and community help - **[Community Forum](https://community.bitquery.io/)** - Feature requests and technical discussions - **[Support Desk](https://support.bitquery.io/)** - Technical issues and data problems ### **Learning Resources** - **[Learning Path](/docs/start/learning-path/)** - Structured learning from beginner to advanced - **[Starter Queries](/docs/start/starter-queries/)** - Pre-built queries for common use cases - **[GraphQL Guide](/docs/category/building-queries/)** - Complete GraphQL reference - **[Integration Examples](/docs/category/how-to-guides/)** - Real-world application examples ## Next Steps Ready to start building with blockchain data? Here's your path forward: 1. **[Create Your Account](https://ide.bitquery.io/)** - Get instant access to our platform 2. **[Run Your First Query](/docs/start/first-query/)** - Learn the basics in 5 minutes 3. **[Explore Blockchain APIs](/docs/blockchain/supported-chains/)** - Dive into specific blockchain data 4. **[Build Real-time Applications](/docs/category/graphql-subscriptions/)** - Set up live data streams 5. **[Join Our Community](https://t.me/Bloxy_info)** - Get help and share your projects --- **Start building the future of blockchain applications today with Bitquery's comprehensive multi-chain data platform.** --- ## Blockchain Data Lake URL: https://docs.bitquery.io/docs/data-lake/ Blockchain data lake: what the lake holds, its data format including Hyperliquid, how streaming works, and a hands-on tutorial to stream and decode blocks. # Blockchain Data Lake The Bitquery **Blockchain Data Lake** gives you the complete archive of a blockchain. It holds every block from **genesis to the current tip** as raw data that you can stream directly into your own systems. Hyperliquid is the exception: it starts on 17 July 2026. You get the full node dataset without running a node, so there is no syncing, no RPC rate limits, and no indexing infrastructure to operate. Each block is stored raw as a **Protobuf** message. We publish the [**schema**](https://github.com/bitquery/streaming_protobuf), so you decode each block with one documented definition, the same schema used for our Kafka streams, and parse it your own way. The archive lives as individual block files in **[SeaweedFS](https://github.com/seaweedfs/seaweedfs)**, a highly scalable distributed object store, and it is served over a standard **S3 interface**. Because reads fan out across many storage servers, you can pull the full history at **1–10 Gbps network bandwidth (depending on server)**, limited by your network rather than by a node's export speed. ## Why not just run an archive node? An archive node is built for consensus and for serving recent state over JSON-RPC. It is not built for handing you the entire chain. Extracting full history from a node means millions of rate-limited RPC calls, days or weeks of wall-clock time, and the cost of running and storing the node yourself. The data also comes back raw and undecoded, so you still have to build the decoding layer. The data lake works the other way around. The archive is stored as Protobuf objects with a published schema, so reading it becomes a bulk, parallel, network-bound operation instead of a slow, serial, CPU- and disk-bound one. | | Archive node (RPC) | Bitquery Data Lake (SeaweedFS) | | ---------------------- | --------------------------- | --------------------------------------------------------- | | Access pattern | Per-call JSON-RPC | Bulk S3 object streaming | | Full-history export | Days to weeks | Network-bound (hours) | | Throughput | Rate-limited | 1–10 Gbps (depending on server) | | Infrastructure you run | Full archive node + storage | None, read directly | | Data format | Raw, undecoded | Structured Protobuf (schema provided), one file per block | | Concurrency | Limited | Highly parallel (volume-server fan-out) | ## What's in the lake The lake holds the complete, structured history of each supported chain. It covers the full archive from block zero forward rather than samples or recent windows. Hyperliquid starts on 17 July 2026. The structure of every field is defined in the published schema. **Supported chains:** - **All EVM / Ethereum chains** (e.g. Ethereum, Base, BNB Chain, Polygon, Arbitrum, Optimism, Robinhood) - **Solana** - **Tron** - **Bitcoin** - **Hyperliquid** — Hyperliquid core (the L1 order-book exchange) as the raw node feed: fills, order statuses, book diffs, TWAP statuses, oracle updates, misc events (funding among them) and consensus transactions. It starts at block 1,075,857,000 (17 July 2026), not at genesis. See [Hyperliquid](#hyperliquid) below. On the block-structured chains, each block file also carries the block header and the lower-level data that chain exposes, such as receipts, logs, traces, instructions, and inputs/outputs. This gives you full-fidelity data rather than a summarized subset. ## Data format Each block is stored as a single file in Bitquery's native streaming format. It is a **Protobuf** message, **LZ4-compressed**, and named by block number and hash: ``` __<...>.block.lz4 ``` This is the same schema Bitquery uses for its Kafka streams, so one schema works for both the data lake and live streaming. Decoding is a cheap local step of decompress and then parse, which keeps end-to-end speed bounded by your network instead of by parsing. - **Schema:** [github.com/bitquery/streaming_protobuf](https://github.com/bitquery/streaming_protobuf) - **Python package (pb2):** [`bitquery-pb2-kafka-package`](https://pypi.org/project/bitquery-pb2-kafka-package/) — generated Python protobuf bindings from the schema (`pip install bitquery-pb2-kafka-package`; modules: `evm`, `solana`, `tron`, `utxo`, `market`, `hyperliquid`, `ton`, `offchain`) For scale reference, a single Base block in the tutorial below is about 3.4 MB compressed and 12.1 MB decoded. The lake is hundreds of millions of such files per chain. ### Hyperliquid Hyperliquid core is an L1 order-book exchange rather than an EVM chain, so its records are exchange events, not EVM blocks. The lake holds the **raw HyperCore feed** from block **1,075,857,000 (17 July 2026)** onward (the transactions stream starts a few minutes later), in two streams. Each file is a pack of 1,000 blocks rather than a single block: ``` hyperliquidcore.blocks//__.blocks.lz4 hyperliquidcore.transactions//__.blocks.lz4 ``` The history has gaps. About **96 hours** of chain time are missing from both streams, in 166 ranges: about 51 hours in July 2026, 43 hours in August, and about an hour each in September and October. The longest range is about 2.4 hours, on 28 July. The packs for those blocks are absent, not empty, so list a prefix before you assume a run of packs is continuous. Ask [support](https://t.me/Bloxy_info) for the exact list of missing block ranges. A pack is one LZ4-compressed Protobuf message. The schema lives under [`hyperliquid/`](https://github.com/bitquery/streaming_protobuf/tree/main/hyperliquid) and has a raw layer, which is what the lake stores, and a parsed layer, which is what the Kafka topics carry: | Message | Defined in | Where | Carries | | --- | --- | --- | --- | | `HyperCoreBlocks` (list of `HyperCoreBlock`) | `hypercore.proto` | Lake, `hyperliquidcore.blocks` | The node's seven event streams per block: fills, order statuses, raw book diffs, TWAP statuses, oracle updates, misc events (funding, ledger updates and more), CoreWriter actions | | `HyperCoreTransactionsBlocks` (list of `HyperCoreTransactionsBlock`) | `transactions.proto` | Lake, `hyperliquidcore.transactions` | Consensus transactions per block: signed actions with the engine's verdict, grouped in bundles | | `HyperliquidCoreBlockMessage` | `hyperliquid_block_message.proto` | Kafka, `hyperliquidcore.messages.proto` | Parsed trades, order updates, book updates, liquidations, funding, TWAPs, prices, leverage updates and signed actions — the shape behind the [Hyperliquid cubes](/docs/perpetuals/hyperliquid) | | `CandlesBlockMessage` | `candles.proto` | Kafka, `hyperliquid.candles.proto` | OHLCV candles per market and interval | All four are in the `hyperliquid` module of [`bitquery-pb2-kafka-package`](https://pypi.org/project/bitquery-pb2-kafka-package/). The parsed messages are not stored in the lake. The lake holds the raw layer, which you decode and parse your own way. For older history as parsed tables, use a [Data Store export](https://bitquery.io/datastore). ```python from hyperliquid.hypercore_pb2 import HyperCoreBlocks pack = HyperCoreBlocks() pack.ParseFromString(lz4.frame.decompress(raw)) # raw = the bytes of one .blocks.lz4 pack for block in pack.Blocks: print(block.BlockNumber, block.BlockTime, len(block.Fills)) # BlockTime is epoch nanoseconds ``` The [Hyperliquid API](/docs/perpetuals/hyperliquid) serves the parsed datasets over GraphQL and WebSocket within its rolling retention window. For older history as parsed tables, use a [Data Store export](/docs/cloud/hyperliquid/). The Data Store lists the last 30 days. Older ranges are available on request from [sales@bitquery.io](mailto:sales@bitquery.io). The lake has the raw feed back to 17 July 2026 if you want to decode and parse it your own way. See [Data Coverage & Retention](/docs/graphql/data-coverage-retention/). ## How streaming works There is no special protocol. Streaming from the lake is reading object bytes over the S3/HTTP API, and three properties of SeaweedFS make it fast: - **One lookup, then a direct read.** A small, cacheable map points the client at the volume server holding the object. The client then reads bytes straight from that server, so no central node sits in the data path. - **Range reads.** Objects support HTTP range requests, so a client can pull data in chunks and begin processing before a file fully arrives. - **Parallel fan-out.** Blocks are spread across many volume servers. Reading many blocks (or many ranges) at once hits many servers at once, so aggregate bandwidth scales horizontally within the **1–10 Gbps** range. Because the interface is S3, standard clients work unchanged, including `aws s3`, boto3, and s3fs. Streaming the full archive is bounded by your network rather than by the lake: you get **1–10 Gbps network bandwidth**, depending on the server handling your reads. ## Try it: hands-on tutorial The fastest way to understand the lake is the [blockchain-data-lake-sample](https://github.com/bitquery/blockchain-data-lake-sample) repo. It is a complete walkthrough, not just a sample file. You get: - **`stream.py`** — a Python client that streams blocks over S3, decompresses LZ4, and decodes Protobuf - **A real Base block** — the object key used in every command below - **A local demo lake** — a Docker image with that block already loaded All of the commands on this page run from that repo after you clone it. ### 1. Clone the repo and install dependencies This is where `stream.py` comes from. Run the rest of the steps from this directory. ```bash git clone https://github.com/bitquery/blockchain-data-lake-sample cd blockchain-data-lake-sample pip install -r requirements.txt KEY="base/blocks/000046600927_0x0133403c4fe53c434b1d2a1686d339eebd4e8e7f50ab52ab84cd68029e82e955_49e9339dd61bdb91320044378bff935efd925d868ca257ef8c3bc42177f9fd44.block.lz4" ``` ### 2. Start the demo lake We publish a [Docker image](https://hub.docker.com/r/marketingbitquery/datalake-demo) with the block already loaded: ```bash docker run -p 8333:8333 marketingbitquery/datalake-demo ``` This serves a lake at `http://localhost:8333`. Point `stream.py` at it: ```bash export DATA_LAKE_ENDPOINT=http://localhost:8333 export DATA_LAKE_ACCESS_KEY=admin export DATA_LAKE_SECRET_KEY=secret ``` ### 3. Stream and decode a block ```bash python stream.py --bucket archive --key "$KEY" --decode ``` ``` streamed 3.24 MB in 0.0s -> 203.3 MB/s (1.63 Gbps) reads: 1, object size: 3.24 MB decoded 11.55 MB (evm): number : 46,600,927 hash : 0x0133403c4fe53c434b1d2a1686d339eebd4e8e7f50ab52ab84cd68029e82e955 timestamp : 1779991201 gas used : 50,521,537 transactions: 169 logs : 1,180 ``` ### 4. Scale up with parallel readers Run several concurrent readers to see aggregate throughput rise: ```bash python stream.py --bucket archive --key "$KEY" --duration 15 --concurrency 16 ``` The demo runs a single SeaweedFS node, so it only illustrates the streaming and decoding path and how concurrency adds up. The actual Bitquery Blockchain Data Lake runs on a distributed SeaweedFS cluster with many volume servers, where you get **1 to 10 Gbps network bandwidth depending on the server**. The same `stream.py` client works unchanged against the live lake once you have its endpoint and credentials. ## From a block to transactions, transfers, and trades A decoded block is the full structured record. It holds the header, every transaction, each transaction's receipt and logs, and the complete opcode-level execution trace. Nothing is summarized away, so any entity you care about can be derived from it. Back in the tutorial repo, `stream.py` can also print individual transactions straight from the schema (same `$KEY` and env vars as above): ```bash python stream.py --bucket archive --key "$KEY" --tx 1 ``` The detail goes all the way down to the EVM execution itself. Each transaction's `Trace` records every internal call and, inside each call, every opcode that ran, with its program counter, gas, gas cost, and stack depth. Storage writes are captured as both the raw `SSTORE` and a `StorageChange` with the pre and post values. So you can reconstruct exactly what the transaction did at the bytecode level, not just its inputs and outputs. A single transaction comes back like this (trimmed; byte fields are base64-encoded because JSON has no byte type): ```json { "TransactionHeader": { "Hash": "w9VR+y41FcMsk8LvKHYlRRHgdCfg3kkd/lWd1K8HvS4=", "Gas": "1000000", "Type": 126, "From": "3q3erd6t3q3erd6t3q3erd6tAAE=", "To": "QgAAAAAAAAAAAAAAAAAAAAAAABU=", "Data": "Pba+KwAACN0AEBwSAAAAAAAAAAQAAAAAahiCYwAAAAAB..." }, "Receipt": { "ReceiptHeader": { "GasUsed": "46218", "CumulativeGasUsed": "46218", "Status": "1" } }, "Trace": { "Calls": [ { "Depth": 1, "CaptureEnter": { "Opcode": { "Code": 244, "Name": "DELEGATECALL" }, "From": "QgAAAAAAAAAAAAAAAAAAAAAAABU=", "To": "O6QAf1ySL7szxFS0Hqeh8R6D3yw=", "Gas": "957211" }, "CaptureExit": { "GasUsed": "18587" }, "CaptureStates": [ { "CaptureStateHeader": { "Pc": "5", "Opcode": { "Code": 52, "Name": "CALLVALUE" }, "Gas": "957193", "Cost": "2", "Depth": "2" } }, { "CaptureStateHeader": { "Pc": "1506", "Opcode": { "Code": 85, "Name": "SSTORE" }, "Gas": "956931", "Cost": "5000", "Depth": "2" }, "Store": { "Address": "QgAAAAAAAAAAAAAAAAAAAAAAABU=", "Location": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM=", "Value": "AAAAAAAAAAAAAAAAAAAAAAAACN0AEBwSAAAAAAAAAAQ=" }, "StorageChange": { "Address": "QgAAAAAAAAAAAAAAAAAAAAAAABU=", "Slot": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM=", "Pre": "AAAAAAAAAAAAAAAAAAAAAAAACN0AEBwSAAAAAAAAAAM=", "Post": "AAAAAAAAAAAAAAAAAAAAAAAACN0AEBwSAAAAAAAAAAQ=" } } ] } ] } } ``` That is two of the opcode steps from a single internal call. The real trace for this transaction has the full sequence (`CALLVALUE`, `CALLDATASIZE`, `CALLDATALOAD`, `CALLER`, `SSTORE`, and the rest), each with its gas accounting, and every storage slot it touched. The block in the tutorial carries this for all 169 transactions. Once you have a decoded block, you can either build your own parser or use Bitquery's published protobuf definitions. The tutorial's `stream.py` shows the second approach; below is how to do both yourself. ### Write your own parser The block is plain protobuf, so you walk the message and pull out what you need. The transactions, receipts, logs, and traces are all addressable fields. A minimal pass over the transactions looks like this: ```python for tx in block.Transactions: th = tx.TransactionHeader status = tx.Receipt.ReceiptHeader.Status if tx.HasField("Receipt") else None logs = tx.Receipt.Logs if tx.HasField("Receipt") else [] print("0x" + th.Hash.hex(), "status", status, "logs", len(logs)) for log in logs: # log.Address and log.Topics identify the event; # decode against the contract ABI to get transfers, swaps, etc. ... ``` This gives you full control. You decide how to turn raw logs and traces into transfers, swaps, or anything else, by decoding them against the relevant contract ABIs. For worked examples, see [Extract transfers from an EVM block](./extract-transfers-evm/) and [Extract transfers from a Solana block](./extract-transfers-solana/). ### Use Bitquery's protobuf files You do not have to define the message structure yourself. Bitquery publishes the [protobuf schema](https://github.com/bitquery/streaming_protobuf) and the [`bitquery-pb2-kafka-package`](https://pypi.org/project/bitquery-pb2-kafka-package/) Python bindings listed above, so you parse blocks with the same definitions Bitquery uses internally. Every field, for transactions, receipts, logs, and traces, is already described. With these you load a block in a few lines and read its fields directly. This is the core of what `stream.py` in the tutorial repo does: ```python from evm.block_message_pb2 import BlockMessage block = BlockMessage() block.ParseFromString(lz4.frame.decompress(raw)) # raw = the .block.lz4 bytes for tx in block.Transactions: th = tx.TransactionHeader # th.Hash, th.From, th.To, tx.Receipt, tx.Receipt.Logs, tx.Trace ... ``` So you bring the block, our protobuf files describe it, and you parse out transactions, transfers, and trades using definitions that already match the data. ## Related documentation - [Data Store exports](/docs/cloud/) covers parsed Parquet datasets you download from S3 or Cloudflare R2, or get delivered to your own bucket or warehouse as a custom export. - [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) covers real-time blockchain data streams that use the same protobuf schema. - [Hyperliquid API](/docs/perpetuals/hyperliquid/) covers the GraphQL and WebSocket interface to the parsed Hyperliquid datasets. - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) covers how far back each API goes, and when to reach for the lake instead. - [streaming_protobuf](https://github.com/bitquery/streaming_protobuf) is the block schema. --- ## Blockchain Data Pipeline to Google BigQuery with Bitquery URL: https://docs.bitquery.io/docs/category/data-pipeline-writing-to-google-bigquery/ Land live blockchain data in Google BigQuery: a Bitquery subscription feeds Pub/Sub and a subscriber writes rows to a BigQuery table. Guides and prerequisites. # Blockchain Data Pipeline to Google BigQuery with Bitquery This section builds a live pipeline in three steps: a Bitquery GraphQL subscription streams rows over WebSocket, a small process publishes each row to a Google Pub/Sub topic, and a Pub/Sub subscriber writes them into a BigQuery table. Pub/Sub sits in the middle so the Bitquery side never changes when you add consumers: BigQuery today, a Cloud Function or an alerting job tomorrow. It scales on its own, delivers each message at least once, and fans out one topic to many subscribers. You need a Google Cloud project with billing enabled (the free tier is enough) and a service account allowed to use Pub/Sub and BigQuery. For bulk history rather than a live feed, [cloud datasets](/docs/cloud/) deliver Parquet straight to BigQuery without a pipeline. ## The three guides | Step | Guide | What you set up | |---|---|---| | 1 | [Getting started](/docs/subscriptions/google-bigquery/intro) | The architecture, prerequisites and a video walkthrough | | 2 | [Setting up Google Pub/Sub](/docs/subscriptions/google-bigquery/pub-sub) | A topic, a subscription, credentials, and the publisher that forwards subscription rows | | 3 | [Filing data into Google BigQuery](/docs/subscriptions/google-bigquery/bigquery) | The BigQuery table and the subscriber that writes rows into it | ## The stream that feeds the pipeline Any subscription works as the source. This one streams every ETH transfer on Ethereum; swap the network, the cube or the filter for the data you want in your table. Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account to see the rows before wiring Pub/Sub. ```graphql subscription { EVM(network: eth) { Transfers(where: { Transfer: { Currency: { Native: true } } }) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver } } } } ``` Keep the selection flat, as above: each field becomes a column, and nested objects are easier to load when the publisher flattens them before Pub/Sub. ## Related pages - [WebSocket subscriptions](/docs/subscriptions/subscription) - [Kafka streams](/docs/category/kafka-streams) - [Cloud datasets](/docs/cloud/) - [Real-time streaming compared](/docs/streams/) --- ## Blockchain Data in Cloud URL: https://docs.bitquery.io/docs/cloud/ Bitquery blockchain data as Parquet files for S3, Snowflake and BigQuery: which chains and tables exist, how the files are laid out, and where to buy them. # Blockchain Data in Cloud Bitquery sells full-history blockchain datasets as **Parquet files** through the [Bitquery Data Store](https://bitquery.io/datastore). The pages in this section document these **Data Store exports**. Pick a chain or protocol dataset, check the schema and a free sample, pay a fixed price by card or bank transfer, and download from **S3** or **Cloudflare R2**. The same files load into **Snowflake**, **BigQuery**, **Google Cloud Storage**, DuckDB, Spark or any other Parquet reader. This page documents what each dataset contains and how the files are laid out. Buying happens on the Data Store. :::tip Looking to buy a dataset? Browse [all datasets on the Data Store](https://bitquery.io/datastore/datasets). Each listing shows the tables and columns, a free sample to test before you pay, and the price. The listing is not the full catalogue. For a chain, table or date range that is not listed, email [sales@bitquery.io](mailto:sales@bitquery.io). ::: Bitquery provides ready-to-use blockchain **Data Store exports** in **Parquet format** via popular cloud providers such as **AWS S3**, **Google Cloud Storage**, **Snowflake**, and **BigQuery**. You can plug these datasets directly into your existing analytics stack and build custom data pipelines without running your own blockchain infrastructure or maintaining complex indexing systems. ## Overview Data Store exports deliver **production-ready blockchain datasets** optimized for large-scale analytics, historical backfills, and data lake integrations. All data is provided in **Apache Parquet format**, ensuring optimal compression, columnar storage, and compatibility with modern analytics engines. We can also provide other file formats if required. ### Key Benefits - **No Infrastructure Management** – Skip running blockchain nodes, indexers, or data processing infrastructure - **Production-Ready Format** – Parquet files optimized for analytics workloads - **Cloud-Native** – Direct integration with AWS S3, Google Cloud Storage, Snowflake, and BigQuery - **Historical Coverage** – Full history from genesis for most chains; the Hyperliquid Data Store listing is the last 30 days, and older ranges are available on request - **Multi-Chain Support** – Access data from major blockchain networks - **Cost-Effective** – Pay only for the data you need, when you need it - **Scalable** – Built for large historical backfills ## Available Data Store Exports Bitquery provides Data Store exports for the following blockchains: ### [EVM Chains Data Export](/docs/cloud/evm/) Export blockchain data for **Ethereum, BSC, Base, Polygon/Matic, Optimism, Arbitrum, Robinhood**, and other EVM-compatible chains. Includes: - **Blocks** – Block-level metadata and timestamps - **Transactions** – Full transaction-level data with gas information - **Transfers** – Native token and ERC-20 token transfers - **Balance Updates** – Account balance changes per block - **Balances** – Daily end-of-day balance snapshots per account and token - **DEX Trades** – Decentralized exchange trading data - **DEX Pools** – Liquidity pool metadata and state - **Smart Contract Calls** – Function calls and interactions - **Events** – Ethereum event logs and emissions - **Miner Rewards** – Block rewards and transaction fees - **Uncle Blocks** – Ethereum uncle block data **Use Cases:** DeFi analytics, NFT tracking, smart contract analysis, token holder analysis, DEX volume analysis, cross-chain analytics. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Ethereum Transfers](https://bitquery.io/datastore/datasets/ethereum-transfers) · [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) · [Base Transfers](https://bitquery.io/datastore/datasets/base-transfers) · [Polygon Transfers](https://bitquery.io/datastore/datasets/polygon-transfers) · [Arbitrum Transfers](https://bitquery.io/datastore/datasets/arbitrum-transfers) ### [Solana Blockchain Data Export](/docs/cloud/solana/) Export **Solana blockchain data** including slot-level blocks, transactions, transfers, and DEX activity: - **Blocks** – Slot-level block metadata - **Transactions** – Full transaction-level data with signatures - **Transfers** – Native SOL and SPL token transfers - **Balance Updates** – Account balance changes per slot - **DEX Pools** – Decentralized exchange pool metadata - **DEX Orders** – Order-level DEX activity and fills - **DEX Trades** – Executed trades on Solana DEXs - **Rewards** – Validator and staking rewards **Use Cases:** Solana DeFi analytics, NFT marketplace analysis, token transfer tracking, DEX volume analysis, validator performance monitoring. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Solana datasets on the Data Store](https://bitquery.io/datastore/datasets?network=solana), including [Pump.fun](https://bitquery.io/datastore/datasets/pumpfun), [PumpSwap](https://bitquery.io/datastore/datasets/pumpswap), [Raydium AMM v4](https://bitquery.io/datastore/datasets/raydium-amm-v4), [Jupiter](https://bitquery.io/datastore/datasets/jupiter), [Meteora DLMM](https://bitquery.io/datastore/datasets/meteora-dlmm) and [Orca Whirlpool](https://bitquery.io/datastore/datasets/orca-whirlpool) ### [Tron Blockchain Data Export](/docs/cloud/tron/) Export **Tron blockchain data** for comprehensive network analysis: - **Blocks** – Block-level metadata - **Transactions** – Full transaction-level data - **Transfers** – Native TRX and TRC-20 token transfers - **Balance Updates** – Account balance changes per block - **DEX Trades** – Executed trades on Tron DEXs **Use Cases:** Tron DeFi analytics, TRC-20 token tracking, DEX volume analysis, account balance monitoring, transaction flow analysis. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [TRON Transfers](https://bitquery.io/datastore/datasets/tron-transfers) ### [Bitcoin Blockchain Data Export](/docs/cloud/bitcoin/) Export **Bitcoin blockchain data** including transaction inputs, outputs, and OMNI Layer protocol data: - **Blocks** – Block-level metadata - **Transactions** – Full transaction-level data - **Inputs** – Transaction input data and UTXO references - **Outputs** – Transaction output data and addresses - **OMNI Transactions** – OMNI Layer protocol transactions - **OMNI Transfers** – OMNI Layer token transfers **Use Cases:** Bitcoin transaction analysis, UTXO tracking, address clustering, OMNI token analysis, blockchain forensics, historical price analysis. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Bitcoin](https://bitquery.io/datastore/datasets/bitcoin) ### [Ripple (XRP Ledger) Data Export](/docs/cloud/ripple/) Export **Ripple / XRP Ledger data**, modelled around XRPL's ledger objects: - **Transactions** – Transaction envelope with fee, sequence, result code, memos, and signers - **Transfers** – Unified value movement: XRP and issued-token payments, DEX and AMM trade sides, NFT trades and mints, and fee burns - **Payments** – `Payment` transactions with requested, delivered, send-max, and deliver-min amounts - **Balances** – Account balance before and after each change, native and issued - **Account Roots** – Account state: XRP balance, owner count, sequence, domain, transfer rate - **Ripple States** – Trust line balances between two accounts for an issued currency - **Offers** – DEX order book offers, before and after each change - **NFToken Offers** – NFT buy and sell offers with the asking price - **Escrows** – Escrow creation, finish, and cancel with conditions and time locks - **Checks** – Deferred payment authorizations **Use Cases:** XRP payment flow analysis, issued-token and stablecoin tracking, XRPL DEX and AMM volume analysis, order book reconstruction, trust line and issuer exposure analysis, NFT marketplace activity, network fee revenue analysis. ### [Hyperliquid (HyperCore) Data Export](/docs/cloud/hyperliquid/) Export **Hyperliquid Core (HyperCore)** order-book exchange data — an event stream rather than a state chain: - **Trades** – Both sides of every match, with realized PnL, fees, taker flag, position after the fill, execution order in the block and TWAP link - **Perp Liquidations** – Both sides of every liquidation, with the liquidated account, mark price and method - **TWAPs** – TWAP order state, executed size and notional, terminal status - **Order Updates** – Full order lifecycle: open, canceled, filled, triggered, and every rejection reason - **Book Updates** – **L4** per-order book changes with the owning address and order id - **Price Updates** – Mark, oracle and external perp prices per HIP-3 market, and the inputs behind them - **Perp Fundings** – Every account's funding payment at each hourly settlement **Use Cases:** Perp market microstructure research, order book reconstruction at L4, maker and taker behaviour analysis, per-wallet realized PnL and funding, liquidation forensics, HIP-3 builder market analysis, backtesting against full order flow. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Hyperliquid](https://bitquery.io/datastore/datasets/hyperliquid) · [Hyperliquid Trades](https://bitquery.io/datastore/datasets/hyperliquid-trades) · [Hyperliquid Order Book](https://bitquery.io/datastore/datasets/hyperliquid-order-book) · [Hyperliquid Funding](https://bitquery.io/datastore/datasets/hyperliquid-ledger) ### [Robinhood Chain Data Export](/docs/cloud/robinhood/) Export **Robinhood Chain** data — an EVM network (chain ID `4663`) where tokenized equities trade alongside crypto-native assets: - **DEX Trades** – Buy and sell side with token metadata, USD amounts, pool and protocol - **Transfers** – Native and ERC-20 movements with USD value and currency metadata - **Balances** – Balance snapshot per address and currency, with change times and update count - **Events** – Decoded logs with arguments, topics, and the emitting call context - **Calls** – Internal and top-level calls with decoded arguments, returns, and state changes **Use Cases:** Tokenized equity and RWA flow analysis, USDG stablecoin tracking, Robinhood DEX volume analysis across Uniswap and Pons, wallet balance reconstruction, contract call tracing, cross-venue arbitrage research. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Pons](https://bitquery.io/datastore/datasets/pons) ### [Pump.fun Data Export](/docs/cloud/pumpfun/) Export **Pump.fun** data on Solana: - **Creation & Migration Events** – Pump.fun token creation and migration events - **DEX Trades** – Executed trades on Pump.fun - **DEX Pools** – Liquidity pool metadata and activity - **OHLCV** – Open/High/Low/Close/Volume candles per token **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Pump.fun](https://bitquery.io/datastore/datasets/pumpfun) · [PumpSwap](https://bitquery.io/datastore/datasets/pumpswap) ### [Stellar Data Export](/docs/cloud/stellar/) Export **Stellar** data, modelled around ledgers, transactions, operations and effects: - **Blocks** – Ledger-level metadata - **Transactions** – Transaction-level data with fee account, memo and sequence - **Operations** – Operation-level records with source account and operation details - **Payments** – Payment and path-payment operations - **Transfers** – Native XLM and issued-asset transfers - **Effects** – Ledger effects, including balance, trade, claimable balance and liquidity pool effects ### [Polymarket Data Export](/docs/cloud/polymarket/) Export **Polymarket** data on Polygon, joined with the market question, outcome label and collateral token. History starts in September 2025: - **Prediction Trades** – Outcome-token trades with market question, outcome label, price, and collateral amounts - **Prediction Settlements** – Position splits, merges and payout redemptions - **DEX Trades** – Polymarket trades in the standard EVM DEX trades schema **Use Cases:** Backtesting, research, leaderboards, model training, warehouse joins. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Polymarket](https://bitquery.io/datastore/datasets/polymarket) ### [BSC (BNB Chain) Data Export](/docs/cloud/bsc/) Export **BSC (BNB Chain) blockchain data** for comprehensive EVM-compatible chain analysis: - **Blocks** – Block-level metadata and timestamps - **Transactions** – Full transaction-level data with gas information - **Transfers** – Native BNB and BEP-20 token transfers - **Balance Updates** – Account balance changes per block - **DEX Trades** – Executed trades on BSC DEXs (PancakeSwap, etc.) - **DEX Pools** – Liquidity pool metadata and state - **Smart Contract Calls** – Function calls and contract interactions - **Events** – BSC event logs and emissions - **Miner Rewards** – Block rewards and transaction fees **Use Cases:** BSC DeFi analytics, PancakeSwap analysis, BEP-20 token tracking, DEX volume analysis, smart contract monitoring, yield farming analytics, NFT marketplace data. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) ## Data Format and Structure Blockchain data is provided by default in **Apache Parquet format**, a columnar storage file format optimized for analytics workloads. We can also provide data in other file formats (CSV, JSON, Avro, etc.) based on your requirements. Parquet offers: - **High Compression** – Columnar encoding and compression keep files small - **Columnar Storage** – Enables efficient column pruning and predicate pushdown - **Schema Evolution** – Supports schema changes over time - **Universal Compatibility** – Works with all major analytics engines ### File Organization Data is organized by blockchain and topic, with files named using block/slot ranges: ``` bitquery-blockchain-dataset/ ├── ethereum/ │ ├── blocks/ │ ├── transactions/ │ ├── transfers/ │ ├── balance_updates/ │ ├── dex_trades/ │ └── ... ├── solana/ │ ├── blocks/ │ ├── transactions/ │ ├── transfers/ │ ├── dex_trades/ │ └── ... ├── bitcoin/ │ ├── blocks/ │ ├── transactions/ │ ├── inputs/ │ ├── outputs/ │ └── ... ├── tron/ │ ├── blocks/ │ ├── transactions/ │ ├── transfers/ │ └── ... ├── ripple/ │ ├── transactions_tx/ │ ├── transfers_tx/ │ ├── payments_tx/ │ ├── balances/ │ └── ... ├── hyperliquid/ │ ├── trades/ │ ├── order_updates/ │ ├── book_updates/ │ ├── perp_fundings/ │ └── ... └── robinhood/ ├── dex_trades/ ├── transfers/ ├── balances/ ├── events/ └── ... ``` ## Sample Parquet Data To quickly explore the structure of the data and test your tooling, you can use our **public sample datasets**: - **GitHub repository** with sample Parquet files and schemas: [`https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main`](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main) In the GitHub repo, **each sample file (per data point or topic)** includes the **exact S3 URL** in a comment, so you can: - Point test pipelines to the same path - Buy the full dataset on the [Data Store](https://bitquery.io/datastore/datasets), or ask [sales@bitquery.io](mailto:sales@bitquery.io) for a custom export - Validate schemas before production integration ### Example: Ethereum Balance Updates ```text https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balance_updates/24053500_24053549.parquet bitquery-blockchain-dataset/ └── ethereum/ └── balance_updates/ ├── 24053500_24053549.parquet ├── 24053550_24053599.parquet ├── 24053600_24053649.parquet ├── 24053650_24053699.parquet ├── 24053700_24053749.parquet ├── 24053750_24053799.parquet ├── 24053800_24053849.parquet ├── 24053850_24053899.parquet ├── 24053900_24053949.parquet └── 24053950_24053999.parquet ``` ### Use Sample Data To: - **Validate ETL Pipelines** – Test your data processing workflows against realistic blockchain data - **Inspect Schemas** – Review column names, types, and data structures before production - **Benchmark Performance** – Measure query performance on realistic data sizes - **Develop Analytics** – Build and test analytics queries before full dataset access - **Validate Tooling** – Ensure compatibility with your analytics stack ## Cloud Platform Integration ### AWS S3 Integration Store blockchain data in **Amazon S3** and query with: - **Amazon Athena** – Serverless SQL queries on S3 data - **Amazon Redshift** – Data warehouse with S3 integration - **AWS Glue** – ETL jobs and data catalog - **Amazon EMR** – Spark-based analytics on S3 ### Google Cloud Platform Integration Store blockchain data in **Google Cloud Storage** and analyze with: - **BigQuery** – Serverless data warehouse with native Parquet support - **Dataproc** – Managed Spark and Hadoop clusters - **Dataflow** – Stream and batch data processing - **BigQuery ML** – Machine learning on blockchain data ### Snowflake Integration Load blockchain data into **Snowflake** for: - **Data Warehousing** – Centralized blockchain data storage - **SQL Analytics** – Complex queries across multiple chains - **Data Sharing** – Share blockchain datasets across teams - **Snowpark** – Python, Java, and Scala analytics ### Other Platforms Our Parquet datasets are compatible with: - **Databricks** – Unified analytics platform - **Apache Spark** – Distributed data processing - **Presto/Trino** – Distributed SQL query engine - **Apache Drill** – Schema-free SQL queries - **DuckDB** – In-process analytical database ## Building Scalable Real-Time Solutions Bitquery enables you to build **enterprise-grade, scalable, real-time, low-latency solutions** in the cloud. Our cloud-native architecture supports both batch and streaming data pipelines for blockchain analytics. ### Real-Time Streaming Architecture Build low-latency applications using: - **[Kafka Streams](/docs/streams/kafka-streaming-concepts/)** – High-throughput, low-latency blockchain data streams - **Mempool Data** – Access pending transactions before block confirmation - **Committed Data** – Real-time confirmed transaction streams - **Multi-Chain Support** – Stream data from Ethereum, Solana, Bitcoin, Tron, and more - **Protobuf Format** – Efficient binary serialization for optimal performance - **GraphQL Subscriptions** – WebSocket-based real-time data subscriptions - **Live Queries** – Subscribe to specific blockchain events and transactions - **Custom Filters** – Filter data streams by address, token, contract, or event - **Low Latency** – Live delivery for time-sensitive applications - **[gRPC (CoreCast)](/docs/grpc/solana/introduction)** – Low-latency gRPC streams, Solana only For raw blocks to decode and parse your own way, see the [Blockchain Data Lake](/docs/data-lake/). ## Use Cases ### DeFi Analytics - **DEX Volume Analysis** – Track trading volumes across decentralized exchanges - **Liquidity Pool Analytics** – Monitor pool sizes, fees, and impermanent loss - **Yield Farming Analysis** – Analyze yield opportunities and risks - **Token Flow Tracking** – Monitor token movements between addresses ### NFT Analytics - **Collection Analysis** – Track NFT sales, floor prices, and market trends - **Marketplace Analytics** – Compare performance across NFT marketplaces - **Holder Analysis** – Identify whale wallets and distribution patterns - **Rarity Analysis** – Calculate and track NFT rarity metrics ### Blockchain Forensics - **Transaction Tracing** – Follow funds through complex transaction paths - **Address Clustering** – Identify related addresses and entities - **Compliance Monitoring** – Track suspicious transactions and patterns - **Risk Assessment** – Evaluate transaction risks and anomalies ### Data Science and Machine Learning - **Price Prediction** – Build models using historical transaction data - **Anomaly Detection** – Identify unusual patterns in blockchain activity - **Network Analysis** – Analyze blockchain network topology - **Sentiment Analysis** – Correlate on-chain activity with market sentiment ### Business Intelligence - **Portfolio Tracking** – Monitor multi-chain portfolio performance - **Revenue Analytics** – Track protocol revenues and fees - **User Analytics** – Analyze user behavior and engagement - **Market Research** – Study market trends and competitive analysis ## Real-Time vs Batch Data Access Data Store exports are optimized for **batch analytics and historical workloads**. They provide: - **Deep Historical Data** – Full history for most datasets (Hyperliquid: the Data Store lists the last 30 days, older ranges on request; Polymarket from September 2025) - **Cost-Effective Storage** – Optimized compression reduces costs - **Batch Processing** – Ideal for ETL pipelines and scheduled analytics - **Data Warehousing** – Perfect for building comprehensive warehouses If you require **low-latency or streaming blockchain data**, Bitquery also provides: - **[Kafka Streams](/docs/streams/kafka-streaming-concepts/)** – Real-time blockchain data streams via Apache Kafka - **GraphQL Subscriptions** – Live data subscriptions for real-time applications - **[gRPC (CoreCast)](/docs/grpc/solana/introduction)** – Low-latency gRPC streams, Solana only For raw blocks to decode and parse your own way, see the [Blockchain Data Lake](/docs/data-lake/). ## Getting Started 1. **Explore Sample Data** – Review our [GitHub repository](https://github.com/bitquery/blockchain-cloud-data-dump-sample) to understand data structures 2. **Choose Your Blockchain** – Select from [EVM](/docs/cloud/evm/), [BSC](/docs/cloud/bsc/), [Solana](/docs/cloud/solana/), [Pump.fun](/docs/cloud/pumpfun/), [Tron](/docs/cloud/tron/), [Bitcoin](/docs/cloud/bitcoin/), [Ripple](/docs/cloud/ripple/), [Stellar](/docs/cloud/stellar/), [Polymarket](/docs/cloud/polymarket/), [Robinhood](/docs/cloud/robinhood/), or [Hyperliquid](/docs/cloud/hyperliquid/) data exports 3. **Set Up Cloud Storage** – Configure AWS S3, Google Cloud Storage, or your preferred storage solution 4. **Integrate Analytics Engine** – Connect Snowflake, BigQuery, Athena, or your analytics platform 5. **Build Your Pipeline** – Create ETL jobs to process and transform blockchain data ## Related Documentation - [EVM Data Export](/docs/cloud/evm/) – Ethereum, Polygon, and other EVM chains - [BSC Data Export](/docs/cloud/bsc/) – BNB Chain Data Store exports - [Solana Data Export](/docs/cloud/solana/) – Solana Data Store exports - [Pump.fun Data Export](/docs/cloud/pumpfun/) – Pump.fun creations, migrations, trades, pools and OHLCV - [Tron Data Export](/docs/cloud/tron/) – Tron Data Store exports - [Bitcoin Data Export](/docs/cloud/bitcoin/) – Bitcoin blockchain and OMNI data - [Ripple Data Export](/docs/cloud/ripple/) – XRP Ledger transactions, payments, balances and ledger objects - [Stellar Data Export](/docs/cloud/stellar/) – Stellar ledgers, operations, payments and effects - [Polymarket Data Export](/docs/cloud/polymarket/) – Polymarket prediction trades and settlements - [Hyperliquid Data Export](/docs/cloud/hyperliquid/) – HyperCore order book, fills, and L4 book diffs - [Robinhood Data Export](/docs/cloud/robinhood/) – Robinhood Chain trades, transfers, and tokenized equities - [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) – Real-time blockchain data streams --- ## Blockchain Reorg Tree URL: https://docs.bitquery.io/docs/graphql/dataset/select-blocks/ Blockchain Reorg Tree in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Blockchain Reorg Tree Blocks in the blockchain form a tree (or directed acyclic graph DAG in general): ![Blockchain graph](/img/diagrams/tree.png) Blocks that linked together from the highest tip we call the __trunk__ : ![Blockchain trunk](/img/diagrams/trunk.png) Blocks that not having the highest tip linked to are called __branches__ : ![Blockchain branches](/img/diagrams/branches.png) Archive database contains only trunk blocks, branches (forked Block 101 and Block 102) are not included in archive database. :::note Branched block 102 however is included in real time database. ::: ## Select Blocks The `select_blocks` attribute controls which blocks a `realtime` or `combined` query reads. It is ignored for `dataset: archive`, which holds trunk blocks only. | value | Solana | other chains (EVM, Tron, ...) | | --- | --- | --- | | `tree` (default) | every block the real-time database holds, abandoned forks included | the same | | `trunk` | leaves out the blocks of abandoned forks | no filtering: the same blocks as `tree` | | `branches` | only the blocks of abandoned forks | not supported: use `tree` | **The default is `tree`.** A query without the argument also returns the rows of abandoned forks. On Solana these are a small share of rows. If a transaction must not be counted twice, or must have landed on the chain, pass `select_blocks: trunk`. **How `trunk` works on Solana.** The real-time database stores a block as soon as a validator has processed it, before the cluster decides on it. When a fork is abandoned, its blocks drop out of `trunk` results once the kept chain is 5 blocks past them. That usually takes under a second, at most a few seconds. A query run in that window can still return the block. **Aggregated queries.** Some Solana queries are answered from pre-aggregated tables, for example volume metrics of `DEXTradeByTokens`. These tables keep the trades of abandoned forks even under `trunk`. To leave them out completely, add `aggregates: no`. The query then reads the row-level tables, covers only the real-time window (see the [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/)), and can be slower. **`branches` on Solana** returns only the blocks of abandoned forks, for analyzing reorganizations. On `combined` it reads nothing from the archive, because the archive holds no abandoned blocks. :::tip On chains other than Solana, `trunk` does not filter anything and disables the aggregated tables, so it only makes queries slower. Leave the argument out there. ::: --- ## BonkSwap API: Trades, Top Traders, One Wallet's Swaps and OHLC on Solana URL: https://docs.bitquery.io/docs/blockchain/Solana/BonkSwap-API/ BonkSwap on Solana via Bitquery GraphQL: latest swaps, top traders by USD volume, one wallet's BonkSwap trades, hourly OHLC for USELESS/USD1, and a live stream. # BonkSwap API: Trades, Top Traders, One Wallet's Swaps and OHLC on Solana BonkSwap is the AMM of the Bonk ecosystem on Solana, program `BSwp6bEBihVLdqJRKGgzjcGLHkcTuzmSo1TQkHepzH8p`. Its volume today runs through pairs quoted in USD1, the stablecoin the venue leans on, with USELESS/USD1 the busiest of them. Bitquery labels its swaps `ProtocolName: "bonkswap"` in the Solana `DEXTrades` and `DEXTradeByTokens` cubes, so every query on this page is one filter away from covering any other Solana DEX. Every example runs in the [IDE](https://ide.bitquery.io); Solana queries go to the `graphql` endpoint. Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. For swaps with the trader, USD and market cap on every row for the last month, the [Trading cube](/docs/trading/crypto-trades-api/trades-api) covers BonkSwap too. ## Latest swaps on BonkSwap One row per swap per token, newest first, with the counter token, the price in USD, the market and the signer. Change `query` to `subscription` and drop `limit` and `orderBy` for a live feed. Saved query [here](https://ide.bitquery.io/Latest-Trades-on-BonkSwap). ```graphql { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Transaction: { Result: { Success: true } } Trade: { Dex: { ProtocolName: { is: "bonkswap" } } } } ) { Block { Time } Trade { Currency { Symbol MintAddress } Amount PriceInUSD Side { Currency { Symbol } Amount Type } Market { MarketAddress } } Transaction { Signature Signer } } } } ``` ## Top traders by USD volume Group the last day by the transaction signer. `tokens` says how many different tokens each wallet touched. Saved query [here](https://ide.bitquery.io/Top-Traders-on-BonkSwap). ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 50 } where: { Transaction: { Result: { Success: true } } Trade: { Dex: { ProtocolName: { is: "bonkswap" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Transaction { Signer } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) tokens: uniq(of: Trade_Currency_MintAddress) } } } ``` ## One wallet's BonkSwap trades Filter `Transaction.Signer`. The example is the most active BonkSwap wallet at the time of writing; take any address from the table above. Saved query [here](https://ide.bitquery.io/Bonkswap-Trades-by-Trader-API). ```graphql { Solana { DEXTrades( orderBy: [{ descending: Block_Time }, { descending: Transaction_Index }, { descending: Trade_Index }] limit: { count: 20 } where: { Transaction: { Signer: { is: "9EVzTzLSfYHrjXpejBRFGmZVG9jRsS4tDtcE1NpD6srb" } } Trade: { Dex: { ProtocolName: { is: "bonkswap" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time } Trade { Buy { Currency { Symbol } Amount AmountInUSD } Sell { Currency { Symbol } Amount AmountInUSD } Market { MarketAddress } } Transaction { Signature } } } } ``` ## Hourly OHLC for USELESS/USD1 Candles for the last day of the busiest BonkSwap pair. `Trade.Amount` sums the USELESS volume; the four price fields come from the highest and lowest prices in the hour and the first and last slot. Saved query [here](https://ide.bitquery.io/ohlc-for-bonkswap-token). ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "bonkswap" } } Currency: { MintAddress: { is: "Dz9mQ9NzkBcCsuGPFJ3r1bS4wgqKMHBPiVuniW8Mbonk" } } Side: { Currency: { MintAddress: { is: "USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB" } } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 24 } orderBy: { descendingByField: "Block_Timefield" } ) { Block { Timefield: Time(interval: { in: hours, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Every BonkSwap swap, live The protocol filter on `DEXTrades` as a subscription; each message is one swap with both sides. ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "bonkswap" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Buy { Currency { Symbol MintAddress } Amount AmountInUSD Account { Address } } Sell { Currency { Symbol MintAddress } Amount AmountInUSD } Market { MarketAddress } } Transaction { Signature Signer } } } } ``` ## Related pages - [Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) - [Solana API hub](/docs/blockchain/Solana/) - [Shred streams for Solana](/docs/streams/real-time-solana-data/) --- ## Breaking Down Price Streams in Detail URL: https://docs.bitquery.io/docs/trading/crypto-price-api/in-depth/ How the Pairs cube decides which token is base and which is quote: stablecoin priority, native-asset priority, then stablecoin-pair volume. # Breaking Down Price Streams in Detail ## What it is This page explains how the `Pairs` cube decides which token in a pair is the **base** and which is the **quote**. You do not need it to start using the API; the [examples](/docs/trading/crypto-price-api/examples) do that. For how prices and volumes are computed (trade filtering, the liquidity-weighted token and currency blend, field semantics), see [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). ## How it is derived ### Base and quote in the Pairs cube In every pair, one token is the base and the other is the quote. The price is how much of the quote token buys 1 unit of the base token. Example: if SOL/USDC = 180.0, then 1 SOL costs 180 USDC. SOL is the base, USDC the quote. ### The logic behind quote token selection The rules below pick the **quote** token, in order. 1. **Stablecoin priority.** If one of the tokens is a **stablecoin**, it is chosen as the **quote**. > Example: In a USDC/ETH pair, ETH is base, USDC is quote — you get the ETH price in USD. Stablecoins include: - USDT - USDC - DAI - USDS - USD1 - TUSD - USDD - USD₮0 2. **Native asset vs another token.** If neither token is a stablecoin but one is a **native token** of the blockchain (e.g., ETH on Ethereum, SOL on Solana, BTC on Bitcoin), the native token is the **quote**. > Example: For a wBTC/ETH pair on Ethereum, ETH is quote because it's the native asset of that chain. 3. **Dynamic volume-based decision.** If neither rule applies (two non-stable, non-native tokens), the quote is chosen **dynamically** based on liquidity: - We calculate the **trading volume** of both tokens across all stablecoin pairs. - The token with the **higher total volume in USD** is selected as the **quote**. > This makes the quote the more liquid asset, which gives more stable and usable price data. ## Related - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) - [Pairs cube](/docs/trading/crypto-price-api/pairs) - [Examples](/docs/trading/crypto-price-api/examples) --- ## Build AI Trading Agents with Bitquery Base Chain Data URL: https://docs.bitquery.io/docs/blockchain/Base/ai-agent-base-data/ Base AI trading agent guide: trending Base tokens by USD volume, a live trade stream, decision logic and setup steps to run the open-source agent. # Build AI Trading Agents with Bitquery Base Chain Data ## Recommended: Trading API feeds for agents (real-time + last ~30 days) For live signals, point your agent at the [**Trading API**](/docs/trading/trading-data-overview) — **USD price, market cap, and supply on every row**, MEV-filtered. The chain-level queries below remain the right tool for **history older than ~30 days** or call/event context. ### Trending Base tokens by USD volume Run it [in the IDE](https://ide.bitquery.io/Trading-API-Trending-Tokens-Base). ```graphql { Trading { Tokens( where: { Interval: {Time: {Duration: {eq: 3600}}} Token: {Network: {is: "Base"}} Block: {Time: {since_relative: {hours_ago: 2}}} Volume: {Usd: {gt: 10000}} } limit: {count: 10} orderBy: {descending: Volume_Usd} ) { Token { Symbol Address Network } Interval { Time { Start Duration } } Volume { Base Usd } Price { Ohlc { Open High Low Close } } Supply { MarketCap FullyDilutedValuationUsd } } } } ``` ### Live Base trade stream Run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains) — scoped here to Base; drop the `Network` filter to stream all 10 chains. ```graphql subscription { Trading { Trades(where: {Pair: {Market: {Network: {is: "Base"}}}}) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` In this section, we will explore how to use Bitquery APIs and real-time streams to build AI-enabled trading agents for the Base blockchain. For **ready-made Bitquery-backed [OpenClaw](https://openclaw.ai/) skills** (installable via [ClawHub](https://clawhub.ai/)—for example real-time BTC, USD charts, Pump.fun, Polymarket, and Solana stablecoin streams), see [bitquery/openclaw-skills-master](https://github.com/bitquery/openclaw-skills-master) and the [ClawHub CLI docs](https://docs.openclaw.ai/tools/clawhub). This page focuses on a **custom** Base trading agent you build with Bitquery APIs directly. ## Your AI Trading Agent's Mission: You are a specialized trading agent operating on the Base blockchain, you will optimize an existing portfolio by analyzing and trading trending tokens using Bitquery data. Your primary goal is to identify profitable tokens in the Base ecosystem, assess wallet balances, and execute calculated swap decisions to enhance portfolio value. ```python prompt = ( f"Analyze the following Base chain token:\n" f"Name: {token_data['name']}\n" f"Symbol: {token_data['symbol']}\n" f"Market Cap: {token_data['market_cap']}\n" f"Liquidity (USD): {token_data['liquidity_usd']}\n" f"Volatility: {token_data['volatility']}\n" f"Top Holder Concentration (%): {token_data['holder_concentration']}\n" f"Current Price: {token_data['current_price']}\n" f"Trading Volume (24h): {token_data['trading_volume']}\n" "\nBased on this data and Base ecosystem considerations, decide whether to 'Buy', 'Sell', 'Hold', or 'Avoid'. Only reply with one word: Buy, Sell, Hold, or Avoid." ) ``` ## Trading Decision Process This is a rough draft of what an AI agent can do using Base chain on-chain and off-chain data. For live DEX prices grouped by theme, browse [DEXrabbit Categories](https://dexrabbit.bitquery.io/categories) — for example [AI Agents](https://dexrabbit.bitquery.io/categories/ai-agents) or [Base Meme Coins](https://dexrabbit.bitquery.io/categories/base-meme-coins). - Use trending data to identify promising Base tokens with potential profit. - For each trending token, retrieve detailed information to evaluate its market cap, liquidity, volatility, and security. - Check the wallet balance to understand the available assets and decide on a safe percentage to invest. - Execute swaps to acquire trending tokens on Base DEXs (Uniswap V3, PancakeSwap), ensuring the chosen amount. - Continuously monitor token performance and adjust holdings to maximize profits. For this you can use Bitquery Real-time Streams to monitor Base token prices, new token creation and other activities with sub-second latency. ## Code Structure and Logic: A Good Starting Point Your code sets up a flexible AI trading agent framework for Base chain, handling: - **backtesting**: historical simulation on Base chain data. - **live mode**: real-time trading/decision making on Base DEXs - **Integration with Claude AI** to guide trading decisions based on Base chain fundamentals - **Base ecosystem analysis** where the AI agent makes data-driven trading decisions using Bitquery Base data. Below is a sample project structure: ``` base_ai_trading_agent/ ├── base_main.py # Entry point for Base agent ├── base_bitquery_utils.py # Bitquery API functions for Base ├── ai_decision.py # Claude AI logic for trade decisions ├── base_config.py # Base chain configuration ├── .env # Store API keys securely └── requirements.txt # Python dependencies ``` ## Video Tutorial ## How to Run the Base Chain AI Agent ### 1. Clone the Repository ```bash git clone https://github.com/Akshat-cs/Base-onchain-aiagent cd Base-onchain-aiagent ``` ### 2. Install Dependencies ```bash pip install -r requirements.txt ``` ### 3. Environment Setup Create a `.env` file in the project root: ```bash # Required API Keys CLAUDE_API_KEY=your_claude_api_key BITQUERY_TOKEN=your-bitquery-token-here WALLET_ADDRESS=your-wallet-address ``` ### 4. Run the Trading Agent ```bash python base_main.py ``` ## Key Bitquery Streams and Queries for Base Trading Agents ### 1. Top Trending Tokens on Base Detect Base tokens with rising popularity and trader activity.
Click to expand GraphQL query ```graphql query TrendingBaseTokens { EVM(network: base, dataset: realtime) { DEXTradeByTokens( limit: { count: 10 } orderBy: { descendingByField: "buyers" } where: { Trade: { Currency: { SmartContract: { notIn: [ "0x4200000000000000000000000000000000000006" "0x0000000000000000000000000000000000000000" ] } } } Block: { Time: { since: "2024-12-01T00:00:00Z" } } } ) { Trade { Currency { Name Symbol SmartContract } } buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) trades: count volume: sum(of: Trade_Side_AmountInUSD) } } } ```
### 2. Token Volatility Analysis on Base Evaluate price stability and trading patterns for Base tokens.
Click to expand GraphQL query ```graphql query BaseTokenVolatility($tokenAddress: String!) { EVM(network: base, dataset: realtime) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $tokenAddress } } Side: { Currency: { SmartContract: { is: "0x4200000000000000000000000000000000000006" } } AmountInUSD: { gt: "100" } } } } ) { volatility: standard_deviation(of: Trade_PriceInUSD) avg_price: average(of: Trade_PriceInUSD) Trade { max_price: PriceInUSD(maximum: Trade_PriceInUSD) min_price: PriceInUSD(minimum: Trade_PriceInUSD) } } } } ```
**Use**: Assess price stability before entering positions on Base tokens. ### 3. Market Cap of a Base Token You can fetch Market Cap of a Base token using the below query.
Click to expand GraphQL query ```graphql query BaseTokenMarketCap($tokenAddress: String!) { EVM(network: base, dataset: realtime) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $tokenAddress } } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Trade { PriceInUSD Currency { Name Symbol SmartContract } } } } } ```
**Use**: Focus on Base tokens with strong liquidity to ensure reliable entry and exit points. ### 4. Base Token Supply Analysis (also helps in calculation of marketcap) Get comprehensive supply metrics for Base tokens.
Click to expand GraphQL query ```graphql query BaseTokenSupply($tokenAddress: String!) { EVM(network: base, dataset: combined) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: $tokenAddress } } Success: true } } ) { minted: sum( of: Transfer_Amount if: { Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } } } ) burned: sum( of: Transfer_Amount if: { Transfer: { Receiver: { is: "0x0000000000000000000000000000000000000000" } } } ) } } } ```
**Use**: Calculate circulating supply and assess tokenomics for Base tokens. ### 5. Base Token Holders Distribution (Security Check) Check token decentralization on Base to avoid risky, whale-dominated assets. `Holders` ranks a token's holders on a given `date`. For large tokens, set a balance floor (`Balance.Amount ge`) to keep the query fast.
Click to expand GraphQL query ```graphql query BaseHolders($tokenAddress: String!, $date: String!, $floor: String!) { EVM(network: base) { Holders( date: $date orderBy: { descending: Balance_Amount } limit: { count: 50 } where: { Currency: { SmartContract: { is: $tokenAddress } } Balance: { Amount: { ge: $floor } } } ) { Holder { Address } Balance { Amount } Currency { Name Symbol SmartContract } } } } ``` Variables: ```json { "tokenAddress": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "date": "2026-09-30", "floor": "1000000" } ```
**Use**: Avoid Base tokens with highly concentrated ownership that may be vulnerable to manipulation. ### 6. Base Wallet Balances Monitoring Review current portfolio composition on Base before making swaps.
Click to expand GraphQL query ```graphql query BaseWalletBalances($walletAddress: String!) { EVM(network: base, dataset: combined) { Balances( where: { Balance: { Address: { is: $walletAddress } } } orderBy: { descending: Balance_Amount } limit: { count: 100 } ) { Balance { Address Amount(selectWhere: { gt: "0" }) } Currency { Name Symbol SmartContract } } } } ```
**Use**: Determine available Base assets and calculate safe investment amounts for token swaps. ### 7. Base DEX Trade Streams for Real-Time Trades Subscribe to continuous streams of Base DEX trades for live market intelligence.
Click to expand GraphQL Stream ```graphql subscription BaseTradesStream { EVM(network: base) { DEXTrades { Block { Time Number } Transaction { Hash } Trade { Buy { Amount PriceInUSD Currency { Symbol SmartContract } Buyer } Sell { Amount PriceInUSD Currency { Symbol SmartContract } Seller } Dex { ProtocolName ProtocolFamily } } } } } ```
**Use**: React instantly to time-sensitive trades on Base DEXs. ## Calculating Trading Indicators for Base You can calculate SMA, EMA, RSI etc with Bitquery Base data. Your AI Agent can reconstruct Base token price charts and calculate: - **SMA 50**: Simple Moving Average over last 50 data points - **SMA 200**: Simple Moving Average over last 200 data points **Detect crossovers**: - SMA 50 crosses above SMA 200 → Consider Buy - SMA 50 crosses below SMA 200 → Consider Sell This logic can be integrated into the AI Trading Loop along with the Base on-chain analysis. ## Building the Base AI Trading Loop Your Base AI Trading Agent combines the above streams as follows: 1. **Fetch Top Trending Base Tokens** to shortlist candidates 2. **For each token**: - Analyze Liquidity, Volatility, and Holders Distribution - Check Supply metrics and tokenomics - Evaluate Base ecosystem fit 3. **Check Base Wallet Balances** to calculate possible investment amount 4. **Use Real-Time Base Trade Streams** to time the market entry 5. **Execute Swaps** on Base DEXs for high-potential tokens (not implemented, you can implement this) 6. **Continuously monitor** Base market data and adjust holdings as needed --- ## Build AI Trading Agents with Bitquery Solana Data URL: https://docs.bitquery.io/docs/blockchain/Solana/ai-agent-solana-data/ Solana AI trading agent guide: trending tokens, live trade streams, market cap and liquidity checks, wallet balances and holder distribution for agents. # Build AI Trading Agents with Bitquery Solana Data ## Recommended: Trading API feeds for agents (real-time + last ~30 days) For live signals, point your agent at the [**Trading API**](/docs/trading/trading-data-overview) — **USD price, market cap, and supply on every row**, MEV-filtered. The chain-level queries below remain the right tool for **history older than ~30 days** or instruction context. ### Trending Solana tokens by USD volume Run it [in the IDE](https://ide.bitquery.io/Trading-API-Trending-Tokens-Solana). ```graphql { Trading { Tokens( where: { Interval: {Time: {Duration: {eq: 3600}}} Token: {Network: {is: "Solana"}} Block: {Time: {since_relative: {hours_ago: 2}}} Volume: {Usd: {gt: 10000}} } limit: {count: 10} orderBy: {descending: Volume_Usd} ) { Token { Symbol Address Network } Interval { Time { Start Duration } } Volume { Base Usd } Price { Ohlc { Open High Low Close } } Supply { MarketCap FullyDilutedValuationUsd } } } } ``` ### Live Solana trade stream Run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains) — scoped here to Solana; drop the `Network` filter to stream all 10 chains. ```graphql subscription { Trading { Trades(where: {Pair: {Market: {Network: {is: "Solana"}}}}) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` In this section, we will explore how to use **Bitquery APIs and real-time streams** to build AI-enabled trading agents for the **Solana blockchain**. **Use the [Bitquery MCP Server](/docs/mcp/mcp-server/)** for the hosted ClickHouse-backed MCP, or follow this [walkthrough on building MCPs with Bitquery](https://youtu.be/q-QL5EGfT5k). For **ready-made [OpenClaw](https://openclaw.ai/) skills** that pipe Bitquery WebSocket feeds into an agent (Bitcoin price, multi-token USD charts, Pump.fun, Polymarket, Solana stablecoin transfers), install from [ClawHub](https://clawhub.ai/) and see the skill list and setup in [bitquery/openclaw-skills-master](https://github.com/bitquery/openclaw-skills-master). ClawHub usage: [ClawHub CLI docs](https://docs.openclaw.ai/tools/clawhub). **Your AI Trading Agent's Mission:** >You are a specialized trading agent operating on the Solana blockchain, you will optimize an existing portfolio by analyzing and trading trending tokens using Bitquery data. Your primary goal is to identify profitable tokens in the market, assess wallet balances, and execute calculated swap decisions to enhance portfolio value. ``` prompt = ( f"Analyze the following Solana token:\n" f"Name: {token_data['name']}\n" f"Symbol: {token_data['symbol']}\n" f"Market Cap: {token_data['market_cap']}\n" f"Liquidity (USD): {token_data['liquidity_usd']}\n" f"Volatility: {token_data['volatility']}\n" f"Top Holder Concentration (%): {token_data['holder_concentration']}\n" "\nBased on this data, decide whether to 'Buy', 'Avoid', or 'Hold'. Only reply with one word: Buy, Avoid, or Hold." ) ``` ### Trading Decision Process This is a rough draft of what an AI agent can do using on-chain and off-chain data: 1. Use trending data to identify promising tokens with potential profit. Cross-check narratives with live category dashboards on [DEXrabbit](https://dexrabbit.bitquery.io/categories) — for example [AI Agents](https://dexrabbit.bitquery.io/categories/ai-agents), [Solana Meme Coins](https://dexrabbit.bitquery.io/categories/solana-meme-coins), or [Pump.fun](https://dexrabbit.bitquery.io/categories/pump-fun). 2. For each trending token, retrieve detailed information to evaluate its market cap, liquidity, volatility, and security. 3. Check the wallet balance to understand the available assets and decide on a safe percentage to invest. 4. Execute swaps to acquire trending tokens, ensuring the chosen amount. 5. Continuously monitor token performance and adjust holdings to maximize profits. For this you can use [Bitquery Shred Streams](/docs/streams/real-time-solana-data/#kafka-stream-by-bitquery) to monitor token prices, new token creation and other activities with sub-second latency. ## Code Structure and Logic: A Good Starting Point Your code sets up a flexible AI trading agent framework, handling: - backtesting : historical simulation. - live mode: real-time trading/decision making - Portfolio tracking (cash, positions, realized gains) - Integration with an AI model (likely LLM) to guide trading decisions - where the AI agent makes data-driven trading decisions based on Bitquery Solana data. Below is a sample project structure: ``` ai_trading_agent/ ├── main.py # Entry point for agent ├── bitquery_utils.py # Bitquery API functions ├── ai_decision.py # AI model logic for trade decisions ├── wallet_utils.py # Wallet balance + transaction logic ├── config.env # Store API keys securely ``` ## Video Tutorial ## Key Bitquery Streams and Queries for Trading Agents ### 1. Top Trending Tokens Detect tokens with rising popularity and trader activity. **Docs:** [Top 10 Trending Solana Tokens](/docs/blockchain/Solana/solana-dextrades/#top-50-trending-solana-token-pairs-with-all-the-data)
Click to expand GraphQL query ```graphql query TrendingTokens { Solana(network: solana, dataset: realtime) { DEXTradeByTokens( limit: {count: 10} orderBy: {descendingByField: "tradesCountWithUniqueTraders"} where: {Trade: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112","11111111111111111111111111111111"]}}}} ) { Trade { Currency { Name Symbol MintAddress } } tradesCountWithUniqueTraders: count(distinct: Transaction_Signer) } } } ```
**Use:** Filter tokens with rising trader activity to shortlist tokens to buy. ### 3. Marketcap & Liquidity Pool Analysis Evaluate token liquidity to avoid low-volume or illiquid tokens. **Docs:** [Top Pools based on Liquidity](/docs/blockchain/Solana/Solana-DexPools-API/#get-top-pools-based-on-liquidity) [Run Query](https://ide.bitquery.io/top-10-liquidity-pools_1)
Click to expand GraphQL query ```graphql query GetTopPoolsByDex { Solana { DEXPools( orderBy: { descending: Pool_Quote_PostAmount } where: { Block: { Time: { after: "2024-08-27T12:00:00Z" } } Transaction: { Result: { Success: true } } } limit: { count: 10 } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolName ProtocolFamily } Quote { PostAmount PostAmountInUSD PriceInUSD } Base { PostAmount } } } } } ```
#### Marketcap of a token You can fetch Marketcap of a token using below query. [Run Query](https://ide.bitquery.io/market-cap-of-token_1) [Docs](/docs/blockchain/Solana/token-supply-cube/#marketcap-of-a-token)
Click to expand GraphQL query ```graphql query MyQuery { Solana { TokenSupplyUpdates( where: {TokenSupplyUpdate: {Currency: {MintAddress: {is: "6D7NaB2xsLd7cauWu1wKk6KBsJohJmP2qZH9GEfVi5Ui"}}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { TokenSupplyUpdate { PostBalanceInUSD } } } } ```
**Use:** Focus on tokens with strong liquidity to ensure reliable entry and exit points. ### 4. Wallet Balances Monitoring Review current portfolio composition before making swaps. **Docs:** [Account Balances on Solana](/docs/blockchain/Solana/solana-balance-updates/#get-all-the-tokens-owned-by-an-address) [Run Query](https://ide.bitquery.io/tokens-owned-by-an-address)
Click to expand GraphQL query ```graphql query MyQuery { Solana { BalanceUpdates( where: { BalanceUpdate: { Account: { Owner: { is: "WALLET ADDRESS" } } } } orderBy: { descendingByField: "BalanceUpdate_Balance_maximum" } ) { BalanceUpdate { Balance: PostBalance(maximum: Block_Slot) Currency { Name Symbol } } } } } ```
**Use:** Determine available assets and calculate safe investment amounts for token swaps. ### 5. DEX Trade Streams for Real-Time Trades Subscribe to continuous streams of Solana DEX trades for live market intelligence. [Solana Trade Stream Run](https://ide.bitquery.io/solana-trades-subscription_3) The same stream can be obtained with lower latency via [Kafka containing Solana Shreds](/docs/streams/protobuf/chains/Solana-protobuf/).
Click to expand GraphQL Stream ```graphql subscription { Solana { DEXTrades { Block { Time Slot } Transaction { Signature Index Result { Success } } Trade { Index Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Amount Account { Address } Currency { MetadataAddress Key MintAddress IsMutable EditionNonce Decimals CollectionAddress Fungible Symbol Native Name } Price PriceInUSD Order { LimitPrice LimitAmount OrderId } } Market { MarketAddress } Sell { Account { Address } Currency { IsMutable Decimals CollectionAddress Fungible Symbol Native Name } Price PriceInUSD } } } } } ```
**Use:** React instantly to time-sensitive trades. ### 6. Token Holders Distribution (Security Check) Check token decentralization to avoid risky, whale-dominated assets. The query ranks wallets by the sum of their balance changes, which equals their current balance for a token launched within the real-time window (about 12 hours). For older tokens such as USDC, use the V1 method on the [Solana Token Holders API](/docs/blockchain/Solana/solana-token-holders/) page.
Click to expand GraphQL query ```graphql query TopHolders($token: String!) { Solana(dataset: realtime) { BalanceUpdates( limit: { count: 100 } orderBy: { descendingByField: "Holding" } where: { BalanceUpdate: { Currency: { MintAddress: { is: $token, not: "" } } } Transaction: { Result: { Success: true } } } ) { BalanceUpdate { Account { Owner } } Holding: sum(of: BalanceUpdate_Amount) } } } ``` ```json { "token": "token mint address" } ```
**Use:** Avoid tokens with highly concentrated ownership that may be vulnerable to manipulation. ### 7. Avoiding Bots with DEXRabbit (Built by Bitquery) Your AI Trading Agent should monitor **bot activity** on DEXs. Bots can cause **sudden price spikes**, **wash trading**, or manipulate token prices, posing risks to human traders. **[DexRabbit.bitquery.io](https://dexrabbit.bitquery.io/)**, built on Bitquery data, offers charts and dashboards to detect bot activity in real-time. ### Key Bot Activity Indicators to Monitor: ![DexRabbit Bot Detection using Charts](/img/usecases/gopher_bot.png) | Indicator | Description | | -------------------------------------- | --------------------------------------------------------------------- | | **Highly repetitive trade patterns** | Identical trades happening in short intervals suggest bot activity. | | **Large trade bursts at odd hours** | Bots often execute trades at low-liquidity times to influence price. | | **Frequent pump-and-dump patterns** | Sharp price surges followed by rapid sell-offs indicate manipulation. | | **Unusual token holder concentration** | Bots may use multiple wallets to appear as unique traders. | ## Calculating Trading Indicators You can SMA, EMA, RSI etc with Bitquery data. A tutorial is available [here](/docs/usecases/trading-indicators/) Your AI Agent can reconstruct price charts and calculate: - SMA 50: Simple Moving Average over last 50 data points (could be trades, time intervals, etc.). - SMA 200: Simple Moving Average over last 200 data points. Detect crossovers: - SMA 50 crosses above SMA 200 → Consider Buy. - SMA 50 crosses below SMA 200 → Consider Sell. This logic can be integrated into the AI Trading Loop along with the on-chain analysis. ## Building the AI Trading Loop Your AI Trading Agent combines the above streams as follows: 1. Fetch Top Trending Tokens to shortlist candidates. 2. For each token: - Analyze Liquidity, Volatility, and Holders Distribution. 3. Check Wallet Balances to calculate possible investment amount. 4. Use Real-Time Trade Streams to time the market entry. 5. Execute Swaps on high-potential tokens. 6. Continuously monitor market data and adjust holdings as needed. ## Next Steps - Integrate these Bitquery APIs into your AI agent. - Define risk management parameters, such as maximum percentage of balance per trade. - Automate decision-making logic based on market data. - Continuously refine and improve trading strategies using real-time data. You can also integrate off-chain information like Twitter feeds to decide if a token is worth investing - Combine with **NLP (Natural Language Processing)** to do **sentiment analysis** on tweets. - Build **alert systems** based on specific keywords or sentiment spikes. - Monitor tweets from key influencers and trigger trades based on their content. - Use Twitter data as a factor in your **AI models' decision-making**. --- _This material is for educational and informational purposes only and is not intended as investment advice. The content reflects the author's personal research and understanding. While specific investments and strategies are mentioned, no endorsement or association with these entities is implied. Readers should conduct their own research and consult with qualified professionals before making any investment decisions. Bitquery is not liable for any losses or damages resulting from the application of this information._ --- ## Build Solana OHLC from DEX Trades URL: https://docs.bitquery.io/docs/usecases/solana-ohlc-calculator/ Calculate Solana OHLC candles from Bitquery DEX trades with JavaScript examples for intervals, pricing, and chart integrations. # Build OHLC Values using DEX Trades Data This script calculates **OHLC (Open, High, Low, Close)** data for a particular Token Pair Solana-based trades by leveraging percentile filtering thus removing anomaly or bot trades. It fetches trading data from the Bitquery API and processes it to compute the OHLC values for a specific trading pair. For pre-aggregated OHLC data, see our [Crypto Price API](/docs/trading/crypto-price-api/). The sole motive of this tutorial is to guide you how an OHLC is calculated and Bot trades or anomaly trades are filtered out. We have shown one of the by using `quantile`, you can devise your own strategy to use different filters or logics to omit these anomaly trades. ## Tutorial Video ## Features - Fetches the 5th and 95th percentiles of trade prices for a specific Solana trading pair. - Filters trades within the percentile price range. - Computes and displays **OHLC** data: - **Open**: The first trade's price. - **High**: The highest trade price. - **Low**: The lowest trade price. - **Close**: The last trade's price. ## Prerequisites Make sure you have the following before starting: 1. **Node.js** installed on your system. 2. A **Bitquery API token** to fetch data from the APIs You can get your API token from Bitquery using these steps [here](/docs/authorization/how-to-generate/). 3. Information about the Solana trading pair you want to analyze: - **Main Currency Address**: The mint address of the main currency. - **Side Currency Address**: The mint address of the side currency. - **Market Pair Address**: The address of the trading pair. ## Installation 1. Clone this repository and navigate to the project directory: ```bash git clone https://github.com/Akshat-cs/OHLC-Calculator-Solana.git ``` 2. Install the required dependencies: ```bash npm install ``` 3. Create a `.env` file in the root directory and add your Bitquery API Token, check the steps to get it [here](/docs/authorization/how-to-generate/): ``` AUTH_TOKEN = ``` ## Configuration Before running the script, update the following constants in the code (`index.js`) to match your Solana trading pair details: ```javascript const MAIN_CURRENCY_ADDRESS = "9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump"; const SIDE_CURRENCY_ADDRESS = "So11111111111111111111111111111111111111112"; const PAIR_ADDRESS = "Bzc9NZfMqkXR6fz1DBph7BDf9BroyEf6pnzESP7v5iiw"; ``` ## Usage To calculate OHLC values, run the script: ```bash node index.js ``` ## Script Workflow 1. Fetches the 5th and 95th percentiles of trade prices for the past hour using the Bitquery API. 2. Retrieves trades that fall within the calculated percentile price range. 3. Computes the **OHLC** data based on the filtered trades: - **Open**: The price of the earliest trade. - **High**: The highest trade price. - **Low**: The lowest trade price. - **Close**: The price of the latest trade. 4. Displays the OHLC values in the console. ## Code Overview ### 1. Fetching Percentiles The `fetchPercentiles` function retrieves the 5th and 95th percentiles for the specified trading pair using the Bitquery API. ```javascript async function fetchPercentiles() { const timestamp1Hago = getTimestamp(60); const percentileData = JSON.stringify({ query: `query ($mainCurrencyAddress: String , $sideCurrencyAddress: String, $pairAddress: String, $timestamp1Hago: DateTime ) { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: $mainCurrencyAddress}}, Side: {Currency: {MintAddress: {is: $sideCurrencyAddress}}}, Market: {MarketAddress: {is: $pairAddress}}}, Transaction: {Result: {Success: true}}, Block: {Time: {since: $timestamp1Hago}}} ) { percentile5th: quantile(of: Trade_PriceInUSD, level: 0.05) percentile95th: quantile(of: Trade_PriceInUSD, level: 0.95) } } }`, variables: JSON.stringify({ mainCurrencyAddress: MAIN_CURRENCY_ADDRESS, sideCurrencyAddress: SIDE_CURRENCY_ADDRESS, pairAddress: PAIR_ADDRESS, timestamp1Hago, }), }); const config = { method: "post", maxBodyLength: Infinity, url: API_URL, headers: { "Content-Type": "application/json", Authorization: `Bearer ${AUTH_TOKEN}`, }, data: percentileData, }; try { const response = await axios.request(config); return response.data.data.Solana.DEXTradeByTokens[0]; } catch (error) { console.error("Error fetching percentiles:", error); throw error; } } ``` ### 2. Fetching Trades and Computing OHLC The `fetchTradesAndComputeOHLC` function retrieves trades within the specified percentile price range and calculates the **OHLC** values: - **Open**: The price of the earliest trade. - **High**: The highest trade price. - **Low**: The lowest trade price. - **Close**: The price of the latest trade. ```javascript async function fetchTradesAndComputeOHLC(lowerBoundPrice, upperBoundPrice) { const timestamp1Hago = getTimestamp(60); const tradeData = JSON.stringify({ query: `query ($mainCurrencyAddress: String , $sideCurrencyAddress: String, $pairAddress: String, $lowerBoundPrice: Float, $upperBoundPrice: Float, $timestamp1Hago: DateTime ) { Solana { DEXTradeByTokens( orderBy: {descending: Block_Time} where: {Trade: {Currency: {MintAddress: {is: $mainCurrencyAddress}}, Side: {Currency: {MintAddress: {is: $sideCurrencyAddress}}}, Market: {MarketAddress: {is: $pairAddress}}, PriceInUSD: {ge: $lowerBoundPrice, le: $upperBoundPrice}}, Transaction: {Result: {Success: true}}, Block: {Time: {since: $timestamp1Hago}}} ) { Block { Time Slot } Trade { Price PriceInUSD } } } }`, variables: JSON.stringify({ mainCurrencyAddress: MAIN_CURRENCY_ADDRESS, sideCurrencyAddress: SIDE_CURRENCY_ADDRESS, pairAddress: PAIR_ADDRESS, lowerBoundPrice, upperBoundPrice, timestamp1Hago, }), }); const config = { method: "post", maxBodyLength: Infinity, url: API_URL, headers: { "Content-Type": "application/json", Authorization: `Bearer ${AUTH_TOKEN}`, }, data: tradeData, }; try { const response = await axios.request(config); const trades = response.data.data.Solana.DEXTradeByTokens; if (trades.length === 0) { console.log("No trades found."); return; } // Compute OHLC const ohlc = { open: trades[trades.length - 1].Trade.Price, high: Math.max(...trades.map((t) => t.Trade.Price)), low: Math.min(...trades.map((t) => t.Trade.Price)), close: trades[0].Trade.Price, }; console.log("OHLC:", ohlc); } catch (error) { console.error("Error fetching trades:", error); } } ``` This function ensures the OHLC values are accurately calculated based on filtered trade data within the provided range. ### 3. Main Execution The `main` function orchestrates the entire process by: 1. Fetching the 5th and 95th percentiles for the specified trading pair. 2. Using these percentiles to filter trades within the range. 3. Computing and displaying the **OHLC** data. ```javascript // Main Function (async function main() { try { const percentiles = await fetchPercentiles(); await fetchTradesAndComputeOHLC( percentiles.percentile5th, percentiles.percentile95th ); } catch (error) { console.error("Error in main function:", error); } })(); ``` This function acts as the entry point for the script, coordinating the percentile fetching and OHLC calculation in a seamless workflow. --- ## Build Trading Indicators for Crypto Data URL: https://docs.bitquery.io/docs/usecases/trading-indicators/ Build Trading Indicators for Crypto Data: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Build Trading Indicators for Crypto Data Technical indicators are a vital tool for cryptocurrency traders, as they can help to identify trends, predict price movements, and make informed trading decisions. For real-time price data with pre-calculated indicators, use our [Crypto Price API](/docs/trading/crypto-price-api/). With our new [Crypto Price Stream](/docs/trading/crypto-price-api/) we can get real-time crypto market data with **Simple Moving Average (SMA)**, **Exponential Moving Average (EMA)**, and **Weighted Simple Moving Average (WSMA)** at 1-second interval precalculated. In this tutorial we will see how to stream them and calculate advanced trading indicators. **This code is available readily as a Python package [here](https://pypi.org/project/bitquery-trading-indicators-stream/)** The list of indicators we will be calculating - Simple Moving Average (SMA) - Exponential Moving Average (EMA) - Weighted Simple Moving Average - Relative Strength Index (RSI) - Volume Weighted Average Price (VWAP) ### Sample Output **Step 1: Setup WebSocket Connection** ```python from gql import gql from gql.transport.websockets import WebsocketsTransport transport = WebsocketsTransport( url=f"wss://streaming.bitquery.io/graphql?token={config.oauth_token}", headers={"Sec-WebSocket-Protocol": "graphql-ws"} ) await transport.connect() print("Connected") ``` **Remember:** Replace `YOUR_TOKEN` with an OAuth token from your Bitquery account. You can generate it [here](https://account.bitquery.io/user/api_v2/access_tokens) **Step 2: Subscribe to the Price Feed** We write a query to get OHLC data for the Uniswap pair ETH-DAI, filtering for trades in the past 10 minutes and returning the volume, trade details, and block timestamps. You can [extend the query to get data for longer duration of different periods like year/month/day](https://ide.bitquery.io/USDT-OHLC-Price-Data-V2_3). We’ll request **Solana token** prices in **1-minute intervals**, including SMA/EMA/WSMA. > Streaming every token on a chain is a good fit for the `Tokens` cube. To compute indicators for **one specific token**, swap in [`Pairs` with `Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price): the same `Price.Average` fields (`SimpleMoving`, `ExponentialMoving`, `WeightedSimpleMoving`) are available there, computed from the token's top market rather than blended across all of its pools. ```python query = gql(""" subscription { Trading { Tokens( where: { Token: { Network: { is: "Solana" } }, Interval: { Time: { Duration: { eq: 1 } } } } ) { Token { Address Symbol } Interval { Time { End } } Volume { Base Quote Usd } Price { Ohlc { Close } Average { SimpleMoving ExponentialMoving WeightedSimpleMoving } } } } } """) async for data in transport.subscribe(query): for t in data["Trading"]["Tokens"]: close = t["Price"]["Ohlc"]["Close"] sma = t["Price"]["Average"]["SimpleMoving"] ema = t["Price"]["Average"]["ExponentialMoving"] wsma = t["Price"]["Average"]["WeightedSimpleMoving"] # Choose a volume basis suitable for your use case volume = (t.get("Volume", {}).get("Base") or t.get("Volume", {}).get("Quote") or t.get("Volume", {}).get("Usd") or 1.0) print(t["Token"]["Address"], sma, ema, wsma, close, volume) ``` **Step 3: Calculate RSI in Real Time** We’ll keep RSI state in memory for each token and update it with **Wilder’s smoothing**. ```python rsi_period = 14 state = {} # address → RSI state def update_rsi(address, close): s = state.setdefault(address, {"prev_close": None, "avg_gain": 0, "avg_loss": 0, "count": 0, "initialized": False}) if s["prev_close"] is None: s["prev_close"] = close return None delta = close - s["prev_close"] gain, loss = max(delta, 0), max(-delta, 0) if not s["initialized"]: s["avg_gain"] += gain s["avg_loss"] += loss s["count"] += 1 if s["count"] >= rsi_period: s["avg_gain"] /= rsi_period s["avg_loss"] /= rsi_period s["initialized"] = True else: s["avg_gain"] = ((s["avg_gain"] * (rsi_period - 1)) + gain) / rsi_period s["avg_loss"] = ((s["avg_loss"] * (rsi_period - 1)) + loss) / rsi_period s["prev_close"] = close if not s["initialized"]: return None return 100 if s["avg_loss"] == 0 else 100 - (100 / (1 + s["avg_gain"] / s["avg_loss"])) ``` **Step 4: Calculate VWAP (rolling window)** We maintain a small rolling window of prices and volumes per token for a simple, streaming VWAP. ```python from collections import defaultdict vwap_period = 20 vwap_state = defaultdict(lambda: {"prices": [], "volumes": [], "pv_sum": 0.0, "vol_sum": 0.0}) def update_vwap(address, price, volume): s = vwap_state[address] s["prices"].append(price) s["volumes"].append(volume) if len(s["prices"]) > vwap_period: rp = s["prices"].pop(0) rv = s["volumes"].pop(0) s["pv_sum"] -= rp * rv s["vol_sum"] -= rv s["pv_sum"] += price * volume s["vol_sum"] += volume return s["pv_sum"] / s["vol_sum"] if s["vol_sum"] > 0 else price ``` **Step 5: Putting It Together** Inside your subscription loop: ```python for t in data["Trading"]["Tokens"]: address = t["Token"]["Address"] close = t["Price"]["Ohlc"]["Close"] sma = t["Price"]["Average"]["SimpleMoving"] ema = t["Price"]["Average"]["ExponentialMoving"] wsma = t["Price"]["Average"]["WeightedSimpleMoving"] volume = (t.get("Volume", {}).get("Base") or t.get("Volume", {}).get("Quote") or t.get("Volume", {}).get("Usd") or 1.0) rsi = update_rsi(address, close) vwap = update_vwap(address, float(close), float(volume)) if rsi is not None: print(f"{address} SMA:{sma} EMA:{ema} WSMA:{wsma} VWAP:{vwap:.6f} RSI:{rsi:.2f} Close:{close}") ``` **Advantages of this approach:** - **No polling** — prices are pushed to you as soon as they’re available. - **Built-in indicators** — SMA/EMA/WSMA come directly from Bitquery. - **Custom logic** — you can add advanced indicators like RSI without losing speed. --- ## Build a Trading Agent with Bitquery MCP URL: https://docs.bitquery.io/docs/mcp/build-a-trading-agent/ Build a Trading Agent with Bitquery MCP with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Build a Trading Agent with Bitquery MCP Use Bitquery's MCP server as the data layer for an AI trading agent: discover trending tokens, pull OHLC and liquidity, watch wallets, and alert on volume spikes — without writing GraphQL by hand. ## Architecture ``` Your agent (Claude / Cursor / custom) → mcp.bitquery.io → Bitquery trading dataset ``` The agent calls MCP tools in plain English; Bitquery returns structured trade, price, and wallet data from the same production dataset as the GraphQL API. The same server covers Hyperliquid perpetuals and spot markets: funding, open interest, liquidations and trader positions. See [Hyperliquid MCP](/docs/mcp/hyperliquid/). ## Step 1 — Connect MCP Pick your runtime: | Client | Config | |--------|--------| | Claude Desktop | Custom connector → `https://mcp.bitquery.io` | | Cursor | `.cursor/mcp.json` with `mcp-remote` → `https://mcp.bitquery.io/mcp` | | Claude Code | `claude mcp add bitquery -- npx -y mcp-remote https://mcp.bitquery.io/mcp` | Sign in with a [Bitquery account](https://account.bitquery.io/) on first tool call. The client opens a browser once for OAuth 2.1, then caches and refreshes the token for you (see [MCP overview](/docs/mcp/mcp-server/#first-connection-and-permissions)). ## Step 2 — Discovery loop Ask the agent to rank tokens by volume, filter wash trading, and return mint/ pool addresses: > *"Top 20 Solana tokens by USD volume in the last 24h, exclude pools with suspicious wash patterns."* Save mint addresses for monitoring. ## Step 3 — Price & liquidity monitoring > *"1-minute OHLC for [TOKEN] on Raydium for the last 6 hours."* > *"Alert me when 5m volume on [POOL] exceeds 2× its 24h average."* For sub-second pipelines (under 500ms on Kafka, under 300ms on Solana gRPC), graduate to [Kafka](/docs/streams/kafka-streaming-concepts/) or [Solana protobuf streams](/docs/streams/protobuf/chains/Solana-protobuf/) after validating logic via MCP. ## Step 4 — Wallet intelligence > *"All trades for wallet [ADDRESS] on Base in the last 7 days with realised PnL per token."* Combine with your execution layer (CEX, on-chain router, etc.) — MCP is read-only and does not place trades. ## Next steps - [MCP server overview](/docs/mcp/mcp-server/) - [Cursor setup](/docs/mcp/cursor/) - [Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades/) - [Trading cube overview](/docs/trading/trading-data-overview/) --- ## Building GraphQL Queries on Bitquery: First Query to Aggregates URL: https://docs.bitquery.io/docs/category/building-queries/ From a first Bitquery GraphQL query to filters, datasets, metrics and the schema reference: what each guide covers and the order to read them in. # Building GraphQL Queries on Bitquery: First Query to Aggregates Every Bitquery query has the same shape: a root for the chain or the Trading family, a cube for the kind of fact, a `where` filter, an `orderBy`, a `limit`, and a selection of fields or metrics. Learn that shape once and it carries across every chain and cube. This section takes you from a first query to aggregates and history in four steps: query principles and filters, datasets that decide how far back you reach, metrics that turn rows into numbers, and the schema reference for field names. Everything runs in the [Bitquery IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. ## Read in this order | Step | Guide | What you get | |---|---|---| | 1 | [Query principles](/docs/graphql/query) | The root, cube, filter and selection structure | | 2 | [Query filters](/docs/graphql/filters), [date and time filters](/docs/graphql/datetime), [relative time](/docs/graphql/capabilities/relative-time) | Narrowing rows by address, token, amount and time | | 3 | [Dataset options](/docs/graphql/dataset/options), [realtime](/docs/graphql/dataset/realtime), [archive](/docs/graphql/dataset/archive), [combined](/docs/graphql/dataset/combined) | How far back a query can reach and how fresh it is | | 4 | [Metrics overview](/docs/graphql/metrics/metrics), [count](/docs/graphql/metrics/count), [sum](/docs/graphql/metrics/sum), [uniq](/docs/graphql/metrics/uniq), [quantile](/docs/graphql/metrics/quantile), [conditional metrics](/docs/graphql/metrics/if) | Aggregates, conditions and statistics | | 5 | [Sorting](/docs/graphql/sorting), [limits](/docs/graphql/limits), [indexed fields](/docs/graphql/indexed-fields-reference), [optimizing queries](/docs/graphql/optimizing-graphql-queries) | Fast, well-formed queries | | 6 | [EVM schema reference](/docs/schema/evm/dextrades) | Exact field names per cube | The [data coverage and retention](/docs/graphql/data-coverage-retention) page answers "how far back does the data go" per cube and chain, and the [capabilities](/docs/category/capabilities) section covers joins, calculations, JSON filters and subscriptions. ## A first query The five most recent transfers on Ethereum: one root, one cube, an order and a limit. ```graphql { EVM(network: eth) { Transfers(limit: { count: 5 }, orderBy: { descending: Block_Time }) { Block { Time } Transfer { Amount Currency { Symbol } Sender Receiver } } } } ``` From here, add a `where` to pick one token or one wallet, replace the field list with `count` and `sum(of: Transfer_Amount)` to aggregate, add `dataset: archive` to the root to reach history, or change `query` to `subscription` to stream new transfers. ## The four groups in this section - **Capabilities** (20 pages): filters, time windows, sorting, limits, aggregates, calculations, joins, array and JSON filters, subscriptions, Postman. [Open the capabilities hub](/docs/category/capabilities). - **Dataset** (7 pages): [options](/docs/graphql/dataset/options), [realtime](/docs/graphql/dataset/realtime), [archive](/docs/graphql/dataset/archive), [combined](/docs/graphql/dataset/combined), [database selection](/docs/graphql/dataset/database), [network selection](/docs/graphql/dataset/network), [reorg handling](/docs/graphql/dataset/select-blocks). - **Metrics** (11 pages): [overview](/docs/graphql/metrics/metrics), [alias](/docs/graphql/metrics/alias), [count](/docs/graphql/metrics/count), [distinct](/docs/graphql/metrics/distinct), [if](/docs/graphql/metrics/if), [priceAsymmetry](/docs/graphql/metrics/priceAsymmetry), [selectWhere](/docs/graphql/metrics/selectWhere), [statistics](/docs/graphql/metrics/statistics), [sum](/docs/graphql/metrics/sum), [uniq](/docs/graphql/metrics/uniq), [quantile](/docs/graphql/metrics/quantile). - **Schema reference** (11 pages): [blocks](/docs/schema/evm/blocks), [miner rewards](/docs/schema/evm/miners), [uncles](/docs/schema/evm/uncles), [balances](/docs/schema/evm/balances), [token holders](/docs/schema/evm/token-holders), [transfers](/docs/schema/evm/transfers), [transactions](/docs/schema/evm/transactions), [events](/docs/schema/evm/events), [DEX trades](/docs/schema/evm/dextrades), [calls](/docs/schema/evm/calls), [arguments and returns](/docs/schema/evm/arguments). ## Related pages - [GraphQL query capabilities](/docs/category/capabilities) - [Understanding cubes](/docs/category/understanding-cubes) - [How to generate an access token](/docs/authorization/how-to-generate/) - [Data coverage and retention](/docs/graphql/data-coverage-retention) --- ## Building a Basic UI for Balance Tracker URL: https://docs.bitquery.io/docs/usecases/real-time-balance-tracker/ui/ Building a Basic UI for Balance Tracker: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Building a Basic UI for Balance Tracker In this section we will create a simple UI using HTML, CSS and JavaScript to make the real-time Balance Tracker intuitive. For that we will create a HTML file named `index.js` in the same directory. ## HTML Code ``` html

Enter Address to Track Balance

Current Balance: 0 ETH

``` To run the project run the following command: ```bash node index.js ``` Now we can check the UI and test the project by visiting `localhost:3000`. **Note:** Make sure that the port 3000 is free. ## Final Results This is how the real-time Balance Tracker UI looks. You can enter any wallet address of your choice and track its activities, by tracking its Ethereum Balance changes in real-time. ![Balance Tracker](/img/real_time_balance_tracker_demo.png) To avoid redundancy, it updates the balance every 10 seconds. --- ## Building a Trading Bot Using Bitquery Kafka Streams URL: https://docs.bitquery.io/docs/streams/sniper-trade-using-bitquery-kafka-stream/ Building a Trading Bot Using Bitquery Kafka Streams with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. # Building a Trading Bot Using Bitquery Kafka Streams This is a tutorial to build a fast, automated BSC (Binance Smart Chain) sniper bot for trading newly launched Four Meme tokens. The bot **detects new token launches in real time via [Bitquery’s Kafka streams](/docs/streams/kafka-streaming-concepts/)**, buys them instantly using the Four Meme Launchpad contract, and sells them after 1 minute—aiming to capitalize on rapid price movements. Checkout the complete codebase [here](https://github.com/bitquery/sniper-bot-bsc) if facing any issue. :::note Use a wallet/private key with only test funds **at your own risk** as this bot is highly experimental and is for **educational use only**! ::: --- ## Features - **Real-Time Token Detection:** Subscribes to Bitquery's Kafka protobuf streams to spot new Four Meme token launches within seconds. - **Automated Buy & Sell:** Uses the Four Meme Launchpad DEX smart contract to buy new tokens and automatically sell them after 60 seconds. - **Nonce & Gas Handling:** Handles transaction nonces and gas prices to handle failed/reverted transaction errors. --- ## Final Output --- ## Creating `.env` File Create a `.env` file and define these variables. - PRIVATE_KEY1: Private key of your custodial wallet. - KAFKA_USERNAME: Bitquery Protobuf Kafka stream username. Contact us on our [Telegram Channel](https://t.me/Bloxy_info) - KAFKA_PASSWORD: Bitquery Protobuf Kafka stream password. ## Understanding the Functions In this section, we will explore the code logic behind the important functions used in our trading bot that are written in `executeTrade.js` file, namely: - `buyViaLaunchpad` - `sellTokenViaLaunchpad` - `sendTxWithNonce` This is how the folder structure looks. EVM sniper bot project files on the main branch: .gitignore, Readme.md, executeTrade.js, index.js, package-lock.json and package.json The code snippet below includes all the imports for the `executeTrade.js` file and setup wallet and provider for trade execution. ```js dotenv.config(); const RPC_URL = "https://bsc-dataseed.binance.org/"; const provider = new JsonRpcProvider(RPC_URL); const privateKey = process.env.PRIVATE_KEY1; const wallet = new Wallet(privateKey, provider); ``` ## Setting Up the Kafka Consumer to Listen to Bitquery Streams In this section we will setup a Kafka consumer in JS using the `kafkajs` library. Extended tutorials for other languages are available above. ### Imports ```js const { CompressionTypes, CompressionCodecs } = pkg; CompressionCodecs[CompressionTypes.LZ4] = new LZ4().codec; ``` ### Defining Constants ```js const username = process.env.KAFKA_USERNAME; const password = process.env.KAFKA_PASSWORD; const topic = "bsc.tokens.proto"; const id = uuidv4(); ``` ### Initialising Kafka Consumer ```js const kafka = new Kafka({ clientId: username, brokers: [ "rpk0.bitquery.io:9092", "rpk1.bitquery.io:9092", "rpk2.bitquery.io:9092", ], sasl: { mechanism: "scram-sha-512", username: username, password: password, }, }); const consumer = kafka.consumer({ groupId: username + "-" + id }); ``` ### Creating `convertBytes` Helper Function Since the on-chain data is encoded in hex, we will need a convert function to get them into human readable format. ```js const convertBytes = (value, encoding = "hex") => { if (encoding === "base58") { return bs58.default.encode(value); } return value?.toString("hex"); }; ``` ### Send Transaction with Nonce Functionality The main purpose of this function is to make the overall trade execution of the bot less prone to errors due to transaction failure/revert. This would avoid scenarios where a token might be purchased but not sold due to transaction failure, which could lead to losses. 1. Defining Variable and Nonce Initiator ```js let nextNonce; async function initNonce() { const current = await provider.getTransactionCount(wallet.address, "pending"); nextNonce = BigInt(current); } ``` 2. Creating the `sendTxWithNonce` Function ```js async function sendTxWithNonce(txRequest, maxRetries = 3) { if (typeof nextNonce === "undefined") { // If nonce not initialized yet, wait briefly await new Promise((r) => setTimeout(r, 500)); } for (let attempt = 0; attempt <= maxRetries; attempt++) { try { // Attach the current nonce txRequest.nonce = Number(nextNonce); // Slot in a default gasPrice if not explicitly set: if (!txRequest.gasPrice) { const base = (await provider.getFeeData()).gasPrice; txRequest.gasPrice = base; } const txResponse = await wallet.sendTransaction(txRequest); nextNonce++; // only bump after successful send return await txResponse.wait(); } catch (err) { const msg = (err.reason || err.message || "").toLowerCase(); if (msg.includes("replacement underpriced") && attempt < maxRetries) { // bump gasPrice by ~10% and retry const bumped = (BigInt(txRequest.gasPrice) * 110n) / 100n; txRequest.gasPrice = bumped; console.warn( `⚠️ Replacement underpriced—bumping gas to ${bumped.toString()} and retrying (${ attempt + 1 }/${maxRetries})` ); continue; } throw err; } } throw new Error("Exceeded maxRetries for transaction"); } ``` ## Buy Token Functionality via Launchpad In this section we will how to automate the buy functionality using etherjs. The code snippets given below are written in `executeTrade.js` file, which is in the same directory as the `index.js`(entrypoint) file. 1. Defining Constants ```js // Launchpad contract (for both buy and sell) const LAUNCHPAD_ADDRESS = ethers.getAddress( "0x5c952063c7fc8610ffdb798152d69f0b9550762b" ); const BUY_ABI = [ { inputs: [ { internalType: "address", name: "token", type: "address" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "funds", type: "uint256" }, { internalType: "uint256", name: "minAmount", type: "uint256" }, ], name: "buyTokenAMAP", outputs: [], stateMutability: "payable", type: "function", }, ]; const buyContract = new ethers.Contract(LAUNCHPAD_ADDRESS, BUY_ABI, wallet); ``` 2. Creating the Buy Function ```js export async function buyViaLaunchpad( tokenAddress, amountBNB = "0.001", minAmount = 0n ) { await initNonce(); try { const funds = parseEther(amountBNB); console.log(`🛒 Buying token ${tokenAddress} with ${amountBNB} BNB…`); const data = buyContract.interface.encodeFunctionData("buyTokenAMAP", [ tokenAddress, wallet.address, funds, minAmount, ]); const txRequest = { to: LAUNCHPAD_ADDRESS, data, value: funds, gasLimit: 300_000, }; const receipt = await sendTxWithNonce(txRequest); console.log("✅ Purchase TX mined in block", receipt.blockNumber); return receipt; } catch (err) { console.error("❌ Purchase failed:", err.reason || err.message || err); return null; } } ``` ## Sell Token Functionality via Launchpad 1. Defining Constants ```js const SELL_ABI = [ { constant: false, inputs: [ { name: "token", type: "address" }, { name: "amount", type: "uint256" }, ], name: "sellToken", outputs: [], payable: false, type: "function", }, ]; const ERC20_ABI = [ "function approve(address spender, uint256 amount) external returns (bool)", "function decimals() view returns (uint8)", "function balanceOf(address account) view returns (uint256)", ]; const sellContract = new ethers.Contract(LAUNCHPAD_ADDRESS, SELL_ABI, wallet); ``` 2. Creating the Sell Token Function ```js export async function sellTokenViaLaunchpad(tokenAddress) { await initNonce(); try { const tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, wallet); // 1) fetch decimals + balance const [decimals, rawBalance] = await Promise.all([ tokenContract.decimals(), tokenContract.balanceOf(wallet.address), ]); if (rawBalance === 0n) { console.log(`⚠️ Balance is zero for ${tokenAddress}, skipping sell.`); return null; } console.log(`🔓 Approving ${rawBalance.toString()} tokens for sale…`); const approveData = tokenContract.interface.encodeFunctionData("approve", [ LAUNCHPAD_ADDRESS, rawBalance, ]); await sendTxWithNonce({ to: tokenAddress, data: approveData, gasLimit: 100_000, }); console.log(`💰 Selling ${rawBalance.toString()} of ${tokenAddress}…`); const sellData = sellContract.interface.encodeFunctionData("sellToken", [ tokenAddress, rawBalance, ]); const txRequest = { to: LAUNCHPAD_ADDRESS, data: sellData, gasLimit: 300_000, }; const receipt = await sendTxWithNonce(txRequest); console.log("✅ Sell TX mined in block", receipt.blockNumber); return receipt; } catch (err) { console.error("❌ Sale failed:", err.reason || err.message || err); return null; } } ``` ## Filtering for Four Meme Token Creation in the `run` Function This is the main function for this script, where the kafka consumer instance is ran, newly created Four Meme tokens are checked and trades are executed. All the code snippets under this sub-section are written under the `run` function. ```js const run = async () => { .... } ``` 1. Defining Variables ```js let ParsedMessage = await loadProto(topic); // Load proto before starting Kafka await consumer.connect(); await consumer.subscribe({ topic, fromBeginning: false }); const seenTokens = new Set(); // Track processed token addresses ``` 2. Running the Consumer Instance In this section, we use the protobuf schema from the Bitquery library, which is available [here](https://github.com/bitquery/streaming_protobuf). For JS, the schema is available as a package [here](https://www.npmjs.com/package/bitquery-protobuf-schema). We're listening to `bsc.tokens.proto` topic, we're using the JS library to match the output to the schema. For the `bsc.tokens.proto` topic, Bitquery uses the [TokenBlockMessage](https://github.com/bitquery/streaming_protobuf/blob/930e4a8c2d69de2d6da11a4d31ee5f4e4b11c5fb/evm/token_block_message.proto#L41) schema which contains the `TokenTransfer` message format. This structure allows us to parse out key data such as token addresses, transaction senders, and smart contract information. We're using Four Meme DEX address `0x5c952063c7fc8610ffdb798152d69f0b9550762b` to track token creation. ```js await consumer.run({ autoCommit: false, eachMessage: async ({ message }) => { try { // Getting Transfers const buffer = message.value; const decoded = ParsedMessage.decode(buffer); const msgObj = ParsedMessage.toObject(decoded, { bytes: Buffer }); const transfers = msgObj.Transfers; // Iterating Transfers for (let i in transfers) { const transfer = transfers[i]; const to = `0x${convertBytes(transfer.TransactionHeader.To)}`; const sender = `0x${convertBytes(transfer.Sender)}`; const tokenAddr = `0x${convertBytes(transfer.Currency.SmartContract)}`; const name = transfer.Currency.Name; const symbol = transfer.Currency.Symbol; // Checking the conditions implying Four Meme Token Creation using the DEX Address if ( to == "0x5c952063c7fc8610ffdb798152d69f0b9550762b" && sender == "0x0000000000000000000000000000000000000000" ) { // Checking if the token is already seen and updating the list of seen tokens if the token is new if (!seenTokens.has(tokenAddr)) { seenTokens.add(tokenAddr); console.log(`🚀 New Token: ${tokenAddr}, ${name} (${symbol})`); // Buying the token const buyReceipt = await buyViaLaunchpad(tokenAddr, "0.001", 0n); if (buyReceipt) { // Schedule Sell in 60 seconds setTimeout(async () => { try { await sellTokenViaLaunchpad(tokenAddr); } catch (e) { console.error( `❌ Sell error for ${tokenAddr}:`, e.reason || e.message || e ); } }, 60 * 1000); } } } } } catch (err) { console.error("Error decoding Protobuf message:", err); } }, }); ``` ### Creating the Entrypoint for the script ```js run().catch(console.error); ``` ## Running the Script To run the bot script locally, enter the following command ```sh node index.js ``` You can also, run this script on cloud platforms by getting a VM(virtual machine instance). Once you have a VM with **Node**, **Git** and **NPM** installed, you can get the code on the same VM using these commands. ```sh git clone < repository link > cd < folder name > sudo npm install -g pm2 pm2 start index.js --name "evm-sniper" ``` The status and logs of the bot could be checked using these commands ``` pm2 status pm2 logs evm-sniper ``` ## Important Notes - Test carefully! On-chain transactions are irreversible. - Gas fees and front-running risks exist on BSC—proceed at your own risk. - Code is for educational and research purposes only. ## Video Tutorial --- ## Building with WebSockets URL: https://docs.bitquery.io/docs/subscriptions/examples/ Building with WebSockets using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Building with WebSockets: Code Samples in Python & JavaScript This section provides examples of how to implement subscription queries in your code. **Remember: You need to implement logic to handle silent disconnect( when no data or keep-alive is received for say X seconds) in your code. Sample [here](/docs/subscriptions/silent-disconnect-reconnect/)**. ## How do I subscribe to live DEX trades using Bitquery WebSocket? {#how-do-i-subscribe-to-live-dex-trades-using-bitquery-websocket} Use Bitquery’s **GraphQL over WebSocket**: connect to [`wss://streaming.bitquery.io/graphql`](/docs/subscriptions/websockets/) with the **`graphql-ws`** or **`graphql-transport-ws`** subprotocol, authenticate as described in [WebSocket authorization](/docs/authorization/websocket/), then send a **`subscription`** whose root field is your chain API (for example `EVM` or `Solana`) and a **`DEXTrades`** selection. Each new trade matching your `where` clause is pushed as a message. Test the subscription in the [Bitquery IDE](https://ide.bitquery.io) by changing the operation from `query` to `subscription`, then reuse the same document in your client. The GraphQL document is the same whether you run it from Python, JavaScript, or any other client; only the WebSocket wiring differs (see the sections below). ```graphql subscription LiveDexTrades { EVM(network: bsc) { DEXTrades { Block { Time } Trade { Dex { ProtocolName SmartContract } Buy { Buyer Amount Currency { Symbol SmartContract } } Sell { Seller Amount Currency { Symbol SmartContract } } } } } } ``` Narrow results with a `where` argument on `DEXTrades` (specific pair, DEX, USD size, and so on) using the same [filter syntax](/docs/graphql/filters/) as queries. For more BSC examples and IDE links, see [BSC DEX Trades](/docs/blockchain/BSC/bsc-dextrades/); for Solana, see [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades/). A saved BSC stream you can open in the IDE: [Subscribe to BSC DEX trades](https://ide.bitquery.io/subscribe-to-bsc-dex-trades). ## Implementation Example: Using WebSocket Using Python This example demonstrates how to use the `gql` library in Python to create a client that connects to a WebSocket endpoint, subscribes to a query, and prints the results. The script also uses the `asyncio` library to wait for results from the wss endpoint and all asynchronous operations. ```python from gql import Client, gql from gql.transport.websockets import WebsocketsTransport async def main(): transport = WebsocketsTransport( url="wss://streaming.bitquery.io/graphql?token=ory_at_...", headers={"Sec-WebSocket-Protocol": "graphql-ws"}) await transport.connect() print("Connected") # Define the subscription query query = gql(""" subscription MyQuery { EVM(network: eth) { count: Blocks { Block { TxCount } } } } """) async def subscribe_and_print(): try: async for result in transport.subscribe(query): print(result) except asyncio.CancelledError: print("Subscription cancelled.") # Run the subscription and stop after 100 seconds try: await asyncio.wait_for(subscribe_and_print(), timeout=100) except asyncio.TimeoutError: print("Stopping subscription after 100 seconds.") # Close the connection await transport.close() #this sends complete message to server before closing websocket print("Transport closed") # Run the asyncio event loop asyncio.run(main()) ``` The `transport.connect()` function is used to establish a connection to the WebSocket server and start the subscription. Similarly, `transport.close()` is used to close the connection and stop the subscription after 100 seconds. ## Implementation Example: Using WebSocket Using JavaScript {#implementation-exampleusing-websocket-using-javascript} Open any online code editor and use this JavaScript code to use the websocket. Starting January you need to use OAuth to use the V2 APIs. Read more [here](/docs/authorization/websocket/) ```javascript const { WebSocket } = require("ws"); const bitqueryConnection = new WebSocket( "wss://streaming.bitquery.io/graphql?token=ory_", ["graphql-ws"] ); bitqueryConnection.on("open", () => { console.log("Connected to Bitquery."); // Send initialization message (connection_init) const initMessage = JSON.stringify({ type: "connection_init" }); bitqueryConnection.send(initMessage); }); bitqueryConnection.on("message", (data) => { const response = JSON.parse(data); switch (response.type) { case "connection_ack": console.log("Connection acknowledged by server."); // Send subscription message const subscriptionMessage = JSON.stringify({ type: "start", id: "1", payload: { query: ` subscription { Tron(mempool: true) { Transfers { Transfer { Sender Receiver Amount AmountInUSD Currency { Symbol } } } } } `, }, }); bitqueryConnection.send(subscriptionMessage); console.log("Subscription message sent."); // Automatically close the connection after 10 seconds setTimeout(() => { console.log("Closing WebSocket connection after 10 seconds."); // Send complete message to properly terminate subscription before closing if (bitqueryConnection.readyState === WebSocket.OPEN) { const completeMessage = { type: "complete", id: "1", }; bitqueryConnection.send(JSON.stringify(completeMessage)); console.log("Complete message sent for subscription termination."); } bitqueryConnection.close(); }, 10000); break; case "data": console.log("Received data from Bitquery:", response.payload.data); break; case "ka": console.log("Keep-alive message received."); break; case "complete": console.log("Subscription completed."); break; case "error": console.error("Error message received:", response.payload.errors); break; default: console.warn("Unhandled message type:", response.type); } }); bitqueryConnection.on("close", () => { console.log("Disconnected from Bitquery."); }); bitqueryConnection.on("error", (error) => { console.error("WebSocket Error:", error); }); ``` ### How the WebSocket Connection is Managed: - **Start Connection**: - The connection is initiated using `bitqueryConnection.on("open")`. - After the WebSocket is open, the client sends a `connection_init` message. - Once the server responds with `connection_ack`, a GraphQL subscription is sent. - **Subscription**: - The client subscribes to real-time onchain data (in this example, `Tron` mempool transfers). - The server streams data to the client as events occur. - **Handling Incoming Messages**: - **`data`**: Actual blockchain event data, logged to the console. - **`ka` (Keep-alive)**: Indicates the connection is still active. - **`error`**: Any server-side errors are printed. - **Stop Connection**: - The WebSocket is closed using `bitqueryConnection.close()` after 10 seconds. - This cleanly ends the subscription and triggers the `close` event. - **Error Handling**: - If any WebSocket-level error occurs, it is logged in the `error` handler. - Bitquery graphQL subscription does not acknowledge `stop` messages, so closing the WebSocket is the correct way to end a subscription. --- ## Building with WebSockets: Code Sample in Rust URL: https://docs.bitquery.io/docs/subscriptions/example-rust/ Building with WebSockets: Code Sample in Rust using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Building with WebSockets: Code Sample in Rust In this section we will see how to use bitquery subscriptions in Rust. The final output will look something like this ![Rust WebSocket subscription example](/img/ApplicationExamples/rust.png) You can find the complete code [here](https://github.com/bitquery/graphql-streaming-example-rs/) ## 1. Set Up Your Rust Project First, ensure you have a Rust project set up. If not, you can create a new one: ```sh cargo new bitquery_realtime cd bitquery_realtime ``` ## 2. Add Dependencies Open your `Cargo.toml` file and add the necessary dependencies. For real-time data fetching and processing, you'll likely need dependencies like `tokio`, `reqwest`, `serde`, and `serde_json`. ```toml [dependencies] tokio = { version = "1", features = ["full"] } reqwest = { version = "0.11", features = ["json"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" futures = "0.3" graphql-client = "0.10.0" # Adjust version as necessary ``` ## 3. Implement the Logic This is the basic outline of what we will do - Establish a WebSocket connection to Bitquery's streaming endpoint. - Set up up a GraphQL subscription to receive real-time DEX trades data. - The `subscribe` function handles the connection setup and starts the streaming operation. - The `main` function initializes the subscription and processes the incoming data. This Rust code sets up a WebSocket client to subscribe to real-time data from Bitquery Solana APIs using the GraphQL over WebSocket protocol. ### **How Everything Connects** 1. **Tokio (Async Runtime)**: Handles asynchronous operations. 2. **WebSockets (async_tungstenite)**: Maintains a real-time connection with Bitquery’s API. 3. **GraphQL Queries (`queries.rs`)**: Defines how we request and handle blockchain data. 4. **Tokio Task Spawner (`tokio_spawner.rs`)**: Helps manage background tasks. 5. **Main Function (`main.rs`)**: Sets up and runs our application. ### **TokioSpawner Module** Let's create a `TokioSpawner` module responsible for handling task execution within the Tokio runtime. It allows tasks to be spawned asynchronously within the WebSocket client. #### **Key Features:** - **Encapsulates Tokio's Runtime Handle:** It holds a reference to the Tokio runtime, ensuring tasks are spawned properly. - **Implements `futures::task::Spawn`:** This trait allows it to be used as a task spawner for the GraphQL WebSocket client. #### **Implementation Details:** ```rust pub struct TokioSpawner(tokio::runtime::Handle); impl TokioSpawner { pub fn new(handle: tokio::runtime::Handle) -> Self { TokioSpawner(handle) } pub fn current() -> Self { TokioSpawner::new(tokio::runtime::Handle::current()) } } impl futures::task::Spawn for TokioSpawner { fn spawn_obj( &self, object: futures::task::FutureObj<'static, ()>, ) -> Result<(), futures::task::SpawnError> { self.0.spawn(object); Ok(()) } } ``` #### **How It Works:** 1. `TokioSpawner::current()` retrieves the current Tokio runtime handle. 2. It implements the `Spawn` trait from `futures::task`, allowing it to schedule tasks asynchronously. 3. This spawner is passed into the WebSocket client for handling GraphQL subscription events efficiently. ---------- ### **GraphQL Queries Module (`queries.rs`)** Create a `queries.rs` file that defines custom data types and the GraphQL subscription structure for fetching real-time DEX trades. #### **Key Features:** - **Defines Custom Scalar Types**: GraphQL often uses custom scalar types that don’t directly map to Rust’s built-in types. This file defines wrappers for common data types like `Decimal`, `BigInt`, `Timestamp`, and `DateTime`. - **Implements GraphQL Query with `graphql_client`**: The `DexTrades` struct is automatically generated by the `graphql_client` crate and represents the structure of the GraphQL query. #### **Custom Scalar Type Implementations** ```rust #[derive(Debug, Clone, Deserialize)] pub struct Decimal(pub String); impl Decimal { pub fn new(decimal: String) -> Self { Self(decimal) } } impl From for Decimal { fn from(item: String) -> Self { Self::new(item) } } ``` - The `Decimal` struct ensures that decimal numbers returned as strings from GraphQL are handled properly. - Similar wrappers exist for: - **`BigInt`** (large integers stored as strings) - **`Timestamp`** (Unix timestamps) - **`DateTime`** (ISO 8601 formatted date-time strings) #### **GraphQL Query Definition** ```rust #[derive(GraphQLQuery, Debug, Clone, Deserialize)] #[graphql( schema_path = "graphql/schema.graphql", query_path = "graphql/subscriptions/dextrades.graphql", response_derives = "Debug, Clone" )] pub struct DexTrades; ``` This defines the GraphQL subscription structure for DEX trades. ### `subscribe` Function ```rust pub async fn subscribe( oauth_token: &str, variables: T::Variables, ) -> Result<( AsyncWebsocketClient, SubscriptionStream>, )> where ::Variables: Send + Sync + Unpin, ::ResponseData: std::fmt::Debug, { let mut request = "wss://streaming.bitquery.io/graphql".into_client_request()?; request.headers_mut().insert( header::SEC_WEBSOCKET_PROTOCOL, HeaderValue::from_str("graphql-transport-ws")?, ); request .headers_mut() .insert("Authorization", HeaderValue::from_str(format!("Bearer {}", oauth_token).as_str())?); let (connection, _) = async_tungstenite::tokio::connect_async(request).await?; let (sink, stream) = connection.split::(); let mut client = GraphQLClientClientBuilder::new() .build(stream, sink, TokioSpawner::current()) .await?; let stream = client .streaming_operation(StreamingOperation::::new(variables)) .await?; Ok((client, stream)) } ``` This function sets up a WebSocket connection to the Bitquery streaming endpoint. 1. **Create WebSocket Request**: - Create a WebSocket request to the Bitquery streaming endpoint. - Add headers for the WebSocket protocol and authorization. 2. **Connect to WebSocket**: - Establish an asynchronous WebSocket connection using `async_tungstenite`. 3. **Split Connection**: - Split the connection into a sink (for sending messages) and a stream (for receiving messages). 4. **Build GraphQL Client**: - Create a `GraphQLClient` using `GraphQLClientClientBuilder`. 5. **Start Streaming Operation**: - Start a streaming GraphQL operation using the provided variables. 6. **Return Client and Stream**: - Return the client and the stream of data. ### Main Function In this function we will pass the OAuth token. The best practice would be to include it as an environment variable, but for the sake of this tutorial it has been hard coded. You can generate a token [here](/docs/authorization/how-to-generate/) #### Imports ```rust use async_tungstenite::tungstenite::{ client::IntoClientRequest, http::{header, HeaderValue}, Message, }; use eyre::Result; use futures::StreamExt; use graphql_client::GraphQLQuery; use graphql_ws_client::{ graphql::{GraphQLClient, StreamingOperation}, AsyncWebsocketClient, GraphQLClientClientBuilder, SubscriptionStream, }; pub mod queries; mod tokio_spawner; use tokio_spawner::TokioSpawner; ``` - `async_tungstenite`: Used for WebSocket communication. - `eyre::Result`: A result type for error handling. - `futures::StreamExt`: Provides extensions for working with streams. - `graphql_client::GraphQLQuery`: Defines the GraphQL query structure. - `graphql_ws_client`: Provides WebSocket client functionality for GraphQL. - `queries`: Contains the GraphQL queries. - `tokio_spawner`: Contains the task spawner implementation. #### Type Definitions ```rust pub type DexTradesQuery = queries::DexTrades; pub type DexTradesVariables = queries::dex_trades::Variables; ``` Defines type aliases for the GraphQL query and variables. ```rust #[tokio::main] async fn main() -> Result<()> { dotenv::dotenv().ok(); let token = "YOUR_HARDCODED_TOKEN"; let (_client, mut stream) = subscribe::( token, DexTradesVariables { program_id: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P".to_string(), }, ) .await?; while let Some(response) = stream.next().await { dbg!(&response); } Ok(()) } ``` This is the entry point of the application. 1. **Load Environment Variables**: - Load environment variables from a `.env` file if it exists. 2. **Subscribe to Data**: - Call the `subscribe` function with the hardcoded API key and query variables. 3. **Process Incoming Data**: - Iterate over the stream of incoming responses. - Print each response using `dbg!`. ### 4. Run the Project With everything set up, you can now build and run your project: ```sh cargo run ``` This should start your application and begin fetching real-time data from Bitquery, printing the results to the console. --- ## BullX-style Trading Terminal Data on Ethereum: Pair Feeds, Prices, Traders URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/evm-bullx-api/ BullX-style terminal data on Ethereum via Bitquery GraphQL: live pair trades, token price and stats, top traders, a wallet's trades, whale swaps and new pools. # BullX-style Trading Terminal Data on Ethereum: Pair Feeds, Prices, Traders A trading terminal like BullX is built from a few feeds: the trades of the pair on screen, the token's price and stats, who the biggest traders are, what one wallet has been doing, and the large swaps hitting the chain. Each is one Bitquery query or subscription on Ethereum, and the same filters work on BSC, Base, Arbitrum and the other EVM chains by changing the network. The worked token is Mog, `0xaaee1a9723aadb7afa2810263653a34ba2c21c7a`, in its Uniswap v2 pool with WETH, `0xc2eab7d33d3cb97692ecb231a5d0e4a649cb539d`. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. For pool-page analytics such as trending pools, candles and reserves, see the [GeckoTerminal-style page](/docs/blockchain/Ethereum/dextrades/evm-geckoterminal-api/); for token discovery, the [GMGN-style page](/docs/blockchain/Ethereum/dextrades/evm-gmgn-api/). ## Recommended: Trading API queries (real-time + last ~30 days) ### Live trades with USD price, market cap and supply Streams MEV-filtered trades across all 10 chains; the network filter scopes it to Ethereum. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Ethereum" } } } }) { Block { Time } Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol Network } QuoteToken { Symbol } Market { Protocol Network } } } } } ``` ### Most accurate token price with 1-minute OHLC (top market) Returns the token's price from its top-volume market via `Ranking: { Position: { eq: 1 } }`; swap the token address and network for your token. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Token-Price-Top-Market-Rank-1). ```graphql { Trading { Pairs( where: { Token: {Address: {is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a"}, Network: {is: "Ethereum"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } limit: {count: 1} orderBy: {descending: Block_Time} ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean } } Volume { Base Usd } Block { Time } } } } ``` ## Live trades of a pair Filter the pool under `Trade.Dex.SmartContract` and the token under `Trade.Currency`. Each message is one swap with the amount, the USD price, the side and the wallet that sent it. Saved stream [here](https://ide.bitquery.io/Get-pair-trades-data-just-like-dexcsreener). ```graphql subscription { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { SmartContract: { is: "0xc2eab7d33d3cb97692ecb231a5d0e4a649cb539d" } } Currency: { SmartContract: { is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a" } } } } ) { Block { Time } Trade { Amount PriceInUSD Currency { Symbol } Side { Amount AmountInUSD Type Currency { Symbol } } Dex { ProtocolName } } Transaction { Maker: From Hash } } } } ``` ## Price and stats of a token The header block of a token page in one query: the price at the start and end of the window, trades, buys, sells, makers and USD volume, over the last day with a one-hour sub-window. `Side.Type` names the counter-side of a trade, so the token was bought where the side was sold. Saved query [here](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-a-eth-pair). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { SmartContract: { is: "0xc2eab7d33d3cb97692ecb231a5d0e4a649cb539d" } } Currency: { SmartContract: { is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol } Side { Currency { Symbol } } start: PriceInUSD(minimum: Block_Number) end: PriceInUSD(maximum: Block_Number) } trades: count trades1h: count(if: { Block: { Time: { after_relative: { hours_ago: 1 } } } }) buys: count(if: { Trade: { Side: { Type: { is: sell } } } }) sells: count(if: { Trade: { Side: { Type: { is: buy } } } }) makers: uniq(of: Transaction_From) volumeUsd: sum(of: Trade_Side_AmountInUSD) volumeUsd1h: sum(of: Trade_Side_AmountInUSD, if: { Block: { Time: { after_relative: { hours_ago: 1 } } } }) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Top traders of a token Rank by `Transaction.From`, the wallet that sent the swap, so routers and aggregators do not appear as traders. Saved query [here](https://ide.bitquery.io/top-traders-of-a-token_7). ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 50 } where: { Trade: { Currency: { SmartContract: { is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## One wallet's trades The Trading cube keys trades by wallet across chains, with USD on every row. The example is an Ethereum wallet with large trades at the time of writing; take any address from the top traders above. As a subscription without the `Block` filter the same `where` follows the wallet live. ```graphql { Trading { Trades( where: { Trader: { Address: { is: "0xae2fc483527b8ef99eb5d9b44875f005ba1fae13" } } Pair: { Market: { Network: { is: "Ethereum" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Block { Time } Side PriceInUsd AmountsInUsd { Base Quote } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol Address } } } } } ``` ## Whale swaps on Ethereum Swaps over a hundred thousand dollars in the last hour, newest first. Drop the `Block` filter and subscribe for alerts. ```graphql { Trading { Trades( where: { AmountsInUsd: { Base: { gt: 100000 } } Pair: { Market: { Network: { is: "Ethereum" } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Block { Time } Side Trader { Address } AmountsInUsd { Base } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` ## New Uniswap v3 pools The factory's `PoolCreated` event names both tokens, the fee tier and the new pool address. New pools on Ethereum arrive minutes to hours apart, so query the last day rather than waiting on a stream. Saved query [here](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3_9). ```graphql { EVM(network: eth) { Events( where: { Log: { SmartContract: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } Signature: { Name: { is: "PoolCreated" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 50 } orderBy: { descending: Block_Time } ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` ## Related pages - [GeckoTerminal-style EVM API](/docs/blockchain/Ethereum/dextrades/evm-geckoterminal-api/) - [GMGN-style EVM API](/docs/blockchain/Ethereum/dextrades/evm-gmgn-api/) - [Traders API](/docs/trading/crypto-trades-api/traders-api) - [Ethereum DEX trades API](/docs/blockchain/Ethereum/dextrades/dex-api) --- ## Calculating Profit or Loss Over Time URL: https://docs.bitquery.io/docs/usecases/p-l-product/pnl/ Build Calculating Profit or Loss Over Time: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Calculating Profit or Loss Over Time This is the first step, where we calculate the Weighted Average of Buy Price(WABP) by getting all the `buy` trades of the token. For this tutorial, we are getting the PnL of the `0x2107662b0eb1f95a42f47f667c6d4622fe1c9231` address for the following token `0x6982508145454ce325ddbe47a25d4ec3d2311933`. ``` WABP = sum(buyAmount*buyPriceInUSD)/sum(buyAmount) ``` We get the `sell` trades for the entire period and multiply the amount of tokens sold with the `priceInUSD` minus the WABP calculated. ``` pnl = sum(sellPriceInUSD-WABP) ``` 1. Import the necessary libraries: ```javascript const axios = require('axios'); require('dotenv').config() ``` 2. Create the config object with URL and headers, including your API key: ```javascript let data; let config = { method: 'post', maxBodyLength: Infinity, url: 'https://streaming.bitquery.io/graphql', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.AUT_TOKEN}` }, data : data }; ``` 3. Make the `getWeightedAverage()` function to get the Weighted Average for the Buy Price. ```javascript const getWeightedAverage = async (token, wallet) => { } ``` 4. Inside the declared function define the data property of object and get the response: ```javascript let data = JSON.stringify({ "query": "query MyQuery($token: String = \"\", $wallet: String = \"\") {\n EVM(dataset: combined) {\n DEXTrades(\n where: {Trade: {Buy: {Currency: {SmartContract: {is: $token}}, PriceInUSD: {ne: 0}}}, Transaction: {From: {is: $wallet}}}\n ) {\n Trade {\n Buy {\n Amount\n PriceInUSD\n }\n }\n }\n }\n}\n", "variables": `{\n \"token\": \"${token}\",\n \"wallet\": \"${wallet}\"\n}` }); config.data = data; const response = await axios.request(config); const buyTrades = response.data.data.EVM.DEXTrades; ``` 6. Declare variables and Traverse the `buyTrades` array: ```javascript let count = 0; let sum = 0; for( let i in buyTrades){ } ``` 7. Extract the `amount` and `PriceInUSD` from the buyTrades: ```javascript let amount = parseFloat(buyTrades[i].Trade.Buy.Amount); let price = buyTrades[i].Trade.Buy.PriceInUSD; ``` 8. Update the `sum` and `count` variables and return the WABP: ```javascript sum += amount*price; count += amount; return sum/count; ``` 9. Make the `getPnL()` function to calculate the PnL for the address and the token. ```javascript const getPnL = async (token, wallet) => { } ``` 10. Inside the declared function define the data property of object and get the response: ```javascript let data = JSON.stringify({ "query": "query MyQuery($token: String = \"\", $wallet: String = \"\") {\n EVM(dataset: combined) {\n DEXTrades(\n where: {Trade: {Sell: {Currency: {SmartContract: {is: $token}}, PriceInUSD: {ne: 0}}}, Transaction: {From: {is: $wallet}}}\n orderBy: {ascending: Block_Time}\n ) {\n Trade {\n Sell {\n Amount\n PriceInUSD\n }\n }\n }\n }\n}\n", "variables": `{\n \"token\": \"${token}\",\n \"wallet\": \"${wallet}\"\n}` }); config.data = data; const response = await axios.request(config); const sellTrades = response.data.data.EVM.DEXTrades; ``` 11. Get the weighted average for the adress and token: ```javascript const average = await getWeightedAverage(token, wallet); ``` 12. Declare variables and Traverse the `sellTrades` array: ```javascript let pnl = 0; for(let i in sellTrades){ } ``` 13. Update the `pnl` variable: ```javascript let amount = parseFloat(sellTrades[i].Trade.Sell.Amount); let sellPrice = sellTrades[i].Trade.Sell.PriceInUSD; let margin = amount*(sellPrice-average); pnl += margin; ``` 14. Print the `pnl`: ```javascript console.log(pnl); ``` 15. Run the function inside the `JS` script: ```javascript getPnL("0x6982508145454ce325ddbe47a25d4ec3d2311933", "0x2107662b0eb1f95a42f47f667c6d4622fe1c9231"); // (token address, wallet address) ``` You can change the token address and wallet address as per your requirements, or even use these functions for creating a pipeline in a bigger application. The realised Profit for this account by trading this token as of `2024-10-21` is around `4 USD`. --- ## Calculations and Scripting URL: https://docs.bitquery.io/docs/usecases/real-time-balance-tracker/scripts/ Build Calculations and Scripting: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Calculations and Scripting We will read the current balance once with the `Balances` cube, then keep it up to date from a live `TransactionBalances` stream. Each streamed row carries the balance after the transaction (`PostBalance`), so no summing is needed. To do this through code we will build two files (namely balance.js and index.js). ``` Current Balance = Balances (on load), then PostBalance from each streamed TransactionBalances row ``` ## Initialise and Installing Dependencies To initiate the project run the following command. ```bash npm init -y ``` Before going further make sure that all the dependencies are installed. The dependencies are listed below: - axios - dotenv - express - ws Use the following command to install these dependencies. ```bash npm install axios dotenv express ws ``` ## Create Balance Script This script will fetch the current balance from the `Balances` cube, giving the current balance of a particular currency (Ethereum in this example) for the wallet. Follow the steps given below to build the script 1. Import the dependencies ``` js const axios = require('axios'); require('dotenv').config() ``` **NOTE:** Make sure to create a `.env` file and create a AUTH_TOKEN variable to store your Bitquery Access Token. To know more about the access token click [here](https://account.bitquery.io/user/api_v2/access_tokens). 2. Create a standard config for the getBalance function. This includes the API url we are trying to hit, access token to authenticate the request, and the request body as data. ``` js let data = JSON.stringify({ "query": "{\n EVM(dataset: combined, network: eth) {\n Balances(\n where: {Balance: {Address: {is: \"\"}}, Currency: {SmartContract: {is: \"0x\"}}}\n ) {\n Balance {\n Amount\n }\n }\n }\n}\n", "variables": "{}" }); let config = { method: 'post', maxBodyLength: Infinity, url: 'https://streaming.bitquery.io/graphql', headers: { 'Content-Type': 'application/json', 'X-API-KEY': 'YOUR_API_KEY', 'Authorization': `Bearer ${process.env.AUTH_TOKEN}` }, data : data }; ``` Please note that the data part is a standard case, but will be modified upon the user input. 3. Create the asynchronous getBalance function. ``` js const getBalance = async (config) => { try { const response = await axios.request(config); // console.log(response.data.data.EVM.Balances[0].Balance.Amount) return response.data.data.EVM.Balances[0]?.Balance.Amount; } catch (error) { return error; } } ``` 4. Export the requirements from the file. ```js module.exports = {getBalance, config}; ``` ## Create Index Script In this file we will write code to: - Get Balance using the getBalance function from balance.js. - Create an express server so that we can render a simple UI. - Run a websoket connection to get real-time balance updates. 1. Import the requirements. ``` js const express = require('express'); const path = require('path'); const { getBalance, config } = require('./balance.js'); require('dotenv').config(); ``` 2. Initiate the express server and declare the address variable. ```js const app = express(); app.use(express.static(path.join(__dirname))); app.use(express.json()); let currentAddress = ''; // Default address if none provided ``` 3. Creating the endpoint to handle address input from frontend. ``` js app.post('/track-balance', (req, res) => { const { address } = req.body; if (!address) { return res.status(400).json({ success: false, message: 'Address required' }); } currentAddress = address; res.json({ success: true }); }); ``` 4. Creating the endpoint to get the balance from getBalance function. ``` js app.get('/get-balance', async (req, res) => { try { // Update the address in the config dynamically config.data = JSON.stringify({ "query": `{\n EVM(dataset: combined, network: eth) {\n Balances(\n where: {Balance: {Address: {is: \"${currentAddress}\"}}, Currency: {SmartContract: {is: \"0x\"}}}\n ) {\n Balance {\n Amount\n }\n }\n }\n}\n`, "variables": "{}" }); const balance = await getBalance(config); res.json({ balance: balance || '0' }); } catch (error) { console.error('Error fetching balance:', error); res.status(500).json({ error: 'Error fetching balance' }); } }); ``` 5. Start WebSocket connection for real-time updates. `Balances` is query-only, so the live feed uses `TransactionBalances`, which streams the balance before and after each transaction. ``` js const { WebSocket } = require("ws"); const bitqueryConnection = new WebSocket( "wss://streaming.bitquery.io/graphql?token=" + process.env.AUTH_TOKEN, ["graphql-ws"], ); bitqueryConnection.on("open", () => { console.log("Connected to Bitquery."); const initMessage = JSON.stringify({ type: "connection_init" }); bitqueryConnection.send(initMessage); }); bitqueryConnection.on("message", async (data) => { const response = JSON.parse(data); if (response.type === "connection_ack") { const subscriptionMessage = JSON.stringify({ type: "start", id: "1", payload: { query: ` subscription { EVM{ TransactionBalances( where: { TokenBalance: { Address: { is: "${currentAddress}" }, Currency: {SmartContract: {is: "0x"}} } } ) { Block { Time } TokenBalance { PreBalance PostBalance } } } }`, }, }); bitqueryConnection.send(subscriptionMessage); console.log("Subscription message sent."); } }); bitqueryConnection.on("error", (error) => { console.error("WebSocket Error:", error); }); ``` 6. Start the Express server. ``` js const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); ``` Now we need to build a simple UI using HTML, CSS and Javascript to make this project inituitive. --- ## Cardano API Documentation URL: https://docs.bitquery.io/docs/blockchain/Cardano/ Cardano API overview: query blocks, transactions, addresses and staking, native tokens, stablecoins and fund tracing on Cardano, with a quick start guide. # Cardano API Documentation ## Overview Bitquery's Cardano APIs let you query the chain through GraphQL — blocks, transactions, addresses, native tokens, UTXO-level inputs and outputs, staking, and multi-hop fund flow. Replace the example addresses and token IDs in any query with your own values to point them at real wallets and assets. If you get stuck or need a data point that isn't covered here, reach out on [Telegram](https://t.me/Bloxy_info). :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ### What you can do with the Cardano API - Look up blocks by height, hash, or time window — including epoch, slot, slot leader, and VRF key. - Pull transactions with input/output totals, fees in ADA and USD, mint count, and withdrawals. - Get address balances across ADA and every native token a wallet holds, plus staking and rewards. - Walk UTXO-level inputs and outputs to reconstruct exact balances or build transaction feeds. - Track mints and burns of any native token (NFTs, fungibles, stablecoins like DJED). - Trace ADA flows inbound and outbound across multiple hops with Coinpath. ### How the Cardano API differs from running your own node | `cardano-node` / RPC | Bitquery Cardano API | | --- | --- | | Raw chain state — you build the indexer | Pre-indexed and parsed: blocks, txs, UTXOs, native tokens, staking | | No historical analytics out of the box | History, joins, aggregations, USD conversion | | You stream and decode CBOR yourself | GraphQL response — pick the fields you need | | Best for submitting transactions and full validation | Best for analytics, dashboards, wallet UIs, and compliance work | ## Quick start This query returns the 5 most recent Cardano blocks with hash, height, transaction count, and timestamp. ```graphql { cardano(network: cardano) { blocks(options: {desc: "height", limit: 5}) { height blockHash transactionCount timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } } } ``` ## API reference ### Core data - [Cardano Blocks API](/docs/blockchain/Cardano/blocks) — block lookups by height or time, epoch/slot context, slot-leader metadata. - [Cardano Transactions API](/docs/blockchain/Cardano/transactions) — transaction details, fees in ADA and USD, mint counts, daily counts. - [Cardano Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs) — UTXO-level data for balance reconstruction and transfer feeds. ### Addresses and staking - [Cardano Address API](/docs/blockchain/Cardano/address) — per-asset balances, staking snapshot, and the `addressStats` aggregate cube. ### Native tokens - [Cardano Mints API](/docs/blockchain/Cardano/mints) — native-token mint and burn events, including NFT drops and fungible issuance. ### Stablecoins - [Djed Stablecoin API](/docs/blockchain/Cardano/djed) — DJED mints, burns, transfers, and wallet-level balance examples. ### Fund tracing - [Cardano Coinpath API](/docs/blockchain/Cardano/coinpath) — multi-hop inbound and outbound ADA flow tracing for compliance and treasury work. ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Cardano Address API URL: https://docs.bitquery.io/docs/blockchain/Cardano/address/ Cardano address data: get wallet balances and staking info, plus address activity stats from addressStats, with GraphQL queries you can run in the IDE. # Cardano Address API The Address API gives you everything tied to a Cardano wallet: ADA balance, balances for every native token the wallet holds, and the staking snapshot (controlled stake, rewards available, rewards withdrawn). For quick activity profiling you can also use the `addressStats` cube, which returns pre-aggregated inflow, outflow, counterparty, and first/last-active metrics. :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get Cardano wallet balances and staking info This query returns ADA plus every native token a Cardano address holds, with the wallet's full staking context — total controlled stake, the staked amount with and without rewards, rewards currently available, and how much has already been withdrawn. Useful for portfolio dashboards, wallet UIs, and staking analytics. Swap the example address with the wallet you want to inspect. Stake addresses (`stake1...`) work in the same filter. ```graphql { cardano(network: cardano) { address( address: {is: "addr1v9m34968vfwya2dydafkaq48ag9pzerznwjf0ewu4jj5vfsvgmyhk"} ) { address { address annotation } balance { value currency { name symbol decimals address tokenId tokenType } } staking { controlledTotalStake stakedAmount stakedAmountWithRewards rewardsAmount rewardsAvailable withdrawnAmount address { address annotation } } } } } ``` If you only want the ADA balance, filter the response client-side where `currency.symbol == "ADA"`. Drop the `staking` block when stake context isn't needed. ## Get Cardano address activity stats (addressStats) `addressStats` is a pre-aggregated view of a wallet's lifetime activity — total inflows and outflows, inbound and outbound transaction counts, unique senders and receivers, unique active days, current balance, and the first / last active timestamps. It's the fastest way to profile an address for compliance checks, exchange screening, or analytics dashboards. :::caution `addressStats` is pre-aggregated and can lag the chain slightly. For exact, up-to-the-block balance math, sum `outputs` and subtract `inputs` from the [Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs). ::: ```graphql { cardano(network: cardano) { addressStats( address: {is: "addr1v9m34968vfwya2dydafkaq48ag9pzerznwjf0ewu4jj5vfsvgmyhk"} ) { address { address annotation balance inflows outflows inboundTransactions outboundTransactions uniqueSenders uniqueReceivers uniqueDaysWithTransfers firstActive { time } lastActive { time } } } } } ``` Pair this with the `address(...)` query above when you want fast aggregate metrics and per-asset balances in one round trip, or run it against a list of exchange / DAO / protocol addresses to compare them side-by-side. ## Related resources - [Cardano Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs) — UTXO-level balance reconstruction - [Cardano Transactions API](/docs/blockchain/Cardano/transactions) — transaction-level data with fees - [Cardano Coinpath API](/docs/blockchain/Cardano/coinpath) — multi-hop ADA flow tracing --- ## Cardano Blocks API - Query Blocks by Height, Slot & Epoch URL: https://docs.bitquery.io/docs/blockchain/Cardano/blocks/ Cardano blocks by height, slot and epoch: look up a single block by height or list recent Cardano blocks in a time window with GraphQL query examples. # Cardano Blocks API The Blocks API exposes everything you'd expect from a Cardano block: height, hash, size, protocol version, epoch and slot context, slot-leader metadata, VRF key, transaction count, and timestamp. Use it to power explorer front-ends, monitor chain progression, or pull historical block context for downstream analytics. :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Look up a Cardano block by height Fetch a single block by its height. The response carries the block hash, size and protocol version, epoch and slot context, operational certificate, slot-leader description and hash, VRF key, transaction count, and the production timestamp. ```graphql query { cardano(network: cardano) { blocks(height: {is: 9612373}) { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } blockHash blockSize blockVersion transactionCount epoch opCert slot slotInEpoch slotLeaderDescription slotLeaderHash vrfKey height } } } ``` To look up by hash instead, swap `height` for `blockHash: {is: "..."}`. To pull several blocks in one request, pass an array with `height: {in: [...]}`. ## List recent Cardano blocks in a time window Get the 10 most recent blocks produced between two timestamps. Handy for explorer recent-block widgets, throughput dashboards, and watching slot leaders across an epoch. ```graphql { cardano(network: cardano) { blocks( options: {desc: "height", limit: 10, offset: 0} time: {since: "2023-11-30T06:10:00Z", till: "2023-11-30T06:17:00Z"} ) { height blockHash blockSize transactionCount epoch slot slotInEpoch timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } } } ``` Sort ascending with `asc: "height"` to walk the chain forward, and widen the `time` window for longer scans. ## Related resources - [Cardano Transactions API](/docs/blockchain/Cardano/transactions) — per-block transaction details and fees - [Cardano Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs) — UTXO data tied to each transaction --- ## Cardano Coinpath API - Trace ADA Flows Across Multiple Hops URL: https://docs.bitquery.io/docs/blockchain/Cardano/coinpath/ Cardano Coinpath: trace inbound and outbound ADA flows for an address across multiple hops, including a deeper outbound trace, with GraphQL examples. # Cardano Coinpath API Coinpath walks ADA flows between Cardano addresses across multiple hops — forward to see where funds went, backward to see where they came from. Because Cardano uses an eUTXO model, the API stitches chains of UTXOs together and returns senders, receivers, hop depth, amounts, and transaction counts at each level. Common use cases: AML / compliance screening, DAO treasury audits, exchange deposit tracing, and source-of-funds verification. :::tip Trace Cardano funds with AI — no queries needed Connect the [Bitquery MCP server](https://mcp.bitquery.io/) to Claude, Cursor, or ChatGPT and ask in plain English: _"Trace where ADA from addr1... came from and where it went, 2 hops each way."_ The agent walks the fund flow for you. See [AI Investigations](https://bitquery.io/solutions/ai-investigations) and the [Tracing MCP guide](/docs/mcp/Tracing/overview). ::: :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Trace inbound and outbound ADA flows for an address This query runs both directions in one request. The `inbound` block walks backward from the initial address to find fund sources; the `outbound` block walks forward to find destinations. Each side is capped at 2 hops with up to 2 paths per hop — a good starting point before widening for deeper investigations. ```graphql { cardano(network: cardano) { inbound: coinpath( currency: {is: "ADA"} initialAddress: {is: "addr1q8hq60cyqg68aqfzs9geq084yj0tvvpm7rnckn6gsf3ahyrwak0antyvs6lyd7ymqg2zp6q8999vsdadmpm70x93f8msd7uwux"} depth: {lteq: 2} options: {direction: inbound, asc: "depth", desc: "amount", limitBy: {each: "depth", limit: 2}} date: {since: "2023-11-30", till: "2023-12-18"} ) { sender { address annotation } receiver { address annotation } amount depth count } outbound: coinpath( currency: {is: "ADA"} initialAddress: {is: "addr1q8hq60cyqg68aqfzs9geq084yj0tvvpm7rnckn6gsf3ahyrwak0antyvs6lyd7ymqg2zp6q8999vsdadmpm70x93f8msd7uwux"} depth: {lteq: 2} options: {asc: "depth", desc: "amount", limitBy: {each: "depth", limit: 2}} date: {since: "2023-11-30", till: "2023-12-18"} ) { sender { address annotation } receiver { address annotation } amount depth count } } } ``` Raise `depth: {lteq: N}` (typically 3–5) for broader tracing, increase `limitBy.limit` for more paths per hop, and widen the `date` window. Keep only the block you need if a single direction is enough. ## Deeper outbound ADA trace Walk forward from an address up to 3 hops deep with 5 paths per hop — a compact view that covers more ground than the 2-hop example above. Returns `amount`, `depth`, and `count` per hop, which is enough for most DAO treasury audits and fraud investigations. ```graphql { cardano(network: cardano) { coinpath( currency: {is: "ADA"} initialAddress: {is: "addr1q8hq60cyqg68aqfzs9geq084yj0tvvpm7rnckn6gsf3ahyrwak0antyvs6lyd7ymqg2zp6q8999vsdadmpm70x93f8msd7uwux"} depth: {lteq: 3} options: {asc: "depth", desc: "amount", limitBy: {each: "depth", limit: 5}} date: {since: "2023-01-01", till: "2023-12-31"} ) { sender { address annotation } receiver { address annotation } amount depth count } } } ``` For forensic work, depths of 5–7 are common. Add `direction: inbound` to `options` to flip the trace. If you're running the same query repeatedly in parallel and want to bypass intermediate-stage caching, set `options: {seed: 110, ...}` with any random integer. ## Related resources - [Cardano Address API](/docs/blockchain/Cardano/address) — wallet balances, staking, and `addressStats` - [Cardano Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs) — UTXO-level inflows and outflows --- ## Cardano Djed Stablecoin API URL: https://docs.bitquery.io/docs/blockchain/Cardano/djed/ Djed stablecoin on Cardano: recent DJED mints and burns, wallet DJED and ADA balances, network-wide movements, and DJED sent or received by an address. # Djed Stablecoin API [Djed](https://djed.xyz) is an overcollateralized, USD-pegged stablecoin on Cardano, issued by COTI and designed in collaboration with Input Output Global. It trades under the ticker **DJED** (asset name `DjedMicroUSD`) and is backed by ADA reserves. Every issuance is an on-chain **mint** of the DJED native token, and every redemption is a **burn** — which means Djed's full lifecycle maps cleanly onto Bitquery's existing Cardano primitives: - Mint and burn activity → [Cardano Mints API](/docs/blockchain/Cardano/mints) - Holder balances → [Cardano Address API](/docs/blockchain/Cardano/address) - Movements between wallets → [Cardano Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs) You can verify the on-chain asset on Cardanoscan: [DjedMicroUSD token page](https://cardanoscan.io/token/8db269c3ec630e06ae29f74bc39edd1f87c819f1056206e879a1cd61446a65644d6963726f555344). :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## How to filter for DJED in Bitquery Bitquery's `currency: {is: "..."}` filter on Cardano matches native tokens by their **`tokenId`** — the [CIP-14 asset fingerprint](https://cips.cardano.org/cip/CIP-0014). For DJED, that value is: ```graphql currency: {is: "asset15f3ymkjafxxeunv5gtdl54g5qs8ty9k84tq94x"} ``` The asset name / symbol (`DjedMicroUSD`) and the `currency.address` field are **not** usable as filter values — Bitquery returns `currency.address` as `"-"` for Cardano native tokens. Always filter by the `tokenId` fingerprint above. ## Recent DJED mint and burn events Pulls the 25 most recent DJED mint events, filtered server-side. A positive `value` is a mint (DJED issued against ADA collateral), a negative `value` is a burn (redemption). Useful for tracking Djed supply changes, correlating large mints with ADA price moves, or driving an issuance dashboard. ```graphql { cardano(network: cardano) { mints( currency: {is: "asset15f3ymkjafxxeunv5gtdl54g5qs8ty9k84tq94x"} options: {limit: 25, desc: "block.height"} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } value transaction { hash index } currency { name symbol tokenId tokenType decimals } } } } ``` Sort with `desc: "value"` to surface the largest single mints and burns. Tighten the `date` filter or raise `limit` for deeper history. ## Wallet's DJED and ADA balances Returns every asset a Cardano address holds, plus stake and rewards context. The `balance` block lists one entry per currency, so ADA and every native token in the wallet — including DJED — come back in the same response. On the client, match `currency.tokenId == "asset15f3ymkjafxxeunv5gtdl54g5qs8ty9k84tq94x"` to pull out just the DJED position. Good for portfolio tracking of Djed holders, wallet-level risk analytics, or balance widgets in Djed-aware wallet UIs. ```graphql { cardano(network: cardano) { address( address: {is: "addr1q8de89fu0j09gze96nf8mfrcz056tw8nz35lqkr46zn52j9cvtjm8enawhyjjkcf6eves2cwz4c8y9tvhjuzpvmu4rwstxfht5"} ) { address { address annotation } balance { value currency { name symbol decimals tokenId tokenType } } staking { controlledTotalStake stakedAmount stakedAmountWithRewards rewardsAmount rewardsAvailable withdrawnAmount address { address annotation } } } } } ``` Drop the `staking` block when you don't need stake context, or pair this with `addressStats` (see the [Cardano Address API](/docs/blockchain/Cardano/address)) to combine per-asset balances with aggregate activity metrics in a single request. ## Recent DJED movements network-wide Lists the 10 most recent DJED movements across the chain. In the eUTXO model, `inputs` are UTXOs being spent (DJED "sent") and `outputs` are UTXOs being created (DJED "received"). Each row carries block height and timestamp, transaction hash, counterparty address, UTXO index, raw DJED `value`, and USD-equivalent `value_usd`. Good for live activity feeds, recent-transfers widgets, or auditing large DJED transactions. ```graphql { cardano(network: cardano) { inputs( currency: {is: "asset15f3ymkjafxxeunv5gtdl54g5qs8ty9k84tq94x"} options: {desc: "block.height", limit: 10} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } transaction { hash } inputAddress { address annotation } inputIndex value value_usd: value(in: USD) currency { name symbol tokenId } } outputs( currency: {is: "asset15f3ymkjafxxeunv5gtdl54g5qs8ty9k84tq94x"} options: {desc: "block.height", limit: 10} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } transaction { hash } outputAddress { address annotation } outputIndex outputDirection value value_usd: value(in: USD) currency { name symbol tokenId } } } } ``` Replace the `options` block with aggregates (`count`, `value(calculate: sum)`, `value(in: USD, calculate: sum)`) when you want totals instead of a row-level list. ## DJED received by a specific address Lists the 20 most recent DJED-bearing UTXOs received by an address, with block context, transaction hash, output index, DJED `value`, and USD equivalent. "Received" in eUTXO terms means the address appears as the `outputAddress` on a UTXO that contains DJED. Useful for merchant payment ingestion, on-chain invoicing, and exchange deposit monitoring. ```graphql { cardano(network: cardano) { outputs( currency: {is: "asset15f3ymkjafxxeunv5gtdl54g5qs8ty9k84tq94x"} outputAddress: {is: "addr1q8de89fu0j09gze96nf8mfrcz056tw8nz35lqkr46zn52j9cvtjm8enawhyjjkcf6eves2cwz4c8y9tvhjuzpvmu4rwstxfht5"} options: {desc: "block.height", limit: 20} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } transaction { hash } outputIndex outputDirection value value_usd: value(in: USD) currency { name symbol tokenId } } } } ``` Pass `outputAddress: {in: [...]}` with a list of addresses to aggregate receipts across several wallets. Replace `options` with aggregates to get totals received instead of per-UTXO rows. ## DJED sent by a specific address Same idea as above, in reverse. Lists the 20 most recent DJED-bearing UTXOs spent by an address — i.e. UTXOs where the address appears as `inputAddress` and the UTXO is being consumed. Useful for outflow tracking, spend-side accounting, and tax reporting. ```graphql { cardano(network: cardano) { inputs( currency: {is: "asset15f3ymkjafxxeunv5gtdl54g5qs8ty9k84tq94x"} inputAddress: {is: "addr1q8de89fu0j09gze96nf8mfrcz056tw8nz35lqkr46zn52j9cvtjm8enawhyjjkcf6eves2cwz4c8y9tvhjuzpvmu4rwstxfht5"} options: {desc: "block.height", limit: 20} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } transaction { hash } inputIndex value value_usd: value(in: USD) currency { name symbol tokenId } } } } ``` Combine this with the "received" query above to reconstruct a wallet's complete DJED ledger — net DJED held equals the sum of received `value` minus the sum of sent `value`. ## Related resources - [Cardano Mints API](/docs/blockchain/Cardano/mints) — generic mint and burn query patterns - [Cardano Address API](/docs/blockchain/Cardano/address) — wallet balances and the `addressStats` cube - [Cardano Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs) — full UTXO query reference - [Cardano Coinpath API](/docs/blockchain/Cardano/coinpath) — multi-hop fund tracing - [Djed official site](https://djed.xyz) - [Djed launch announcement on COTI Medium](https://medium.com/cotinetwork/a-new-era-for-stablecoins-begins-djed-is-live-on-mainnet-55971971f2a8) --- ## Cardano Inputs and Outputs API URL: https://docs.bitquery.io/docs/blockchain/Cardano/inputs-outputs/ Cardano UTXO inputs and outputs: compute an address balance from UTXOs, list outputs received by an address, and read the parsed datum of a transaction UTXO. # Cardano Inputs and Outputs API Cardano runs on an **eUTXO** model — there are no account balances stored on-chain. To get an address's balance or activity you walk its inputs (UTXOs being spent) and outputs (UTXOs being received). These APIs return that UTXO-level data with transaction hash, output index, ADA and USD values, and block timestamps. :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Compute a Cardano address balance from UTXOs In the eUTXO model, an address balance is simply `sum(outputs received) - sum(inputs spent)`. This query pulls both sides in one request, with total counts, ADA values, USD values, and the first / last active dates. ```graphql { cardano(network: cardano) { inputs( currency: {is: "ADA"} inputAddress: {is: "addr1v9m34968vfwya2dydafkaq48ag9pzerznwjf0ewu4jj5vfsvgmyhk"} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } outputs( currency: {is: "ADA"} outputAddress: {is: "addr1v9m34968vfwya2dydafkaq48ag9pzerznwjf0ewu4jj5vfsvgmyhk"} ) { count value value_usd: value(in: USD) min_date: minimum(of: date) max_date: maximum(of: date) } } } ``` Add `date: {since: ..., till: ...}` to scope a window, pass `inputAddress: {in: [...]}` / `outputAddress: {in: [...]}` to aggregate across multiple wallets in one call, or drop the `currency: {is: "ADA"}` filter to include native tokens alongside ADA. For the aggregate shortcut (with pre-computed inflows, outflows, counterparty counts, etc.) see the [`addressStats` query](/docs/blockchain/Cardano/address#get-cardano-address-activity-stats-addressstats). ## List UTXO outputs received by a Cardano address Return individual UTXOs received by an address inside a date window. Each row carries block height and timestamp, transaction hash, output index, output direction, and ADA / USD value. Use it for transaction reports, wallet activity feeds, or merchant payment ingestion. ```graphql { cardano(network: cardano) { outputs( currency: {is: "ADA"} date: {since: "2022-10-19", till: "2022-10-26T23:59:59"} outputAddress: {is: "addr1qxz3ve4caaywwg6q82ax9l5xknyc7juvwwsw20cpugyz5gv9zent3m6guu35qw46vtlgddxf3a9ccuaqu5lsrcsg9gss69fhxw"} options: {desc: ["block.height", "outputIndex"], limit: 10, offset: 0} ) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } transaction { hash } outputIndex outputDirection value value_usd: value(in: USD) currency { symbol } } } } ``` Swap `outputs` for `inputs` (and `outputAddress` for `inputAddress`) to see UTXOs the wallet has spent. Remove the `currency` filter entirely to include every asset type — native tokens included. ## Get the parsed datum of a Cardano transaction UTXO Cardano UTXOs can carry inline `datum` — script-readable data attached to an output, used by Plutus smart contracts. This query returns all outputs for a given transaction hash and exposes the parsed datum inside `currency.properties` (in YAML-like format), so you don't have to decode CBOR yourself. ```graphql query ($network: CardanoNetwork!, $hash: String!, $limit: Int!, $offset: Int!) { cardano(network: $network) { outputs( txHash: {is: $hash} options: {asc: "outputIndex", limit: $limit, offset: $offset} ) { outputIndex address: outputAddress { address annotation } value value_usd: value(in: USD) currency { symbol tokenType tokenId properties name decimals address } outputDirection date { date } transaction { hash } valueDecimal } } } ``` Variables: ```json { "limit": 10, "offset": 0, "network": "cardano", "hash": "6c83cf62225ecdf0cbb57e11718a8ec079f490b7f05d97f5a6d2214fb00be182" } ``` The `properties` field on the currency object contains the parsed datum: ``` "properties": "---\nassetName: 494e4459\nfingerprint: asset1u8caujpkc0km4vlwxnd8f954lxphrc8l55ef3j\npolicyId: 533bb94a8850ee3ccbe483106489399112b74c905342cb1792a797a0\n", ``` ## Related resources - [Cardano Address API](/docs/blockchain/Cardano/address) — balances, staking, and the `addressStats` aggregate cube - [Cardano Coinpath API](/docs/blockchain/Cardano/coinpath) — multi-hop ADA flow tracing across addresses - [Cardano Transactions API](/docs/blockchain/Cardano/transactions) — transaction-level totals and fees --- ## Cardano Mints API - Track Native Token Mints URL: https://docs.bitquery.io/docs/blockchain/Cardano/mints/ Cardano native token mints: get recent mint and burn events and aggregate Cardano token mints by month, with GraphQL queries you can run. # Cardano Mints API Cardano doesn't mint tokens through smart contracts the way EVM chains do. Every native token — fungible or NFT — is issued under a **minting policy**, and every mint or burn shows up on-chain as a single event tied to that policy. The Mints API exposes those events with amounts, transaction hash, block context, and the full asset metadata. Use it to track NFT collection drops, fungible-token issuance, stablecoin supply changes, or any kind of on-chain supply movement. :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get recent Cardano mint and burn events Pull the 10 most recent mint events across every minting policy on a given date. The `value` field is signed: positive numbers are mints, negative numbers are burns. Each result includes block height and timestamp, transaction hash and index, and full currency metadata — including the policy-based `address`, asset name, symbol, `tokenId` (CIP-14 fingerprint), `tokenType`, and decimals. ```graphql { cardano(network: cardano) { mints(options: {limit: 10, desc: "block.height"}, date: {is: "2026-05-01"}) { block { height timestamp { time(format: "%Y-%m-%d %H:%M:%S") } } value transaction { hash index } currency { address name symbol tokenId tokenType decimals } } } } ``` To find the largest single mints, sort by `desc: "value"`. To filter by a specific policy or asset, add `currency: {is: ""}` — see the [DJED examples](/docs/blockchain/Cardano/djed) for the pattern. On Cardano, the policy ID is the first 56 hex characters of `currency.address`; the remainder is the hex-encoded asset name. ## Aggregate Cardano mints by month Get monthly mint counts by pulling `mintCount` from the `transactions` cube. Returns one row per month with the total mint count, input and output values, and fees — a compact view for tracking issuance trends across quarters or years. ```graphql { cardano(network: cardano) { transactions( options: {desc: "date.month", limit: 12} date: {since: "2023-01-01", till: "2023-12-31"} ) { date { month startOfInterval(unit: month) } mintCount(calculate: sum) inputValue input_value_usd: inputValue(in: USD) outputCount inputCount feeValue fee_value_usd: feeValue(in: USD) } } } ``` Change `startOfInterval(unit: month)` to `week` or `day` for finer buckets. To drill from a monthly total down to the individual mint events, combine this query with the one above. ## Related resources - [Djed Stablecoin API](/docs/blockchain/Cardano/djed) — currency-filtered mint and burn examples on a real asset - [Cardano Transactions API](/docs/blockchain/Cardano/transactions) — full transaction context for mint events --- ## Cardano Transactions API - Fees, Inputs, Outputs & Mints URL: https://docs.bitquery.io/docs/blockchain/Cardano/transactions/ Cardano transactions: query transactions for a specific date with fees, inputs and outputs, and count daily Cardano transactions over time. # Cardano Transactions API The Transactions API returns transaction-level data on Cardano: input and output totals, fees in ADA and USD, mint counts, withdrawals, and block context. Use it for daily reporting, fee analysis, spotting outlier transactions, and building activity dashboards. :::info Endpoint Cardano GraphQL queries are served at `https://graphql.bitquery.io`. ::: ## Get Cardano transactions for a specific date Pull 10 transactions from a single day with full economic context — input value in ADA and USD, fee value in ADA and USD, mint count, withdrawal totals, output value, and input/output counts. ```graphql { cardano(network: cardano) { transactions(options: {limit: 10}, date: {is: "2023-11-29"}) { block { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } height } hash index inputValue input_value_usd: inputValue(in: USD) outputValue inputCount outputCount feeValue fee_value_usd: feeValue(in: USD) mintCount withdrawalValue withdrawalCount } } } ``` Switch `date: {is: ...}` to `date: {since: ..., till: ...}` for a range, sort with `options: {desc: ["block.height", "index"], limit: 10}` to pull the latest, or add `feeValue: {gt: ...}` to surface high-fee transactions only. ## Count daily Cardano transactions Aggregate the total transaction count per day for the last 10 days. Useful for activity dashboards, throughput monitoring, and spotting unusual spikes. ```graphql { cardano(network: cardano) { transactions(options: {desc: "date.date", limit: 10}) { date { date } count } } } ``` Use `startOfInterval(unit: day, interval: 10)` for coarser buckets, raise `limit` for more days, or add a `date: {since: ..., till: ...}` window. ## Related resources - [Cardano Blocks API](/docs/blockchain/Cardano/blocks) — block-level lookups and time-window queries - [Cardano Inputs and Outputs API](/docs/blockchain/Cardano/inputs-outputs) — UTXO-level transaction data - [Cardano Mints API](/docs/blockchain/Cardano/mints) — drill into the mint events behind `mintCount` --- ## Chain-Scale Screeners with selectWhere URL: https://docs.bitquery.io/docs/trading/query-operators/selectwhere-screeners/ Filter on computed aggregates server-side with selectWhere — the HAVING clause of the Bitquery Trading cube — to build token and wallet screeners in one request. # Chain-Scale Screeners with `selectWhere` `selectWhere` is the Trading cube's `HAVING` clause: it filters on a **computed aggregate** rather than on input rows. That is what makes a screener possible in one request — "every token whose 24-hour volume exceeded $1M", "every wallet with more than 500 trades" — instead of paginating the whole chain into your client and filtering there. A one-day, all-network screener scans a few million one-minute rows covering a few hundred thousand tokens and returns a few hundred survivors in **one to three seconds**. ```graphql { Trading { Tokens( where: { Token: { Network: { is: "Solana" } } Interval: { Time: { Duration: { eq: 60 } } } Block: { Time: { since: "2026-09-01T00:00:00Z", till: "2026-09-02T00:00:00Z" } } } orderBy: { descendingByField: "vol" } limit: { count: 1000 } ) { Token { Id Symbol } vol: sum(of: Volume_Usd, selectWhere: { gt: "1000000" }) } } } ``` ## Where it runs in the pipeline ``` where → GROUP BY → selectWhere (HAVING) → orderBy → limitBy → limit ``` This is ClickHouse's own clause order, and each position matters: - **`selectWhere` binds the aggregate it is attached to**, and only that one. A sibling aggregate in the same selection set is unaffected — which is the test that actually distinguishes HAVING from WHERE. (A contradictory predicate returning zero rows proves nothing; a contradictory `where` does the same.) - **HAVING runs before `limit`.** With N groups in the window and K qualifying, a small `limit: L` returns L **qualifying** rows. If the limit were applied first you would get roughly `L × K / N` — mostly non-qualifying rows. That cardinality argument is the proof. - **`limitBy` runs after ordering**, so it slices an already-filtered, already-sorted result into a per-key top-N. It is not a pre-filter and does not make a screener cheaper. :::caution `limitBy` is a per-key top-N only if you also supply `orderBy` Without `orderBy`, `limitBy` returns an arbitrary N per key that varies between runs. The outer `limit` is applied after `limitBy` and truncates the whole result. ::: ## The operator set depends on what you attach it to | Attached to | Type | Operators | | --- | --- | --- | | An aggregate metric (`sum`, `count`, `median`, …) | `Metric_filter_String` / `_Float` | `gt` `ge` `lt` `le` `eq` `ne` | | A **numeric** field-level selector | `OLAP_Float` | the same six | | A **string** field-level selector | `OLAP_String` | the full 15-operator string set — `like`, `startsWith`, `includes`, … | | A boolean leaf field | `Boolean` | a bare value: `selectWhere: true` | There is **no `between`** anywhere. Multiple clauses AND together, both inside one `selectWhere` object and across different metrics in the same selection set — so express a range with `ge` and `le`: ```graphql vol: sum(of: Volume_Usd, selectWhere: { ge: "10000" le: "1000000" }) ``` ## Literal types follow the metric's return type `sum`, `count` and `uniq` return JSON strings and take **string** literals; every Float-returning metric takes a **numeric** literal. Passing the wrong one is a clean schema error, not a silent failure. String literals are compared **numerically, not lexicographically** — `"100"` is greater than `"20"`, and `{gt: "9", lt: "400"}` correctly admits `19.09` and `318.96`. ## The silent no-op — the most important rule on this page A bare leaf field is a **GROUP BY dimension, not an aggregate**, so a `selectWhere` attached to it has nothing to filter. It is accepted, does nothing, and returns plausible wrong rows with no error. ```graphql # WRONG — silently unfiltered Volume { Usd(selectWhere: { gt: 1000 }) } # RIGHT — maximum: makes it an aggregate Volume { Usd(maximum: Volume_Usd, selectWhere: { gt: 1000 }) } ``` The rule: **the field must carry at least one of `maximum:`, `minimum:` or `if:`.** :::warning `if:` alone satisfies the rule but returns an arbitrary representative `if:` makes the field an aggregate, so the HAVING binds — but the value returned is an arbitrary row's value, not a statistic. Use `maximum:` or `minimum:` to make a leaf field an aggregate; use `if:` only alongside one of them. ::: ## Conditional HAVING Combining `if:` and `selectWhere` on the same metric filters on a **slice** of the group — for example wallets whose buy-side volume alone clears a threshold, or tokens active earlier in the window but dormant in the last two hours: ```graphql buys: sum(of: AmountsInUsd_Quote, if: { Side: { is: "Buy" } }, selectWhere: { gt: "50000" }) ``` ## What you cannot express | Want | Status | Do instead | | --- | --- | --- | | HAVING on a **ratio** | `calculate` takes no `selectWhere` | Compute and **rank** the ratio server-side (see below); apply the final cut client-side | | `in` / `notIn` | Absent from metric filters; present in `OLAP_String` but fails at runtime | Use `like` / `startsWith`, or put set membership in the cube's own `where:` | | Filtering `array_intersect` | The argument exists and type-checks, then fails server-side | Known limitation — filter in your client | | Any of this on a **stream** | `selectWhere` is absent from all four subscription cubes | Query only — see [what does not survive streaming](/docs/subscriptions/what-does-not-survive-streaming/) | ### Ranking by a ratio server-side You cannot put a HAVING on a ratio, but you can compute and order by one: ```graphql ratio: calculate(expression: "sum(of: Volume_Usd) / count") n: count(selectWhere: { gt: "100" }) ``` `calculate` needs **at least one other aggregate in the same selection set** — alone, or beside a bare leaf field, it returns a ClickHouse error (`Column ... is not under aggregate function and not in GROUP BY`). Pair it with `orderBy` on its alias and a `selectWhere` floor on a separate aggregate, and only the final ratio cut happens in your client. ## Reproducibility near a threshold Aggregates built from floating-point sums — `sum`, and anything derived from it — vary in the last few significant figures between identical runs over a frozen window, because summation order across parallel shards is not fixed. A token sitting within about 0.01% of a **sum-based** threshold can therefore move in and out of the result between runs. `count`, `uniq` and `maximum:` / `minimum:` selectors are exactly stable. Prefer a count-based or max-based threshold when a stable membership list matters. ## Related - [Trending Tokens (Multi-Chain)](/docs/trading/crypto-price-api/examples#trending-tokens-multi-chain) — a real multi-chain screener built with `selectWhere` - [Select by metric (general reference)](/docs/graphql/metrics/selectWhere/) - [Conditions with `if`](/docs/graphql/metrics/if/) - [Trading Data Overview](/docs/trading/trading-data-overview/) --- ## Cloud Lambda Function Examples URL: https://docs.bitquery.io/docs/cloud/examples/lambda-functions/ Lambda Functions that read and parse raw Protobuf blocks from the Bitquery data lake on S3. Keep queries fast with indexed filters. # How to Write a Lambda Function to get Ethereum Data from AWS (Use AWS for Web3 ) In this tutorial we will see how to write a Lambda function to retrieve raw Ethereum blocks from the [Bitquery data lake](/docs/data-lake/). The blocks are LZ4-compressed Protobuf that the function decodes. We use the sample buckets available in the [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-oi4sbdu6zro3i?sr=0-1&ref_=beagle&applicationId=AWSMPContessa). ### Prerequisites 1. An AWS account with appropriate permissions to create Lambda functions and S3 bucket access. 2. Access to the Ethereum data in the specified S3 bucket ### Step-by-Step Guide: #### 1. Navigating to Lambda Functions Page 1. Open your web browser and go to [AWS Management Console](https://aws.amazon.com/console/). 2. Sign in to your AWS account. 3. Once signed in, navigate directly to the Lambda service by using the following URL: [AWS Lambda Console](https://console.aws.amazon.com/lambda/home) - Alternatively, you can access the Lambda console by following these steps: - Click on "Services" in the top left corner of the AWS Management Console. - In the "Compute" section, select "Lambda" from the options provided. Remember to replace `region-name` in the URL with the appropriate AWS region code where your Lambda functions are deployed. For example, `us-east-1`, `us-west-2`, etc. This will direct you to the Lambda console for the specified AWS region where you can manage your Lambda functions. #### 2. Prepare the Python Module as a Layer The `lz4` does not come preinstalled on the Python SDK in AWS . To use the `lz4` module in your Lambda function, you'll need to create a Python layer. Here's how you can do it: Open a new terminal on your machine and run the following commands. This will create a zip file with the `lz4` package installed ```bash # Install lz4 to a local directory pip3 install --target ./python lz4 # Create a ZIP archive of the Python module zip -r lz4.zip ./python ``` Once done, go to the Lambda function page, scroll down to "Layers" in the Designer section. - Click on "Add a layer" and select "Upload a .zip file". - Upload the `lz4.zip` file you created earlier. - Add the layer to your Lambda function. ![AWS Layer](/img/aws/layers.png) #### 3. Create a Lambda Function - Go to the AWS Lambda Console. - Click on "Create function" and choose "Author from scratch". - Give your function a name, choose Python 3.x as the runtime, and select an appropriate role with S3 read permissions. - Click on "Create function". ![lambda function](/img/aws/fn.png) #### 4. Configure the Lambda Function Code Replace the default function code with the following Python code: ```python def lambda_handler(event, context): s3 = boto3.client('s3') bucket_name = 'demo-streaming-eth' key = 'eth.blocks.s3/000016780000/000016780000_0xf127ae770b9b73af1be93e5a7ac19be5e3bac41673b2685c6b4619fb09af09f0_41452bd33251301d32c606c704120d027de580505d611e4fb1c5ff3ef51d0cb7.block.lz4' obj = s3.get_object(Bucket=bucket_name, Key=key) blocks_local_path = '/tmp/s3downloadblocks.lz4' s3.download_file(bucket_name, key, blocks_local_path) with open(blocks_local_path, 'rb') as f: compressed_data = f.read() decompressed_data = lz4.frame.decompress(compressed_data) return { 'statusCode': 200, 'body': 'File downloaded and processed successfully' } ``` This code uses the `boto3` library to download from the s3 bucket at `eth.blocks.s3/000016780000/` and store it in `s3downloadblocks.lz4` file. Once downloaded to local library on AWS, we use the `lz4` module to decompress the data. #### 5. Configure Environment Variables (Optional) If needed, you can set environment variables for the Lambda function to specify bucket names or keys dynamically. #### 6. Save and Test the Lambda Function - Click on "Save" at the top right of the Lambda function editor. - Use the "Test" button to simulate a test event. Ensure that the function executes without errors. #### 7. Invocation and Monitoring - Once the function is properly configured, you can invoke it through the Lambda console or integrate it with other AWS services. Remember to replace the `bucket_name` and `key` variables in the code with the appropriate S3 bucket details and Ethereum data file's key you want to retrieve. Adjust the code as needed to suit your specific use case. --- ## Coinpath Explained - How Bitquery Computes Fund Flows URL: https://docs.bitquery.io/docs/moneyflow-lite/coinpath-explained/overview/ Coinpath is the fund-flow engine behind MoneyFlow Lite. This section explains the graph model it builds and how amounts are attributed on account-based, UTXO and ledger-based blockchains. # Coinpath® Explained Coinpath® is the engine that computes every MoneyFlow. It turns raw transfers into a directed graph of who paid whom, how much, and how many hops away from the origin. The same engine is exposed as the Coinpath® API on the v1 GraphQL endpoint, which is what the **Get API** button opens. This section explains the model so you can interpret a trace correctly: - [How to read a Coinpath graph](/docs/moneyflow-lite/coinpath-explained/how-to-read-coinpath-graph): nodes, levels, edges and the query dimensions. - [Coinpath for EVM networks](/docs/moneyflow-lite/coinpath-explained/evm-chains): how amounts are matched on account-based chains. - [Coinpath for UTXO networks](/docs/moneyflow-lite/coinpath-explained/utxo-chains): proportional attribution on Bitcoin-like chains. - [Coinpath for ledger-based networks](/docs/moneyflow-lite/coinpath-explained/ledger-based-chains): Stellar and Ripple specifics. Coinpath® abstracts the protocol details of each blockchain and focuses on the transfer of value, so one trace reads the same way on Bitcoin, Ethereum or Tron. ## Query examples - [Bitcoin Coinpath API](/docs/blockchain/Bitcoin/bitcoin-coinpath-api) - [Cardano Coinpath API](/docs/blockchain/Cardano/coinpath) - [Algorand Coinpath API](/docs/blockchain/Algorand/algorand-coinpath-api) - [v1 money flow API examples](https://docs.bitquery.io/v1/docs/Examples/coinpath/money-flow-api) --- ## Coinpath for EVM Networks - Last Received, First Spent Attribution URL: https://docs.bitquery.io/docs/moneyflow-lite/coinpath-explained/evm-chains/ How Coinpath attributes amounts on account-based chains such as Ethereum, BNB Smart Chain and Polygon: a recursive walk that matches incoming and outgoing transfers with the last received, first spent method. # Coinpath® for EVM Networks Account-based chains keep a balance per account. A transfer is a record that adds to one balance and subtracts from another. Coinpath® turns these records into a money flow as follows. - The algorithm is **recursive**. It starts at the initial address and computes the flow for each next level, going deeper into the graph. - At each level it looks at every incoming and outgoing transfer of the addresses on that level. It then applies a rule to associate incoming with outgoing transfers and to assign amounts to the edges. - Two common rules exist: **last received, first spent** (LRFS) and **proportional**. The Coinpath® API uses LRFS on account-based chains. ## How last received, first spent works 1. Start at the initial address and compute the money flow for each next level. 2. At each level, collect all incoming and outgoing transfers of the addresses on that level. 3. Associate each incoming transfer with the first outgoing transfer that is equal to or smaller than the incoming amount. 4. If several outgoing transfers qualify, prefer the one sent first. 5. Repeat steps 3 and 4 until every incoming transfer is associated with outgoing transfers. The result is the **tracing amount** you see in MoneyFlow Lite: the part of each outgoing transfer that is attributed to funds from the origin. ## Tokens On EVM chains a MoneyFlow traces one currency at a time, chosen in the **Currency** dropdown when you [create the MoneyFlow](/docs/moneyflow-lite/create-a-moneyflow). The engine follows transfers of that token only. Swaps on a DEX change the token, so a trace of USDT stops where the funds are swapped to ETH. Create a second MoneyFlow for the new token from the swap address to continue. Chains in MoneyFlow Lite that use this model: Algorand, Arbitrum One, Arc, Base, BNB Smart Chain, Ethereum Mainnet, Filecoin Mainnet, Optimism, Polygon, Robinhood Chain and TRON. --- ## Coinpath for Ledger-Based Networks - Stellar and Ripple Fund Tracing URL: https://docs.bitquery.io/docs/moneyflow-lite/coinpath-explained/ledger-based-chains/ Why payment ledgers such as Stellar and Ripple XRP Ledger need special handling in Coinpath: multi-currency payments, multiple issuers, implicit transfers and taker-only trades. # Coinpath® for Ledger-Based Networks Payment ledgers such as Stellar and the Ripple XRP Ledger add complexity that account-based and UTXO chains do not have: 1. **A payment can be sent in one currency and received in another.** The money flow graph must track the conversion between addresses. 2. **One payment can convert through several currencies.** Every conversion inside a single transaction must be tracked. 3. **A currency can have several issuers.** USD issued by one gateway is not the same asset as USD issued by another, and the graph must keep them apart. 4. **The Ripple API does not expose every transfer inside a transaction.** The graph has to infer transfers that are not explicit in the ledger data. ## How Coinpath® adapts - Every transfer has separately defined **sent** and **received** amounts, each with its own currency, and they may differ. - Pre-processing extracts every value transfer between addresses, including those that happen implicitly inside a transaction. - The graph allows edges with different currencies on the same path. - The same address may appear on level N and level N+1 when it transfers to itself as a result of trading. - Only **taker** trades appear in the money flow. The maker side is not part of the path. In MoneyFlow Lite, Ripple XRP Ledger is available in the **Blockchain** dropdown. --- ## Coinpath for UTXO Networks - Proportional Input-Output Attribution URL: https://docs.bitquery.io/docs/moneyflow-lite/coinpath-explained/utxo-chains/ How Coinpath splits amounts between inputs and outputs on Bitcoin, Litecoin, Dogecoin and other UTXO chains, with a worked example that shows how change outputs are handled. # Coinpath® for UTXO Networks On Bitcoin, Litecoin, Dogecoin, Dash and Cardano the unit of value is the unspent transaction output (UTXO). A transaction consumes some UTXOs as inputs and creates new ones as outputs. There is no account balance to follow, so Coinpath® has to decide how much of each input ends up in each output. Coinpath® uses a **proportional input-output attribution** formula. It splits every output among the inputs in proportion to each input's share of the total input amount. ## Worked example Take this transaction: ``` Inputs: Address A: 1 BTC Address B: 2 BTC Outputs: Address C: 0.5 BTC Address D: 2 BTC Address B: 0.49 BTC ``` Address B appears on both sides, so its 0.49 BTC output is **change** returning to the sender. Coinpath® attributes the outputs as: - Address C: 0.5 BTC - Address D: 1.51 BTC (2 BTC minus the 0.49 BTC change) - Address B: 0.49 BTC (change) The change output is treated as a separate output in UTXO mode. In account-based mode it is ignored. ## What this means in MoneyFlow Lite - A Bitcoin transaction with many inputs and outputs produces several edges from one transaction hash. The transactions table lists the same hash once per sender-receiver pair. - The **Tracing Amount** of an edge is the proportional share that came from the origin. It is often much smaller than the **Txn Amount**, especially after an exchange sweep. - The tracing method shown in the MoneyFlow summary for Bitcoin is **First-in, First-out**, applied on top of the proportional split when funds pass through an address across several transactions. --- ## Combined Database URL: https://docs.bitquery.io/docs/graphql/dataset/combined/ Combined Database in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. See examples in the Bitquery IDE. # Combined Database When you query combined database, actually the query goes to the archive and real time databases separately and then the results are joined together. That's why this is the combination of features of these databases. :::note [Select Block](/docs/graphql/dataset/select-blocks/) attributes for combined database controls how you can query the trunk or branch block updates **ONLY for real time database data part**. On Solana, `select_blocks: branches` reads nothing from the archive part, because the archive holds no abandoned blocks. On other chains, use the default `tree`. ::: :::tip Typically you should avoid using this type of query, as it is slower than real time and archive and does not give full consistency of the data. ::: Also Check [Archive](/docs/graphql/dataset/archive) and [RealTime](/docs/graphql/dataset/realtime) dataset. ## What is the difference between realtime, archive, and combined datasets? **Realtime** holds a **rolling recent window** (roughly the last hours) with **low latency** and may include branch blocks. **Archive** holds **genesis-to-near-present** data with **trunk** consistency and **higher ingest delay**. **Combined** runs your query against **both** and **merges** results so one query can span recent + historical, but it is **slower** and can expose **different fields** than realtime-only (especially on Solana). Read [Realtime](/docs/graphql/dataset/realtime), [Archive](/docs/graphql/dataset/archive), and [Dataset options](/docs/graphql/dataset/options). ## Why does data from archive dataset not match combined dataset? **Archive** and **realtime** are separate pipelines: block inclusion, **finality**, and **delay** differ. **Combined** **joins** the two, so row counts, last timestamps, and aggregates may not equal archive alone plus realtime alone. ## Why does dataset: combined return fewer fields than dataset: realtime on Solana? On Solana, some projections (for example certain **`Trade.Side`** / account-level fields) are only populated in the **realtime** slice. **Combined** and **archive** historical aggregates may **omit** those columns, which triggers “columns not available” errors if you request them. Use fields documented for **archive/combined** (e.g. `DEXTradeByTokens` aggregates) or switch to **`dataset: realtime`** for debugging. See [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/) and [Pump.fun combined-dataset note](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#why-does-my-pumpfun-query-return-columns-not-available-in-combined-dataset). ## Why do some filters error out on dataset: combined or archive? On Solana, `DEXTradeByTokens` on **archive** and **combined** is served from pre-aggregated tables that do not carry USD-denominated columns. Using `Trade.PriceAsymmetry`, `Trade.AmountInUSD`, `Trade.Side.AmountInUSD`, or `Trade.PriceInUSD` inside `where:` fails with `no table can query DEXTradeByToken` or `database schema not defined for archive cube`. The failure is a hard error, not a silently dropped filter. The same fields still work as **output measures** — for example `sum(of: Trade_Side_AmountInUSD)` and `quantile(of: Trade_PriceInUSD)` return correct values on archive. Native-unit equivalents (`Trade.Amount`, `Trade.Side.Amount`, `Trade.Price`) filter normally. See [Filter limitations on aggregate datasets](/docs/blockchain/Solana/historical-aggregate-data/#filter-limitations-on-aggregate-datasets). --- ## Combined Dataset in Bitquery GraphQL URL: https://docs.bitquery.io/docs/graphql/combined/ Combined Dataset in Bitquery GraphQL in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Combined Queries Several queries can be combined and return results in one request: * queries to different databases and blockchains can be combined in one query; * queries to different cubes can be combined as well Example of query returning max block for ETH and BSC networks: ```graphql query { eth: EVM(network: eth) { Blocks { Block{ Number(maximum: Block_Number) } } } bsc: EVM(network: bsc) { Blocks { Block{ Number(maximum: Block_Number) } } } } ``` :::tip Use [Aliases](/docs/graphql/metrics/alias) to name the elements if needed ::: :::danger Subscriptions and queries can not be combined ::: --- ## Conditional Metrics URL: https://docs.bitquery.io/docs/graphql/metrics/if/ Conditional Metrics in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. See examples in the Bitquery IDE. # Conditional Metrics Metrics have ```if``` attribute to define the condition for metric execution. This way you can calculate metrics, that only refer to the part of the dataset you request. This expression returns count of blocks with the non-zero gas used: ``` count(distinct: Block_Number if: {Block: {GasUsed: {gt: "0"}}}) ``` :::note The ```if``` attribute has the same structure as [filters](/docs/graphql/filters), and applies to almost all metrics — see the exceptions below. ::: ## Example: buy and sell statistics in one row `if:` is what lets you split a group without splitting the query. On the Trading cube: ```graphql { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } } }, Block: { Time: { since: "...", till: "..." } } } limitBy: { by: Trader_Address, count: 1 } limit: { count: 100 } ) { Trader { Address } buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) bought: sum(of: AmountsInUsd_Quote, if: { Side: { is: "Buy" } }) sold: sum(of: AmountsInUsd_Quote, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$sold - $bought") } } } ``` `if:` also accepts **string dimensions that the `of:` / `with:` arguments reject**, so it is the escape hatch that makes much of the metric surface usable on categorical columns. ## Exceptions and limits :::warning `any:` inside `if:` crashes the request Nesting an `any:` combinator inside an `if:` filter returns `runtime error: invalid memory address or nil pointer dereference`. Express the alternation a different way — usually as two separate aliased metrics. ::: Three metrics do **not** accept `if:` at all: `gini`, `nakamoto` and `theil_index`. Every other metric, including `entropy`, does. Combining `if:` with [`selectWhere`](/docs/graphql/metrics/selectWhere) gives a conditional HAVING — filtering groups on a **slice** of their own data, such as wallets whose buy-side volume alone clears a threshold. :::tip Use [Aliases](/docs/graphql/metrics/alias) to name these metrics ::: --- ## Contract Calls & Traces on Robinhood Chain — WebSocket Streams URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-calls-api/ Stream Robinhood contract calls and internal traces over GraphQL WebSockets: decoded inputs, call trees, deployments and reverts. No node required. # Contract Calls & Traces on Robinhood Chain — WebSocket Streams Stream **every contract call and internal trace on Robinhood** with Bitquery GraphQL — top-level calls and nested internal calls, with **decoded input arguments**, gas accounting, revert errors, and the surrounding transaction and receipt joined into one record. The `EVM.Calls` cube on `network: robinhood` replaces a tracing node: no `debug_traceTransaction` loops, no 4-byte databases, no trace decoding pipeline. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). Open **one WebSocket that carries every call on the chain**, or narrowly filtered sockets — per contract, per function, per selector, deployments-only, reverts-only. Every subscription on this page was verified live over WebSocket, and every query was executed against the production endpoint before publishing. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Events API](/docs/blockchain/robinhood/robinhood-events-api/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) - [Robinhood Trades](/docs/blockchain/robinhood/robinhood-trades/) - [WebSocket authentication](/docs/authorization/websocket/) ::: **On this page:** [Why not a tracing node](#why-stream-calls-instead-of-tracing-a-node) · [Datasets & history](#datasets-and-history) · [Call anatomy](#what-one-call-row-contains) · [Firehose](#stream-all-calls-firehose) · [By contract](#stream-calls-to-one-contract) · [By function](#stream-by-function-name-or-selector) · [Deployments](#stream-contract-deployments) · [Reverts](#stream-reverted-calls) · [Value traces](#internal-eth-value-transfers) · [By wallet](#calls-from-a-wallet) · [Call tree](#full-call-tree-of-a-transaction) · [Analytics](#top-called-contracts) · [FAQ](#faq) --- ## Why stream calls instead of tracing a node | | Tracing node (`debug_traceTransaction` / `trace_filter`) | Bitquery Calls stream | | --- | --- | --- | | Infrastructure | Archive node with tracing enabled — heavy to run and sync | One WebSocket to `streaming.bitquery.io` | | Decoding | Raw calldata; you maintain ABIs and 4-byte lookups | `Arguments` arrive **decoded and typed** for known signatures | | Scope | Per-transaction or per-block tracing loops | Server-side filters: contract, function name, selector, caller, `Create`, `Reverted`, value, time | | Context | Trace only — separate calls for tx and receipt | Transaction and `Receipt` joined onto every call | | Deployments | Diff traces for `CREATE` frames yourself | `Call: { Create: true }` is a filter | | Backfill | Re-trace history block by block | Same query with `dataset: archive` / `combined` | --- ## Datasets and history - **`realtime`** (the default) — a rolling window of recent blocks whose depth varies; measure it with the probe below rather than assuming it. - **`archive`** — deep call history with no age limit: it holds Robinhood calls from 30 April 2026, its earliest rows (measured 6 November 2026); its head lags the chain by minutes. - **`combined`** — archive + realtime union; the safe choice for fixed windows (24h, 7d). For bulk history, ask about a [Data Store export](https://bitquery.io/datastore) at sales@bitquery.io. ### Check the calls window ```graphql { EVM(network: robinhood) { Calls { count earliest: Block { Time(minimum: Block_Time) } latest: Block { Time(maximum: Block_Time) } } } } ``` --- ## What one call row contains | Group | What it gives you | | --- | --- | | **`Call`** | `From`/`To`, `Value` (+USD), gas fields, `Signature` (function `Name`, full `Signature`, 4-byte `SignatureHash`), flags: `Create`, `Delegated`, `Reverted`, `Success`, `SelfDestruct`, `Error`, plus tree position (`Index`, `CallerIndex`, `CallPath`, `InternalCalls`) | | **`Arguments`** | Decoded, typed **function input values** (`address`, `bigInteger`, `string`, `hex`, `bool`, `integer`) with parameter names | | **`Transaction`** | Hash, `From`/`To`, value, full gas and fee fields (incl. USD) | | **`Receipt`** | `GasUsed`, `CumulativeGasUsed`, `ContractAddress`, receipt `Type` | | **`Block`** | `Number`, `Time`, `Nonce` | Tree semantics: `Index` numbers each call within the transaction, `CallerIndex` points to the parent call's index, and `CallPath` is the position path from the top-level call (e.g. `[2, 0]` = first sub-call of call 2) — enough to rebuild the entire trace tree client-side. For calls, `Signature.SignatureHash` is the **4-byte selector** as uppercase hex **without** a `0x` prefix (e.g. `A9059CBB` for `transfer(address,uint256)`). Calls with an empty `Name` are undecoded selectors — still streamed and filterable by hash. Note that on-chain `balanceOf`-style reads made by contracts also appear: this cube sees every call executed, not just state-changing ones. --- ## Stream all calls (firehose) One socket, every call on the chain — top-level and internal — with decoded inputs and full context. Events arrive in per-block batches. :::warning Very high volume Calls are the highest-volume cube on a busy chain (every transaction fans out into many internal calls). Use the firehose for exploration and full indexers; filter in production. ::: ```graphql subscription { EVM(network: robinhood) { Calls { Block { Number Time Nonce } Call { CallPath InternalCalls From To Signature { Name Parsed Signature SignatureHash SignatureType } CallerIndex Create Delegated Error Gas GasUsed Index Reverted SelfDestruct Success Value ValueInUSD } Receipt { CumulativeGasUsed ContractAddress Type GasUsed } Transaction { From To Type Cost CostInUSD Gas GasFeeCap GasFeeCapInUSD GasPriceInUSD GasPrice GasTipCapInUSD GasTipCap Hash Value ValueInUSD } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` :::tip WebSocket connection Connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol (`connection_init` → `connection_ack` → `subscribe`). See [WebSocket authentication](/docs/authorization/websocket/). Any subscription on this page also runs as a query — add `limit` and `orderBy` and drop the `subscription` keyword. ::: :::tip Prefer Kafka for the firehose Consuming the full call feed continuously? Bitquery also delivers Robinhood data as **Kafka streams** — decoded transactions, calls, and events on the protobuf topic `robinhood.transactions.proto` — with consumer-group scaling and replay. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). ::: --- ## Stream calls to one contract **Protocol ops:** every function invocation of one contract — including internal calls from other contracts, which a mempool or tx-level watcher misses. Example: the Uniswap V4 pool manager. ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { To: { is: "0x8366a39cc670b4001a1121b8f6a443a643e40951" } } } ) { Block { Time } Call { From To Signature { Name SignatureHash } GasUsed Success } Transaction { Hash } } } } ``` --- ## Stream by function name or selector **Method-level feeds:** filter by decoded function name to receive one method across **every** contract — for example, every ERC-20 `transfer` call on the chain. ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { Signature: { Name: { is: "transfer" } } } } ) { Block { Time } Call { From To Signature { Name SignatureHash } } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` To pin one exact ABI variant — or to match an **undecoded** method — filter the 4-byte selector instead (uppercase hex, no `0x`): ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { Signature: { SignatureHash: { is: "70A08231" } } } } ) { Block { Time } Call { To Signature { Name SignatureHash } } } } } ``` --- ## Stream contract deployments ▶️ [Run in IDE](https://ide.bitquery.io/new-contracts-deployed-robinhood-chain) **New-contract radar:** `Call: { Create: true }` matches every `CREATE`/`CREATE2` frame — top-level and factory-internal. On these rows **`Call.To` is the newly deployed contract address** and `Call.From` is the deployer (`Receipt.ContractAddress` is populated only for top-level deployment transactions). ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { Create: true } } ) { Block { Time } Call { From To Create Success } Transaction { Hash From } } } } ``` --- ## Stream reverted calls **Error monitoring:** every failed call with its revert reason — watch your own contracts for breakage, or the whole chain for failing bots and exploits in progress. `Call.Error` carries the message (commonly `execution reverted`). ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { Reverted: true } } ) { Block { Time } Call { From To Error Reverted Success Signature { Name } } Transaction { Hash } } } } ``` Scope it with a `Call.To` filter to alert only on your own deployments. --- ## Internal ETH value transfers **Value tracing:** calls that move native ETH (`Call.Value > 0`) — including internal transfers that never appear as top-level transaction values. The [Transfers cube](/docs/blockchain/robinhood/robinhood-transfers/) models the same movements with USD enrichment; use Calls when you want them inside their execution context. ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { Value: { gt: "0" } } } ) { Block { Time } Call { From To Value ValueInUSD Signature { Name } } Transaction { Hash } } } } ``` --- ## Calls from a wallet Everything one address executes — as transaction sender or as an internal caller (routers and bots show up here with their full fan-out). Swap in any address; rows appear only while it is active. ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { From: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } ) { Block { Time } Call { To Value Signature { Name } } Transaction { Hash } } } } ``` --- ## Full call tree of a transaction **The `debug_traceTransaction` replacement:** every call frame of one transaction, ordered by `Call_Index`, with `CallerIndex`/`CallPath` to rebuild the tree and decoded arguments per frame. ```graphql { EVM(network: robinhood, dataset: archive) { Calls( orderBy: { ascending: Call_Index } where: { Transaction: { Hash: { is: "0x816be7f8f359f85066599fcd2585cbf7c3b544590315afc5298dc7e538b3678b" } } } ) { Call { Index CallerIndex CallPath From To Delegated Create Success GasUsed Value Signature { Name } } } } } ``` --- ## Top called contracts **Discovery:** the most-invoked contracts over a window, with how many distinct methods each serves. ```graphql { EVM(network: robinhood) { Calls( limit: { count: 10 } orderBy: { descendingByField: "calls" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Call { To } calls: count signatures: count(distinct: Call_Signature_SignatureHash) } } } ``` --- ## Top function signatures Which methods dominate the chain — grouped by signature with counts. Rows with an empty `Name` are undecoded selectors. ```graphql { EVM(network: robinhood) { Calls(limit: { count: 15 }, orderBy: { descendingByField: "count" }) { Call { Signature { Name SignatureHash } } count } } } ``` --- ## Top gas-burning contracts **Gas analytics:** rank contracts by total gas consumed over a window — where the chain's compute actually goes. ```graphql { EVM(network: robinhood) { Calls( limit: { count: 10 } orderBy: { descendingByField: "gas" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Call { To } gas: sum(of: Call_GasUsed) calls: count } } } ``` --- ## Call volume in a time window One-row stats for dashboards: total calls, distinct callers, distinct called contracts. Use `dataset: combined` when the window must be complete regardless of realtime depth. ```graphql { EVM(network: robinhood, dataset: combined) { Calls(where: { Block: { Time: { since_relative: { hours_ago: 1 } } } }) { count callers: count(distinct: Call_From) contracts: count(distinct: Call_To) } } } ``` --- ## Use-case patterns | Goal | Approach | | --- | --- | | Trace explorer / tx debugger | [Per-transaction call tree](#full-call-tree-of-a-transaction) with `Index`/`CallerIndex`/`CallPath` | | New-contract & token-factory radar | [`Create: true` stream](#stream-contract-deployments) — `Call.To` is the deployed address | | Contract error alerting | [`Reverted: true`](#stream-reverted-calls) scoped to your `Call.To` | | Method-level analytics | [Name / selector streams](#stream-by-function-name-or-selector); counts via [top signatures](#top-function-signatures) | | Internal ETH flow tracing | [`Value > 0` calls](#internal-eth-value-transfers), or [Transfers](/docs/blockchain/robinhood/robinhood-transfers/) for USD-priced movements | | Bot / router monitoring | [`Call.From` stream](#calls-from-a-wallet) for the full execution fan-out | | Chain ops dashboards | [Top called contracts](#top-called-contracts), [gas burners](#top-gas-burning-contracts), [window stats](#call-volume-in-a-time-window) | | Event-side view of the same activity | [Robinhood Events API](/docs/blockchain/robinhood/robinhood-events-api/) | --- ## Tips 1. **Filter production streams.** The calls firehose outweighs every other cube — per-contract, per-selector, deployments-only, and reverts-only sockets are cheap. 2. For calls, `SignatureHash` is the **4-byte selector, uppercase hex, no `0x`** (events use the full 32-byte topic hash instead). 3. `Create: true` rows put the **deployed contract in `Call.To`**; `Receipt.ContractAddress` fills only for top-level deployment transactions. 4. Function names collide across ABIs and undecoded methods have empty names — pin exact behavior with the selector filter. 5. Every executed call appears, including contract-to-contract `balanceOf`-style reads — filter by name/selector to cut that noise from analytics. 6. Rebuild trace trees client-side from `Index`, `CallerIndex`, and `CallPath`; `InternalCalls` tells you how many children a frame has. 7. Realtime depth varies — measure with the [window probe](#check-the-calls-window); use `combined` for fixed windows. Archive has no age limit, and its calls start on 30 April 2026; for bulk data, ask about a [Data Store export](https://bitquery.io/datastore) at sales@bitquery.io. 8. Decoded `Arguments` are the function **inputs**; for emitted results, join the same transaction on the [Events API](/docs/blockchain/robinhood/robinhood-events-api/). --- ## FAQ ### Can I trace Robinhood transactions without a tracing node? Yes — filter `EVM.Calls` by `Transaction.Hash` and order by `Call_Index` to get every internal call frame with decoded inputs, gas, and revert state: a `debug_traceTransaction` replacement served over GraphQL. Stream the same cube for live traces. ### How do I detect new contract deployments in real time? Subscribe with `Call: { Create: true }`. Each row's `Call.To` is the freshly deployed contract address and `Call.From` its deployer — factory-internal deployments included. See [Stream contract deployments](#stream-contract-deployments). ### How do I monitor failed or reverted calls? Subscribe with `Call: { Reverted: true }` (optionally scoped by `Call.To` to your contracts) and read `Call.Error` for the revert reason. See [Stream reverted calls](#stream-reverted-calls). ### How do I filter by a 4-byte function selector? Use `Call.Signature.SignatureHash` with the selector as uppercase hex without `0x` — e.g. `A9059CBB` for `transfer(address,uint256)`. This also matches methods whose ABI is unknown (empty `Name`). ### How far back does Robinhood calls data go? `archive` has no age limit (its calls start on 30 April 2026), and `realtime` holds a rolling recent window — measure either with the [window probe](#check-the-calls-window). For bulk history, Bitquery can provide data exports on request. ### Which cube should I use — Calls, Events, or Transfers? `Calls` is execution: who invoked what, with inputs, gas, and reverts. [`Events`](/docs/blockchain/robinhood/robinhood-events-api/) is what contracts emitted. [`Transfers`](/docs/blockchain/robinhood/robinhood-transfers/) is pre-modeled asset movement with USD enrichment. See [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/). --- ## Counterparties of a Wallet in USD with Labels on the Bitquery MCP URL: https://docs.bitquery.io/docs/mcp/counterparties/ List everyone a wallet or a set of wallets paid and was paid by, in USD with entity labels, or total the flow by label type (exchanges, bridges, sanctioned entities), on Ethereum, Tron, Solana, Bitcoin and Zcash through the Bitquery MCP server. # Counterparties of a Wallet The `counterparties` tool on the [Bitquery MCP server](/docs/mcp/mcp-server/) lists everyone an address paid and was paid by, in one call. Every row carries the USD value each way, the transfer counts, the first and last time the two transacted, and the counterparty's labels. It can also total the whole flow by label type, for example _"62% of the inflow came from exchanges, 3% from sanctioned addresses"_. One tool serves five chains. You pick the chain with the `chain` argument: `ethereum`, `tron`, `solana`, `bitcoin` or `zcash` (transparent addresses only). | Question | Use | | --- | --- | | Who did this wallet, or this set of wallets, pay and get paid by, in USD and with labels? | `counterparties` | | What share of the inflow came from exchanges, bridges or risk entities? | `counterparties` with `group_by: "label_type"` | | A quick look at one address's top flows | `_address_flow_summary` | | The labels of addresses you already have | `labels_for_addresses` | | A risk score for an address | `address_risk_report` | ## Ask the agent _"List the counterparties of the CoW Protocol settlement contract 0x9008d19f58aabd9ed0d60971565aa8510560ab41 on Ethereum since yesterday, money in only, above $100,000."_ _"For this Tron wallet, what share of the USD it received in 2026 came from exchanges? Use counterparties with group_by label_type."_ _"Here are 20 Ethereum addresses that belong to one fund. Treat them as one set and list who they paid in USDT this quarter."_ ## Inputs | Input | Default | What it does | | --- | --- | --- | | `chain` | required | `ethereum`, `tron`, `solana`, `bitcoin` or `zcash` | | `addresses` | required | One address, or a set of up to 50 separated by spaces, commas or `\|`. The set is treated as one wallet. Bitcoin and Zcash take one address per call. | | `direction` | `both` | `in` counts only who paid the set, `out` only who the set paid, `both` counts each way | | `after_time` / `before_time` | last 90 days | The window. Accepts `YYYY-MM-DD`, `YYYY-MM-DD HH:MM[:SS]`, ISO-8601 such as `2026-09-20T00:00:00Z`, or 10-digit unix seconds. `after_time` is inclusive, `before_time` is exclusive. The answer echoes the resolved window. | | `max_txs` | `1000` | Bitcoin and Zcash only. How many of the address's newest spends and newest receipts to read, 1 to 2,000 per side. Raise it to look further back. | | `group_by` | `address` | `address` returns one row per counterparty. `label_type` totals the flow by each counterparty's primary label type. | | `label_type` | empty | Keep only counterparties with at least one label of these types, a comma-separated list such as `cex-hot-wallet,cex-deposit-address` | | `exclude_label_type` | empty | Drop counterparties with any label of these types | | `token` | empty (every token) | Restrict to one token: a contract address on Ethereum; a TRC-20 contract or a TRC-10 numeric asset id on Tron. Rejected on Solana, Bitcoin and Zcash. | | `min_usd` | `0` | Return only counterparties whose USD received plus sent is at least this much. The rest still count in `below_cutoff`. | | `include_zero_value` | `0` | `1` keeps zero-amount transfers. They are dropped by default because address poisoning plants look-alike addresses with 0-amount transfers. | | `include_internal` | `0` | Ethereum only. `1` also counts value moved by contract code inside a transaction (internal transfers). Rejected on the other chains. | | `limit` | `100` | How many counterparties to return, largest USD first, 1 to 1,000 | | `cursor` | empty | Paging token from `next_cursor`. `group_by: "address"` only. | | `format` | `markdown` | `markdown` returns a summary and a counterparty table to read. `json` returns the full object described below. | ## How the chains differ | | Ethereum | Tron | Solana | Bitcoin | Zcash | | --- | --- | --- | --- | --- | --- | | Address format | `0x` + 40 hex characters | Base58, starts with `T` | Base58, 32 to 44 characters, case-sensitive | `1...`, `3...` or `bc1...` | Transparent `t1...` or `t3...` | | Addresses per call | Up to 50, as one set | Up to 50, as one set | Up to 50, as one set | 1 | 1 | | Window | `after_time` / `before_time` | `after_time` / `before_time` | `after_time` / `before_time` | The newest `max_txs` spends and receipts, inside `after_time` / `before_time` | The newest `max_txs` spends and receipts, inside `after_time` / `before_time` | | `token` filter | Token contract address | TRC-20 contract or TRC-10 asset id | Not available | Not available | Not available | | `include_internal` | Available | Rejected | Rejected | Rejected | Rejected | | Labels | Labels from every EVM chain the counterparty is known on | Tron labels | Solana labels | Bitcoin labels | No address labels, so every counterparty falls in `(none)` | An address that is not valid for the chain is skipped and listed in `addresses_invalid`; the call still runs for the others. Compare `addresses_requested` with `addresses_used`. On Bitcoin and Zcash the counterparties come from the address's newest `max_txs` transactions on each side, so the window the answer echoes can start at the chain's first block. A busy address may have more history than `max_txs` reaches: raise it, up to 2,000. ## Output: one row per counterparty With `group_by: "address"` (the default), counterparties sort by `usd_total` (USD received plus sent), largest first. | Field | Meaning | | --- | --- | | `counterparty` | The other address | | `usd_in`, `usd_out` | USD the set received from it and sent to it, each transfer valued at its own time. `null` (never 0) when no transfer on that side could be priced. | | `usd_total` | `usd_in` plus `usd_out`. This is the ranking key, not a net balance: a pass-through counterparty counts on both sides. | | `transfers_in`, `transfers_out` | Transfer counts each way | | `unpriced_transfers_in`, `unpriced_transfers_out` | Transfers that were counted but could not be priced | | `first_seen`, `last_seen` | First and last transfer between them in the window | | `label`, `label_value`, `label_chain` | The primary label type, its value (for example the exchange's name) and the chain it was found on | | `labels` | Every label type the counterparty carries | | `label_status` | `labeled` when a primary label was picked; `unlabeled` when the counterparty carries only descriptive types such as `high-transacting` or `signer`; `none` when it has no labels | | `token_count`, `tokens` | How many tokens moved, and a per-token breakdown: `token`, `amount_in`, `amount_out` (in token units, as decimal strings), `usd_in`, `usd_out`, `transfers_in`, `transfers_out` | | `set_members` | When you pass more than one address: which of your addresses dealt with this counterparty | The summary around the rows: | Field | Meaning | | --- | --- | | `window` | The resolved `after_time` and `before_time` | | `addresses_requested`, `addresses_used`, `addresses_invalid` | How many addresses you passed, how many were used, and which were skipped | | `below_cutoff` | `usd` and `transfers` of every counterparty past `limit` or under `min_usd`. The returned rows plus this bucket account for the whole flow. | | `totals` | `usd_in`, `usd_out`, `usd_total`, `transfers_in`, `transfers_out`, and the unpriced transfers split into `no_price_transfers`, `suspect_transfers` and `stale_transfers` | | `self_transfers` | Transfers between two of your own addresses. They are left out of the rows. | | `share_base_usd_in`, `share_base_usd_out` | The USD base the shares are computed over, after the label filters | | `labeled_usd_share_in`, `labeled_usd_share_out` | Share of that USD that went to or came from labelled counterparties | | `pick_rule` | The label-type priority used to pick each `label` (see below) | | `partial` | `true` when the call stopped early and returned only what finished. Narrow the window or the set. | | `next_cursor` | Present when more counterparties follow | | `cost`, `timing_ms` | Statements run, rows and bytes read, and time taken | `format: "markdown"` returns the same summary and a shorter table: counterparty, label, label status, USD in and out, transfer counts, unpriced counts, token count, first and last seen. Ask for `format: "json"` when you need `usd_total`, the full `labels` list, `tokens`, `set_members` or `cost`. ## Output: totals by label type With `group_by: "label_type"` each counterparty counts once, under its primary label type, so the shares add up to 100%. Each row of `types` carries: | Field | Meaning | | --- | --- | | `label_type` | The label type. `(none)` collects counterparties with no usable label; `(below_cutoff)` collects the counterparties past `limit`. | | `counterparties` | How many counterparties fall in the type | | `usd`, `share` | USD received plus sent, and its share of `share_base_usd` | | `share_in`, `share_out` | The share of the inflow and of the outflow | | `top_counterparties` | The largest counterparties of the type, with their USD | The summary carries `share_base_usd`, `share_base_usd_in`, `share_base_usd_out`, `self_transfers`, `pick_rule`, `partial` and `cost`. With `label_type` or `exclude_label_type` set, the tool filters first and then groups, so the shares are over the filtered total. ## Which label is picked A counterparty often has many labels. The primary `label` is the first type it has in this order: 1. Risk: `sanctioned-entity`, `terrorist`, `hacker`, `ransomware`, `darknet-market`, `mixer`, `money-laundering`, `tainted`, `scam`, `phishing`, `issuer-blocked-usdt`, `issuer-blocked-usdc`, `risk-flag`. 2. Exchanges and services: `cex-hot-wallet`, `cex-cold-wallet`, `cex-deposit-address`, `cex-withdrawal-address`, `cex-unknown-type`, `otc-desk`, `payment-processor`, `gambling`, `custodian`, `e-commerce`, `no-kyc`, `mining-pool`, `bridge`. 3. DeFi and contracts: `dex-router`, `dex-aggregator`, `dex-pool`, `lending-protocol`, `staking-protocol`, `derivatives-protocol`, `yield-aggregator`, `asset-manager`, `market-maker`, `service`, `infrastructure`, `token-contract`, `contract`. 4. Every other type, most common first. Within one type the most trusted source wins, then the most sources, then the lowest value. These types describe an address but not who owns it, so they are never picked: `account-abstraction-user`, `deployer`, `dormant`, `first-funder`, `governance`, `high-transacting`, `multisig`, `platform-user`, `proxy`, `safe-wallet`, `signer`, `tron-energy-delegate`, `username`. The exact list in force comes back in `pick_rule` on every call. ## USD values - Each transfer is valued at its own time and the values are summed. - A transfer in a token with no price is counted in the transfer totals and in `unpriced_transfers_*`, and adds nothing to USD. Spam and look-alike tokens usually have no price, so a huge amount of one cannot push its sender to the top of the list. - A side with no priced transfer is `null`, not 0. Shares are over priced USD only. ## Paging Pass `next_cursor` as `cursor` on the next call with the same `chain`, `addresses`, window and filters. Keep going until no `next_cursor` comes back. Each counterparty appears on one page only, so the pages joined together are the full list. Take the overall totals from the first page: on a later page, `totals` covers only the counterparties from that page on, which is the previous page's `below_cutoff`. Set `after_time` and `before_time` to fixed times when you page, so every page reads the same window. ## Related - [Tracing on the MCP](/docs/mcp/Tracing/overview/) for multi-hop fund tracing and investigation prompts. - [Holders and balances](/docs/mcp/holders-balances/) for holder exports and wallet balance checks. --- ## Create a MoneyFlow - Start Tracing an Address in MoneyFlow Lite URL: https://docs.bitquery.io/docs/moneyflow-lite/create-a-moneyflow/ Step-by-step guide to creating a MoneyFlow in MoneyFlow Lite: enter an address, choose the blockchain and currency, set a date range and read the address statistics before you trace. # Create a MoneyFlow A MoneyFlow is one trace, saved under your account. It starts from one address on one blockchain. This page walks through the create form at [lite.bitquery.io](https://lite.bitquery.io/). ![Create MoneyFlow form with address statistics](/img/moneyflow-lite/create-moneyflow.jpg) ## Step 1: Enter an address Paste the address you want to trace into **Enter an address**. The field accepts one address. ## Step 2: Select the blockchain Open the **Blockchain** dropdown and pick the network the address belongs to. You can type to filter the list. ![Blockchain dropdown in MoneyFlow Lite](/img/moneyflow-lite/blockchain-list.jpg) As soon as both fields are filled, the **Address statistics** card on the right loads: - **Balance** of the address, and **Balance USD** on account-based chains. - **Inbound transactions** count. - **Outbound transactions** count. Use these numbers to sanity-check the address before you trace. An address with thousands of transactions produces a dense chart, so narrow the date range first. ## Step 3: Choose the currency (account-based chains only) On Ethereum, BNB Smart Chain, TRON and the other account-based chains a **Currency** dropdown appears. It lists the native coin and every token the address has moved, with the date of the last transfer for each. ![Currency dropdown on Ethereum](/img/moneyflow-lite/currency-select.jpg) Pick the asset you want to follow. This form traces ETH from an Ethereum address over a four-day window: ![Create MoneyFlow form for an Ethereum address with ETH selected](/img/moneyflow-lite/create-moneyflow-ethereum.png) A MoneyFlow traces one currency. To follow a second token from the same address, create another MoneyFlow. Bitcoin and the other UTXO chains have no currency selector. They always trace the native coin. ## Step 4: Set the date range (optional) **Select Date Range** is filled automatically with the first and last activity of the address. Shorten it to focus on the period you care about. The trace only includes transfers inside this window. You can change the range later. The calendar button at the top of a trace opens a **Change Date Range** dialog that creates a new MoneyFlow for the same address. ## Step 5: Click Create MoneyFlow Click **Create MoneyFlow**. The page shows **Generating MoneyFlow** while the first hop is computed. A busy address can take a minute. When it finishes you land on the trace page. The URL looks like `https://lite.bitquery.io/moneyflow//origin`. The MoneyFlow is saved under your account, so you can return to it from the **MoneyFlows** list at any time. The first version of every trace is **V1.0** with depth **In:1 – Out:1**. That is one hop in and one hop out from the origin address. See [Trace In and Trace Out](/docs/moneyflow-lite/trace-in-and-trace-out) to go deeper. ## Rename a MoneyFlow The title defaults to `
MoneyFlow`. Click the pencil icon next to the title to rename it, for example to a case number. The copy icon next to it copies the title. ## Create another MoneyFlow The **+** button in the top-right corner returns to the create form. ## Next step [How to read the MoneyFlow chart](/docs/moneyflow-lite/how-to-read-the-moneyflow-chart) --- ## Creating a Discord Bot to Fetch Price Data URL: https://docs.bitquery.io/docs/usecases/discord-bot/ Build Creating a Discord Bot to Fetch Price Data: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Tutorial: Creating a Discord Bot to Fetch Price Data In this tutorial, we will walk you through the process of creating a Discord bot using the `discord.js` library. The bot will fetch price data using the dextrades API and respond to a specific command in a Discord server. ### Prerequisites Before we begin, make sure you have the following: - Node.js installed on your machine - A Discord account - A Bitquery API Token (you can sign up for a free API token at [Bitquery](https://ide.bitquery.io/)) #### Setting up the Bot Before we began coding, you need to create a bot on https://discord.com/developers/applications . - Once your application is created, navigate to the Bot tab and set the **MESSAGE CONTENT INTENT**. This permission is necessary for the bot to read and send messages. ![intent](/img/ApplicationExamples/discord-appn.png) - Next, navigate to the URL generator and set scope as `bot` as shown in the image below ![scope](/img/ApplicationExamples/discord-scope.png) - Finally, set the permissions you want the bot to have and copy the URL generated. Go to the URL and add the bot to the channel of your choice. ![permission](/img/ApplicationExamples/discord-permissions.png) You are now ready to write the code. ### Step 1: Setting Up the Project 1. Create a new directory for your project and navigate to it in your terminal. 2. Initialize a new Node.js project by running the command `npm init` and following the prompts. 3. Install the required dependencies by running the command `npm install discord.js axios dotenv`. 4. Create a new file named `index.js` and open it in your preferred code editor. ### Step 2: Importing Dependencies At the top of your `index.js` file, import the necessary dependencies: ```javascript const { Client, GatewayIntentBits } = require("discord.js"); const axios = require("axios"); require("dotenv").config(); ``` - The `discord.js` package provides a convenient interface for interacting with the Discord API. - The `axios` package is used to make HTTP requests to the Bitquery API. - The `dotenv` package allows us to load environment variables from a `.env` file. ### Step 3: Configuring the Discord bot Next, configure the Discord bot by creating a new instance of the `Client` class: ```javascript const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], }); ``` - The `intents` property specifies which events the bot will listen to. In this case, we are listening for guild and message related events. ### Step 4: Adding Bot Token and API OAuth Token Retrieve your Discord bot token and Bitquery OAuth token. Replace the placeholders in the following code with your actual tokens: ```javascript const CLIENT_TOKEN = ""; ``` ### Step 5: Handling Bot Events Add the necessary event listeners to handle bot events: ``` client.on("debug", console.log); client.on("ready", () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on("messageCreate", async (message) => { console.log("message", message.content); // Add your command logic here }); ``` - The `"debug"` event will log debug information to the console. - The `"ready"` event is triggered when the bot successfully logs in and is ready to receive commands. - The `"messageCreate"` event is triggered whenever a new message is sent in a guild. We will add our command logic here. ### Step 6: Fetching Price Data Inside the `"messageCreate"` event listener, add the code to fetch price data using the Bitquery API: ``` if (message.content === "price") { try { let data = JSON.stringify({ query: '{\n EVM(dataset: combined, network: eth) {\n buyside: DEXTrades(\n limit: {count: 1}\n orderBy: {descending: Block_Time}\n where: {Trade: {Buy: {Currency: {SmartContract: {is: "0x5283d291dbcf85356a21ba090e6db59121208b44"}}}}}\n ) {\n Block {\n Number\n Time\n }\n Transaction {\n From\n To\n Hash\n }\n Trade {\n Buy {\n Amount\n Buyer\n Currency {\n Name\n Symbol\n SmartContract\n }\n Seller\n Price\n }\n Sell {\n Amount\n Buyer\n Currency {\n Name\n SmartContract\n Symbol\n }\n Seller\n Price\n }\n }\n }\n }\n}\n', variables: "{}", }); let config = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", "X-API-KEY": API_KEY, Authorization: "Bearer YOUR_BEARER_TOKEN", }, data: data, }; axios .request(config) .then((response) => { const priceData = JSON.stringify(response.data.data.EVM.buyside[0]); const priceMessage = `Latest Price: ` + priceData; message.channel.send(priceMessage); }) .catch((error) => { console.log(error); }); } catch (error) { console.error("Error fetching price:", error); message.channel.send("Error fetching price."); } } ``` - Replace `'YOUR_GRAPHQL_QUERY'` with your actual GraphQL query. This query is used to fetch the latest price data. - Replace `'YOUR_BEARER_TOKEN'` with your actual Bearer token from Bitquery. ### Step 7: Logging in the Bot Finally, add the code to log in the bot using the Discord bot token: ``` client.login(CLIENT_TOKEN); ``` ### Step 8: Running the Bot Save the changes to your `index.js` file and run the command `node index.js` in your terminal to start the bot. ### Testing the Bot Type the message `price` in your chat. You will see the latest trade information on the chat. --- ## Creating a Heatmap for Ethereum Token Holders using Python URL: https://docs.bitquery.io/docs/usecases/tokenholder-heatmap/ Build Creating a Heatmap for Ethereum Token Holders using Python: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application. # Creating a Heatmap for Ethereum Token Holders using Python In this tutorial we will see how to visualize top token holders in a heatmap using the [Token Holder APIs](/docs/blockchain/Ethereum/token-holders/token-holder-api/) with Python. 1. **Import libraries**: Necessary Python libraries are imported including `requests` for making HTTP requests, `json` for parsing JSON data, `pandas` for data manipulation and analysis, `seaborn` and `matplotlib` for data visualization. ```python import requests import json import pandas as pd import seaborn as sn import numpy as np import matplotlib.pyplot as plt ``` 2. **Define API URL and headers**: The Bitquery Streaming API URL is defined along with necessary headers including content type, API key, and authorization token. ```python url = "https://streaming.bitquery.io/graphql" headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ory_at_...' } ``` 3. **Create the payload**: The payload consists of a GraphQL query that fetches the top 50 token holders of a specific Bitfinex LEO Token (`0x2af5d2ad76741191d15dfe7bf6ac92d4bd912ca3`) on a specific date. You can read more about Token Holder APIs [here](/docs/blockchain/Ethereum/token-holders/token-holder-api/) ```python payload = json.dumps({ "query": "{\nEVM(dataset: archive, network: eth) {\nHolders(\ndate: \"2026-08-01\"\nwhere: {Currency: {SmartContract: {is: \"0x2af5d2ad76741191d15dfe7bf6ac92d4bd912ca3\"}}}\nlimit: {count: 50}\norderBy: {descending: Balance_Amount}\n) {\nHolder {\nAddress\n}\nBalance {\nAmount\n}\n}\n}\n}\n", "variables": "{}" }) ``` 4. **Make the API request**: A POST request is sent to the Bitquery Streaming API with the headers and payload. The response is then saved in the `response` variable. ```python response = requests.request("POST", url, headers=headers, data=payload) ``` 5. **Parse the response**: The JSON response is parsed and the relevant data is extracted into a pandas DataFrame. The balance amounts are converted to float type and a new column `Amount_Share` is created which represents the proportion of each holder's balance to the total balance. ```python data_json2 = response.json() holders = data_json2['data']['EVM']['Holders'] df_holders = pd.json_normalize(holders) df_holders['Balance.Amount'] = df_holders['Balance.Amount'].astype(float) total_amount = df_holders['Balance.Amount'].sum() df_holders['Amount_Share'] = df_holders['Balance.Amount'] / total_amount * 100 ``` 6. **Create aliases for Ethereum addresses**: To simplify the visualization, each unique Ethereum address is mapped to an alias. ```python aliases = {address: f"Ad_{i}" for i, address in enumerate(df_holders['Holder.Address'].unique())} df_holders['Alias'] = df_holders['Holder.Address'].map(aliases) ``` 7. **Reshape data**: The aliases and amount shares are reshaped into a 2D array preparing it to be rendered in a heatmap. ```python a = 10 b = 5 address_reshaped = df_holders['Alias'].values.reshape(a, b) amount_reshaped = df_holders['Amount_Share'].values.reshape(a, b) ``` 8. **Create annotations**: Annotations are created for the heatmap. These annotations consist of the pair of address alias and the corresponding amount share. ```python annotations = [ f"{pair}\n{value:.3f}%" for pair, value in zip(address_reshaped.flatten(), amount_reshaped.flatten()) ] annotations = np.array(annotations).reshape(a, b) ``` 9. **Plot the heatmap**: Lastly, a heatmap is plotted using seaborn. The x and y labels represent the pairs of addresses, the color intensity indicates the amount share, and the annotations show the exact value of the amount share for each pair. The title of the plot is 'Token Holder Volume Percentage'. ```python plt.figure(figsize=(10, 8)) sn.heatmap(amount_reshaped, annot=annotations, fmt="", cmap='YlOrRd', cbar_kws={'label': 'Holder Volume %'}) plt.title('Token Holder Volume Percentage') plt.show() ``` Please note that you will need to replace the placeholder values in the script with your actual authorization token, and the smart contract address of the token you are interested in. Also, the reshaping dimensions (a=10, b=5) might need to be adjusted based on the number of token holders. This is how it will look finally, you can change the heatmap palette based on your design. ![heatmap](/img/ApplicationExamples/heatmap.png) --- ## Cross-Chain Blockchain Data API: One Query Across Chains URL: https://docs.bitquery.io/docs/category/cross-chain/ Three ways to read several blockchains in one Bitquery call: Trading cubes with one schema for ten chains, aliases over chain roots, and the Currencies cube. # Cross-Chain Blockchain Data API: One Query Across Chains Bitquery serves every chain from one GraphQL endpoint, and there are three ways to read more than one chain in a single call. The `Trading` cubes carry trades, prices, market cap and supply for Solana, Ethereum, BNB Chain, Base, Arbitrum, Optimism, Polygon, Tron, Robinhood Chain and Arc in one schema, so a filter on a token symbol returns rows from every network at once. GraphQL aliases let one query address several chain roots, such as `EVM(network: bsc)` and `EVM(network: arc)`, and return them side by side. And the `Currencies` cube aggregates one asset across networks into a single price, so `bid:bitcoin` is one row rather than a list of wrapped versions. ## Three ways to go cross-chain | Approach | Use it when | Example | |---|---|---| | Trading cubes, one schema, ten chains | You want trades, candles, market cap or supply for a token wherever it trades | The USDC query below | | Aliases over chain roots | You need chain-level cubes (transfers, balances, calls) for the same address or contract on several chains | [NFTs tracking across chains](/docs/examples/cross-chain/cross-chain-api) | | `Trading.Currencies` | You want one price per asset regardless of chain | `Currency: { Id: { is: "bid:bitcoin" } }` on the [Crypto Price API](/docs/trading/crypto-price-api/) | ## USDC trades on every chain in one call No network filter: the rows come back tagged with the network they happened on. Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account. ```graphql { Trading { Trades( where: { Pair: { Token: { Symbol: { is: "USDC" } } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } Pair { Market { Network Protocol } Token { Symbol Network } QuoteToken { Symbol } } PriceInUsd AmountsInUsd { Base } } } } ``` Add `Pair: { Market: { NetworkBid: { in: ["bid:eth", "bid:base"] } } }` to keep only the chains you care about, or group by `Pair_Market_Network` with `count` and `sum` to compare chains in one table. ## Aliases over several chain roots A GraphQL alias names each root, so `binance: EVM(network: bsc) { ... }` and `ethereum: EVM(network: eth) { ... }` run in one request and come back as two keys. Fragments keep the selection identical across them. The [NFTs tracking across chains](/docs/examples/cross-chain/cross-chain-api) page shows the pattern for one wallet's NFTs on several chains; the same pattern applies to transfers, calls or events. Note that the cubes and field names must exist on every root you alias, so it works across the EVM chains, while Solana needs its own selection. ## Related pages - [Crypto Price API](/docs/trading/crypto-price-api/) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api/) - [Supported chains](/docs/blockchain/supported-chains) - [Understanding cubes](/docs/category/understanding-cubes) --- ## Crypto Coin Ticker API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/crypto-coin-ticker/ Crypto Coin Ticker API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Scale further with WebSocket subscriptions or Kafka streams. # Crypto Coin Ticker API You can build your crypto coin ticker using our [DEX APIs](https://bitquery.io/products/dex) based on the requirements of the data field. For pre-aggregated price data with OHLC, consider using our [Crypto Price API](/docs/trading/crypto-price-api/). For **per-swap ticks**, see the **[Crypto Trades API](/docs/trading/crypto-trades-api/trades-api)**. ## Using Crypto price API For a **live ticker**, use the **[Crypto Price API](/docs/trading/crypto-price-api/)** stream. [Open the 1-second price stream in the IDE](https://ide.bitquery.io/1-second-crypto-price-stream). > Note: A `Volume: {Usd: {gt: 5}}` filter is applied to remove extreme outliers; the price stream already pre-filters outliers—this is an additional check. ```graphql subscription { Trading { Tokens( where: { Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 5 } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` ## OHLC ticker from DEXTradeByTokens Open this API on our [GraphQL IDE](https://ide.bitquery.io/Coin-ticker-api_4). ```graphql { EVM(dataset: realtime) { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Side: {Currency: {SmartContract: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}}}, Currency: {SmartContract: {is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}}, PriceAsymmetry: {lt: 0.1}}} ) { Block { Timefield: Time(interval: {in: minutes, count: 10}) lastTradeTime: Time(maximum: Block_Time) FirstTradeTime: Time(minimum: Block_Time) LastTradeBlock: Number(maximum: Block_Number) FirstTradeBlock: Number(minimum: Block_Number) } volume: sum(of: Trade_Amount) Trade { Currency { Name Symbol } Side { Currency { Name Symbol } } high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } count } } } ``` We are getting OHLC (Open High Low Close) data, with the last trade details on 10-minute intervals. You can change this interval like the following. - Time(interval: \{in: minutes, count: 5\}) - Time(interval: \{in: seconds, count: 10\}) - Time(interval: \{in: hours, count: 3\}) - Time(interval: \{in: days, count: 14\}) - Time(interval: \{in: weeks, count: 3\}) - Time(interval: \{in: months, count: 1\}) - Time(interval: \{in: years, count: 2\}) You can also add additional information if you want; there are many more fields available. --- ## Crypto Currency Price API URL: https://docs.bitquery.io/docs/trading/crypto-price-api/currency/ One chain-agnostic USD price per asset, blended across its wrapped and bridged forms on every chain, with GraphQL queries and streams. # Currency Cube ## What it is The Currency cube gives one chain-agnostic USD price per asset. Bitcoin is one currency, `bid:bitcoin`, blended from WBTC, cbBTC and its other bridged or wrapped forms across every supported chain. Use it when you want one global number for an asset like BTC or ETH. For the price of a specific token on a specific market, use the [Pairs cube with `Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). ## How to get it Query or subscribe to `Trading.Currencies`. Filters that matter: - **Currency**: `Currency: { Id: { is: "bid:bitcoin" } }`. Ids are lowercase symbols for listed currencies (`usdc`, `dai`, `aave`, `arb`) and `bid::
` for tokens that are their own currency. - **Interval**: `Interval: { Time: { Duration: { eq: 60 } } }`. Durations are 1, 3, 5, 10, 30, 60, 300, 900, 1800 and 3600 seconds. `Ranking`, `RankingDetail` and `LeadingPool` do not exist on `Currencies`. `Liquidity` and `Supply` do. ## How it is derived The index blends the asset's token representations into one series, weighting each by its liquidity share after the staleness discount. See [How Currency Prices Are Determined](/docs/trading/crypto-price-api/price-index-algorithm#how-currency-prices-are-determined). Stablecoin currencies are priced from an external spot source, not from DEX trades. At currency level they carry `Liquidity.Usd` `0`, `Liquidity.Source` `""`, `RealShare` `0` and `Supply.MarketCap` `0`. ### How OHLC is calculated The OHLC values describe a **single computed cross-chain index series** over the interval. Within each interval the cube tracks the liquidity-weighted blend of the asset's token representations and records that blend's open, high, low and close: - Open: the index value at the start of the interval. - High: the highest value **the index** reached during the interval. - Low: the lowest value **the index** reached during the interval. - Close: the index value at the end of the interval. :::caution The index is not a min/max envelope across chains `High` and `Low` are **not** the maximum and minimum of the per-chain prices. Because the index is a liquidity-weighted blend, an extreme print on a single chain, especially a thin one, is damped and may never reach the currency candle at all. Individual chain representations can therefore sit outside the currency's High/Low band. If you are monitoring a depeg or a single-venue dislocation, query the constituents through [`Tokens`](/docs/trading/crypto-price-api/tokens) filtered on `Currency.Id` instead. ::: ## Fields | Field | Type | Meaning | | --- | --- | --- | | `Currency { Id Name Symbol }` | String | The asset. | | `Block { Date Time Timestamp }` | String / DateTime / String | Time of the last update in the interval. | | `Interval { Time { Start End Duration } }` | DateTime / DateTime / Int | The bar. `Duration` in seconds. | | `Price.Ohlc { Open High Low Close }` | Float | OHLC of the index series, above. | | `Price.Average { Estimate Mean SimpleMoving WeightedSimpleMoving ExponentialMoving }` | Float | Averages over the interval and a 5-entry moving window. `Estimate` is the valuation price. | | `Price.IsQuotedInUsd` | Boolean | `true` by default; prices are in USD. | | `Volume.Base` | Float | Asset amount traded across all representations and chains. | | `Volume.Quote` | Float | Sum of quote-token amounts. Not USD; use `Volume.Usd`. | | `Volume.Usd` | Float | Volume in USD. | | `Volume.BaseAttributedToUsd` | Float | Part of `Volume.Base` traded against quote tokens with a known USD price. | | `Liquidity { Usd Source RealShare ... }` | Float / String | USD liquidity summed over every token representation and chain in the blend. `RealShare` is the fraction backed by measured reserves; `Source` is the leading pool's. Per-pool reserve fields and `UpdatedAt` are not set here. See [Liquidity fields](/docs/trading/crypto-price-api/liquidity-fields). | | `Supply { CirculatingSupply TotalSupply MaxSupply MarketCap FullyDilutedValuationUsd }` | Float | Currency-level supply and valuation, the same figures as on Tokens and Pairs. See [Supply fields reference](/docs/trading/crypto-price-api/supply-fields). | ## Examples ### What is the latest cross-chain Bitcoin price? ```graphql { Trading { Currencies( where: { Currency: { Id: { is: "bid:bitcoin" } }, Interval: { Time: { Duration: { eq: 60 } } } }, limit: { count: 1 }, orderBy: { descending: Block_Time } ) { Currency { Id Name Symbol } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base BaseAttributedToUsd Quote # Sum of quote token amounts (not USD); use Usd for USD totals (see Price Index Algorithm) Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd #The price is shown in USD (`IsQuotedInUsd: true` by default). Ohlc { Open # Index value at the start of the interval High # Highest index value in the interval Low # Lowest index value in the interval Close # Index value at the end of the interval } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` - `Price.Ohlc.Close` is the index price at the end of the latest minute. - `Supply.TotalSupply` is the on-chain wrapped supply, not Bitcoin's 19.9 M; see [Bitcoin and on-chain supply](/docs/trading/crypto-price-api/supply-fields#bitcoin-bidbitcoin-and-on-chain-supply). ## Related - [Tokens cube](/docs/trading/crypto-price-api/tokens) - [Pairs cube](/docs/trading/crypto-price-api/pairs) - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) - [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields) - [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) --- ## Crypto Liquidity API: Token Liquidity, Pool Reserves and Rug Pull Checks URL: https://docs.bitquery.io/docs/trading/crypto-price-api/liquidity-use-cases/ Query crypto liquidity with the Bitquery Trading API: real vs estimated token liquidity, DEX pool reserves, the best pool to trade, rug pull checks, stale reserves, slippage depth, liquidity history and chain-wide rankings. # Crypto Liquidity API: token liquidity, pool reserves and rug pull checks ## What it is Each question below is one query on the Trading cubes, using the [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields). Every query was run against the live API on 2026-10-20; the IDE link opens it ready to run. ## Examples Two things to keep in mind throughout: - `Liquidity.Usd` is the pool's balance of the row's quote token, in USD. It is not TVL: a pool explorers show at $2M TVL reports about $1M here. - Only `Source: "real"` and `"real_stale"` are measured. Everything else is an estimate; most queries below filter on it. ### Checking one token #### Is this token's price backed by real liquidity, and which pool sets it? One `Tokens` row gives the liquidity summed over the token's pools, how much of it is measured (`RealShare`), the market cap, and the pool at `Ranking.Position: 1`. :::note `LeadingPool.PoolAddress` is empty on some rows; the pool address is the last segment of `MarketId`. ::: [Run in IDE](https://ide.bitquery.io/Is-this-token-backed-by-real-liquidity) ```graphql query IsTokenBackedByRealLiquidity { Trading { Tokens( limit: {count: 1} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:solana:6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} } ) { Block { Time } Token { Symbol Id } Price { Average { Mean } } Liquidity { Usd Source RealShare } Supply { MarketCap } LeadingPool { MarketId QuoteTokenId PoolAddress } } } } ``` #### Which pool should I trade this token on? The token's pools ordered by measured liquidity, with the quote asset, reserves, the last price in each pool and its rank in the price blend. Only `real` and `real_stale` sources, so estimates cannot push a thin pool to the top. [Run in IDE](https://ide.bitquery.io/Best-pool-to-trade-a-token-by-liquidity) ```graphql query BestPoolToTradeAToken { Trading { Pairs( limit: {count: 5} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Liquidity_Usd} where: { Token: {Id: {is: "bid:solana:6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} Liquidity: {Source: {in: ["real", "real_stale"]}} } ) { Market { Protocol Name } Pool { Address } QuoteToken { Symbol } Price { Ohlc { Close } } Liquidity { Usd QuoteReserve BaseReserve UpdatedAt Source } Ranking { Position Weight } } } } ``` #### How did one pool's liquidity move over the last 24 hours? Hourly rows for a single pool. `Liquidity.Usd` on an hourly row is the last snapshot in that hour; hours with no trade have no row. [Run in IDE](https://ide.bitquery.io/Pool-liquidity-history-hourly) ```graphql query PoolLiquidityHistoryHourly { Trading { Pairs( limit: {count: 24} orderBy: {descending: Block_Time} where: { Pool: {Address: {is: "EQEu6NyEq8nECAiem1YkTu3uDBiGTEA2tYBLBmr9YJ7Y"}} QuoteToken: {Symbol: {is: "WSOL"}} Interval: {Time: {Duration: {eq: 3600}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Block { Time } Interval { Time { Start } } Liquidity { Usd Source } Price { Ohlc { Open Close } } Volume { Usd } } } } ``` ### Screening for risk #### Which tokens show a big market cap on almost no liquidity? The classic scam shape: a tiny pool sets a price, the supply is huge, and the market cap looks like billions. `RealShare: 1` keeps estimates out, so the $20 pools are genuinely $20 pools. [Run in IDE](https://ide.bitquery.io/Tokens-with-big-market-cap-and-no-liquidity) ```graphql query BigMarketCapNoLiquidity { Trading { Tokens( limit: {count: 10} limitBy: {by: Token_Id, count: 1} orderBy: {descending: Supply_MarketCap} where: { Token: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Supply: {MarketCap: {gt: 1000000}} Liquidity: {Usd: {lt: 5000}, RealShare: {ge: 1}} } ) { Token { Symbol Id } Supply { MarketCap } Liquidity { Usd Source RealShare } Volume { Usd } } } } ``` #### Which pools trade heavily on almost no liquidity? Thousands of dollars of volume against a $20 reserve is a wash-trading or honeypot signal. Today's result is a cluster of Raydium pools named like stablecoin pairs, each with identical volume. [Run in IDE](https://ide.bitquery.io/High-volume-pools-with-almost-no-liquidity) ```graphql query HighVolumePoolsAlmostNoLiquidity { Trading { Pairs( limit: {count: 10} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Volume_Usd} where: { Market: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Liquidity: {Source: {is: "real"}, Usd: {lt: 1000}} Volume: {Usd: {gt: 5000}} } ) { Token { Symbol Id } Market { Protocol } Pool { Address } Liquidity { Usd } Volume { Usd } } } } ``` #### Which pools are priced off a reserve that is hours old? `real_stale` plus an `UpdatedAt` filter finds pools whose reserve snapshot is older than six hours but still counts in full. Their `Verdict` is still `priced`. [Run in IDE](https://ide.bitquery.io/Pools-priced-off-a-stale-reserve) ```graphql query PoolsPricedOffAStaleReserve { Trading { Pairs( limit: {count: 10} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Liquidity_Usd} where: { Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Liquidity: {Source: {is: "real_stale"}, UpdatedAt: {till_relative: {hours_ago: 6}}} } ) { Block { Time } Market { Network Protocol } Token { Symbol } Pool { Address } Liquidity { Usd UpdatedAt Source } RankingDetail { Verdict StaleMultiplier } } } } ``` #### Which large tokens have the most, and the least, liquidity relative to market cap? Tokens above $10M market cap with at least 90 % measured liquidity. Divide `Liquidity.Usd` by `Supply.MarketCap` on your side: today Old Slerf is 87 %, BOME 16 %, PUMP 1 %. [Run in IDE](https://ide.bitquery.io/Liquidity-share-of-market-cap-Solana) ```graphql query LiquidityShareOfMarketCapSolana { Trading { Tokens( limit: {count: 15} limitBy: {by: Token_Id, count: 1} orderBy: {descending: Liquidity_Usd} where: { Token: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} Supply: {MarketCap: {gt: 10000000}} Liquidity: {RealShare: {ge: 0.9}} } ) { Token { Symbol Id } Liquidity { Usd RealShare } Supply { MarketCap } } } } ``` ### Launches #### Which pump.fun curves are closest to graduation? On a launch curve `Liquidity.NetQuoteUsd` is the money paid in minus the money taken out, which is what migrates to the AMM at graduation. Ordering by it lists the curves nearest the threshold. :::note The graduation threshold is not in the API; divide `NetQuoteUsd` by the current threshold yourself to get a percentage. ::: [Run in IDE](https://ide.bitquery.io/Pump-fun-curves-closest-to-graduation) ```graphql query PumpFunCurvesClosestToGraduation { Trading { Pairs( limit: {count: 10} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Liquidity_NetQuoteUsd} where: { Market: {Network: {is: "Solana"}, Protocol: {is: "pump"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Liquidity: {Source: {is: "migration"}} } ) { Token { Symbol Id } Pool { Address } Liquidity { NetQuoteUsd Usd } Volume { Usd } Price { Ohlc { Close } } } } } ``` ### Execution #### Where can I sell $100k of WETH inside 1 % slippage? `DepthUsd` is how much quote, in USD, can be sold into the pool within 1 % slippage. Filter above your trade size and order by it. EVM only: Solana pools report `0`. [Run in IDE](https://ide.bitquery.io/Pools-deep-enough-for-a-100k-sale) ```graphql query PoolsDeepEnoughForA100kSale { Trading { Pairs( limit: {count: 5} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Liquidity_DepthUsd} where: { Market: {Network: {is: "Ethereum"}} Token: {Symbol: {is: "WETH"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Liquidity: {DepthUsd: {gt: 100000}} } ) { Market { Protocol } Pool { Address } QuoteToken { Symbol } Liquidity { DepthUsd Usd QuoteReserveUsd } Price { Ohlc { Close } } } } } ``` ### Chain-wide rankings #### What are the ten deepest pools on a chain? Any token, measured reserves only, one row per pool. [Run in IDE](https://ide.bitquery.io/Top-pools-by-measured-liquidity-Solana) ```graphql query TopPoolsByMeasuredLiquiditySolana { Trading { Pairs( limit: {count: 10} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Liquidity_Usd} where: { Market: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} Liquidity: {Source: {is: "real"}} } ) { Market { Protocol } Pool { Address } Token { Symbol } QuoteToken { Symbol } Liquidity { Usd QuoteReserve UpdatedAt } Volume { Usd } } } } ``` #### Which pools gained or lost the most liquidity in the last hour? `Usd(maximum: Block_Time)` returns the liquidity on the newest row and `Usd(minimum: Block_Time)` on the oldest row of the window. The change has to be computed on your side; the API cannot order by it. [Run in IDE](https://ide.bitquery.io/Pool-liquidity-now-vs-one-hour-ago) ```graphql query PoolLiquidityNowVsOneHourAgo { Trading { Pairs( limit: {count: 20} orderBy: {descendingByField: "now_Usd_maximum"} where: { Market: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {hours_ago: 1}}} Liquidity: {Source: {is: "real"}, Usd: {gt: 50000}} } ) { Pool { Address } Token { Symbol } QuoteToken { Symbol } now: Liquidity { Usd(maximum: Block_Time) } then: Liquidity { Usd(minimum: Block_Time) } first: Block { Time(minimum: Block_Time) } last: Block { Time(maximum: Block_Time) } } } } ``` #### Which DEX protocols hold the most deep pools? Count of pools above $100k measured liquidity per protocol, plus the largest pool each one has. [Run in IDE](https://ide.bitquery.io/DEX-protocols-with-the-most-deep-pools) ```graphql query DexProtocolsWithTheMostDeepPools { Trading { Pairs( limit: {count: 10} orderBy: {descendingByField: "pools"} where: { Market: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} Liquidity: {Source: {is: "real"}, Usd: {gt: 100000}} } ) { Market { Protocol } pools: count(distinct: Pool_Address) Liquidity { Usd(maximum: Liquidity_Usd) } } } } ``` #### How fragmented is liquidity: which tokens are spread over the most pools? Count of pools with at least $10k measured liquidity per token, and the largest pool for each. [Run in IDE](https://ide.bitquery.io/Token-liquidity-fragmentation-pools-per-token) ```graphql query TokenLiquidityFragmentation { Trading { Pairs( limit: {count: 10} orderBy: {descendingByField: "pools"} where: { Market: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Liquidity: {Source: {is: "real"}, Usd: {gt: 10000}} } ) { Token { Symbol Id } pools: count(distinct: Pool_Address) Liquidity { Usd(maximum: Liquidity_Usd) } } } } ``` #### Where is ETH's liquidity, chain by chain? Filtering `Tokens` by `Currency.Id` returns one row per ETH representation per chain, each with its own liquidity, source and measured share. [Run in IDE](https://ide.bitquery.io/ETH-liquidity-by-chain) ```graphql query EthLiquidityByChain { Trading { Tokens( limit: {count: 10} limitBy: {by: Token_Id, count: 1} orderBy: {descending: Liquidity_Usd} where: { Currency: {Id: {is: "bid:eth"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} } ) { Token { Network Symbol Id } Liquidity { Usd Source RealShare } Volume { Usd } } } } ``` ## Pitfalls {#what-these-fields-cannot-answer} These fields cannot answer: - **Is the LP locked or burned?** Not in the Trading cube; that is a token-program question on the chain schemas. - **When was the pool created?** No creation time here. Use the `DEXPools` cube on the chain schemas for pool-creation events, then come back here for liquidity. - **Total liquidity per chain.** There is no `sum` aggregate on `Liquidity.Usd`; page through `limitBy: {by: Pool_Address}` and add on your side. - **Order by change.** The now-vs-then query returns both values; sorting by the difference is yours to do. - **Anything before 2026-10-19.** Older rows carry `Liquidity` fields of `0`; the blend was volume-weighted then. --- ## Crypto Market Cap API URL: https://docs.bitquery.io/docs/trading/crypto-price-api/crypto-marketcap-api/ USD market cap, FDV and supply on every Crypto Price API row: query, stream or read from Kafka for tokens, currencies and pairs across ten chains. # Crypto Market Cap API ## What it is Every row of the Crypto Price API carries a `Supply` object: `MarketCap`, `FullyDilutedValuationUsd`, `CirculatingSupply`, `TotalSupply` and `MaxSupply`. It is on `Trading.Currencies`, `Trading.Tokens` and `Trading.Pairs`, next to the price and volume of that row. Query it for one token, rank a chain by it, or stream it over GraphQL subscriptions or the `trading.prices` Kafka topic. This page is a FAQ of runnable queries; field semantics are in the [Supply fields reference](/docs/trading/crypto-price-api/supply-fields). ## How to get it **Cube.** `Tokens` for a token on one chain, `Currencies` for the asset across chains. `Pairs` rows carry the same currency-level `Supply`, so a pool query gets market cap for free. **Filters.** `Token: { Address, Network }` or `Currency: { Id }` to pick the asset; `Interval: { Time: { Duration: { eq: ... } } }` always (without it every row repeats at ten durations); `Volume: { Usd: { gt: ... } }` to drop dead tokens from rankings. **Streaming.** Put `subscription` in place of `query` on any example that has no `selectWhere`, `if` or `interval:` argument. Kafka: [Multi-Chain Trading Data Streams](/docs/streams/protobuf/kafka-trading-topics-protobuf). ### How do I get the USD market cap of a single token? {#how-do-i-get-usd-market-cap-of-a-single-token} Set the token address and read `Supply.MarketCap` from the latest row. [Run query ➤](https://ide.bitquery.io/marketcap-of-pump-token) ```graphql { Trading { Tokens( where: { Token: { Address: { is: "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } } Interval: { Time: { Duration: { eq: 1 } } } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Token { Address Id IsNative Name Network Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } Supply { TotalSupply MarketCap FullyDilutedValuationUsd } } } } ``` - `Supply` is a currency-level figure: the same value appears on every row and every pool of that token. - When `CirculatingSupply` is unknown, `MarketCap` equals `FullyDilutedValuationUsd`. ## How it is derived `MarketCap` is `Price.Average.Estimate` x `CirculatingSupply`; `FullyDilutedValuationUsd` is `Price.Average.Estimate` x `TotalSupply`, and both fall back to the FDV figure when circulating supply is unknown. How `Estimate` itself is blended from pools is in the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm); the supply sources and their gaps are in the [Supply fields reference](/docs/trading/crypto-price-api/supply-fields). ## Examples ### How do I list top tokens by market cap on a blockchain? {#how-do-i-list-top-tokens-by-market-cap-on-a-blockchain} Top Solana tokens by `MarketCap`, one row per token, with a $1,000 volume floor. Change or remove `Network` for another chain or all chains. [Run query ➤](https://ide.bitquery.io/top-tokens-by-mcap-on-Solana-vol-gt-1000-USD) ```graphql { Trading { Tokens( limit: { count: 50 } limitBy: { count: 1, by: Token_Id } orderBy: { descending: Supply_MarketCap } where: { Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 1000 } } Token: { Network: { is: "Solana" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Currency { Id Name Symbol } Price { Average { Mean(maximum: Block_Time) } } Volume { Base(maximum: Block_Time) Quote(maximum: Block_Time) Usd(maximum: Block_Time) } Token { Network Symbol Address } Supply { MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) TotalSupply(maximum: Block_Time) } } } } ``` - The 1-hour `since_relative` window keeps the scan small; widen it if a token you expect is missing. - `maximum: Block_Time` picks the latest row for each token. ### How do I query total supply and circulating supply for a cryptocurrency? {#how-do-i-query-total-supply-and-circulating-supply} Set a currency id on `Currencies` and read the `Supply` fields. ```graphql { Trading { Currencies( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Currency: { Id: { is: "pump" } } Interval: { Time: { Duration: { eq: 60 } } } } ) { Currency { Id Name Symbol } Supply { TotalSupply CirculatingSupply MaxSupply MarketCap FullyDilutedValuationUsd } } } } ``` - `CirculatingSupply` and `MaxSupply` are often 0 or null for meme tokens; `TotalSupply` comes from on-chain supply. ### How do I rank tokens by 1-hour market cap change? {#how-do-i-rank-tokens-by-1-hour-market-cap-change} Set the network and a 1-hour interval and sort on the `change_mcap` [expression](/docs/graphql/capabilities/expression/). [Run query ➤](https://ide.bitquery.io/top-tokens-by-mcap-change-1h-on-Solana) ```graphql { Trading { Tokens( limit: { count: 50 } orderBy: { descendingByField: "change_mcap" } where: { Interval: { Time: { Duration: { eq: 3600 } } } Token: { Network: { is: "Solana" } } } ) { Currency { Id Name Symbol } Token { Network Symbol Address } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } change_mcap: calculate( expression: "($Price_Ohlc_Close-$Price_Ohlc_Open) * Supply_TotalSupply" ) Price { Ohlc { Open Close } } } } } ``` - `change_mcap` is the price move times `TotalSupply`, i.e. the FDV move in USD. Use `Supply_CirculatingSupply` for the market-cap move where it is known. ### How do I stream aggregated OHLC and market cap for all tokens on one chain? {#how-do-i-stream-ohlc-and-marketcap-on-one-chain} Subscribe to `Trading.Tokens` with a network and an interval for OHLC, volume and `Supply` of every token on that chain in one feed. Intervals are listed in the [OHLC guide](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api#supported-intervals). [Run Query](https://ide.bitquery.io/Aggregated-Price-of-all-tokens-in-real-time-on-one-chain_1) ```graphql subscription { Trading { Tokens( where: { Token: { Network: { is: "Solana" } } Interval: { Time: { Duration: { eq: 60 } } } } ) { Token { Id Symbol Network } Interval { Time { Start Duration End } } Volume { Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Open High Low Close } } } } } ``` ### How do I stream OHLC for a token pair across chains? {#how-do-i-stream-ohlc-for-a-token-pair-across-chains} `Trading.Pairs` with `Currency` and `QuoteCurrency` ids streams every ETH/USDC market on every chain at the chosen interval. [Run Query](https://ide.bitquery.io/Token-OHLC-Stream-1-second-Multi-Chains) ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Currency: { Id: { is: "bid:eth" } } QuoteCurrency: { Id: { is: "usdc" } } } ) { Token { Symbol } QuoteToken { Symbol } Interval { Time { Start } } Volume { Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Open High Low Close } } } } } ``` ### How do I get 5-minute price change % for high-liquidity tokens? {#how-do-i-get-5-minute-price-change-percent} `Trading.Tokens` at 300s, a USD volume floor, and `calculate` on open/close for the percentage move. [Run Query](https://ide.bitquery.io/5-minute-price-change-api) ```graphql { Trading { Tokens( limit: { count: 10 } orderBy: { descendingByField: "change" } where: { Volume: { Usd: { gt: 100000 } } Interval: { Time: { Duration: { eq: 300 } } } } ) { Token { Address Did Id IsNative Name Network Symbol TokenId } Currency { Symbol Id Name } Interval { VolumeBased Time { Start End } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } diff: calculate(expression: "Price_Ohlc_Close - Price_Ohlc_Open") change: calculate(expression: "round(($diff / Price_Ohlc_Open), 3) * 100") } } } ``` ### How do I stream trades with USD price, market cap and supply on every row? [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) streams MEV-filtered trades from all ten chains with `PriceInUsd` and `Supply` on each row. The chain-level `DEXTrades` subscriptions below are for per-protocol detail and transaction context. [Run query ➤](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains) ```graphql subscription { Trading { Trades { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol Network } QuoteToken { Symbol } Market { Protocol Network } } } } } ``` ### How do I subscribe to latest Solana DEX trades in real time? {#how-do-i-subscribe-to-latest-solana-dex-trades} `Solana { DEXTrades }` as a subscription returns each swap with buy/sell legs, USD price and DEX protocol. [Run Query](https://ide.bitquery.io/solana-trades-subscription_3) ```graphql subscription { Solana { DEXTrades { Block { Time Slot } Transaction { Signer Signature Index Result { Success } } Trade { Index Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Amount AmountInUSD Account { Address Owner } Currency { MintAddress Decimals Symbol Name } Price PriceInUSD } Market { MarketAddress } Sell { Amount AmountInUSD Account { Address Owner } Currency { Decimals Symbol Name } Price PriceInUSD } } } } } ``` ### How do I stream Ethereum DEX trades in real time? {#how-do-i-stream-ethereum-dex-trades-in-real-time} `EVM(network: eth) { DEXTrades }` streams decoded swaps with transaction, log and buy/sell legs. [Run Query](https://ide.bitquery.io/Ethereum-dextrades) ```graphql subscription MyQuery { EVM(network: eth) { DEXTrades { Block { Time Number } Transaction { Hash } Log { Index SmartContract Signature { Signature Name } } Trade { Sender Buy { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } Dex { SmartContract ProtocolName ProtocolVersion } Sell { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } ``` ### How do I stream BSC (PancakeSwap) DEX trades? {#how-do-i-stream-bsc-pancakeswap-dex-trades} `EVM(network: bsc).DEXTrades` for PancakeSwap and other BSC fills with block, receipt and trade detail. [Run Query](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades---Stream) ```graphql subscription { EVM(network: bsc) { DEXTrades { Block { Time Number } Receipt { ContractAddress Status } TransactionStatus { Success } Log { Signature { Name } } Trade { Dex { ProtocolName SmartContract OwnerAddress } Buy { Amount PriceInUSD Price Currency { Name Symbol SmartContract } } Sell { Amount PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } ``` ### How do I stream Uniswap v1, v2, and v3 trades on Ethereum? {#how-do-i-stream-uniswap-v1-v2-v3-trades-on-ethereum} Filter `DEXTrades` on `ProtocolName` in `uniswap_v3`, `uniswap_v2`, `uniswap_v1`. [Run Query](https://ide.bitquery.io/uniswap-all-versions-trades-stream) ```graphql subscription { EVM(network: eth) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { in: ["uniswap_v3", "uniswap_v2", "uniswap_v1"] } } } } ) { Block { Time } Trade { Dex { ProtocolName } Buy { Amount Currency { Symbol } } Sell { Amount Currency { Symbol } } } } } } ``` ### How do I stream 1-second OHLC for a specific pair (e.g. BTC/USDT)? {#how-do-i-stream-1-second-ohlc-for-a-trading-pair} `Trading.Pairs` at 1s with base and quote currency ids: OHLC, volume and market cap for every BTC/USDT market. [Run Query](https://ide.bitquery.io/Token-OHLC-Stream-1-second-Multi-Chains) ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Currency: { Id: { is: "bid:bitcoin" } } QuoteCurrency: { Id: { is: "usdt" } } } ) { Market { Name Network Address } Token { Symbol } QuoteToken { Symbol } Volume { Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Open High Low Close } } } } } ``` ### How do I find cross-chain price arbitrage for the same pair? {#how-do-i-find-cross-chain-price-arbitrage} `limitBy` on `Market_Address` returns the latest row per venue for the same currency and quote. [Run Query](https://ide.bitquery.io/Find-arbitrage-opportunity-with-same-token-across-chains) ```graphql { Trading { Pairs( where: { Currency: {Id: {is: "bid:bitcoin"}} QuoteCurrency: {Id: {is: "usdt"}} } limit: {count: 10} orderBy: {descending: Block_Time} limitBy: {by: Market_Address, count: 1} ) { Currency { Name Id } Market { Name NetworkBid Network Address } Price { IsQuotedInUsd Average { Mean } } QuoteCurrency { Id Symbol Name } QuoteToken { Symbol Name Id NetworkBid Network Did Address } Token { Name Id NetworkBid } } } } ``` - No `Duration` filter here, so rows can be at any of the ten durations; add one before comparing volumes. ### How do I stream second-level Uniswap pair OHLC (K-line)? {#how-do-i-stream-uniswap-pairs-ohlc-seconds} `Trading.Pairs` filtered on Uniswap protocols at a 1s interval. [Run Query](https://ide.bitquery.io/Stream-all-Uniswap-Seconds-OHLC-Kline) ```graphql subscription { Trading { Pairs( where: {Market: {Protocol: {in: ["uniswap_v3", "uniswap_v2"]}}, Interval: {Time: {Duration: {eq: 1}}}} ) { Currency { Name Id } Market { Name NetworkBid Network Address } Price { IsQuotedInUsd Average { Mean } } QuoteCurrency { Id Symbol Name } QuoteToken { Symbol Name Id NetworkBid Network Did Address } Token { Name Id NetworkBid } } } } ``` ### How do I stream PancakeSwap v3 liquidity adds on BSC? {#how-do-i-stream-pancakeswap-v3-liquidity-adds-on-bsc} `Mint` logs on the PancakeSwap v3 position manager contract. [Run Query](https://ide.bitquery.io/Stream---Liqiidity-add-for-all-tokens-on-PancakeSwap-v3) ```graphql subscription { EVM(network: bsc) { Events( orderBy: [ { descending: Block_Time } { descending: Transaction_Index } { descending: Log_Index } ] where: { Log: { Signature: { Name: { is: "Mint" } } } Transaction: { To: { is: "0x46A15B0b27311cedF172AB29E4f4766fbE7F4364" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` - The `since_relative` filter is there so the same text also completes when run as a query. ### How do I stream PancakeSwap v3 liquidity removals on BSC? {#how-do-i-stream-pancakeswap-v3-liquidity-removals-on-bsc} Same contract, `Burn` signature. [Run Query](https://ide.bitquery.io/Stream---Liquidity-remove-for-all-tokens-on-PancakeSwap-v3) ```graphql subscription { EVM(network: bsc) { Events( orderBy: [ { descending: Block_Time } { descending: Transaction_Index } { descending: Log_Index } ] where: { Log: { Signature: { Name: { is: "Burn" } } } Transaction: { To: { is: "0x46A15B0b27311cedF172AB29E4f4766fbE7F4364" } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ### How do I stream Raydium liquidity adds on Solana? {#how-do-i-stream-raydium-liquidity-adds-on-solana} `Solana.DEXPools` with Raydium's program and a positive base change. [Run Query](https://ide.bitquery.io/liquidity-addition-for-radium_1) ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } Base: { ChangeAmount: { gt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ``` ### How do I stream Raydium liquidity removals on Solana? {#how-do-i-stream-raydium-liquidity-removals-on-solana} Same program filter, negative `ChangeAmount` on the base side. [Run Query](https://ide.bitquery.io/liquidity-removal-for-radium_1) ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } Base: { ChangeAmount: { lt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ``` ### How do I stream Orca Whirlpool liquidity adds on Solana? {#how-do-i-stream-orca-whirlpool-liquidity-adds} `DEXPools` filtered on the Orca Whirlpool program with a positive base change. [Run Query](https://ide.bitquery.io/liquidity-addition-for-orca-whirlpool_1) ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } Base: { ChangeAmount: { gt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ``` ### How do I stream Orca Whirlpool liquidity removals on Solana? {#how-do-i-stream-orca-whirlpool-liquidity-removals} Orca's program with a negative base change. [Run Query](https://ide.bitquery.io/liquidity-removal-for-orca-whirlpool_1) ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } Base: { ChangeAmount: { lt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ``` ### How do I query Uniswap Router Burn events (liquidity removed) on Ethereum? {#how-do-i-query-uniswap-router-burn-liquidity-removed} `EVM(network: eth, dataset: realtime).Events` for `Burn` logs in transactions sent to the Uniswap V2 Router. [Run Query](https://ide.bitquery.io/uniswap-v2-liquidity-removed) ```graphql { EVM(network: eth, dataset: realtime) { Events( limit: {count: 100} where: {Transaction: {To: {is: "0x7a250d5630b4cf539739df2c5dacb4c659f2488d"}}, Log: {Signature: {Name: {in: ["Burn"]}}}} ) { Transaction { Hash From To } Block { Number } Log { Signature { Name } SmartContract } Transaction { From To Type } LogHeader { Address Index } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } Name } } } } ``` - `Transaction.Type` is only served by the `realtime` dataset; on `combined` this selection errors. ### How do I find addLiquidityETH calls for a token pair on Ethereum? {#how-do-i-find-addliquidityeth-calls-on-ethereum} `EVM(dataset: archive).Calls` with `Call.Signature.Name` `addLiquidityETH` and argument filters, scoped to one transaction here. [Run Query](https://ide.bitquery.io/addLiquidityETH_function) ```graphql query MyQuery { EVM(dataset: archive, network: eth) { Calls( where: { Transaction: { Hash: { is: "0x60ce9acd0053f20092e7871868afe5187c95ff6d7750ad65a8d4ff99a052c357" } } Call: { Signature: { Name: { is: "addLiquidityETH" } } } Arguments: { length: { eq: 6 } includes: [ { Index: { eq: 0 } Value: { Address: { is: "0x9cbc0be914e480beee4014e190fdbfc48ed5a4a8" } } } { Index: { eq: 3 } Value: { BigInteger: { ge: "1000000000000000000" } } } { Index: { eq: 5 }, Value: { BigInteger: { ge: "1690878863" } } } ] } } limit: { count: 10 } ) { Arguments { Index Name Type Path { Name Index Type } Name Value { ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { Signature { Name Signature } } } } } ``` ## Pitfalls - **No `Duration` filter means ten rows per timestamp.** Rankings and sums come out inflated. - **`Supply` is currency-level.** Every pool and every chain row of the same asset shows the same supply and market cap. - **Missing circulating supply collapses `MarketCap` into FDV.** Common for meme tokens; check `CirculatingSupply` before trusting a cap. - **Stablecoins carry `MarketCap` 0 at currency level.** - **`bid:bitcoin` supply is the on-chain wrapped supply**, not Bitcoin's 19.9 M, so its market cap is the wrapped-BTC cap. See [Bitcoin and on-chain supply](/docs/trading/crypto-price-api/supply-fields#bitcoin-bidbitcoin-and-on-chain-supply). - **Chain-wide scans at Duration 1 are heavy.** Add a `since_relative` window as in the top-tokens example. ## Related {#related-dex-launchpad-trading-apis} Use these pages for protocol-specific filters, bonding curves, pool events and full DEX examples that pair with the Trading metrics above. ### Solana - [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API): live trades, OHLCV, ATH, market cap, bonding curve, migrations to PumpSwap - [PumpSwap API](/docs/blockchain/Solana/Pumpfun/pump-swap-api): PumpSwap trades, prices, pools, historical and realtime datasets - [Raydium DEX API](/docs/blockchain/Solana/Solana-Raydium-DEX-API): Raydium swaps, pools and liquidity - [Orca DEX API](/docs/blockchain/Solana/solana-orca-dex-api): Orca / Whirlpool trades and pools - [Jupiter API](/docs/blockchain/Solana/solana-jupiter-api): Jupiter aggregator swaps, routing, limit orders - [Solana DEX trades (hub)](/docs/blockchain/Solana/solana-dextrades): `DEXTrades`, `DEXTradeByTokens` and chain-wide patterns - [gRPC: Pump.fun streams](/docs/grpc/solana/examples/pump-fun-grpc-streams): low-latency CoreCast example ### BNB Chain (BSC) - [PancakeSwap API (BSC)](/docs/blockchain/BSC/pancake-swap-api): PancakeSwap v2/v3 trades and pools - [PancakeSwap Infinity (BSC)](/docs/blockchain/BSC/bsc-pancakeswap-infinity-api): Infinity pools and hooks - [BSC DEX trades](/docs/blockchain/BSC/bsc-dextrades): general BSC DEX query patterns - [Four.meme API](/docs/blockchain/BSC/four-meme-api): Four.meme launchpad and bonding on BSC - [BSC mempool stream](/docs/blockchain/BSC/bsc-mempool-stream): pending / pre-confirmation monitoring ### Ethereum and cross-chain - [DEX API (Ethereum hub)](/docs/blockchain/Ethereum/dextrades/dex-api): Uniswap-style DEX patterns on Ethereum - [Crypto Price API introduction](/docs/trading/crypto-price-api/): Tokens, Pairs, Currencies cubes and Kafka `trading.prices` - [OHLC / K-line API](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api): candlesticks and intervals for charting - [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) --- ## Crypto OHLC Candle (K-Line) API URL: https://docs.bitquery.io/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/ OHLC candles for tokens, pairs and currencies on ten chains: ten fixed intervals from 1 second to 1 hour, 30 days of history, streamed over GraphQL or Kafka. # Crypto OHLC Candle (K-Line) API ## What it is OHLC candles (Open, High, Low, Close) come pre-aggregated on the three cubes of the Crypto Price API: `Trading.Pairs` for one pool, `Trading.Tokens` for a token on one chain, `Trading.Currencies` for an asset across chains. Each row is one candle at one of ten fixed durations from 1 second to 1 hour, with volume, moving averages and supply fields next to it. The cubes cover Ethereum, Solana, BSC, Polygon, Arbitrum, Optimism, Base, Tron, Robinhood and Arc and keep a rolling 30 days of history. For older candles, build them from raw trades with `DEXTradeByTokens` (see [the comparison](#crypto-price-api-vs-dextradebytoken)). ## How to get it {#how-do-i-get-ohlcv-data-for-a-token-using-bitquery} **Pick the cube by what one candle should mean.** `Pairs` for a single market, `Tokens` for a chain-wide token candle, `Currencies` for a cross-chain asset candle. See [Choosing the cube](#which-cube-should-i-use-for-ohlc). **Select `Price { Ohlc { Open High Low Close } }`** plus `Interval { Time { Start Duration End } }`, `Volume { Usd }` and whatever else you need. Always filter on `Interval: { Time: { Duration: { eq: } } }`. **Run it as a query, a subscription, or from Kafka.** A query returns history; the same text with `subscription` on top streams each new candle. The `trading.prices` Kafka topic carries the same candles for all three cubes; see [Multi-Chain Trading Data Streams](/docs/streams/protobuf/kafka-trading-topics-protobuf) and [Kafka concepts](/docs/streams/kafka-streaming-concepts). Most examples below add `Volume: { Usd: { gt: 5 } }`. The index already filters outliers; this is an extra guard against near-empty candles. ### Your first OHLC query {#your-first-ohlc-query} Bitcoin 1-minute candles, blended across every chain where a Bitcoin token trades. ```graphql subscription { Trading { Currencies( where: { Currency: { Id: { is: "bid:bitcoin" } }, Interval: { Time: { Duration: { eq: 60 } } }, Volume: { Usd: { gt: 5 } } } ) { Currency { Id Name Symbol } Price { Ohlc { Open High Low Close } } Volume { Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` [Run this query ➤](https://ide.bitquery.io/bitcoin-currency-price-stream) ### Supported intervals | Interval | Duration | |----------|----------| | 1 second | 1s | | 3 seconds | 3s | | 5 seconds | 5s | | 10 seconds | 10s | | 30 seconds | 30s | | 1 minute | 60s | | 5 minutes | 300s | | 15 minutes | 900s | | 30 minutes | 1800s | | 1 hour | 3600s | These ten values are the complete set. Any other value (120, 7200, 86400) is not an error: the query returns `[]` with HTTP 200 and no `errors` key. :::danger The Duration filter is effectively mandatory The cube stores all ten durations side by side. A query without `Interval: { Time: { Duration: { eq: 3600 } } }` returns one row per duration for the same timestamp, so a `sum(of: Volume_Usd)` comes back roughly ten times too high and row counts equal the sum of the ten per-duration counts. ::: ### Bucket arithmetic - `Interval.Time.End` == `Start + Duration - 1 second`. At Duration 1, `End == Start`. - Buckets are Unix-epoch aligned: `Start_epoch % Duration == 0` for every row. - **Candles are sparse.** A bucket with no trades is absent. There is no gap filling; reindex client-side if you need a contiguous series. ### Multiple timeframes in one request `Duration` accepts the full `OLAP_Integer` comparator set (`eq`, `ne`, `in`, `notIn`, `gt`, `ge`, `lt`, `le`). Pull several timeframes at once with `Interval: { Time: { Duration: { in: [60, 300, 3600] } } }` and split them client-side on `Interval.Time.Duration`. Two comparators together apply AND. :::note The 1-second series under-reports totals Aggregate volume at Duration 1 comes in below every coarser bucket, by up to a few percent depending on token and window. Coarser buckets agree with each other closely. Use 60s or larger when totals must reconcile. ::: ### Custom 4-hour, daily and weekly candles {#custom-4-hour-daily-and-weekly-candles} Durations above 3600s do not exist natively. Roll 1-hour candles up to any multiple with the `interval:` argument on `Block.Time` plus argmin/argmax selectors. The aggregation is exact. ```graphql { Trading { Tokens( where: { Token: { Address: { is: "So11111111111111111111111111111111111111112" }, Network: { is: "Solana" } } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since_relative: { days_ago: 7 } } } } limit: { count: 1000 } ) { Block { Time(interval: { in: hours, count: 4 }) } Price { Ohlc { Open(minimum: Interval_Time_Start) High(maximum: Price_Ohlc_High) Low(minimum: Price_Ohlc_Low) Close(maximum: Interval_Time_Start) } } volume: sum(of: Volume_Usd) n: count } } } ``` - `interval:` accepts `seconds`, `minutes`, `hours`, `days`, `weeks`, `months` and `years` with a `count` and an optional `offset`. 4-hour, 12-hour, daily and weekly candles all use this pattern. - `n` is the number of 1-hour rows in each bucket; 4 means the bucket is complete. - This is a query-only pattern. `interval:`, `selectWhere` and `if` do not survive conversion to a subscription. :::warning Do not add `orderBy` to a roll-up query Any `orderBy` un-groups the aggregation and you silently get the raw source rows back instead of your buckets: a 21-row daily series becomes 504 hourly rows. Sort client-side. ::: ### Volume-based aggregation {#volume-based-aggregation} `Interval.VolumeBased` and `Interval.TargetVolume` exist in the schema but carry no data: filtering on either returns zero rows with HTTP 200 and no error. Use time-based intervals and, if you need a volume floor, `Volume: { Usd: { gt: ... } }` in the `where` clause. ## How it is derived A candle is built from the trades in its bucket: Open is the first price, High and Low the extremes, Close the last. On `Pairs` those trades belong to one pool, so the candle is that market's own price. On `Tokens` the candle is the chain's index for the token: every pool where the token is base, blended by each pool's share of the token's liquidity (measured reserve where known, volume-derived estimate otherwise, after the staleness discount). On `Currencies` it is the cross-chain index over every token representation of the asset. Since 2026-10-19 the blend is liquidity-weighted; rows before that date in the 30-day history are volume-weighted and carry zero `Liquidity`. Full rules: [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). ### Which cube should I use for OHLC? {#which-cube-should-i-use-for-ohlc} **Currency** is the underlying asset (BTC, ETH, SOL). **Token** is one implementation of it on one chain (cbBTC, WBTC). **Pair** is a market between two tokens (WBTC/ETH on one pool). - **Currencies**: one candle per asset across all chains and representations. USD-quoted only. [Currency cube ➤](/docs/trading/crypto-price-api/currency/) - **Tokens**: one candle per token per chain, or a stream of candles for every token on a chain. USD-quoted only. Thin pools contribute to the blend. [Tokens cube ➤](/docs/trading/crypto-price-api/tokens/) - **Pairs**: one candle per market, quoted in USD or in the quote token. Add `Ranking: { Position: { eq: 1 } }` to get candles from the token's top market instead of a blend ([how and why](/docs/trading/crypto-price-api/pairs#most-accurate-token-price)). [Pairs cube ➤](/docs/trading/crypto-price-api/pairs/) ## Examples ### How do I stream Bitcoin OHLC across all chains? One 60-second candle per minute, blended from every chain where a Bitcoin token trades. ```graphql subscription { Trading { Currencies( where: { Currency: { Id: { is: "bid:bitcoin" } }, Interval: { Time: { Duration: { eq: 60 } } }, Volume: { Usd: { gt: 5 } } } ) { Currency { Id Name Symbol } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Open # First price in interval High # Highest price in interval Low # Lowest price in interval Close # Last price in interval } Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving } } } } } ``` [Run Live Stream ➤](https://ide.bitquery.io/OHLC-of-a-currency-on-multiple-blockchains) - Moving averages use a 5-entry window at every interval. ### How do I stream OHLC for every ETH pool on every DEX? `Pairs` filtered on the currency id returns one candle per market, so one minute yields many rows. ```graphql subscription { Trading { Pairs( where: {Currency: {Id: {is: "bid:eth"}}, Interval: {Time: {Duration: {eq: 60}}}, Volume: {Usd: {gt: 5}}} ) { Token { Symbol Network Address } QuoteToken { Symbol Network Address } Market { Name Protocol Network Address } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving } } } } } ``` [Run Live Stream ➤](https://ide.bitquery.io/All-pairs-of-ETH-currency) - Without `Price: { IsQuotedInUsd: true }` each market publishes both a USD row and a quote-token row; check `Price.IsQuotedInUsd` before charting. ### How do I stream OHLC for every token on Solana? ```graphql subscription { Trading { Tokens( where: { Token: { Network: { is: "Solana" } }, Interval: { Time: { Duration: { eq: 60 } } }, Volume: { Usd: { gt: 5 } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` [Run Live Stream ➤](https://ide.bitquery.io/Aggregated-Price-of-all-tokens-in-real-time-on-one-chain) - Swap `Network` for any of the ten chains. Token candles are USD-quoted only. ### How do I get hourly Bitcoin candles for the last 7 days? [Run Query](https://ide.bitquery.io/historical-Bitcoin-OHLC-data-for-the-last-7-days) ```graphql { Trading { Currencies( where: { Currency: { Id: { is: "bid:bitcoin" } }, Interval: { Time: { Duration: { eq: 3600 } } }, Volume: { Usd: { gt: 5 } }, Block: {Time:{ since_relative:{days_ago:7} }} }, limit: { count: 240 }, orderBy: { descending: Block_Time } ) { Currency { Id Name Symbol } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving } } } } } ``` - `since_relative` keeps the window moving. History is capped at a rolling 30 days. ### Which tokens moved most in the last 5 minutes? Ranks the top 10 tokens by 5-minute percentage change, with at least $100k of volume in the candle. ```graphql { Trading { Tokens( limit: { count: 10 } orderBy: { descendingByField: "change" } where: { Price: { IsQuotedInUsd: true } Volume: { Usd: { gt: 100000 } } Interval: { Time: { Duration: { eq: 300 } } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Currency { Symbol Id Name } Interval { Time { Start End Duration } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } diff: calculate(expression: "Price_Ohlc_Close - Price_Ohlc_Open") change: calculate(expression: "round(($diff / Price_Ohlc_Open), 3) * 100") } } } ``` [Run Query ➤](https://ide.bitquery.io/5-minute-price-change-api) - `change` is a `calculate` [expression](/docs/graphql/capabilities/expression/); it can be sorted on but not filtered on server-side. ### How do I compute a percentage price change in the query? Same idea, with the expression written in one step. ```graphql { Trading { Tokens( where: { Price: { IsQuotedInUsd: true }, Volume: { Usd: { gt: 100000 } }, Interval: { Time: { Duration: { eq: 300 } } } } ) { Token { Symbol Network } Price { Ohlc { Open Close } } # Calculate price change percentage priceChange: calculate(expression: "((Price_Ohlc_Close - Price_Ohlc_Open) / Price_Ohlc_Open) * 100") # Calculate absolute price change priceDiff: calculate(expression: "Price_Ohlc_Close - Price_Ohlc_Open") } } } ``` ### How do I stream 1-second candles for Uniswap v3? Filter `Pairs` on the market's factory address. One row per pool per second. ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } }, Price: { IsQuotedInUsd: true }, Market: { Network: { is: "Ethereum" }, Address: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } }, Volume: { Usd: { gt: 5 } } } ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency { Name Symbol Id } Token { Name Symbol Address Id NetworkBid } QuoteToken { Name Symbol Id Address NetworkBid } } } } ``` [Run Stream ➤](https://ide.bitquery.io/Uniswap-v3-DEX-tokens-1-second-price-stream-with-OHLC) ### How do I stream 1-second candles for Raydium on Solana? On Solana, filter on `Market.Program` instead of the address. ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } }, Price: { IsQuotedInUsd: true }, Market: { Network: { is: "Solana" }, Program: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } }, Volume: { Usd: { gt: 5 } } } ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency { Name Symbol Id } Token { Name Symbol Address Id NetworkBid } QuoteToken { Name Symbol Id Address NetworkBid } } } } ``` [Run Stream ➤](https://ide.bitquery.io/Raydium-Launchpad-DEX-tokens-1-second-price-stream-with-OHLC) ### How do I stream 1-second candles for PancakeSwap v3 on BSC? ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } }, Price: { IsQuotedInUsd: true }, Market: { Network: { is: "Binance Smart Chain" }, Address: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } }, Volume: { Usd: { gt: 5 } } } ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency { Name Symbol Id } Token { Name Symbol Address Id NetworkBid } QuoteToken { Name Symbol Id Address NetworkBid } } } } ``` [Run Stream ➤](https://ide.bitquery.io/PancakeSwap-v3-DEX-tokens-1-second-price-stream-with-OHLC) ### How do I get moving averages next to OHLC? `Price.Average` carries the mean plus simple, weighted and exponential moving averages on every row. ```graphql subscription { Trading { Pairs( where: { Currency: { Id: { is: "bid:eth" } }, Interval: { Time: { Duration: { eq: 60 } } }, Volume: { Usd: { gt: 5 } } } ) { Token { Symbol } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Open High Low Close } Average { WeightedSimpleMoving # Volume-weighted average Mean # Simple average } } } } } ``` - Each moving average is computed over the last 5 candles of the same duration. ### How do I compare the BTC/USDT price across chains? `limitBy` on `Market_Address` returns the latest row per market, so the spread between venues is visible in one response. ```graphql { Trading { Pairs( where: { Currency: { Id: { is: "bid:bitcoin" } }, QuoteCurrency: { Id: { is: "usdt" } }, Volume: { Usd: { gt: 5 } } }, limit: { count: 10 }, orderBy: { descending: Block_Time }, limitBy: { by: Market_Address, count: 1 } ) { Currency { Name Symbol } Market { Name Network Address } Price { Ohlc { Close } Average { Mean } } QuoteCurrency { Symbol } } } } ``` [Run Query ➤](https://ide.bitquery.io/Find-arbitrage-opportunity-with-same-token-across-chains) - This block has no `Duration` filter, so the 10 rows can mix durations; add one before summing anything. ### When should I use DEXTradeByTokens instead? {#crypto-price-api-vs-dextradebytoken} Use the Crypto Price API for live and recent candles. Use `DEXTradeByTokens` on `EVM` or `Solana` when you need candles older than 30 days, per-trade detail, or an interval the index does not store. | Feature | Crypto Price API | DEXTradeByTokens | |---------|------------------|-----------------| | **Data availability** | Real-time + rolling 30 days | Real-time + full history (`dataset: combined` / `archive`) | | **Data processing** | Pre-aggregated candles | Raw trades aggregated in your query | | **Data quality** | Filtered index price | Trade-level price | | **Intervals** | Ten fixed durations | Any `Block { Time(interval: ...) }` bucket | **Crypto Price API:** charts, dashboards, bots, mark prices for limit orders, oracles, anything that wants a normalized real-time feed. **DEXTradeByTokens:** backfills, archive ranges, custom buckets, candles built from one DEX's trades. Bucket with `Block { Time(interval: { count, in: minutes | hours | days }) }` and derive open/high/low/close from `PriceInUSD`; see [OHLC in a DEXTradeByTokens query](/docs/cubes/dextradesbyTokens/#how-do-i-get-ohlc-in-a-dextradebytokens-query). ### Can I get 1-minute historical OHLC data for a full year? {#can-i-get-1-minute-historical-ohlc-data-for-a-full-year} Not from the Crypto Price API; it keeps 30 days. With `DEXTradeByTokens`, bucket with `Time(interval: { count: 1, in: minutes })` over a 365-day `Block.Time` range. Minutes with no trades are absent and the query is heavy, so prefer hourly or daily bars, or export raw trades for a backfill. See [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/) and [DEXTradeByTokens OHLC](/docs/cubes/dextradesbyTokens/#how-do-i-get-ohlc-in-a-dextradebytokens-query). ## Pitfalls - **No `Duration` filter inflates aggregates ten-fold.** Every row exists at all ten durations. - **An unsupported duration returns `[]`, not an error.** A typo reads as "no data". - **Candles are sparse.** Missing buckets mean no trades, not missing data. - **1-second totals run a few percent low.** Reconcile on 60s or larger. - **`orderBy` on a roll-up query returns raw rows.** Sort client-side. - **Pairs publish USD and quote-token rows.** Filter `Price: { IsQuotedInUsd: true }` or you may chart WBTC in SOL. Tokens and Currencies are USD only. - **Volume-based intervals return zero rows.** Use time durations. - **Rows before 2026-10-19 are volume-weighted.** `Liquidity` is zero on them and `Ranking.Weight` follows volume share, not liquidity share. - **`interval:`, `selectWhere` and `if` are query-only.** They do not survive conversion to a subscription. ## Related - [Crypto Price API introduction](/docs/trading/crypto-price-api/) - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) - [Pairs](/docs/trading/crypto-price-api/pairs/), [Tokens](/docs/trading/crypto-price-api/tokens/), [Currencies](/docs/trading/crypto-price-api/currency/) - [Quick Start Examples](/docs/trading/crypto-price-api/examples/) - [Kafka: Multi-Chain Trading Data Streams](/docs/streams/protobuf/kafka-trading-topics-protobuf) (topic `trading.prices`, [protobuf schema](https://github.com/bitquery/streaming_protobuf/tree/main/market), [Python](https://pypi.org/project/bitquery-pb2-kafka-package/) and [npm](https://www.npmjs.com/package/bitquery-protobuf-schema) packages) - [TradingView SDK on npm](https://www.npmjs.com/package/@bitquery/tradingview-sdk) - [DEXTradeByTokens cube](/docs/cubes/dextradesbyTokens/) ### OHLCV and price data: quick answers {#ohlcv-and-price-data-quick-answers} | Question | Where to read / run | |----------|---------------------| | How do I get OHLCV data for a token using Bitquery? | **Last 30 days:** [How to get it](#how-do-i-get-ohlcv-data-for-a-token-using-bitquery) ; **older history:** [DEXTradeByTokens OHLC](/docs/cubes/dextradesbyTokens/#how-do-i-get-ohlc-in-a-dextradebytokens-query) | | How do I get OHLC in a DEXTradeByTokens query? | [DEXTradeByTokens OHLC](/docs/cubes/dextradesbyTokens/#how-do-i-get-ohlc-in-a-dextradebytokens-query) | | How do I get historical OHLCV for a Solana token? | [Tokens cube](/docs/trading/crypto-price-api/tokens/) · [Historical OHLCV on Solana](/docs/blockchain/Solana/solana-dextrades/#how-do-i-get-historical-ohlcv-for-a-solana-token) · [Solana OHLC API](/docs/blockchain/Solana/solana-dextrades/#solana-ohlc-api) | | How do I get the current price of a token? | [Pairs + rank 1 (top market)](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) · [Quick start](/docs/trading/crypto-price-api/#quick-start) · [Examples](/docs/trading/crypto-price-api/examples/) | | Which cube gives the most accurate price for one token? | [Pairs with `Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) | | How do I get 1-minute OHLC candles for a DEX pair? | [Your first OHLC query](#your-first-ohlc-query) (`Duration: { eq: 60 }`) · [Pairs cube](/docs/trading/crypto-price-api/pairs/) | | How do I get the all-time high (ATH) price of a token? | [Solana ATH example](/docs/blockchain/Solana/solana-dextrades/#get-ath-market-cap-of-tokens) | | Is there an API to get token price in USD on Solana? | [Pairs + rank 1](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) · [Latest USD (Solana DEX trades)](/docs/blockchain/Solana/solana-dextrades/#latest-usd-price-of-a-token) | | How do I use DEXTradeByTokens vs DEXTrades for OHLCV? | [OHLCV: which cube?](/docs/cubes/dextradesbyTokens/#how-do-i-use-dextradebytokens-vs-dextrades-for-ohlcv) · [DEXTrades cube](/docs/cubes/dextrades/) | --- ## Crypto Price API: Real-Time Token Prices, OHLC and Market Cap URL: https://docs.bitquery.io/docs/trading/crypto-price-api/ Crypto price API for any token on ten chains: live and 30-day USD prices, OHLC from one second, market cap and supply via GraphQL, WebSocket and Kafka. # Crypto Price API: Real-Time Token Prices, OHLC and Market Cap ## What it is The Crypto Price API returns the price of any token that trades on-chain, real-time and for the last 30 days, in USD or against any quote token. Every row carries OHLC for intervals from one second up, mean and moving-average prices, volume, liquidity, market cap and supply, over GraphQL queries, WebSocket subscriptions and Kafka. Prices are built from DEX trades with outlier filtering, and a cross-chain view aggregates the same asset across networks, so `bid:bitcoin` returns one Bitcoin price. Every query below runs as written in the [Bitquery IDE](https://ide.bitquery.io). :::tip Real-time + last ~30 days only `Trading.Tokens`, `Trading.Currencies` and `Trading.Pairs` hold real-time data and a rolling ~30 days. For OHLC older than that, use chain-level [`DEXTradeByTokens`](/docs/cubes/dextradesbyTokens) or the [Solana historical page](/docs/blockchain/Solana/historical-aggregate-data/). See the [Trading Data Overview](/docs/trading/trading-data-overview) for the side-by-side comparison, and the [Crypto Price API](https://bitquery.io/products/crypto-price-api) product page for chains and plans. ::: ## How to get it - **GraphQL and WebSocket:** the [streaming endpoint](https://ide.bitquery.io/?endpoint=https://streaming.bitquery.io/graphql). Queries and subscriptions use the same cubes; see [What does not survive streaming](/docs/subscriptions/what-does-not-survive-streaming/) for the Trading-cube exceptions (`selectWhere`, `if`, most statistical metrics and `interval:`). - **Kafka:** the `trading.prices` topic in Protobuf, [schema](https://github.com/bitquery/streaming_protobuf/tree/main/market). - **SDKs:** [NPM package](https://www.npmjs.com/package/bitquery-crypto-price) and the [TradingView SDK](https://www.npmjs.com/package/@bitquery/tradingview-sdk). Expressions are supported in this API. ### Networks - Arbitrum - Base - Matic - Ethereum - Solana - Binance Smart Chain - Tron - Optimism - Robinhood - Arc :::tip Faster queries: filter with `NetworkBid` instead of `Network` When you scope **Tokens**, **Pairs**, or related **Trading** queries by chain, prefer **`NetworkBid`** over the **`Network`** field in your `where` clause for lower latency. Use the same **`bid:`** convention as **`Token.Id`**. | Network Name | `NetworkBid` Value | | ------------------- | ------------------ | | Solana | `bid:solana` | | Ethereum | `bid:eth` | | Binance Smart Chain | `bid:bsc` | | Base | `bid:base` | | Arbitrum | `bid:arbitrum` | | Matic (Polygon) | `bid:matic` | | Tron | `bid:tron` | | Optimism | `bid:optimism` | | Robinhood | `bid:robinhood` | | Arc | `bid:arc` | ::: ### Quick start {#quick-start} :::tip Pricing one specific token? Start with Pairs + rank 1 The stream below is a **firehose** of every token on every chain, and the `Tokens` cube is the right choice for it. For the price of **one token**, query the [**Pairs** cube with `Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). It returns the price from the token's **leading pool** rather than the blend across all of its pools. ::: [Run Stream >](https://ide.bitquery.io/1-second-crypto-price-stream) > Note: A `Volume: {Usd: {gt: 5}}` filter is applied to remove extreme outliers; the price stream already pre-filters outliers—this is an additional check. ```graphql subscription { Trading { Tokens( where: { Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 5 } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` ### Cubes The API has three cubes. Each row is one asset over one interval. - **`Tokens`:** one blended price per token per chain, across every pool where the token is base. Use it for chain-wide streams and per-chain aggregates. [Tokens cube](/docs/trading/crypto-price-api/tokens). - **`Currencies`:** one price per asset across chains. cbBTC, WBTC and other Bitcoin representations are grouped under `bid:bitcoin`. Use it for a chain-agnostic number. [Currencies cube](/docs/trading/crypto-price-api/currency). - **`Pairs`:** price and volume for one token against one quote token on one market, such as SOL/USDC on Raydium. Use it for market-level data and, with `Ranking: { Position: { eq: 1 } }`, for a specific token's price. [Pairs cube](/docs/trading/crypto-price-api/pairs). Choosing between them: - **A specific token's price:** `Pairs` with `Ranking: { Position: { eq: 1 } }`. The `Tokens` price is a liquidity-weighted blend of every pool, and on tokens with fragmented liquidity that blend can sit away from the leading pool's price. - **Every token on a chain, or aggregate volume across a token's pools:** `Tokens`. - **Pair-level data, a specific DEX, or spreads across venues:** `Pairs`. - **One global number for BTC, ETH or another multi-chain asset:** `Currencies`. ### Kafka topic: `trading.prices` {#kafka-topic-for-crypto-price-stream-tradingprices} The topic delivers pre-aggregated price data for tokens, currencies and pairs across all supported chains. One message type combines the three cubes above. The [python package](https://pypi.org/project/bitquery-pb2-kafka-package/) and [npm package](https://www.npmjs.com/package/bitquery-protobuf-schema) carry the current schema. Each message contains: - **Price metrics:** OHLC, mean price, SMA, WMA and EMA in USD. - **Volume:** base, quote, and base in USD. - **Supply:** currency-level MarketCap, FullyDilutedValuationUsd, CirculatingSupply, TotalSupply and MaxSupply ([Supply fields](/docs/trading/crypto-price-api/supply-fields)). - **Liquidity, RankingDetail and LeadingPool** ([Liquidity fields](/docs/trading/crypto-price-api/liquidity-fields#kafka-tradingprices)). - **Pool price** on pairs: the liquidity pool's own price next to the traded one ([PoolPrice fields](/docs/trading/crypto-price-api/pool-price-fields#kafka-tradingprices)). - **Fixed intervals:** 1s, 3s, 5s, 10s and up. - **Clean feed:** low-quality and outlier trades are filtered per the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). > **Note on `"Quotes"`**: > The `"Quotes": [...]` section in the Kafka stream shows how much was traded in the native token (e.g., SOL) and how the USD value was derived. > All following price entries (`MeanPrice`, `SMA`, `OHLC`, etc.) are already expressed in USD and ready for direct use in charting, bots, or analytics. ## How it is derived 1. **Ingestion.** DEX trades are collected and parsed on every supported chain. 2. **Filtering.** Trades with zero amount or an amount below decimal precision are dropped. Outliers are rejected per pool. 3. **Blending.** Each pool's price is weighted by its liquidity (measured reserve where known, volume-derived estimate otherwise, times a staleness discount) to give one token price, and token prices are blended the same way into a currency price. Details in [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). 4. **Aggregation.** Rows are cut by fixed time intervals and OHLC, moving averages and other statistics are pre-calculated. 5. **Distribution.** Rows go out over GraphQL queries, subscriptions and Kafka. ### Intervals {#understanding-intervals} Intervals are fixed; arbitrary values are not supported, unlike the DEX trades cubes. Volume-based intervals (`Interval.VolumeBased` / `Interval.TargetVolume`) exist in the schema but carry no rows. ### Supported time intervals {#supported-time-intervals} Durations in seconds, for queries and streams: `1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600` Nothing above 3600 exists. Build 4-hour, daily and weekly candles client side from 3600-second rows ([how](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/#custom-4-hour-daily-and-weekly-candles)). ### Moving averages SMA, WMA and EMA use a **window of 5 entries** at every interval: five 1-second rows on the 1-second interval, five 1-hour rows on the 3600-second interval. This keeps moving averages comparable across intervals. ### Retention A rolling ~30 days is queryable. Older history comes from chain-level [`DEXTradeByTokens`](/docs/trading/trading-data-overview/). ## Fields {#key-features-of-these-apis} Groups on every `Tokens`, `Currencies` and `Pairs` row: | Group | Fields | Meaning | | --- | --- | --- | | `Price.Ohlc` | `Open High Low Close` | Candle for the interval, in USD or in the quote token (`Price.IsQuotedInUsd`). | | `Price.Average` | `Mean SimpleMoving WeightedSimpleMoving ExponentialMoving Estimate` | Mean price and 5-entry moving averages. `Estimate` is the price MarketCap and FDV are built from. | | `Volume` | `Base Quote Usd BaseAttributedToUsd` | `Quote` is quote-token units, not USD. Use `Usd` for USD totals. | | `Supply` | `MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply` | [Supply fields](/docs/trading/crypto-price-api/supply-fields). | | `Liquidity` | `Usd Source RealShare …` | Reserve behind the price. [Liquidity fields](/docs/trading/crypto-price-api/liquidity-fields). | | `PoolPrice` | `Price Ohlc Average Source UpdatedAt` | `Pairs` only. The liquidity pool's own price from its curve. [PoolPrice fields](/docs/trading/crypto-price-api/pool-price-fields). | | `Interval.Time` | `Start End Duration` | The interval the row covers. | | `Block` | `Date Time Timestamp` | Block time of the row. | `Ranking { Position Weight }` and `RankingDetail { Verdict StaleMultiplier }` are on `Tokens` and `Pairs`; `LeadingPool` is on `Tokens` only. Responses are GraphQL JSON, or Protobuf on Kafka. ## Examples Crypto Price API stream with pre-calculated OHLC in the response Rows carry pre-calculated OHLC, so they can feed a chart without further work. Most queries become a stream by changing `query` to `subscription`; see the Trading-cube exceptions linked above. ### What is the Bitcoin price across all chains? The `Currencies` cube takes amounts and prices from every chain that trades BTC and its wrapped or bridged versions and returns one aggregated view. > Note: We include `Volume: {Usd: {gt: 5}}` to further remove extreme outliers. The stream already pre-filters outliers, so this is an additional check. ```graphql { Trading { Currencies( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Currency: { Id: { is: "bid:bitcoin" } } Volume: { Usd: { gt: 5 } } } ) { Volume { Usd Quote BaseAttributedToUsd Base } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } Price { Ohlc { Open Low High Close } IsQuotedInUsd Average { Mean WeightedSimpleMoving SimpleMoving ExponentialMoving } } Currency { Symbol Name Id } Block { Timestamp } Interval { Time { Duration Start End } } } } } ``` - `Currency.Id` is `bid:bitcoin`; `CirculatingSupply` here is the wrapped supply on the covered chains, not BTC's own supply. ### What is one token's price on one chain? `Tokens` filtered by `Address` and `Network`. The price is blended across **all pools** where the token is base; for a single token the [rank-1 Pairs query](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) prices it from its leading pool instead. > Same outlier filter as above. ```graphql { Trading { Tokens( where: { Token: { Address: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } Network: { is: "Solana" } } Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 5 } } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Token { Address Id IsNative Name Network Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` ### How do I stream every token price on Solana? Drop the `Address` filter and keep `Network`. > Same outlier filter as above. ```graphql subscription { Trading { Tokens( where: { Token: { Network: { is: "Solana" } } Volume: { Usd: { gt: 5 } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` ### How do I stream a pair on one market? `Pairs` gives price, volume and market-level data between a base token and a quote token. How base and quote are chosen is in [Breaking Down Price Streams in Detail](/docs/trading/crypto-price-api/in-depth). > **Recommended for single-token prices:** add `Ranking: { Position: { eq: 1 } }` to a Pairs query to get a token's price from its **leading pool**, the one with the largest liquidity-weighted share. See [Getting the Most Accurate Token Price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). > **Tip**: Use `TokenId` instead of `Token.Address` to fetch all variants of the same token (e.g., ETH, WETH, bridged ETH) across multiple chains. > Same outlier filter as above. ```graphql subscription { Trading { Pairs( where: { Market: { Network: { is: "Base" } } QuoteToken: { Address: { is: "0x4200000000000000000000000000000000000006" } } Token: { Address: { is: "0x940181a94a35a4569e4529a3cdfb74e38fd98631" } } Volume: { Usd: { gt: 5 } } } ) { Currency { Symbol Name Id } Market { Protocol Program Network Name Address } Token { Address Id Name Symbol TokenId } Volume { Usd Base Quote BaseAttributedToUsd } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } QuoteToken { TokenId Name Id Address Symbol } QuoteCurrency { Id } Price { Ohlc { Open Low High Close } Average { WeightedSimpleMoving SimpleMoving Mean ExponentialMoving } } } } } ``` ## Related - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm): trade filtering and the liquidity-weighted blend. - [OHLC / K-line API](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/), [Market cap API](/docs/trading/crypto-price-api/crypto-marketcap-api), [Examples](/docs/trading/crypto-price-api/examples). - [Solana Token Price API](/docs/blockchain/Solana/solana-token-price-api) for Solana-only examples. ### Crypto Price API for TradingView Feed the stream to a custom datafeed object in the TradingView charting library and charts update in real time. A tutorial is [here](/docs/usecases/tradingview-subscription-realtime/getting-started/); the ready-to-chart SDK is [here](https://www.npmjs.com/package/@bitquery/tradingview-sdk): copy the advanced charting library into the right folder, add a Bitquery access token, and it runs. ### Video tutorial --- ## Crypto Profit and Loss Calculator URL: https://docs.bitquery.io/docs/usecases/p-l-product/overview/ Build a JavaScript crypto PnL calculator with Bitquery DEX trades for cost basis, proceeds, realized gains, and reporting. # Overview Profit and Loss calculation in crypto is not easy to build. However, it is an important metric while evaluating the financial performance of an asset. In this tutorial, we will see how to build a simple profit and loss calculator in Javascript using Bitquery's [DEXTrades API](/docs/blockchain/Ethereum/dextrades/dex-api/) ## Realized PnL We will be calculating realised profit and loss. Realized PnL is calculated after traders have sold their holdings of a token. Only the executed price of the orders is taken into account in realized PnL. For this purpose, we will the weighted average of the buy price(WABP) in USD. This is the formula we will be using: ``` WABP = sum(buyAmount*buyPriceInUSD)/sum(buyAmount) pnl = sum(sellAmount*(sellPriceInUSD-WABP)) ``` ### Example Scenario: An account buys and sells a token as follows: 1. **Buy Transactions**: - Buys 10 tokens at $5 each. - Buys 20 tokens at $6 each. 2. **Sell Transaction**: - Sells 15 tokens at $7 each. #### Step 1: Calculate the Weighted Average Buy Price (WABP) Using the formula: WABP = (Sum of each buy amount multiplied by its buy price in USD) divided by (Sum of all buy amounts). ``` WABP = ( (10 * 5) + (20 * 6) ) / (10 + 20) WABP = (50 + 120) / 30 WABP = 170 / 30 WABP = 5.67 ``` So, the weighted average buy price (WABP) is $5.67. #### Step 2: Calculate Realized PnL Using the formula: For the sell of 15 tokens at $7 each: ``` Realized PnL = Sum of each sell amount multiplied by (sell price in USD minus WABP). Realized PnL = 15 * (7 - 5.67) Realized PnL = 15 * 1.33 Realized PnL = 19.95 ``` ### Result: The realized PnL for this transaction is $19.95. Click [here](/docs/usecases/p-l-product/pnl) to get started with the project. ## Complete Video Tutorial --- ## Crypto Token Price API URL: https://docs.bitquery.io/docs/trading/crypto-price-api/tokens/ One price per token per chain, blended across its pools, with volume, supply and liquidity fields and a live subscription. # Tokens Cube ## What it is The Tokens cube gives one row per token per chain per interval. The price is a **liquidity-weighted blend of every pool** where the token is the base asset, so it answers "what is this token worth on this chain" with a single number. Use it for a chain-wide number or a firehose of every token on a chain. It does not say which quote token or pool a price came from; that lives on [Pairs](/docs/trading/crypto-price-api/pairs). :::tip Looking for one token's price? Use the Pairs cube with rank 1 For a **specific token**, especially one whose liquidity is spread across many pools, a pool with a large but stale or estimated reserve can outweigh the pool where the trading happens and pull the blend. Query the [Pairs cube with `Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) to get the quote from its top market. ::: ## How to get it Query or subscribe to `Trading.Tokens`. Filters that matter: - **Token**: `Token: { Address: ..., Network: ... }` or `Token: { Id: { is: "bid::
" } }`. A bare address in `Token.Id` returns 0 rows. - **Interval**: `Interval: { Time: { Duration: { eq: 60 } } }`. Durations are 1, 3, 5, 10, 30, 60, 300, 900, 1800 and 3600 seconds. - **Chain**: `Token: { Network: { is: "Solana" } }` for every token on one chain. The subscription below streams every token's 1-minute bar on every chain. For a query that returns tokens with volume and average price over the last 24h, see [Aggregated Token Data](https://ide.bitquery.io/aggregated-data) or the [examples](/docs/trading/crypto-price-api/examples#aggregated-token-data-volume--price-last-24h). ```graphql subscription { Trading { Tokens(where: { Interval: { Time: { Duration: { eq: 60 } } } }) { Token { Address Id IsNative Name Network Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base # Volume of the token itself Quote # Volume of all tokens it traded against Usd # Combined USD volume across all trades } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd # Whether price values are in USD (true/false) Ohlc { Open High Low Close } Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving } } Currency { Name Symbol Id } } } } ``` ## How it is derived The index takes every pool where the token is the base asset, prices each pool from its latest trade, and blends them. Each pool's weight is its share of the token's liquidity after the staleness discount: `Liquidity.Usd x RankingDetail.StaleMultiplier`, normalised over the token's pools. Details in [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm#how-token-prices-are-determined) and [how Position and Weight behave](/docs/trading/crypto-price-api/pairs#ranking-how-position-and-weight-behave). Volume on the row is the sum across all pools in the interval. OHLC and the averages use only trades with known USD values. **Where the blend can mislead.** Weight follows liquidity, not trading. A pool whose reserve is large but stale, or only estimated from volume (`Liquidity.Source: "volume"`), can outweigh the pool where the token actually trades. Check `Ranking.Weight` on the [Pairs cube](/docs/trading/crypto-price-api/pairs#most-accurate-token-price): a top-market weight near 1 means the blend is effectively one pool and this cube's price is equivalent; a low weight means you should price the token from its [rank-1 market](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) instead. Since 2026-10-19 the blend is liquidity-weighted. Rows before that date in the 30-day history are volume-weighted and carry `Liquidity` fields of `0`. ## Fields {#field-notes} | Field | Type | Meaning | | --- | --- | --- | | `Token { Address Id Symbol Name Network NetworkBid IsNative TokenId Did }` | String / Boolean | The token. See [Identity fields](#identity-fields). | | `Currency { Id Name Symbol }` | String | The cross-chain currency the token belongs to, for example `bid:bitcoin` for WBTC. | | `Block { Date Time Timestamp }` | String / DateTime / String | Time of the last update in the interval. | | `Interval { Time { Start End Duration } }` | DateTime / DateTime / Int | The bar. `Duration` in seconds. | | `Price.Ohlc { Open High Low Close }` | Float | OHLC of the blended price for the interval. | | `Price.Average { Estimate Mean SimpleMoving WeightedSimpleMoving ExponentialMoving }` | Float | Averages over the interval and a 5-entry moving window. | | `Price.IsQuotedInUsd` | Boolean | Constant `true` on this cube. | | `Volume.Base` | Float | Amount of the token traded across all its pairs. | | `Volume.Quote` | Float | Sum of quote-token amounts across all pairs. Not USD; use `Volume.Usd`. | | `Volume.Usd` | Float | Volume in USD. | | `Volume.BaseAttributedToUsd` | Float | Part of `Volume.Base` the index could attribute to a USD value. | | `Liquidity { Usd Source RealShare ... }` | Float / String | Liquidity summed over the token's pools. See below. | | `Ranking { Position Weight }` | Int / Float | The token's rank and weight as a part of its currency. | | `RankingDetail { Verdict StaleMultiplier }` | String / Float | Why it got that rank. | | `LeadingPool { MarketId PoolAddress QuoteTokenId }` | String | The Position-1 pool that sets the token's price. | | `Supply { CirculatingSupply TotalSupply MaxSupply MarketCap FullyDilutedValuationUsd }` | Float | Currency-level figures, aggregated across chains; price and volume on the row stay chain-specific. See [Supply fields](/docs/trading/crypto-price-api/supply-fields). | ### `Price.Average.Estimate`: the valuation price `Estimate` is the price the supply valuations are built from: `Supply.FullyDilutedValuationUsd` is `TotalSupply x Estimate`, and `MarketCap` is `CirculatingSupply x Estimate`. If you are reconciling a market cap, use `Estimate`, not `Mean` and not `Ohlc.Close`. ### `Volume.BaseAttributedToUsd` The portion of base-token volume the index could attribute to a USD value. It is always less than or equal to `Volume.Base`; how often the two are equal varies by chain. Use it when you need volume you can trust a USD figure for. ### `Volume.Quote` The Tokens cube does not show which token was the quote in each trade. `Volume.Quote` sums quote-token amounts across all pairs regardless of quote token, so it is not a USD figure. For pair-level granularity use [Pairs](/docs/trading/crypto-price-api/pairs). ### `Ranking` `Ranking.Position` and `Ranking.Weight` are present on `Tokens` as well as `Pairs`. See [how Position and Weight behave](/docs/trading/crypto-price-api/pairs#ranking-how-position-and-weight-behave). ### `Liquidity`, `RankingDetail` and `LeadingPool` `Liquidity.Usd` on a `Tokens` row is the pool's balance of the row's quote token, valued in USD, **summed over the token's pools**, including pools that did not trade in the interval. `RealShare` says how much of it is measured rather than estimated. `LeadingPool` names the Position-1 pool that sets the price. `Liquidity.UpdatedAt` is `1970-01-01` at token level and the per-pool reserve fields are `0`. See [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields). ### Identity fields {#identity-fields} | Field | Notes | | --- | --- | | `Token.Id` | Chain-qualified: `bid::
`. **A bare address returns 0 rows silently**; use `Token.Address` for a raw address | | `Token.Address` | The raw contract address. Empty for native assets | | `Token.NetworkBid` | Populated: the chain bid, e.g. `bid:solana` | | `Token.Did` | A **chain-level** DID, empty on essentially every row. Not a per-token identifier | | `Token.Decimals` | **Does not exist** on this cube | ## Pitfalls - **`Price.IsQuotedInUsd` is a constant `true` here.** Filtering on `false` returns nothing. - **`(Token.Id, Interval.Time.Start)` is not a unique key.** A small share of mints return two rows for the same token and bar. The duplicates are identical on identity and ranking and differ only in mutable metadata, typically one row has an empty `Token.Symbol` while the other has arrived: a metadata-arrival split on freshly launched tokens. - **Aggregate by `Token.Id`**, not by treating one row as one token. Do not build a natural key from metadata columns: `Symbol` can change. ## Related - [Pairs cube](/docs/trading/crypto-price-api/pairs) - [Currencies cube](/docs/trading/crypto-price-api/currency) - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) - [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields) - [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) - [Examples](/docs/trading/crypto-price-api/examples) --- ## Crypto Trades API — Real-Time DEX Trade Streams Across URL: https://docs.bitquery.io/docs/trading/crypto-trades-api/trades-api/ Crypto Trades API — Real-Time DEX Trade Streams Across via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. # Crypto Trades API — Real-Time DEX Trade Streams :::tip Which trade API should you use? This page covers **`Trading.Trades`** — the curated, multi-chain trade feed for **real-time and the last ~30 days**. For older / historical data (anything beyond ~30 days) drop down to chain-level [`DEXTrades`](/docs/cubes/dextrades) or [`DEXTradeByTokens`](/docs/cubes/dextradesbyTokens). See the [**Trading Data Overview**](/docs/trading/trading-data-overview) for a full side-by-side comparison. ::: > **Bitquery Crypto Trades API** streams **individual swap-level DEX trades** in **real time** across **Solana**, **Ethereum**, **BSC**, **Base**, **Arbitrum**, and **Polygon**. Each row includes **price**, **USD amounts**, **market cap**, **FDV**, **supply**, **trader address**, and **transaction metadata** via **GraphQL subscriptions**. The **Trades** cube streams individual **swap-level** rows from the **Trading** API: each event includes **side**, **amounts** (base, quote, USD), **price**, **pair** (market, tokens, currencies), **trader**, **transaction** metadata, and a **supply** snapshot (**MarketCap**, **FDV**, circulating/total/max supply) for the token context on that row. For **aggregated** token metrics across all pairs, use the **[Tokens cube](/docs/trading/crypto-price-api/tokens)**. For **pair-level** OHLC and volume intervals, use the **[Pairs cube](/docs/trading/crypto-price-api/pairs)**. Supply field meanings are documented under **[Supply fields](/docs/trading/crypto-price-api/supply-fields)**. ## Video Tutorial | How to Track DEX Trades & Trader PnL Across All Blockchain networks in a single API ### Key points - **Subscriptions**: These examples use **`subscription`** for real-time streams; you can often run the same selection as a **`query`** with an added time window on **`Block`** / **`Interval`** where supported. - **Networks**: Filter by chain with **`Pair.Market.Network`** to filter trades on a particular network. For **faster queries**, use **`Pair.Market.NetworkBid`** as showcased in the tip below. - **Token filter**: Use **`Pair.Token.Id`** with the full id (e.g. **`bid:solana:`**, **`bid:eth:`**) per your dataset conventions. - **Trader filter**: Use **`Trader.Address`** for the wallet executing the trade. - **Aggregations**: Examples at the end of this page use **`query`** with **`limit`**, **`orderBy`**, **`sum`**, **`average`**, **`count`**, **`calculate`**, **`limitBy`**, and **`distinct`** for volume, token, DEX, time-bucket, and fee analytics on **`Trades`**. - **USD vs quote**: **`PriceInUsd`** and **`AmountsInUsd`** are in USD where indexed; see **[Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm)** for how amounts and prices are derived. More patterns: **[Crypto Price API examples](/docs/trading/crypto-price-api/examples)**. :::tip Faster queries: filter with `NetworkBid` instead of `Network` On **`Trading.Trades`**, you can scope by chain with **`Pair.Market.NetworkBid`** instead of **`Pair.Market.Network`** for faster results. se the same **`bid:`** convention as **`Pair.Token.Id`**. | Network Name | `NetworkBid` Value | | ---------------------- | ------------------------- | | Solana | `bid:solana` | | Ethereum | `bid:eth` | | Binance Smart Chain | `bid:bsc` | | Base | `bid:base` | | Arbitrum | `bid:arbitrum` | | Matic (Polygon) | `bid:matic` | | Tron | `bid:tron` | | Optimism | `bid:optimism` | | Robinhood | `bid:robinhood` | | Arc | `bid:arc` | The same **`NetworkBid`** pattern applies on the **[Crypto Price API](/docs/trading/crypto-price-api/)** for **`Token.NetworkBid`** and **`Market.NetworkBid`** on **Tokens** and **Pairs**. ::: ## Before you aggregate: three things about a Trades row These affect every wallet-analytics or volume figure you compute from this cube. ### One row is a swap *leg*, not a transaction A single on-chain transaction can produce several rows. Unlike `DEXTradeByTokens`, rows are not mirrored per token, and aggregator roll-ups are not included. Count transactions with `count(distinct: TransactionHeader_Hash)`, not `count`. ### Trades of a transaction in execution order (`TradeIndex`) `TradeIndex` is the trade's sequence number **inside its transaction**, 0-based, in the order the chain executed them — from the call, log and event index on EVM, the instruction index on Solana. `TransactionHeader.Index` is the transaction's position in the block and is the same on every leg of the transaction. Two things to know before you rely on it: - **Gaps are intentional.** The counter runs over every trade of the transaction, so a leg the parser later drops leaves a gap rather than renumbering the rest. A transaction whose first row has `TradeIndex: 1` is not missing data. - On the `trading.trades` Kafka topic it is `Trade.Transaction.TradeIndex` (`TradeTransaction` field 4 in `market/transaction.proto`). Latest multi-leg Solana transactions, legs in execution order inside each transaction: [Run query ➤](https://ide.bitquery.io/Trades-in-execution-order-TradeIndex) ```graphql query TradesInExecutionOrderTradeIndex { Trading { Trades( limit: {count: 30} orderBy: [{descending: Block_Time}, {ascending: TradeIndex}] where: { Block: {Time: {since_relative: {minutes_ago: 2}}} Pair: {Market: {Network: {is: "Solana"}}} TradeIndex: {ge: 1} } ) { Block { Time } TradeIndex TransactionHeader { Index Hash } Pair { Market { Name } Token { Symbol } QuoteToken { Symbol } } Side Price PriceInUsd Amounts { Base Quote } } } } ``` To read one transaction, filter `TransactionHeader: { Hash: { is: "…" } }` with a `Block.Time` window around it and keep `orderBy: { ascending: TradeIndex }`. ### Use `AmountsInUsd.Quote` for USD, not `.Base` `AmountsInUsd.Base` is `Amounts.Base x PriceInUsd`, and **`PriceInUsd` is a smoothed reference price, not the executed price**. On fast-moving tokens the two USD legs diverge — on Solana, roughly a quarter of rows differ by more than 1%, with outliers of several orders of magnitude during sharp moves. `AmountsInUsd.Quote` is the sound leg: the implied quote-token USD price is consistent to within a rounding error across trades in the same second. ```graphql # prefer this for USD volume and PnL sum(of: AmountsInUsd_Quote, if: { Side: { is: "Buy" } }) ``` :::danger The cube emits some exact duplicate rows A small but material share of rows — on the order of one percent on Solana — are **exact duplicates of the same swap leg**, inflating USD volume by a similar fraction. No field distinguishes the copies; the behaviour is persistent, not a transient glitch. Deduplicate on `(TransactionHeader.Hash, Trader.Address, Side, Amounts.Base)` before reporting exact trade counts or volumes. The rate is much higher on Matic, where Polymarket outcome tokens all share one ERC-1155 address, so distinct markets collapse onto the same token identity. ::: ### Field meanings shift between chains | Field | Solana | EVM | | --- | --- | --- | | `Pair.Pool.Address` | the pool | the pool | | `Pair.Market.Address` | the pool | the protocol **factory** | | `Pair.Market.Program` | the DEX program | the pool | Only `Pool.Address` and `Market.Id` mean the same thing on every chain. `TransactionHeader.Sender` and `.To` are leg-level and their meanings differ between Solana and EVM; on Tron, `Fee`, `FeePayer` and `To` are absent entirely. `Token.Did` and `Token.TokenId` are empty on every row, and `Token.Address` is empty on native assets — group by `Token.Id`. ### Scope and window `Trading.Trades` is **realtime only** — `dataset: archive` and `combined` are rejected — and holds roughly the last 30 days. Both `since` and `till` bounds are inclusive. It is also **not DEX-only**: it carries Seaport NFT fills and Polymarket activity, so filter by `Pair.Market.ProtocolFamily` if you mean DEX swaps specifically. ## How Do I Stream New DEX Trades Across All Chains in Real Time? > *Real-time* **multi-chain DEX trade stream** — subscribe to every new swap on **Solana**, **Ethereum**, **BSC**, **Base**, **Arbitrum**, and **Polygon** in a single **GraphQL subscription**. Each event returns **price**, **USD amounts**, **market cap**, **supply**, **trader wallet**, and **transaction hash** the moment a trade is confirmed on-chain. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/all-chains-New-Trades-Stream---Solana-eth-bsc-base--arbitrum-matic_2#). ```graphql subscription { Trading { Trades { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## How Do I Get All DEX Trades on Solana With Price, Market Cap, and Supply? > Stream **all Solana DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Network: Solana`** to capture every swap across **Raydium**, **Orca**, **Jupiter**, **PumpSwap**, and other Solana DEXs in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Solana-with-Price-Marketcap-supply). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Solana" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## How Do I Stream Trades for a Specific Token on Solana? > Filter the **Solana trade stream** to a **single token** by its **mint address** using **`Pair.Token.Id`** — get real-time **swap events**, **USD price**, **market cap**, **supply**, and **trader wallet** for any **SPL token** traded on Raydium, Orca, Jupiter, pumpfun, or PumpSwap. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/Trades-of-a-specific-token-on-Solana). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } } Token: { Id: { is: "bid:solana:4YiLHDR4B4pE4R5GUMA8HG8YunyeLwcobtEtvwMupump" } } } } ) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## How Do I Get All Trades for a Specific Ethereum Token With Price, Market Cap, and Supply? > Stream **Ethereum ERC-20 token trades** in real time — filter by **contract address** with **`Pair.Token.Id: bid:eth:0x…`** to get every **Uniswap**, **SushiSwap**, or other DEX swap including **USD price**, **market cap**, **FDV**, **supply**, **trader address**, and **transaction hash**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-of-a-specific-Ethereum-token-with-Price-Marketcap-supply_1). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Ethereum" } } Token: { Id: { is: "bid:eth:0x8b1484d57abbe239bb280661377363b03c89caea" } } } } ) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## How Do I Stream Uniswap v4 Trades on Ethereum With Pool Id and Market Cap? > Stream **Uniswap v4** swaps on **Ethereum** by filtering **`Pair.Market.Network: Ethereum`** and **`Pair.Market.Protocol: uniswap_v4`**. Each event includes **`Pair.Pool.Id`** (the **v4 pool identifier** the protocol uses), **`Pair.Pool.Address`**, **market cap** and **circulating supply** under **`Supply`**, and full **pair** and **trader** context. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/Uniswap-v4-trades-with-pool-id-and-mcap). ```graphql subscription { Trading { Trades( where: {Pair: {Market: {Network: {is: "Ethereum"}, Protocol: {is: "uniswap_v4"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } Pool { Id Address } } } } } ``` On **Uniswap v4**, use **`Pair.Pool.Id`** as the stable **pool id** field (alongside **`Pair.Pool.Address`**). Example shape: ```json "Pool": { "Address": "0x000000000004444c5dc75cb358380d2e3de08a90", "Id": "0x71ad627a0586a06b24834f7af328c5c387a512d183dbd7b8c31189a866adcefa" } ``` --- ## How Do I Stream All DEX Trades on BSC (BNB Chain)? > Stream **every DEX swap on BNB Smart Chain** in real time — filter by **`Pair.Market.Network: Binance Smart Chain`** to capture trades across **PancakeSwap**, **Four.meme**, and other BSC DEXs. Each event returns **side**, **USD amounts**, **market cap**, **circulating supply**, **trader address**, and **pair metadata**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-BNB-Trade-Stream). ```graphql subscription { Trading { Trades(where: {Pair: {Market: {Network: {is: "Binance Smart Chain"}}}}) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } Currency { Symbol Id Name } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Stream All DEX Trades on Base? > Stream **every DEX swap on Base** in real time — filter by **`Pair.Market.Network: Base`** to capture trades across **Aerodrome**, **Uniswap**, **BaseSwap**, and other Base DEXs. Each event returns **side**, **USD amounts**, **market cap**, **circulating supply**, **trader wallet**, and **pair metadata**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-Base-Trade-Stream). ```graphql subscription { Trading { Trades(where: {Pair: {Market: {Network: {is: "Base"}}}}) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } Currency { Symbol Id Name } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Get All Trades for a Specific Wallet on Solana? > Track a **Solana wallet's DEX trading activity** in real time — filter by **`Trader.Address`** to stream every **buy and sell** swap executed by a specific wallet, including **token pair**, **USD price**, **amounts**, **market cap**, and **transaction details**. Useful for **copy trading bots**, **whale watching**, and **wallet PnL tracking**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-of-a-trader). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } } } Trader: { Address: { is: "GWcAopUZKokUUQAMDrNzd1YVHLJqbzJomu2pzNqLe9U3" } } } ) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## How Do I Get Trades for a Specific Trader on a Specific Token? > Combine **wallet address** and **token mint** filters to stream only the trades a **specific trader** made on a **specific token** — ideal for **position tracking**, **entry/exit analysis**, and **wallet-level PnL** on a per-token basis across **Solana**, **Ethereum**, or any supported chain. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/trades-of-a-specific-trader-of-a-specific-token). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } } Token: { Id: { is: "bid:solana:4YiLHDR4B4pE4R5GUMA8HG8YunyeLwcobtEtvwMupump" } } } Trader: { Address: { is: "GWcAopUZKokUUQAMDrNzd1YVHLJqbzJomu2pzNqLe9U3" } } } ) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## How Do I Stream All PumpFun Trades? > Stream **every pumpfun trade** in real time by filtering on the **pumpfun program address** (`6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`). Captures all bonding-curve swaps on pumpfun including **token pair**, **USD amounts**, **market cap**, **circulating supply**, and **trader wallet** — useful for **new token sniping**, **bonding-curve monitoring**, and **pumpfun analytics dashboards**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-pumpfun-Trade-Stream_2). ```graphql subscription { Trading { Trades( where: {Pair: {Market: {Program: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } Currency { Symbol Id Name } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Stream All PumpSwap Trades? > Stream **every PumpSwap trade** in real time by filtering on the **PumpSwap program address** (`pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA`). Captures all AMM swaps on PumpSwap — the successor DEX for tokens that graduated from the pumpfun bonding curve — including **token pair**, **USD amounts**, **market cap**, **supply**, and **trader wallet**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-Pumpswap-Trade-Stream). ```graphql subscription { Trading { Trades( where: {Pair: {Market: {Program: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } Currency { Symbol Id Name } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Get Only Buy or Sell Trades for a Token? > Stream **buy-side or sell-side trades** for a specific token by filtering on **`Pair.Token.Address`**. The **`Side`** field on each event tells you whether the trade was a **buy** or **sell** — use it client-side to split streams, calculate **buy/sell ratio**, track **buy pressure**, or trigger **sell alerts** for any token across supported chains. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-wsol-Trade-Stream). ```graphql subscription { Trading { Trades( where: {Pair: {Token: {Address: {is: "So11111111111111111111111111111111111111112"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Pool { Address Id } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Get Recent Trades for WSOL (Last 10 Minutes)? > Query the **last 10 minutes of WSOL trades** using **`Block.Time.since_relative`** with **`Pair.Token.Id`** (indexed field for faster lookups). Returns trades sorted by **most recent first** with **USD amounts**, **market cap**, **supply**, **pool address**, and **trader wallet** — ideal for building **live trade feeds**, **recent activity widgets**, or **short-window analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Last-10-minutes-trades-for-WSOL). ```graphql { Trading { Trades( orderBy:{descending:Block_Time} where: { Block:{Time:{since_relative:{minutes_ago:10}}} Pair: {Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Pool { Address Id } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Stream Trades for a Specific Trading Pair? > Stream **trades for a specific token pair** (e.g. **WSOL/USDC**) by filtering both **`Pair.Token.Id`** and **`Pair.QuoteToken.Id`**. This captures every swap between the two tokens **across all pools and DEXs** — useful for **pair-level price feeds**, **liquidity monitoring**, and **arbitrage detection** between Raydium, Orca, Jupiter, and other venues. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/WSOL-USDC-Token-pair-trade-stream). ```graphql subscription { Trading { Trades( where: {Pair: {Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}}, QuoteToken: {Id: {is: "bid:solana:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Pool { Address Id } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Get the Last 10 Trades for a Token Pair Across All Pools? > Query the **last 10 trades** for a specific pair (e.g. **WSOL/USDC**) across **every pool and DEX** using **`limit`**, **`orderBy: descending Block_Time`**, and a **`since_relative`** time window. Returns the most recent swaps with **pool address**, **USD amounts**, **market cap**, **trader wallet**, and **side** — ideal for **recent trades widgets**, **pair activity tables**, and **cross-pool comparison**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Last-10-WSOL-USDC-Token-pair-trades). ```graphql { Trading { Trades( limit:{count:10} orderBy: {descending: Block_Time} where: {Block: {Time: {since_relative: {minutes_ago: 10}}}, Pair: {Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}}, QuoteToken: {Id: {is: "bid:solana:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Pool { Address Id } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Get Trades Above a Minimum USD Value (Whale Trades)? > Stream **whale trades** across all chains by filtering **`AmountsInUsd.Base`** with **`gt`** (greater than) — for example, only swaps worth **over $100,000 USD**. Captures large-size DEX trades in real time with **trader wallet**, **token pair**, **pool**, **market cap**, and **supply** — ideal for **whale alert bots**, **smart money tracking**, **large-order flow analysis**, and **institutional activity monitoring**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/Stream---Trades-over-100k-usd). ```graphql subscription { Trading { Trades(where: {AmountsInUsd: {Base: {gt: 100000}}}) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Pool { Address Id } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How Do I Track Trades for Multiple Tokens in One Subscription? > Monitor **multiple tokens in a single subscription** using the **`in`** operator on **`Pair.Token.Id`** and **`Pair.QuoteToken.Id`** with the **`any`** combinator — or filter by **multiple pool addresses** with **`Pair.Pool.Address.in`**. Both approaches let you batch-watch a **token watchlist** or a **set of liquidity pools** without opening separate streams — ideal for **portfolio dashboards**, **multi-token alert bots**, and **pool-level monitoring**. There are two ways to track multiple tokens. You can specify token IDs using the **`any`** combinator to match trades where your tokens appear on either side of the pair. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/How-do-I-track-trades-for-multiple-tokens-in-one-subscription). ```graphql subscription { Trading { Trades(where: { any:[ {Pair:{Token:{Id:{in:["bid:solana:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "bid:solana:SKRbvo6Gf7GondiT3BbTfuRDPqLWei4j2Qy2NPGZhW3","bid:solana:Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"]}}}} {Pair:{QuoteToken:{Id:{in:["bid:solana:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "bid:solana:SKRbvo6Gf7GondiT3BbTfuRDPqLWei4j2Qy2NPGZhW3","bid:solana:Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"]}}}} ] Pair: {Market: {Network: {is: "Solana"}}}}) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Pool { Address Id } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` You can also specify **pool addresses** directly to monitor all tokens traded in those pools. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/Using-Pairs---How-do-I-track-trades-for-multiple-tokens-in-one-subscription). ```graphql subscription { Trading { Trades( where: {Pair: {Pool: {Address: {in: ["BMhbJpKihPsrQwWTNrzYLFwh2LbuDwWYbHKzEZrV9f6V", "916HUQvjHzJ3UP1LgtyoVYyxhkwqbnBxPshxNKBbz5uN", "aXQtJ9cGr1zgLyrppKJ5BR5jv1RMjyYL5Wetd2KZNtB"]}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Pool { Address Id } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## What Are the Most Traded Tokens on Solana in the Last Hour? > Get the **most traded tokens on Solana** in the last hour ranked by **trade count** — returns **number of trades**, **average trade size in USD**, and **total volume** per token pair. Useful for **trending token feeds**, **volume dashboards**, **hot token detection**, and identifying which tokens have the highest trading activity right now. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Most-traded-token-in-last-1-hour-on-solana-and-its-average-trade-amount-and-total-volume). ```graphql { Trading { Trades( orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { count average_trade_size: average(of: AmountsInUsd_Quote) sum(of:AmountsInUsd_Quote) Pair { Pool { Address } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How do I compare buy vs sell volume in USD per pool on Solana (last hour)? > Aggregates **Solana** **`Trades`** from the last **hour** into up to **100** rows per **liquidity pool**, ranked by **trade count**. Each row returns **quoted USD volume** (`AmountsInUsd_Quote`) split into **buy** vs **sell** sums plus **buy/sell counts**. Useful for **per-pool flow** and **directional pressure** dashboards. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Total-buy-vs-sell-volume-in-USD-per-token_1#). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) Pair { Pool { Address } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How do I rank pools by net buy-minus-sell trade count on Solana (last hour)? > Same **pool-level** aggregation as above, but adds **`net_flow`** as **`buys − sells`** (difference in **trade counts**, not USD). Ordered by **`net_flow`** so pools with more **buy-side prints** rank higher. For **USD** net flow, define a **`calculate`** on **`buy_volume`** and **`sell_volume`** instead. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Net-flow-buys---sells-per-token-symbol_2). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "net_flow"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) net_flow: calculate(expression: "$buys - $sells") Pair { Pool { Address } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How do I aggregate quoted USD volume by DEX program on Solana (last hour)? > Groups **Solana** trades by **`Pair.Market.Program`** (and **protocol** metadata), returning **trade count** and **total quoted USD volume** per **DEX program**. Useful for **share-of-volume** charts across **AMMs** and programs. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Volume-distribution-by-DEX-program#). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "Dex_Volume"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { Trades_count: count Dex_Volume: sum(of: AmountsInUsd_Quote) Pair { Market { Program Protocol ProtocolFamily Network } } } } } ``` --- ## How do I rank Solana tokens by market cap using trade-window supply snapshots (last hour)? > One row per **base token** (**`limitBy`** on **`Pair.Token.Address`**) with **`Supply.MarketCap`**, **FDV**, and **total supply** taken at **`maximum: Block_Time`** inside the last hour, plus **volume** and **trade stats**. Replace **`Pair.Market.Network`** or add **`Pair.Token.Id`** filters to narrow the universe. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Tokens-ranked-by-market-cap_1). ```graphql { Trading { Trades( limit: {count: 100} limitBy: {by: Pair_Token_Address, count: 1} orderBy: {descending: Supply_MarketCap} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) Pair { Pool { Address } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Supply { TotalSupply(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) MarketCap(maximum: Block_Time) } } } } ``` --- ## How do I find tokens with the highest trade frequency on Solana (last hour)? > Ranks **base tokens** by **`count`** of **`Trades`** in the window (plus **average trade size** and **volume** on **`AmountsInUsd_Quote`**). The selection nests **`Pair.Token`** only — ideal for **“most swapped assets”** style lists. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Tokens-with-highest-trade-frequency). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) Pair { Token { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How do I rank tokens by number of unique buyers on Solana (last hour)? > Adds **`unique_buyers`** as **`count(distinct: Trader_Address)`** on **Buy** side trades, ordered by that field — surfaces tokens with the **widest retail participation** in the window (subject to your filters). You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Tokens-with-most-unique-buyers). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "unique_buyers"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) unique_buyers: count(distinct: Trader_Address, if: {Side: {is: "Buy"}}) Pair { Token { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How do I find the most active liquidity pools on Solana by trade count (last hour)? > Ranks **pools** by **`count`** with full **pair** context (tokens + market). Same shape as **buy/sell volume per pool** but sorted purely by **activity** — good for **“hottest pools”** views. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Most-active-market-pools-by-trades). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "count"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) Pair { Pool { Address } Market { Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How do I count unique tokens traded per DEX program on Solana (last hour)? > Groups by **`Pair.Market`** program metadata and computes **`Unique_tokens`** with **`count(distinct: Pair_Token_Id)`** plus **volume** and **trade count** — shows how many **different base tokens** touched each **program** in the window. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Unique-tokens-per-DEX-program). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "Unique_tokens"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { Trades_count: count Dex_Volume: sum(of: AmountsInUsd_Quote) Unique_tokens: count(distinct: Pair_Token_Id) Pair { Market { Program Protocol ProtocolFamily Network } } } } } ``` --- ## How do I get per-minute trade counts for a Solana token (last hour)? > Buckets **`Block.Time`** into **1-minute** intervals via **`Time(interval: {in: minutes, count: 1})`**, filtered to one **`Pair.Token.Id`** on **Solana**. Returns **count**, **volume**, and **buy/sell** breakdown **per minute** — useful for **intraday activity** charts. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Trade-count-over-time-by-block-timestamp). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "Block_Timefield"} where: { Block: {Time: {since_relative: {hours_ago: 1}}} Pair: { Token: {Id: {is: "bid:solana:FVo4K9FtXg9A4M6cAovqm4qgM7ALUpgei2da4D6R9FXb"}} Market: {Network: {is: "Solana"}} } } ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) Pair { Token { Address Id IsNative Symbol TokenId Network } } } } } ``` --- ## How do I find the busiest one-minute volume windows for a Solana token (last hour)? > Same **1-minute** buckets and **token** filter as above, but **`orderBy`** **`total_volume`** so the **largest quoted-USD minutes** float to the top — a simple **volume spike** detector. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Volume-spikes--busiest-1min-time-windows). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "total_volume"} where: { Block: {Time: {since_relative: {hours_ago: 1}}} Pair: { Token: {Id: {is: "bid:solana:FVo4K9FtXg9A4M6cAovqm4qgM7ALUpgei2da4D6R9FXb"}} Market: {Network: {is: "Solana"}} } } ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } count average_trade_size: average(of: AmountsInUsd_Quote) total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Quote, if: {Side: {is: "Sell"}}) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) Pair { Token { Address Id Symbol Network } } } } } ``` --- ## How do I get total Solana DEX trade count, quoted USD volume, and sum of fees (last hour)? > Single-row aggregate over **all Solana** **`Trades`** in the window: **`TransactionHeader.Fee`** summed in **native units** (e.g. **lamports**), plus **trade count** and **`AmountsInUsd_Quote`** sum. Interpret **fees** with your own **SOL** reference price or decimals. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Total-SOL-fees-Total-Volume-Total-count-trades). ```graphql { Trading { Trades( where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { Trades_count_solana: count Solana_Volume: sum(of: AmountsInUsd_Quote) Total_fees_Solana: sum(of: TransactionHeader_Fee) } } } ``` --- ## How do I get average transaction fee per trade by DEX program on Solana (last hour)? > Groups by **`Pair.Market`** program fields, returning **`average(of: TransactionHeader_Fee)`** alongside **trade count**, **total fees**, and **quoted USD volume** per **program**. Fee values are **native**; compare **programs** on a **relative** basis or convert off-chain. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Average-fee-per-trade-Total-fees-total-volume-trades-count-per-DEX-program). ```graphql { Trading { Trades( limit: {count: 100} orderBy: {descendingByField: "Average_Fee_per_DEX"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Pair: {Market: {Network: {is: "Solana"}}}} ) { Trades_count_dex: count Dex_Volume: sum(of: AmountsInUsd_Quote) Total_fees_DEX: sum(of: TransactionHeader_Fee) Average_Fee_per_DEX: average(of: TransactionHeader_Fee) Pair { Market { Program Protocol ProtocolFamily } } } } } ``` --- ## How do I stream live prices for a Pump.fun token using the Trades API? > Subscribe to **real-time price updates** for a specific Pump.fun token — streams every trade with **USD price**, **market cap**, **FDV**, **total supply**, **buy/sell amounts**, and **transaction details** as they happen. Filter by **`Pair.Market.Program`** (Pump.fun program address) and **`Pair.Token.Id`** to lock onto one token. Useful for **live price tickers**, **trading bots**, **real-time dashboards**, and **token monitoring**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/pump-fun-token-live-prices-using-trades-api_1#). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } Program:{is:"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"} } Token: { Id: { is: "bid:solana:DhDRgwGeTPzkykcSYgTw42EsH3DBZg1p6FnnnXkrpump" } } } } ) { Side Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## How do I get the first 50 buyers of a token? > Retrieve the **first 50 buy trades** for a specific token ordered by **ascending block time** — returns the **earliest buyers**, their **wallet addresses**, **amounts paid**, **USD values**, **price at entry**, **market cap**, and **supply data** at the time of each trade. Filter by **`Side: "Buy"`** and **`Pair.Token.Id`** to target one token. Useful for **early buyer analysis**, **smart money tracking**, **insider detection**, and **token launch forensics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/first-50-buyers-of-a-token_3#). ```graphql { Trading { Trades( limit: {count: 50} orderBy: {ascending: Block_Time} where: {Side: {is: "Buy"}, Pair: {Market: {Network: {is: "Solana"}}, Token: {Id: {is: "bid:solana:DhDRgwGeTPzkykcSYgTw42EsH3DBZg1p6FnnnXkrpump"}}}} ) { Side Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` --- ## Crypto Trading Pairs Price API URL: https://docs.bitquery.io/docs/trading/crypto-price-api/pairs/ Pool-level price, volume, liquidity and ranking for a token on one DEX market, with GraphQL queries and streams. # Pairs Cube ## What it is The Pairs cube is one row per pool, quote token and interval: a base token traded against a quote token on one DEX market. Each row carries the pool's OHLC, volume, liquidity and its `Ranking` in the token's price blend. It answers two questions: what does this token trade at on its main market, and which pools price it. `Pairs` is [`Tokens`](/docs/trading/crypto-price-api/tokens) plus venue and quote identity; there are no Tokens-only fields. If you do not need `Market`, `Pool` or `QuoteToken`, query `Tokens` instead, it is the cheaper shape for the same price and volume data. ## How to get it ### The most accurate token price: rank 1 {#most-accurate-token-price} :::tip Querying the price of a specific token? Use this pattern Query the **Pairs** cube with **`Ranking: { Position: { eq: 1 } }`**. This returns the token's price on its **top market**: the pool holding the largest share of the token's liquidity in the blend, after the staleness discount. It is a single-market price, not a value blended across every pool the token trades in. ::: Filters that matter: - **Token**: `Token: { Address: ..., Network: ... }` or `Token: { Id: { is: "bid::
" } }`. - **Rank**: `Ranking: { Position: { eq: 1 } }` for the top market, `in: [1, 2, 3]` for the main venues. - **Interval**: `Interval: { Time: { Duration: { eq: 60 } } }`. Durations are 1, 3, 5, 10, 30, 60, 300, 900, 1800 and 3600 seconds. - **Denomination**: `Price: { IsQuotedInUsd: true }`. Rank 1 selects the market, not the currency the price is quoted in. - **A known pool**: `Pool: { Address: ... }` works on every chain. See the `Market.Address` pitfall below before filtering by market. Change `query` to `subscription` for a stream. The same rows are published on Kafka as `trading.prices`; see [Kafka: trading.prices](/docs/trading/crypto-price-api/liquidity-fields#kafka-tradingprices). | You want | Use | | --- | --- | | The price of one specific token | **`Pairs` + `Ranking: { Position: { eq: 1 } }`** | | A firehose of every token on a chain, or one chain-wide number per token | [`Tokens`](/docs/trading/crypto-price-api/tokens) | | One number for an asset across all chains (BTC, ETH) | [`Currencies`](/docs/trading/crypto-price-api/currency) | | A specific pool you already know the address of | `Pairs` + `Pool: { Address: ... }` | ### Why the top market, and not the blended token price The [Tokens cube](/docs/trading/crypto-price-api/tokens) reports one price per token per chain. That price is a **liquidity-weighted blend of every pool** where the token is the base asset (see [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm)). It is the right answer for a single chain-wide number, and for a token whose liquidity sits in one deep pool it agrees closely with the rank-1 price. Fragmented tokens behave differently. Thin pools get little weight because they hold little liquidity, but a pool with a large reserve that is stale, or whose reserve is only estimated from volume, can outweigh the pool where the trading actually happens. The blend can then sit at a price nobody is trading at. Filtering `Pairs` to `Ranking.Position = 1` avoids that. You get one market's quote, the one the index trusts most, which is the closest thing to an executable price. ## How it is derived ### Quote token choice Every pair has a base and a quote; the price is quote units per 1 base. Stablecoins win the quote slot, then native tokens. The full rules are in [Breaking Down Price Streams in Detail](/docs/trading/crypto-price-api/in-depth#the-logic-behind-quote-token-selection). A pool's price is the latest trade price, normalised to USD when the quote token has a USD price: ``` if quoteInUsd { vol.AveragePrice.Price = vol.AveragePrice.Usd / vol.AveragePrice.BaseAttributedToUsd } else { vol.AveragePrice.Price = vol.AveragePrice.Quote / vol.AveragePrice.Base } ``` ### Ranking: how `Position` and `Weight` behave {#ranking-how-position-and-weight-behave} `Ranking.Weight` is the pool's share of the token's liquidity, after the staleness discount, so the weights of a token's pools sum to 1. `Liquidity.Usd` is the measured reserve where one is known (`Source` `real` or `real_stale`), a launch-curve balance (`migration`), or an estimate from the last hour's decay-weighted volume (`volume`). For `volume` pools weight therefore still follows volume. See [How liquidity is calculated](/docs/trading/crypto-price-api/liquidity-fields#how-liquidity-is-calculated). `Ranking.Position` orders a token's pools by `Weight` descending. It is a **competition rank**, not a dense index: - Ties occur, and are followed by a skipped value. - Additional gaps appear that ties alone do not explain, so the highest `Position` always exceeds the row count. - `Position` can be `0`, paired with `Weight` `0`. `RankingDetail.Verdict` is `""` on such rows: not ranked in this batch. **Normalise before treating weights as shares.** `Weight` is in `[0, 1]` per row and the per-token sum is centred on 1.0, but it is not guaranteed to equal it; sums above and below 1 both occur. Pools that did not trade in the interval hold weight but have no `Pairs` row, so the rows you fetch cover only part of the sum. **Weight and Position are recomputed every batch from the current liquidity state**, not from the row's own interval. A rank-1 row can report less `Volume.Usd` for its interval than a lower-ranked row does. On BSC on 2026-10-22, the rank-1 WBNB pool carried 2.9 % of hourly volume and 50.6 % of liquidity; the rank-2 pool carried 78 % of volume. **Verdict gating applies before weighting.** Pools the blend rejected (`outlier`, `ineligible`, `no_price`, `retired`) keep a row and a `Position`; filter on `RankingDetail.Verdict: { is: "priced" }` for the pools whose price the token actually uses. See [RankingDetail](/docs/trading/crypto-price-api/liquidity-fields#fields). :::note History before 2026-10-19 is volume-weighted Since 2026-10-19 the blend is liquidity-weighted. Rows before that date in the 30-day history are volume-weighted: `Liquidity` fields are `0` on them and `Weight` is the pool's share of decay-weighted volume. ::: ### Reading `Ranking.Weight` Treat `Weight` as a confidence signal on the blended price: - **Weight close to 1.** One pool holds essentially all the liquidity. The blended `Tokens` price and the rank-1 price will be nearly identical, so either works. - **Low weight.** Liquidity is spread across many pools and the blend mixes all of them. This is where the rank-1 price and the blended price diverge, and the rank-1 price is the one you want. ## Fields {#schema-and-fields} | Field | Type | Meaning | | --- | --- | --- | | `Token { Address Id Symbol Name Network NetworkBid IsNative TokenId Did }` | String / Boolean | The base token being priced. `Id` is `bid::
`; `Address` is empty for native assets. | | `QuoteToken { ... }` | same as `Token` | The quote token of this row. | | `Currency { Id Name Symbol }` / `QuoteCurrency { ... }` | String | The cross-chain currency each token belongs to, for example `bid:bitcoin` for WBTC. | | `Market { Address Id Name Network NetworkBid Program Protocol ProtocolFamily }` | String | The DEX market. `Address` is the factory on EVM and Tron and the pool on Solana; `Program` is the pool contract on EVM and the DEX program on Solana. | | `Pool { Address Id }` | String | `Address` is the portable pool key on every chain. `Id` is empty except on singleton-contract protocols (Uniswap v4, PancakeSwap Infinity), where it carries the pool identity. | | `Block { Date Time Timestamp }` | String / DateTime / String | Time of the last update in the interval. | | `Interval { Time { Start End Duration } }` | DateTime / DateTime / Int | The bar. `Duration` in seconds. | | `Price.Ohlc { Open High Low Close }` | Float | OHLC for the interval, from trades with known USD values. | | `Price.Average { Estimate Mean SimpleMoving WeightedSimpleMoving ExponentialMoving }` | Float | Averages over the interval and a 5-entry moving window. `Estimate` is the price `Supply.MarketCap` and `FullyDilutedValuationUsd` are built from. | | `Price.IsQuotedInUsd` | Boolean | `true`: prices in USD. `false`: prices in quote-token units. | | `PoolPrice { Price Ohlc { Open High Low Close } Average { … } Source UpdatedAt }` | Float / String / DateTime | The liquidity pool's own price from its curve after the last swap, next to the traded `Price`. `null` with `Source: ""` when the pool reports no price. See [PoolPrice fields](/docs/trading/crypto-price-api/pool-price-fields). | | `Volume.Base` | Float | Base token amount traded in the interval. | | `Volume.Quote` | Float | Sum of quote-token amounts. Not USD, even for stablecoin quotes; use `Volume.Usd`. | | `Volume.Usd` | Float | Trade volume in USD. | | `Volume.BaseAttributedToUsd` | Float | Part of `Volume.Base` traded against quote tokens with a known USD price. Used for the USD average price. | | `Liquidity { Usd Source RealShare BaseReserve QuoteReserve QuoteReserveUsd DepthUsd NetQuoteUsd UpdatedAt }` | Float / String / DateTime | The pool's balance of the row's quote token, valued in USD, plus how it was measured. See [Liquidity fields](/docs/trading/crypto-price-api/liquidity-fields#fields). | | `Ranking { Position Weight }` | Int / Float | The pool's rank and liquidity share in the token's blend, above. | | `RankingDetail { Verdict StaleMultiplier }` | String / Float | Why the pool got that rank. See [RankingDetail](/docs/trading/crypto-price-api/liquidity-fields#fields). | | `Supply { CirculatingSupply TotalSupply MaxSupply MarketCap FullyDilutedValuationUsd }` | Float | Currency-level figures, repeated on every row of the asset. See [Supply fields](/docs/trading/crypto-price-api/supply-fields). | **Row fan-out.** One row per (`Market.Address`, `Pool.Address`, `Pool.Id`, `QuoteToken.Id`) per token per interval, not one row per market. A token quoted against two assets on the same market produces two rows. **`Liquidity.Usd` values the quote leg only and can be an estimate.** Read [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields) before ranking pools by it. For full pool state use the chain-level `DEXPools` cube, or a [cloud export](/docs/cloud/) for historical depth. ## Examples ### What is a token's latest price on its top market? [Run query ➤](https://ide.bitquery.io/Token-price-from-top-market--rank-1_2) ```graphql { Trading { Pairs( where: { Token: { Address: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 60 } } } Price: { IsQuotedInUsd: true } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } } Ranking { Position Weight } Volume { Usd } Block { Time } } } } ``` - `Price.Ohlc.Close` is the token's latest price on its top market. - `Ranking.Weight` says how much of the token's liquidity that market holds. ### How do I stream the top-market price? Change `query` to `subscription` and drop `limit`/`orderBy` to receive top-market updates as they happen: [Run Stream ➤](https://ide.bitquery.io/Token-price-stream-from-top-market--rank-1) ```graphql subscription { Trading { Pairs( where: { Token: { Address: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true } } ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address } Price { IsQuotedInUsd Ohlc { Close } } Ranking { Position Weight } } } } ``` - To stream the top market of **every** token on a chain, replace the `Token.Address` filter with `Token: { Network: { is: "Solana" } }` and keep the rank filter. - The rank-1 pool can change mid-stream. Key your state on `Market.Address` from each message. ### How do I get the top-market price for several tokens at once? Add `limitBy` to collapse the result to one current row per token: [Run query ➤](https://ide.bitquery.io/Multi-token-watchlist--rank-1-per-token) ```graphql { Trading { Pairs( where: { Token: { Address: { in: [ "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" "So11111111111111111111111111111111111111112" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" ] } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 60 } } } Price: { IsQuotedInUsd: true } Block: { Time: { since_relative: { minutes_ago: 10 } } } } limit: { count: 10 } limitBy: { by: Token_Id, count: 1 } orderBy: { descending: Block_Time } ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol } Price { Ohlc { Close } } Ranking { Position Weight } Block { Time } } } } ``` - Group by `Token_Id`, not `Token_Address`: native assets share an empty `Token.Address`. - Widen `minutes_ago` for tokens whose top market trades rarely. ### How do I get candles for one pool I know the address of? ```graphql { Trading { Pairs( where: {Market: {Network: {is: "Solana"}}, Pool: {Address: {is: "58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2"}}, Interval: {Time: {Duration: {eq: 300}}}, Price: {IsQuotedInUsd: true}} limit: {count: 10} orderBy: {descendingByField: "Block_Time"} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd #Are the values in USD or Native } } } } ``` - The address is the Raydium AMM v4 SOL/USDC pool. Filter by `Pool.Address`, which is the pool on every chain. - One row per quote token of the pool; add `QuoteToken { Symbol }` if the pool has more than one. ## Pitfalls - **`Position: { eq: 1 }` silently drops tokens.** Rank 1 returns only tokens whose top market traded in that interval. A token whose rank-1 market was quiet is omitted, a few percent of tokens per interval, varying by chain. Widen the interval or fall back to `Tokens` for coverage. - **Rank 1 does not imply USD.** Always pair the rank filter with `Price: { IsQuotedInUsd: true }`, or read `IsQuotedInUsd` on each row. - **The top market can change.** Ranking is recomputed every batch as liquidity and staleness change, so a token's rank-1 pool, and its quote token, may flip during a stream. Key your state on `Market.Address` from each message. - **Always scope the query.** An unscoped rank-1 query across a whole chain scans very wide and can time out. Filter by `Token.Address` with `Network` (or `Market: { NetworkBid: { is: "bid:eth" } }` for lower latency), and add `Block: { Time: { since_relative: { minutes_ago: N } } }` for broad queries. Chain-wide rank-1 sweeps take a few seconds for a short interval, longer for hour-to-day windows. - **`Price.IsQuotedInUsd` selects a denomination, it does not de-duplicate.** Markets are not published twice: an unfiltered query returns the USD rendering only, byte-identical to `IsQuotedInUsd: true`. `false` re-renders the same rows in quote-token units; only `Price.*` changes, `Volume`, `Ranking` and `Supply` are identical. Prices are in USD even when the quote token is WSOL, because the index normalises the quote side; see [How Pool Prices Are Normalized](/docs/trading/crypto-price-api/price-index-algorithm#how-token-prices-are-determined). - **Group by `Token_Id`, not `Token_Address`.** ETH on Ethereum, Arbitrum, Base and Optimism, BNB on BSC and MATIC on Matic all carry `""` as `Token.Address`. Grouping by address collapses them into one row. - **Want the runner-up markets too?** Use `Ranking: { Position: { in: [1, 2, 3] } }` to compare a token's main venues, or `orderBy: { descending: Ranking_Weight }`. - **`Ranking` does not exist on `Currencies`.** It is available on `Trades`, `Pairs` and `Tokens` only. - **`Market.Address` is not the pool on EVM.** It is the protocol factory there, and an empty string for singleton protocols (uniswap_v4, balancer_v2, curve, fluid_dex). Filtering an EVM pool by `Market: { Address: ... }` matches the factory and silently returns a different pool's data. Use `Pool.Address`. | Chain family | `Market.Address` | `Market.Program` | `Pool.Address` | | --- | --- | --- | --- | | EVM and Tron | the protocol factory, empty for singleton protocols | the pool contract | the pool | | Solana | the pool | the DEX program | the pool | ## Related - [Tokens cube](/docs/trading/crypto-price-api/tokens) - [Currencies cube](/docs/trading/crypto-price-api/currency) - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) - [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields) - [PoolPrice fields](/docs/trading/crypto-price-api/pool-price-fields) - [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) - [Breaking Down Price Streams in Detail](/docs/trading/crypto-price-api/in-depth) --- ## Custom DataFeed Setup URL: https://docs.bitquery.io/docs/usecases/tradingview-subscription-realtime/custom_datafeed/ Build Custom DataFeed Setup: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Custom DataFeed Setup In this section, we will create a custom DataFeed for TradingView's Advanced Charting Library, integrating historical OHLC data and real-time data subscription. We will use three main files: - `getBars.js`: Handles fetching historical data and subscribing to real-time updates. - `resolveSymbol.js`: Provides symbol resolution for the chart. - `onReady.js`: Supplies configuration details like supported resolutions. Finally, we will integrate everything into `customDatafeed.js`. --- ### 1. `getBars.js` The `getBars.js` file is responsible for fetching historical data and subscribing to real-time data streams via WebSocket. ```javascript // Fetch historical data bars export const getBars = async ( symbolInfo, resolution, periodParams, // compulsorily needed by TradingView onHistoryCallback, onErrorCallback ) => { try { console.log( "[getBars]: Fetching bars for", symbolInfo, resolution, periodParams.from, periodParams.to ); // Fetch historical data const bars = await fetchHistoricalData(); // Pass bars to the chart if data is available if (bars.length > 0) { onHistoryCallback(bars, { noData: false }); } else { onHistoryCallback([], { noData: true }); } } catch (err) { console.error("[getBars] Error fetching data:", err); onErrorCallback(err); } }; // Subscribe to real-time data using WebSocket export const subscribeBars = ( symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback ) => { subscribeToWebSocket(onRealtimeCallback); }; // Unsubscribe from real-time data export const unsubscribeBars = (subscriberUID) => { delete this.subscribers[subscriberUID]; }; ``` - **getBars**: This function fetches historical OHLC data using `fetchHistoricalData()` and provides it to TradingView. It handles the `periodParams` provided by TradingView, which indicates the required time range. - **subscribeBars**: Subscribes to a WebSocket data feed using `subscribeToWebSocket()` for real-time trade data, emitting bars as new trades come in. - **unsubscribeBars**: Unsubscribes from the real-time WebSocket data feed, stopping the stream of new bars. --- ### 2. `resolveSymbol.js` The `resolveSymbol.js` file defines how a symbol (like a token pair) is resolved. TradingView needs to resolve symbols before fetching data for them. ```javascript export const resolveSymbol = ( symbolName, onSymbolResolvedCallback, onResolveErrorCallback, extension ) => { // Hardcode or query token symbol const tokenSymbol = "BCAT"; if (!tokenSymbol) { onResolveErrorCallback(); } else { const symbolInfo = { ticker: tokenSymbol, name: `${tokenSymbol}/WSOL`, session: "24x7", timezone: "Etc/UTC", minmov: 1, pricescale: 1000,// set it dynamically according to price range of token has_intraday: true, intraday_multipliers: ["1", "5", "15", "30", "60"], has_empty_bars: false, has_weekly_and_monthly: false, supported_resolutions: ["1", "5", "15", "30", "60", "1D", "1W", "1M"], supported_intervals: ["1", "5", "15", "30", "60", "1D", "1W", "1M"], countBack: 30, volume_precision: 2, visible_plots_set: 'ohlcv', }; onSymbolResolvedCallback(symbolInfo); } }; ``` - **resolveSymbol**: Resolves a symbol (like a token's ticker) for TradingView. It provides metadata like the symbol's name, supported time intervals, and price scale. In this case, the symbol is hardcoded as `BCAT`, but it can be dynamic based on the query or user input. --- ### 3. `onReady.js` The `onReady.js` file provides the configuration data that TradingView needs when it initializes the chart, such as supported time resolutions. ```javascript const configurationData = { supported_resolutions: ['1', '5', '15', '30', '60', '1D', '1W', '1M'], // ... other configuration data }; export const onReady = (callback) => { setTimeout(() => callback(configurationData), 0); }; ``` - **onReady**: This function provides the configuration of the charting library, including the supported time intervals for the chart (1 minute, 5 minutes, etc.). It’s called when the chart is first initialized. --- ### 4. `customDatafeed.js` This file ties everything together, providing the custom DataFeed object that TradingView requires to interface with the charting library. ```javascript // Datafeed object for TradingView const Datafeed = { onReady, resolveSymbol, getBars, subscribeBars, unsubscribeBars, }; export default Datafeed; ``` - **Datafeed**: This object integrates the `onReady`, `resolveSymbol`, `getBars`, `subscribeBars`, and `unsubscribeBars` functions into a complete custom DataFeed that TradingView uses to fetch historical and real-time OHLC data. --- ### How It Works 1. **Resolving the Symbol**: The chart resolves the symbol via `resolveSymbol.js`, which provides metadata about the token pair (e.g., POPCAT/WSOL). 2. **Fetching Historical Data**: When the chart requests historical data, `getBars.js` fetches the data via the `fetchHistoricalData` method and returns it to TradingView. 3. **Subscribing to Real-Time Data**: The chart subscribes to real-time updates via WebSocket using `subscribeBars` in `getBars.js`. New bars are emitted as trades occur. 4. **Configuration**: `onReady.js` provides configuration data like supported time intervals to TradingView. 5. **Unsubscribing**: When real-time updates are no longer needed, `unsubscribeBars` stops the WebSocket feed. --- ## DEX Liquidity & Slippage on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-liquidity/ Query & stream Robinhood DEX pool liquidity, TVL, and slippage with Bitquery GraphQL: Uniswap V2/V3/V4 and PancakeSwap reserves, depth, and price impact. # DEX Liquidity & Slippage on Robinhood Chain Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). Track **DEX pool liquidity, TVL, and slippage / price impact** on Robinhood with Bitquery GraphQL — across **Uniswap V2 / V3 / V4 and PancakeSwap** pools, including **tokenized stock pairs (AAPL, NVDA)**. Use: | Cube | What it returns | | --- | --- | | **`DEXPoolEvents`** | Pool reserves, spot prices (A↔B), protocol metadata, and the tx that changed pool state | | **`DEXPoolSlippages`** | Max trade size and min out at fixed slippage tolerances (0.1%–10%) for both swap directions | Both cubes sit on the `EVM` root with `network: robinhood`. For how pool records and price tables are built, see the [DEXPools Cube](/docs/cubes/evm-dexpool/). This page covers pool liquidity only. For Robinhood Chain transactions, receipts, status, gas and fees, use the [Robinhood Chain Transactions & Receipts API](/docs/blockchain/robinhood/robinhood-transactions-receipts-api/). Paste any example below into the [Bitquery IDE](https://ide.bitquery.io/) to run it against live Robinhood data. Every query on this page was executed against the production endpoint before publishing. :::warning Realtime dataset only Robinhood **`DEXPoolEvents`** and **`DEXPoolSlippages`** are available only on **`dataset: realtime`**. `archive` and `combined` return errors such as *no archive or API tables found for cube DEXPoolEvent / DEXPoolSlippage*. Always use realtime (or omit `dataset`, which defaults to realtime). For older pool data, ask about a [Data Store export](https://bitquery.io/datastore). ::: :::note API Key Required To query or stream outside the Bitquery IDE, you need an API access token. Follow: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending) — new pools, trending tokens, pair lookup and token search - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Trades](/docs/blockchain/robinhood/robinhood-trades/) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) - [DEXPools Cube](/docs/cubes/evm-dexpool/) - [Base Liquidity API](/docs/blockchain/Base/base-liquidity-api/) - [Base Slippage API](/docs/blockchain/Base/base-slippage-api/) ::: **On this page:** [Latest liquidity](#latest-liquidity-events) · [By pool](#liquidity-for-a-specific-pool) · [By token](#liquidity-for-pools-involving-a-token) · [Protocols](#filter-by-dex-protocol) · [Largest pools](#largest-recent-liquidity-readings-by-usd) · [Price watchlist](#live-price-watchlist-latest-state-per-pool) · [Active pools & ranges](#most-active-pools-and-price-ranges-1-hour-window) · [TVL time series](#pool-tvl-and-price-time-series-5-minute-buckets) · [Stream](#stream-liquidity-updates) · [Slippage](#slippage-and-price-impact) · [FAQ](#faq) --- ## Useful contracts and example pools | Item | Value | | --- | --- | | Network | `network: robinhood` | | ETH (native, `CurrencyA` on most V4 pools) | `0x` | | WETH | `0x0bd7d308f8e1639fab988df18a8011f41eacad73` | | USDG (Global Dollar) | `0x5fc5360d0400a0fd4f2af552add042d716f1d168` | | AAPL (Apple · Robinhood Token) | `0xaf3d76f1834a1d425780943c99ea8a608f8a93f9` | | NVDA (NVIDIA · Robinhood Token) | `0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec` | | Example Uniswap V4 manager | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | | Example ETH/USDG PoolId (V4) | `0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32` | | Example USDG/AAPL PoolId (V4) | `0xc748f4671a867db48b552f6b7650bf3255e05f80f00e3f7aad1b17ccb7898fdb` | | Example CASHCAT/WETH pool (V3) | `0xa70fc67c9f69da90b63a0e4c05d229954574e313` | :::note Example pools The example `PoolId` and pool addresses are **illustrative addresses that were active when this page was last tested**. Meme and long-tail pools can go quiet — replace them with any pool you care about. ::: :::tip Pool identity: V2/V3 vs V4 - **Uniswap V2/V3:** each pool is its own contract — filter with `Pool.SmartContract`; `PoolId` is empty (`0x`). - **Uniswap V4:** many pools share the same manager `SmartContract` — use **`Pool.PoolId`** to select a specific pool. - **Mixed sets (rankings, watchlists):** a pool's unique key is the **pair** (`Pool.SmartContract`, `Pool.PoolId`). Deduplicate with `limitBy: { by: [PoolEvent_Pool_SmartContract, PoolEvent_Pool_PoolId], count: 1 }` so neither family collapses into one row. ::: --- ## How to read pool prices Price fields are directional and quoted in the pool's own currencies. For the ETH/USDG V4 pool (`CurrencyA` = ETH, `CurrencyB` = USDG), a typical row reads: | Field | Meaning | Example | | --- | --- | --- | | `AtoBPrice` | Units of **CurrencyA** per 1 **CurrencyB** | `0.000525` (ETH per USDG) | | `AtoBPriceInUSD` | USD price of 1 **CurrencyB** | `0.998` (USDG ≈ $1) | | `BtoAPrice` | Units of **CurrencyB** per 1 **CurrencyA** | `1905.83` (USDG per ETH) | | `BtoAPriceInUSD` | USD price of 1 **CurrencyA** | often `0` (see below) | Sanity check: `AtoBPrice × BtoAPrice ≈ 1`. The same convention holds on every pool — on CASHCAT/WETH (V3), `AtoBPrice ≈ 43,072` is CASHCAT per 1 WETH. :::note When `*InUSD` is 0 USD enrichment is not populated for every row — `BtoAPriceInUSD` and the `Liquidity.*InUSD` fields frequently return `0`, especially on V2/V3 pools and non-ETH-quoted pairs. When you have reserves, derive the missing price yourself: `AmountCurrencyAInUSD ÷ AmountCurrencyA` gives the USD price of CurrencyA (≈ $1,902 per ETH in the row above). ::: --- ## Latest liquidity events Recent pool updates with reserves and spot prices. Useful for dashboards and pool health monitors. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } PoolEvent { AtoBPrice AtoBPriceInUSD BtoAPrice BtoAPriceInUSD Dex { SmartContract ProtocolName ProtocolVersion ProtocolFamily } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } Transaction { Hash From To CostInUSD } } } } ``` Example response shape (fields truncated): ```json { "EVM": { "DEXPoolEvents": [ { "Block": { "Number": "17339306", "Time": "2026-07-23T13:55:06Z" }, "PoolEvent": { "AtoBPrice": 0.0005247070221230388, "AtoBPriceInUSD": 0.9981142611098761, "BtoAPrice": 1905.8255615234375, "BtoAPriceInUSD": 0, "Dex": { "ProtocolName": "uniswap_v4", "ProtocolVersion": "4", "SmartContract": "0x8366a39cc670b4001a1121b8f6a443a643e40951" }, "Liquidity": { "AmountCurrencyA": 152.95826721191406, "AmountCurrencyAInUSD": 290962.04438267834, "AmountCurrencyB": 4398114.5, "AmountCurrencyBInUSD": 0 }, "Pool": { "PoolId": "0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32", "CurrencyA": { "Name": "Ethereum", "SmartContract": "0x", "Symbol": "ETH" }, "CurrencyB": { "Name": "Global Dollar", "Symbol": "USDG" } } } } ] } } ``` Note the `BtoAPriceInUSD: 0` and `AmountCurrencyBInUSD: 0` — real rows carry USD gaps; see [How to read pool prices](#how-to-read-pool-prices). --- ## Liquidity for a specific pool ### Uniswap V3 pool (by SmartContract) ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { PoolEvent: { Pool: { SmartContract: { is: "0xa70fc67c9f69da90b63a0e4c05d229954574e313" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { ProtocolName ProtocolVersion } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } } Transaction { Hash } } } } ``` ### Uniswap V4 pool (by PoolId) ▶️ Runnable IDE examples: [new Uniswap v4 pools](https://ide.bitquery.io/uniswap-v4-pools-on-robinhood-chain) and [v4 hooks in use](https://ide.bitquery.io/uniswap-v4-hooks-robinhood-chain) ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } PoolEvent { AtoBPrice AtoBPriceInUSD BtoAPrice BtoAPriceInUSD Dex { ProtocolName ProtocolVersion SmartContract } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } Transaction { Hash From To } } } } ``` --- ## Liquidity for pools involving a token **Trading / RWA / stablecoins:** find pools where a token is CurrencyA or CurrencyB. Examples: WETH, USDG, AAPL, NVDA. ### WETH pools ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { any: [ { PoolEvent: { Pool: { CurrencyA: { SmartContract: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } } } } } { PoolEvent: { Pool: { CurrencyB: { SmartContract: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } } } } } ] } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { AtoBPrice BtoAPrice Dex { ProtocolName ProtocolVersion } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } } Transaction { Hash } } } } ``` ### Tokenized stock pools (AAPL) Robinhood tokenized equities trade in ordinary DEX pools. An active AAPL venue is the **USDG/AAPL Uniswap V4 pool** (`PoolId 0xc748f467…`); its `AtoBPrice` is the AAPL price quoted in USDG. Swap in the NVDA address (`0xd0601ce1…`) for NVIDIA pools. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { any: [ { PoolEvent: { Pool: { CurrencyA: { SmartContract: { is: "0xaf3d76f1834a1d425780943c99ea8a608f8a93f9" } } } } } { PoolEvent: { Pool: { CurrencyB: { SmartContract: { is: "0xaf3d76f1834a1d425780943c99ea8a608f8a93f9" } } } } } ] } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { AtoBPrice BtoAPrice Dex { ProtocolName ProtocolVersion } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } Transaction { Hash } } } } ``` ### Find pools by token symbol When you only know the ticker, filter on `Currency.Symbol`. One latest row per pool via the composite `limitBy`. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { PoolEvent: { Pool: { CurrencyB: { Symbol: { is: "NVDA" } } } } } limitBy: { by: [PoolEvent_Pool_SmartContract, PoolEvent_Pool_PoolId], count: 1 } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { AtoBPriceInUSD Dex { ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB } Pool { PoolId SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } } } } ``` :::warning Symbols are not unique Robinhood has **two different contracts both claiming the NVDA symbol**: the canonical `NVIDIA • Robinhood Token` (`0xd0601ce1…`) and a copycat named just `NVDA` (`0xdecf74e4…`). Use symbol filters for discovery, then pin the `SmartContract` address in anything that trades. Also check the other side of the pair — the ETH/NVDA pool has NVDA as `CurrencyB`, but flip the filter to `CurrencyA` (or use `any:`) for full coverage. ::: --- ## Filter by DEX protocol Isolate one protocol's pool updates — Uniswap V2/V3/V4 or PancakeSwap. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { PoolEvent: { Dex: { ProtocolName: { is: "uniswap_v4" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { Dex { ProtocolName ProtocolVersion ProtocolFamily } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } } } } } ``` ### Protocol activity breakdown ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( limit: { count: 10 } orderBy: { descendingByField: "count" } ) { PoolEvent { Dex { ProtocolName ProtocolVersion ProtocolFamily } } count } } } ``` Protocols observed on Robinhood pool events: **Uniswap** (`uniswap_v2`, `uniswap_v3`, `uniswap_v4`) and **PancakeSwap** (`pancake_swap_v3`, `pancakeswap_infinity`). Run the breakdown query above for the current split. ### Network-wide totals One-row dashboard stat: total pool updates and distinct pool contracts in the realtime window. `count(distinct: …)` is exact; `uniq(of: …)` is a faster approximate alternative. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents { updates: count pools: count(distinct: PoolEvent_Pool_SmartContract) } } } ``` Note: this counts distinct **contracts** — every V2/V3 pool individually, while all V4 pools share their manager contract. Count `PoolEvent_Pool_PoolId` instead to enumerate V4 pools. --- ## Largest recent liquidity readings by USD **Trading / risk:** rank recent pool **events** by `AmountCurrencyAInUSD` within the realtime window. Without `limitBy`, the same busy pool fills the top rows (many updates, one pool). Deduplicate on the **composite pool key** — using `PoolId` alone would merge every V2/V3 pool into a single row, since they all share `PoolId: "0x"`: ``` limitBy: { by: [PoolEvent_Pool_SmartContract, PoolEvent_Pool_PoolId], count: 1 } ``` :::note Float filters and USD gaps `AmountCurrencyAInUSD` / `AmountCurrencyBInUSD` filters expect **Float** values (for example `gt: 10000`), not quoted strings. Because V2/V3 and non-ETH-quoted rows often report `0` USD, a USD threshold effectively ranks the native-ETH V4 pools — combine with token filters, or rank raw amounts per token, when you need the rest. ::: ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { PoolEvent: { Liquidity: { AmountCurrencyAInUSD: { gt: 10000 } } } } limit: { count: 20 } limitBy: { by: [PoolEvent_Pool_SmartContract, PoolEvent_Pool_PoolId], count: 1 } orderBy: { descending: PoolEvent_Liquidity_AmountCurrencyAInUSD } ) { Block { Time } PoolEvent { AtoBPrice AtoBPriceInUSD Dex { ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } } Transaction { Hash } } } } ``` --- ## Live price watchlist (latest state per pool) One call, one **latest** row per active pool: spot prices both directions plus current reserves in USD. This is the query behind a screener or watchlist page — poll it, or move to the [stream](#stream-liquidity-updates) for push updates. The `gt: 100` USD floor drops dust pools. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { PoolEvent: { Liquidity: { AmountCurrencyAInUSD: { gt: 100 } } } } limitBy: { by: [PoolEvent_Pool_SmartContract, PoolEvent_Pool_PoolId], count: 1 } limit: { count: 30 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { AtoBPrice AtoBPriceInUSD BtoAPrice BtoAPriceInUSD Dex { ProtocolName } Liquidity { AmountCurrencyAInUSD AmountCurrencyBInUSD } Pool { PoolId SmartContract CurrencyA { Symbol } CurrencyB { Symbol } } } } } } ``` --- ## Most active pools and price ranges (1-hour window) **Momentum / volatility screening:** group the last hour of pool events per pool and get update count, price high/low/last, and current TVL — a volatility screener in a single query. The `Field(maximum: OtherField)` syntax is an **argmax**: it returns this field's value on the row where `OtherField` is highest. So `AtoBPriceInUSD(maximum: PoolEvent_AtoBPriceInUSD)` is the window high, and `AtoBPriceInUSD(maximum: Block_Number)` is the **latest** price (value at the highest block). ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } PoolEvent: { AtoBPriceInUSD: { gt: 0 } Liquidity: { AmountCurrencyAInUSD: { gt: 1000 } } } } limit: { count: 10 } orderBy: { descendingByField: "updates" } ) { PoolEvent { Dex { ProtocolName } Pool { SmartContract PoolId CurrencyA { Symbol } CurrencyB { Symbol } } } updates: count price_high: PoolEvent { AtoBPriceInUSD(maximum: PoolEvent_AtoBPriceInUSD) } price_low: PoolEvent { AtoBPriceInUSD(minimum: PoolEvent_AtoBPriceInUSD) } price_last: PoolEvent { AtoBPriceInUSD(maximum: Block_Number) } price_avg: average(of: PoolEvent_AtoBPriceInUSD) tvl_last: PoolEvent { Liquidity { AmountCurrencyAInUSD(maximum: Block_Number) } } } } } ``` Compute swing % client-side as `(high − low) ÷ low`; use absolute `since:`/`till:` timestamps if you prefer fixed windows. --- ## Pool TVL and price time series (5-minute buckets) **Charting / TWAP checks:** bucket one pool's events into intervals with `Time(interval: …)` and take close values via argmax on `Block_Number`. This builds candles for **price and TVL** from pool state — complementary to trade-based OHLCV in [Robinhood Trades](/docs/blockchain/robinhood/robinhood-trades/). Note `orderBy: { descendingByField: "interval_Time" }` — the sort key is the alias plus `_Time`, the name the server generates for the interval field. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32" } } } Block: { Time: { since_relative: { hours_ago: 2 } } } } limit: { count: 24 } orderBy: { descendingByField: "interval_Time" } ) { interval: Block { Time(interval: { count: 5, in: minutes }) } updates: count price_avg: average(of: PoolEvent_BtoAPrice) price_close: PoolEvent { BtoAPrice(maximum: Block_Number) } tvl_eth_close: PoolEvent { Liquidity { AmountCurrencyA(maximum: Block_Number) } } tvl_usd_close: PoolEvent { Liquidity { AmountCurrencyAInUSD(maximum: Block_Number) } } } } } ``` The realtime window only reaches back a limited time — this is for intraday series, not multi-month TVL history. Record the stream to build your own series, or ask about a [Data Store export](https://bitquery.io/datastore) for older data. --- ## Stream liquidity updates Live pool reserve and spot-price updates for bots and alerting, over GraphQL subscriptions. :::warning Filter production streams Robinhood pool events are frequent. Prefer filters by `PoolId`, `SmartContract`, token, or protocol in production. ::: ```graphql subscription { EVM(network: robinhood) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } } Transaction { Hash } } } } ``` :::tip WebSocket connection Connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol (`connection_init` → `connection_ack` → `subscribe`). See [WebSocket authentication](/docs/authorization/websocket/). ::: :::tip Prefer Kafka for the firehose Consuming pool updates at firehose scale? Bitquery also delivers Robinhood DEX data as **Kafka streams** (protobuf topic `robinhood.dextrades.proto`) with consumer-group scaling and replay. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). ::: --- ## Slippage and price impact `DEXPoolSlippages` answers: *how much can I trade before I exceed X% price impact?* **In this section:** [Latest rows](#latest-slippage-rows) · [Curve for one pool](#slippage-curve-for-one-pool-all-bps-levels) · [1% tolerance](#fixed-tolerance-1--100-bps) · [USDG at 1%](#usdg-pools-at-1-slippage) · [Deepest pools](#deepest-pools-by-executable-trade-size) · [Capacity screeners](#whale-capacity-and-thin-liquidity-screeners) · [Pool stream](#stream-slippage-for-a-pool) · [Screener stream](#stream-a-network-wide-slippage-screener) Each row is one slippage level for a pool update: | `SlippageBasisPoints` | Tolerance | | --- | --- | | 10 | 0.1% | | 50 | 0.5% | | 100 | 1% | | 200 | 2% | | 500 | 5% | | 1000 | 10% | | 0 | Spot / zero-slippage reference (often empty max amounts) | For each level you get **AtoB** and **BtoA**: - **`MaxAmountIn` / `MaxAmountInInUSD`** — largest input that stays within that slippage - **`MinAmountOut` / `MinAmountOutInUSD`** — minimum output at that size - **`Price` / `PriceInUSD`** — average execution price for that size ### Latest slippage rows ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolSlippages( limit: { count: 12 } orderBy: { descending: Block_Time } ) { Block { Time Number } Price { SlippageBasisPoints AtoB { MaxAmountIn MaxAmountInInUSD MinAmountOut MinAmountOutInUSD Price PriceInUSD } BtoA { MaxAmountIn MaxAmountInInUSD MinAmountOut MinAmountOutInUSD Price PriceInUSD } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract Decimals } CurrencyB { Name Symbol SmartContract Decimals } } Dex { SmartContract ProtocolName ProtocolVersion ProtocolFamily } } Transaction { Hash From To } } } } ``` ### Slippage curve for one pool (all bps levels) Pull recent levels for a V4 `PoolId`. Compare `MaxAmountIn` across 10 → 1000 bps to build a depth curve. Rows for all seven levels (0, 10, 50, 100, 200, 500, 1000) come back interleaved. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolSlippages( where: { Price: { Pool: { PoolId: { is: "0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32" } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Price { SlippageBasisPoints AtoB { MaxAmountIn MaxAmountInInUSD MinAmountOut Price } BtoA { MaxAmountIn MinAmountOut MinAmountOutInUSD Price } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } Dex { ProtocolName } } } } } ``` ### Fixed tolerance (1% = 100 bps) `SlippageBasisPoints` filters use **Int** (`eq: 100`), not strings. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolSlippages( where: { Price: { Pool: { PoolId: { is: "0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32" } } SlippageBasisPoints: { eq: 100 } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Price { SlippageBasisPoints AtoB { MaxAmountIn MaxAmountInInUSD MinAmountOut Price } BtoA { MaxAmountIn MinAmountOut MinAmountOutInUSD Price } } } } } ``` ### USDG pools at 1% slippage **Payments / stablecoin routing:** size trades against USDG pairs at a fixed tolerance. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolSlippages( where: { any: [ { Price: { Pool: { CurrencyA: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } } } } { Price: { Pool: { CurrencyB: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } } } } ] Price: { SlippageBasisPoints: { eq: 100 } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Price { SlippageBasisPoints AtoB { MaxAmountIn MaxAmountInInUSD MinAmountOut } BtoA { MaxAmountIn MinAmountOut MinAmountOutInUSD } Pool { PoolId SmartContract CurrencyA { Symbol SmartContract } CurrencyB { Symbol SmartContract } } Dex { ProtocolName ProtocolVersion } } } } } ``` ### Deepest pools by executable trade size **Venue routing:** rank pools by how much you can actually trade at 1% impact. Ranking the **raw** `MaxAmountIn` on native-ETH-quoted pools (`CurrencyA` = `0x`) gives a depth leaderboard in ETH terms — "which pool absorbs the most ETH at 1%". One row per pool via composite `limitBy`. ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolSlippages( where: { Price: { SlippageBasisPoints: { eq: 100 } Pool: { CurrencyA: { SmartContract: { is: "0x" } } } AtoB: { MaxAmountIn: { gt: 0.1, lt: 10000 } } } } limitBy: { by: [Price_Pool_SmartContract, Price_Pool_PoolId], count: 1 } limit: { count: 10 } orderBy: { descending: Price_AtoB_MaxAmountIn } ) { Block { Time } Price { SlippageBasisPoints AtoB { MaxAmountIn MaxAmountInInUSD MinAmountOut } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol Name SmartContract } } Dex { ProtocolName } } } } } ``` :::warning Degenerate pools report absurd depth One-sided or broken V4 pools can report absurd capacity — millions of ETH, USD values in the trillions — because their curve math degenerates. Keep a sanity band on `MaxAmountIn`, and cross-check any surprising top row against the pool's actual reserves in `DEXPoolEvents` before routing. The same applies to `MaxAmountInInUSD` screeners: long-tail token USD prices can be wildly inflated. ::: ### Whale capacity and thin liquidity screeners Flip one filter to screen from either side. Pools that can absorb **at least $50k** at 1% (whale-tradeable): ```graphql { EVM(network: robinhood, dataset: realtime) { DEXPoolSlippages( where: { Price: { SlippageBasisPoints: { eq: 100 } AtoB: { MaxAmountInInUSD: { ge: 50000 } } } } limitBy: { by: [Price_Pool_SmartContract, Price_Pool_PoolId], count: 1 } limit: { count: 20 } orderBy: { descending: Price_AtoB_MaxAmountInInUSD } ) { Block { Time } Price { SlippageBasisPoints AtoB { MaxAmountInInUSD MinAmountOutInUSD } Pool { PoolId SmartContract CurrencyA { Symbol } CurrencyB { Symbol } } Dex { ProtocolName } } } } } ``` For a **thin-liquidity warning list** — pools where even $1k of input breaches 1% impact — change the filter to `AtoB: { MaxAmountInInUSD: { lt: 1000, gt: 0 } }` and order `ascending`. Remember the USD-inflation caveat above when reading either screen. ### Stream slippage for a pool ```graphql subscription { EVM(network: robinhood) { DEXPoolSlippages( where: { Price: { Pool: { PoolId: { is: "0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32" } } SlippageBasisPoints: { in: [10, 50, 100, 200, 500, 1000] } } } ) { Block { Time Number } Price { SlippageBasisPoints AtoB { MaxAmountIn MaxAmountInInUSD MinAmountOut Price } BtoA { MaxAmountIn MinAmountOut MinAmountOutInUSD Price } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } } } } } ``` ### Stream a network-wide slippage screener Drop the pool filter and keep one tolerance to watch **every pool's 1% depth** as it changes — the push-based version of the screeners above. ```graphql subscription { EVM(network: robinhood) { DEXPoolSlippages( where: { Price: { SlippageBasisPoints: { eq: 100 } } } ) { Block { Time } Price { SlippageBasisPoints AtoB { MaxAmountIn MaxAmountInInUSD MinAmountOut } Pool { PoolId SmartContract CurrencyA { Symbol } CurrencyB { Symbol } } Dex { ProtocolName } } } } } ``` --- ## Useful product patterns | Goal | Cube | Approach | | --- | --- | --- | | Live reserve / TVL monitor | `DEXPoolEvents` | Filter by `PoolId` or token; track `Liquidity.*` on the **short realtime window** or via subscription (not long archive history) | | Price watchlist / screener page | `DEXPoolEvents` | Composite `limitBy` → one latest row per pool ([query](#live-price-watchlist-latest-state-per-pool)) | | Volatility / momentum screen | `DEXPoolEvents` | Argmax high/low/last per pool over `since_relative` window ([query](#most-active-pools-and-price-ranges-1-hour-window)) | | Intraday TVL & price candles | `DEXPoolEvents` | `Time(interval: …)` buckets + argmax close ([query](#pool-tvl-and-price-time-series-5-minute-buckets)) | | Liquidity add/remove alerts | `DEXPoolEvents` | Stream a pool; alert when reserves jump or drain | | Trade sizing / RFQ | `DEXPoolSlippages` | Pick bps (e.g. 100); read `MaxAmountIn` / `MinAmountOut` for AtoB and BtoA | | Best venue for a size | `DEXPoolSlippages` | Rank raw `MaxAmountIn` at fixed bps with a sanity cap ([query](#deepest-pools-by-executable-trade-size)) | | Whale capacity / thin-liquidity flags | `DEXPoolSlippages` | `MaxAmountInInUSD` `ge` / `lt` screeners at 100 bps | | RWA / tokenized stock depth (AAPL, NVDA) | both | Token filter on the stock token; pair with USDG/ETH pools | | Protocol share | `DEXPoolEvents` | Aggregate `count` by `Dex.ProtocolName` (realtime window only) | :::tip Interpreting a slippage row If you want to sell up to `MaxAmountIn` of CurrencyA for CurrencyB at 1% impact, use the **AtoB** fields on the `SlippageBasisPoints: 100` row. `MinAmountOut` is the guaranteed CurrencyB received at that size. See also the [slippage FAQ](/docs/API-Blog/slippage-faq-using-dexpool-stream/). ::: --- ## Response fields (quick reference) ### DEXPoolEvents | Group | Fields | | --- | --- | | **Liquidity** | `AmountCurrencyA`, `AmountCurrencyB`, `AmountCurrencyAInUSD`, `AmountCurrencyBInUSD` | | **Prices** | `AtoBPrice` (A per 1 B), `BtoAPrice` (B per 1 A), `AtoBPriceInUSD` (USD price of B), `BtoAPriceInUSD` (USD price of A) — see [How to read pool prices](#how-to-read-pool-prices) | | **Pool** | `PoolId`, `SmartContract`, `CurrencyA.*`, `CurrencyB.*` | | **Dex** | `ProtocolName`, `ProtocolVersion`, `ProtocolFamily`, `SmartContract` | ### DEXPoolSlippages | Group | Fields | | --- | --- | | **Level** | `SlippageBasisPoints` | | **AtoB / BtoA** | `MaxAmountIn`, `MinAmountOut`, `Price`, plus `*InUSD` variants | | **Pool / Dex** | Same identity fields as pool events | Aggregations available on both cubes: `count` (with `distinct:`/`if:`), `sum`, `average`, `median`, `quantile`, `standard_deviation`, `uniq`, plus per-field argmax/argmin via `Field(maximum: Other_Field)` / `Field(minimum: Other_Field)`. --- ## Tips 1. Always use **`dataset: realtime`** for Robinhood liquidity and slippage (archive/combined are not supported). Use these cubes for **live and short-window** monitoring, not multi-month TVL history. 2. A pool's identity is the pair **(`Pool.SmartContract`, `Pool.PoolId`)**: filter with `SmartContract` for V2/V3 and `PoolId` for V4, and always deduplicate mixed sets with the composite `limitBy` — `by: [PoolEvent_Pool_SmartContract, PoolEvent_Pool_PoolId]` (V2/V3 pools all share `PoolId: "0x"`; V4 pools all share the manager contract). 3. Use **Float** for USD liquidity filters (`gt: 10000`) and **Int** for `SlippageBasisPoints` (`eq: 100`). 4. Treat `*InUSD: 0` as "USD unknown" (common on V2/V3 and non-ETH-quoted rows) and treat extreme `*InUSD` values on long-tail tokens as suspect — size with raw token amounts and sanity caps, and derive prices from `AmountCurrencyAInUSD ÷ AmountCurrencyA` when needed. 5. Window queries with `Block: { Time: { since_relative: { hours_ago: 1 } } }` (or absolute `since:`/`till:` ISO timestamps). 6. Filter WebSocket subscriptions by pool, token, or protocol — unfiltered streams are very noisy. Connect with the `graphql-transport-ws` subprotocol and the token in the URL ([WebSocket auth](/docs/authorization/websocket/)). 7. Symbol filters (`Currency.Symbol`) are handy for discovery but **symbols are not unique** — pin `SmartContract` addresses in production. 8. Combine with [Robinhood Trades](/docs/blockchain/robinhood/robinhood-trades/) for execution prints and [Transfers](/docs/blockchain/robinhood/robinhood-transfers/) for token movements around LP activity. --- ## FAQ ### Is Robinhood liquidity available in archive history? No. `DEXPoolEvents` and `DEXPoolSlippages` on Robinhood work only with the **realtime** dataset. Archive and combined queries error. Build live monitors and short-window views here — not long historical TVL series from these cubes. ### How do I choose between DEXPoolEvents and DEXPoolSlippages? Use **DEXPoolEvents** for current reserves and spot price after each pool update. Use **DEXPoolSlippages** when you need trade-size capacity and price impact at standard slippage tolerances. ### How do I size a swap with 1% max impact? Query `DEXPoolSlippages` with `SlippageBasisPoints: { eq: 100 }` for your pool. Read `AtoB.MaxAmountIn` / `MinAmountOut` (or `BtoA` for the opposite direction). ### How do I find the deepest pool to trade a token? Rank `DEXPoolSlippages` rows at a fixed tolerance by `MaxAmountIn` (raw units, with a sanity cap) or `MaxAmountInInUSD`, deduplicated per pool — see [Deepest pools by executable trade size](#deepest-pools-by-executable-trade-size). Cross-check winners against reserves in `DEXPoolEvents`. ### Can I get a TVL or price time series for a Robinhood pool? Yes, within the realtime window: bucket `DEXPoolEvents` with `Time(interval: { count: 5, in: minutes })` and take closes via `Field(maximum: Block_Number)` — see [the time-series query](#pool-tvl-and-price-time-series-5-minute-buckets). For longer trade-based OHLCV history, use the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades/). ### Which DEX protocols run on Robinhood? Pool events come from `uniswap_v3`, `uniswap_v4`, `uniswap_v2`, plus `pancake_swap_v3` and `pancakeswap_infinity`. Run the [protocol breakdown query](#protocol-activity-breakdown) for the current split. ### Why are some USD fields 0 — or absurdly large? USD enrichment covers mainly native-ETH-quoted pools; V2/V3 and exotic pairs often report `0`, and broken or one-sided pools can report inflated USD capacity (even trillion-dollar readings on meme pools). Prefer raw token amounts with sanity bounds, and derive USD from reserves where needed. ### Why is PoolId `0x` on some rows? V2/V3 pools leave `PoolId` empty and identify the pool via `Pool.SmartContract`. V4 pools use a non-zero `PoolId` under a shared manager contract. --- ## DEX Slippage FAQ: Using the DEX Pools Stream URL: https://docs.bitquery.io/docs/API-Blog/slippage-faq-using-dexpool-stream/ Slippage FAQ for DEX swaps: use DEXPool stream price tables to set amountOutMin, handle removeLiquidity, token decimals, front-running and price impact. # Slippage FAQ: Calculating Necessary Slippage for DEX Swaps Using Bitquery DEXPool Stream This FAQ addresses common developer questions about calculating necessary slippage before executing swaps or withdrawing liquidity on DEXs from smart contracts. Instead of guessing or using trial-and-error, you can use Bitquery's DEXPool stream data to programmatically determine the appropriate slippage tolerance. ## What is the Best Way to Calculate Necessary Slippage Before Making a Swap from a Smart Contract? Instead of hardcoding slippage tolerances or using trial-and-error, you can calculate necessary slippage programmatically using Bitquery's DEXPool stream data. The stream provides pre-calculated price tables showing exactly how much slippage to expect for different trade sizes. **The Problem with Fixed Slippage:** Many developers hardcode slippage tolerances (e.g., 1% or 5%) in their contracts, but this can lead to: - Failed transactions if liquidity drops (slippage too low) - Unnecessary losses if liquidity is high (slippage too high) - Front-running vulnerabilities when slippage tolerance is set too high **Solution Using Bitquery DEXPool Stream:** The DEXPool stream's `PoolPriceTable` contains `AtoBPrices` and `BtoAPrices` arrays with pre-calculated slippage data at multiple levels (0.1%, 0.5%, 1%, 2%, 5%, 10%). By querying this data before executing a swap, you can: 1. Find the appropriate slippage level for your trade size 2. Get the guaranteed minimum output amount (`MinAmountOut`) for that slippage level 3. Pass this as the `amountOutMin` parameter to functions like `swapExactTokensForTokens` or `removeLiquidity` **Example from DEXPool Stream Data:** ```json { "PoolPriceTable": { "AtoBPrices": [ { "SlippageBasisPoints": 10, "MaxAmountIn": 2557952147, "MinAmountOut": 860478002991619427, "Price": 0.0003364734002389014 }, { "SlippageBasisPoints": 100, "MaxAmountIn": 25456674083, "MinAmountOut": 8465959707294551328, "Price": 0.00033264263765886426 } ] } } ``` **Important:** All amounts (`MaxAmountIn`, `MinAmountOut`) are in raw units (smallest token units), NOT decimal-adjusted. For example, if CurrencyA is USDC (6 decimals), `MaxAmountIn: 2557952147` = 2,557.952147 USDC. If CurrencyB is WETH (18 decimals), `MinAmountOut: 860478002991619427` = 0.860478002991619427 WETH. If you want to swap 25,456 USDC (25,456,000,000 in raw units with 6 decimals), check the `AtoBPrices` array: - At 0.1% slippage (10 basis points): `MaxAmountIn: 2557952147` (2,557.95 USDC) - your trade is too large - At 1% slippage (100 basis points): `MaxAmountIn: 25456674083` (25,456.67 USDC) - your trade fits! Use `MinAmountOut: 8465959707294551328` as your `amountOutMin` **Note:** All `MaxAmountIn` and `MinAmountOut` values in the DEXPool stream are in raw units (smallest token units), not decimal-adjusted. `MaxAmountIn` is in CurrencyA's raw units (e.g., USDC with 6 decimals), and `MinAmountOut` is in CurrencyB's raw units (e.g., WETH with 18 decimals). ## How Do I Determine Slippage Tolerance Programmatically Instead of Guessing? You can determine slippage tolerance programmatically by: 1. **Query DEXPool Stream**: Get the latest `PoolPriceTable` for your target pool 2. **Find Your Trade Size**: Check which `SlippageBasisPoints` level has a `MaxAmountIn` that accommodates your trade 3. **Extract MinAmountOut**: Use the `MinAmountOut` value from that slippage level 4. **Calculate Tolerance**: `slippageTolerance = SlippageBasisPoints / 10000` (e.g., 100 = 1%) **Using the Data Structure:** The DEXPool stream data structure is: ``` PoolEvents[].PoolPriceTable.AtoBPrices[] (or BtoAPrices[]) - SlippageBasisPoints: 10, 50, 100, 200, 500, 1000 (0.1%, 0.5%, 1%, 2%, 5%, 10%) - MaxAmountIn: Maximum input amount at this slippage level - MinAmountOut: Guaranteed minimum output (use as amountOutMin) - Price: Average execution price at this slippage level ``` **Implementation Approach:** ```javascript // Pseudo-code example function calculateSlippageTolerance(tradeAmount, poolPriceTable) { const atoBPrices = poolPriceTable.AtoBPrices; // Find the lowest slippage level that can handle your trade for (const priceData of atoBPrices) { if (tradeAmount <= priceData.MaxAmountIn) { return { slippageBasisPoints: priceData.SlippageBasisPoints, slippageTolerance: priceData.SlippageBasisPoints / 10000, // Decimal format (0.01 for 1%) minAmountOut: priceData.MinAmountOut, price: priceData.Price, }; } } // Trade too large for even 10% slippage return null; } ``` ## How is Slippage Calculated in AMMs Like Uniswap? Slippage in Automated Market Makers (AMMs) is calculated based on the constant product formula (x \* y = k) and the liquidity available in the pool. However, manually calculating this is complex, especially for concentrated liquidity pools (Uniswap V3/V4). **Traditional Calculation:** The constant product formula means that when you swap tokens: - Removing tokens from one side increases the price - The larger your trade relative to pool liquidity, the higher the slippage - Formula: `(x + Δx) * (y - Δy) = k` where k is constant **Why Manual Calculation is Difficult:** - **Uniswap V2**: Requires current reserves and applying the constant product formula - **Uniswap V3/V4**: Much more complex due to concentrated liquidity, ticks, and price ranges - **Real-time updates**: Pool state changes with every trade, making calculations stale quickly **How Bitquery DEXPool Stream Solves This:** The DEXPool stream provides pre-calculated slippage data by simulating swaps through the pool's initialized ticks. This gives you: - **Accurate calculations**: Done by simulating actual swaps through pool ticks - **Real-time data**: Updates whenever liquidity changes (Mint, Burn, Swap events) - **Multiple slippage levels**: Six different slippage scenarios (0.1%, 0.5%, 1%, 2%, 5%, 10%) - **No manual math**: Just query and use the `MinAmountOut` value directly ## How Can I Use DEXPool Stream Data to Set amountOutMin for swapExactTokensForTokens? The `swapExactTokensForTokens` function requires an `amountOutMin` parameter, which is the minimum amount of output tokens you're willing to accept. You can get this value directly from the DEXPool stream's `PoolPriceTable`. **Step-by-Step Process:** 1. **Query DEXPool Stream** for your target pool address 2. **Access PoolPriceTable**: Get `PoolPriceTable.AtoBPrices` (swapping CurrencyA → CurrencyB) or `BtoAPrices` (swapping CurrencyB → CurrencyA) 3. **Find Matching Slippage Level**: Locate the entry where `MaxAmountIn >= yourTradeAmount` 4. **Use MinAmountOut**: The `MinAmountOut` field is your `amountOutMin` parameter **Example from Real Data:** For a USDC/WETH pool (Uniswap V4), if you want to swap 25,000 USDC (with 6 decimals = 25000000000 in raw units): ```json { "PoolPriceTable": { "AtoBPrices": [ { "SlippageBasisPoints": 100, "MaxAmountIn": 25456674083, "MinAmountOut": 8465959707294551328, "Price": 0.00033264263765886426 } ] } } ``` Since 25000000000 < 25456674083 (your trade amount is less than MaxAmountIn), this slippage level (1%) works. **Important Note:** The `MinAmountOut: 8465959707294551328` in the price table is the minimum output for a trade at `MaxAmountIn` (25,456.67 USDC). For a smaller trade like 25,000 USDC, the actual minimum output would be proportionally less. Using the table's `MinAmountOut` is conservative (safer) but may cause transactions to fail if the price moves. For precise calculations, you'd need to calculate the proportional minimum based on your actual trade size, but using the table value provides a safe upper bound. `MaxAmountIn: 25456674083` = 25,456.67 USDC in human-readable format (raw units ÷ 10^6). Your trade of 25,000 USDC fits within this limit. **In Your Smart Contract:** ```solidity // After querying DEXPool stream off-chain uint256 amountOutMin = 8465959707294551328; // From MinAmountOut field IUniswapV2Router02(router).swapExactTokensForTokens( amountIn, amountOutMin, // Use MinAmountOut from DEXPool stream path, to, deadline ); ``` ## How Do I Calculate Slippage for Removing Liquidity (removeLiquidity)? Similar to swaps, you can use DEXPool stream data to calculate slippage when removing liquidity. The `PoolPriceTable` shows liquidity depth, which helps determine how removing liquidity will affect token amounts received. **Understanding Liquidity Removal Slippage:** When you remove liquidity, you receive both tokens in the pair. The ratio depends on: - Current pool reserves (available in `Liquidity.AmountCurrencyA` and `AmountCurrencyB`) - Your liquidity share (LP token balance) - Current pool price **Using DEXPool Stream Data:** The DEXPool stream provides: - `Liquidity.AmountCurrencyA`: Current reserves of CurrencyA in the pool - `Liquidity.AmountCurrencyB`: Current reserves of CurrencyB in the pool - `PoolPriceTable.AtoBPrice`: Current spot price (CurrencyA per CurrencyB) - `PoolPriceTable.BtoAPrice`: Current spot price (CurrencyB per CurrencyA) **Calculating Expected Output:** 1. Calculate your share: `yourShare = yourLPTokens / totalLPTokens` 2. Expected CurrencyA: `expectedA = Liquidity.AmountCurrencyA * yourShare` 3. Expected CurrencyB: `expectedB = Liquidity.AmountCurrencyB * yourShare` 4. Apply slippage tolerance: `minA = expectedA * (1 - slippageTolerance)`, `minB = expectedB * (1 - slippageTolerance)` **Example:** If the pool has: - `AmountCurrencyA: 1000000000000` (1M USDC with 6 decimals) - `AmountCurrencyB: 337656994815915800` (0.337 WETH with 18 decimals) - Your LP tokens represent 1% of the pool Expected output: - CurrencyA: `1000000000000 * 0.01 = 10000000000` (10,000 USDC) - CurrencyB: `337656994815915800 * 0.01 = 3376569948159158` (0.003376 WETH) With 1% slippage tolerance: - `minAmountA = 10000000000 * 0.99 = 9900000000` - `minAmountB = 3376569948159158 * 0.99 = 3342804248677576` ## What's the Difference Between Price Impact and Slippage Tolerance? **Price Impact** is the change in the pool's price caused by your trade. It's calculated based on the AMM formula and current liquidity. **Slippage Tolerance** is the maximum price movement you're willing to accept - it's a parameter you set in your transaction. **In Practice:** - **Price Impact**: `(Price After Trade - Price Before Trade) / Price Before Trade` - **Slippage Tolerance**: The maximum price movement you allow (e.g., 1% means you'll accept up to 1% worse price) **How DEXPool Stream Helps:** The `PoolPriceTable` shows both: - `Price`: Average execution price at different slippage levels (represents price impact) - `SlippageBasisPoints`: The slippage tolerance level - `MinAmountOut`: Guaranteed minimum output at that slippage tolerance By comparing the `Price` field across different `SlippageBasisPoints` levels, you can see how price impact increases with larger trades. **Example from Data:** ```json { "AtoBPrices": [ { "SlippageBasisPoints": 10, "Price": 0.0003364734002389014, "MaxAmountIn": 2557952147 }, { "SlippageBasisPoints": 1000, "Price": 0.00030166094074957073, "MaxAmountIn": 278317227427 } ] } ``` At 0.1% slippage: Price = 0.00033647 (better price, smaller max trade) At 10% slippage: Price = 0.00030166 (worse price, larger max trade) The price difference shows the price impact: `(0.00033647 - 0.00030166) / 0.00033647 ≈ 10.34%` ## How Can I Avoid Front-Running by Setting Appropriate Slippage? Setting slippage tolerance too high can make you vulnerable to front-running bots that exploit the gap between your tolerance and actual price impact. Using DEXPool stream data helps you set precise slippage tolerances. **The Front-Running Problem:** If you set slippage tolerance to 10% but the actual price impact is only 1%, front-running bots can: 1. See your transaction with high slippage tolerance 2. Execute trades that push the price up by 9% 3. Your transaction still executes (within 10% tolerance) 4. You receive much less than expected **Solution Using DEXPool Stream:** 1. **Query Current Pool State**: Get latest `PoolPriceTable` from DEXPool stream 2. **Find Exact Slippage Needed**: Check which `SlippageBasisPoints` level matches your trade size 3. **Add Small Buffer**: Add 0.1-0.2% buffer for execution delay 4. **Set Precise Tolerance**: Use the exact slippage level instead of guessing **Example:** For a trade of 25,456 USDC (25,456,000,000 in raw units with 6 decimals): - DEXPool stream shows: At 1% slippage (100 basis points), `MaxAmountIn: 25456674083` (25,456.67 USDC) fits your trade - Set slippage tolerance to 1.2% (add 0.2% buffer) - This prevents front-runners from exploiting a large gap between tolerance and actual impact ## How Do I Interpret the PoolPriceTable Data Structure? The `PoolPriceTable` in DEXPool stream contains pre-calculated price data for swaps in both directions: **Structure:** ```json { "PoolPriceTable": { "AtoBPrices": [ { "SlippageBasisPoints": 10, "MaxAmountIn": 2557952147, "MinAmountOut": 860478002991619427, "Price": 0.0003364734002389014 } // ... more levels ], "BtoAPrices": [ { "SlippageBasisPoints": 10, "MaxAmountIn": 824929789949801466, "MinAmountOut": 2434012699, "Price": 2951.27197265625 } // ... more levels ], "AtoBPrice": 2961.585205078125, "BtoAPrice": 0.0003376569948159158 } } ``` **Field Explanations:** - **`AtoBPrices`**: Array for swapping CurrencyA → CurrencyB (e.g., USDC → WETH) - **`BtoAPrices`**: Array for swapping CurrencyB → CurrencyA (e.g., WETH → USDC) - **`SlippageBasisPoints`**: Slippage tolerance in basis points (10 = 0.1%, 100 = 1%, 1000 = 10%) - **`MaxAmountIn`**: Maximum input amount you can swap at this slippage level (in CurrencyA's raw units/smallest units, NOT decimal-adjusted) - **`MinAmountOut`**: Guaranteed minimum output amount (in CurrencyB's raw units/smallest units, NOT decimal-adjusted. Use directly as `amountOutMin` in your swap function) - **`Price`**: Average execution price at this slippage level - **`AtoBPrice`**: Current spot price (CurrencyA per CurrencyB) - **`BtoAPrice`**: Current spot price (CurrencyB per CurrencyA) **Real-World Example:** For a USDC/WETH pool where CurrencyA = USDC (6 decimals) and CurrencyB = WETH (18 decimals): ```json { "SlippageBasisPoints": 100, "MaxAmountIn": 25456674083, "MinAmountOut": 8465959707294551328, "Price": 0.00033264263765886426 } ``` This means: - At 1% slippage tolerance, you can swap up to 25,456.674083 USDC - You're guaranteed to receive at least 8.465959707294551328 WETH - The average execution price is 0.00033264 USDC per WETH (or ~3005.6 USDC per WETH) ## How Often Does DEXPool Stream Update and How Fresh is the Data? DEXPool stream updates in real-time whenever liquidity-changing events occur in the pool. The data is as fresh as the latest on-chain event. **Update Triggers:** **Uniswap V2:** - `Swap` events (every trade) - `Mint` events (liquidity added) - `Burn` events (liquidity removed) **Uniswap V3:** - `Swap` events - `Mint` events (liquidity positions added) - `Burn` events (liquidity positions removed) **Uniswap V4:** - `Swap` events - `ModifyLiquidity` events **Data Freshness:** Each event triggers a new DEXPool record with: - Updated `Liquidity.AmountCurrencyA` and `AmountCurrencyB` - Recalculated `PoolPriceTable` with new slippage data - Latest `AtoBPrice` and `BtoAPrice` spot prices This ensures the slippage calculations reflect the current pool state, not stale data from hours ago. **Best Practice:** For time-sensitive operations, query the DEXPool stream immediately before executing your transaction to get the most current slippage data. ## Can I Use DEXPool Stream to Compare Slippage Across Multiple Pools? Yes! You can query multiple pools simultaneously and compare their `PoolPriceTable` data to find the pool with the best execution (lowest slippage) for your trade size. **Comparison Strategy:** 1. **Query Multiple Pools**: Get DEXPool stream data for all pools trading your token pair 2. **Compare MaxAmountIn**: At your desired slippage level, see which pool can handle larger trades 3. **Compare Prices**: Look at the `Price` field to see which pool offers better execution price 4. **Check Liquidity**: Higher `Liquidity.AmountCurrencyA` and `AmountCurrencyB` usually means lower slippage **Example Comparison:** Pool A (Uniswap V3): ```json { "AtoBPrices": [ { "SlippageBasisPoints": 100, "MaxAmountIn": 25456674083, "MinAmountOut": 8465959707294551328, "Price": 0.00033264263765886426 } ] } ``` Pool B (Uniswap V2): ```json { "AtoBPrices": [ { "SlippageBasisPoints": 100, "MaxAmountIn": 15000000000, "MinAmountOut": 5000000000000000000, "Price": 0.0003333333333333333 } ] } ``` For a swap of 20,000 USDC (20,000,000,000 in raw units with 6 decimals): - Pool A: Can handle it (MaxAmountIn: 25456674083 raw units = 25,456.67 USDC > 20,000 USDC), better price (0.00033264) - Pool B: Cannot handle it (MaxAmountIn: 15000000000 raw units = 15,000 USDC < 20,000 USDC) at 1% slippage Pool A is better for this trade size. ## How Do I Handle Different Token Decimals When Using MinAmountOut? The `MinAmountOut` value in DEXPool stream is in the token's smallest unit (raw amount), so you need to account for token decimals when using it in your smart contract. **Understanding Decimals:** - USDC: 6 decimals (1 USDC = 1,000,000 raw units) - WETH: 18 decimals (1 WETH = 1,000,000,000,000,000,000 raw units) **Example from Data:** ```json { "Pool": { "CurrencyA": { "Symbol": "USDC", "Decimals": 6 }, "CurrencyB": { "Symbol": "WETH", "Decimals": 18 } }, "PoolPriceTable": { "AtoBPrices": [ { "MinAmountOut": 8465959707294551328 } ] } } ``` The `MinAmountOut: 8465959707294551328` is in WETH's raw units (18 decimals). To convert to human-readable: `8465959707294551328 / 10^18 = 8.465959707294551328 WETH` **In Your Smart Contract:** The `amountOutMin` parameter expects the raw amount (smallest units), so you can use `MinAmountOut` directly: ```solidity // MinAmountOut from DEXPool stream is already in correct format uint256 amountOutMin = 8465959707294551328; // Direct use, no conversion needed IUniswapV2Router02(router).swapExactTokensForTokens( amountIn, amountOutMin, // Use MinAmountOut value directly path, to, deadline ); ``` The DEXPool stream data includes `CurrencyA.Decimals` and `CurrencyB.Decimals` fields so you can verify the decimal places if needed. ## What If My Trade Size Exceeds All MaxAmountIn Values in the Price Table? If your trade size is larger than the highest `MaxAmountIn` value (even at 10% slippage), you have several options: **Option 1: Split the Trade** Break your large trade into smaller chunks that fit within the `MaxAmountIn` limits. Execute multiple swaps sequentially. **Option 2: Accept Higher Slippage (Not Recommended)** You could set slippage tolerance higher than 10%, but this exposes you to significant price impact and front-running risks. **Option 3: Wait for Better Liquidity** Monitor the DEXPool stream - when liquidity increases (higher `Liquidity.AmountCurrencyA`/`AmountCurrencyB`), the `MaxAmountIn` values will increase, allowing larger trades. **Option 4: Use Multiple Pools/Routes** Route your trade through multiple pools or use aggregation protocols that split trades across pools automatically. **Using DEXPool Stream to Monitor:** Subscribe to DEXPool stream updates for your target pool. When you see `Liquidity.AmountCurrencyA` and `AmountCurrencyB` increase, check if the new `MaxAmountIn` values can accommodate your trade size. ## Additional Resources - [DEXPools Cube Documentation](/docs/cubes/evm-dexpool/) - Complete guide to DEXPool data structure and concepts - [Bitquery IDE](https://ide.bitquery.io/) - Query DEXPool data in real-time - [Kafka Data Samples](https://github.com/bitquery/kafka-data-sample/blob/main/evm/eth_dexpools.json) - Sample DEXPool stream data structure - [EVM DEXPool Stream Documentation](/docs/cubes/evm-dexpool/) - Understanding when DEXPool records are emitted --- ## DEX Trades Cube URL: https://docs.bitquery.io/docs/cubes/dextrades/ Use Bitquery’s DEX Trades cube to query swap-level DEX activity with filters, aggregates, and GraphQL examples for multi-chain analytics. # DEXTrades Cube :::tip Need real-time data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical data older than ~30 days** (with `dataset: combined` or `archive`), raw per-swap detail, or call / event context. ::: > **Before you start**: Not sure when to use DexTrades vs DexTradesByTokens vs Events vs Calls? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. For a 1-page comparison of these three trade cubes, see [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades). The DEXTrades cube provides comprehensive information about the dex trading data, such as buyer, seller, token prices, pairs, transactions, etc. > **Advanced Usage Note**: This documentation includes advanced patterns for processing DEXTrades data based on production implementations. These patterns help handle complex scenarios like multi-hop swaps, proxy contracts, and proper volume calculations. > Import Note: If there is a trade between 2 addresses, the details in `Buy{}` dropdown are pool details, and the information displayed in the DEXTrades cube is from the pool's perspective. ![Token A to Token B trade pair diagram](/img/tokenAB.png) Let's understand the concept of buyer and seller. Token X and token Y swap as above. If we see the trade from user A's side, then we get the following: - User A becomes the seller of token X. - User A becomes the buyer of token Y. Now, if we see the trade from a user B side, we get the following. - User B becomes the seller of token Y. - User B becomes the buyer of token X. Therefore, buyers and sellers change relatively when the trade sides change. It is important to note that a pool is always involved; whenever any trade occurs between two traders, one must be a pool. Thus, we are considering User B as a pool. ## Understanding DEXTrade Cube data Next, we understand how the Dextrades Cube displays the result: Take this query for example: ```graphql { EVM(network: eth, dataset: archive) { DEXTrades( orderBy: {descending: Block_Time} limit: {count: 50} where: {TransactionStatus: {Success: true}, Block: {Number: {eq: "23674719"}}, Transaction: {Hash: {is: "0x0891b30722d44284d0c110c761190ecd6ad0f33946835bbde164561d847f5c87"}}} ) { Trade { Buy { Buyer Amount Price Currency { SmartContract Name } } Dex { Pair { Name SmartContract } ProtocolName } Sell { Buyer Amount Currency { Name SmartContract } } } Transaction { Hash } } } } ``` Output ```json { "EVM": { "DEXTrades": [ { "Trade": { "Buy": { "Amount": "4002.603343842926485635", "Buyer": "0xad4e4954b2f22525f5c9d7e7182fff9cf251d0f7", "Currency": { "Name": "MUSKITO Token", "SmartContract": "0x7ef790d9bccc87989be0fdb88ffb955bec3d5e92" }, "Price": 6.700259580759855e-9 }, "Dex": { "Pair": { "Name": "Uniswap V2", "SmartContract": "0xad4e4954b2f22525f5c9d7e7182fff9cf251d0f7" }, "ProtocolName": "uniswap_v2" }, "Sell": { "Amount": "0.000026818481402565", "Buyer": "0x5fbf1aba26bf1493cd7677ad4ec25d96a91ab0ec", "Currency": { "Name": "Wrapped Ether", "SmartContract": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } }, "Transaction": { "Hash": "0x0891b30722d44284d0c110c761190ecd6ad0f33946835bbde164561d847f5c87" } } ] } } ``` ### Analyzing the DEXTrades Output Let's break down how DEXTrades presents data from the pool's perspective: **Key Observations:** 1. **Pool Identification**: The `Buy.Buyer` address matches the `Dex.Pair.SmartContract` address. 2. **Buy Side (Pool's Perspective)**: - **Currency**: The token that the pool received (project token) - **Amount**: Quantity of tokens the pool received - **Buyer**: Pool address (the pool is "buying" these tokens) - **Price**: Current trading price per token 3. **Sell Side (Pool's Perspective)**: - **Currency**: The payment token (WETH, stablecoins, etc.) - **Amount**: Quantity of payment tokens the pool gave out - **Buyer**: User address who received the payment tokens **What Actually Happens:** From the **pool's perspective** (which is what DEXTrades shows): - The pool **bought** project tokens (received them from user) - The pool **sold** payment tokens (gave them to user) From the **user's perspective** (the actual trader): - User **sold** project tokens to the pool - User **bought** payment tokens (WETH/stablecoins) in return ## Metrics in DEXTrades Cube Metrics allow for sum, count, average, median, maximum, minimum, and more calculations The count metric can easily retrieve a specific token's total number of trades. [Run this API](https://ide.bitquery.io/Count-of-trade-on-Uniswap-of-pepe) to find the total trades of [PEPE](https://explorer.bitquery.io/ethereum/token/0x6982508145454ce325ddbe47a25d4ec3d2311933) "0x698…" tokens in the [Uniswap v3 factory](https://explorer.bitquery.io/ethereum/token/0x6982508145454ce325ddbe47a25d4ec3d2311933) "0x1f984…" in the ethereum network. ```graphql query MyQuery { EVM(dataset: archive, network: eth) { DEXTradeByTokens( where: {TransactionStatus: {Success: true}, Trade: {Currency: {SmartContract: {is: "0x6982508145454ce325ddbe47a25d4ec3d2311933"}}, Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}}, Block: {Date: {since: "2024-01-01", till: "2024-06-02"}}} ) { total_trades: count } } } ``` ## How Does Bitquery Calculate USD Price for a Token? Bitquery calculates the token price using a simple formula: **UsdPrice of token 1 = amount2 in USD / amount1** **UsdPrice of token 2 = amount1 in USD / amount2** If either of these amounts is missing, the price cannot be determined. To better understand token prices, one must first examine the trade amounts involved. It's important to note that this "price" is not the actual market price of the token, but rather a derivative based on the trade amounts. **Example: BAR/WETH Pair** **BAR Price in USD = WETH amount in USD / Amount of BAR tokens** **WETH Price in USD = BAR amount in USD / Amount of WETH tokens** In this example, the second calculation (WETH Price) may not be accurate because the **BAR amount in USD is unknown**. **Example: WETH/USDT Pair** **USDT Price in USD = WETH amount in USD / Amount of USDT tokens** **WETH Price in USD = USDT amount in USD / Amount of WETH tokens** In this case, both values make sense, as both **WETH** and **USDT** can be valued in USD directly. ## Multi-Hop Trade Detection and Processing When processing DEXTrades data in production applications, it's crucial to handle multi-hop swaps correctly. Multi-hop trades occur when a single transaction contains multiple DEX trades that are part of one logical swap operation (e.g., Token A → WETH → Token B). ### Identifying Multi-Hop Trades Multi-hop trades can be detected by: 1. **Same Transaction Hash**: All trades in a multi-hop swap share the same transaction hash 2. **Sequential Processing**: Trades appear in sequence within the same block following the Trade_Index 3. **Token Chain Logic**: The sell token of one trade matches the buy token of the next ### Processing Strategy For multi-hop trades, use this approach: - **Token Identification**: Use the first hop to identify the actual token being swapped (not the intermediate tokens) - **Volume Calculation**: Use the last hop to determine the final payment amount - **Direction Detection**: Check the signer's role in the final hop to determine if it's a buy or sell ```python # Example pattern for multi-hop detection if tx_hash in processed_transactions: # This is part of a multi-hop swap first_hop = processed_transactions[tx_hash][0] current_hop = trade_data # Last hop seen # Get actual token from first hop (exclude payment tokens) actual_token = get_non_payment_token(first_hop) # Get final volume from last hop payment side final_volume = get_payment_side_amount(current_hop) # Determine buy/sell from signer's role in last hop is_buy = signer_is_buyer_in_final_hop(current_hop, signer) ``` ### Payment Token Classification Different token types require different processing logic: - **Native Tokens**: `0x` (ETH), direct BNB trades - **Wrapped Tokens**: WETH, WBNB - used for volume calculations - **Stablecoins**: USDT, USDC, DAI - also payment tokens ([DEXrabbit Stablecoins](https://dexrabbit.bitquery.io/categories/stablecoins)) - **Other Tokens**: Project tokens, memecoins, etc. (browse themed groups on [DEXrabbit Categories](https://dexrabbit.bitquery.io/categories)) ## Advanced Buyer/Seller Logic and Proxy Contracts ### Understanding BitQuery's Buy/Sell Fields In EVM chains, DEXTrades data, as we see above, the Buy fields represent the pool's events. ### Handling Different Scenarios When processing trades, check multiple scenarios for accurate buyer/seller identification: #### Scenario 1: Direct Signer Matches ```python # Check if signer is directly in buy/sell fields if signer == buy_buyer: # Signer bought the token process_as_buy() elif signer == sell_seller: # Signer sold the token process_as_sell() ``` #### Scenario 2: Proxy Contract Logic When the signer doesn't appear in buyer/seller fields (common with proxy contracts): ```python # Find consistent party across both sides if buy_buyer == sell_seller: # This party appears to buy token and sell payment # BUT for proxy contracts, logic is inverted if signer != buy_buyer: # Signer used proxy -> opposite action process_as_sell() # Inverted logic elif buy_seller == sell_buyer: # This party appears to sell token and buy payment # BUT for proxy contracts, logic is inverted if signer != buy_seller: # Signer used proxy -> opposite action process_as_buy() # Inverted logic ``` ### Trade Type Classification Different trade types require specific handling: #### 1. Native Token Trades ```graphql # Direct BNB/ETH trades (sell_contract = "0x") where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x" } } } } } ``` #### 2. Wrapped Token Trades ```graphql # WETH/WBNB trades where: { Trade: { Buy: { Currency: { SmartContract: { is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" } } } } } ``` #### 3. Token-to-Token Swaps ```graphql # Both sides are tokens (not native/wrapped) where: { Trade: { Buy: { Currency: { SmartContract: { not: "0x" } } }, Sell: { Currency: { SmartContract: { not: "0x" } } } } } ``` ## Common Edge Cases and Filtering Strategies ### Filtering MEV Bots and Unwanted Trades Production applications often need to filter out certain types of trades: ```graphql # Filter out specific MEV bot contracts query FilterMEVBots { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Transaction: { To: { notIn: ["0x802b65b5d9016621e66003aed0b16615093f328b"] } } } ) { # Your trade data } } } ``` ### Handling Zero Value Trades Filter out trades with zero amounts or prices: ```graphql query FilterZeroTrades { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Trade: { Buy: { Amount: { gt: "0" }, PriceInUSD: { gt: 0 } }, Sell: { Amount: { gt: "0" }, PriceInUSD: { gt: 0 } } } } ) { # Your trade data } } } ``` ### Identifying Pool vs Trader Addresses For token-to-token swaps, distinguish between pool addresses and actual traders: ```graphql # Focus on specific signer addresses (real traders) query RealTraders { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Transaction: { Signer: { is: "0x742d35Cc6334C0532925a3b8C836f4b98C6b1e96" } } } ) { Transaction { Signer } Trade { Buy { Buyer Seller } Sell { Buyer Seller } } } } } ``` ### Transaction Status Filtering Always filter for successful transactions: ```graphql query SuccessfulTrades { EVM(dataset: realtime, network: eth) { DEXTrades( where: { TransactionStatus: { Success: true } } ) { # Your trade data } } } ``` ## Video Tutorial | Why PriceInUSD is 0 in Bitquery API response? --- ## DEX Trades on Robinhood Chain — Prices, OHLCV & Live Streams URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-trades/ Robinhood Chain DEX trades API: live trades, USD prices, OHLCV candles, market cap, whale trades, buy/sell pressure, and top traders via Bitquery GraphQL & WebSockets. # DEX Trades on Robinhood Chain — Prices, OHLCV & Live Streams Bitquery exposes **Robinhood** trade and price data through the **Trading** APIs. Use these queries and real-time GraphQL subscriptions to get **live trades, USD prices, OHLCV/K-line candles, market cap, whale trades, top traders, and token leaderboards** on Robinhood — all scoped with the `bid:robinhood` network filter. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). ## Video Tutorial | Robinhood Chain APIs - Real-Time Trades, Transfers & Meme Launches :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending) — new pools, trending tokens, pair lookup and token search - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) - [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity/) - [Robinhood Token Supply API](/docs/blockchain/robinhood/robinhood-token-supply/) - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches/) - [Pons Launchpad API on Robinhood Chain](/docs/blockchain/robinhood/pons-api) — bonding-curve launchpad, graduations, Uniswap v4 pools - [Pools.trade API on Robinhood](/docs/blockchain/robinhood/pools-trade-api) - [Trading data overview](/docs/trading/trading-data-overview/) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api/) - [Crypto Price API](/docs/trading/crypto-price-api/) ::: --- ## Network identifier | Field | Value | Notes | | --- | --- | --- | | `NetworkBid` | `bid:robinhood` | Filter to select Robinhood data (indexed and faster) | | `Network` | `Robinhood` | Filter to select Robinhood data | ### Example tokens used on this page | Item | Value | | --- | --- | | ASSETH (AssetHood, example token) | `0x9077841e155faaf4e4e89470822c2187eeef7777` | | Example pool trading ASSETH | `0xbbaefcfcd7b92ed0df1a3eec22a21ba6beb0b52b` | | MERRY (first-buyers example, a recent Bags launch) | `0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a` | | WETH | `0x0bd7d308f8e1639fab988df18a8011f41eacad73` | These are live examples — meme tokens go quiet over time, so swap in any token, pool, or trader you care about. --- ## Real-Time Trades on Robinhood ▶️ [Stream all Robinhood Chain trades - Run in IDE](https://ide.bitquery.io/stream-robinhood-chain-trades) Stream real-time trades on Robinhood via a GraphQL subscription on `Trading.Trades` that includes details such as Trader Address, Base and Quote Currency Details, amounts, type of trade (buy or sell), market cap and transaction details. ▶️ [Run in IDE](https://ide.bitquery.io/Robinhood-Trades) ```graphql subscription { Trading { Trades( where: { Pair: { Market: { NetworkBid: { is: "bid:robinhood" } } } }) { Block { Time } Trader{ Address } Amounts{ Base Quote } AmountsInUsd{ Base } Pair{ Token{ Name Symbol Address } QuoteToken{ Name Symbol Address } } Side Supply{ FullyDilutedValuationUsd MarketCap } TransactionHeader{ Hash } } } } ``` :::tip WebSocket connection Run subscriptions against `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol (`connection_init` → `connection_ack` → `subscribe`). See [WebSocket authentication](/docs/authorization/websocket/). ::: :::tip Prefer Kafka for the firehose Consuming the full Robinhood trade feed continuously? Bitquery also delivers DEX data as **Kafka streams** (protobuf topic `robinhood.dextrades.proto`) with consumer-group scaling and replay. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). ::: --- ## Historical Trades on Robinhood The Trading APIs cover roughly the **last 30 days** of history (for newer networks, data starts when Bitquery indexing began — measure the exact coverage with [this query](#check-the-trading-data-window)). This example pulls a past window using relative time bounds. ▶️ [Run in IDE](https://ide.bitquery.io/Historical-Robinhood-Trades) ```graphql { Trading { Trades( limit: {count: 50} orderBy: {ascending: Block_Date} where: { Block: { Time: { since_relative: {weeks_ago: 3} till_relative: {weeks_ago: 1} } } Pair: { Market: { NetworkBid: { is: "bid:robinhood" } } } }) { Block { Time } Trader{ Address } Amounts{ Base Quote } AmountsInUsd{ Base } Pair{ Token{ Name Symbol Address } QuoteToken{ Name Symbol Address } } Side Supply{ FullyDilutedValuationUsd MarketCap } TransactionHeader{ Hash } } } } ``` --- ## Latest Trades on Robinhood Query the most recent trades across all Robinhood tokens — the query counterpart to the real-time stream above — ordered by newest first. The `Block.Time` bound keeps the scan to the last hour; without it, sorting the whole rolling window by time is slow enough to hit the gateway timeout. ```graphql { Trading { Trades( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pair: { Market: { NetworkBid: { is: "bid:robinhood" } } } } ) { Block { Time } Trader { Address } Amounts { Base Quote } AmountsInUsd { Base } Pair { Token { Name Symbol Address } QuoteToken { Name Symbol Address } } Side Supply { FullyDilutedValuationUsd MarketCap } TransactionHeader { Hash } } } } ``` --- ## Whale Trades on Robinhood :::caution USD amounts on thin pools `AmountsInUsd` is derived from the pool price at trade time, so a thin or manipulated pool can print absurd dollar values. Sanity-check whale rows against the pool's liquidity, and rank leaderboards by trade `count` rather than USD volume when in doubt. ::: ▶️ [Run in IDE](https://ide.bitquery.io/largest-swaps-robinhood-chain) Fetch large trades by filtering on USD value. This example returns trades of at least `$10,000` — adjust the `AmountsInUsd.Base` threshold as needed. ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: {Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}}, AmountsInUsd: {Base: {ge: 10000}}} ) { Block { Time } Trader { Address } Amounts { Base Quote } AmountsInUsd { Base } Pair { Token { Name Symbol Address } QuoteToken { Name Symbol Address } } Side Supply { FullyDilutedValuationUsd MarketCap } TransactionHeader { Hash } } } } ``` --- ## Real-Time Trades for a Specific Token Using this GraphQL stream you can get real-time trades for a specific token (example: AssetHood, `ASSETH`) with details such as trader address, token details, marketcap, FDV and transaction hash. ▶️ [Run in IDE](https://ide.bitquery.io/Robinhood-Trades-for-a-token) ```graphql subscription { Trading { Trades( where: { Pair: { Token: { Address: { is: "0x9077841e155faaf4e4e89470822c2187eeef7777" } } Market: { NetworkBid: { is: "bid:robinhood" } } } }) { Block { Time } Trader{ Address } Amounts{ Base Quote } AmountsInUsd{ Base } Pair{ Token{ Name Symbol Address } QuoteToken{ Name Symbol Address } } Side Supply{ FullyDilutedValuationUsd MarketCap } TransactionHeader{ Hash } } } } ``` --- ## Trades for a Specific Pair or Pool Scope trades to a single liquidity pool using `Pool.Address` — useful when a token trades across multiple pools and you want just one. ```graphql { Trading { Trades( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Pair: { Market: { NetworkBid: { is: "bid:robinhood" } } Pool: { Address: { is: "0xbbaefcfcd7b92ed0df1a3eec22a21ba6beb0b52b" } } } } ) { Block { Time } Trader { Address } Amounts { Base Quote } AmountsInUsd { Base } Pair { Pool { Address } Token { Name Symbol Address } QuoteToken { Name Symbol Address } } Side Supply { FullyDilutedValuationUsd MarketCap } TransactionHeader { Hash } } } } ``` --- ## First Buyers of a Token on Robinhood Get the earliest trades for a token (example: the MERRY meme token, launched within the rolling window), ordered oldest first, to find the first buyers after launch. Filtered to buys here; remove the `Side` filter for first trades of any side. ```graphql { Trading { Trades( limit: { count: 50 } orderBy: { ascending: [Block_Time, TransactionHeader_Index] } where: { Pair: { Token: { Address: { is: "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a" } } Market: { NetworkBid: { is: "bid:robinhood" } } } Side: { is: "Buy" } } ) { Block { Time } Trader { Address } Amounts { Base Quote } AmountsInUsd { Base } Pair { Token { Name Symbol Address } QuoteToken { Name Symbol Address } } Side TransactionHeader { Hash } } } } ``` --- ## Trades by a Trader Using this GraphQL API endpoint you can get token trades by a trader with details such as trade amount, trade type, token details, marketcap, FDV and transaction hash. ▶️ [Run in IDE](https://ide.bitquery.io/Robinhood-Trades-by-a-trader) ```graphql { Trading { Trades( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Trader:{ Address:{ is: "0xf73644da46ab85da864fc4284322f489134ee82c" } } Pair: { Market: { NetworkBid: { is: "bid:robinhood" } } } }) { Block { Time } Trader{ Address } Amounts{ Base Quote } AmountsInUsd{ Base } Pair{ Token{ Name Symbol Address } QuoteToken{ Name Symbol Address } } Side Supply{ FullyDilutedValuationUsd MarketCap } TransactionHeader{ Hash } } } } ``` --- ## Top Traders of a Token on Robinhood ▶️ Network-wide version: [Top Traders by Volume on Robinhood Chain](https://ide.bitquery.io/top-traders-robinhood-chain) Rank the biggest traders of a specific token by total USD volume, with a buy/sell split and trade count. Aggregates `Trading.Trades` grouped by trader. ```graphql { Trading { Trades( limit: { count: 50 } orderBy: { descendingByField: "volume_usd" } where: { Pair: { Token: { Address: { is: "0x9077841e155faaf4e4e89470822c2187eeef7777" } } Market: { NetworkBid: { is: "bid:robinhood" } } } } ) { Trader { Address } volume_usd: sum(of: AmountsInUsd_Base) bought_usd: sum( of: AmountsInUsd_Base if: { Side: { is: "Buy" } } ) sold_usd: sum( of: AmountsInUsd_Base if: { Side: { is: "Sell" } } ) trades: count } } } ``` --- ## Latest Price of a Token on Robinhood Get the latest USD normalised price of a token on Robinhood network using this API endpoint using `Trading.Tokens`. :::note A single token might be traded on multiple pools, with each pool having a difference in price. As for the price returned by Bitquery we provide the weighted average price across all pools. To know more about the price calculation refer to [this](/docs/trading/crypto-price-api/price-index-algorithm/#how-token-prices-are-determined) document. If you want to monitor price for a particular pool, we suggest usage of `Trading.Pairs` instead of `Trading.Tokens` where you could specify the pool address. ::: ▶️ [Run in IDE](https://ide.bitquery.io/latest-price-of-a-token_10) ```graphql { Trading { Tokens( where: {Token: {Address: {is: "0x9077841e155faaf4e4e89470822c2187eeef7777"}, NetworkBid: {is: "bid:robinhood"}}, Interval: {Time: {Duration: {eq: 1}}}} orderBy: {descending: Interval_Time_End} limit: {count: 1} ) { latest_price: Price { Ohlc { Close } } } } } ``` --- ## Latest Price of a Token for a Liquidity Pool This API endpoint retrieves the latest price of a token for a particular token pair or liquidity pool using the `Trading.Pairs` cube. ▶️ [Run in IDE](https://ide.bitquery.io/latest-price-of-a-token-on-a-pool) ```graphql { Trading { Pairs( where: { Pool: { Address:{ is: "0xbbaefcfcd7b92ed0df1a3eec22a21ba6beb0b52b" } } Token: { Address: { is: "0x9077841e155faaf4e4e89470822c2187eeef7777" }, NetworkBid: {is: "bid:robinhood"}}, Interval: {Time: {Duration: {eq: 1}}} } orderBy: {descending: Interval_Time_End} limit: {count: 1} ) { Pool{ Address } latest_price: Price { Ohlc { Close } } } } } ``` --- ## Market Cap, FDV and Supply of a Token Get the latest market cap, fully-diluted valuation, supply, and price for a single Robinhood token in one row. `limit: 1` with `orderBy: { descending: Interval_Time_Start }` returns the most recent interval — the current snapshot. ```graphql { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Interval_Time_Start } where: { Token: { Address: { is: "0x9077841e155faaf4e4e89470822c2187eeef7777" } NetworkBid: { is: "bid:robinhood" } } Interval: { Time: { Duration: { eq: 1 } } } } ) { Token { Name Symbol Address } Price { Ohlc { Close } } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } Volume { Usd } } } } ``` --- ## Token Supply on Robinhood While `Trading.Tokens` (above) returns supply alongside price and market cap, you can also read **total supply** directly from the `EVM.TransactionBalances` cube. `TokenBalance.TotalSupply` is decimal-normalized (whole tokens). See the full guide in the [Robinhood Token Supply API](/docs/blockchain/robinhood/robinhood-token-supply). ### Latest Supply of a Token Get the most recent total supply for a single token by filtering on its contract address. ```graphql { EVM(network: robinhood) { TransactionBalances( limit: {count: 1} orderBy: {descending: Block_Time} where: {TokenBalance: {Currency: {SmartContract: {is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73"}}}} ) { TokenBalance { Currency { Symbol HasURI SmartContract } TotalSupply } } } } ``` ### Real-Time Supply Stream Stream live total-supply updates across Robinhood tokens. The `SmartContract: {not: "0x"}` filter excludes the native coin. ```graphql subscription { EVM(network: robinhood) { TransactionBalances( where: { TokenBalance: { Currency: { SmartContract: {not: "0x"} } } } ) { TokenBalance { Currency { Symbol HasURI SmartContract } TotalSupply } } } } ``` ### Supply of All Active Tokens Fetch the latest total supply for every recently active token. `limitBy` returns one row — the newest supply — per token contract. Keep a `limit`: unbounded, this returns one row per active token, which can be very large. ```graphql { EVM(network: robinhood) { TransactionBalances( limitBy: {by: TokenBalance_Currency_SmartContract, count: 1} limit: {count: 100} orderBy: {descending: Block_Time} where: {TokenBalance: {Currency: {SmartContract: {not: "0x"}}}} ) { TokenBalance { Currency { Symbol HasURI SmartContract } TotalSupply } } } } ``` --- ## OHLCV / K-Line Candles for a Token Token-level OHLCV candles (USD-normalised, weighted across all pools) for charting. This example uses 1-minute candles (`Duration: 60`); use `300` (5m) or `3600` (1h — the maximum candle) as needed. ```graphql { Trading { Tokens( limit: { count: 100 } orderBy: { descending: Interval_Time_Start } where: { Token: { Address: { is: "0x9077841e155faaf4e4e89470822c2187eeef7777" } NetworkBid: { is: "bid:robinhood" } } Interval: { Time: { Duration: { eq: 60 } } } } ) { Interval { Time { Start End } } Price { Ohlc { Open High Low Close } } Volume { Base Quote Usd } Supply { MarketCap FullyDilutedValuationUsd } Token { Name Symbol Address } } } } ``` --- ## Real-Time OHLCV Stream for a Pair on Robinhood This GraphQL stream for 1 second OHLCV streams the USD normalised OHLC/K-line data for a token pair, and also contains info such as interval start and end time, marketcap, volume and token details for both base and quote tokens. ▶️ [Run in IDE](https://ide.bitquery.io/OHLCV-stream-for-a-token-pair-on-robinhood) ```graphql subscription{ Trading { Pairs( where: { Pool: { Address:{ is: "0xbbaefcfcd7b92ed0df1a3eec22a21ba6beb0b52b" } } Token: { Address: { is: "0x9077841e155faaf4e4e89470822c2187eeef7777" }, NetworkBid: {is: "bid:robinhood"}}, Interval: {Time: {Duration: {eq: 1}}} } ) { Interval{ Time{ Start End } } Price { Ohlc { Open High Low Close } } Token{ Name Symbol Address } QuoteToken{ Name Symbol Address } Volume{ Base Quote Usd } Supply{ MarketCap } } } } ``` --- ## Top Tokens on Robinhood by Volume ▶️ [Run in IDE](https://ide.bitquery.io/top-tokens-by-volume-robinhood-chain) Rank the most actively traded Robinhood tokens by USD volume over the last 24 hours, aggregated from 1-second intervals with `sum`. ```graphql { Trading { Tokens( limit: {count: 50} limitBy: {count: 1, by: Token_Id} orderBy: {descending: [Volume_Usd]} where: {Interval: {Time: {Start: {since_relative: {days_ago: 1}}, Duration: {eq: 1}}}, Token: {NetworkBid: {is: "bid:robinhood"}}} ) { sum(of: Volume_Base) usd: sum(of: Volume_Usd) Token { Name Symbol Address } Supply { MarketCap FullyDilutedValuationUsd } } } } ``` --- ## Buy vs Sell Pressure for a Token Gauge demand in one call: buy and sell USD volume, trade counts, and unique traders for a token over a window. Compute net flow client-side as `bought_usd − sold_usd`. ```graphql { Trading { Trades( where: { Pair: { Token: { Address: { is: "0x9077841e155faaf4e4e89470822c2187eeef7777" } } Market: { NetworkBid: { is: "bid:robinhood" } } } Block: { Time: { since_relative: { days_ago: 1 } } } } ) { bought_usd: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sold_usd: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) traders: uniq(of: Trader_Address) } } } ``` --- ## Most Active Pools on Robinhood Rank pools by trade count over the last day, with USD volume and unique traders per pool. Trade count is a more robust ranking key than USD volume, which can be inflated to absurd values on thin meme pools — treat extreme `volume_usd` readings as suspect. ```graphql { Trading { Trades( limit: { count: 20 } orderBy: { descendingByField: "trades" } where: { Pair: { Market: { NetworkBid: { is: "bid:robinhood" } } } Block: { Time: { since_relative: { days_ago: 1 } } } } ) { Pair { Pool { Address } Market { Protocol } Token { Symbol Address } QuoteToken { Symbol } } trades: count volume_usd: sum(of: AmountsInUsd_Base) traders: uniq(of: Trader_Address) } } } ``` --- ## Price Watchlist: Latest Price for Multiple Tokens One latest price per token in a single call — `limitBy` on `Token_Id` keeps the newest 1-second interval for each token in the list. `Interval.Time.End` doubles as a staleness indicator: it is the last time that token actually traded. ```graphql { Trading { Tokens( limit: { count: 10 } limitBy: { by: Token_Id, count: 1 } orderBy: { descending: Interval_Time_End } where: { Token: { Address: { in: [ "0x9077841e155faaf4e4e89470822c2187eeef7777" "0x66c9ba158b2b80c2a51ca75f3e4155a682676c7a" ] } NetworkBid: { is: "bid:robinhood" } } Interval: { Time: { Duration: { eq: 1 } } } } ) { Token { Symbol Address } Price { Ohlc { Close } } Interval { Time { End } } } } } ``` --- ## Check the Trading Data Window Don't guess how far back Trading data reaches — ask for the earliest available trade. ```graphql { Trading { Trades( limit: { count: 1 } orderBy: { ascending: Block_Time } where: { Pair: { Market: { NetworkBid: { is: "bid:robinhood" } } } } ) { Block { Time } } } } ``` --- ## FAQ ### How do I stream Robinhood trades in real time? Run a GraphQL `subscription` on `Trading.Trades` filtered by `Pair.Market.NetworkBid: "bid:robinhood"`. Every matching trade is pushed to your client as it is indexed. Any query on this page can be turned into a stream by switching the operation to `subscription`. ### What is the difference between `NetworkBid` and `Network`? Both scope results to Robinhood. `NetworkBid: "bid:robinhood"` is the indexed identifier and is faster; `Network: "Robinhood"` is the human-readable equivalent. Prefer `NetworkBid` in filters. ### How do I get the current price of a Robinhood token? Use `Trading.Tokens` for the USD-normalised, pool-weighted price, or `Trading.Pairs` when you need the price on a specific pool. ### Can I get OHLCV / candlestick data for Robinhood tokens? Yes. Query `Trading.Tokens` or `Trading.Pairs` with an `Interval.Time.Duration` in seconds — from 1 second up to a maximum of 3600 (1 hour) per candle. ### How far back does Robinhood trade data go? The Trading APIs cover real-time data and roughly the last 30 days — for newer networks, data starts when Bitquery indexing began. Measure the exact coverage with the [window query](#check-the-trading-data-window). For older history, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs. ### How do I measure buy vs sell pressure for a Robinhood token? Aggregate `Trading.Trades` with conditional sums — `sum(of: AmountsInUsd_Base, if: {Side: {is: "Buy"}})` versus the `Sell` side — over your window, and compare. See [Buy vs Sell Pressure](#buy-vs-sell-pressure-for-a-token). --- ## DEXPools Cube on EVM Chains URL: https://docs.bitquery.io/docs/cubes/evm-dexpool/ DEXPools cube on EVM chains: pool structure, price tables, when Uniswap V2, V3 and V4 pool records are emitted, filters, and liquidity depth analysis. # DEXPools Cube on EVM Chains This section explains how the dexpool data is built and shared via APIs and [Kafka streams](/docs/streams/kafka-streaming-concepts/). It also explains how to understand each entry of the response. > **Note:** In GraphQL, DEXPools data is accessed through two schema cubes: > > - **`DEXPoolEvents`**: Provides pool event data (swaps, mints, burns, etc.) > - **`DEXPoolSlippages`**: Provides slippage and price impact data for different trade sizes ## Concept Explanation Liquidity pools are fundamental components of decentralized exchanges that enable token swaps without traditional order books. Each pool contains two tokens (CurrencyA and CurrencyB), and the ratio of these tokens determines the exchange rate. When a user wants to swap tokens, they interact with a liquidity pool. The pool calculates the output amount based on: - Current liquidity reserves - The amount being swapped - Price impact and slippage tolerance For example, if you want to sell ANKR tokens for WETH in a pool: ``` Pool: 0x13dc0a39dc00f394e030b97b0b569dedbe634c0d DEX: uniswap_v3 (3) Token0: ANKR (decimals: 18) Token1: WETH (decimals: 18) Liquidity: 604099.111169 ANKR, 1.074933 WETH Direction: Sell ANKR → Buy WETH slippage: 0.1%, MaxIn: 205.504593 ANKR, MinOut: 0.000434 WETH, ratio: 473132.526201 ANKR/WETH slippage: 0.5%, MaxIn: 997.299766 ANKR, MinOut: 0.002097 WETH, ratio: 475456.664617 ANKR/WETH slippage: 1.0%, MaxIn: 2012.776732 ANKR, MinOut: 0.004205 WETH, ratio: 478581.192432 ANKR/WETH slippage: 2.0%, MaxIn: 4067.602247 ANKR, MinOut: 0.008289 WETH, ratio: 490722.489031 ANKR/WETH slippage: 5.0%, MaxIn: 10501.563247 ANKR, MinOut: 0.020650 WETH, ratio: 508535.330236 ANKR/WETH slippage: 10.0%, MaxIn: 22396.241185 ANKR, MinOut: 0.040771 WETH, ratio: 549306.392584 ANKR/WETH ``` If you are willing to accept a price impact and slippage of up to 10.0% against the current spot price, you can sell a maximum of 22396.241185 ANKR into the pool. In return, you are guaranteed to receive at least 0.040771 WETH. The average execution price for this trade would be approximately 549306.392584 ANKR per 1 WETH. The calculation considers the price impact plus the worst-case scenario of slippage for different amounts, with limited losses for each, by simulating a swap by iterating through initialized ticks in the TickBitmap. > Important note: The liquidity calculation differs by protocol version: > > - For Uniswap V2 and V3, liquidity reflects exactly the balance of the pool > - For Uniswap V4, liquidity is the token balances in PoolManager ## Understanding Pool Structure In DEXPools, each pool is represented with several key components: - **`Pool`**: The pool smart contract address and token pair information - **`Dex`**: The DEX protocol details (name, version, family) - **`Liquidity`**: Current token reserves in the pool - **`PoolPriceTable`**: Price calculations for different slippage tolerances in both directions ### Example Data Structure A sample entry for a token pair shared via Bitquery Kafka streams is available [here](https://github.com/bitquery/kafka-data-sample/blob/main/evm/eth_dexpools.json) ### Understanding Price Tables The `PoolPriceTable` provides price information for swaps in both directions: - **`AtoBPrices`**: Array of price calculations for swapping CurrencyA to CurrencyB at different slippage tolerances - **`BtoAPrices`**: Array of price calculations for swapping CurrencyB to CurrencyA at different slippage tolerances - **`AtoBPrice`**: Current spot price for CurrencyA to CurrencyB - **`BtoAPrice`**: Current spot price for CurrencyB to CurrencyA Each price entry in the arrays contains: - **`SlippageBasisPoints`**: Slippage tolerance in basis points (100 = 1%) - **`MaxAmountIn`**: Maximum input amount that can be swapped at this slippage level - **`MinAmountOut`**: Minimum output amount guaranteed at this slippage level - **`Price`**: Average execution price for swaps at this slippage level The following slippage levels are available in the data: - 10 basis points (0.1%) - 50 basis points (0.5%) - 100 basis points (1.0%) - 200 basis points (2.0%) - 500 basis points (5.0%) - 1000 basis points (10.0%) For example, in the `AtoBPrices` array above, with a 10 basis point (0.1%) slippage tolerance, you can swap up to 2,557,952,147 units of CurrencyA (USDC) and receive at least 860,478,002,991,619,427 units of CurrencyB (WETH), at an average price of 0.0003364734002389014 USDC per WETH. ## When is a new DEXPool record emitted in the APIs & Streams? A new DEXPool record is emitted in the APIs and Kafka streams when specific events occur that change the pool's liquidity or state. The events tracked vary by protocol version: ### Uniswap V2 The following events trigger a new DEXPool entry: - `Swap(address,uint256,uint256,uint256,uint256,address)` - Emitted when tokens are swapped in the pool - `Mint(address,uint256,uint256)` - Emitted when liquidity is added to the pool - `Burn(address,uint256,uint256,address)` - Emitted when liquidity is removed from the pool ### Uniswap V3 The following events trigger a new DEXPool entry: - `Mint(address,address,int24,int24,uint128,uint256,uint256)` - Emitted when liquidity is added to a position - `Burn(address,int24,int24,uint128,uint256,uint256)` - Emitted when liquidity is removed from a position - `Swap(address,address,int256,int256,uint160,uint128,int24)` - Emitted when tokens are swapped in the pool ### Uniswap V4 The following events trigger a new DEXPool entry: - `ModifyLiquidity(bytes32,address,int24,int24,int256,bytes32)` - Emitted when liquidity is modified in the pool - `Swap(bytes32,address,int128,int128,uint160,uint128,int24,uint24)` - Emitted when tokens are swapped in the pool > Note: Forks of Uniswap can also be tracked with these APIs if the signature is exactly the same. ## Filtering in DEXPools Cube Filtering helps to fetch the exact pool data you are looking for. DEXPools Cube can filter based on pool address, token addresses, DEX protocol, liquidity amounts, and more. Everything inside the "where" clause filters; it follows the `AND` condition by default. ## API Examples For blockchain-specific slippage API documentation, see: - [Arbitrum Slippage API](/docs/blockchain/Arbitrum/arbitrum-slippage-api/) - [Base Slippage API](/docs/blockchain/Base/base-slippage-api/) - [BSC Slippage API](/docs/blockchain/BSC/bsc-slippage-api/) - [Matic Slippage API](/docs/blockchain/Matic/matic-slippage-api/) For blockchain-specific liquidity API documentation, see: - [Arbitrum Liquidity API](/docs/blockchain/Arbitrum/arbitrum-liquidity-api/) - [Base Liquidity API](/docs/blockchain/Base/base-liquidity-api/) - [BSC Liquidity API](/docs/blockchain/BSC/bsc-liquidity-api/) - [Ethereum Liquidity API](/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api/) - [Matic Liquidity API](/docs/blockchain/Matic/matic-liquidity-api/) ## Advanced Use Cases and Processing Patterns ### Liquidity Depth Analysis DEXPools enables analysis of liquidity depth across different pools. By examining the `MaxAmountIn` values at various slippage levels, you can determine: - Which pools can handle large trades without significant price impact - Optimal slippage tolerance for your trade size - Price impact estimation before executing trades ### Multi-Pool Price Comparison The price table data allows comparison of execution prices across different slippage scenarios, helping traders: - Identify the best pool for their trade size - Understand price impact before executing swaps - Optimize trade execution strategies based on available liquidity ### Protocol-Specific Analysis Different DEX protocols (Uniswap V2, V3, V4) have different liquidity mechanisms. The DEXPools cube provides protocol-specific information: - **Uniswap V2/V3**: Liquidity reflects the exact balance of the pool - **Uniswap V4**: Liquidity represents token balances in PoolManager This allows for accurate analysis across different protocol versions and their unique characteristics. --- ## DEXScreener API: Solana Pairs, Trades, OHLC, Live Streams URL: https://docs.bitquery.io/docs/blockchain/Solana/DEXScreener/solana_dexscreener/ The public DEX Screener API has no OHLC, history or price WebSocket. Get the same Solana pair data with candles, history and live streams from Bitquery. # DEXScreener API for Solana: Pairs, Trades, OHLC and Live Streams DEX Screener publishes a public REST API. Its reference lists pair, token and search endpoints at 300 requests a minute and profile, boost and ad endpoints at 60 a minute, all returning the current state of a pair or token. It has no candle, OHLC or historical endpoint. Its WebSocket API streams token profiles, boosts, community takeovers and ads, not pair prices or trades. If that is enough, use it. This page is for the rest: every number on the DEX Screener Solana dashboard, plus the history behind it, over Bitquery GraphQL, WebSocket subscriptions and Kafka streams. Live trades per pair, token prices, OHLC candles at any interval, buy and sell volume with makers, buyers and sellers, top pairs by activity, and trader profit and loss, across Raydium, Orca, Jupiter, PumpSwap and the other Solana DEXs. Every query below runs as written in the [Bitquery IDE](https://ide.bitquery.io) with a free trial key. ## What the official DEX Screener API covers | Endpoint group in the DEX Screener reference | Rate limit | Returns | |---|---|---| | Pairs by chain and pair address, token pairs, tokens by address, search | 300 requests a minute | Current price, liquidity, volume and transaction counts for a pair or token | | Token profiles, boosts, community takeovers and ads (REST, plus WebSocket feeds), orders and metas (REST) | 60 requests a minute | Listing and promotion metadata | Two things are missing from that reference: candles (there is no OHLC or historical endpoint, so a chart has to be built by polling and storing snapshots yourself) and a push channel for market data (the WebSocket page lists only profile, boost, takeover and ad feeds, so live pair prices mean polling within the limit). The queries on this page fill both gaps, and add the aggregates a screener needs, such as distinct makers, buyers and sellers per window. For EVM chains (Ethereum, BNB Chain, Arbitrum, Base, Polygon, Optimism) see the [DEXScreener EVM API page](/docs/blockchain/Ethereum/dextrades/DEXScreener/evm_dexscreener/). ## How the data is delivered - **GraphQL API** for historical and current data with filtering and aggregation. Start at [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades). - **WebSocket subscriptions** for live trades, new pools and price updates. See [Solana subscriptions](/docs/subscriptions/subscription). - **Kafka streams** for high-throughput pipelines. See [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/). - **Data Store exports**: Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore) for bulk history, to load into your own warehouse. Technical details: [Solana exports](/docs/cloud/solana/). ## Get trade transactions of a pair in real time This subscription streams every trade on one Solana pair as it is confirmed. Open it in the IDE [here](https://ide.bitquery.io/Get-Solana-pair-trades-data-just-like-dexcsreener#). ```graphql subscription MyQuery { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}, Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}, Market: {MarketAddress: {is: "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Trade { Currency { Name Symbol } Amount PriceAgainstSideCurrency: Price PriceInUSD Side { Currency { Name Symbol } Amount Type } } Transaction { Maker: Signer Signature } } } } ``` ## Get the price of a token This query returns the latest price of a token from the Trading API, with mean, estimate and moving-average prices alongside the OHLC of the latest one-second interval. Saved query [here](https://ide.bitquery.io/token-usd-price-using-trading-api_1). ```graphql query MyQuery { Trading { Pairs( where: {Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}}, Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}} limit: {count: 10} orderBy: {descending: Interval_Time_Start} ) { Token { Name Address Id NetworkBid } Price { Average { Mean Estimate ExponentialMoving SimpleMoving WeightedSimpleMoving } Ohlc { Open High Low Close } } } } } ``` ## Get OHLC candles for a token pair This is the candle endpoint DEX Screener does not have. It fetches Open, High, Low and Close prices in USD for a token pair across DEXs, at the interval you set in seconds. Put the base and quote token addresses in the `Token.Id` and `QuoteToken.Id` filters and set `Interval.Time.Duration` to the candle size (`3600` for one hour, `60` for one minute). The query returns the most recent candles sorted by interval start. Saved query [here](https://ide.bitquery.io/ohlc-of-a-solana-token-pair-1-hour-interval). For long histories and other aggregate windows, see [Historical Solana data](/docs/blockchain/Solana/historical-aggregate-data). ```graphql query MyQuery { Trading { Pairs( where: {Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}}, QuoteToken: {Id: {is: "bid:solana:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Interval: {Time: {Duration: {eq: 3600}}}, Price: {IsQuotedInUsd: true}} limit: {count: 10} orderBy: {descending: Interval_Time_Start} ) { Token { Name Address Id NetworkBid } QuoteToken{ Name Address Id NetworkBid } Price { Average { Mean Estimate ExponentialMoving SimpleMoving WeightedSimpleMoving } Ohlc { Open High Low Close } } } } } ``` ## Buy volume, sell volume, buys, sells, makers, buyers and sellers for a pair {#pair-stats} This is the query behind a DEX Screener pair row: total and 5-minute buy and sell volume, trade counts, unique makers, buyers and sellers, and the price at the start of the window, five minutes ago, and now. Two things make it reliable: - **`since_relative` / `after_relative` instead of absolute timestamps.** The window is always "the last hour" and "the last 5 minutes" no matter when the query runs. A hardcoded date silently widens every day it sits in your code. - **`Transaction: { Result: { Success: true } }`** drops failed transactions, which otherwise inflate trade counts and volume. ```graphql query PairStats($token: String!, $side_token: String!, $pair_address: String!) { Solana(dataset: realtime) { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: $token } } Side: { Currency: { MintAddress: { is: $side_token } } } Market: { MarketAddress: { is: $pair_address } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Trade { Currency { Name MintAddress Symbol } price_start: PriceInUSD(minimum: Block_Time) price_5min_ago: PriceInUSD( minimum: Block_Time if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) price_now: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) makers_5min: count( distinct: Transaction_Signer if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) buyers: count(distinct: Transaction_Signer, if: { Trade: { Side: { Type: { is: buy } } } }) sellers: count(distinct: Transaction_Signer, if: { Trade: { Side: { Type: { is: sell } } } }) trades: count trades_5min: count(if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } }) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) buy_volume: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) sell_volume: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) } } } ``` Variables. This example uses the **WSOL/USDC Orca Whirlpool**, a long-lived pool that will still be there when you run it: ```json { "token": "So11111111111111111111111111111111111111112", "side_token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "pair_address": "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE" } ``` :::tip Choosing a `pair_address` Two traps here. **Aggregators return an empty `MarketAddress`.** Routers such as Jupiter, dflow and Aquifer carry large volume but expose no single pool, so filtering by `Market.MarketAddress` on them yields nothing. Filter on an AMM pool (Whirlpool, Raydium, PumpSwap) instead. **Memecoin pools are short-lived.** A pump.fun graduate can do eight figures of volume in one hour and almost nothing an hour later, so a mint that looks ideal today may be dead by the time you copy the query. Use [Get top pairs on Solana](#top-pairs) to find a currently active pool, then substitute its address here. ::: ## Get top pairs on Solana {#top-pairs} This returns the top 10 Solana pairs by trade count over the last hour, with total trades, buys, sells, traded volume and buy volume, the data behind a screener leaderboard or a "trending" list. Use it to find a currently active pool to plug into the [pair stats query](#pair-stats) above. `since_relative` keeps the window rolling, so there is no date to update. Note you cannot run this as a WebSocket subscription: aggregate functions like `sum` do not work in `subscription`. You can find the query [here](https://ide.bitquery.io/Dexscreener--All-in-One-query_1) ```graphql query MyQuery { Solana { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Trade: {Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}, Block: {Time: {since_relative: {hours_ago: 1}}}} orderBy: {descendingByField: "total_trades"} limit: {count: 10} ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after_relative: {minutes_ago: 5}}}} ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct:Transaction_Signer) total_trades: count total_traded_volume: sum(of: Trade_Side_AmountInUSD) total_buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) total_sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) total_buys: count(if: {Trade: {Side: {Type: {is: buy}}}}) total_sells: count(if: {Trade: {Side: {Type: {is: sell}}}}) } } } ``` ## New pairs and new pools DEX Screener's "new pairs" tab is a stream of pool creations. On Bitquery that is the DEXPools cube, which reports every new liquidity pool with its tokens and initial liquidity, and can be subscribed to over WebSocket. The queries live on the [Solana DEX Pools API page](/docs/blockchain/Solana/Solana-DexPools-API). Launchpad tokens that have not reached a pool yet are covered by the [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/). --- ## Trader-focused trade APIs (with USD price, market cap and supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get all DEX trades on Solana with price, market cap and supply Stream **all Solana DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Network: Solana`** to capture every swap across **Raydium**, **Orca**, **Jupiter**, **PumpSwap**, and other Solana DEXs in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Solana-with-Price-Marketcap-supply).
Click to expand GraphQL query ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Solana" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
### Top traders by PnL for a specific pool (last 30 minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. The example pool is the WSOL/USDC Orca Whirlpool; swap in any active pool address from the [top pairs query](#top-pairs). You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-pair#).
Click to expand GraphQL query ```graphql { Trading { Trades( limit: { count: 10 } orderBy: [{ descendingByField: "PnL" }] where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
--- ## API key, trial and pricing You need a Bitquery access token to run these outside the IDE. Create one at [account.bitquery.io](https://account.bitquery.io/) and follow [how to generate a token](/docs/authorization/how-to-generate/); there is no approval step. The free trial runs for seven days and includes 1,000 API points, 100 MCP credits and two simultaneous streams. Request rate limits by plan are 30 a minute on Personal, 90 on Pro and 240 on Scale, with custom limits on Enterprise; see [rate limits](/docs/plans/rate-limits/). How points and streams are billed is on [how billing works](/docs/plans/how-billing-works/), and plan prices are on the [pricing page](https://bitquery.io/pricing). ## DEX Screener API compared with Bitquery | | DEX Screener public API | Bitquery | |---|---|---| | Access | Public REST, no key listed in the reference | Access token from account.bitquery.io, free trial | | Rate limit | 300 requests a minute (pairs, tokens, search), 60 (profiles, boosts, ads) | 30, 90 or 240 requests a minute by plan, custom on Enterprise | | Data shape | Current snapshot of a pair or token | Trades, pools, balances, transfers and aggregates, current and historical | | Candles and history | Not in the reference | OHLC at any interval, full trade history | | Real-time delivery | WebSocket for profiles, boosts and ads; polling for pair data | WebSocket subscriptions for trades, pools and prices, Kafka, gRPC | | Screener aggregates | Volume and transaction counts per pair | Volume, trades, distinct makers, buyers and sellers per window, top pairs, trader PnL | | Chains | Multi-chain | Solana plus the EVM chains on the [EVM page](/docs/blockchain/Ethereum/dextrades/DEXScreener/evm_dexscreener/) | ## Video tutorial on how to get Solana DEXTrades data just like DEXScreener from Bitquery API ## Video tutorial | How to get buys, sells, buy volume, sell volume, makers and trades for a specific Solana token pair ## Related pages - [Solana API hub](/docs/blockchain/Solana/) - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades) - [Solana DEX Pools API](/docs/blockchain/Solana/Solana-DexPools-API) - [Historical Solana data and OHLC](/docs/blockchain/Solana/historical-aggregate-data) - [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [Solana Token Price API](/docs/blockchain/Solana/solana-token-price-api): latest USD price, live price stream and OHLC per token - [GMGN API alternative](/docs/blockchain/Solana/solana-gmgn-api): trending tokens, top pairs and buy/sell stats - [DEXScreener EVM API](/docs/blockchain/Ethereum/dextrades/DEXScreener/evm_dexscreener/) - [How Bitquery compares with other APIs](/docs/api-comparison) --- ## DEXTrades vs DEXTradeByTokens vs Trades cube URL: https://docs.bitquery.io/docs/cubes/dextrades-dextradebytokens-trading-trades/ DEXTrades, DEXTradeByTokens and the Trades cube compared: what each returns, when to use which, a quick decision guide and chain-specific examples. # DEXTrades vs DEXTradeByTokens vs Trades cube > **Looking for the product-family choice first?** This page is the **cube-by-cube row-shape** comparison. For the higher-level "should I use chain-level trades or the curated Trading cube?" decision (with the full Trading cube family — `Trading.Trades`, `Tokens`, `Currencies`, `Pairs`), start with the [**Trading Data Overview**](/docs/trading/trading-data-overview). Bitquery exposes **three** common ways to work with **DEX swap–level** data. They differ by **GraphQL root**, **row shape** (how each swap is represented), and **what fields are normalized for you**. :::tip Time window decides first, row shape second - **Real-time + last ~30 days** → **`Trading { Trades }`** (and `Tokens` / `Pairs` / `Currencies` for OHLC). USD price, market cap, and supply on every row; MEV-filtered; 10 chains in one API. - **Older than ~30 days** → chain-level **`DEXTrades`** / **`DEXTradeByTokens`** with `dataset: combined` / `archive` — the Trading cube is a **rolling ~30-day window** and does not reach further back. Pick the cube by row shape (below) only after the time window has narrowed the choice. See the [Trading Data Overview](/docs/trading/trading-data-overview). ::: This page compares them so you can pick the right primitive before you write filters, subscriptions, or aggregations. For the broader “transfers vs events vs calls vs DEX” picture, see the [mental model guide](/docs/start/mental-model-transfers-events-calls). --- ## At a glance | | **DEXTrades** | **DEXTradeByTokens** | **Trades cube** (`Trading { Trades }` — [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api)) | |---|----------------|----------------------|---------------------------------------------| | **GraphQL root** | Chain APIs such as `EVM(...)`, `Solana { ... }`, `Tron { ... }` | Same chain roots | `Trading { Trades }` | | **Time window** | Full historical archive (`dataset: combined` / `archive`) | Full historical archive (`dataset: combined` / `archive`) | **Rolling ~30 days + real-time** — no deeper history | | **Focus (by chain)** | **EVM / Tron:** **Pool-focused**—`Buy`/`Sell` follow the pool’s perspective ([DEXTrades cube](/docs/cubes/dextrades)). **Solana:** **Trader-focused**—natural fit for signer, buyer/seller, and account-style filters (see [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades), [trader patterns](/docs/blockchain/Solana/solana-trader-API)). | **EVM / Tron:** Still **pool-relative** on the **`Side`** leg (e.g. `Side.Type` vs pool); rows are **token-expanded**, not “wallet-first.” **Solana:** **Trader-focused** in practice—e.g. buyers/sellers and volume by **`Transaction.Signer`** and `Side.Type` in [Solana examples](/docs/blockchain/Solana/solana-dextrades). | **Trader-focused** everywhere: first-class **`Trader.Address`**, **`Pair`**, **`Side`**, and USD fields aligned to the [Price Index](/docs/trading/crypto-price-api/price-index-algorithm). | | **Rows per swap** | **One** row per swap | **Multiple** rows per swap (token-centric; typically **two** for a two-token pool) | **One** row per swap | | **Core shape** | `Trade.Buy` / `Trade.Sell` (shape varies by chain; see above) | `Trade` (primary token) + `Trade.Side` (counter leg) | `Side`, `Pair` (market, tokens, currencies), `Amounts` / `AmountsInUsd`, `Price` / `PriceInUsd`, `Trader`, transaction header | | **USD / long-tail tokens** | **`PriceInUSD`** and related fields are **often missing or zero** for illiquid or meme tokens—amounts exist, but USD requires a usable valuation path ([DEXTrades cube — PriceInUSD](/docs/cubes/dextrades#video-tutorial--why-priceinusd-is-0-in-bitquery-api-response)). Same class of issue on **`DEXTradeByTokens`** when the schema cannot price the leg. | Same limitation as chain DEX rows: **not guaranteed** for every token. | **Much more usable USD for trading UIs:** **`PriceInUsd`** and **`AmountsInUsd`** are driven by the **Trading price index**, so you typically **do not hit the “no USD for meme coins” problem** that shows up on raw chain DEX cubes. | | **Best when you need** | **EVM:** one record per pool swap, protocol/pool analytics, multi-hop debugging. **Solana:** trades by **wallet** / signer / account, buy vs sell counts, DEX-level analytics on chain. | **EVM:** token-level OHLC from raw trades, “all pairs for this token,” portfolio-style filters (with dedupe discipline). **Solana:** token **and** trader analytics (buyers, sellers, makers) in one model. | **Real-time and anything within the last ~30 days**: **multi-chain** swap stream, **trader-centric** apps, **reliable USD** on each row, **supply snapshot** (market cap, FDV, circulating/total/max). | | **Watch out for** | On **EVM**, `Buy`/`Sell` are **pool**-relative—not the end-user’s intuition without reading the field docs. | **Double counting** if you sum without filtering by token or deduplicating (e.g. by transaction hash / index). | Not a substitute for **pre-aggregated OHLC** on **Tokens** / **Pairs**; for aggregated charts prefer [Crypto Price API](/docs/trading/crypto-price-api/) unless you need raw swap rows | Full reference pages: [DEXTrades cube](/docs/cubes/dextrades), [DEXTradesByTokens cube](/docs/cubes/dextradesbyTokens), [Crypto Trades API — `Trades`](/docs/trading/crypto-trades-api/trades-api). --- ## DEXTrades The [DEXTrades](/docs/cubes/dextrades) cube is **normalized DEX swap data** with **`Trade.Buy`** and **`Trade.Sell`**. How you should read those fields depends on the chain: **EVM (and similar pool-centric docs):** **`Buy`** and **`Sell`** are from the **pool’s** perspective—the pool always sits in the trade; **`Buy`** is what the pool received, **`Sell`** what it paid out (diagrams and examples on the [DEXTrades cube](/docs/cubes/dextrades) page). You get **one row per swap** at the pool, which fits **protocol**, **pair/pool**, **routing**, and **multi-hop** analysis ([multi-hop section](/docs/cubes/dextrades)). **Solana:** The same `DEXTrades` field is **trader- and account-oriented** in typical queries—e.g. filtering by **`Transaction.Signer`**, **`Trade.Buy` / `Trade.Sell`** accounts and token owners, and building **buy vs sell** stats for wallets. See [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades) and [Solana trader API patterns](/docs/blockchain/Solana/solana-trader-API). **USD on chain DEX rows:** For many **long-tail or meme** tokens, **`PriceInUSD`** (and similar) may be **0 or absent** because USD is derived from trade amounts and available USD legs—not a guaranteed field for every asset. See pricing notes and the video on the [DEXTrades cube — Why PriceInUSD is 0](/docs/cubes/dextrades#video-tutorial--why-priceinusd-is-0-in-bitquery-api-response) section. **Available on chain roots** such as `EVM`, `Solana`, and `Tron` (see [mental model — applying across chains](/docs/start/mental-model-transfers-events-calls#applying-this-model-across-chains)). --- ## DEXTradeByTokens (token-expanded; EVM pool leg vs Solana trader stats) The [DEXTradesByTokens](/docs/cubes/dextradesbyTokens) / **`DEXTradeByTokens`** field describes the **same swaps** as DEXTrades, but **explodes** them into **token-centric** rows: - Each row emphasizes **`Trade`** (one token leg: **currency**, **amount**, **buyer**, **seller**) and **`Side`** (the counter leg). On **EVM**, **`Side.Type`** and buyer/seller on the side are still **pool-relative** (see [structure comparison](/docs/cubes/dextradesbyTokens#understanding-trade-and-side-structure)). - **Solana** examples often stress **trader** dimensions—e.g. **distinct signers**, **buyers** and **sellers** conditional on **`Trade.Side.Type`**, and volume in USD when available ([Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades)). - A single swap can produce **multiple rows** (e.g. both tokens get a row). That is **by design** for “everything involving token X” without reshaping **`Buy`/`Sell`** yourself on **EVM**. **Important:** There are **roughly twice as many records per swap** as with DEXTrades for a two-asset swap. **Filter by token (or pair)** and understand [how to avoid duplicate-looking totals](/docs/cubes/dextradesbyTokens#how-do-i-avoid-duplicate-results-in-dex-trade-queries) (e.g. specify side currency, dedupe by transaction, or use DEXTrades when you need **strictly one row per swap**). **Typical uses:** token price across DEXs, portfolio-style **user** tracking (buyer or seller), pairs a token trades in, and **historical OHLC derived from raw DEX trades** (bucket with `Block { Time(interval: ...) }` and min/max price fields—see [OHLC on DEXTradeByTokens](/docs/cubes/dextradesbyTokens#how-do-i-get-ohlc-in-a-dextradebytokens-query)). **OHLCV choice between the two DEX cubes:** Prefer **`DEXTradeByTokens`** for **one token’s** candle path (all pools/sides from the token’s view). Prefer **`DEXTrades`** when you need **each raw swap** as a single row (pool view, routing, debugging). For **default** OHLC/charting, the docs recommend the **[Crypto Price API](/docs/trading/crypto-price-api/)** first; see [DEXTradeByTokens vs DEXTrades for OHLCV](/docs/cubes/dextradesbyTokens#how-do-i-use-dextradebytokens-vs-dextrades-for-ohlcv) and [Crypto OHLC FAQ](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api). --- ## Trades cube (Crypto Trades API — trader-focused, strong USD) The **`Trades`** field under **`Trading`** is documented as the [Crypto Trades API — real-time DEX trade streams](/docs/trading/crypto-trades-api/trades-api). It is **not** nested under `EVM` / `Solana` per chain in the same way; you use **`Trading { Trades }`** and narrow with **`Pair.Market.Network`**, token ids, and **`Trader.Address`**. **Trader-first model:** Rows are built for **who traded**—**`Trader.Address`** is a first-class filter—alongside **`Pair`**, **`Side`**, and amounts. That is the natural API for **wallet streams**, **leaderboards**, and **per-user** trade history across **Solana**, **Ethereum**, **BSC**, **Base**, **Arbitrum**, **Optimism**, **Polygon**, **Tron**, **Robinhood**, and **Arc** in one schema ([Trades API](/docs/trading/crypto-trades-api/trades-api)). **USD vs chain DEX cubes:** On **`DEXTrades`** / **`DEXTradeByTokens`**, **`PriceInUSD`** is often **missing or zero** for **meme or thinly traded** tokens (see [DEXTrades cube](/docs/cubes/dextrades) pricing notes). The **`Trades`** cube is different: **`PriceInUsd`** and **`AmountsInUsd`** are tied to the **Trading price index**, so you **usually get usable USD** for the same long-tail assets where raw chain DEX USD fields fail. Details: [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). **What each row includes (per docs):** **`Side`**, **amounts** (base, quote, **USD**), **`Price`** / **`PriceInUsd`**, **`Pair`** (market, tokens, currencies), **`Trader`**, **transaction** header fields, and **`Supply`** (**MarketCap**, **FDV**, circulating/total/max) for token context. **Operational notes from the Trades docs:** - **Subscriptions** are the primary pattern for **live** streams; you can often use the **same selection as a `query`** with a **time window** on **`Block`** / **`Interval`** where supported. - **Token filter:** **`Pair.Token.Id`** with the full id (e.g. `bid:solana:`, `bid:eth:`) per dataset conventions. - **Trader filter:** **`Trader.Address`**. For **aggregated** token metrics across pairs, use **[Tokens](/docs/trading/crypto-price-api/tokens)**; for **pair-level** OHLC intervals, use **[Pairs](/docs/trading/crypto-price-api/pairs)**—as noted on the [Trades API page](/docs/trading/crypto-trades-api/trades-api). --- ## Quick decision guide 1. **EVM / Tron: one row per pool swap** with pool **`Buy`/`Sell`** semantics, or **Solana: trades by signer / account / buy vs sell** on chain? → **`DEXTrades`** on the right **chain root**. 2. **Token-expanded rows**, OHLC **from raw DEX trades older than ~30 days**, or **Solana** maker/buyer/seller aggregates on **`DEXTradeByTokens`**? → **`DEXTradeByTokens`**, with **strict filters** on **EVM** so counts are not doubled. (For OHLC within ~30 days, prefer the pre-aggregated [Crypto Price API](/docs/trading/crypto-price-api/) instead.) 3. **Real-time or last-~30-days** trades: **trader-centric** product, **multi-chain** `Trading` stream, **reliable USD** (including meme / long-tail), plus **supply** on each row? → **`Trading { Trades }`** ([Crypto Trades API](/docs/trading/crypto-trades-api/trades-api)). Note the **~30-day rolling window** — for a deeper backfill, drop to the chain-level cubes above. 4. **Need pre-built candles / moving averages / mean price** without aggregating raw swaps yourself? → **[Crypto Price API](/docs/trading/crypto-price-api/)** (**Tokens**, **Pairs**, **Currencies**)—not the same as **`Trades`**, as explained in the [mental model](/docs/start/mental-model-transfers-events-calls#trading-crypto-price-cube). --- ## Chain hub examples These guides start with a **live swap stream** from the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) (IDE link where we ship a saved query), then keep **`DEXTrades`** / **`DEXTradeByTokens`** for pools, OHLC, and analytics: - [BNB (BSC) DEX Trades](/docs/blockchain/BSC/bsc-dextrades) - [Base DEX Trades](/docs/blockchain/Base/base-dextrades) - [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades) - [Polygon (MATIC) DEX Trades](/docs/blockchain/Matic/matic-dextrades) - [Optimism DEX Trades](/docs/blockchain/Optimism/optimism-dextrades) - [Tron DEX Trades](/docs/blockchain/Tron/tron-dextrades) - [Arbitrum DEX Trades](/docs/blockchain/Arbitrum/DexTrades) --- ## Related documentation - [Mental model: transfers, events, calls, DEX, Trading](/docs/start/mental-model-transfers-events-calls) - [DEXTrades cube](/docs/cubes/dextrades) - [DEXTradesByTokens cube](/docs/cubes/dextradesbyTokens) - [Crypto Trades API — `Trades`](/docs/trading/crypto-trades-api/trades-api) - [GraphQL limits](/docs/graphql/limits) (paging, `orderBy`, time windows) --- ## DEXTradesByTokens Cube URL: https://docs.bitquery.io/docs/cubes/dextradesbyTokens/ DEXTradeByTokens cube explained: trade and side structure, OHLC queries, when to use it vs DEXTrades, filtering, portfolio tracking and avoiding duplicates. # DEXTradesByTokens Cube :::tip Need real-time data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this cube when you need **historical data older than ~30 days** (with `dataset: combined` or `archive`), custom OHLC intervals, or token-expanded rows. ::: > **Before you start**: Not sure when to use DexTradesByTokens vs DexTrades vs Events vs Calls? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. For a 1-page comparison of these three trade cubes, see [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades). The DEXTradesByTokens cube provides comprehensive information about DEX trading data from a token-centric perspective, showing both sides of each trade for every participant. This includes buyer, seller, token prices, pairs, transactions, OHLC data, and more. Unlike DEXTrades cube which uses `Buy` and `Sell` from the pool's perspective, DEXTradesByTokens uses the concept of `Trade` and `Side` to represent both sides of each trade from a token-centric view. ## Concept Explanation Let's understand the concept of buyer and seller when a trade occurs between User A and User B, and Token X and Token Y are swapped between them. ![Token A to Token B trade pair diagram](/img/tokenAB.png) We see the trade from user A's side, then we get the following: - User A becomes the seller of token X. - User A becomes the buyer of token Y. Now, if we see the trade from a user B side, we get the following. - User B becomes the seller of token Y. - User B becomes the buyer of token X. Therefore, buyers and sellers change relatively when the trade sides change. > Important note: If a trade occurs between User A and User B, the DexTradesByTokens API shows User A as both buyer and a seller, and similarly for User B. The result includes both perspectives, displaying each user as a buyer and then as a seller. [Run this API for better understanding](https://ide.bitquery.io/DEXTradeByTokens-API_1). When you run this API you get the following result. ```json { "EVM": { "DEXTradeByTokens": [ { "Trade": { "Buyer": "0x92560c178ce069cc014138ed3c2f5221ba71f58a", "Currency": { "Name": "Wrapped Ether" }, "Seller": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c", "Side": { "Buyer": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c", "Seller": "0x92560c178ce069cc014138ed3c2f5221ba71f58a" } } }, { "Trade": { "Buyer": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c", "Currency": { "Name": "Ethereum Name Service" }, "Seller": "0x92560c178ce069cc014138ed3c2f5221ba71f58a", "Side": { "Buyer": "0x92560c178ce069cc014138ed3c2f5221ba71f58a", "Seller": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c" } } } ] } } ``` In the above result, User A (0x925...) is included as both a buyer and a seller. The same applies to User B (0xa69...), who is also shown as both a buyer and a seller. If one become a buyer then other automatically become a seller. > Important note: Let's say currency X and currency Y are swapped in trade. Then, the trade side currency of X is Y, and the trade side currency of Y is X. Therefore, the trade side currency is relatively changed based on the currency that is traded against it. ## Understanding Trade and Side Structure In DEXTradesByTokens, each trade is represented with two main components: - **`Trade`**: The primary side of the trade, focusing on one specific token/currency - **`Side`**: The counter-side of the trade, representing what the token is being traded against ### Example Structure Comparison **DEXTrades Approach (Pool Perspective):** ```graphql Trade { Buy { Currency { Symbol } # What the pool buys Amount Buyer # Pool address } Sell { Currency { Symbol } # What the pool sells Amount Seller # User address } } ``` **DEXTradesByTokens Approach (Token Perspective):** ```graphql Trade { Currency { Symbol } # Primary token (e.g., "PEPE") Amount # Amount of primary token Buyer # Who bought the primary token Seller # Who sold the primary token Side { Currency { Symbol } # Counter token (e.g., "WETH") Amount # Amount of counter token Type # "buy" or "sell" (from pool's perspective) Buyer # Buyer of the side currency Seller # Seller of the side currency } } ``` **Note on Pool Role**: The `Side.Type` field indicates the pool's role relative to the side currency: - If `Side.Type` is `"buy"`, the pool is the buyer of the side currency (pool = `Side.Buyer`) - If `Side.Type` is `"sell"`, the pool is the seller of the side currency (pool = `Side.Seller`) ## How do I get OHLC in a DEXTradeByTokens query? {#how-do-i-get-ohlc-in-a-dextradebytokens-query} For OHLC, use the **[Crypto Price API](/docs/trading/crypto-price-api/)** (`Trading` → `Tokens` / `Pairs`) as the **main** source—pre-aggregated and simpler. **Use `DEXTradeByTokens` on this page when you need historical OHLC** or when you must derive candles from **raw DEX trades** for a specific token or pool. Aggregate trades into candles with **`Block { Time(interval: { count, in: minutes | hours | days }) }`** on **`DEXTradeByTokens`**, then derive **open / high / low / close** from **`PriceInUSD`** (or your chain’s price field)—for example **`minimum`** / **`maximum`** of **`Trade_PriceInUSD`** and **`minimum`/`maximum` of `Block_Number`** for open and close. Filter by **`Trade.Currency`** (token address or mint) and optionally **`Trade.Dex`**. The same pattern works on **`EVM`** and **`Solana`**; see also [Solana OHLC API](/docs/blockchain/Solana/solana-dextrades/#solana-ohlc-api). ```graphql { EVM(network: eth, dataset: combined) { DEXTradeByTokens( limit: { count: 24 } orderBy: { ascending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Currency: { SmartContract: { is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" } } } Block: { Time: { since: "2024-12-01" } } } ) { Block { Time(interval: { count: 1, in: hours }) } Trade { open: PriceInUSD(minimum: Block_Number) high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) close: PriceInUSD(maximum: Block_Number) } volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## How do I use DEXTradeByTokens vs DEXTrades for OHLCV? {#how-do-i-use-dextradebytokens-vs-dextrades-for-ohlcv} For **OHLCV**, treat the **Crypto Price API** as the default—see [when to use which](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/#crypto-price-api-vs-dextradebytoken). Among DEX cubes, prefer **`DEXTradeByTokens`** for **one token’s** chart (all pools and sides from the token’s view with **`Trade`** + **`Side`**). Use **`DEXTrades`** when you need **each raw swap** as a row (pool **`Buy`/`Sell`** view, routing, or debugging). Both can power candles; **`DEXTradeByTokens`** is usually simpler for **per-token** open/high/low/close and volume. Compare with [DEXTrades](/docs/cubes/dextrades/). ## Filtering in DEXTradeByTokens Cube Filtering helps to fetch the exact data you are looking for. DexTradeByTokens Cube can filter based on currency, buyer, seller, dex, pool, sender, transaction, time, etc. Everything inside the "where" clause filters; it follows the `AND' condition by default. ## Advanced Use Cases and Processing Patterns ### Portfolio Tracking and User Analytics DEXTradesByTokens excels at tracking individual user activity across all their trades: #### User Portfolio Balance Tracker ```python def track_user_portfolio(user_address, trades_data): """Track user's token portfolio changes over time""" portfolio = defaultdict(lambda: {'balance': 0, 'total_bought': 0, 'total_sold': 0}) for trade in trades_data: token = trade['currency']['smart_contract'].lower() amount = float(trade['amount']) if trade['seller'].lower() == user_address.lower(): # User sold this token portfolio[token]['balance'] -= amount portfolio[token]['total_sold'] += amount elif trade['buyer'].lower() == user_address.lower(): # User bought this token portfolio[token]['balance'] += amount portfolio[token]['total_bought'] += amount return portfolio ``` #### Query for User Activity Tracking ```graphql query UserActivityTracking( $userAddress: String! $sinceDate: ISO8601DateTime! ) { EVM(dataset: combined, network: eth) { DEXTradeByTokens( where: { Block: { Time: { since: $sinceDate } } Trade: { # Get all trades where user is either buyer or seller any: [ { Buyer: { is: $userAddress } } { Seller: { is: $userAddress } } ] } } orderBy: { ascending: Block_Time } ) { Block { Time Number } Trade { Buyer Seller Amount AmountInUSD Currency { SmartContract Symbol Name } Side { Amount AmountInUSD Currency { SmartContract Symbol } } } Transaction { Hash Signer } } } } ``` ## How do I avoid duplicate results in DEX trade queries? **`DEXTradeByTokens`** intentionally returns **multiple rows per swap** (token-centric **Trade** + **Side**). If you want to avoid this, please specify the **Side** currency. Alternatively, switch to **`DEXTrades`** if you need **one row per pool swap**. To deduplicate during analysis, group or filter by **`Transaction.Hash`** (and trade index when present). For paging, use a **stable `orderBy`** and **time/blocks windows**; see [GraphQL limits](/docs/graphql/limits/). Background: [DEXTrades vs DEXTradeByTokens](/docs/cubes/dextradesbyTokens/#how-do-i-use-dextradebytokens-vs-dextrades-for-ohlcv) and the [mental model](/docs/start/mental-model-transfers-events-calls). --- ## DFlow API: Solana Swaps, Routes, Fees and Traders URL: https://docs.bitquery.io/docs/blockchain/Solana/dflow-api/ DFlow on Solana via Bitquery GraphQL: live aggregator swaps with the user's wallet, apps and bots routing through DFlow, top tokens, route legs and fees. # DFlow API: Solana Swaps, Routes, Fees and Traders DFlow is a Solana trading infrastructure company. Its aggregator, DFlow Swap, routes a trade across several venues for the best price, and apps reach it through the DFlow Trade API. The on-chain program is `DF1ow4tspfHX9JwWJsAb9epbkA8hmpSEAtxXy1V27QBH`. Bitquery records each aggregated swap in the Solana `DEXTrades` and `DEXTradeByTokens` cubes under `ProtocolName: "dflow"` and `ProtocolFamily: "DFlow"`. In the hour to 10:00 UTC on 2026-10-26 DFlow carried about 39,000 trades worth $7.4 million. Two things shape every query on this page: - **The user's wallet is in `Trade.Buy.Account.Owner`, not always in `Transaction.Signer`.** Apps such as FOMO sign and pay for their users' transactions, so the signer is the app. The DFlow row still carries the user's own wallet as the account owner. Wallets and bots that trade directly sign their own transactions, so signer and owner match. - **A routed swap produces more than one trade row.** The DFlow row is the user's trade, from the input token to the output token. The pools the route passed through appear as separate rows with their own protocol names. Filter on `ProtocolName: "dflow"` to count each user trade once. Every example runs in the [Bitquery IDE](https://ide.bitquery.io). To stream one, change `query` to `subscription` and remove `limit` and `orderBy`. For the FOMO app, which routes most of its trades through DFlow, see the [FOMO API](/docs/blockchain/Solana/fomo-api/). ## Latest DFlow swaps Each row is one user trade: what the user received (`Buy`), what they paid (`Sell`), the USD value and the user's wallet. [Run it in the IDE ➤](https://ide.bitquery.io/DFlow-latest-swaps) ```graphql query DFlowLatestSwaps { Solana { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolName: {is: "dflow"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Trade { Buy { Amount AmountInUSD Account { Owner } Currency { Symbol MintAddress } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } } Dex { ProtocolName ProgramAddress } } } } } ``` ## Apps and bots routing through DFlow Groups the last hour of DFlow trades by transaction signer. A signer with many distinct user wallets is an app that signs for its users; a signer with one wallet is a wallet or bot trading for itself. [Run it in the IDE ➤](https://ide.bitquery.io/DFlow-apps-and-bots-by-signer) ```graphql query DFlowSigners { Solana { DEXTrades( limit: {count: 20} orderBy: {descendingByField: "trades"} where: {Trade: {Dex: {ProtocolName: {is: "dflow"}}}, Block: {Time: {since_relative: {minutes_ago: 60}}}, Transaction: {Result: {Success: true}}} ) { Transaction { Signer } trades: count users: uniq(of: Trade_Buy_Account_Owner) volume_usd: sum(of: Trade_Buy_AmountInUSD) } } } ``` ## Most traded tokens on DFlow Ranks tokens by USD volume through DFlow in the last hour, leaving out SOL and USDC so the list shows what users are buying and selling. [Run it in the IDE ➤](https://ide.bitquery.io/DFlow-most-traded-tokens) ```graphql query DFlowTopTokens { Solana { DEXTradeByTokens( limit: {count: 20} orderBy: {descendingByField: "volume_usd"} where: {Trade: {Dex: {ProtocolName: {is: "dflow"}}, Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}}, Block: {Time: {since_relative: {minutes_ago: 60}}}, Transaction: {Result: {Success: true}}} ) { Trade { Currency { Symbol MintAddress } } trades: count volume_usd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## DFlow trades of one wallet Filters on the user's wallet as the account owner, which works whether the user signed the trade or an app signed it for them. Replace the address with the wallet you want. [Run it in the IDE ➤](https://ide.bitquery.io/DFlow-trades-of-a-wallet) ```graphql query DFlowWalletTrades { Solana { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolName: {is: "dflow"}}, Buy: {Account: {Owner: {is: "A5Y3Wz4t2trwdezJyWgaeugNEu6HfuQgEk8Bb8D2UF5Y"}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Trade { Buy { Amount AmountInUSD Currency { Symbol } } Sell { Amount Currency { Symbol } } } } } } ``` ## Route legs: which venue each DFlow swap used The DFlow program logs a `SwapEvent` for every leg of a route. `amm` is the program of the venue that filled the leg, and the mints and amounts are that leg's input and output, in each token's smallest unit. [Run it in the IDE ➤](https://ide.bitquery.io/DFlow-route-legs) ```graphql query DFlowRouteLegs { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "DF1ow4tspfHX9JwWJsAb9epbkA8hmpSEAtxXy1V27QBH"}, Method: {is: "SwapEvent"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` ## Fees taken on DFlow swaps Apps that integrate DFlow can charge a fee on each swap. The program logs a `FeeEvent` with the fee `account`, the `mint` and the `amount` in the mint's smallest unit. [Run it in the IDE ➤](https://ide.bitquery.io/DFlow-swap-fees) ```graphql query DFlowFees { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "DF1ow4tspfHX9JwWJsAb9epbkA8hmpSEAtxXy1V27QBH"}, Method: {is: "FeeEvent"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` ## Pitfalls - **Count user trades on the DFlow row only.** Adding the pool rows of the same transaction counts each trade two or more times. - **Signer is not the user for app trades.** Use `Trade.Buy.Account.Owner` for the user's wallet. - **Instruction data covers about 12 hours.** The route-leg and fee queries read `Instructions`, which is real-time only. Trade queries can go further back with `dataset: archive`. --- ## Dashboard : Top 10 Ethereum Token Pairs URL: https://docs.bitquery.io/docs/usecases/Top-10-ethereum-tokens/ Build Dashboard : Top 10 Ethereum Token Pairs: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Dashboard : Top 10 Ethereum Token Pairs The following tutorial helps build a Top 10 Ethereum Tokens Dashboard with Next JS and Bitquery APIs that fetches and displays the Top 10 Token Pairs in last 1 hour on Ethereum mainnet in desceneding order of number of transactions. ## Video Tutorial of the project ## Github Repository Github Code Repository - [Repository Link](https://github.com/Akshat-cs/Top-10-Ethereum-Tokens-live.git) ## Prerequisites 1. **Node.js** and **npm** installed on your system. 2. **Bitquery Account** with OAuth token (follow instructions [here](/docs/authorization/how-to-generate/)). 3. **Git** installed on your pc. ## Code Walkthrough ### Data Fetching We are going to fetch our dashboard data using these 3 files - #### 1. **data.js file** - We are using Bitquery API and made this `getData` utility function which will fetch top 10 Token Pairs according to the transactions happened in them in last 1 hour. Query used here gives the top pair addresses, tokens in them, total transactions, total buys, total sells, price in usd of the token ( at last 1 hour timestamp, past 5 min timestamp and current timestamp). We will use these prices to get Price change in our `page.js` file. You can test the saved query on ide [here](https://ide.bitquery.io/Top-10-pairs-on-ethereum_2). ```javascript // Function to fetch trade data const getData = async () => { // Get the current UTC time and subtract one hour and five minutes const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString(); const min5backtimestamp = new Date(Date.now() - 5 * 60 * 1000).toISOString(); let data = JSON.stringify({ query: ` query MyQuery($oneHourAgo: DateTime, $min5backtimestamp: DateTime) { EVM(network: eth, dataset: realtime) { DEXTradeByTokens( orderBy: {descendingByField: "total_trades"} limit: {count: 10} where: { Block: {Time: {since: $oneHourAgo}}, Trade: {Side: {Currency: {SmartContract: {is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}}}}, TransactionStatus: {Success: true} } ) { Trade { hour1: PriceInUSD(minimum: Block_Time) min5: PriceInUSD(minimum: Block_Time, if: { Block: { Time: { after: $min5backtimestamp } } }) end: PriceInUSD(maximum: Block_Time) Currency { Name Symbol } Side { Currency { Name Symbol } } Dex { ProtocolName ProtocolFamily ProtocolVersion SmartContract } } total_trades: count totalbuys: count(if: {Trade: {Side: {Type: {is: sell}}}}) totalsells: count(if: {Trade: {Side: {Type: {is: buy}}}}) total_traded_volume: sum(of: Trade_Side_AmountInUSD) } } } `, variables: { oneHourAgo, min5backtimestamp }, }); let config = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.NEXT_PUBLIC_BITQUERY_TOKEN}`, }, data: data, }; let response = await axios.request(config); return response.data.data.EVM.DEXTradeByTokens; }; export default getData; ``` #### 2. **liquidity.js file** - We are using Bitquery API here and have made this utility function `getLiquidityData` to get `current liquidity` and `initial liquidity` of a particular pool. We are going to pass the 10 pool addresses to `getLiquidityData` we are going to get when we call `getData` in `page.js` and get the initial and current liquidities for the top 10 pools. ```javascript // liquidityData.js const getLiquidityData = async (poolAddresses) => { let data = JSON.stringify({ query: ` query MyQuery ($poolAddresses: [String!]){ EVM(dataset: combined, network: eth) { Initial_liquidity: Transfers( limitBy:{by:Transfer_Receiver count:2} orderBy: {ascending: Block_Time} where: {Transfer: {Receiver: {in: $poolAddresses }}, TransactionStatus: {Success: true}} ) { Transaction { Hash } Transfer { Receiver Amount Currency { SmartContract Name Symbol } } } Current_liquidity: Balances( where: {Balance: {Address: {in: $poolAddresses}}} orderBy: {descending: Balance_Amount} ) { Currency { Name SmartContract Symbol } Balance { Address Amount(selectWhere: {gt: "0"}) } } } } `, variables: { poolAddresses }, }); let config = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.NEXT_PUBLIC_BITQUERY_TOKEN}`, }, data: data, }; let response = await axios.request(config); return response.data.data.EVM; }; export default getLiquidityData; ``` #### 3. **wethPrice.js file** - We used Bitquery API here to get the latest USD price of `WETH` token as it will help us in converting Amount of WETH to USD Amount in current liquidity. You can test the saved query on ide [here](https://ide.bitquery.io/get-weth-price). ```javascript const getPrice = async () => { let data = JSON.stringify({ query: ` query MyQuery{ EVM(network: eth, dataset: realtime) { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Currency: {SmartContract: {is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}}, Side: {Currency: {SmartContract: {is: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"}}}}, TransactionStatus: {Success: true}} ){ Trade{ PriceInUSD } } } } `, variables: {}, }); let config = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.NEXT_PUBLIC_BITQUERY_TOKEN}`, }, data: data, }; let response = await axios.request(config); return response.data.data.EVM.DEXTradeByTokens; }; export default getPrice; ``` ### Dashboard frontend #### **page.js file** The `page.js` file is a React component that serves as the main page for displaying the top 10 Ethereum token pairs traded in the last hour. It uses Bitquery APIs to fetch and display various data, including trade information, token prices, and liquidity data. #### 1. Imports The component imports necessary dependencies, including React, hooks (`useState`, `useEffect`), and three functions (`getData`, `getPrice`, `getLiquidityData`) used to fetch trade details, weth price, and liquidity data, respectively. #### 2. State Management It uses the `useState` hook to manage several states, such as `trades`, `liquidityData`, `currentPage`, and `price`. #### 3. Component Structure ##### a. **State Initialization**: - `trades`: Stores the trade data. - `liquidityData`: Stores initial and current liquidity data. - `currentPage`: Keeps track of the current page number for pagination. - `price`: Stores the price data. ##### b. **Data Fetching with `useEffect`**: - The first `useEffect` fetches trade and price data using `getData` and `getPrice` functions and sets the `trades` and `price` states. - The second `useEffect` fetches liquidity data once the `trades` data is available. It extracts pool addresses from the trades and fetches corresponding liquidity data using the `getLiquidityData` function. ##### c. **Utility Functions**: - `truncateAddress(address)`: Truncates a given address for display purposes. - `calculatePriceChange(endPrice, hour1Price, min5Price)`: Calculates the percentage change in price over the last hour and the last 5 minutes. - `formatInitialLiquidity(liquidityList)`: Formats the initial liquidity for display, showing both token amounts. - `formatCurrentLiquidity(liquidityList, rowCurrencySymbol, currentPrice)`: Formats the current liquidity in USD based on the token amounts and prices. ##### d. **Rendering**: - The component displays a table with information about the top 10 Ethereum pairs, including token pair, price, DEX, smart contract address, price change, total traded volume, transaction count, initial liquidity, and current liquidity. - It uses the `currentTrades` variable to slice the trades array for pagination and display the trades of the current page. ##### e. **Export**: - The component is exported as the default export of the file. #### 4. **Key Components in the Table** - **Token Pair**: Displays the symbol of the trading pair. - **Price**: Shows the current price in USD. - **DEX**: The decentralized exchange where the pair is traded. - **Pair Smart Contract**: A link to the smart contract address on the Bitquery explorer. - **Price Change (1 Hour and 5 Min)**: Displays the percentage price change in the last hour and last 5 minutes. - **Total Traded Volume**: The total volume traded for the pair. - **Txns**: The number of transactions, including buys and sells. - **Initial Liquidity**: The initial liquidity provided in the pool. - **Current Liquidity**: The current liquidity in USD. --- ## Data Coverage & Retention: How Far Back Can You Query? URL: https://docs.bitquery.io/docs/graphql/data-coverage-retention/ How much history each Bitquery API keeps per chain — realtime vs archive vs combined datasets, Kafka backfill, and when to use Data Store exports. # Data Coverage & Retention How far back Bitquery data goes depends on the **chain**, the **cube** (Trades, Transfers, Balances, Holders, …), the **dataset** (`realtime`, `archive`, `combined`), and the **interface** (GraphQL, WebSocket, Kafka, or a [Data Store export](https://bitquery.io/datastore)). This page is the single source of truth for those windows. **If a query returns empty results for a date range, check here first** — most "missing data" reports are really a dataset or retention mismatch, not a bug. :::note Windows expand over time Retention windows widen as coverage grows. If you need more than the realtime window, add the chain's historical add-on to a paid plan, move to Enterprise for complete history on every chain, or buy a [Data Store export](https://bitquery.io/datastore) (see below). ::: ## The three datasets: realtime, archive, combined Every GraphQL cube is served from one or more datasets, selected with the `dataset:` argument: - **`realtime`** — the most recent data (roughly the last few hours), lowest latency. Always available. - **`archive`** — deep history. Available where Bitquery has back-indexed the chain/cube. - **`combined`** — stitches `archive` + `realtime` into one continuous result. Use it when you need both history and the latest rows in a single query. **Availability differs by chain and by cube.** Selecting a dataset a chain doesn't support surfaces a ClickHouse error such as `no table can query ... consider use realtime dataset`. That's not a bug — it means the archive/combined table for that cube isn't deployed on that chain. See the [dataset reference](/docs/graphql/dataset/realtime/) for details. :::caution `combined` is not available everywhere On **Solana**, `combined` works on `DEXTrades` and `DEXTradeByTokens`. `DEXTrades` on `archive` and `combined` needs a time or slot bound: see [Historical DEXTrades on archive and combined](/docs/blockchain/Solana/solana-dextrades/#historical-dextrades-archive-combined). For the other Solana cubes, see the Solana table below. On EVM chains, `combined` works on `Events` and `Calls`. A `Transfers` query that selects some `Call` fields, such as `Call.CallerIndex` or `Call.Value`, fails on `combined` with `no table can query Transfer`: query those fields on `realtime`. Where a dataset is genuinely undeployed you get the clean `no table can query …` message above. A raw 500 is a different thing. If you hit one, re-run the same query on `archive` before treating it as an outage. ::: :::tip Measure your own window Retention also depends on your plan, so confirm rather than assume. One query per cube gives you the floor: ```graphql query RetentionFloor { Solana(dataset: realtime) { Transfers(limit: { count: 1 }) { Block { oldest: Time(minimum: Block_Time) newest: Time(maximum: Block_Time) } } } } ``` `Time(minimum: Block_Time)` returns the oldest row the dataset currently holds. Swap the cube, the `dataset:` and the chain root to fill in the matrix for your own account. Note that `Balances` and `Holders` expose `Block.Date` but **not** `Block.Time`, so the query above errors against them. Their grain is daily rather than per-block, so "how far back" is answered by ordering on `Block_Date` instead. See [end-of-day balances](/docs/usecases/end-of-day-balances/). ::: Rule of thumb: reach for `realtime` for live/streaming use cases, `combined` for "recent history + now", and `archive` for pure backfills — but only where the matrix below says archive exists. ## Coverage matrix Windows are expressed as rolling ranges, not fixed dates, so they stay correct over time. ### EVM chains (Ethereum, BSC, Base, Arbitrum, Optimism, Polygon, …) | Cube | realtime | archive / combined | Kafka | Notes | |---|---|---|---|---| | DEX Trades | ✅ | ✅ full history | ✅ | Deep history via `combined`. | | Transfers | ✅ | ✅ full history | ✅ | | | Transactions | ✅ | ✅ full history | ✅ | | | Balances | ✅ | ✅ | — | Query at a block/date for point-in-time balances. | | Holders | ✅ | ✅ all v2 EVM chains | — | The Holders API is available on all v2 EVM chains. | | Calls & Events | ✅ **~24 h** | ✅ full history (gaps on Base and BSC, see notes) | ✅ | **Base** calls and events for April 2025 to the end of May 2026 are being backfilled: on 6 November 2026 most of that range had no rows yet, apart from fragments between 5 and 23 May 2025. Base transfers, transactions and DEX trades have rows in every month of that period. **BSC** has no calls or events from 30 March 2026 14:20 UTC to 1 April 2026 00:00 UTC; BSC transfers and transactions cover those hours. | | Mempool | ✅ (stream) | — | — | Pending-tx data is realtime only. | Where EVM archive history starts for transfers, transactions, calls and events (measured on 6 November 2026): Ethereum 7 August 2015 (event logs from 8 August), Polygon 30 May 2020, BSC 29 August 2020, Arbitrum 31 August 2022, Optimism 6 June 2023 and Base 15 June 2023. Arbitrum history starts at the Nitro upgrade and Optimism history at the Bedrock upgrade; nothing older is in the archive. DEX trades start at the first DEX trade Bitquery parses on each chain, which is later than these dates on Ethereum, Polygon, BSC and Base. ### Solana | Cube | realtime | archive / combined | Kafka | Notes | |---|---|---|---|---| | `DEXTradeByTokens` | ✅ **~7 days** | Since mid-2024 (`archive`) | ✅ | The longer-retention chain-level trade cube (vs ~12 h on `DEXTrades`). For anything within ~30 days prefer the [Trading cube](/docs/trading/trading-data-overview/); use this for older history or instruction context. | | `DEXTrades` | ✅ **~12 hours** | Individual trades, being backfilled toward 2024 (`archive` / `combined`) | ✅ | Same trades as above. On `archive` and `combined` a query needs a `Block.Time`, `Block.Slot` or `Block.Date` bound: see [Historical DEXTrades](/docs/blockchain/Solana/solana-dextrades/#historical-dextrades-archive-combined). | | OHLC / price aggregates | ✅ | Minute-level since October 2024 | ✅ (trading topics) | Chain-level aggregated candles go back much further than raw trades. (Distinct from the `Trading` cubes' pre-aggregated OHLC, which is ~30 days.) | | `Transfers` | ✅ **~12 hours** | — | ✅ | Older history via a Data Store export. | | `Instructions` | ✅ **~12 hours** | — | ✅ | Deep historical instruction lookup by signature is not available via API. | | `InstructionBalanceUpdates` | ✅ **~12 hours** | — | ✅ | | | `BalanceUpdates` | ✅ **~12 hours** | — | ✅ | Solana has no `Balances` cube; balance changes are queried here. | | `DEXPools` | ✅ **~12 hours** | — | ✅ | Realtime only. The `archive` / `combined` datasets do not exist for this cube — a query against them errors with `no API tables for cube DEXPool`. For historical pool state use a [Data Store export](/docs/cloud/). | | `Transactions` / `Blocks` / `Rewards` / `DEXOrders` / `TokenSupplyUpdates` | ✅ **~12 hours** | — | ✅ | | :::warning Two Solana cubes carry the same trades with very different depth On `realtime`, `DEXTrades` retains roughly **12 hours**; `DEXTradeByTokens` retains roughly **7 days** — about 15× longer, from the same underlying trades. On `archive`, `DEXTrades` holds individual trades, being backfilled toward 2024, and `DEXTradeByTokens` reaches back to mid-2024 as aggregates. That pair is the exception, not a general rule: **every other Solana realtime cube measured here holds roughly 12 hours**, including `BalanceUpdates`, `DEXPools`, `Transfers`, `Instructions` and `TokenSupplyUpdates`. If a Solana query "loses" older data, check whether `DEXTradeByTokens` or an archive dataset covers the same question before assuming the history is gone. ::: ### Tron & Bitcoin | Cube | realtime | archive / combined | Notes | |---|---|---|---| | Transfers / Transactions | ✅ | ✅ full history | Full archive available. | | Balances | ✅ | ✅ | Point-in-time supported. | | Coinpath (money flow) | — | ✅ (v1) | Coinpath is served by the [v1 API](https://docs.bitquery.io/v1/); there is no v2 equivalent yet. For AI-driven fund tracing, use the [Bitquery MCP server](https://mcp.bitquery.io/) ([Tracing MCP guide](/docs/mcp/Tracing/overview)). | ### Trading cube (cross-chain Trades / Tokens / Pairs) | Surface | Window | Notes | |---|---|---| | Trades / Tokens / Pairs / Currencies | ~30 days | All four cubes measure the same floor. For older raw trades use chain-level `DEXTradeByTokens` or a Data Store export. | | Price / OHLC aggregates (`Tokens` / `Pairs` / `Currencies`) | ~30 days | Pre-aggregated OHLC down to 1-second intervals, same rolling window as `Trades`. See the [Crypto Price API](/docs/trading/crypto-price-api/). | ### Robinhood chain | Cube | Window | Notes | |---|---|---| | Trades | Since the chain was onboarded | Full history from onboarding forward. | | Transfers | Complete history | Full transfer history available. | ### Arc mainnet Circle's Arc mainnet uses `EVM(network: arc)`. The realtime path, USD fields, `Holders`, and the cross-chain `Trading.Trades`, `Trading.Tokens`, and `Trading.Pairs` cubes returned live data in checks on 16 September 2026. `dataset: archive` and `dataset: combined` were not enabled, so leave the dataset argument out and measure the live window before assuming a range. See the [Arc Mainnet API guides](/docs/blockchain/arc-mainnet/). | Surface | Window | Notes | |---|---|---| | EVM cubes | Realtime window | Query with `EVM(network: arc)` and no dataset argument. | | `Trading.Trades`, `Trading.Tokens`, `Trading.Pairs` | Trading rolling window | Filter with network name `Arc` or network id `bid:arc`. | | `archive`, `combined` | Not available | Retry before building a historical backfill. | ### Arc testnet Circle's Arc testnet (`EVM(network: arc_testnet)`) is served from the **realtime dataset only**. There is no archive for the testnet, so `dataset: archive` and `dataset: combined` return errors, the `Holders` cube is not available, and every `...InUSD` field is 0. The realtime window is a rolling range of recent blocks; measure it with `Block { Time(minimum: Block_Time) }`. Use [Arc mainnet](/docs/blockchain/arc-mainnet/) for live production data with USD pricing. See the [Arc Testnet hub](/docs/blockchain/arc-testnet/). | Cube | Window | Notes | |---|---|---| | `DEXTrades`, `DEXTradeByTokens`, `Transfers`, `Events`, `Calls`, `Transactions`, `Blocks`, `Balances`, `TransactionBalances` | Realtime window only | No archive; USD fields are 0. | | `Holders`, `DEXPoolEvents`, `DEXPoolSlippages`, `Trading.*` | Not available | `Holders` needs the archive; pool cubes have no data yet; the Trading cubes cover mainnet chains only. | ### Hyperliquid Hyperliquid core is an L1 order-book exchange, so its cubes carry exchange events rather than EVM blocks. The cubes are served from the realtime dataset only: `dataset: archive` and `dataset: combined` return the error `API schema not configured`. Windows measured on 13 October 2026: | Cube | realtime / API | API archive dataset | Kafka | Notes | |---|---|---|---|---| | `Trades`, `PerpLiquidations`, `PerpFundings`, `Twaps`, `PriceUpdates`, `TraderLeverageUpdates`, `Candles` | ✅ **~30 days** | Not available | ✅ | Fills, liquidations, hourly funding, TWAPs, leverage changes, and oracle and mark prices (HIP-3 markets only). Candles stream on their own topic. | | `Orders`, `BookUpdates`, `SignedActions` | ✅ **~7 days** of raw rows | Not available | ✅ | Order counts by market, trader, status, side or type come from 10-minute aggregates that reach back ~30 days, so a `count` over an older date returns numbers while a row-level select for the same date returns `[]`. | | `CurrentPositions`, `MarkPrices` | Current state, no time window | Not available | — | One row per account and market; `MarkPrices` has one per HIP-3 market. `RealizedPnl` and `Funding` are sums since the data window began (~30 days), not lifetime. Query only. | :::note Where older Hyperliquid data lives The API window is rolling, which suits bots, dashboards and monitoring. A query for a date before the window returns an empty list with HTTP 200, not an error. For older data: - **[Data Store export](/docs/cloud/hyperliquid/)**: parsed Hyperliquid tables as Parquet files. The Data Store lists the last 30 days on every table, including the order flow the API keeps for only ~7 days. Older ranges are available on request from [sales@bitquery.io](mailto:sales@bitquery.io). - **[Blockchain Data Lake](/docs/data-lake/#hyperliquid)**: the raw HyperCore feed (the node's event streams and consensus transactions) from 17 July 2026, which you decode and parse your own way. The parsed messages that Kafka and the API serve are not stored there. Hyperliquid's own `s3://hyperliquid-archive` bucket holds L2 book snapshots and asset contexts only, refreshed roughly monthly with no completeness guarantee. Contact [sales@bitquery.io](mailto:sales@bitquery.io) for a Hyperliquid export covering an older range. ::: ## Kafka is not a historical firehose Streams are for live data. Kafka keeps a **short replay window, not history**. Solana gRPC has no replay. If you connect a fresh consumer, you get recent messages forward, not the chain from genesis. For older data, use GraphQL (within the API's retention) or a Data Store export. See the [Kafka Operations Cookbook](/docs/streams/kafka-operations/). ## Need more history than the API keeps? When you need a full backfill beyond the API windows above: - **Data Store exports**: parsed Parquet datasets you download from S3 or Cloudflare R2 (or get delivered to your own bucket or warehouse as a custom export), including history older than the API window. See [Data Store exports](/docs/cloud/). - **Blockchain Data Lake**: raw Protobuf blocks over S3, using the same schema as the Kafka streams, which you decode and parse your own way. For Hyperliquid it holds the raw feed from 17 July 2026. See [Data Lake](/docs/data-lake/). - **Enterprise plans** — the self-serve plans (Personal/Pro/Scale) share a rolling window (about 30-day trades and 4–8h on-chain data); history on a self-serve plan comes from a per-chain historical add-on, Enterprise includes complete history on every chain, and a Data Store export covers bulk history. See the [pricing page](https://bitquery.io/pricing). See [Plans, Points & Limits](/docs/plans/how-billing-works/). Contact [sales@bitquery.io](mailto:sales@bitquery.io) for custom export ranges. ## Next steps - [Datasets: realtime, archive, combined](/docs/graphql/dataset/realtime/) - [Common errors — including empty results](/docs/start/errors/) - [Kafka Operations Cookbook](/docs/streams/kafka-operations/) - [Data Store exports (Parquet)](/docs/cloud/) --- ## Database Selection URL: https://docs.bitquery.io/docs/graphql/dataset/database/ Database Selection in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. See examples in the Bitquery IDE. # Database Selection Dataset attribute on the query top level defines the database to query: ![Dataset option](/img/ide/dataset_option.png) * ```realtime``` (default) is the real time database, containing the new blocks * ```archive``` is the finalized database, data from the first block to a recent time (from hours to minutes ago) * ```combined``` if you need to query both in one query --- ## Date and Time Filters in GraphQL URL: https://docs.bitquery.io/docs/graphql/datetime/ Date and Time Filters in GraphQL in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Date and Time ## Format We use the UTC timezone for both date and time. In Graphql, time is represented as a `DateTime` scalar type in the RFC 3339 quoted string format. ## Interval When aggregating data over time, use the interval argument for `Date` and `Time` fields. For example, in an OHLC query for [DEX trade](/docs/schema/evm/dextrades): ```graphql Time(interval: {in: minutes, count: 10}) ``` You can apply the same interval to `Date`: ```graphql Date(interval: {in: months, count: 12}) ``` :::note Maintain consistency by using order or orderBy when filtering data with `Time` or `Date`. If you create intervals using `Time`, use `Block_Time`, and for `Date`, use `Block_Date`. ::: ## Offset To shift the starting point of an interval, use the `offset` parameter: ```graphql Time(interval: {in: minutes count: 10 offset: 1}) ``` This configuration will count intervals starting at 1, 11, 21, and so on in minutes. --- ## Derived Values with calculate() URL: https://docs.bitquery.io/docs/trading/query-operators/calculate-expressions/ calculate(expression:) evaluates an expression server-side on the Bitquery Trading cube — the $ reference rule, when it forces a GROUP BY, and the coercion and non-finite traps. # Derived Values with `calculate()` `calculate(expression: "...")` computes a derived value server-side, so ratios, differences and percentages come back with the row instead of being assembled in your client. ```graphql buys: count(if: { Side: { is: "Buy" } }) all: count ratio: calculate(expression: "$buys / $all") ``` ## `$name` refers to a response key Inside an expression, `$name` refers to **a key in the same selection set** — the explicit alias when you give one, otherwise the field's own path with nested levels joined by underscore: | Selection | Reference | | --- | --- | | `all: count` | `$all` | | `Amounts { Base }` | `$Amounts_Base` | | `q: Amounts { Base }` | `$q_Base` | It reaches native fields, native metrics and other `calculate` results alike. **The `$` is required** — a bare `buys / all` is passed through as raw column names and fails. References are **order-independent** (a forward reference is fine) and chain to any depth. They compile to SQL aliases, so a self-reference fails with `Code: 47 MISSING_COLUMNS` and a mutual reference with `Code: 174 CYCLIC_ALIASES`. ## When your query becomes aggregated **`calculate` never triggers a GROUP BY on its own.** What matters is whether a *native* metric (`count`, `sum`, `uniq`, `average`, …) is present: - **No native metric** — the query stays in row mode. A bare column reference such as `"Amounts_Base"` evaluates per row and works fine. - **A native metric is present** — the API groups by the selected dimensions. Any bare column in your expression must now be one of those selected dimensions, or ClickHouse raises `Code: 215 NOT_AN_AGGREGATE`. :::caution The error names the wrong field `Code: 215` names the **dimension**, not your expression — for example `Column 'Price' is not under aggregate function and not in GROUP BY`. The fix is usually to add a native metric, or to select the column your expression references. ::: An aggregate expression on its own is fine — `calculate(expression: "sum(Amounts_Base)")` with nothing else selected returns one row. It only needs a companion native metric once you also select a dimension. ## What you can write The expression is evaluated by ClickHouse, so the standard function library is available: arithmetic (`+ - * / %`), `pow`, `sqrt`, `abs`, `log`, `round`, `greatest`, `least`, conditionals (`if`, `multiIf`), aggregates (`sum`, `count`, `avg`, `min`, `max`, `uniqExact`, `argMax`, `sumIf`, `countIf`, `quantile(0.5)(...)`) and window forms such as `row_number() OVER ()`. ```graphql buyShare: calculate(expression: "countIf(Side = 'Buy') / count()") ``` Use **single quotes** for SQL string literals — the expression is a GraphQL string, so a double quote must be escaped. Commas, nested parentheses, newlines and SQL comments are all fine. ## Ranking by a derived value `orderBy` accepts a `calculate` alias, and it composes with `limitBy` — this is the rank-by-derived-ratio pattern: ```graphql orderBy: { descendingByField: "buyShare" } limitBy: { by: Pair_Token_Address, count: 1 } ``` `calculate` itself takes **no `selectWhere` and no `if:`** — `expression` is its only argument. To gate a ranked ratio, put a `selectWhere` floor on a sibling aggregate (for example `count(selectWhere: { ge: "100" })`) and apply the final cut on the ratio in your client. ## Traps | Trap | Behaviour | | --- | --- | | **Everything coerces to Float** | The expression is wrapped in `toFloat64(...)` and the field's type is `Float`. A string-producing expression fails with `Code: 6` unless the string parses as a number — `toString(42)` works, `concat('a','b')` does not | | **`^` is not exponentiation** | `2^3` fails with `Code: 62`. Use `pow(2,3)` | | **The ternary `? :` is unusable** | `?` collides with the SQL builder's placeholder — `not enough args when interpolating`. Use `if(cond, a, b)` | | **Booleans and dates flatten** | `Bool` → `1`/`0`, `DateTime` → unix seconds, `Date` → days since epoch | :::danger Infinity, NaN and NULL are silently returned as `0` A divide-by-zero ratio comes back as `0`, indistinguishable from a genuine zero — and under `ascendingByField` those rows sort **first**. The values really are non-finite inside ClickHouse (`isInfinite(count()/0)` returns `1`), so guard the denominator yourself: ```graphql safe: calculate(expression: "$numerator / nullIf($denominator, 0)") ``` ::: ## In subscriptions The grammar is much narrower on a stream: **arithmetic only**. Every function call — `round()`, `floor()`, `abs()` — returns `null`, and a single unsigiled reference makes the whole expression `null` with no error. See [what does not survive streaming](/docs/subscriptions/what-does-not-survive-streaming/). ## Related - [Expressions (general reference)](/docs/graphql/capabilities/expression/) - [Screeners with `selectWhere`](/docs/trading/query-operators/selectwhere-screeners/) - [Statistics](/docs/trading/query-operators/statistics/) --- ## Detect Sandwich Attack Opportunities URL: https://docs.bitquery.io/docs/usecases/sandwich-detection/ Build Detect Sandwich Attack Opportunities: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # How to Detect Sandwich Opportunities - Tutorial ### MEV Opportunities Detection Bitquery's queries can help users in DeFi space by providing them with the potential MEV opportunities. By providing real-time data from Mempool on transaction amount, and other key metrics, Bitquery can help users to identify such money making opportunities. ## Tutorial This is a tutorial to build a simple webpage using PHP code that connects to the Bitquery API and retrieves data for sandwich attack opportunities on the Ethereum network. The code then displays the data on a webpage built using PHP and HTML. ## GraphQL query For this tutorial, we will use [this](https://ide.bitquery.io/Sandwitch-Opportunity_1) query given below. The sandwich attack observes the DEX Trade transaction in Mempool with a large purchase amount as it will highly influence the price of the token. For this tutorial, the logic is that any transaction with a 'Buy Amount' greater than 1000 USD would influence the price of the token in the pool, hence we will place two transactions around the target transaction, so that we could get an instantaneous profit on the same. ```graphql subscription { EVM(mempool: true) { DEXTrades(where: {Trade: {Buy: {AmountInUSD: {gt: "1000"}}}}) { Trade { Buy { AmountInUSD Buyer Currency { Name Symbol SmartContract } } Dex { OwnerAddress SmartContract ProtocolFamily } Sell { AmountInUSD Currency { Name Symbol SmartContract } } } Block { Time } } } } ``` ## Required Libraries The code uses the following libraries: HTTP_Request2: A PHP library for interacting with APIs ## Step by Step Code Implementation ### Installation Before writing any code, make sure that the required libraries are installed using the following command: ```shell sudo pear install http_request2 ``` ### Importing the Required Libraries The first step in the code is to import the required libraries using the import statement: ```php ``` ### Establishing Connection with the Bitquery API Next, the code connects to the Bitquery API using the HTTP_Request2 library and retrieves data on the latest sandwich opportunities across all EVM chains (in support) using a GraphQL query. The query is passed as a JSON payload to the request() method, along with the necessary headers and oAuth Token. ```php $request = new HTTP_Request2(); $request->setUrl('https://streaming.bitquery.io/graphql'); $request->setMethod(HTTP_Request2::METHOD_POST); $request->setConfig(array( 'follow_redirects' => TRUE )); $request->setHeader(array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer YOUR_ACCESS_TOKEN' )); $request->setBody('{"query":"subscription {\\n EVM(mempool: true) {\\n DEXTrades(where: {Trade: {Buy: {AmountInUSD: {gt: \\"1000\\"}}}}) {\\n Trade {\\n Buy {\\n AmountInUSD\\n Buyer\\n Currency {\\n Name\\n Symbol\\n SmartContract\\n }\\n }\\n Dex {\\n OwnerAddress\\n SmartContract\\n ProtocolFamily\\n }\\n Sell {\\n AmountInUSD\\n Currency {\\n Name\\n Symbol\\n SmartContract\\n }\\n }\\n }\\n Block {\\n Time\\n }\\n }\\n }\\n}\\n","variables":"{}"}'); $response = $request->send(); $responseBody = $response->getBody(); $responseData = json_decode($responseBody, true); $sandwichOpportunityData = $responseData['data']['EVM']['DEXTrades'] ``` The code retrieves an array of necessary data to execute trade from the response data and stores it in the sandwichOpportunityData variable. ### Building the webpage The code then displays the retrieved data in a PHP webpage built using basic HTML. The webpage includes a simple table with all the real time data retrieved from the Bitquery API. ```php echo ''; echo '

Sandwich MEV Opportunities

'; echo '

Possibilities on EVM chains

'; echo '
';
echo formatArrayAsTable($sandwichOpportunityData);
echo '
'; echo ''; ``` The formatArrayAsTable() method is used to render the array as a table. ### Adding a Table #### Adding table headers This function will be used to get the column headings for the table. ```php function getTableHeaders($data) { $headers = []; foreach ($data as $row) { foreach ($row as $key => $value) { if (!in_array($key, $headers)) { $headers[] = $key; } } } return $headers; } ``` #### Helper function This function will be used to recursively flattens the nested arrays and objects into a single-level array with concatenated keys. ```php function flattenArray($array, $prefix = '') { $result = []; foreach ($array as $key => $value) { $newKey = $prefix ? "{$prefix}_{$key}" : $key; if (is_array($value)) { $result = array_merge($result, flattenArray($value, $newKey)); } else { $result[$newKey] = $value; } } return $result; } ``` Finally this code snippet takes up the latest DEX trades with large purchase amount from the EVM chains, and displays them in a table using simple HTML. ```php function formatArrayAsTable($data) { $flattenedData = array_map('flattenArray', $data); $html = ''; $html .= ''; $columns = getTableHeaders($flattenedData); foreach ($columns as $column) { $html .= ''; } $html .= ''; $html .= ''; foreach ($flattenedData as $row) { $html .= ''; foreach ($columns as $column) { $html .= ''; } $html .= ''; } $html .= '
' . htmlspecialchars($column) . '
' . htmlspecialchars($row[$column] ?? '') . '
'; return $html; } ``` ### Important Note Make sure that all the above code snippets lies within the php tag shown below. ```php ``` ## Here's how it looks If you want to build up query from scratch you are welcome or you can use the [premade examples](https://ide.bitquery.io/explore/All%20queries) as well. ## Video Tutorial on How to Detect Sandwich Opportunities --- ## ERC20 Token Transfers API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api/ Query and stream Ethereum ERC-20 and native transfers: filter by contract or address, aggregate volume, rank top transfers and backfill deterministically. # ERC20 Token Transfers API Track and analyze ERC20 token transfers across the Ethereum blockchain in real-time and historically. Monitor token movements, analyze transfer volumes, track wallet activity, and build comprehensive token transfer analytics using Bitquery's ERC20 Token Transfers API. ## What are ERC20 Token Transfers? ERC20 is the most widely adopted token standard on Ethereum, enabling fungible tokens that can be transferred between addresses. ERC20 token transfers represent the movement of tokens from one wallet to another, forming the foundation of DeFi, trading, and token-based applications. Understanding ERC20 transfers is essential for: - **Portfolio Tracking**: Monitor token movements in and out of wallets - **Tax & Accounting**: Generate comprehensive transfer reports for crypto tax calculations, cost basis tracking, and token accounting reconciliation - **Compliance & Auditing**: Track token flows for regulatory requirements - **DeFi Analytics**: Analyze liquidity movements and protocol interactions - **Token Analytics**: Understand token distribution and holder behavior - **Security Monitoring**: Detect suspicious transfers and wallet activity ## 🔗 Related APIs ### Ethereum APIs - **[Ethereum Balance API](/docs/blockchain/Ethereum/balances/balance-api)** - Get wallet balances for ERC20, ERC721, and ERC1155 tokens - **[Ethereum Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/)** - Track real-time balance changes with reason codes - **[Ethereum Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api)** - Get top token holders and distribution data - **[Ethereum Token Supply API](/docs/blockchain/Ethereum/token-supply/evm-token-supply)** - Track total supply and supply changes - **[Ethereum DEX Trades API](/docs/blockchain/Ethereum/dextrades/dex-api)** - Monitor DEX trading activity - **[Ethereum Transactions API](/docs/blockchain/Ethereum/transactions/transaction-api)** - Get comprehensive transaction data - **[Ethereum Events API](/docs/blockchain/Ethereum/events/events-api)** - Query smart contract events ### EVM APIs - **[EVM Transfers API](/docs/schema/evm/transfers)** - General EVM token transfers documentation - **[EVM Balance Updates API](/docs/schema/evm/balances)** - Track balance changes across EVM chains - **[EVM DEX Trades API](/docs/schema/evm/dextrades)** - DEX trading data across EVM chains ### NFT & Other Token Standards - **[NFT Transfer API](/docs/blockchain/Ethereum/transfers/nft-token-transfer-api)** - Track ERC721 and ERC1155 NFT transfers - **[RWA Token API](/docs/blockchain/Ethereum/transfers/rwa-api)** - Real World Asset token transfers ### Solana APIs - **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** - Track SPL token transfers and SOL transfers on Solana - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor Solana wallet balance changes - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Track Solana DEX trading activity --- ## 📋 Table of Contents - **How do I get token transfers for a specific contract?** - Filter by ERC-20 address - **How do I get all inbound and outbound transfers for an address?** - Sender or receiver OR filter - **Get Latest ERC20 Token Transfers** - Query recent token transfers - **Subscribe to Real-Time Transfers** - WebSocket subscriptions for live data - **Filter by Sender or Receiver** - Query transfers involving specific addresses - **Transfer Volume Analysis** - Calculate sent and received volumes - **Top Transfers** - Get largest token transfers - **Earliest Transfer Tracking** - Find first transfers to addresses - **Use Cases** - Common applications and examples - **API Response Fields** - Complete field reference --- ## How do I get token transfers for a specific contract? Query `EVM.Transfers` with `where.Transfer.Currency.SmartContract` equal to the ERC-20 contract address, plus `dataset` and `network` (`eth` or another EVM chain). Order by `Block_Time` and use `limit` for pagination. The same filter works for historical windows using `Block.Time` or related filters. ```graphql { EVM(dataset: realtime, network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount Currency { Name Symbol } Receiver Sender Type } Block { Time Number } Transaction { Hash } } } } ``` ## Get Latest ERC20 Token Transfers Query the most recent ERC20 token transfers for any token on Ethereum. This example retrieves the latest USDT (Tether) token transfers. The contract address for USDT is [0xdac17f958d2ee523a2206206994597c13d831ec7](https://explorer.bitquery.io/ethereum/token/0xdac17f958d2ee523a2206206994597c13d831ec7). You can run this query [here](https://ide.bitquery.io/UDST-Token-Transfers-on-Ethereum_2). ```graphql { EVM(dataset: realtime, network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount Currency { Name Symbol } Receiver Sender Type } } } } ``` **Common ERC20 Token Addresses (Ethereum):** | Token | Contract Address | Symbol | | ----- | -------------------------------------------- | ------ | | USDT | `0xdac17f958d2ee523a2206206994597c13d831ec7` | USDT | | USDC | `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` | USDC | | WETH | `0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` | WETH | | DAI | `0x6b175474e89094c44da98b954eedeac495271d0f` | DAI | | LINK | `0x514910771af9ca656af840dff83e8264ecf986ca` | LINK | --- ## Query Multiple Tokens in a Single Query Query transfers for multiple ERC20 tokens simultaneously using the `in` operator. This is useful for monitoring multiple tokens at once, building portfolio trackers that track several tokens, or analyzing transfers across a token basket. The example below queries transfers for USDT, USDC, WETH, and native ETH (`0x` represents native ETH) in a single request: ```graphql { EVM(dataset: realtime, network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { in: [ "0xdac17f958d2ee523a2206206994597c13d831ec7" "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" "0x" ] } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount Currency { Name Symbol } Receiver Sender Type } } } } ``` **Use Cases:** - Monitor multiple stablecoins simultaneously (USDT, USDC, DAI) - Track transfers for a portfolio of tokens - Analyze token movements across a token basket - Build multi-token dashboards and analytics :::tip Multi-Chain Support **Query Any EVM Network**: Change the `network` parameter to query token transfers on other EVM-compatible blockchains: - `eth` - Ethereum Mainnet - `bsc` - BNB Smart Chain (BSC) - `base` - Base L2 - `arbitrum` - Arbitrum One - `matic` - Polygon PoS - `optimism` - Optimism L2 **Example for BSC:** ```graphql { EVM(dataset: realtime, network: bsc) { Transfers( where: { Transfer: { Currency: { SmartContract: { in: ["0x55d398326f99059fF775485246999027B3197955"] // USDT on BSC } } } } limit: { count: 10 } ) { Transfer { Amount Currency { Name Symbol } Sender Receiver } } } } ``` **Solana Token Transfers**: For SPL token transfers on Solana, see our **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** documentation. ::: --- ## Subscribe to Real-Time ERC20 Token Transfers Monitor ERC20 token transfers in real-time using GraphQL subscriptions. This is ideal for building live dashboards, alert systems, and real-time analytics applications. This example subscribes to WETH (Wrapped Ethereum) token transfers. The contract address is [0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2](https://explorer.bitquery.io/ethereum/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2). You can test this subscription [here](https://ide.bitquery.io/Subscribe-to-Latest-WETH-token-transfers). ```graphql subscription { EVM(network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } orderBy: { descending: Block_Time } ) { Transaction { Hash } Transfer { Amount Currency { Name Symbol } Receiver Sender Type } } } } ``` :::tip Real-Time Monitoring For more information on setting up real-time subscriptions, see our [GraphQL Subscriptions documentation](/docs/subscriptions/subscription). ::: --- ## How do I get all inbound and outbound transfers for an address? Query transfers where a specific address is either the sender or receiver. This uses the `any` filter to implement OR logic, allowing you to find all transfers involving a particular address regardless of direction. Use `EVM.Transfers` with `where.any`: one branch matches `Transfer.Sender`, the other `Transfer.Receiver`, both set to the wallet. That returns **ERC-20** movements in both directions. Add `Block.Time` or `Block.Number` for windows, and `Currency.SmartContract` if you only want one token. Native coin movements use a separate native-transfer pattern on the same `Transfers` cube with appropriate currency filters. You can find the query [here](https://ide.bitquery.io/Sender-OR-Receiver-Transfer-on-Ethereum). ```graphql query MyQuery { EVM(dataset: archive, network: eth) { Transfers( where: { any: [ { Transfer: { Sender: { is: "0x881d40237659c251811cec9c364ef91dc08d300c" } } } { Transfer: { Receiver: { is: "0x881d40237659c251811cec9c364ef91dc08d300c" } } } ] Block: { Number: { eq: "23814227" } } } limit: { count: 100 } orderBy: { descending: Block_Time } ) { Transfer { Amount Sender Receiver Currency { Symbol Name } } Transaction { Hash From To Index } Block { Number Time } } } } ``` --- ## Addresses That Sent or Received from Multiple Addresses Find addresses that have interacted with multiple addresses from a given list. This query uses the `array_intersect` function to identify addresses that have sent or received funds to/from every address in your list. You can run the query [here](https://ide.bitquery.io/array_intersect-example-for-2-addresses_2). ```graphql query ($addresses: [String!]) { EVM(dataset: archive) { Transfers( where: { any: [ { Transfer: { Sender: { in: $addresses } } } { Transfer: { Receiver: { in: $addresses } } } ] Block: { Date: { after: "2024-04-01" } } } ) { array_intersect( side1: Transfer_Sender side2: Transfer_Receiver intersectWith: $addresses ) } } } ``` **Variables:** ```json { "addresses": [ "0x21743a2efb926033f8c6e0c3554b13a0c669f63f", "0x107f308d85d5481f5b729cfb1710532500e40217" ] } ``` :::note Array Intersect Function Learn more about the `array_intersect` function in our [Array Intersect documentation](/docs/graphql/capabilities/array-intersect). ::: --- ## Transfer Volume Analysis (Sent and Received) Calculate the total amount of tokens sent and received by a specific address for a particular token over a time period. This is essential for portfolio analysis, tax reporting, and wallet analytics. You can run this query [here](https://ide.bitquery.io/transfer-volume). ```graphql query MyQuery($address: String, $token: String) { EVM { Transfers( where: { Block: { Time: { since_relative: { years_ago: 1 } } } Transfer: { Currency: { SmartContract: { is: $token } } any: [ { Transfer: { Sender: { is: $address } } } { Transfer: { Receiver: { is: $address } } } ] } } ) { Sent: sum( of: Transfer_Amount if: { Transfer: { Sender: { is: $address } } } ) Received: sum( of: Transfer_Amount if: { Transfer: { Receiver: { is: $address } } } ) } } } ``` **Variables:** ```json { "address": "0x782c362fbf71f939445e6902a064f7e9384f47e2", "token": "0x" } ``` :::note Native ETH Transfers Use `"0x"` as the token address to query native ETH transfers. For ERC20 tokens, use the token's contract address. ::: --- ## Top Transfers of a Token Retrieve the largest token transfers for any ERC20 token. This is useful for identifying whale movements, large transactions, and significant token flows. Try the query [here](https://ide.bitquery.io/Copy-of-top-transfers-of-a-token-on-Ethereum). ```graphql query MyQuery { EVM(dataset: archive) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } TransactionStatus: { Success: true } Block: { Date: { is: "2024-06-29" } } } orderBy: { descending: Block_Time } limit: { count: 10 } ) { Transfer { Amount AmountInUSD Currency { Name Symbol SmartContract } Success Sender Receiver Index Id } Transaction { To Hash Value Type GasPrice Gas From Cost } Log { Signature { Signature Name } SmartContract } Call { From To Value Signature { Name } } Block { Number Time } } } } ``` --- ## Earliest Transfer to a Wallet Find the first transfer ever received by a specific wallet address. This is useful for wallet age analysis, first transaction tracking, and onboarding analytics. [Run Query](https://ide.bitquery.io/Copy-of-find-earliest-transfer-to-an-account). ```graphql query MyQuery { EVM(network: eth, dataset: archive) { Transfers( limit: { count: 1 } where: { Transfer: { Receiver: { is: "0xe37b87598134a2fc0Eda4d71a3a80ad28C751Ed7" } } } ) { Block { Time(minimum: Block_Number) } Transaction { From Hash } Transfer { Amount Currency { Native } } } } } ``` --- ## Use Cases ### 1. Portfolio Tracking & Analytics Track all token transfers for a wallet to build comprehensive portfolio dashboards: - Monitor incoming and outgoing transfers - Calculate total sent/received volumes - Track transfer history over time - Build transaction timelines **Related APIs:** - [Ethereum Balance API](/docs/blockchain/Ethereum/balances/balance-api) - Get current wallet balances - [Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) - Real-time balance updates ### 2. Tax & Accounting Generate comprehensive transfer reports for tax calculations, accounting reconciliation, and financial reporting: **Tax Use Cases:** - Calculate capital gains/losses from token transfers - Track cost basis for tax reporting (FIFO, LIFO, or specific identification) - Generate Form 8949 compatible reports - Calculate realized gains/losses by token and date - Export transfer history for tax software integration **Accounting Use Cases:** - Reconcile token movements with accounting records - Track transfer volumes by token and time period - Generate audit trails for financial statements - Calculate token balances from transfer history - Export CSV/JSON reports for accounting systems **Key Features:** - Export all transfers for a wallet with timestamps - Calculate transfer volumes by token - Track transfer dates and USD values - Generate comprehensive CSV/JSON reports - Filter transfers by date ranges for tax periods ### 3. DeFi Protocol Analytics Analyze token flows in and out of DeFi protocols: - Monitor liquidity movements - Track protocol token distributions - Analyze user deposit/withdrawal patterns - Measure protocol adoption **Related APIs:** - [Ethereum DEX Trades API](/docs/blockchain/Ethereum/dextrades/dex-api) - Track DEX trading activity - [Ethereum Events API](/docs/blockchain/Ethereum/events/events-api) - Monitor smart contract events ### 4. Token Distribution Analysis Understand how tokens are distributed across addresses: - Track token holder changes - Analyze concentration metrics - Monitor whale movements - Identify distribution patterns **Related APIs:** - [Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api) - Get top holders - [Token Supply API](/docs/blockchain/Ethereum/token-supply/evm-token-supply) - Track supply changes ### 5. Security & Fraud Detection Monitor transfers for suspicious activity: - Detect large unexpected transfers - Track transfers to known scam addresses - Monitor wallet activity patterns - Set up real-time alerts ### 6. Wallet Analytics Build comprehensive wallet analysis tools: - Calculate wallet age (earliest transfer) - Track transfer frequency - Analyze token diversity - Monitor wallet activity levels --- ## API Response Fields | Field | Description | | ------------------------------ | ---------------------------------------------- | | `Transfer.Amount` | Amount of tokens transferred | | `Transfer.AmountInUSD` | Transfer amount in USD (if available) | | `Transfer.Sender` | Address that sent the tokens | | `Transfer.Receiver` | Address that received the tokens | | `Transfer.Currency.Name` | Token name (e.g., "Tether USD") | | `Transfer.Currency.Symbol` | Token symbol (e.g., "USDT") | | `Transfer.Currency.SmartContract` | Token contract address | | `Transfer.Success` | Whether the transfer was successful | | `Transfer.Type` | Type of transfer (e.g., "call") | | `Transaction.Hash` | Transaction hash | | `Transaction.From` | Transaction sender address | | `Transaction.To` | Transaction recipient address | | `Block.Number` | Block number | | `Block.Time` | Block timestamp | --- ## Best Practices 1. **Use Appropriate Datasets**: - `realtime` for recent data (a few days on EVM chains) - `archive` for historical data - `combined` for comprehensive queries 2. **Filter by Token Contract**: Always filter by `SmartContract` address when querying specific tokens to improve performance. 3. **Use Limit and OrderBy**: Always specify `limit` and `orderBy` to control result size and ordering. 4. **Handle Large Result Sets**: For large queries, use pagination or time-based filters to avoid timeouts. 5. **Subscribe for Real-Time Data**: Use GraphQL subscriptions for live monitoring instead of polling. 6. **Combine with Other APIs**: Enhance transfer data with balance, transaction, and event APIs for comprehensive analytics. --- ## Getting Started 1. **Get API Access**: Sign up at [Bitquery](https://bitquery.io/) to get your API key 2. **Try in IDE**: Test queries in the [Bitquery IDE](https://ide.bitquery.io/) 3. **Read Documentation**: Explore our [Getting Started Guide](/docs/start/first-query/) For more information on authentication and API usage, see our [Authorization Guide](/docs/authorization/how-to-use). ## Deterministic Pagination for Backfilling Transfers When backfilling Ethereum transfer data or building a historical index, use deterministic pagination to guarantee no records are missed or duplicated. **Try it live:** [Deterministic Transfer API](https://ide.bitquery.io/Reliable-transfer-api) ```graphql { EVM(dataset: combined, network: eth) { Transfers( where: { Transfer: { Success: true } } orderBy: { ascending: [ Block_Number, Transaction_Index, Call_Index, Log_Index, Transfer_Index, Transfer_Type ] } limit: { count: 10, offset: 0 } ) { Block { Time Number } Transaction { Hash From Index } Transfer { Amount AmountInUSD Sender Receiver Index Currency { Symbol Name SmartContract Decimals Native } } Call { Index } Log { LogAfterCallIndex Index } Transfer { Type } } } } ``` The composite `orderBy` across `Block_Number`, `Transaction_Index`, `Call_Index`, `Log_Index`, `Transfer_Index`, and `Transfer_Type` uniquely positions every transfer, making offset-based pagination safe for backfilling. Increment `offset` by the `count` value on each request. You can pull up to **25,000 records in a single request** by setting `count: 25000`. --- ## EVM Arguments and Returns API URL: https://docs.bitquery.io/docs/schema/evm/arguments/ EVM Arguments and Returns API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. # EVM Arguments and Returns API Smart contract calls and events have arguments. In case the call or event signature is parsed against ABI, the arguments are showing the values, types and names passed to call or event. In addition, returns shows the return values from the smart contract calls. Arguments and returns are represented by the same data structure. It is array, containing entries for each argument value. In case when the data type of argument is array or emedded structure, the argument will have separate object for every value of array or structure. It means that all argument values are flattened. To represent all possible cases, the following additional information is provided: - Index - sequential index of argument value inside an array or strucutre - Name - name of the argument or the name of the element of structure - Type - the type of the argument - Path - the array of top-level elements where the argument value is used. Each element of path have Name, Index, Type As example, the following data means the array of size 2 of addresses: ```json { "Index": 0, "Name": "", "Path": [ { "Index": 2, "Name": "path", "Type": "address[]" } ], "Type": "address", "Value": { "__typename": "EVM_ABI_Address_Value_Arg", "address": "0x6c812ab49f4b350b9d115e3f367302cd4fb58bbf" } }, { "Index": 1, "Name": "", "Path": [ { "Index": 2, "Name": "path", "Type": "address[]" } ], "Type": "address", "Value": { "__typename": "EVM_ABI_Address_Value_Arg", "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } }, ``` meaning `['0x6c812ab49f4b350b9d115e3f367302cd4fb58bbf','0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2']` To query attribute values, use union as shown: ```graphql Arguments { Index Name Type Path { Index Name Type } Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } ``` Data types are mapped to this values by the following rules: 1. string, addresses, boolean are mapped directly to corresponding types (EVM_ABI_String_Value_Arg,EVM_ABI_Address_Value_Arg,EVM_ABI_Boolean_Value_Arg) 2. bytes and byte array of any pre-defined size ( such as byte[24]) mapped to hex bytes (EVM_ABI_Bytes_Value_Arg) 3. integers of size int8,16,32 and uint8,16 are mapped to integer (EVM_ABI_Integer_Value_Arg) 4. all other integers mapped to big integer represented as string ( possible negative ) (EVM_ABI_BigInt_Value_Arg) ## Filters on arguments Arguments and returns are arrays, and this enables to use filtering on them as described on [filters](/docs/graphql/filters/#array-filter-types). For example, this query selects specific calls by applying filter to argument length and to specific values of arguments. Combining argument filters with signature filters on events and calls gives you the power to analyze the arguments used in smart contracts in specific context. ```graphql { EVM { Calls( where: { Arguments: { length: {eq: 2} includes: [ { Index: {eq: 0} Name: {is: "recipient"} Value: {Address: {is: "0xa7f6ebbd4cdb249a2b999b7543aeb1f80bda7969"}} } { Name: {is: "amount"} Value: {BigInteger: {ge: "1000000000"}} } ] } } limit: {count: 10}) { Arguments { Index Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { Signature { Signature } } } } } ``` The value of argument filter must be defined depending on the expected argument type. There are the following options: - BigInteger - for uint256/int256/int64/uint64 arguments - Address - for addresses, 0x prefixed - String - for strings - Boolean - for boolean, just true/false - UnsignedInteger - for uint8/16/32 - SignedInteger - int8/16/32 - Bytes - for bytes, 0x prefixed optional :::note filters affect the whole query to calls / events, so you anyway can query all arguments, not just which pass the filter. ::: --- ## EVM Balance Schema API URL: https://docs.bitquery.io/docs/schema/evm/balances/ EVM Balance API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. See examples in the Bitquery IDE. # EVM Balance API :::caution Query-only A subscription on `Balances` is accepted but never pushes a message. Poll it, or stream `TransactionBalances` / `Transfers` and apply deltas. See [which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/). ::: The **Balances** API returns current and historical token balances for addresses on EVM chains. To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | |---------|-------------| | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | Full Ethereum examples: [Address Balance API](/docs/blockchain/Ethereum/balances/balance-api/). ## Balance of an address ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x76147fd7891731e01f35cc18f87ae8e95bf06869" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ### Examples on Ethereum - [Balance of an address](/docs/blockchain/Ethereum/balances/balance-api/#balance-of-an-address) - [Balance on a specific date](/docs/blockchain/Ethereum/balances/balance-api/#balance-on-a-specific-date) - [Balance for a specific token](/docs/blockchain/Ethereum/balances/balance-api/#balance-for-a-specific-token) - [Balance history by date](/docs/blockchain/Ethereum/balances/balance-api/#balance-history-by-date) - [Wallet balance for a specific token on a date](/docs/blockchain/Ethereum/balances/balance-api/#wallet-balance-for-a-specific-token-on-a-date) --- ## EVM Blocks Schema URL: https://docs.bitquery.io/docs/schema/evm/blocks/ Blocks: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. Copy GraphQL snippets for production apps. # EVM Blocks Schema Blocks API provide details on blocks. You can use different [filters](/docs/graphql/filters/) to query data from different dimensions. You can find more examples [here](/docs/blockchain/Ethereum/blocks/blocks-api/) Let's see an example of Blocks API to get the latest 10 blocks on Ethereum blockchain. ```graphql { EVM(dataset: archive, network: eth) { Blocks(limit: { count: 10 }, orderBy: { descending: Block_Number }) { Block { Time Date Number Hash } } } } ``` You can see more example of Blocks api in [here](/docs/blockchain/Ethereum/blocks/blocks-api/). --- ## EVM Builder Terms Explaination URL: https://docs.bitquery.io/docs/glossary/EVM/ EVM API terms explained: dataset, mempool, network and filter parameters, plus field definitions for Blocks, Calls, DEXTrades, Events, Transfers and more. # EVM Builder Terms Explaination ### Dataset Parameters EVM API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from the first (genesis) block up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Mempool Parameter - `mempool` - The mempool in EVM (Ethereum Virtual Machine) is a temporary storage area where pending transactions are held before being included in a block by miners. ### Network Parameter - `network` - Through network field you can select EVM based network such as bsc, arbitrum, eth , and etc available on Bitquery. ### Filter Parameters EVM API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Address`: The wallet address where the balance update occurred. - `Amount`: The quantity of token involved in the balance update. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. - `Id`: The unique identifier for the balance update event. - `Type`: The nature of the balance update, such as `transfer` or `block_reward`. - `URI`: The link to additional information or metadata about the balance update. ### Blocks API Terms - `BaseFee`: The minimum gas price for transactions in the block. - `BaseFeeInUSD`: The equivalent base fee value in US dollars. - `Hash`: The unique identifier for the block. - `GasUsed`: The total gas consumed by all transactions in the block. - `GasLimit`: The maximum amount of gas that can be used by all transactions in the block. - `Extra`: Additional data included in the block. - `Difficulty`: The complexity level of the block mining process. - `Date`: The timestamp of when the block was mined. - `Coinbase`: The address of the miner who mined the block. - `Bloom`: A data structure for quickly checking the presence of a particular log entry. - `MixDigest`: A unique value from the proof-of-work algorithm. - `UnclesCount`: The number of uncle blocks included in this block. - `UncleHash`: The hash of the uncle blocks. - `TxHash`: The hash of the transactions included in the block. - `TxCount`: The number of transactions in the block. - `Time`: The exact time when the block was mined. - `Root`: The root hash of the state trie. - `Result`: Contains details about gas used and any errors encountered. - `ReceiptHash`: The hash of the transaction receipts. - `ParentHash`: The hash of the previous block. - `Number`: The unique number of the block in the blockchain. - `Nonce`: A value used to validate the block's proof-of-work. ### Calls API Terms #### Arguments - `Index`: The position of the argument within the function call. - `Name`: The name of the argument in the function call. - `Value`: The data value of the argument, which can be of various types such as boolean, bytes, big integer, address, string, or integer. - `bool`: A boolean value (true or false). - `hex`: A hexadecimal byte string. - `bigInteger`: A large integer value. - `address`: An Ethereum address. - `string`: A text string. - `integer`: A numerical integer value. - `Type`: The data type of the argument. - `Path`: The location of the argument in nested calls, including type, name, and index. #### Calls - `ValueInUSD`: The value of the call in US dollars. - `Value`: The value transferred in the call. - `To`: The recipient address of the call. - `Success`: Indicates whether the call was successful. - `Signature`: Details about the function signature used in the call. - `SignatureType`: The type of the signature. - `SignatureHash`: The hash of the function signature. - `Signature`: The actual function signature. - `Parsed`: The parsed details of the signature. - `Name`: The name of the function. - `Abi`: The ABI (Application Binary Interface) details. - `SelfDestruct`: Indicates if the contract self-destructed during the call. - `Reverted`: Indicates if the call was reverted. - `Output`: The output data from the call. - `Opcode`: The operation code details. - `Name`: The name of the opcode. - `Code`: The numeric code of the opcode. - `LogCount`: The number of logs generated by the call. - `InternalCalls`: Details about calls made within the current call. - `Input`: The input data for the call. - `Index`: The position of the call within a block or transaction. - `GasUsed`: The amount of gas used by the call. - `Gas`: The gas limit for the call. - `From`: The sender address of the call. - `CallPath`: The sequence of calls leading to the current call. - `CallerIndex`: The index of the caller within nested calls. - `Create`: Indicates if a new contract was created during the call. - `ExitIndex`: The exit position of the call. - `Error`: Details about any error that occurred during the call. - `EnterIndex`: The entry position of the call. - `Depth`: The depth of the call within nested calls. - `Delegated`: Indicates if the call was a delegated call. ### DEXTradeByTokens API Terms DEXTradeByTokens API retrieves trade details for a token pair, distinguishing between the primary token (`Trade{Currency}`) and the side currency (`Side{Currency}`). The fields within each section provide specific trade-related information as follows: DEXTradeByTokens API contains Trade field which has below attributes: - **Trade** - `Amount`: Quantity of tokens traded. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Buyer`: Address of the buyer. - `Fees` - `Amount`: Amount of fees paid. - `AmountInUSD`: Equivalent value of fees in USD. - `Ids`: IDs related to the trade. - `OrderId`: Identifier for the order. - `Price`: Price of Primary currency in the trade. - `PriceAsymmetry`: Asymmetry factor in token pricing. - `PriceInUSD`: Token price in USD. - `Sender`: Address of the sender. - `Seller`: Address of the seller. - `Success`: Indicates if the trade was successful. - `Dex` - `Delegated`: Indicates if the trade is delegated. - `DelegatedTo`: Address of the delegate. - `OwnerAddress`: Address of the owner. - `SmartContract`: DEX smart contract address. - `ProtocolVersion`: Version of the protocol. - `ProtocolName`: Name of the protocol. - `Pair` - `Symbol`: Symbol of the token pair. - `SmartContract`: Token Pair Smart contract address. - `Name`: Name of the token pair. - `Decimals`: Decimal places for token precision. - `ProtocolFamily`: Family of the protocol. - `Currency` - `Name`: Name of the currency. - `Symbol`: Symbol of the currency. - `SmartContract`: Currency smart contract address. - `Side` - `URIs`: Uniform Resource Identifiers related to the trade side. - `Type`: Type of the trade side (buy or sell). - `Seller`: Address of the seller. - `OrderId`: Identifier for the order related to the side. - `Ids`: IDs related to the trade side. - `AmountInUSD`:AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Amount`: Quantity of side tokens traded. - `Currency`: Side Currency Details. ### DEXTrades API Terms Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. For your information this buy side and sell side is wrt to Liquidity Pool. For video explaination, watch this [video](https://www.youtube.com/watch?v=f052KzAsqnQ). - `Buy` - `Buyer`: Address of the buyer of this bought currency. This is the pool address. - `Seller`: Address of the Seller of this bought currency. - `Amount`: Quantity of tokens bought. - `Price`: Price of the buy currency in the trade. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Sell` - `Buyer`: Address of the buyer of this sold currency. - `Seller`: Address of the Seller of this sold currency. This is the pool address. - `Amount`: Quantity of tokens sold. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Price`: Price of the sell currency in the trade. - `Dex` - `ProtocolName`: Name of the DEX protocol. - `SmartContract`: Smart contract address of the DEX. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolVersion`: Version of the DEX protocol. - `Pair`: Contains the liquidity pair details ### Events API Terms - `Log`: Detailed log information. - `LogAfterCallIndex`: Index after the call. - `Index`: Log index within the block. - `ExitIndex`: Index when exiting. - `EnterIndex`: Index when entering. - `Pc`: Program counter value. - `Signature`: Signature details of the log. - `Abi`: ABI of the signature. - `Name`: Name of the signature. - `SignatureType`: Type of the signature. - `SignatureHash`: Hash of the signature. - `Signature`: Full signature string. - `Parsed`: Indicates if the signature is parsed. - `SmartContract`: Indicates if the log involves a smart contract. - `LogHeader`: Header information of the log. - `Removed`: Indicates if the log is removed. - `Index`: Index of the log header. - `Data`: Data of the log. - `Address`: Address of the log. - `Receipt`: Transaction receipt details. - `GasUsed`: Amount of gas used by the transaction. - `CumulativeGasUsed`: Total gas used by the block. - `ContractAddress`: Address of the contract created. - `Status`: Status of the transaction. - `Type`: Type of the transaction. - `Topics`: Log topics. - `Hash`: Hash of the topic. ### Transactions API Terms - `ValueInUSD`: Value of the transaction in USD. - `Value`: Value of the transaction in cryptocurrency. - `Type`: Type of transaction (e.g., transfer, contract creation, contract creation). - `To`: Recipient address of the transaction. - `Time`: Timestamp of the transaction. - `Protected`: Indicates if the transaction is protected. - `Nonce`: Nonce value of the transaction. - `Index`: Index position of the transaction. - `Hash`: Hash of the transaction. - `GasTipCap`: Tip cap for gas. - `GasPriceInUSD`: Gas price in USD. - `GasPrice`: Gas price in cryptocurrency. - `GasFeeCap`: Fee cap for gas. - `Gas`: Amount of gas used. - `From`: Sender address of the transaction. - `Data`: Data associated with the transaction. - `Cost`: Cost of the transaction in cryptocurrency. - `CostInUSD`: Equivalent cost of the transaction in USD. - `CallCount`: Number of calls made in the transaction. ### MinerRewards API Terms - `Reward`: Details of the reward. - `UncleInUSD`: USD value of uncle rewards. - `Uncle`: Amount of uncle rewards. - `TxFeesInUSD`: USD value of transaction fees. - `TxFees`: Amount of transaction fees. - `TotalInUSD`: Total reward value in USD. - `Total`: Total reward amount. - `StaticInUSD`: USD value of static rewards. - `Static`: Amount of static rewards. - `DynamicInUSD`: USD value of dynamic rewards. - `Dynamic`: Amount of dynamic rewards. - `BurntFeesInUSD`: USD value of burnt transaction fees. - `BurntFees`: Amount of burnt transaction fees. ### Transfers API Terms - **Transfers**: Retrieves details of token transfers. - `Transfer` - `Type`: Type of transfer (e.g., token, transaction, call). - `Success`: Indicates if the transfer was successful. - `Sender`: Address of the sender. - `Receiver`: Address of the receiver. - `Id`: Identifier for the transfer. - `Data`: Additional data associated with the transfer. - `Currency` - `Name`: Name of the token transferred. - `Symbol`: Symbol of the token transferred. - `Amount`: Quantity of tokens transferred. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. ### Currency Field Attributes Explained - `Currency`: Details about a token or asset. - `Symbol`: Symbol representing the token. - `SmartContract`: Token Program Address. - `Name`: Name of the token. - `HasURI`: Indicates if the currency has a Uniform Resource Identifier (URI). - `Fungible`: Indicates if the currency is fungible. - `Decimals`: Number of decimal places used to represent fractional amounts of the currency. --- ## EVM Builder Terms Explanation URL: https://docs.bitquery.io/docs/cubes/EVM/ EVM cube terms explained: dataset, mempool, network and filter parameters, plus the fields of Blocks, Calls, Events, DEXTrades, Transfers and other EVM APIs. # EVM Builder Terms Explanation ### Dataset Parameters EVM API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from the first (genesis) block up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Mempool Parameter - `mempool` - The mempool in EVM (Ethereum Virtual Machine) is a temporary storage area where pending transactions are held before being included in a block by miners. ### Network Parameter - `network` - Through network field you can select EVM based network such as bsc, arbitrum, eth , and etc available on Bitquery. ### Filter Parameters EVM API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Address`: The wallet address where the balance update occurred. - `Amount`: The quantity of token involved in the balance update. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. - `Id`: The unique identifier for the balance update event. - `Type`: The nature of the balance update, such as `transfer` or `block_reward`. - `URI`: The link to additional information or metadata about the balance update. ### Blocks API Terms - `BaseFee`: The minimum gas price for transactions in the block. - `BaseFeeInUSD`: The equivalent base fee value in US dollars. - `Hash`: The unique identifier for the block. - `GasUsed`: The total gas consumed by all transactions in the block. - `GasLimit`: The maximum amount of gas that can be used by all transactions in the block. - `Extra`: Additional data included in the block. - `Difficulty`: The complexity level of the block mining process. - `Date`: The timestamp of when the block was mined. - `Coinbase`: The address of the miner who mined the block. - `Bloom`: A data structure for quickly checking the presence of a particular log entry. - `MixDigest`: A unique value from the proof-of-work algorithm. - `UnclesCount`: The number of uncle blocks included in this block. - `UncleHash`: The hash of the uncle blocks. - `TxHash`: The hash of the transactions included in the block. - `TxCount`: The number of transactions in the block. - `Time`: The exact time when the block was mined. - `Root`: The root hash of the state trie. - `Result`: Contains details about gas used and any errors encountered. - `ReceiptHash`: The hash of the transaction receipts. - `ParentHash`: The hash of the previous block. - `Number`: The unique number of the block in the blockchain. - `Nonce`: A value used to validate the block's proof-of-work. ### Calls API Terms #### Arguments - `Index`: The position of the argument within the function call. - `Name`: The name of the argument in the function call. - `Value`: The data value of the argument, which can be of various types such as boolean, bytes, big integer, address, string, or integer. - `bool`: A boolean value (true or false). - `hex`: A hexadecimal byte string. - `bigInteger`: A large integer value. - `address`: An Ethereum address. - `string`: A text string. - `integer`: A numerical integer value. - `Type`: The data type of the argument. - `Path`: The location of the argument in nested calls, including type, name, and index. #### Calls - `ValueInUSD`: The value of the call in US dollars. - `Value`: The value transferred in the call. - `To`: The recipient address of the call. - `Success`: Indicates whether the call was successful. - `Signature`: Details about the function signature used in the call. - `SignatureType`: The type of the signature. - `SignatureHash`: The hash of the function signature. - `Signature`: The actual function signature. - `Parsed`: The parsed details of the signature. - `Name`: The name of the function. - `Abi`: The ABI (Application Binary Interface) details. - `SelfDestruct`: Indicates if the contract self-destructed during the call. - `Reverted`: Indicates if the call was reverted. - `Output`: The output data from the call. - `Opcode`: The operation code details. - `Name`: The name of the opcode. - `Code`: The numeric code of the opcode. - `LogCount`: The number of logs generated by the call. - `InternalCalls`: Details about calls made within the current call. - `Input`: The input data for the call. - `Index`: The position of the call within a block or transaction. - `GasUsed`: The amount of gas used by the call. - `Gas`: The gas limit for the call. - `From`: The sender address of the call. - `CallPath`: The sequence of calls leading to the current call. - `CallerIndex`: The index of the caller within nested calls. - `Create`: Indicates if a new contract was created during the call. - `ExitIndex`: The exit position of the call. - `Error`: Details about any error that occurred during the call. - `EnterIndex`: The entry position of the call. - `Depth`: The depth of the call within nested calls. - `Delegated`: Indicates if the call was a delegated call. ### DEXTradeByTokens API Terms DEXTradeByTokens API retrieves trade details for a token pair, distinguishing between the primary token (`Trade{Currency}`) and the side currency (`Side{Currency}`). The fields within each section provide specific trade-related information as follows: DEXTradeByTokens API contains Trade field which has below attributes: - **Trade** - `Amount`: Quantity of tokens traded. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Buyer`: Address of the buyer. - `Fees` - `Amount`: Amount of fees paid. - `AmountInUSD`: Equivalent value of fees in USD. - `Ids`: IDs related to the trade. - `OrderId`: Identifier for the order. - `Price`: Price of Primary currency in the trade. - `PriceAsymmetry`: Asymmetry factor in token pricing. - `PriceInUSD`: Token price in USD. - `Sender`: Address of the sender. - `Seller`: Address of the seller. - `Success`: Indicates if the trade was successful. - `Dex` - `Delegated`: Indicates if the trade is delegated. - `DelegatedTo`: Address of the delegate. - `OwnerAddress`: Address of the owner. - `SmartContract`: DEX smart contract address. - `ProtocolVersion`: Version of the protocol. - `ProtocolName`: Name of the protocol. - `Pair` - `Symbol`: Symbol of the token pair. - `SmartContract`: Token Pair Smart contract address. - `Name`: Name of the token pair. - `Decimals`: Decimal places for token precision. - `ProtocolFamily`: Family of the protocol. - `Currency` - `Name`: Name of the currency. - `Symbol`: Symbol of the currency. - `SmartContract`: Currency smart contract address. - `Side` - `URIs`: Uniform Resource Identifiers related to the trade side. - `Type`: Type of the trade side (buy or sell). - `Seller`: Address of the seller. - `OrderId`: Identifier for the order related to the side. - `Ids`: IDs related to the trade side. - `AmountInUSD`:AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Amount`: Quantity of side tokens traded. - `Currency`: Side Currency Details. ### DEXTrades API Terms Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. For your information this buy side and sell side is wrt to Liquidity Pool. For video explaination, watch this [video](https://www.youtube.com/watch?v=f052KzAsqnQ). - `Buy` - `Buyer`: Address of the buyer of this bought currency. This is the pool address. - `Seller`: Address of the Seller of this bought currency. - `Amount`: Quantity of tokens bought. - `Price`: Price of the buy currency in the trade. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Sell` - `Buyer`: Address of the buyer of this sold currency. - `Seller`: Address of the Seller of this sold currency. This is the pool address. - `Amount`: Quantity of tokens sold. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Price`: Price of the sell currency in the trade. - `Dex` - `ProtocolName`: Name of the DEX protocol. - `SmartContract`: Smart contract address of the DEX. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolVersion`: Version of the DEX protocol. - `Pair`: Contains the liquidity pair details ### Events API Terms - `Log`: Detailed log information. - `LogAfterCallIndex`: Index after the call. - `Index`: Log index within the block. - `ExitIndex`: Index when exiting. - `EnterIndex`: Index when entering. - `Pc`: Program counter value. - `Signature`: Signature details of the log. - `Abi`: ABI of the signature. - `Name`: Name of the signature. - `SignatureType`: Type of the signature. - `SignatureHash`: Hash of the signature. - `Signature`: Full signature string. - `Parsed`: Indicates if the signature is parsed. - `SmartContract`: Indicates if the log involves a smart contract. - `LogHeader`: Header information of the log. - `Removed`: Indicates if the log is removed. - `Index`: Index of the log header. - `Data`: Data of the log. - `Address`: Address of the log. - `Receipt`: Transaction receipt details. - `GasUsed`: Amount of gas used by the transaction. - `CumulativeGasUsed`: Total gas used by the block. - `ContractAddress`: Address of the contract created. - `Status`: Status of the transaction. - `Type`: Type of the transaction. - `Topics`: Log topics. - `Hash`: Hash of the topic. ### Transactions API Terms - `ValueInUSD`: Value of the transaction in USD. - `Value`: Value of the transaction in cryptocurrency. - `Type`: Type of transaction (e.g., transfer, contract creation, contract creation). - `To`: Recipient address of the transaction. - `Time`: Timestamp of the transaction. - `Protected`: Indicates if the transaction is protected. - `Nonce`: Nonce value of the transaction. - `Index`: Index position of the transaction. - `Hash`: Hash of the transaction. - `GasTipCap`: Tip cap for gas. - `GasPriceInUSD`: Gas price in USD. - `GasPrice`: Gas price in cryptocurrency. - `GasFeeCap`: Fee cap for gas. - `Gas`: Amount of gas used. - `From`: Sender address of the transaction. - `Data`: Data associated with the transaction. - `Cost`: Cost of the transaction in cryptocurrency. - `CostInUSD`: Equivalent cost of the transaction in USD. - `CallCount`: Number of calls made in the transaction. ### MinerRewards API Terms - `Reward`: Details of the reward. - `UncleInUSD`: USD value of uncle rewards. - `Uncle`: Amount of uncle rewards. - `TxFeesInUSD`: USD value of transaction fees. - `TxFees`: Amount of transaction fees. - `TotalInUSD`: Total reward value in USD. - `Total`: Total reward amount. - `StaticInUSD`: USD value of static rewards. - `Static`: Amount of static rewards. - `DynamicInUSD`: USD value of dynamic rewards. - `Dynamic`: Amount of dynamic rewards. - `BurntFeesInUSD`: USD value of burnt transaction fees. - `BurntFees`: Amount of burnt transaction fees. ### Transfers API Terms - **Transfers**: Retrieves details of token transfers. - `Transfer` - `Type`: Type of transfer (e.g., token, transaction, call). - `Success`: Indicates if the transfer was successful. - `Sender`: Address of the sender. - `Receiver`: Address of the receiver. - `Id`: Identifier for the transfer. - `Data`: Additional data associated with the transfer. - `Currency` - `Name`: Name of the token transferred. - `Symbol`: Symbol of the token transferred. - `Amount`: Quantity of tokens transferred. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. ### Currency Field Attributes Explained - `Currency`: Details about a token or asset. - `Symbol`: Symbol representing the token. - `SmartContract`: Token Program Address. - `Name`: Name of the token. - `HasURI`: Indicates if the currency has a Uniform Resource Identifier (URI). - `Fungible`: Indicates if the currency is fungible. - `Decimals`: Number of decimal places used to represent fractional amounts of the currency. --- ## EVM Cloud Data Exports URL: https://docs.bitquery.io/docs/cloud/evm/ Access Bitquery EVM cloud datasets for historical blockchain exports in Parquet, ready for S3, BigQuery, Snowflake, and data lakes. # EVM Data Bitquery provides **blockchain data for EVM-base chains like Ethereum, BSC, Base, Polygon/Matic, Optimism, Robinhood, etc.** as Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore) that you can host directly in your own cloud (for example AWS S3) and plug into your analytics stack or data lake. ## Available Topics For EVM chains we currently provide the following topics: - **Blocks** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/blocks.js) - **Balance Updates** – [sample file](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balance_updates/24053500_24053549.parquet) - **Balances** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/balances.js), daily snapshots, see [Balances](#balances-daily-snapshots) below - **DEX Trades** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/dextrades.js) - **Uncle Blocks** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/uncle_blocks.js) - **Transactions** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/transactions.js) - **Transfers** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/transfers.js) ## Sample Ethereum Cloud Dataset To explore the schema and test your tooling, use our **public sample EVM datasets** on GitHub: - **Ethereum samples**: [`https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/ethereum`](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/ethereum) The GitHub repository includes one sample file for most topics; Balance Updates is only in the public S3 bucket. More sample files are in our public S3 bucket and can be accessed directly. For example: `https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balance_updates/24053500_24053549.parquet` ```text bitquery-blockchain-dataset/ └── ethereum/ ├── balances/ │ ├── 2025-01-01.parquet │ ├── 2025-01-02.parquet │ └── ... ├── balance_updates/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet ├── blocks/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet ├── calls/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet ├── dex_trades/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet ├── events/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet ├── miner_rewards/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet ├── transactions/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet ├── transfers/ │ ├── 24053500_24053549.parquet │ ├── 24053550_24053599.parquet │ ├── 24053600_24053649.parquet │ ├── 24053650_24053699.parquet │ ├── 24053700_24053749.parquet │ ├── 24053750_24053799.parquet │ ├── 24053800_24053849.parquet │ ├── 24053850_24053899.parquet │ ├── 24053900_24053949.parquet │ └── 24053950_24053999.parquet └── uncle_blocks/ ├── 15535500_15535549.parquet ├── 15535550_15535599.parquet ├── 15535600_15535649.parquet ├── 15535650_15535699.parquet ├── 15535700_15535749.parquet ├── 15535750_15535799.parquet ├── 15535800_15535849.parquet └── 15535850_15535899.parquet ``` Use these samples to: - **Validate your ETL / analytics pipeline** against realistic EVM data. - **Inspect column names and types** before connecting to full buckets. - **Benchmark query performance** on your preferred engines and hardware. ## Balances (Daily Snapshots) The **Balances** topic is a daily snapshot of account balances, both native (ETH) and token. It differs from **Balance Updates** in two ways: - **Balance Updates** are *deltas* — one row per balance change, which you must sum to reconstruct a balance. - **Balances** are *levels* — one row per account/token with the balance **as of the end of that day**, already aggregated. Files are partitioned by **date**, not block range: ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balances/.parquet ``` **Sample Parquet download (public S3)** - **Ethereum Balances** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balances/2025-01-01.parquet) Each daily file covers **only the accounts whose balance changed that day**, not the entire chain state. The `2025-01-01` sample holds about 954,000 rows across roughly 514,000 addresses and 13,000 currencies. To reconstruct full chain state at a date, carry forward the last known balance per account from earlier files. ### Balances Schema | Column | Type | Description | | --- | --- | --- | | `Balance_Address` | string | Account holding the balance | | `Block_Date` | date | Snapshot date, matches the file name | | `Currency_SmartContract` | string | Token contract address; `0x` for native ETH | | `Currency_Symbol` | string | Token symbol as declared by the contract | | `Currency_Name` | string | Token name as declared by the contract | | `Currency_ProtocolName` | string | Token standard, e.g. `erc20`, `erc721`, `erc1155`, `erc404_v1` | | `Balance_Amount` | string | Balance at end of day, decimal string — see the precision note below | | `Balance_FirstChangeTime` | datetime | First balance change on this date (UTC) | | `Balance_LastChangeTime` | datetime | Last balance change on this date (UTC) | | `Balance_UpdateCount` | uint64 | Number of balance changes on this date | | `Balance_RowCount` | uint64 | Number of underlying aggregate rows merged into this row | ### Filter on the Contract Address, Never the Symbol Token symbols are set by the contract, so anyone can deploy a token claiming any symbol. In the `2025-01-01` sample, **25 different contracts report the symbol `ETH`** and **34 report `USDT`**. Filtering `Currency_Symbol = 'ETH'` picks up impostor ERC-20s and inflates the native ETH total by several orders of magnitude. Native ETH is identified by the contract address: ```sql -- correct: native ETH WHERE Currency_SmartContract = '0x' -- correct: real USDT WHERE Currency_SmartContract = '0xdac17f958d2ee523a2206206994597c13d831ec7' -- wrong: matches impostor tokens too WHERE Currency_Symbol = 'USDT' ``` Filtered correctly, the largest native ETH holders in the sample are the Ethereum staking deposit contract (`0x00000000219ab540356cbb839cbe05303d7705fa`) and the WETH contract (`0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2`), which you can cross-check on any block explorer. ### `Balance_Amount` Is a String Balances are stored as **decimal strings**, not floats, so that 18-decimal values survive intact. Casting to a 64-bit float silently loses precision on large balances. Parse to a decimal type instead: ```python from decimal import Decimal df["amount"] = df["Balance_Amount"].map(Decimal) ``` In SQL, cast to a wide decimal — for example `CAST(Balance_Amount AS DECIMAL(38, 18))` — rather than `DOUBLE`. Note that some scam tokens carry balances near `2^256`: in the sample, 2,419 rows across 70 contracts overflow `DECIMAL(38, 18)`, and 1,537 rows across 3 contracts overflow even `DECIMAL(76, 18)`. Filter those contracts out, or keep the column as a string. ### Row Grain and Deduplication The grain is nearly `(Balance_Address, Currency_SmartContract, Currency_ProtocolName)`; 177 sample rows repeat even that key. Tokens recorded under more than one standard appear once per standard, so the same address and contract can sit on several rows — about 4,600 such pairs in the sample, most of them `erc20` plus `erc20_deposable`. These rows can repeat the **same** balance under a different `Currency_ProtocolName` (about one pair in five in the sample), so summing across them double-counts. Pick one `Currency_ProtocolName`, or deduplicate on the address and contract before aggregating. ### Reading a File in Python ```python from decimal import Decimal url = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balances/2025-01-01.parquet" df = pd.read_parquet(url) # native ETH only, identified by contract address rather than symbol native = df[df.Currency_SmartContract == "0x"].copy() native["amount"] = native.Balance_Amount.map(Decimal) print(len(native), "accounts changed ETH balance on this date") # sort_values, not nlargest: pandas cannot rank an object/Decimal column top = native.sort_values("amount", ascending=False).head(10) print(top[["Balance_Address", "amount"]]) ``` ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). EVM transfer datasets on the Data Store, one row per native or token transfer with sender, receiver and USD value: - [Ethereum Transfers](https://bitquery.io/datastore/datasets/ethereum-transfers) — Ethereum - [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) — BSC - [Base Transfers](https://bitquery.io/datastore/datasets/base-transfers) — Base - [Polygon Transfers](https://bitquery.io/datastore/datasets/polygon-transfers) — Polygon - [Arbitrum Transfers](https://bitquery.io/datastore/datasets/arbitrum-transfers) — Arbitrum This listing is not the full catalogue. Other topics, chains and date ranges are available on request from **sales@bitquery.io**. ## Other Ways to Access EVM Data Data Store exports are ideal for **batch analytics** and **historical workloads**. If you need **low-latency real-time data**, you can also consume Bitquery streams via **Kafka** and GraphQL subscriptions. - **Kafka-based real-time streams** (mempool and committed data) are documented here: [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts) --- ## EVM Cubes: Trades, Transfers, Balances, Calls and Events URL: https://docs.bitquery.io/docs/category/evm-cube/ The cubes under EVM(network: ...) for Ethereum, BNB Chain, Base, Arbitrum, Optimism, Polygon, Robinhood and Arc: what each holds and which to query. # EVM Cubes: Trades, Transfers, Balances, Calls and Events Every EVM chain Bitquery indexes is queried through one root, `EVM(network: ...)`, with the same cubes underneath: `DEXTrades`, `DEXTradeByTokens`, `DEXPools`, `Transfers`, `Balances`, `Holders`, `TransactionBalances`, `Transactions`, `Calls`, `Events`, `Blocks` and `MinerRewards`. A query written for Ethereum runs on BNB Chain, Base, Arbitrum, Optimism, Polygon, Robinhood Chain or Arc by changing the network name. Each cube takes `where`, `orderBy` and `limit`, supports `count`, `sum`, `uniq` and the other aggregates, and streams as a subscription, except `Balances` and `Holders`, which are query-only. This page is the map; the [EVM builder terms](/docs/cubes/EVM) page lists every field. ## The cubes | Cube | One row is | Reach for it when | |---|---|---| | `DEXTrades` | One swap with buy and sell sides, DEX, pool and trader | You need individual trades or a trade feed | | `DEXTradeByTokens` | One token side of a swap | You want per-token volume, OHLC, buyers, sellers or top pairs | | `DEXPools` | A pool event: creation, liquidity change, reserves | Pool discovery, TVL, slippage | | `Transfers` | One token or native transfer | Wallet activity, whale alerts, holder movements | | `Balances` and `Holders` | Current balance of an address, or holders of a token | Portfolios, holder rankings, distribution | | `TransactionBalances` | One balance change caused by a transaction | Per-transaction balance changes, live balance streams | | `Transactions` | One transaction with receipt, gas and status | Receipts, fees, failure rates | | `Calls` | One call or internal call with decoded arguments | Method traces, contract deployments, reverts | | `Events` | One decoded log | Any contract event, an `eth_getLogs` replacement | | `Blocks` and `MinerRewards` | One block, one reward | Block metadata and validator or miner rewards | ## Networks `eth`, `bsc`, `base`, `arbitrum`, `optimism`, `matic`, `robinhood`, `arc` and `arc_testnet` work in `EVM(network: ...)`. Arc mainnet has live USD fields and is documented in the [Arc Mainnet hub](/docs/blockchain/arc-mainnet/). Arc testnet is realtime-only with USD fields at 0; see the [Arc Testnet hub](/docs/blockchain/arc-testnet/). The schema is shared across these EVM networks. ## Datasets and depth Add `dataset: archive` or `dataset: combined` for history; without it a cube returns its realtime window only, which is hours to a few days depending on the cube. `DEXPools` is realtime-only on every chain: the archive and combined datasets do not exist for it. `Transactions` keeps full history on archive. The per-cube table is on [data coverage and retention](/docs/graphql/data-coverage-retention). ## Example: the busiest tokens on Ethereum in the last hour `DEXTradeByTokens` with a relative time filter, sorted by an aggregate. Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account; change `eth` to another network and it still runs. ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } } orderBy: { descendingByField: "trades" } limit: { count: 5 } ) { Trade { Currency { Symbol SmartContract } } trades: count volume_usd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Pages in this section | Page | Read it for | |---|---| | [EVM builder terms](/docs/cubes/EVM) | Every argument and field across the EVM cubes | | [DEX Trades cube](/docs/cubes/dextrades) | Swap-level rows | | [DEXTradeByTokens cube](/docs/cubes/dextradesbyTokens) | Per-token aggregates and OHLC | | [DEXTrades vs DEXTradeByTokens vs Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades) | Which trade cube to use | | [DEXPools cube](/docs/cubes/evm-dexpool) | Pools, reserves, liquidity events | | [Transaction cube](/docs/cubes/transaction-cube) | Transactions and receipts | | [Balances and Holders cubes](/docs/cubes/balances-cube) | Current balances and holder rankings | | [Balance Updates cube](/docs/cubes/balance-updates-cube) | Balance history | | [Transfers cube](/docs/cubes/transfers-cube) | Token and native transfers | | [EVM token holders schema](/docs/schema/evm/token-holders) | Holder field reference | ## Related pages - [Understanding cubes](/docs/category/understanding-cubes) - [Ethereum API hub](/docs/blockchain/Ethereum/) - [EVM schema reference](/docs/schema/evm/dextrades) - [Data coverage and retention](/docs/graphql/data-coverage-retention) --- ## EVM DEX Slippage API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/ethereum-slippage-api/ EVM DEX Slippage API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Includes filters and field selection tips. # EVM DEX Slippage API In this section we will see how to get Ethereum DEX pool slippage information using our API. The slippage API helps you understand **Uniswap price impact slippage** and liquidity depth for token swaps on Ethereum DEX pools. Use it as a **Uniswap slippage calculator** to **calculate slippage** and set **Uniswap slippage tolerance** for Uniswap V2, V3, and V4 pools—including **Uniswap V3 price impact slippage** at different tolerance levels. > **Note:** This API also works for other EVM chains such as Base, BSC, and Arbitrum—just change the network parameters in your request. ## What is Slippage and Price Impact in Crypto DEX pools? Slippage refers to the difference between the expected price of a trade and the actual execution price. When swapping tokens in a DEX pool, larger trades can move the price due to limited liquidity, resulting in slippage. The DEXPoolSlippages API provides detailed information about: - Maximum input amounts that can be swapped at different slippage tolerances - Minimum output amounts guaranteed at each slippage level - Average execution prices for different trade sizes - Price impact calculations for both swap directions (A to B and B to A) For a comprehensive explanation of how DEX pools work, liquidity calculations, and price tables, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/). ## Realtime Slippage Monitoring for Uniswap Pools This subscription query returns real-time slippage data for all DEX pools on Ethereum. You can monitor price impact and liquidity depth as trades occur. You can find the query [here](https://ide.bitquery.io/realtime-slippage-on-ethereum) ```graphql subscription { EVM(network: eth) { DEXPoolSlippages { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` ## Latest Slippage for a Specific Pool on Uniswap V3 This query retrieves the latest slippage data for a specific DEX pool on Ethereum. Use it to calculate slippage and check Uniswap V3 price impact slippage for a particular token pair before trading. You can find the query [here](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Uniswap-v3-Ethereum) ```graphql query { EVM(network: eth) { DEXPoolSlippages( where: {Price: {Pool: {SmartContract: {is: "0xa43fe16908251ee70ef74718545e4fe6c5ccec9f"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` > **Note:** This query can be converted to a subscription to monitor in real-time. Simply replace `query` with `subscription` to receive live updates whenever the pool's liquidity changes. ## Realtime Slippage for Uniswap V4 Pools This subscription query retrieves real-time slippage data for Uniswap V4 pools on Ethereum. Unlike Uniswap V3, which uses the pool's smart contract address, Uniswap V4 requires using the `PoolId` to identify pools. In Uniswap V4, liquidity is managed by a centralized pool manager contract. You can find the query [here](https://ide.bitquery.io/realtime-pair-slippage-on-ethereum-uniswap-v4) ```graphql subscription { EVM(network: eth) { DEXPoolSlippages( where: {Price: {Pool: {PoolId: {is: "0x89c10991af36a29d4a14b346a272baa7205d2b41c72013f61cfca41ef2666412"}}}} ) { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` ## Realtime Slippage Data via Kafka Streams Slippage data can also be obtained via Kafka streams for lower latency and better reliability. The Kafka topic for Ethereum DEX pools is: **`ethereum.dexpools.proto`** Kafka streams provide the same slippage data as GraphQL subscriptions but with several advantages: - Lower latency due to shorter data pipeline - Better reliability with persistent connections - Ability to read from latest offset without gaps - Better scalability with multiple consumers For detailed information on how to connect to Kafka streams, subscribe to topics, and parse messages, refer to the [Kafka Streaming Concepts documentation](/docs/streams/kafka-streaming-concepts/). > **Note:** IDE credentials will not work with Kafka Streams. You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## Understanding the Response The `DEXPoolSlippages` API response contains the following information: - **`Price`**: Price information for swaps at a specific slippage tolerance - **`AtoB`**: Price data for swapping CurrencyA to CurrencyB - `Price`: Average execution price for swaps at this slippage level - `MinAmountOut`: Minimum output amount guaranteed at this slippage level - `MaxAmountIn`: Maximum input amount that can be swapped at this slippage level - **`BtoA`**: Price data for swapping CurrencyB to CurrencyA (same structure as AtoB) - **`SlippageBasisPoints`**: Slippage tolerance in basis points (100 = 1%) - **`Pool`**: Pool information including token pair details - **`Dex`**: DEX protocol information (Uniswap V2, V3, V4, etc.) - **`Block`**: Block information when the slippage data was recorded - `Time`: Timestamp of the block - `Number`: Block number For more details on how slippage is calculated and when new pool records are emitted, see the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#when-is-a-new-dexpool-record-emitted-in-the-apis--streams). ## Use Cases ### Liquidity Depth Analysis Use the slippage API as a Uniswap slippage calculator to analyze which pools can handle large trades without significant price impact. By examining `MaxAmountIn` values at different slippage levels, you can: - Identify pools with sufficient liquidity for your trade size - Determine optimal slippage tolerance settings - Estimate price impact before executing trades ### Multi-Pool Price Comparison Compare execution prices across different pools and slippage scenarios to: - Find the best pool for your specific trade size - Understand price differences between DEX protocols - Optimize trade execution strategies ### Trading Applications #### Live Execution Testing Use the slippage API to test and validate trade execution strategies in real-time: - **Pre-trade validation**: Check if your intended trade size can be executed within acceptable slippage bounds before submitting - **Execution simulation**: Calculate expected price impact and minimum output amounts for different trade sizes - **Strategy backtesting**: Monitor historical slippage data to validate trading algorithms and optimize entry/exit points - **Risk assessment**: Evaluate maximum position sizes that can be entered without exceeding your slippage tolerance #### Detecting Liquidity Shocks and Toxic Order Flow The slippage API helps identify temporary price dislocations and liquidity shocks that can be exploited or avoided: - **Flow toxicity detection**: Monitor sudden changes in `MaxAmountIn` values to detect when pools experience large outflows or inflows - **Price impact analysis**: Track how `MinAmountOut` changes relative to `MaxAmountIn` to identify when pools become less liquid - **Mean reversion opportunities**: Identify pools where large swaps have created temporary price dislocations that may revert - **Toxic order flow avoidance**: Use slippage data to avoid entering positions when liquidity is thin or when large trades are likely to move price against you For a practical implementation example of using slippage data for automated trading strategies, including flow toxicity detection and mean-reversion trading, see the [AMM Flow Toxicity Alpha Engine](https://github.com/Divyn/amm-flow-toxicity-alpha-engine) repository. This system demonstrates how to: - Detect large swaps that move price significantly (50-500 basis points) - Verify isolation from trending markets - Execute fade trades against temporary price impacts - Manage positions with dynamic stop losses and take profits based on slippage data For more advanced use cases, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#advanced-use-cases-and-processing-patterns). --- ## EVM DEX Trades Schema URL: https://docs.bitquery.io/docs/schema/evm/dextrades/ Explore the EVM DEX Trades schema in Bitquery GraphQL, including trade fields, joins, filters, and example queries for swap analytics. # EVM DEX Trades Schema DEXTrades api gives trading-related data from different DEXs such as Uniswap, Pancakeswap, 0x, etc. API provides historical and real-time trades and pricing information for tokens. The API allows different filters to query the Smart contract calls details from different dimensions, such as from different DEXs, protocols, tokens, trades, pools, etc. You can find more examples [here](/docs/blockchain/Ethereum/dextrades/get-trading-pairs-of-token/) ## DEX Trades Cube Dex Trades represent every swap of tokens on decentralised exchange. Every trade has two sides, represented by currencies ( tokens or native currency ), which are exchanged. Buyer and seller side in some cases are selected related to the "maker" side of the trade if the DEX is limit orders type. In case of automated trading ( uniswap, balancer and others) the trade is related to the pool smart contract, executing the trade. Use DEX Trades Cube in case when you need to build query based on protocol or smart contracts, for example: * total count of trades by protocols or smart contracts or oter dimensions * gas spending on trades * dynamics in time of DEX usage ## DEX Trades By Tokens DEX Trades By Tokens exposes trades relative to the token. So every trade is represented by 2 records - by every token participating in trade. This allows to build queries by tokens which take into account all orders for token (buy side and sell side). Use DEX Trades Cube in case when you need to build query based on token or pair of tokens, for example: * query every pair the token is involved * price of trading the token * open-high-low-close OHLC graph building ( see example below ) :::caution DEX Trades By Tokens has twice as much records for dex trades. Always use at least one filter by token to query correctly! ::: :::tip Use interval argument for date/time to build OHLC graph by time interval ::: ## Examples Here are the sample queries to get started: ### OHLC API Query price OHLC data for token pairs using DEX Trades By Tokens ```graphql query MyQuery { EVM(dataset: archive) { DEXTradeByTokens( orderBy: {descendingByField: "Block_datefield"} #WETH-USDT trades on Uniswap V3 where: {Trade: {Currency: {SmartContract: {is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}}, Side: {Currency: {SmartContract: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}}}, Dex: {SmartContract: {is: "0x4e68ccd3e89f51c3074ca5072bbac773960dfa36"}}}} limit: {count: 10} ) { Block { datefield: Date(interval: {in: days, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) Currency { Name } Dex { ProtocolName SmartContract } Side { Currency { Name SmartContract } } } count } } } ``` :::note we applied filter by tokens, used [interval](/docs/graphql/datetime) and actual numbers calculated by aggregated [metrics ( max/min )](/docs/graphql/calculations) ::: ```graphql { EVM(dataset: archive, network: eth) { buyside: DEXTrades( limit: {count: 10} orderBy: {descending: Block_Time} where: {Trade: {Buy: {Currency: {SmartContract: {is: "0x5283d291dbcf85356a21ba090e6db59121208b44"}}}}, Block: {Time: {since: "2023-03-03T01:00:00Z", till: "2023-03-05T05:15:23Z"}}} ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price } Sell { Amount Buyer Currency { Name SmartContract Symbol } Seller Price } } } sellside: DEXTrades( limit: {count: 10} orderBy: {descending: Block_Time} where: {Trade: {Buy: {Currency: {SmartContract: {is: "0x5283d291dbcf85356a21ba090e6db59121208b44"}}}}, Block: {Time: {since: "2023-03-03T01:00:00Z", till: "2023-03-05T05:15:23Z"}}} ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price } Sell { Amount Buyer Currency { Name SmartContract Symbol } Seller Price } } } } } ``` --- ## EVM Kafka Protobuf Streams URL: https://docs.bitquery.io/docs/streams/protobuf/chains/EVM-protobuf/ EVM Protobuf with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. Great for bots, dashboards, and alerts. # EVM Streams This section provides details about Bitquery's EVM Streams via Kafka. The top-level Kafka section explains how we use Kafka Streams to deliver data. You can find the schema [here](https://github.com/bitquery/streaming_protobuf/tree/main/evm). EVM blockchains produce blocks at varying intervals depending on the network. Ethereum mainnet targets ~12 seconds per block, while other EVM chains may have different block times. :::info USD Values All amounts in the EVM protobuf streams now include USD equivalents — token transfer amounts, DEX trade sides, transaction fees, and balance updates each carry an `...InUSD` field (e.g. `AmountInUSD`, `TransactionFeeInUSD`, `PostBalanceInUSD`). These are populated in real time on the streams. ::: ## Structure of On-Chain Data The EVM Protobuf Streams provide three main message types for different use cases: - `BlockMessage`: Full blocks with detailed transaction traces - `TokenBlockMessage`: Focused on token transfers with currency metadata - `DexBlockMessage`: Specialized for DEX (Decentralized Exchange) trading activity - `DexPoolBlockMessage` - Focused on real-time slippage at multiple bps and liquidity from Uniswap Pools ### Block-Level Data Each block in the stream includes a `BlockHeader` with fields such as: - `Hash`: The unique identifier of the block - `ParentHash`: Hash of the previous block - `Number`: Block number/height in the chain - `GasLimit`: Maximum gas allowed in this block - `GasUsed`: Actual gas consumed by transactions - `Time`: Block timestamp - `BaseFee`: Base fee per gas (EIP-1559) The `BlockMessage` also includes: - `Chain`: Information about the blockchain (ChainId, Config) - `Uncles`: Uncle/ommer blocks (Ethereum PoW) - `Transactions`: All transactions in the block - `L1Header`: For Layer 2 chains, information about the corresponding L1 block ## Transaction-Level Data Each transaction in the stream provides detailed information about execution, state changes, and balance updates. ### Structure Each transaction includes: - **`TransactionHeader`** — Core transaction metadata: - `Hash` — Transaction hash - `Gas` — Gas limit for this transaction - `Value` — Amount of native currency transferred - `Data` — Call data for contract interactions - `From` / `To` — Sender and recipient addresses - `GasPrice`, `GasFeeCap`, `GasTipCap` — Fee parameters - `Nonce`, `ChainId` — Transaction metadata - Special fields for EIP-4844 blob transactions - **`ReceiptHeader`** — Execution results: - `Status` — Success or failure - `GasUsed` — Actual gas consumed - `Logs` — Event logs emitted by smart contracts - `ContractAddress` — Deployed address for contract creation transactions - **`TransactionFee`** — Fee information: - `SenderFee` — Total fee paid by the sender - `MinerReward` — Portion rewarded to the validator/miner - `Burnt` — Portion of the fee burned (EIP-1559) - `GasRefund` — Gas refunded due to contract execution - **`Calls`** — Full internal call trace: - Includes all nested contract calls with fields such as `From`, `To`, `Input`, `Output`, `GasUsed`, `Opcode`, and parsed `Signature` - Each call may include `Logs`, `StateChanges`, and `ReturnValues` - **`Signature`** — Cryptographic components: - `R`, `S`, and `V` values from the transaction’s ECDSA signature - **`TokenBalanceUpdates`** — Token (ERC-20, ERC-721, ERC-1155) balance updates detected during the transaction: - `Token` — Information about the token - `Address` — Token contract address - `Fungible` — Whether the token is fungible (ERC-20) or non-fungible (ERC-721/1155) - `Decimals` — Number of decimal places for fungible tokens - `TotalSupply` — Current total supply recorded - `Address` — Wallet whose balance changed - `PostBalance` — Balance after the transaction - `TokenOwnership` — For NFTs, indicates ownership details if applicable - `PreBalanceInUSD` / `PostBalanceInUSD` — USD value of the balance before and after the transaction - `TotalSupplyInUSD` — USD value of the token's total supply - **`NativeBalanceUpdates`** — Native currency (e.g., ETH) balance changes detected during the transaction: - `Address` — Wallet whose native balance changed - `PreBalance` — Balance before the transaction - `PostBalance` — Balance after the transaction - `BalanceChangeReasonCode` — Numeric code describing why the balance changed (see [Transaction Balance Tracker documentation](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) for code meanings) ### Token Data The `TokenBlockMessage` stream provides information about token transfers: - `TokenTransfer`: Records token movements with: - `Sender`: Address sending tokens - `Receiver`: Address receiving tokens - `Amount`: Amount of tokens transferred - `Id`: Token ID (for non-fungible tokens) - `Currency`: Detailed token information - `Success`: Whether the transfer succeeded - `AmountInUSD`: USD value of the transferred amount - `TokenInfo`: Metadata about each token: - `SmartContract`: Token contract address - `Name`: Token name - `Symbol`: Token symbol - `Decimals`: Token decimal places - `Fungible`: Whether token is fungible (ERC-20) or non-fungible (ERC-721/1155) ### DEX (Decentralized Exchange) Data The `DexBlockMessage` stream specializes in DEX trading activity: - `DexTrade`: Records of trades executed on DEXs - `Buy`/`Sell`: Both sides of the trade, each with an `AmountInUSD` field giving the USD value of that side - `Dex`: Information about the exchange - `Success`: Whether the trade succeeded - `Fees`: Trading fees paid - `TransactionFeeInUSD`: USD value of the transaction fee - `DexInfo`: Details about the exchange: - `SmartContract`: Exchange contract address - `ProtocolName`: Name of the protocol (e.g., "Uniswap", "SushiSwap") - `ProtocolFamily`: Family of DEX protocols - `ProtocolVersion`: Version of the protocol - `Pair`: Trading pair information - `TradeSide`: Details about each side of a trade: - `Buyer`/`Seller`: Addresses involved - `OrderId`: Identifier for the order - `Assets`: What was traded ### DEXPools DEXPools provide real-time liquidity pool data for decentralized exchanges, including current token reserves, price calculations at different slippage tolerances, and pool state information. DEXPools data is available via Kafka streams and GraphQL APIs, and is emitted when specific events occur that change pool liquidity (such as swaps, mints, burns, or liquidity modifications depending on the protocol version). For detailed information about DEXPools, including: - Pool structure and liquidity information - Price tables and slippage calculations - When DEXPool records are emitted for different protocol versions (Uniswap V2, V3, V4) - Filtering and advanced use cases See the [DEXPools Cube on EVM Chains documentation](/docs/cubes/evm-dexpool/). ### Layer 2 Support EVM Protobuf Streams provide dedicated fields for Layer 2 chains: - `L1Header`: Corresponding L1 block information - Optimism-specific fields: `SequenceNumber`, `BatcherAddr`, `L1FeeOverhead`, etc. - Arbitrum-specific fields: `GasL1` for L1 data costs ### Using This Stream in Python, JavaScript, and Go Python, JavaScript, and Go code samples can be used with these streams by changing the topic to one of: - `eth.transactions.proto` -> `ParsedAbiBlockMessage` - `eth.tokens.proto` -> `TokenBlockMessage` - `eth.dextrades.proto` -> `DexBlockMessage` - `eth.raw.proto` (for raw block data) -> `BlockMessage` - `eth.broadcasted.transactions.proto` (for broadcasted transactions) -> `ParsedAbiBlockMessage` - `eth.broadcasted.tokens.proto` (for broadcasted token transfers) -> `TokenBlockMessage` - `eth.broadcasted.dextrades.proto` (for broadcasted DEX trades) -> `DexBlockMessage` - `eth.broadcasted.raw.proto` (for raw broadcasted block data) -> `BlockMessage` The Python package [bitquery-pb2-kafka-package](https://pypi.org/project/bitquery-pb2-kafka-package/) includes all schema and is up to date so you don't have to manually install schema files. ## Video Tutorial to Track Deposits and Withdrawals for Exchange Wallets Using Kafka ## Video Tutorial to Get Latest Four Meme Trades Using Kafka --- ## EVM Miner Rewards API URL: https://docs.bitquery.io/docs/schema/evm/miners/ EVM Miner Rewards API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. See examples in the Bitquery IDE. # EVM Miner Rewards API Miner Rewards are the incentives paid out to miners for validating transactions and creating new blocks on the blockchain. You can access Miner Rewards data using the Bitquery API. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { MinerRewards(limit: {count: 10}, orderBy: {descending: Block_Time}) { Reward { BurntFees Dynamic Static TxFees Total } Block { Time } } } } ``` **Data** `MinerRewards`: Returns an array of the top 10 miner rewards on the Ethereum network. - `Reward`: Returns the details of the miner reward. - `BurntFees`: Returns the amount of fees that were burnt - `Dynamic`: Returns the amount of dynamic fees. - `Static`: Returns the amount of static fees. - `TxFees`: Returns the amount of transaction fees. - `Total`: Returns the total amount of the miner reward. - `Block`: Returns the details of the block that the miner reward was received in. - `Time`: Returns the time that the block was created. --- ## EVM Schema Overview URL: https://docs.bitquery.io/docs/schema/evm/top/ Explore Bitquery’s EVM GraphQL schema cubes for blocks, transactions, transfers, events, calls, and DEX trade analytics. # Overview Bitquery APIs provide access to real-time and historical data from the Ethereum Virtual Machine (EVM) based blockchains through its EVM-based schema. The schema is designed to enable developers to query blockchain data through an API using GraphQL. The EVM-based schema contains different types of queries, such as block, transaction, event, miner rewards, and token transfers. These queries can be used to retrieve different types of blockchain data, such as block information, transaction details, events, and token transfers. Here's a list of different sections in this documentation: 1. [Blocks](/docs/schema/evm/blocks) 2. [Miner Rewards](/docs/schema/evm/miners) 3. [Uncle Blocks](/docs/schema/evm/uncles) 4. [Balances](/docs/schema/evm/balances) 5. [Token Holders](/docs/schema/evm/token-holders) 6. [Transfers](/docs/schema/evm/transfers) 7. [Transactions](/docs/schema/evm/transactions) 8. [Events](/docs/schema/evm/events) 9. [Dex Trades](/docs/schema/evm/dextrades) 10. [Calls](/docs/schema/evm/calls) --- ## EVM Smart Contract Calls API URL: https://docs.bitquery.io/docs/schema/evm/calls/ EVM Smart Contract Calls API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. # EVM Smart Contract Calls API Calls API provides details about smart contract calls, arguments, callers, etc. This api gives detailed information about the smart contract calls, including raw data, and supports [Opcodes](https://github.com/crytic/evm-opcodes). The API allows different filters to query the Smart contract calls details from different dimensions. You can find more examples [here](/docs/blockchain/Ethereum/calls/smartcontract/) Here's a sample query to get started. ```graphql { EVM(dataset: combined, network: eth) { Calls( limit: { count: 1 } where: { Call: { Signature: { Name: { is: "swap" } } From: { is: "0x000000000000084e91743124a982076c59f10084" } } } ) { Call { From To CallPath CallerIndex Create Delegated Depth EnterIndex Error ExitIndex Gas GasUsed Index Input InternalCalls LogCount Opcode { Code Name } Output Reverted SelfDestruct Signature { Abi Name Parsed Signature SignatureHash SignatureType } Success } Arguments { Type { Name Type } Value { String } } } } } ``` Calls contain the arguments and return values as arrays, refer to [arguments](/docs/schema/evm/arguments) for data structure. --- ## EVM Smart Contract Events & logs API URL: https://docs.bitquery.io/docs/schema/evm/events/ EVM Smart Contract Events & logs API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. # EVM Smart Contract Events & logs API Smart contract events and logs are an important feature of Ethereum smart contracts that allow developers to track and record specific actions or data on the blockchain. You can retrieve data on blockchain calls and logs from the blockchain network. You can find more examples [here](/docs/blockchain/Ethereum/events/events-api/) ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { Events( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Block: { Date: { is: "2023-03-06" } } } ) { Call { CallPath From GasUsed To Signature { Name Signature } } Log { EnterIndex ExitIndex Index LogAfterCallIndex SmartContract Signature { Name Signature } } } } } ``` The query includes the Call and Log objects, which are parts of the events. The Call object contains information about the function calls made in the event, including the path, sender address, gas used, receiver address, and the name and signature of the function. The Log object contains information about the event logs, including the enter and exit indexes, log index, log after call index, the smart contract address, and the name and signature of the event. Events contain the arguments as array, refer to [arguments](/docs/schema/evm/arguments) --- ## EVM Token Holders API URL: https://docs.bitquery.io/docs/schema/evm/token-holders/ EVM Token Holders API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. See examples in the Bitquery IDE. # EVM Token Holders API :::caution Query-only A subscription on `Holders` is accepted but never pushes a message. Poll it on a schedule, and stream `Transfers` for the token to know when a refresh is worthwhile. See [which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/). ::: The **Holders** API returns token holder data for ERC-20 tokens: top holders, holder counts, and balance thresholds. Non-zero balances use `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | |---------|-------------| | **`combined`** | Latest holder count, top holders, and balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Addresses not recently active (not in the realtime window). | Full Ethereum examples: [Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api). ## Token holder count ```graphql query { EVM(network: eth, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } ) { uniq(of: Holder_Address) } } } ``` ### Filter parameters - `dataset: combined` — latest holder count, top holders, and activity - `dataset: archive` — addresses not recently active - `where.Currency.SmartContract` — token contract address (required) - `where.Balance.LastChangeTime` — filter by last balance change (datetime, e.g. `till: "2026-05-01T00:00:00Z"`). The Holders cube does not support `Block.Date`. - `where.Holder.Address` — filter to a specific wallet - `Balance.Amount(selectWhere: { gt: "..." })` — non-zero balances when listing amounts - `uniq(of: Holder_Address, if: { Balance: { Amount: { gt: "..." } } } })` — holder count above a threshold - `limit`, `orderBy` — pagination and sorting (e.g. `descending: Balance_Amount`) ### Return fields - `Holder.Address` — holder wallet address - `Balance.Amount`, `Balance.AmountInUSD` — token balance (use `selectWhere` for non-zero) - `Balance.UpdateCount`, `Balance.FirstChangeTime`, `Balance.LastChangeTime` — holder activity ### Examples on Ethereum - [Top holders (current)](/docs/blockchain/Ethereum/token-holders/token-holder-api#top-holders-of-a-currency-current) - [Token holder count](/docs/blockchain/Ethereum/token-holders/token-holder-api#token-holder-count-for-an-erc-20-token) - [Holder count above a threshold](/docs/blockchain/Ethereum/token-holders/token-holder-api#holder-count-with-balance-above-a-threshold) - [Track whale wallets](/docs/blockchain/Ethereum/token-holders/token-holder-api#track-whale-wallets-and-token-holdings) - [Historical top holders](/docs/blockchain/Ethereum/token-holders/token-holder-api#historical-top-holders-by-date) - [Holder count history](/docs/blockchain/Ethereum/token-holders/token-holder-api#token-holder-count-history-over-time) - [Wallet token balance at a date](/docs/blockchain/Ethereum/token-holders/token-holder-api#wallet-balance-at-a-point-in-time) (via [Balances API](/docs/blockchain/Ethereum/balances/balance-api/#wallet-balance-for-a-specific-token-on-a-date)) - [Holder activity](/docs/blockchain/Ethereum/token-holders/token-holder-api#token-holder-activity) — `UpdateCount`, `FirstChangeTime`, `LastChangeTime` --- ## EVM Token Supply API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/token-supply/evm-token-supply/ EVM Token Supply API: stream Ethereum market cap, FDV, supply, and price using Bitquery Trading GraphQL APIs. Run it in the IDE, then ship in your app. # EVM Token Supply API Track real-time and historical token supply data across all EVM-compatible blockchains including Ethereum, BNB Chain (BSC), Base, Arbitrum, Polygon, and more using Bitquery's Token Supply API. :::info Looking for Solana Token Supply? Bitquery also provides comprehensive **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** with features including: - Real-time token supply changes and market cap tracking - Pump.fun and Moonshot token creation monitoring - Token burn event tracking - Top tokens by market cap queries ➡️ **[View Solana Token Supply Documentation](/docs/blockchain/Solana/token-supply-cube/)** ::: ## What is Token Supply? Token supply refers to the total number of tokens that exist for a particular cryptocurrency or token. Understanding token supply is crucial for: - **Market Cap Calculation**: Total Supply × Token Price = Market Capitalization - **Inflation/Deflation Analysis**: Monitor minting and burning events - **DeFi Protocol Analysis**: Track liquidity and TVL changes - **Stablecoin Monitoring**: Verify backing and supply changes for USDT, USDC, DAI, etc. - **Investment Research**: Evaluate tokenomics and supply dynamics ## How do I get the total supply or circulating supply of a token? **Total supply on EVM:** Use Bitquery `EVM.TransactionBalances` (or streaming equivalents) and read `TokenBalance.TotalSupply` for the token contract, setting `network` to `eth`, `bsc`, `base`, or another supported chain. **Circulating supply** is not a single on-chain field: it is usually derived as total supply minus known treasury or locked wallets, or adjusted for burns—use mint/burn and transfer patterns from the same API family if you define it that way. ## 🔗 Related APIs ### EVM APIs - **[EVM Balance Updates API](/docs/schema/evm/balances/)** - Track wallet balance changes - **[EVM Token Holders API](/docs/schema/evm/token-holders/)** - Get top holders of any token - **[EVM Transfers API](/docs/schema/evm/transfers/)** - Monitor token transfers - **[EVM DEX Trades API](/docs/schema/evm/dextrades/)** - Track trading activity ### Solana APIs - **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** - Track SPL token supply, market cap, and burn events - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor Solana wallet balances - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Track Solana DEX trading activity --- ## Real-Time Token Supply Stream (WebSocket) ### Latest Token Supply on BNB Chain Subscribe to real-time token supply updates across all tokens on the BNB Chain (BSC). This WebSocket subscription provides continuous updates as token supplies change due to minting or burning. You can run this query [here](https://ide.bitquery.io/latest-token-supply-on-BSC-chain). ```graphql subscription { EVM(network: bsc) { TransactionBalances( limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 } where: { TokenBalance: { Currency: { SmartContract: { not: "0x" } } } } ) { TokenBalance { TotalSupply Currency { Name Symbol SmartContract } } } } } ``` **Key Parameters:** - `limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 }` - Returns only the latest supply for each unique token - `SmartContract: { not: "0x" }` - Excludes native currency (BNB) to focus on ERC-20 tokens :::tip Multi-Chain Support Change the `network` parameter to query other EVM chains: - `eth` - Ethereum - `bsc` - BNB Chain - `base` - Base - `arbitrum` - Arbitrum - `matic` - Polygon - `optimism` - Optimism ::: --- ## Token Supply Queries (GraphQL) ### Latest Token Supply of Specific Tokens on Ethereum Get the current total supply for specific tokens like USDC and USDT on Ethereum or any EVM network. This is ideal for stablecoin tracking and portfolio applications. You can run this query [here](https://ide.bitquery.io/latest-token-supply-on-USDT-and-USDC-on-ethereum-chain). ```graphql { EVM(network: eth) { TransactionBalances( orderBy: { descending: Block_Time } limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 } where: { TokenBalance: { Currency: { SmartContract: { in: [ "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" "0xdac17f958d2ee523a2206206994597c13d831ec7" ] } } } } ) { TokenBalance { TotalSupply Currency { Name Symbol SmartContract } } } } } ``` **Common Token Addresses (Ethereum):** | Token | Contract Address | | ----- | -------------------------------------------- | | USDT | `0xdac17f958d2ee523a2206206994597c13d831ec7` | | USDC | `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` | | DAI | `0x6b175474e89094c44da98b954eedeac495271d0f` | | WETH | `0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` | | LINK | `0x514910771af9ca656af840dff83e8264ecf986ca` | --- ### Latest Token Supply of All Active Tokens on Base Retrieve the latest total supply for all active tokens on the Base blockchain. This query is useful for market analytics, portfolio trackers, and DeFi dashboards. You can run this query [here](https://ide.bitquery.io/latest-token-supply-of-all-active-tokens-on-base-chain). ```graphql { EVM(network: base) { TransactionBalances( orderBy: { descending: Block_Time } limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 } where: { TokenBalance: { Currency: { SmartContract: { not: "0x" } } } } ) { TokenBalance { TotalSupply Currency { Name Symbol SmartContract } } } } } ``` --- ## Use Cases ### 1. Stablecoin Supply Monitoring Track stablecoin supplies to monitor market dynamics and potential de-pegging risks: - Monitor USDT, USDC, DAI supply changes in real-time - Detect large minting or burning events - Compare supply across different chains ### 2. Market Cap Calculation Calculate accurate market capitalization by combining supply data with price feeds: ``` Market Cap = Total Supply × Current Price ``` ### 3. Token Inflation Analysis Analyze token inflation rates by comparing supply changes over time: - Track new token emissions - Monitor burning mechanisms - Calculate inflation/deflation rates ### 4. DeFi Protocol Analytics Monitor supply changes for DeFi governance tokens and LP tokens to understand protocol health and user activity. ### 5. Compliance & Auditing Maintain audit trails of supply changes for regulatory compliance and financial reporting. --- ## API Response Fields | Field | Description | | ------------------------------------- | ---------------------------------------- | | `TokenBalance.TotalSupply` | Current total supply of the token | | `TokenBalance.Currency.Name` | Token name (e.g., "USD Coin") | | `TokenBalance.Currency.Symbol` | Token symbol (e.g., "USDC") | | `TokenBalance.Currency.SmartContract` | Token contract address | | `TokenBalance.Currency.Decimals` | Number of decimal places | | `Block.Number` | Block number of the supply update | | `Block.Time` | Timestamp of the supply update | --- ## Supported Networks | Network | Parameter | Description | | -------- | ----------- | ------------------- | | Ethereum | `eth` | Ethereum Mainnet | | BNB Chain| `bsc` | BNB Smart Chain | | Base | `base` | Base L2 | | Arbitrum | `arbitrum` | Arbitrum One | | Polygon | `matic` | Polygon PoS | | Optimism | `optimism` | Optimism L2 | | Robinhood| `robinhood` | Robinhood network | | Arc | `arc` | Arc mainnet | --- ## Best Practices 1. **Use `limitBy` for Latest Data**: Always use `limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 }` to get only the most recent supply for each token. 2. **Filter by Smart Contract**: When querying specific tokens, use the `SmartContract: { is: "..." }` filter to improve query performance. 3. **Use Archive Dataset for History**: For historical queries, specify `dataset: archive` to access complete blockchain history. 4. **Handle Decimals Properly**: Remember to divide `TotalSupply` by `10^Decimals` to get the human-readable supply value. --- ## Getting Started 1. **Get API Access**: Sign up at [Bitquery](https://bitquery.io/) to get your API key 2. **Try in IDE**: Test queries in the [Bitquery IDE](https://ide.bitquery.io/) 3. **Integrate**: Use the GraphQL endpoint in your application For more information on authentication and API usage, see our [Getting Started Guide](/docs/start/first-query/). --- ## EVM Token Transfers API URL: https://docs.bitquery.io/docs/schema/evm/transfers/ EVM Token Transfers API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. See examples in the Bitquery IDE. # EVM Token Transfers API To retrieve data on token and currency transfers using Bitquery, users can utilize the platform's GraphQL API. The Bitquery API allows users to construct custom queries to retrieve data on a wide range of blockchain events and transactions, including token transfers. You can find more examples [here](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api/) ```graphql Transfers(limit: {count: 10}, orderBy: {descending: Block_Time}) { Transfer { Amount Currency { Fungible Name ProtocolName Symbol } Data Id Receiver Sender Success Type } } ``` `Transfers`: The top level method that returns transfer information - `Transfer`: Returns information on the token transfer. - `Amount`: Returns the amount of tokens transferred. - `Currency`: Returns information on the currency of the token transferred. - `Fungible`: Returns a Boolean value indicating whether the token is fungible. - `Name`: Returns the name of the token. - `ProtocolName`: Returns the name of the protocol on which the token is built. - `Symbol`: Returns the symbol used to represent the token. - `Data`: Returns any additional data associated with the token transfer. - `Id`: Returns the ID of the token transfer. - `Receiver`: Returns the address of the token receiver. - `Sender`: Returns the address of the token sender. - `Success`: Returns a Boolean value indicating whether the token transfer was successful. - `Type`: Returns the type of token transfer. e.g. call. --- ## EVM Transactions Schema API URL: https://docs.bitquery.io/docs/schema/evm/transactions/ Transactions API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. Scale further with WebSocket subscriptions or Kafka streams. # EVM Transactions Schema API The Transactions API provides detailed information on transactions including call count, gas, hash, type, and sender and recipient addresses etc. Here's a sample query to get started. You can see more examples [here](/docs/blockchain/Ethereum/transactions/transaction-api/) query MyQuery \{ EVM(dataset: realtime, network: bsc) \{ Transactions( limit: \{count: 10\} orderBy: \{descending: Block_Time\} where: \{Block: \{Date: \{after: "2023-02-05"\}\}} ) \{ Transaction \{ CallCount Gas Hash Type To From } Block \{ Date } TransactionStatus \{ Success FaultError EndError } } } } ### Parameters: - `limit`: Limits the number of transactions returned in the query. In this case, it is set to 10. - `orderBy`: Specifies the field to order the results by. In this case, it is ordered in descending order based on block time. - `where`: Filters the results based on specific criteria. In this case, it returns transactions that occurred after February 5, 2023. ### Returns: - `Transaction`: Contains information about the transaction, including call count, gas, hash, type, and sender and recipient addresses. - `Block`: Contains information about the block that the transaction was included in, including the date of the block. - `TransactionStatus`: Contains information about the transaction status, including whether it was successful, and if there were any errors. --- ## EVM Uncle Blocks API URL: https://docs.bitquery.io/docs/schema/evm/uncles/ EVM Uncle Blocks API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. See examples in the Bitquery IDE. # EVM Uncle Blocks API ### What are Uncle Blocks? Uncle blocks, also known as "orphan blocks", are blocks on the blockchain that are not included in the main blockchain. Uncle blocks are still valid blocks, but they were not selected to be included in the main blockchain by the network consensus algorithm. Please note that after the September 2022 merge of PoS Ethereum, validators will be pre-selected to validate the blocks. Hence, there will be no uncle blocks created. ### Why do Uncle Blocks occur? Uncle blocks occur due to network latency issues or network forks that can cause two or more miners to solve a block at the same time. Only one of these blocks can be included in the main blockchain, while the others become uncle blocks. ### What is the significance of Uncle Blocks? Uncle blocks are significant because they can have an impact on the security and efficiency of the Ethereum blockchain. When uncle blocks are created, they reduce the rewards that miners receive for their work, and can also reduce the overall efficiency of the blockchain. ### How can I access Uncle Blocks data? You can access Uncle Blocks data using our API. Here's an example GraphQL query to retrieve Uncle Blocks data: ```graphql query MyQuery { EVM(dataset: archive, network: eth) { Uncles(limit: { count: 10 }, orderBy: { descending: Uncle_Block_Time }) { Block { Time } Uncle { Index Block { TxHash Time Number ParentHash Bloom Date } } } } } ``` - `Block`: Returns the details of the block that included the uncle block. - `Time`: Returns the time that the block was created. - `Uncle`: Returns the details of the uncle block. - `Index`: Returns the index of the uncle block. - `Block`: Returns the details of the uncle block itself. - `TxHash`: Returns the hash of the uncle block's transaction. - `Time`: Returns the time that the uncle block was created. - `Number`: Returns the number of the uncle block. - `ParentHash`: Returns the hash of the uncle block's parent block. - `Bloom`: Returns the bloom filter of the uncle block. - `Date`: Returns the date that the uncle block was created. --- ## Edge Details - Inspect a Transfer Between Two Addresses URL: https://docs.bitquery.io/docs/moneyflow-lite/edge-details/ Click an edge in the MoneyFlow chart to see sender, receiver, amount by currency and every transaction behind that flow in MoneyFlow Lite. # Edge Details An edge is the band between two nodes. Click it to open **Edge details** in the right-hand panel. ![Edge details panel](/img/moneyflow-lite/edge-details.jpg) ## Sender, amount, receiver The header of the panel reads left to right: - **Sender**: the node the funds left, and how many addresses it groups. - **Amount**: the total USD value of the edge. - **Receiver**: the node the funds reached, and how many addresses it groups. **New Tag** adds a custom tag to the edge. ## Amounts by Currencies The table lists each currency carried by the edge with the amount and the USD value. On a Bitcoin trace there is one row, Bitcoin. On an account-based chain an edge can carry several assets. Use the **Search** box to find one currency. ## Transactions of Flow When an edge is selected, the table at the bottom of the page becomes **Transactions of Flow**. It lists every on-chain transaction that makes up the edge: time, depth, hash, sender, receiver, transaction amount, tracing amount, currency and status. Click a transaction hash to open it in the Bitquery Explorer. See [transactions table](/docs/moneyflow-lite/transactions-table) for the full column reference. ## Get API **Get API** in the panel header opens the Coinpath® query behind this edge in the Bitquery IDE. See [Get API](/docs/moneyflow-lite/get-api-coinpath-query). --- ## Embed Bitquery Queries in Your App URL: https://docs.bitquery.io/docs/start/embed/ Embed Bitquery Queries in Your App: practical Bitquery setup guidance with examples for authentication, endpoints, and first queries. # Use it in Your Application You can integrate both queries and subscriptions in your application on any programming language and framework. First you create a query or subscription in [IDE](/docs/start/first-query/), and then you embed this query and some client code in your application. The client code depends on the programming language and set of libraries you prefer to use, try search google on "graphql YOUR-LANGUAGE library" keyword to start with. [IDE](/docs/start/first-query/) provides an example code templates to your queries on some programming languages. After you created the query, press the `````` button located to the right from the endpoint URL entry field. You will see the code snippet and the selection of languages and libraries to use: ![IDE code snippets](/img/ide/code_snippets.png) Select your programming language and run the code in your application. Note that you have to use your [OAuth key](/docs/authorization/how-to-generate/). [IDE](/docs/start/first-query/) automatically substituted it for you in the code, but in production environment you may need to change it to another one, potentially with the [paid plan](/docs/ide/paid). --- ## End of Day Balances - Historical Balance Snapshots URL: https://docs.bitquery.io/docs/usecases/end-of-day-balances/ Get an address's token balance as of a past date on EVM, Tron and Solana, for accounting, tax reporting and reconciliation. # End-of-day balances Accounting, tax reporting and reconciliation all need the same thing: what an address held at the close of a given day, not what it holds now. This page covers that on EVM, Tron and Solana. For current holdings instead, see the [wallet portfolio recipe](/docs/usecases/wallet-portfolio-api/). ## EVM and Tron The `Holders` cube takes a `date` argument and returns the holder set as of that date. Filter it to a single address and you have that address's end-of-day balance. ```graphql query EndOfDayBalance { EVM(network: eth, dataset: archive) { Holders( date: "2026-07-01" where: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } Holder: { Address: { is: "0x28c6c06298d514db089934071355e5743bf21d60" } } } ) { Holder { Address } balance: sum(of: Balance_Amount) } } } ``` Run it across consecutive dates and you get a genuine daily series, not a running total: | Date | USDT balance | |---|---:| | 2026-06-28 | 520,591,652.30 | | 2026-06-29 | 638,001,909.50 | | 2026-06-30 | 561,901,590.46 | | 2026-07-01 | 819,349,860.88 | | 2026-07-02 | 550,887,384.37 | (An exchange hot wallet, so the swings are real activity rather than an artefact.) `date` is a single scalar, so a range means one request per day. Issue them in parallel and assemble the series client-side. The same query shape works on Tron with `Tron { Holders(...) }`. :::caution Use `dataset: archive` for past dates The default realtime dataset only carries a recent window, so an older `date` comes back empty and looks like the address held nothing. Empty results here almost always mean the wrong dataset rather than a zero balance. ::: ### The same series from `Balances` `Balances` carries **daily aggregates**, one row per address per day, exposed as `Block.Date`. That makes it the more natural source for a series, because a single query returns every day at once instead of one request per date: ```graphql query DailyBalanceSeries { EVM(network: eth, dataset: archive) { Balances( where: { Balance: { Address: { is: "0x28c6c06298d514db089934071355e5743bf21d60" } } Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } orderBy: { descending: Block_Date } limit: { count: 30 } ) { Block { Date } Balance { Amount AmountInUSD } } } } ``` For a single past date, add `Block: { Date: { till: "2026-07-01" } }` and keep the descending order — the first row is that day's closing balance. :::caution Always order by `Block_Date` Without `orderBy: { descending: Block_Date }` you get an arbitrary day's row, not the latest or the one you filtered to. The query still succeeds, so the mistake is silent — it looks like a current balance and is not. With the ordering, `Balances` and `Holders(date: …)` agree exactly. Both return `819349860.876615` for the wallet and date above. ::: ## Solana Solana has no `Holders` cube, so take the last balance update at or before the cutoff. `limitBy` collapses to one row per mint: ```graphql query SolanaEndOfDayBalance { Solana { BalanceUpdates( where: { BalanceUpdate: { Account: { Owner: { is: "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9" } } } Block: { Time: { till: "2026-08-02T23:59:59Z" } } } orderBy: { descending: Block_Time } limitBy: { by: BalanceUpdate_Currency_MintAddress, count: 1 } limit: { count: 50 } ) { Block { Time } BalanceUpdate { PostBalance PostBalanceInUSD Currency { Symbol MintAddress } } } } } ``` Three parts do the work, and dropping any one of them gives a wrong answer: - `Block: { Time: { till: ... } }` sets the cutoff. - `orderBy: { descending: Block_Time }` puts the most recent update first. - `limitBy` on the mint keeps exactly one row per token. `PostBalance` is the balance immediately after that update, which is the balance the address carried into the next day. The returned `Block.Time` tells you how stale the figure is: a token last touched weeks before the cutoff still reports its correct balance, just with an older timestamp. ## Reconciliation notes - **Set your day boundary explicitly.** `till: "2026-08-02T23:59:59Z"` is UTC. If your books close in another timezone, convert before querying rather than after. - **A missing row is not a zero balance.** On Solana, an address that never held a token has no balance update for it at all. Treat absent and zero as different cases. - **Large tokens can time out.** A dated `Holders` query filtered to one address is cheap, but the same query without an address filter on a token with millions of holders may exceed the request timeout. Always include the address filter when you want one balance. - **Cross-check one date against a block explorer** before trusting a whole series. It is the fastest way to catch a timezone or dataset mistake. ## Related - [Wallet portfolio](/docs/usecases/wallet-portfolio-api/) — current holdings - [Balances & Holders cubes](/docs/cubes/balances-cube/) - [Build your own crypto P&L calculator](/docs/usecases/p-l-product/overview/) --- ## Ethereum API - Best Blockchain Data API for Developers URL: https://docs.bitquery.io/docs/blockchain/Ethereum/ Ethereum on-chain data API: DEX trades, slippage, liquidity, token holders, balances and token transfers, with real-time streaming and how it differs from RPC. # Ethereum API - Complete Developer Guide :::tip Building a trading app or DEX UI on Ethereum? For **real-time trades and prices on Ethereum** (and the last ~30 days), use the curated [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. For **historical Ethereum data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: ## What is Bitquery? Bitquery is the leading blockchain data platform that provides comprehensive **Ethereum API** solutions for developers. Instead of running your own Ethereum node or building complex indexing infrastructure, you can use our pre-built **Ethereum API** to get the blockchain data you need in seconds. Our **Ethereum API** provides comprehensive access to all Ethereum blockchain data including transactions, token balances, DEX trades, liquidity events, slippage data, pool reserves, blocks, smart contract events, gas fees, mempool data, and NFT information. Available through GraphQL API with real-time streaming via GraphQL subscriptions and Kafka. ## Getting Started New to Bitquery? Here's how to get started: 1. **[Create a free account](https://ide.bitquery.io/)** - Get instant access to our GraphQL IDE 2. **[Generate your API key](/docs/authorization/how-to-generate/)** - Required for API access 3. **[Run your first query](/docs/start/first-query/)** - Learn the basics in 5 minutes 4. **[Explore examples](/docs/start/starter-queries/)** - Copy-paste ready queries **Free trial**: 7 days and 1,000 API points, on real-time data only. No credit card required. Need help crafting a query or subscription? Message us on [support](https://t.me/Bloxy_info). ## Why Choose Bitquery's Ethereum API? Unlike traditional Ethereum JSON-RPC providers, our **Ethereum API** stores, indexes, and enriches every Ethereum transaction, event, contract call, token transfer, balance update, and DEX trade. Our advanced **Ethereum API** allows you to query both historical and real-time Ethereum blockchain data from multiple dimensions without the complexity of running your own infrastructure. ### Key Benefits of Our Ethereum API: - **Complete Data Coverage**: Access to all Ethereum blockchain data since genesis - **Real-time Updates**: Live data streaming via GraphQL subscriptions and Kafka - **Advanced Analytics**: Pre-computed metrics and enriched data - **Developer-Friendly**: GraphQL interface with comprehensive documentation - **High Performance**: Sub-second response times for complex queries - **Cost-Effective**: Free tier with 1,000 API calls per day ## How is it different from raw Ethereum RPC or Ethereum node API? **Ethereum RPC** - Low‑level JSON‑RPC that returns raw node data - No historical indexing, joins, or analytics out of the box - Best for transaction submission and node-level introspection **Bitquery Ethereum API** - Pre‑indexed, enriched datasets exposed via GraphQL - Powerful filtering, joins, aggregations, and subscriptions (Websockets / Webhooks) - Ideal for building applications, analytics, monitoring, dashboards, and reporting without running infra ## What can you build with it? Build powerful applications including: - **Trading Tools**: Trading terminals, bots, and automated strategies - **Portfolio Trackers**: Monitor wallet portfolios and token holders - **Compliance Tools**: Tax reporting, auditing, and accounting products - **DeFi Analytics**: Monitor DEX price/volume, liquidity events, slippage, and pool reserves - **Network Analysis**: Analyze gas usage, fees, and network health - **Real-time Monitoring**: Stream mempool activity and pending transactions - **Business Intelligence**: Compute KPIs over blocks/transactions for dashboards ## Real-time Data & Streaming Get live Ethereum data through our streaming solutions: - **GraphQL Subscriptions**: Convert any query to a live stream by changing `query` to `subscription` - **Kafka Streaming**: High-throughput streaming for enterprise applications See examples and code snippets [here](/docs/subscriptions/websockets/) for GraphQL subscription implementation, and learn about [Kafka streaming](/docs/streams/kafka-streaming-concepts/) for high-volume use cases. ## Ethereum DEX Trades APIs - [Ethereum DEX API](/docs/blockchain/Ethereum/dextrades/dex-api) - [Ethereum Token Trades APIs](/docs/blockchain/Ethereum/dextrades/token-trades-apis) - [Trades of an Ethereum Address API](/docs/blockchain/Ethereum/dextrades/trades-of-an-address-api) - [Uniswap API](/docs/blockchain/Ethereum/dextrades/uniswap-api) - [Pancakeswap API](/docs/blockchain/Ethereum/dextrades/pancakeswap-api) - [DEXScreener (EVM)](/docs/blockchain/Ethereum/dextrades/DEXScreener/evm_dexscreener) Query and subscribe to on‑chain swaps, OHLCV, liquidity events, pools, and per‑wallet trading activity across major EVM DEXes. ## Ethereum Slippage API - [Ethereum Slippage API](/docs/blockchain/Ethereum/dextrades/ethereum-slippage-api) Get slippage and price impact data for Ethereum DEX pools. Understand price impact and liquidity depth for token swaps, calculate maximum input amounts at different slippage tolerances, and monitor real-time slippage data across all DEX pools on Ethereum. ## Ethereum Liquidity API - [Ethereum Liquidity API](/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api) Monitor real-time liquidity changes, track pool reserves, and analyze liquidity depth for token pairs on Ethereum DEX pools. Track when liquidity is added or removed, monitor pool health and depth, and analyze liquidity patterns across different pools. ## Ethereum Token Holders API - [Token Holder API](/docs/blockchain/Ethereum/token-holders/token-holder-api) Track and analyze token holder distributions with comprehensive historical and real-time data. Get top holders by balance, monitor holder count changes, calculate distribution metrics like Gini coefficient and Nakamoto coefficient for decentralization analysis, identify new and active holders, and track first/last activity dates for any ERC-20 token on Ethereum. ## Ethereum Balance API - [Balance API](/docs/blockchain/Ethereum/balances/balance-api) Get real‑time and historical token and native ETH balances for any Ethereum address. Track balance changes over time, calculate portfolio values in USD, and monitor wallet holdings across ERC20, ERC721, and ERC1155 tokens. Perfect for building portfolio trackers, tax tools, and wallet analytics. ## Ethereum Token Transfers API - [ERC20 Token Transfer API](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api) - [Ethereum Token Total Supply API](/docs/blockchain/Ethereum/transfers/total-supply) Track comprehensive token transfer activity across Ethereum with support for all major ERC standards including ERC20, ERC721, ERC1155, and more. Monitor transfers for any Ethereum address or smart contract, analyze inflow and outflow patterns, and discover specific transfers across the entire blockchain for any token. Get enriched data with corresponding USD values, transfer volumes, and detailed transaction context to power portfolio tracking, Tax tools, compliance monitoring, and token analytics applications. ## Ethereum Blocks API - [Ethereum Blocks API](/docs/blockchain/Ethereum/blocks/blocks-api) Access comprehensive Ethereum block data including block headers, timestamps, gas usage, miner/validator information, base fees, and transaction counts. Build time‑series analytics, monitor network health, track block production patterns, analyze fee dynamics, and compute blockchain metrics. Perfect for building block explorers, network monitoring tools, and blockchain analytics dashboards. ## Ethereum Smart Contract Events API - [Ethereum Smart Contract Events API](/docs/blockchain/Ethereum/events/events-api) Access and analyze smart contract events across Ethereum with comprehensive filtering and decoding capabilities. Query contract logs by specific topics, parameters, addresses, and event signatures to track contract interactions, state changes, and protocol activity. Get decoded event data with parameter names and values, filter by block ranges or time periods, and monitor real-time contract events. Essential for building DeFi analytics, protocol monitoring tools, governance trackers, and smart contract auditing systems. ## Ethereum Transaction Fees API - [Ethereum Transaction Fees API](/docs/blockchain/Ethereum/fees/fees-api) Analyze comprehensive transaction fee data across Ethereum including gas usage patterns, base fee dynamics, priority fees, and transaction cost distributions. Track gas consumption by transaction type, monitor EIP-1559 fee market mechanics, calculate average gas prices over time, and analyze fee optimization strategies. Get detailed gas usage statistics, fee predictions, and cost analysis to power gas estimation tools, transaction optimization services, and fee market analytics dashboards. ## Ethereum Mempool API - [Ethereum Mempool API](/docs/blockchain/Ethereum/mempool/mempool-api) Monitor and analyze Ethereum's mempool to track pending transactions before they are included in blocks. Get real-time insights into transaction queues, fee estimations, and network congestion patterns. Track pending transactions by address, value, gas price, and transaction type to build MEV strategies, optimize transaction timing, and provide better fee estimation services. Additionally, simulate mempool transactions to preview potential transfers, trades, and contract interactions before execution, enabling advanced analysis of transaction outcomes and state changes. Essential for building frontrunning protection, transaction monitoring tools, MEV detection systems, and advanced DeFi applications that need to react to pending on-chain activity. ## Ethereum NFT API - [Ethereum NFT API](/docs/blockchain/Ethereum/nft/nft-api) Access comprehensive NFT data across Ethereum including collections, ownership tracking, transfer history, marketplace trades, and metadata. Query NFT collections by contract address, track ownership changes and holder distributions, monitor NFT transfers and sales across major marketplaces like OpenSea and LooksRare, and retrieve detailed token metadata including images, attributes, and rarity information. Get enriched trading data with USD values, floor prices, and volume metrics to power NFT analytics dashboards, portfolio trackers, rarity tools, and marketplace monitoring applications. ## Ethereum Transactions API - [Ethereum Transaction API](/docs/blockchain/Ethereum/transactions/transaction-api) Query detailed Ethereum transaction data including transaction hashes, from/to addresses, values transferred, gas prices, gas limits, gas used, nonce values, and transaction status. Access transaction input data, method signatures, internal transactions, and execution traces. Filter transactions by sender, receiver, value ranges, time periods, or transaction type to analyze payment flows, contract calls, and wallet behavior. Retrieve comprehensive transaction receipts with logs, events, and error details for both successful and failed transactions. Essential for transaction monitoring, forensic analysis, compliance reporting, and building comprehensive blockchain data applications. ## Ethereum Videos Tutorials ### DEX Trades on EVM (Uniswap, Aggregators, Screens) ### Ethereum Price & Balances ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Ethereum Balance API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/balance-api/ Ethereum Balance API: fetch current and historical Ethereum balances with Bitquery GraphQL balance queries. Great for bots, dashboards, and alerts. # Address Balance API The **Balances** API returns current and historical token balances for an address on Ethereum. To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | | -------------- | ------------------------------------------------------------------------------------------- | | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | ## Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. [Run in IDE](https://ide.bitquery.io/Ethereum-Balance-of-an-Address) ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x76147fd7891731e01f35cc18f87ae8e95bf06869" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` **Parameters** - `network: eth`: Ethereum mainnet. - `dataset: combined`: Merges realtime and archive data for the latest balance state. - `Balance.Address`: Wallet address to query. **Returned fields** - `Currency.Symbol`, `Currency.SmartContract`: Token metadata. - `Balance.Amount`, `Balance.AmountInUSD`: Token balance and USD value (use `selectWhere` to filter non-zero amounts). ## Balance on a Specific Date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. [Run in IDE](https://ide.bitquery.io/ethereum-balances-address-by-date) ```graphql { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xf9D48e42d0FEb477a0286B206eDbafefA3577F63" } } Block: { Date: { till: "2026-04-01" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` ## Balance for a Specific Token Add a `Currency.SmartContract` filter. Always use the contract address, not the token name. [Run in IDE](https://ide.bitquery.io/ethereum-balances-specific-token) ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x3416cf6c708da44db2624d63ea0aaef7113527c6" } } Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Balance History by Date Returns balance snapshots over time for an address. Use `dataset: archive`. Order by `Block_Date` descending and use `limit` to paginate. Add `Currency.SmartContract` under `Currency` to filter by a specific token. [Run in IDE](https://ide.bitquery.io/ethereum-balances-history) ```graphql query { EVM(network: eth, dataset: archive) { Balances( where: { Balance: { Address: { is: "0x5646c5b4845e565706ef107f62887145a51a3127" } } Currency: {} } orderBy: { descending: Block_Date } limit: { count: 100 } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } Block { Date } } } } ``` ## Wallet Balance for a Specific Token on a Date Use `dataset: archive`, `Block.Date.till`, `orderBy: { descending: Block_Date }`, and `limit: { count: 1 }` to get the balance as of that date. [Run in IDE](https://ide.bitquery.io/ethereum-wallet-balance-token-at-date) ```graphql query { EVM(network: eth, dataset: archive) { Balances( where: { Block: { Date: { till: "2026-05-05" } } Balance: { Address: { is: "0xA46320Aa0b4877b9a46a07B4F3DB93719bd422dE" } } Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } limit: { count: 1 } orderBy: { descending: Block_Date } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` --- ## Ethereum Blocks API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/blocks/blocks-api/ Ethereum blocks: get the latest blocks on the network with their parameters and result fields explained, using a ready-to-run Bitquery GraphQL query. # Blocks API ## Latest blocks in the Ethereum network This GraphQL query retrieves the latest blocks in real time on the Ethereum network that were mined after March 3rd, 2023. It includes information on the block number, hash, mix digest, date, base fee, coinbase, transaction hash, transaction count, and result (including gas and errors). You can find the query [here](https://ide.bitquery.io/Latest-blocks-in-the-Ethereum-network_1). ```graphql subscription { EVM(network: eth) { Blocks( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Block: { Date: { after: "2023-03-03" } } } ) { Block { Number Hash MixDigest Date BaseFee Coinbase TxHash TxCount Result { Errors Gas } } } } } ``` ### Parameters - `network`: The blockchain network to query (e.g., `eth`, `bsc`, `polygon`). - `limit`: The maximum number of blocks to retrieve (here set to 10). - `orderBy`: The field and direction to sort the results (e.g., `orderBy: {descending: Block_Time}`). - `where`: Conditions to filter blocks by (e.g., `where: {Block: {Date: {after: "2023-03-03"}}}`). ### Results - **Block**: Information about each block, including: - `Number` - `Hash` - `MixDigest` - `Date` - `BaseFee` - `Coinbase` - `TxHash` - `TxCount` - **Result**: Execution details for each block: - `Errors` - `Gas` --- ## Ethereum DEX Trades API: Every DEX, Pair Stats, Traders and Latest Swaps URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/dex-api/ Ethereum DEX data with Bitquery GraphQL: which protocols trade and how much, one family's daily stats, busiest pairs, top traders, latest swaps, no outliers. # Ethereum DEX Trades API: Every DEX, Pair Stats, Traders and Latest Swaps Two cubes hold Ethereum's DEX swaps. `DEXTrades` has one row per swap with both sides, the pool and the protocol, and reaches history on the archive dataset. `DEXTradeByTokens` has one row per swap per token, which is the shape for anything grouped by token, pair, protocol or trader. The [Trading cube](/docs/trading/crypto-trades-api/trades-api) adds a third option for the last month or so: swaps with the trader, USD price, market cap and supply on every row across ten chains, and it is the better start for live feeds. This page uses the two chain cubes to answer the questions people ask about Ethereum DEXs as a whole: which ones trade, how much, who trades on them, what just happened. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. One caution runs through the page: a few swaps in thin pools carry absurd USD values, so every sum here caps the USD of a single trade with `Side: { AmountInUSD: { lt: "10000000" } }`; drop the cap if you want raw totals. ## Which DEXs trade on Ethereum, and how much Group by protocol over the last day. `ProtocolFamily` is the brand and `ProtocolName` the version; Uniswap v3, v4 and v2 lead by trades, with PancakeSwap v3, Balancer, Curve, Fluid and the rest behind them. Saved query [here](https://ide.bitquery.io/dex-markets). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "trades" } limit: { count: 30 } ) { Trade { Dex { ProtocolFamily ProtocolName } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) traders: uniq(of: Transaction_From) } } } ``` The same list, kept live, is on [DEXrabbit](https://dexrabbit.bitquery.io/eth/dex_market). ## One DEX family's day Trades, USD volume, distinct traders, tokens and pools for a protocol family. Saved query [here](https://ide.bitquery.io/dex-info). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Uniswap" } } Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) traders: uniq(of: Transaction_From) tokens: uniq(of: Trade_Currency_SmartContract) pools: uniq(of: Trade_Dex_SmartContract) } } } ``` ## The busiest pairs on a DEX Pairs against WETH, USDC or USDT on Uniswap over the last three hours, ranked by USD volume, with distinct buyers and sellers. Each row is a token and the quote it traded against. Saved query [here](https://ide.bitquery.io/trading-pairs-on-a-specific-dex). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Uniswap" } } Side: { AmountInUSD: { lt: "10000000" } Currency: { SmartContract: { in: [ "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" "0xdac17f958d2ee523a2206206994597c13d831ec7" ] } } } } Block: { Time: { since_relative: { hours_ago: 3 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 50 } ) { Trade { Currency { Symbol SmartContract } Side { Currency { Symbol } } Dex { ProtocolName } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) } } } ``` ## Top traders on a DEX Rank by `Transaction.From`, the account that sent the swap, which works for every protocol version including Uniswap v4, where the pool manager appears as buyer and seller on raw rows. Saved query [here](https://ide.bitquery.io/top-traders-on-a-DEX_1). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Uniswap" } } Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 50 } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) tokens: uniq(of: Trade_Currency_SmartContract) } } } ``` [DEXrabbit](https://dexrabbit.bitquery.io/eth/dex_market/Uniswap#traders) shows this table for each DEX. ## Latest swaps on a DEX Raw rows from `DEXTrades`, newest first; change `query` to `subscription` and drop `limit` and `orderBy` for a live feed. Saved query [here](https://ide.bitquery.io/latest-trades_5). ```graphql { EVM(network: eth) { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Uniswap" } } } } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Block { Time } Trade { Dex { ProtocolName SmartContract } Buy { Currency { Symbol } Amount AmountInUSD } Sell { Currency { Symbol } Amount AmountInUSD } } Transaction { Hash From } } } } ``` ## Where to go next - One venue in depth: [Uniswap](/docs/blockchain/Ethereum/dextrades/uniswap-api), [Uniswap v4](/docs/blockchain/Ethereum/dextrades/uniswap-v4-api), [PancakeSwap](/docs/blockchain/Ethereum/dextrades/pancakeswap-api). - Every pool a token trades in: [trading pairs API](/docs/blockchain/Ethereum/dextrades/get-trading-pairs-of-token). - Live swaps with trader and market cap on each row: [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api). - When to use which cube: [DEXTrades vs DEXTradeByTokens vs Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades). --- ## Ethereum EVM DEXscreener API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/DEXScreener/evm_dexscreener/ Ethereum EVM DEXscreener API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. See examples in the Bitquery IDE. # DEXScreener EVM API Everything you see on the DEXScreener EVM dashboard—live pairs, trades, prices, volumes, makers/buyers/sellers, and more—can be accessed via APIs/Streams with Bitquery. We expose the same on-chain data via GraphQL APIs, real-time WebSocket streams, and enterprise Kafka topics, with Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore) (S3, GCS, Snowflake or BigQuery) for analytics pipelines. Checkout our [DEXScreener Solana API documentation](/docs/blockchain/Solana/DEXScreener/solana_dexscreener/) if you are interested in getting Solana data which DEXScreener shows. :::note DEXScreener EVM APIs include data apis for EVM chains like Ethereum, Binance Smart Chain(BSC), Arbitrum, Base, Matic, Optimism, etc ::: ## Bitquery EVM Data Access Options - **GraphQL APIs**: Query historical and real-time EVM data with flexible filtering and aggregation - **Real-time Streams**: Subscribe to live EVM blockchain events via WebSocket subscriptions - **Data Store exports**: parsed Parquet you download from S3 or Cloudflare R2; custom exports can go to your own bucket or warehouse. See the [Bitquery Data Store](https://bitquery.io/datastore). - **Kafka Streams**: High-throughput data streaming for enterprise applications ## Getting Started with EVM - **[EVM API Examples](/docs/blockchain/Ethereum/)** - Complete collection of EVM API examples - **[EVM DEX Trades](/docs/category/dex-trades/)** - Real-time DEX trading data and analytics - **[EVM Subscriptions](/docs/subscriptions/subscription)** - Learn how to set up real-time data streams - **[IDE for EVM](https://ide.bitquery.io)** - Interactive development environment for testing EVM queries This guide shows how to retrieve the same EVM DEX data that DEXScreener displays—real-time trades, pair stats, volumes, buyers/sellers, and more—using Bitquery APIs, streams, and Kafka. ## Get the Top Trading Pairs The query will fetch you the Top Trading Pairs in desceneding order of the total number of trades took place in them just like how DEXScreener shows in its UI. You can check out the video tutorial [here](https://www.youtube.com/watch?v=qAJ2SPFaO-k) to understand the query better. You can find the query [here](https://ide.bitquery.io/List-of-trading-pairs-in-descending-order-of-trxns-in-last-24-hours) ```graphql query TrendingPairs { EVM(dataset: combined, network: eth) { DEXTradeByTokens( orderBy: {descendingByField: "TradeCount"} where: {Block: {Time: {since: "2024-06-05T08:08:00Z"}}, TransactionStatus: {Success: true}} limit: {count: 10} limitBy: {by: Trade_Dex_Pair_SmartContract, count: 1} ) { TradeCount: count Trade { Dex { SmartContract ProtocolName ProtocolFamily Pair { SmartContract } } Currency { Symbol SmartContract } Side { Currency { Symbol SmartContract } } } } } } ``` ## Get Trade Transactions for a particular pair in realtime The query will subscribe you to real-time trade transactions for a pair, providing a continuous stream of data as new trades are processed and recorded. You can find the query [here](https://ide.bitquery.io/Get-pair-trades-data-just-like-dexcsreener) ```graphql subscription{ EVM(network: eth) { DEXTradeByTokens( orderBy: {ascending: Block_Time} where: {Trade: {Currency: {SmartContract: {is: "0x382ea807A61a418479318Efd96F1EFbC5c1F2C21"}}, Side: {Currency: {SmartContract: {is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}}}}} ) { Block{ Time } Trade { Amount Currency { Symbol } PriceInUSD Dex { ProtocolName SmartContract } Side { Amount AmountInUSD Currency { Symbol } Buyer Seller } Buyer Seller } Transaction { Maker: From Hash Type } } } } ``` ## Get Price of a Token This query will give you the latest Price of a specified token using Trading API. Here is the [saved query link](https://ide.bitquery.io/token-usd-price-using-trading-api) ```graphql query MyQuery { Trading { Pairs( where: {Token: {Id: {is: "bid:eth:0xa12cc123ba206d4031d1c7f6223d1c2ec249f4f3"}}, Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}} limit: {count: 10} orderBy: {descending: Interval_Time_Start} ) { Token { Name Address Id NetworkBid } Price { Average { Mean Estimate ExponentialMoving SimpleMoving WeightedSimpleMoving } Ohlc { Open High Low Close } } } } } ``` ## Get Liquidity of a specific pair by using its Pair Address The below query finds the liquidity of a pool using the pool address `0xc2eaB7d33d3cB97692eCB231A5D0e4A649Cb539d`. With this query we can get balance of the pool tokens. And to get the USD Liquidity you can multiply the balances of both the tokens to their respective USD prices and then sum it up. ```graphql query MyQuery { EVM(dataset: archive, network: eth) { Balances( where: {Balance: {Address: {is: "0xc2eaB7d33d3cB97692eCB231A5D0e4A649Cb539d"}}, Currency: {SmartContract: {in: ["0xaaeE1A9723aaDB7afA2810263653A34bA2C21C7a","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"]}}} orderBy: { descending: Balance_Amount } ) { Currency { Name } Balance { Amount } } } } ``` ## Get the Buys, Sells, Buy Volume, Sell Volume and Makers The query will fetch you the buys, sells, buy volume, sell volume and also the number of makers for a particular token just like how DEXScreener shows in its UI. We are getting these trade metrics for this particular pool address `0x842293fa6ee0642bf61ebf8310e7e546039ba7f4`. You can find the query [here](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-a-eth-pair#) ```graphql query MyQuery($network: evm_network, $token: String,$pairAddress: String , $min5_timestamp: DateTime, $hr1_timestamp: DateTime) { EVM(dataset: realtime, network: $network) { DEXTradeByTokens( where: {TransactionStatus: {Success: true}, Trade: {Currency: {SmartContract: {is: $token}}, Dex: {SmartContract: {is: $pairAddress}}}, Block: {Time: {since: $hr1_timestamp}}} ) { Trade { Currency { Name SmartContract Symbol } startPrice: PriceInUSD(minimum: Block_Time) Price_at_min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after: $min5_timestamp}}} ) current_price: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily SmartContract } Side { Currency { Symbol Name SmartContract } } } makers: count(distinct: Transaction_From) makers_5min: count( distinct: Transaction_From if: {Block: {Time: {after: $min5_timestamp}}} ) buyers: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: sell}}}} ) buyers_5min: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $min5_timestamp}}} ) sellers: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: buy}}}} ) sellers_5min: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $min5_timestamp}}} ) trades: count trades_5min: count(if: {Block: {Time: {after: $min5_timestamp}}}) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {after: $min5_timestamp}}} ) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $min5_timestamp}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $min5_timestamp}}} ) buys: count(if: {Trade: {Side: {Type: {is: sell}}}}) buys_5min: count( if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $min5_timestamp}}} ) sells: count(if: {Trade: {Side: {Type: {is: buy}}}}) sells_5min: count( if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $min5_timestamp}}} ) } } } { "network": "eth", "token": "0x6982508145454Ce325dDbE47a25d4ec3d2311933", "pairAddress": "0xA43fe16908251ee70EF74718545e4FE6C5cCEc9f", "hr1_timestamp": "2024-11-14T03:20:00Z", "min5_timestamp": "2024-11-14T04:15:00Z" } ``` ## Get OHLC Data for a Token Pair This query fetches the Open, High, Low, and Close (OHLC) price data (USD-quoted) for a given token pair across DEXs, using a specified quote token and time interval (in seconds). Specify the base token and quote token contract addresses in the `Token.Id` and `QuoteToken.Id` filters. The `Interval.Time.Duration` field allows you to define the candle interval (e.g., `3600` for 1 hour). The query returns the most recent OHLC data for up to 10 pairs sorted by their interval start time. You can find the query [here](https://ide.bitquery.io/ohlc-of-a-token-pair-1-hour-interval) ```graphql query MyQuery { Trading { Pairs( where: {Token: {Id: {is: "bid:eth:0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}}, QuoteToken: {Id: {is: "bid:eth:0xdac17f958d2ee523a2206206994597c13d831ec7"}}, Interval: {Time: {Duration: {eq: 3600}}}, Price: {IsQuotedInUsd: true}} limit: {count: 10} orderBy: {descending: Interval_Time_Start} ) { Token { Name Address Id NetworkBid } QuoteToken{ Name Address Id NetworkBid } Price { Average { Mean Estimate ExponentialMoving SimpleMoving WeightedSimpleMoving } Ohlc { Open High Low Close } } } } } ``` ## Top Traders of a token This query will fetch you top traders of a token for the selected network. You can test the query [here](https://ide.bitquery.io/top-traders-of-a-token_1). ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}}} ) { Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "eth", "token": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } ``` ## Track newly created pairs on uniswap v3 You can track newly created pairs on uniswap v3 on ethereum mainnet. Open this query on our GraphQL IDE using this [link](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3_9). ```graphql subscription { EVM(network: eth) { Events( orderBy: { descending: Block_Number } limit: { count: 10 } where: { Log: { SmartContract: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } Signature: { Name: { is: "PoolCreated" } } } } ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } Name } } } } ``` ## Video Tutorial on How to Get EVM Chains Trades Data just like DEXScreener from Bitquery API ## Video Tutorial on How to Get USD Price of a pool Token and Liquidity of the Pool just like DEXScreener shows ## Video Tutorial on How to Get Buys, Sells, Buy Volume, Sell Volume, and Makers for EVM Chains just like DEXScreener ## Video Tutorial on How to Get Top Trading Pairs for EVM Chains just like DEXScreener --- ## Ethereum EVM Photon API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/evm-photon-api/ Ethereum EVM Photon API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Built for traders and analytics teams. # Photon EVM API ## Recommended: Trading API queries (real-time + last ~30 days) ### Live trades with USD price, market cap and supply Streams MEV-filtered trades across all 10 chains — add `Network: {is: "Ethereum"}` inside `Pair.Market` to scope to one chain. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains). ```graphql subscription { Trading { Trades { Block { Time } Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol Network } QuoteToken { Symbol } Market { Protocol Network } } } } } ``` ### Most accurate token price with 1-minute OHLC (top market) Returns the token's price from its top-volume market via `Ranking: { Position: { eq: 1 } }` — swap the token address and network for your token. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Token-Price-Top-Market-Rank-1). ```graphql { Trading { Pairs( where: { Token: {Address: {is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"}, Network: {is: "Solana"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } limit: {count: 1} orderBy: {descending: Block_Time} ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean } } Volume { Base Usd } Block { Time } } } } ``` The chain-level queries below remain the right tool for **history older than ~30 days** and per-pool detail. This section will guide you through different APIs which will tell you how to get data like realtime trades, price of a token, buys, sells, sell volume, makers, top holders of a token, liquidity of a pair and many more just like how Photon shows for EVM Chains. ## Get the Top Trading Pairs The query will fetch you the Top Trading Pairs in desceneding order of the total number of trades took place in them just like how Photon shows in its UI. You can check out the video tutorial [here](https://www.youtube.com/watch?v=qAJ2SPFaO-k) to understand the query better. You can find the query [here](https://ide.bitquery.io/List-of-trading-pairs-in-descending-order-of-trxns-in-last-24-hours) ```graphql query TrendingPairs { EVM(dataset: combined, network: eth) { DEXTradeByTokens( orderBy: {descendingByField: "TradeCount"} where: {Block: {Time: {since: "2024-06-05T08:08:00Z"}}, TransactionStatus: {Success: true}} limit: {count: 10} limitBy: {by: Trade_Dex_Pair_SmartContract, count: 1} ) { TradeCount: count Trade { Dex { SmartContract ProtocolName ProtocolFamily Pair { SmartContract } } Currency { Symbol SmartContract } Side { Currency { Symbol SmartContract } } } } } } ``` ## Get Trade Transactions for a particular pair in realtime The query will subscribe you to real-time trade transactions for a pair, providing a continuous stream of data as new trades are processed and recorded. You can find the query [here](https://ide.bitquery.io/Get-pair-trades-data-just-like-dexcsreener) ```graphql subscription{ EVM(network: eth) { DEXTradeByTokens( orderBy: {ascending: Block_Time} where: {Trade: {Currency: {SmartContract: {is: "0x382ea807A61a418479318Efd96F1EFbC5c1F2C21"}}, Side: {Currency: {SmartContract: {is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}}}}} ) { Block{ Time } Trade { Amount Currency { Symbol } PriceInUSD Dex { ProtocolName SmartContract } Side { Amount AmountInUSD Currency { Symbol } Buyer Seller } Buyer Seller } Transaction { Maker: From Hash Type } } } } ``` ## Get Price of a Token This query will give you the latest Price of a specified token using DEXTrades API. Here we have calculated the price of a token in USD and also against the sell currency. Here is the [saved query link](https://ide.bitquery.io/Price-of-a-token-in-realtime) ```graphql query MyQuery { EVM(network: eth, dataset: realtime) { DEXTrades( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Buy: {Currency: {SmartContract: {is: "0xaaeE1A9723aaDB7afA2810263653A34bA2C21C7a"}}}, Sell: {Currency: {SmartContract: {is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}}}, Dex: {Pair: {SmartContract: {is: "0xc2eaB7d33d3cB97692eCB231A5D0e4A649Cb539d"}}}}, TransactionStatus: {Success: true}} ) { Trade { Buy { Currency { Symbol } Price_In_USD: PriceInUSD Price_against_sell_currency: Price } Sell { Currency { Symbol } } } } } } ``` ## Get Liquidity of a specific pair by using its Pair Address The below query finds the liquidity of a pool using the pool address `0xc2eaB7d33d3cB97692eCB231A5D0e4A649Cb539d`. With this query we can get balance of the pool tokens. And to get the USD Liquidity you can multiply the balances of both the tokens to their respective USD prices and then sum it up. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Balances( where: {Balance: {Address: {is: "0xc2eaB7d33d3cB97692eCB231A5D0e4A649Cb539d"}}, Currency: {SmartContract: {in: ["0xaaeE1A9723aaDB7afA2810263653A34bA2C21C7a","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"]}}} orderBy: { descending: Balance_Amount } ) { Currency { Name } Balance { Amount } } } } ``` ## Get the Buys, Sells, Buy Volume, Sell Volume and Makers The query will fetch you the buys, sells, buy volume, sell volume and also the number of makers for a particular token just like how Photon shows in its UI. We are getting these trade metrics for this particular pool address `0x842293fa6ee0642bf61ebf8310e7e546039ba7f4`. You can find the query [here](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-a-eth-pair#) ```graphql query MyQuery($network: evm_network, $token: String,$pairAddress: String , $min5_timestamp: DateTime, $hr1_timestamp: DateTime) { EVM(dataset: realtime, network: $network) { DEXTradeByTokens( where: {TransactionStatus: {Success: true}, Trade: {Currency: {SmartContract: {is: $token}}, Dex: {SmartContract: {is: $pairAddress}}}, Block: {Time: {since: $hr1_timestamp}}} ) { Trade { Currency { Name SmartContract Symbol } startPrice: PriceInUSD(minimum: Block_Time) Price_at_min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after: $min5_timestamp}}} ) current_price: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily SmartContract } Side { Currency { Symbol Name SmartContract } } } makers: count(distinct: Transaction_From) makers_5min: count( distinct: Transaction_From if: {Block: {Time: {after: $min5_timestamp}}} ) buyers: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: sell}}}} ) buyers_5min: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $min5_timestamp}}} ) sellers: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: buy}}}} ) sellers_5min: count( distinct: Transaction_From if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $min5_timestamp}}} ) trades: count trades_5min: count(if: {Block: {Time: {after: $min5_timestamp}}}) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {after: $min5_timestamp}}} ) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $min5_timestamp}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $min5_timestamp}}} ) buys: count(if: {Trade: {Side: {Type: {is: sell}}}}) buys_5min: count( if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $min5_timestamp}}} ) sells: count(if: {Trade: {Side: {Type: {is: buy}}}}) sells_5min: count( if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $min5_timestamp}}} ) } } } { "network": "eth", "token": "0x6982508145454Ce325dDbE47a25d4ec3d2311933", "pairAddress": "0xA43fe16908251ee70EF74718545e4FE6C5cCEc9f", "hr1_timestamp": "2024-11-14T03:20:00Z", "min5_timestamp": "2024-11-14T04:15:00Z" } ``` ## Get OHLC of a token pair This query retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on DEXes over a defined time period and interval. You can use the `quoteCurrency` to input the contract address of the currency used for quoting the token prices. You can find the query [here](https://ide.bitquery.io/WETH-USDT-OHLC-on-Ethereum_1) ```graphql { EVM(network: eth, dataset: archive) { DEXTradeByTokens( orderBy: {descendingByField: "Block_testfield"} where: {Trade: {Currency: {SmartContract: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}}, Side: {Currency: {SmartContract: {is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}}, Type: {is: buy}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { testfield: Time(interval: {in: hours, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } count } } } ``` ## Top Traders of a token This query will fetch you top traders of a token for the selected network. You can test the query [here](https://ide.bitquery.io/top-traders-of-a-token_7). ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}}} ) { Trade { Buyer Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "eth", "token": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } ``` ## Track newly created pairs on uniswap v3 You can track newly created pairs on uniswap v3 on ethereum mainnet. Open this query on our GraphQL IDE using this [link](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3_9). ```graphql subscription { EVM(network: eth) { Events( orderBy: { descending: Block_Number } limit: { count: 10 } where: { Log: { SmartContract: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } Signature: { Name: { is: "PoolCreated" } } } } ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } Name } } } } ``` --- ## Ethereum Events API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/events/events-api/ Ethereum smart contract events: mempool and recent events with logs, AAVE V3, staking rewards, Uniswap liquidity removals, swaps, Chef Fun and token approvals given to a spender contract. # Events API > **Before you start**: Not sure when to use Events vs Transfers vs Calls vs DexTrades? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. The Event API gives you access real-time blockchain event data. Events represent changes to the state of a blockchain, such as transactions, token transfers, or contract creations. You can find the **Ethers Library equivalents** for these queries at **[Bitquery Ethers Library Section](/docs/blockchain/Ethereum/ethers-library/debug_traceCall/)**. You can find the **NFT Events Examples** at **[Bitquery NFT API Section](/docs/blockchain/Ethereum/nft/nft-blur-marketplace-api/)**. ## Is it possible to subscribe to smart contract events using Bitquery streams? {#is-it-possible-to-subscribe-to-smart-contract-events-using-bitquery-streams} **Yes.** On **EVM** chains (Ethereum, BSC, Base, and other `EVM(network: …)` networks in the API), Bitquery exposes decoded **contract logs** under the **`Events`** field. Use a GraphQL **`subscription`** (not `query`) with the same `where` filters you would use for historical pulls—typically **`Log`** (signature name, smart contract address, topics) and **`Transaction`**—and deliver it over a **WebSocket** to [`wss://streaming.bitquery.io/graphql`](/docs/subscriptions/websockets/) as in [WebSocket access](/docs/subscriptions/websockets/) and [subscription basics](/docs/subscriptions/subscription/). Filter reference: [GraphQL filters](/docs/graphql/filters/). For **high-throughput or replay**, event-style data is also available via **Kafka** topics; see [streaming overview](/docs/streams/). **Solana** does not use this EVM `Events` shape; for live program activity use **`Solana`** subscriptions (e.g. instructions) as in [Solana instructions](/docs/blockchain/Solana/solana-instructions/). Example: stream logs from a specific contract (here USDT on Ethereum) as they are indexed: ```graphql subscription SmartContractEvents { EVM(network: eth) { Events( where: {Log: {SmartContract: {is: "0xdAC17F958D2ee523a2206206994597C13D831ec7"}}} ) { Log { Signature { Name } SmartContract } Transaction { Hash } } } } ``` More patterns below: **mempool** logs (pending), **recent** events with `query`, and other **subscription** examples on this page. ## Mempool Events on Ethereum This query listens to real-time mempool events on the Ethereum (ETH) blockchain. The query is designed to capture details of transactions, logs, events, and arguments from the Ethereum Virtual Machine (EVM) before they are confirmed in a block. You can run it [here](https://ide.bitquery.io/Mempool-event-stream) ```graphql subscription { EVM(network: eth, mempool: true) { Events { Call { CallPath InternalCalls } Topics { Hash } Receipt { CumulativeGasUsed } Transaction { From To Type } Log { Signature { Name } SmartContract } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## Recent Events with Logs on Ethereum This query is used to retrieve recent events' data on the ETH network. You can find the query [here](https://ide.bitquery.io/Recents-Events-and-Logs-on-Ethereum_2). The query returns details on each event include transaction details like hash, sender, call trace and event logs. ```graphql query MyQuery { EVM(dataset: realtime, network: eth) { Events(limit: {count: 10}, orderBy: {descending: Block_Time}) { Block { Number } Call { CallPath InternalCalls } Topics { Hash } Receipt { CumulativeGasUsed } Transaction { From To Type } Log { SmartContract Signature { Name } } Arguments { Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } Name } } } } ``` ## Daily Stats on Calls This query retrieves the date and number of unique event calls for the date. You can find the query [here](https://ide.bitquery.io/Daily-Unique-Call-Count) ```graphql query MyQuery { EVM(dataset: archive, network: bsc) { Events( where: { Block: { Date: { after: "2023-01-10" } } } orderBy: { descendingByField: "count(distinct: Call_Signature_Signature)" } ) { Block { Date } count_unique_calls: count(distinct: Call_Signature_Signature) } } } ``` **Parameters** - `dataset`: This parameter specifies the dataset to use. In this case, the "combined" dataset is being used. - `network`: This parameter specifies the network to query. In this case, the Binance Smart Chain (BSC) network is being queried. - `where`: Filters the results to only include blocks that occurred after a specific date. - `orderBy`: Orders the results in descending order based on the number of unique event call signatures in each block. - `descendingByField`: Specifies that we want to sort the results in descending order. **Returned Data** - `Date`: Returns the date - `count_unique_calls`: Returns the number of unique event calls ### Track all AAVE V3 Events The query below shows latest 10 events emitted by the AAVE V3 contract. The `Log` field in the results will contain information about the event, including its signature, smart contract address, and transaction hash. The `Arguments` field will contain the values of any arguments that were passed to the event. You can find the query [here](https://ide.bitquery.io/All-aave-v3-events-latest) ```graphql { EVM(dataset: realtime, network: eth) { Events( orderBy: {descending: Block_Time} limit: {count: 10} where: {Transaction: {To: {is: "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"}}} ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash From } Block { Date Number Hash Time } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` ## Staking and Rewards To get Staking-related information, we will be using the "Staked" signature to filter the events and logs. Each event contains information about the block number, transaction details (sender, receiver, hash, and type), log signature, smart contract involved, and specific arguments related to the staking actions, such as user addresses and staked amounts. You can find the query [here](https://ide.bitquery.io/Copy-of-Latest-Token-Stake-Events) ```graphql query MyQuery { EVM(dataset: realtime, network: eth) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "Staked"}}}} ) { Block { Number } Transaction { From To Type Hash } Log { Signature { Name SignatureHash Signature } SmartContract } } } } ``` ## Subscribe to the Same Event Across Multiple Contracts In the below query we listen for a specific event (Approval) across multiple smart contracts on the Ethereum (ETH) network. Run the query [here](https://ide.bitquery.io/Subscribe-to-the-Same-Event-Across-Multiple-Contracts) ```graphql subscription { EVM(network: eth) { Events( where: {Log: {Signature: {Name: {is: "Approval"}}, SmartContract: {in: ["0x943af17c37207c9d7a27d12cb5055542a0b7afa8","0x3b62021a8b9fc78106f964853dc375933ab71a06"]}}} ) { Block { Time Number } Transaction { Hash From To ValueInUSD Value Type } Log { Signature { Name } SmartContract } } } } ``` ## Latest Liquidity Removal on Uniswap This query retrieves the most recent liquidity removal events (Burn events) on Uniswap. It includes details about the transaction, block, log, and arguments. You can run the query [here](https://ide.bitquery.io/uniswap-v2-liquidity-removed) ```graphql { EVM(network: eth, dataset: combined) { Events( limit: {count: 100} where: {Transaction: {To: {is: "0x7a250d5630b4cf539739df2c5dacb4c659f2488d"}}, Log: {Signature: {Name: {in: ["Burn"]}}}} ) { Transaction { Hash From To } Block { Number } Log { Signature { Name } SmartContract } Transaction { From To Type } LogHeader { Address Index } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } Name } } } } ``` ## Subscribe to All Swap Events This subscription provides information on the latest real-time swap events on Ethereum. You can run it [here](https://ide.bitquery.io/all-swap-events) ```graphql subscription { EVM(network: eth) { Events(where: {Log: {Signature: {Name: {in: ["swap", "Swap"]}}}}) { Log { SmartContract Signature { Name } } Transaction { From To ValueInUSD Value Type } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } Name } } } } ``` ## Get All Chef Fun Swaps Chefdotfun, similar to platforms like Pumpfun and Sunpump, is a token creation platform on the Ethereum network. This query retrieves the latest Chefdotfun swap transactions by filtering event logs related to the smart contract. You can run the query [here](https://ide.bitquery.io/Latest-chefdog-swaps) ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Events( where: {Log: {SmartContract: {is: "0x4ba1970f8d2dda96ebfbc466943fb0dfaab18c75"}, Signature: {Name: {in: ["swap","Swap"]}}}} orderBy: {descending: Block_Time} limit: {count: 100} ) { Log { SmartContract Signature { Name } } Transaction { From To ValueInUSD Value Type } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } Name } } } } ``` ## Find Who Approved a Spender Contract ERC-20 tokens emit an `Approval(owner, spender, value)` event each time a wallet lets another address spend its tokens. To see which wallets approved a given contract as a spender, filter `Approval` events by the `spender` argument. The query below returns the latest approvals given to Uniswap Permit2 (`0x000000000022d473030f116ddee9f6b43ac78ba3`) in the last 24 hours. Replace the address with any router, protocol or contract you want to check. In the results, `Log.SmartContract` is the token, `owner` is the wallet that gave the approval and `value` is the allowance set by that event. Some tokens also emit `Approval` when the spender uses part of the allowance, so the latest event for an owner and token shows the allowance left. A `value` of `0` means no allowance is left. Widen the `since_relative` window, or remove it, to look further back. [Run this query in the IDE](https://ide.bitquery.io/ethereum-token-approvals-to-a-spender-contract) ```graphql { EVM(network: eth) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Block: {Time: {since_relative: {hours_ago: 24}}}, Log: {Signature: {Name: {is: "Approval"}}}, Arguments: {includes: {Name: {is: "spender"}, Value: {Address: {is: "0x000000000022d473030f116ddee9f6b43ac78ba3"}}}}} ) { Block { Time Number } Transaction { Hash From } Log { SmartContract Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## Ethereum Fees API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/fees/fees-api/ Ethereum Fees API: analyze Ethereum transaction fees and costs with Bitquery GraphQL queries and streams. See examples in the Bitquery IDE. # Ethereum Fees API ## Get Trades with Transaction fees Get a list of successful DEX trades on EVM along with the transaction fee details for each trade. `SenderFee` and `SenderFeeInUSD` fields in query are the transaction fees in ETH and transaction fees in USD respectively. You can test the query [here](https://ide.bitquery.io/trades-with-the-transaction-fees_1#).
Click to expand GraphQL query ```graphql query MyQuery { EVM { DEXTradeByTokens( where: {TransactionStatus: {Success: true}} ) { Block { Time } Trade { AmountInUSD Amount Buyer Seller Currency { SmartContract Name Symbol } Side { Currency { Symbol SmartContract Name } Seller Buyer AmountInUSD Amount } } Transaction { From To Hash } joinTransactions(join: inner, Transaction_Hash: Transaction_Hash) { Fee { SenderFee SenderFeeInUSD } } } } } ````
## Get Transfers by an address and Transaction fees paid for the transfer Track wallet token transfers and get the fees paid for each by the address. `SenderFee` and `SenderFeeInUSD` fields in query are the transaction fees in ETH and transaction fees in USD respectively. You can test the query [here](https://ide.bitquery.io/binancehot-wallet-transfers-with-transaction-fees).
Click to expand GraphQL query ```graphql query MyQuery { EVM { Transfers( where: {Transaction: {From: {is: "0xF977814e90dA44bFA03b6295A0616a897441aceC"}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Block { Time } Fee { SenderFee SenderFeeInUSD } Transfer { Currency { Name SmartContract Symbol } Amount AmountInUSD } } } } ```
## Total transaction fees paid by an account Get the total fees (in Eth and USD) paid by a specific EVM account across all transfers. `SenderFee` and `SenderFeeInUSD` fields in query are the transaction fees in ETH and transaction fees in USD respectively. You can test the query [here](https://ide.bitquery.io/total-txn-fees-paid-by-binance-hot-wallet-in-a-day).
Click to expand GraphQL query ```graphql query MyQuery { EVM(dataset: combined, aggregates: yes) { Transfers( where: {Transaction: {From: {is: "0xF977814e90dA44bFA03b6295A0616a897441aceC"}}, TransactionStatus: {Success: true}, Block: {Time: {till: "2025-05-07T00:00:00Z", since: "2025-05-06T00:00:00Z"}}} ){ Total_Transaction_Fees_paid_in_ETH:sum(of:Fee_SenderFee) Total_Transaction_Fees_paid_in_USD:sum(of:Fee_SenderFeeInUSD) } } } ```
## Transaction fees paid by an account for each currency transfers Get total fees paid by a EVM account for transferring each type of token. `SenderFee` and `SenderFeeInUSD` fields in query are the transaction fees in ETH and transaction fees in USD respectively. You can test the query [here](https://ide.bitquery.io/Transaction-fees-paid-by-Binance-Hot-Wallet-aggregated-by-currency).
Click to expand GraphQL query ```graphql query MyQuery { EVM(dataset: combined, aggregates: yes) { Transfers( where: {Transaction: {From: {is: "0xF977814e90dA44bFA03b6295A0616a897441aceC"}}, TransactionStatus: {Success: true}, Block: {Time: {till: "2025-05-07T00:00:00Z", since: "2025-05-06T00:00:00Z"}}} orderBy: {descendingByField: "Total_Transaction_Fees_paid_in_USD"} ) { Transfer { Currency { Name Symbol SmartContract } } Total_Transaction_Fees_paid_in_ETH: sum(of: Fee_SenderFee) Total_Transaction_Fees_paid_in_USD: sum(of: Fee_SenderFeeInUSD) } } } ```
## Video Tutorial | How to get Total Fees paid by a Account on EVM Network ``` --- ## Ethereum Fluid DEX API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/fluid-dex-api/ Ethereum Fluid DEX API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Run it in the IDE, then ship in your app. # Fluid DEX API :::tip Need real-time Fluid DEX data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Fluid DEX swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Fluid DEX data older than ~30 days**, raw per-swap detail, or call / event context. ::: Fluid DEX is a decentralized exchange protocol built on Ethereum and other EVM chains. Bitquery's APIs support tracking Fluid DEX vault positions, events, and contract interactions in real-time and across historical data. You can get data on other EVM chains like Base, Arbitrum, and Polygon by changing the contract address based on the [Fluid contracts deployments](https://github.com/Instadapp/fluid-contracts-public/blob/main/deployments/deployments.md) and the `network` parameter ## New Position Mint on Fluid Vault Factory Track new position mints on the Fluid DEX Vault Factory contract. This query monitors the `NewPositionMinted` event which is emitted when a new position is created on the vault factory. [Run Query](https://ide.bitquery.io/new-position-mints-on-Fluid-DEX-Vault) | [Run Stream](https://ide.bitquery.io/stream-new-position-mints-on-Fluid-DEX-Vault) ```graphql { EVM(dataset: realtime, network: eth) { Events( limit: {count: 20} where: { Log: { Signature: {Name: {is: "NewPositionMinted"}} SmartContract: {is: "0x324c5Dc1fC42c7a4D43d92df1eBA58a54d13Bf2d"} } } ) { Block { Time Number Hash } Receipt { ContractAddress } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## Recent Transfers to a Fluid Token Vault Track all recent token transfers to a specific Fluid DEX vault. This query is useful for monitoring deposits and liquidity flows into a particular vault. [Run Query](https://ide.bitquery.io/Recent-Transfers-to-cbBTC-Fluid-Vault) **Example Vault Address:** `0x5dae640956711E11016C1b27CF9968Ba5B4a69CC` (cbBTC Fluid Vault) ```graphql query RecentTransfers { EVM(dataset: realtime, network: eth) { Transfers( where: { Transaction: {To: {is: "0x5dae640956711E11016C1b27CF9968Ba5B4a69CC"}} } orderBy: {descending: Block_Number} limit: {count: 100} ) { Block { Time Number } Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Name SmartContract } } } } } ``` ## All Events on Fluid Vault Factory Contract Get a comprehensive list of all events emitted by the Fluid DEX Vault Factory contract. This query aggregates event counts by signature to identify which events are most frequently emitted, helping you understand the contract's activity patterns. [Run Query](https://ide.bitquery.io/all-events-on-fluid-DEX-VaultFactory) **VaultFactory Address:** `0x324c5Dc1fC42c7a4D43d92df1eBA58a54d13Bf2d` ```graphql { EVM(dataset: archive, network: eth) { Events( limit: {count: 20} where: { Log: { SmartContract: {is: "0x324c5Dc1fC42c7a4D43d92df1eBA58a54d13Bf2d"} } } orderBy: {descendingByField: "txc"} ) { txc: count Log { SmartContract Signature { Name Signature } } } } } ``` --- ## Ethereum Gas Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-gas-balance-tracker/ Ethereum Gas Balance Tracker: stream Ethereum balance changes with reason codes using Bitquery GraphQL subscriptions. See examples in the Bitquery IDE. # Ethereum Gas Balance Tracker The Ethereum Gas Balance Tracker API provides real-time balance updates related to Gas Fee activities, including transaction fee rewards, monitoring gas fee spent, and other Gas-related balance changes. ## Get Top Gas Fee Collectors [This](https://ide.bitquery.io/top-gas-fee-collectors_1) API endpoint returns the list of top gas fee collectors. We are tracking the Gas Collection Event causing Balance Update by appliying condition on `BalanceChangeReasonCode` to be equal to `5`. ```graphql query TopGasGainers { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 5}}} orderBy: {descendingByField: "gain", descending: Block_Time} limitBy: {by: TokenBalance_Address, count: 1} ) { TokenBalance { Address Currency { Name Symbol SmartContract } PreBalance PostBalance } gain: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## Track the Balance after Latest Gas Fee Burn [This](https://ide.bitquery.io/Latest-balance-and-gas-fee-paid-for-an-address_1#) API endpoint returns the Balance and the Gas Fee burnt for a particular address after the latest Gas Fee Burn Event. We are tracking the Gas Burn Event causing Balance Update by appliying condition on `BalanceChangeReasonCode` to be equal to `6`. ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 6}, Address: {is: "0x18bb896994283bd9c16aa2072777a97c12f1b290"}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD" ) } } } ``` ## Track the Balance after Latest Gas Fee Burn for Multiple Addresses [This](https://ide.bitquery.io/Latest-balance-and-gas-fee-paid-for-multiple-addresses) API endpoint returns the Balance and the Gas Fee burnt for a list of addresses after the latest Gas Fee Burn Event. ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 6}, Address: {in: ["0x18bb896994283bd9c16aa2072777a97c12f1b290", "0xdadb0d80178819f2319190d340ce9a924f783711"]}}} limitBy: {by: TokenBalance_Address count: 1} orderBy: {descending: Block_Time} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD" ) } } } ``` ## Monitoring Balance after Latest Gas Fee Burn [This](https://ide.bitquery.io/Monitor-balance-and-gas-fee-paid-for-an-address-using-stream_1) stream returns the Balance and the Gas Fee burnt for a particular address in real time. ```graphql subscription { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 6}, Address: {is: "0x18bb896994283bd9c16aa2072777a97c12f1b290"}}} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD" ) } } } ``` ## Monitoring Balance after Latest Gas Fee Burn for Multiple Addresses [This](https://ide.bitquery.io/Monitor-balance-and-gas-fee-paid-for-multiple-addresses--stream_1) stream returns the Balance and the Gas Fee burnt for a list of addresses in real time. ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 6}, Address: {in: ["0x18bb896994283bd9c16aa2072777a97c12f1b290", "0xdadb0d80178819f2319190d340ce9a924f783711"]}}} limitBy: {by: TokenBalance_Address count: 1} orderBy: {descending: Block_Time} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD" ) } } } ``` ## Track the Balance after Latest Gas Return [This](https://ide.bitquery.io/Latest-balance-after-unused-gas-fee-returned--for-an-address#) API endpoint returns the Balance and the Gas Returned for a particular address after the latest Gas Return Event. We are tracking the Gas Return Event causing Balance Update by appliying condition on `BalanceChangeReasonCode` to be equal to `7`. ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 7}, Address: {is: "0x18bb896994283bd9c16aa2072777a97c12f1b290"}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ``` ## Track the Balance after Latest Gas Return for Multiple Addresses [This](https://ide.bitquery.io/Latest-balance-after-unused-gas-fee-returned--for-multiple-addresses#) API endpoint returns the Balance and the Gas Returned for a list of addresses after the latest Gas Return Event. ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 7}, Address: {in: ["0x18bb896994283bd9c16aa2072777a97c12f1b290", "0x4838b106fce9647bdf1e7877bf73ce8b0bad5f97"]}}} limitBy: {by:TokenBalance_Address count: 1} orderBy: {descending: Block_Time} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ``` ## Monitoring Balance after Latest Gas Return [This](https://ide.bitquery.io/Monitor-balance-after-unused-gas-fee-returned--for-an-address--stream#) stream returns the Balance and the Gas Returned for a particular address in real time. ```graphql subscription { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 7}, Address: {is: "0x18bb896994283bd9c16aa2072777a97c12f1b290"}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ``` ## Monitoring Balance after Latest Gas Return for Multiple Addresses [This](https://ide.bitquery.io/Monitor-balance-after-unused-gas-fee-returned--for-multiple-addresses--stream#) stream returns the Balance and the Gas Returned for a list of addresses in real time. ```graphql subscription { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 7}, Address: {in: ["0x18bb896994283bd9c16aa2072777a97c12f1b290", "0x4838b106fce9647bdf1e7877bf73ce8b0bad5f97"]}}} ) { Block{ Time } TokenBalance { PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } fee_paid: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) fee_paid_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ``` --- ## Ethereum Latest Trading Pairs API: Newly Created DEX Pairs URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/latest-trading-pairs-api/ Ethereum latest trading pairs API: get newly created DEX pairs with Bitquery GraphQL queries and live streams. Keep queries fast with indexed filters. # Ethereum Latest Trading Pairs API: Newly Created DEX Pairs ## Latest Trading Pairs for a DEX Let's see how we can get latest trading pairs created on DEXs. In this example we use Smart Contract Events to track PoolCreated event for [Uniswap v3 factory contract](https://explorer.bitquery.io/ethereum/smart_contract/0x1f98431c8ad98523631ae4a59f267346ea31f984/events). Because whenever a new pool gets created Uniswap v3 factory contract emits a PoolCreated event with the details of the pool. ```graphql { EVM(dataset: realtime, network: eth) { Events( orderBy: {descending: Block_Number} limit: {count: 10} where: {Log: {SmartContract: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}, Signature: {Name: {is: "PoolCreated"}}}} ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Name Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` Open this query on our GraphQL IDE using this [link](https://ide.bitquery.io/uniswap-v3-pairs). ## Subscribe to the Latest Pairs for Uniswap V3 You can use our GraphQL Subscription (Webhook) to subscribe to these events in case you don't want to call our APIs periodically. ```graphql subscription { EVM { Events( where: {Log: {SmartContract: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}, Signature: {Name: {is: "PoolCreated"}}}} ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Name Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` Open this query on our GraphQL IDE using this [link](https://ide.bitquery.io/uniswap-v3-pairs-websocket) --- ## Ethereum Liquidity API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api/ Ethereum Liquidity API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Great for bots, dashboards, and alerts. # Ethereum Liquidity API In this section we will see how to get Ethereum DEX pool liquidity information using Bitquery API. The liquidity API helps you monitor real-time liquidity changes, track pool reserves, and analyze liquidity depth for token pairs on Ethereum DEX pools. > **Note:** This API also works for other EVM chains such as Base, BSC, and Arbitrum—just change the network parameters in your request. ## Understanding Liquidity and Pool Reserves Liquidity in DEX pools refers to the amount of tokens available for trading. Pool reserves (the balance of each token in the pool) determine the pool's ability to handle trades without significant price impact. Monitoring liquidity changes helps you: - Track when liquidity is added or removed from pools - Monitor pool health and depth - Identify liquidity events that may affect trading - Analyze liquidity patterns across different pools The DEXPoolEvents API provides real-time information about: - Current liquidity reserves for both tokens in the pool - Spot prices for both swap directions - Pool and token pair information - Transaction details for liquidity-changing events For a comprehensive explanation of how DEX pools work, liquidity calculations, and when pool events are emitted, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/). ## Realtime Liquidity Stream This subscription query returns real-time liquidity data for all DEX pools on Ethereum. You can monitor liquidity changes, pool reserves, and spot prices as trades and liquidity modifications occur across all pools. You can find the query [here](https://ide.bitquery.io/Realtime-Liquidity-Stream_4#) ```graphql subscription MyQuery { EVM(network: eth) { DEXPoolEvents { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` ## Latest Liquidity Changes of a Specific Pool This query retrieves the latest liquidity events for a specific DEX pool on Ethereum. Use this to check current pool reserves, spot prices, and recent liquidity changes for a particular token pair. You can find the query [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_5#) ```graphql query MyQuery { EVM(network: eth) { DEXPoolEvents( limit: { count: 10 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { SmartContract: { is: "0x9c087eb773291e50cf6c6a90ef0f4500e349b903" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` ## Get Liquidity of All Pools for a Token This query returns current liquidity across all pools where a token appears as either `CurrencyA` or `CurrencyB`. It is useful when you want a token-wide liquidity view across multiple pools and DEXes. You can find the query [here](https://ide.bitquery.io/liquidiy-of-all-token-pools_1) ```graphql query MyQuery($token: String) { EVM { DEXPoolEvents( where: { TransactionStatus: { Success: true } any: [ { PoolEvent: { Pool: { CurrencyA: { SmartContract: { is: $token } } } } } { PoolEvent: { Pool: { CurrencyB: { SmartContract: { is: $token } } } } } ] } ) { PoolEvent { Dex { SmartContract } Liquidity { AmountCurrencyA(maximum: Block_Time) AmountCurrencyAInUSD(maximum: Block_Time) AmountCurrencyB(maximum: Block_Time) AmountCurrencyBInUSD(maximum: Block_Time) } Pool { CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } } } } ``` ```json { "token": "0x8eD97a637A790Be1feff5e888d43629dc05408F6" } ``` ## Realtime Liquidity Stream of a Specific Pool This subscription query monitors real-time liquidity changes for a specific DEX pool on Ethereum. Use this to track liquidity events, pool reserves, and spot prices for a particular pool as they occur. You can find the query [here](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_4#) ```graphql subscription MyQuery { EVM(network: eth) { DEXPoolEvents( where: { PoolEvent: { Pool: { SmartContract: { is: "0x9c087eb773291e50cf6c6a90ef0f4500e349b903" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` ## Latest Liquidity Changes of Pools in a Specific DEX Protocol - Uniswap V4 This subscription query monitors real-time liquidity changes for all pools in a specific DEX protocol on Ethereum. Here we have taken example of Uniswap V4. You can find the query [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4_6#) ```graphql subscription MyQuery { EVM(network: ethereum) { DEXPoolEvents( where: { PoolEvent: { Dex: { ProtocolName: { is: "uniswap_v4" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` > **Important Note:** In Uniswap V4, all pools' liquidity is stored in the PoolManager contract, so the DEX smart contract address will be the same for all pairs. Use `PoolId` to differentiate between different pools. The `PoolId` field uniquely identifies each pool within the PoolManager. ## Top Liquidity Pools on Ethereum (USDC, WBTC, WETH, USDT) The following GraphQL query retrieves the top 10 most recent DEX pool events on Ethereum where either side of the pool is one of the major tokens: USDC, WBTC, WETH, or USDT. Pools are filtered so that CurrencyA or CurrencyB is in the following contracts: - USDC: `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` - WBTC: `0x2260fac5e5542a773aa44fbcfedf7c193bc2c599` - WETH: `0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` - USDT: `0xdac17f958d2ee523a2206206994597c13d831ec7` Pools are sorted by latest block time and then by the largest dollar value of liquidity for both A and B sides. Only events from the last 2 minutes are retrieved. You can run and modify this query in the [IDE example](https://ide.bitquery.io/top-liquidity-pools-on-Ethereum). ```graphql query MyQuery { EVM(network: eth) { DEXPoolEvents( limit: { count: 10 } orderBy: [ { descending: Block_Time } { descending: PoolEvent_Liquidity_AmountCurrencyAInUSD } { descending: PoolEvent_Liquidity_AmountCurrencyBInUSD } ] where: { any: [ { PoolEvent: { Pool: { CurrencyA: { SmartContract: { in: [ "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" "0xdac17f958d2ee523a2206206994597c13d831ec7" ] } } } } } { PoolEvent: { Pool: { CurrencyB: { SmartContract: { in: [ "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" "0xdac17f958d2ee523a2206206994597c13d831ec7" ] } } } } } ] Block: { Time: { since_relative: { minutes_ago: 2 } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` ## Top Liquidity Pools of a token on Ethereum The following API query retrieves the top liquidity pools where shiba inu (`0x95ad61b0a150d79219dcf64e1e6cc01f0b64c4ce`) is either token A or token B in the pool on the Base chain. This allows you to identify which pools have the most liquidity for cbBTC, filtered to exclude certain pools if necessary. This query separates results by whether shiba inu is listed as the first token (`CurrencyA`) or the second token (`CurrencyB`) in the DEX pool, returning the 10 pools with the highest liquidity for each category. Exclusions (e.g., pools you want omitted from the results) are specified in the `SmartContract: {notIn: [...]}` filter. To test run, visit the [IDE example](https://ide.bitquery.io/top-liquidity-pools-of-atoken-on-ethereum) or modify the pool filters to target another token as needed. ```graphql query MyQuery { EVM(network: eth) { TokenIsCurrencyA: DEXPoolEvents( limit: { count: 10 } orderBy: { descendingByField: "PoolEvent_Liquidity_AmountCurrencyA_maximum" } where: { PoolEvent: { Pool: { CurrencyA: { SmartContract: { is: "0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE" } } SmartContract: { notIn: ["0x000000000004444c5dc75cB358380D2e3dE08A90"] } } } } ) { PoolEvent { Liquidity { AmountCurrencyA(maximum: Block_Time) AmountCurrencyB(maximum: Block_Time) } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } } TokenIsCurrencyB: DEXPoolEvents( limit: { count: 10 } orderBy: { descendingByField: "PoolEvent_Liquidity_AmountCurrencyB_maximum" } where: { PoolEvent: { Pool: { CurrencyB: { SmartContract: { is: "0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE" } } SmartContract: { notIn: ["0x000000000004444c5dc75cB358380D2e3dE08A90"] } } } } ) { PoolEvent { Liquidity { AmountCurrencyA(maximum: Block_Time) AmountCurrencyB(maximum: Block_Time) } Pool { PoolId SmartContract CurrencyA { Name Symbol SmartContract } CurrencyB { Name Symbol SmartContract } } } } } } ``` ## Realtime Liquidity Data via Kafka Streams Liquidity data can also be obtained via Kafka streams for lower latency and better reliability. The Kafka topic for Ethereum DEX pools is: **`eth.dexpools.proto`** Kafka streams provide the same liquidity data as GraphQL subscriptions but with several advantages: - Lower latency due to shorter data pipeline - Better reliability with persistent connections - Ability to read from latest offset without gaps - Better scalability with multiple consumers For detailed information on how to connect to Kafka streams, subscribe to topics, and parse messages, refer to the [Kafka Streaming Concepts documentation](/docs/streams/kafka-streaming-concepts/). > **Note:** IDE credentials will not work with Kafka Streams. You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## Understanding the Response The `DEXPoolEvents` API response contains the following information: - **`PoolEvent`**: Pool event information - **`Liquidity`**: Current pool reserves - `AmountCurrencyA`: Current balance of CurrencyA in the pool (in raw units) - `AmountCurrencyB`: Current balance of CurrencyB in the pool (in raw units) - **`AtoBPrice`**: Current spot price for swapping CurrencyA to CurrencyB - **`BtoAPrice`**: Current spot price for swapping CurrencyB to CurrencyA - **`Pool`**: Pool information - `SmartContract`: Pool contract address - `PoolId`: Unique pool identifier - `CurrencyA`: First token in the pair (name, symbol, smart contract address) - `CurrencyB`: Second token in the pair (name, symbol, smart contract address) - **`Dex`**: DEX protocol information - `SmartContract`: DEX router/factory contract address - `ProtocolName`: Protocol name (e.g., Uniswap V2, Uniswap V3, Uniswap V4) - **`Block`**: Block information when the liquidity event occurred - `Time`: Timestamp of the block - `Number`: Block number - **`Transaction`**: Transaction information - `Hash`: Transaction hash - `Gas`: Gas used for the transaction For more details on when new pool events are emitted and how liquidity is calculated, see the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#when-is-a-new-dexpool-record-emitted-in-the-apis--streams). ## Use Cases ### Real-Time Liquidity Monitoring Use the liquidity API to monitor pool reserves in real-time: - Track when large amounts of liquidity are added or removed - Monitor pool health and detect potential liquidity issues - Alert on significant liquidity changes that may affect trading ### Liquidity Depth Analysis Analyze which pools have sufficient liquidity for your needs: - Compare liquidity reserves across different pools - Identify pools with deep liquidity for large trades - Monitor liquidity trends over time ### Trading Applications #### Pre-Trade Liquidity Checks Before executing large trades, check current pool reserves: - Verify sufficient liquidity exists for your trade size - Monitor liquidity changes that may affect execution - Identify optimal pools with best liquidity depth #### Liquidity Event Detection Track liquidity events that may create trading opportunities: - Detect when new liquidity is added to pools - Monitor liquidity removals that may signal pool abandonment - Identify pools experiencing rapid liquidity growth For more advanced use cases, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#advanced-use-cases-and-processing-patterns). --- ## Ethereum MEV Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-mev-balance-tracker/ Ethereum MEV Balance Tracker: stream Ethereum balance changes with reason codes using Bitquery GraphQL subscriptions. See examples in the Bitquery IDE. # Ethereum MEV Balance Tracker The Ethereum MEV (Maximal Extractable Value) Balance Tracker API provides real-time balance updates related to MEV activities, including transaction fee rewards, block builder rewards, and other MEV-related balance changes. ## Track MEV-Boost Relay Transaction Balances Track balance changes for MEV-boost relay addresses to monitor their activity and rewards. This example uses the `BloXroute Max Profit` address. [Run query](https://ide.bitquery.io/BloXroute-Max-Profit-Tx-Balance-Tracker) ```graphql { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xF2f5C73fa04406b1995e397B55c24aB1f3eA726C" } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD Address BalanceChangeReasonCode } Transaction { Hash From To Value ValueInUSD GasPrice Index } } } } ``` ## Track MEV-Related Balance Updates Monitor balance changes related to MEV activities, including transaction fee rewards and block builder rewards. Try the API [here](https://ide.bitquery.io/Track-MEV-Related-Balance-Updates). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` **Balance Change Reason Code for MEV:** - **Code 5**: `BalanceIncreaseRewardTransactionFee` - Transaction tip increasing block builder's balance (MEV-related) ## Track MEV Payout Transaction Balances with MEV Reward This query focuses on a block builder address and returns the most recent payouts, including the token metadata, pre/post balances, and USD valuations, so you can quickly see how large each MEV reward was. [Try the API](https://ide.bitquery.io/QuasarBuilder-MEV-Payout-Transaction-Balance) ```graphql { EVM(network: eth) { TransactionBalances( limit: {count: 10} where: {Transaction: {}, TokenBalance: {BalanceChangeReasonCode: {eq: 6}, Address: {is: "0x396343362be2a4da1ce0c1c210945346fb82aa49"}}} orderBy: {descending: Block_Time} ) { Block { Time } TokenBalance { Currency { Symbol HasURI SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode TotalSupplyInUSD TotalSupply TokenOwnership { Owns Id } PostBalanceInUSD } Transaction { Hash MEV_reward: Value ValueInUSD } } } } ``` ## Track Block Builder Rewards Monitor transaction fee rewards received by block builders (MEV extractors): Try the API [here](https://ide.bitquery.io/Track-Block-Builder-Rewards). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Number: { gt: "0" } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash GasPrice } } } } ``` ## Filter by MEV Bot or Builder Address Track balance changes for specific MEV bots or block builders: Try the API [here](https://ide.bitquery.io/Filter-by-MEV-Bot-or-Builder-Address). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xMEVBotOrBuilderAddressHere" } BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash GasPrice } } } } ``` ## Track Large MEV Transactions Monitor large transaction fee rewards that may indicate significant MEV extraction: Try the API [here](https://ide.bitquery.io/Track-Large-MEV-Transactions). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } PostBalanceInUSD: { gt: "1000" } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash GasPrice } } } } ``` ## Aggregate MEV Rewards Calculate total MEV rewards for a specific address or time period: Try the API [here](https://ide.bitquery.io/Aggregate-MEV-Rewards). ```graphql { EVM(dataset: archive, network: eth) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xMEVBotOrBuilderAddressHere" } BalanceChangeReasonCode: { eq: 5 } } } ) { TokenBalance { Currency { Symbol } totalRewards: sum(of: TokenBalance_PostBalanceInUSD) totalRewardsETH: sum(of: TokenBalance_PostBalance) rewardCount: count } } } } ``` --- ## Ethereum Mempool API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/mempool/mempool-api/ Watch Ethereum pending transactions before confirmation with Bitquery mempool GraphQL subscriptions, filters, and stream examples. # Mempool API In this section we will look at some examples of how to write mempool queries to extract the necessary data from broadcasted transactions. To read more about how we offer mempool data, read the introduction [here](/docs/subscriptions/mempool-subscriptions/) ## How do I get unconfirmed/pending transactions for an address? Subscribe to **`EVM(mempool: true)`** **`Transactions`** with **`where.any`** on **`Transaction.From`** and **`Transaction.To`** so you see pending txs **to or from** the wallet. Mempool support varies by **`network`**; the example under [Transactions from an Address](#transactions-from-an-address) shows a **from** filter you can extend with `any`. For **BSC**-specific streaming, see [BSC mempool stream](/docs/blockchain/BSC/bsc-mempool-stream/). ## Simulating Pending Transactions The below query retrieves information about in-flight transactions, helping you simulate the most recent state. It is a way to see if they will succeed without sending them on-chain. The `Success` field tells you if your mempool tranaction is successful and `FaultError` and `FaultError` indicate otherwise. You can find query [here](https://ide.bitquery.io/Simulating-Pending-Transactions_1) ```graphql subscription{ EVM(mempool: true) { Transfers{ Log { Index } Transaction { Time Type To Gas From Cost Hash } Transfer { Amount Currency { Name } Type } TransactionStatus { Success FaultError FaultError } Block { Time } } } } ``` ## Get Recommended Fees The Recommended Fees API provides real-time data from the mempool. It returns fields such as block time, block number, transaction hash, transaction cost, sender address, recipient address, base fee, burnt fees, sender fees, priority fees per gas, miner rewards, gas refunds, effective gas prices, and potential savings. You can use it to build applications that require up-to-date information about recommended transaction fees. You can run the query [here](https://ide.bitquery.io/Get-Mempool-Fees) ```graphql { EVM(mempool: true) { Transactions(limit: {count: 100}) { Block { Time Number BaseFee } Transaction { Hash Cost To From } Fee { Burnt SenderFee PriorityFeePerGas MinerReward GasRefund EffectiveGasPrice Savings } } } } ``` ## PairCreated Events This query returns information about transactions that have triggered the `PairCreated` event in the mempool, including the transaction hash, log signature, and argument values. You can run the query [here](https://ide.bitquery.io/PairCreated-in-Mempool) ```graphql subscription { EVM(mempool: true) { Events(where: {Log: {Signature: {Name: {is: "PairCreated"}}}}) { Transaction { Hash } Log{ Signature{ Name } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## Token Trades This subscription provides information about the most recent token trades in the mempool, including the block number and time, transaction details, and trade information such as buyer, seller, price, and currencies involved. You can run the query [here](https://ide.bitquery.io/mempool-token-trades_1) ```graphql subscription { EVM(mempool: true) { buyside: DEXTrades { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price } Sell { Amount Buyer Currency { Name SmartContract Symbol } Seller Price } } } } } ``` ## Transfers This subscription returns details about the latest token transfers in the mempool, including the transfer amount, currency name and symbol, sender, receiver, and transfer type. You can run the query [here](https://ide.bitquery.io/mempool-transfers_1) ```graphql subscription { EVM(mempool: true) { Transfers { Transfer { Amount Currency { Name Symbol } Receiver Sender Type } } } } ``` ## Transactions from an Address Mempool Transactions API provides real-time data from the Binance mempool. You can use it to build applications that require up-to-date information about transactions associated with a specific address. The example below retrieves mempool transactions **from** the specified address (Binance / BSC mempool context). To also include pending txs **to** that address, use `where: { any: [ { Transaction: { From: { is: "..." } } }, { Transaction: { To: { is: "..." } } } ] }` in the same subscription shape. Results include block time, block number, hash, cost, and from/to fields where available. You can run the query [here](https://ide.bitquery.io/Binance-Mempool-Transactions_1) ```graphql subscription { EVM(mempool: true) { Transactions( where: {Transaction: {From: {is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549"}}} ) { Block { Time Number } Transaction { Hash Cost To From } } } } ``` ## Balance Updates in Mempool in Real-time You can track balance changes from each transaction in the mempool, even before it is confirmed. The `TransactionBalances` cube returns the balance before and after each change, with `BalanceChangeReasonCode` saying why it changed. ```graphql subscription { EVM(network: eth, mempool: true) { TransactionBalances { Block { Time } TokenBalance { Currency { Name Symbol } Address PreBalance PostBalance BalanceChangeReasonCode } Transaction { Hash } } } } ``` ## V, R, S Signature of Mempool Transactions The following subscription query retrieves real-time mempool transactions and includes key details such as the block time, block number, transaction hash, transaction cost, and the V, R, S components of the transaction signature. You can run it [here](https://ide.bitquery.io/vrs-signature) ```graphql subscription { EVM(network: eth, mempool: true) { Transactions { Block { Time Number } Transaction { Hash Cost } Signature { V S R } } } } ``` --- ## Ethereum Miner Balance Tracker: Block Producer Income After the Merge URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-miner-balance-tracker/ Ethereum has had no miners since the Merge. Track what block producers earn now with Bitquery GraphQL: priority fees per transaction, block and builder. # Ethereum Miner Balance Tracker: Block Producer Income After the Merge Ethereum stopped mining at the Merge in September 2022. The mining codes stay in the balance schema, 1 for an uncle reward and 2 for a block reward, but the `TransactionBalances` cube covers the recent realtime window only, so on Ethereum they never appear and a filter on them returns nothing. What a block producer earns today shows up under other codes: - **Priority fees**, reason code 5, credited to the block's fee recipient for each transaction. In practice that address is a block builder, since most blocks are built through MEV-Boost. - **Consensus-layer rewards**, which reach validators through consensus-layer withdrawals. Withdrawals are not transactions, so this cube does not record them; reason code 3 exists in the schema for them but returns no rows in live data. The [validator balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-validator-balance-tracker) covers what can be tracked on the execution layer. - **Builder payments to the proposer**, ordinary transfers in the last transaction of a block, covered by the [MEV balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-mev-balance-tracker). This page tracks the first of these. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The example builder is Titan Builder, `0x4838b106fce9647bdf1e7877bf73ce8b0bad5f97`; the query under "Who collected fees" lists the others. ## Stream fee credits as they happen Each message is one transaction's priority fee. `tip` is the balance after minus the balance before, in ETH. Saved stream [here](https://ide.bitquery.io/Track-Transaction-Fee-Rewards). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Number Time } TokenBalance { Address PreBalance PostBalance Currency { Symbol } } Transaction { Hash From } tip: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## Largest tips in the last ten minutes Sort on the computed field. `calculate` only sees fields that are selected, so `PreBalance` and `PostBalance` stay in the query. Saved query [here](https://ide.bitquery.io/Track-Block-Mining-Rewards). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 20 } orderBy: { descendingByField: "tip" } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } ) { Block { Number Time } TokenBalance { Address PreBalance PostBalance } Transaction { Hash From } tip: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) } } } ``` ## One builder's income per block Group by block for one address. The balance before the first credit and after the last credit in the block bracket the block's fee income, so `end` minus `start` is what the builder collected in that block, and `count` is the number of transactions that paid. Saved query [here](https://ide.bitquery.io/Filter-by-Miner-Address). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 20 } orderBy: { descending: Block_Number } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } Address: { is: "0x4838b106fce9647bdf1e7877bf73ce8b0bad5f97" } } Block: { Time: { since_relative: { minutes_ago: 30 } } } } ) { Block { Number } count start: TokenBalance { PreBalance(minimum: Transaction_Index) } end: TokenBalance { PostBalance(maximum: Transaction_Index) } } } } ``` ## Who collected fees in the last hour Group the code 5 rows by receiving address to see which builders and fee recipients were active, ranked by the number of transactions that paid them. Saved query [here](https://ide.bitquery.io/Track-Miner-Balance-Updates). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 20 } orderBy: { descendingByField: "count" } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { TokenBalance { Address } count } } } ``` ## Why the mining codes return nothing Codes 1 and 2 belong to proof-of-work blocks. The cube has no archive dataset on Ethereum, so the pre-Merge era is out of reach on the API and the count below is zero in any window. For pre-Merge balance history, ask about a [Data Store export](https://bitquery.io/datastore). Saved query [here](https://ide.bitquery.io/Track-Uncle-Block-Rewards). ```graphql { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [1, 2] } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { count } } } ``` ## Video walkthrough ## Related pages - [Ethereum MEV balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-mev-balance-tracker) - [Ethereum validator balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-validator-balance-tracker) - [Ethereum gas balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-gas-balance-tracker) - [Ethereum transaction balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-transaction-balance-tracker) --- ## Ethereum NFT API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-api/ Query Ethereum NFT trades, ownership, metadata, and transfers with Bitquery GraphQL APIs, filters, and live streams. See examples in the Bitquery IDE. # NFT API Non-Fungible Tokens (NFTs) are digital assets with unique identification codes that cannot be exchanged for other tokens on a one-to-one basis. NFTs have gained significant popularity in recent years, with the growth of digital art, collectables, and gaming. Bitquery's APIs help you extract and analyze NFT data from various blockchain networks. Below are some examples of NFT queries that can be performed using Bitquery's platform: ## NFT Holders for a project This query retrieves the Ethereum addresses that hold Axie Infinity NFT tokens associated with that smart contract, ranked by their current balance. `Holders` takes a `date` argument for the snapshot day. ```graphql { EVM(network: eth, dataset: combined) { Holders( date: "2026-09-30" limit: { count: 100 } orderBy: { descending: Balance_Amount } where: { Currency: { SmartContract: { is: "0xf5b0a3efb8e8e4c201e2a935f110eaaf3ffecb8d" } } } ) { Holder { Address } Balance { Amount(selectWhere: { gt: "0" }) } } } } ``` **Parameters** - `network`: This specifies the Ethereum network to use. In this case, the network is "eth". - `date`: The snapshot day for the holder list. - `dataset`: This specifies the dataset to use. In this case, the dataset is [combined](/docs/graphql/dataset/combined). - `limit`: This parameter specifies the maximum number of results to return. In this query, the limit is set to 100. - `orderBy`: This parameter specifies the field to order the results by. In this query, the results are ordered in descending order of balance. - `where`: This parameter specifies the conditions to filter the results by. In this query, the filter condition is that the Currency is a Smart Contract with the address "0xf5b0a3efb8e8e4c201e2a935f110eaaf3ffecb8d". ** Returned Data** - `Address`: This field returns the Ethereum wallet address holding the NFT - `Amount`: This field returns the number of tokens the address holds. `selectWhere: { gt: "0" }` drops zero balances. ## All NFTs owned by an address ```graphql { EVM(network: eth, dataset: combined) { Balances( limit: { count: 100 } orderBy: { descending: Balance_Amount } where: { Balance: { Address: { is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03" } } Currency: { Fungible: false } } ) { Currency { Fungible Symbol SmartContract Name HasURI Decimals } Balance { Address Amount(selectWhere: { gt: "0" }) LastChangeTime } } } } ``` **Parameters** - `EVM(network: eth, dataset: combined)`: specifies that we want to query the [combined](/docs/graphql/dataset/combined) dataset of the Ethereum blockchain. - `Balances`: returns the current balance per currency for the address. - `where: { Balance: { Address: { is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03" } }, Currency: { Fungible: false } }`: keeps only non-fungible (NFT) currencies held by this address. **Returned Data** - `Currency`: returns the currency information for the specified smart contract. - `Fungible`: specifies if the currency is fungible or non-fungible. - `Symbol`: returns the symbol for the currency. - `SmartContract`: returns the address of the smart contract for the currency. - `Name`: returns the name of the currency. - `HasURI`: specifies if the currency has a URI. - `Balance`: returns the balance information for the specified address. - `Address`: returns the holder address. - `Amount`: returns the number of NFTs of this collection the address holds. `selectWhere: { gt: "0" }` drops collections it no longer holds. - `LastChangeTime`: returns when the balance last changed. ## Latest NFT trades for given project ```graphql { EVM(network: eth) { DEXTrades( orderBy: {descending: Block_Number} where: {Trade: {Buy: {Currency: {SmartContract: {is: "0x0fcbd68251819928c8f6d182fc04be733fa94170"}}}}} limit: {count: 10} ) { Block { Time } Transaction { Hash } Trade { Dex { ProtocolFamily ProtocolName ProtocolVersion SmartContract } Buy { Price Buyer Ids URIs } Sell { Seller Amount Currency { Symbol SmartContract } } } } } } ``` **Parameters** - `network: eth` specifies that the Ethereum network is being queried. - `dexTrade` retrieves information about trades on DEXs and NFT marketplace for all type of tokens (Fungible or Non-fungible). - `limit: {count: 100}` specifies that up to 100 results will be returned. - `orderBy: {descending: Block_Number}` sorts the results in descending order by the block number (height). - `where` filters the results based on certain criteria. In this case, the results are filtered based on buyCurrency token address "0x0fcbd68251819928c8f6d182fc04be733fa94170" . ## All NFT transfers in a block This query retrieves all NFT token transfers on the Ethereum network within a specific block, and returns information about the block, transfer amount, token currency, sender, and receiver. ```graphql { EVM(dataset: combined, network: eth) { Transfers( orderBy: { descending: Block_Time } where: { Block: { Number: { eq: "16747554" } } Transfer: { Currency: { Fungible: false } } } ) { Block { Hash Number } Transfer { Amount Currency { Name Symbol Native } Sender Receiver } } } } ``` **Parameters**: The EVM Transfers query takes in the following parameters: - `dataset`: This specifies the dataset to use. In this case, the dataset is [combined](/docs/graphql/dataset/combined) - `network`: This specifies the Ethereum network to use. In this case, the network is "eth". - `date`: The snapshot day for the holder list. - `orderBy`: This parameter specifies the field to order the results by. In this query, the results are ordered in descending order of block time. - `where`: This parameter specifies the conditions to filter the results by. In this query, the filter condition is that the transfer is non-fungible and occurred within a specific block identified by the block number. **Returned Data** The EVM Transfers query returns the following fields: - `Hash`: This field returns the hash of the block in which the transfer occurred. - `Number`: This field returns the number of the block in which the transfer occurred. - `Amount`: This field returns the amount transferred. - `Currency.Name`: This field returns the name of the token currency. - `Currency.Symbol`: This field returns the symbol of the token currency. - `Currency.Native`: This field returns a boolean indicating whether the token currency is a native currency of the blockchain. - `Sender`: This field returns the Ethereum address of the sender. - `Receiver`: This field returns the Ethereum address of the receiver. ## All transfers of an NFT This query retrieves the most recent transfers of a specific non-fungible token (NFT) on the Ethereum network. You can find the GraphQL query [here](https://ide.bitquery.io/All-transfers-of-an-NFT) ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Transfers( orderBy: { descending: Block_Time } where: { Transfer: { Currency: { Fungible: false SmartContract: { is: "0x005e6b6776108f4c9e9c5c1259b9554036f8d55e" } } } } limit: { count: 20 } ) { Block { Hash Number } Transfer { Amount Currency { Name Symbol Native } Sender Receiver } } } } ``` **Parameters** - `EVM(dataset: combined, network: eth)` specifies that the query will be executed on the Ethereum blockchain network. - `Transfers` specifies that the query will retrieve transfer transactions on the Ethereum network. - `orderBy: {descending: Block_Time}` specifies that the transfers should be ordered by the time of the block in which they occurred, in descending order (i.e., most recent first). - `where: {Transfer: {Currency: {Fungible: false, SmartContract: {is: "0x005e6b6776108f4c9e9c5c1259b9554036f8d55e"}}}}` specifies the conditions for the transfers to be retrieved. In this case, it specifies that the transfers must involve a non-fungible token (Fungible: false) whose smart contract address is `0x005e6b6776108f4c9e9c5c1259b9554036f8d55e`. - `limit: {count: 20}` specifies that the query should only return the 20 most recent transfers that meet the specified conditions. **Returned Data** - `Block.Hash`: The hash of the block in which the transfer occurred. - `Block.Number`: The number of the block in which the transfer occurred. - `Amount`: The amount of the NFT that was transferred. - `Currency.Name`: The name of the NFT's currency. - `Currency.Symbol`: The symbol of the NFT's currency. - `Currency.Native`: The native type of the NFT's currency. - `Sender`: The address of the sender of the transfer. - `Receiver`: The address of the receiver of the transfer. --- ## Ethereum NFT Balance API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/nft-balance-api/ Ethereum NFT Balance API: stream Ethereum balance changes with reason codes using Bitquery GraphQL subscriptions. Works with WebSocket live subscriptions. # Ethereum NFT Balance API The Ethereum NFT Balance API provides real-time balance updates for ERC-721 and ERC-1155 non-fungible tokens on the Ethereum blockchain. Track NFT ownership, token IDs, and ownership status for any address holding NFTs. :::note For NFTs (ERC-721 / ERC-1155), the following fields are available: - **Available**: `PostBalance`, `TokenOwnership` - **Not Provided**: `PreBalance`, `BalanceChangeReasonCode`, `TotalSupply`, `TotalSupplyInUSD`, `PostBalanceInUSD` ::: ## Get Latest NFT Balance for an Address Get the latest NFT balance for a specific address and NFT collection. This query returns the current NFT count and ownership information. Try the API [here](https://ide.bitquery.io/Get-Latest-NFT-Balance-for-an-Address). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x2906bF2d33bAd2041B31bd22a728724e23F6e764" } Currency: { SmartContract: { is: "0xbe9371326F91345777b04394448c23E2BFEaa826" } Fungible: false } } } ) { Block { Time Number } TokenBalance { Currency { Symbol Name SmartContract HasURI } PostBalance Address TokenOwnership { Owns Id } } Transaction { Hash } } } } ``` ## Stream NFT Balance Updates in Real Time Subscribe to real-time NFT balance updates for a specific address and collection. This subscription will notify you whenever NFT ownership changes. Try the API [here](https://ide.bitquery.io/Stream-NFT-Balance-Updates-in-Real-Time). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Address: { is: "0x2906bF2d33bAd2041B31bd22a728724e23F6e764" } Currency: { SmartContract: { is: "0xbe9371326F91345777b04394448c23E2BFEaa826" } Fungible: false } } } ) { Block { Time Number } TokenBalance { Currency { Symbol Name SmartContract HasURI } PostBalance Address TokenOwnership { Owns Id } } Transaction { Hash From To } } } } ``` ## Get All NFT Collections for an Address Retrieve all NFT collections held by a specific address. This query returns balances for all NFT collections the address owns. Try the API [here](https://ide.bitquery.io/Get-All-NFT-Collections-for-an-Address_1). ```graphql { EVM(network: eth) { TransactionBalances( orderBy: { descendingByField: "TokenBalance_PostBalanceInUSD_maximum" } where: { TokenBalance: { Address: { is: "0x2906bF2d33bAd2041B31bd22a728724e23F6e764" } Currency: { Fungible: false } } } ) { TokenBalance { Address Currency { Symbol Name SmartContract Decimals } PostBalance(maximum: Block_Time, selectWhere: { ne: "0" }) PostBalanceInUSD(maximum: Block_Time) Address } } } } ``` ## Get NFT Balances for Multiple Addresses Get NFT balances for multiple addresses in a single query. Useful for portfolio tracking or wallet monitoring applications. Try the API [here](https://ide.bitquery.io/Get-NFT-Balances-for-Multiple-Addresses_1). ```graphql { EVM(network: eth) { TransactionBalances( orderBy: { descendingByField: "TokenBalance_PostBalanceInUSD_maximum" } where: { TokenBalance: { Address: { in: [ "0x2906bF2d33bAd2041B31bd22a728724e23F6e764" "0x3c6559E241f6A2e15a98f3270bc66447e0B6222b" ] } Currency: { Fungible: false } } } ) { TokenBalance { Address Currency { Symbol Name SmartContract Decimals } PostBalance(maximum: Block_Time, selectWhere: { ne: "0" }) PostBalanceInUSD(maximum: Block_Time) Address } } } } ``` ## Get NFT Ownership History Retrieve the NFT ownership history of a specific NFT over a specific time period. This helps track NFT transfers and ownership changes. Try the API [here](https://ide.bitquery.io/Get-NFT-Ownership-History_2). ```graphql { EVM(network: eth) { TransactionBalances( orderBy: { descending: Block_Time } where: { TokenBalance: { PostBalance: { eq: "1" } Currency: { SmartContract: { is: "0xbe9371326F91345777b04394448c23E2BFEaa826" } Fungible: false } TokenOwnership: { Id: { eq: "24010" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time Number Hash } TokenBalance { Currency { Symbol Name SmartContract HasURI } PostBalance Address TokenOwnership { Owns Id } } Transaction { Hash From To } } } } ``` ## Track specific NFT Balance Changes Monitor NFT transfers for a specific collection across all transactions. This helps track NFT movements and ownership changes. Try the API [here](https://ide.bitquery.io/Track-specific-NFTs-Balance-Changes). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Currency: { SmartContract: { is: "0xbe9371326F91345777b04394448c23E2BFEaa826" } Fungible: false } } } ) { Block { Time Number } TokenBalance { Currency { Symbol Name SmartContract HasURI } PostBalance Address TokenOwnership { Owns Id } } Transaction { Hash From To } } } } ``` ## Get NFT Owner for Specific Token ID Check the current owner of a specific NFT token ID. This query returns ownership information for a particular token. `0xF9c362CDD6EeBa080dd87845E88512AA0A18c615` is the NFT Contract address and `3042` is the NFT Token ID. Try the API [here](https://ide.bitquery.io/Get-NFT-Owner-for-Specific-Token-ID). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { PostBalance: { eq: "1" } Currency: { SmartContract: { is: "0xF9c362CDD6EeBa080dd87845E88512AA0A18c615" } Fungible: false } TokenOwnership: { Id: { eq: "3042" } } } } ) { Block { Time Number } TokenBalance { Currency { Symbol Name SmartContract HasURI } PostBalance Address TokenOwnership { Owns Id } } Transaction { Hash } } } } ``` --- ## Ethereum NFT Calls API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-calls-api/ Ethereum NFT Calls API: track Ethereum NFT trades, ownership, and metadata with Bitquery GraphQL and streams. Keep queries fast with indexed filters. # NFT Calls API This API helps retrieve information about smart contract transactions, including details about the contract function that was called, the input and output parameters, and more. ## Latest Calls for an NFT Here's an example query that retrieve the most recent smart contract calls made on an NFT token contract. ```graphql { EVM { Calls( limit: {count: 10} orderBy: {descending: Block_Time} where: {Call: {To: {is: "0x60e4d786628fea6478f785a6d7e704777c86a7c6"}}} ) { Call { From Gas GasUsed To Value } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `orderBy` : Orders the results in descending order based on the Block_Time. - `limit` : Specifies the maximum results to return. In this query, the limit is 10. - `where` : It filters the results to include only calls made to the smart contract with the specified address ("0x60e4d786628fea6478f785a6d7e704777c86a7c6"). **Returned Data** - `Transaction` : The `Hash` field represents the hash of the transaction. - `Call` : Retrieves information about the call - * `From`: The address from which the call was made. * `Gas`: The gas limit specified for the call. * `GasUsed`: The amount of gas used during the call. * `To` : The address of the NFT token contract that received the call. * `Value` : The amount of Ether transferred in the call. - `Arguments { Name Value {....} }` : Retrieves Array of arguments passed in the smart contract call, including their names and values, refer to [arguments](/docs/schema/evm/arguments) for data structure. You can find the graphql query [here](https://ide.bitquery.io/Smart-contract-calls-to-an-nft-contract). --- ## Ethereum NFT Collection API: Token List, Holders and Transfers URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-collection-api/ Token list, holders, latest transfers and mints for an Ethereum NFT collection with Bitquery GraphQL, worked on Bored Ape Yacht Club. # Ethereum NFT Collection API: Token List, Holders and Transfers An NFT collection is one contract, and two Bitquery cubes describe it. `Transfers` on the archive dataset holds every mint and transfer of every token id since the contract was deployed, which gives you the full token list with each token's metadata URI. `Holders` holds the current owners, ranked by how many tokens of the collection each address holds, without you aggregating transfers yourself. Both examples use the Bored Ape Yacht Club contract `0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d`; put any ERC-721 or ERC-1155 contract in its place. Every query runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. ## All token ids in a collection Group the collection's transfers by token id on the `archive` dataset. Each row is one token, `count` is how many times it has moved, and `offset` pages through the whole collection in id order. For the current owner of one token, take its latest transfer with `Id` in the filter: the `Receiver` is the owner. Saved query [here](https://ide.bitquery.io/Get-all-NFTs-for-a-collection). ```graphql { EVM(dataset: archive, network: eth) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"}}}} limit: {count: 1000, offset: 0} orderBy: {ascendingByField: "Transfer_Id"} ) { Transfer { Id } count } } } ``` ## Holders of a collection, ranked The `Holders` cube returns current balances per address for the collection contract, so the top rows are the largest holders. Add `date: "YYYY-MM-DD"` to see the holder set on a past day. ```graphql { EVM(network: eth) { Holders( limit: { count: 100 } orderBy: { descending: Balance_Amount } where: { Currency: { SmartContract: { is: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d" } } } ) { Holder { Address } Balance { Amount } } } } ``` See the [Balances and Holders cubes](/docs/cubes/balances-cube) page for more balance and holder query patterns. ## Transfer history and mints Plain rows come from the same filter without the grouping. Add the zero address as `Sender` to keep only mints, `Id` for one token, or a `Block.Time` window for a period; the example lists the first BAYC mints from the collection's launch weeks on the archive dataset. Change `query` to `subscription` and drop the dataset argument to stream new transfers of the collection as they happen. ```graphql { EVM(dataset: archive, network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d" } } Sender: { is: "0x0000000000000000000000000000000000000000" } } Block: { Time: { since: "2021-04-01T00:00:00Z", till: "2021-05-31T00:00:00Z" } } } limit: { count: 20 } orderBy: { ascending: Block_Time } ) { Block { Time } Transfer { Id Receiver URI } Transaction { Hash } } } } ``` ## Related pages - [Ethereum NFT API](/docs/blockchain/Ethereum/nft/nft-api) - [Balances and Holders cubes](/docs/cubes/balances-cube) - [Transfers cube](/docs/cubes/transfers-cube) - [Optimism NFT API](/docs/blockchain/Optimism/optimism-nft) --- ## Ethereum NFT Metadata API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-metadata-api/ Ethereum NFT Metadata API: track Ethereum NFT trades, ownership, and metadata with Bitquery GraphQL and streams. Built for traders and analytics teams. # NFT Metadata API The NFT Metadata API retrieves the metadata of NFT. ## Get the Metadata of an NFT Let see an example query that retrieves the metadata of an NFT based on its token ID and the smart contract address. It fetches the latest transfer of the NFT by ordering the results based on the block Number in descending order. ```graphql { EVM(dataset: archive, network: eth) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"}}, Id: {eq: "4226"}}} limit: {count: 1, offset: 0} orderBy: {descending: Block_Number} ) { Transfer { Currency { SmartContract Name Decimals Fungible HasURI Symbol } Id URI Data owner: Receiver } } } } ``` **Parameters** - `network` : Specifies the Ethereum network. - `dataset` : Indicates the [combined](/docs/graphql/dataset/combined) dataset to be used. - `orderBy` : Orders the results in descending order based on the Block_Number. - `where` : This parameter specifies the conditions to filter the results by. In this case, the token ID is `4226` and the Currency with the Smart Contract being `0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D`. **Returned Data** - `Currency {....}` : Represent currency details. - `owner` : Specifies the address of the current owner of the NFT. - `URI` : Represents the URL associated with the NFT. You can find the graphql query [here](https://ide.bitquery.io/NFT-metadata_1_1). ## Get the Creator of an NFT The Following query retrieves the Creator of the NFT. ```graphql { EVM(dataset: combined, network: eth) { Calls( limit: {count: 1} orderBy: {descending: Block_Time} where: {Call: {To: {is: "0x23581767a106ae21c074b2276d25e5c3e136a68b"}, Create: true}} ) { Call { creator: From Create } Transaction { Hash } } } } ``` **Parameters** - `orderBy` : Orders the results in descending order based on the Block_Time. - `limit` : Specifies the maximum results to return. In this query, the limit is 1. - `where` : It filters the results to include only calls made to the smart contract with the specified address `0x23581767a106ae21c074b2276d25e5c3e136a68b` and only includes create call. **Returned Data** - `Call`: The `creator: From` field represent the address of the creator. - `Transaction` : Represents hash of the transaction at which this NFT was created. You can find the graphql query [here](https://ide.bitquery.io/Creator_of_an_NFT). --- ## Ethereum NFT Ownership API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-ownership-api/ Ethereum NFT Ownership API: track Ethereum NFT trades, ownership, and metadata with Bitquery GraphQL and streams. Built for traders and analytics teams. # NFT Ownership API The NFT Ownership API can be used to retrieve information about the ownership of a specific NFT ( Non-Fungible Token ) on the supported blockchain. For instance using this we can access the owners of an NFT including their addresses and associated metadata and also we can retrieve a list of the top holders of a particular NFT. ## Get NFT Owners This query fetches the most recent owner of the NFT. It reads the latest transfer of token ID `9996` from the `Transfers` cube; the `Receiver` of that transfer is the current owner. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Transfers( orderBy: { descending: Block_Time } limit: { count: 1 } where: { Transfer: { Id: { eq: "9996" } Currency: { Fungible: false SmartContract: { is: "0x8a90cab2b38dba80c64b7734e58ee1db38b8992e" } } } } ) { Transfer { Receiver Amount Id Currency { Name SmartContract } } Block { Number Date } } } } ``` **Parameters** - `network` : This specifies the Ethereum network to use. - `dataset` : This specifies the dataset to use. In this case, the dataset is [combined](/docs/graphql/dataset/combined). - `limit` : Specifies the maximum results to return. In this query, the limit is 1. - `orderBy` : Results are in descending order by Block_Time. - `where` : This parameter allows you to filter the results based on specific conditions. In this case, the token ID is "9996" and the Currency is non-fungible, with the Smart Contract being `0x8a90cab2b38dba80c64b7734e58ee1db38b8992e`. **Returned Data** - `Transfer` : `Receiver` is the current owner of the NFT. It also has the amount, token ID and the NFT currency (`Name`, `SmartContract`). - `Block` : Includes the block number and date of the latest transfer. ## Top Holders of an NFT Let's see an example showcasing the retrieval of the top 10 holders for a particular NFT, with their balances. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Balances( orderBy: { descending: Balance_Amount } limit: { count: 10 } where: { Currency: { SmartContract: { is: "0x7dD4F223D9155F412790D696Fa30923489d4Ad34" } } } ) { Balance { Address Amount(selectWhere: { gt: "0" }) } } } } ``` In this query, you'll need to replace `0x7dD4F223D9155F412790D696Fa30923489d4Ad34` with the contract address of the NFT you'd like to retrieve top holders for. **Parameters** - `dataset` : Specifies combined dataset that includes both realtime & archive data. - `network` : Specifies that the Ethereum network is being queried. - `orderBy` : Orders the results based on the "Balance" field in descending order, meaning the holder with highest balance will appear first. - `limit` : Limits the number of results returned to 10. - `where` : It filters the query results based on the NFT smart contract address `0x7dD4F223D9155F412790D696Fa30923489d4Ad34` . `Currency: {SmartContract: {is: ""}}` specifies the filter for the smart contract address. **Returned Data** - `Balance` : `Address` is the holder of the NFT and `Amount` is how many tokens of the collection it holds. ## Find NFT Creator Address The creator of the NFT can be inferred from the sender of the first transfer. By setting, `Transfers(limit: {count: 1} orderBy: {ascending: Block_Time})` we fetch the earliest (first) transfer record based on block time. You can run the query [here](https://ide.bitquery.io/Fidenza-725) ```graphql query MyQuery { EVM(dataset: archive) { Transfers( limit: {count: 1} orderBy: {ascending: Block_Time} where: {Transfer: {Currency: {SmartContract: {is: "0xa7d8d9ef8D8Ce8992Df33D8b8CF4Aebabd5bD270"}}, Id: {eq: "78000725"}}} ) { Block { Time } Transfer { Amount Currency { Symbol SmartContract ProtocolName Native Name HasURI Fungible DelegatedTo Delegated Decimals } Data Id Receiver Success Type } } } } ``` ## Past (churned) holders of tokens Check past (churned) holders of an NFT collection. The `Balances` cube returns every address that has held the token; `Amount(selectWhere: {le: "0"})` keeps only those whose balance is now zero. `FirstChangeTime` and `LastChangeTime` show when each address started and stopped holding. ```graphql { EVM(dataset: combined) { Balances( limit: {count: 10} where: {Currency: {Fungible: false, SmartContract: {is: "0x364c828ee171616a39897688a831c2499ad972ec"}}} ) { Balance { Address Amount(selectWhere: {le: "0"}) FirstChangeTime LastChangeTime } } } } ``` --- ## Ethereum NFT Trades API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-trades-api/ Ethereum NFT Trades API: track Ethereum NFT trades, ownership, and metadata with Bitquery GraphQL and streams. See examples in the Bitquery IDE. # NFT Trades API The NFT Trades API provides access to diverse NFT DEX trades data on supported blockchain. ## Get Latest NFT Trades of an Address Let's dive into an example query that fetches the most recent NFT trades associated with a specific address. ```graphql query MyQuery { EVM(dataset: combined) { DEXTrades( limit: {offset: 0, count: 10} orderBy: {descendingByField: "Block_Time"} where: {Trade: {Buy: {Buyer: {is: "0x6afdf83501af209d2455e49ed9179c209852a701"}, Currency: {Fungible: false}}}} ) { Trade { Dex { ProtocolName OwnerAddress Delegated DelegatedTo ProtocolName SmartContract } Buy { Price Seller Buyer Currency { Symbol HasURI Name Fungible SmartContract } Ids OrderId URIs } Sell { Price Amount Currency { Name } Buyer Seller } } Transaction { Hash } Block { Time } } } } ``` **Parameters** - `dataset` : Indicates the [combined](/docs/graphql/dataset/combined) dataset to be used. - `orderBy` : Orders the results in descending order based on the Block_Time. - `where` : It filters results based on specified conditions. Here, it selects transfers where the currency is non-fungible and buyer's address is `0x6afdf83501af209d2455e49ed9179c209852a701`. **Returned Data** - `Trade`: It displays the details of the trade, `DEX {}` provides DEX information (protocol name, owner address, delegated status, delegated to address, and smart contract address), `Buy{}` and `sell{}` represents the buy side details ( price, seller, buyer, currency information, NFT IDs, order ID, and URIs ), and the sell side details ( price, amount, currency information, buyer, and seller ) respectively. - `Transaction` : Represents the hash of the transaction associated with the trade. - `Block` - Represents the block time of the trade. You can find the graphql query [here](https://ide.bitquery.io/NFT-trades-of-an-address). ## Get Top Traded NFT Tokens This query retrieves the Top Traded NFT Tokens of the month. ```graphql { EVM(dataset: combined, network: eth) { DEXTrades( orderBy: {descendingByField: "count"} limit: {offset: 0, count: 10} where: {Block: {Date: {since: "2023-05-01", till: "2023-05-28"}}, Trade: {Buy: {Currency: {Fungible: false}}, Sell: {Currency: {Fungible: true}}}} ) { Trade { Buy { Currency { Symbol SmartContract } min_price: Price(minimum: Trade_Buy_Price) max_rice: Price(maximum: Trade_Buy_Price) } Sell { Currency { Symbol SmartContract } } } buy_amount: sum(of: Trade_Buy_Amount) sell_amount: sum(of: Trade_Sell_Amount) count } } } ``` You can find the graphql query [here](https://ide.bitquery.io/Top-traded-NFT-tokens-in-a-month). ## Latest NFT Trades on Opensea The following query retrieves the most latest Opensea trades by tracking the Seaport protocol ( Here seaport_v1.4 means all versions of seaport ) and all transactions sent to Opensea’s seaport contract `0x00000000000000adc04c56bf30ac9d3c0aaf14dc`. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {in: "seaport_v1.4"}}}, Transaction: {To: {is: "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Trade { Buy { Currency { Name ProtocolName Symbol Fungible SmartContract } Amount Buyer Ids Price URIs } Sell { Currency { Name ProtocolName Symbol Decimals Fungible SmartContract } Amount Buyer Ids URIs } } Block { Time Number } } } } ``` **Parameters** - `network` : Specifies the Ethereum network. - `dataset` : Indicates the [combined](/docs/graphql/dataset/combined) dataset to be used. - `orderBy` : Orders the results in descending order based on the Block_Time. - `where` : Filters the results based on the specified conditions. In this case, We need to track `Seaport` protocol and all transactions sent to Opensea’s seaport contract `0x00000000000000adc04c56bf30ac9d3c0aaf14dc`. **Returned Data** - `Buy` : Represents the buy side of the trade, including the currency being bought, amount, buyer's address, currency's name, and smart contract address. - `Sell` : Represents the sell side of the trade, including the currency being sold, amount, buyer's address, currency's name, and smart contract address. - `Block` : Provides the block number and timestamp of the trade. You can find the graphql query [here](https://ide.bitquery.io/Latests-OpenSea-Trades). ## Top Traded NFTs on Opensea This query retrieves the Top Traded NFTs on Opensea based on trade count and can also aggregate trading vol, trade count, buyer, seller, and nfts. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {in: "seaport_v1.4"}}}, Transaction: {To: {is: "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"}}} orderBy: {descendingByField: "count"} limit: {count: 10} ) { tradeVol: sum(of: Trade_Buy_Amount) count buyers: count(distinct: Trade_Buy_Buyer) seller: count(distinct: Trade_Buy_Seller) nfts: count(distinct: Trade_Buy_Ids) Trade { Buy { Currency { Name ProtocolName Symbol Fungible SmartContract } } } } } } ``` **Returned Data** - `tradeVol` : Represents trading volume which is sum of trade buy amount. - `count` : Represents the total number of trades. - `buyers` : count of distinct buyers involved in trades. - `seller` : count of distinct sellers involved in trades. - `nfts` : Represents the count of distinct Ids of NFTs traded. You can find the graphql query [here](https://ide.bitquery.io/Top-Traded-NFTs-on-Opensea). ## Total Buy & Sell of an NFT on Opensea To Retrieve Total Buy & sell of specific NFT on Opensea, we just need to specify the currency contract address in the Buy filter. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {in: "seaport_v1.4"}}, Buy: {Currency: {Fungible: false}}}, Transaction: {To: {is: "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"}}} orderBy: {descendingByField: "count"} limit: {count: 10} ) { tradeVol: sum(of: Trade_Buy_Amount) count buyer: count(distinct: Trade_Buy_Buyer) seller: count(distinct: Trade_Buy_Seller) nfts: count(distinct: Trade_Buy_Ids) Trade { Buy { Currency { Name ProtocolName Symbol Fungible SmartContract } } } } } } ``` You can find the graphql query [here](https://ide.bitquery.io/Total-buy-sell-of-an-NFT-on-opensea). ## Latest NFT buyer on Opensea This query retrieves the Latest NFT buyer on Opensea. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {in: "seaport_v1.4"}}, Buy: {Currency: {Fungible: false}}}, Transaction: {To: {is: "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"}}} orderBy: {descendingByField: "count"} limit: {count: 10} ) { count uniq_tx: count(distinct: Transaction_Hash) Block { first_date: Time(minimum: Block_Date) last_date: Time(maximum: Block_Date) } nfts: count(distinct: Trade_Buy_Ids) difffernt_nfts: count(distinct: Trade_Buy_Currency_SmartContract) total_money_paid: sum(of: Trade_Sell_Amount) Trade { Buy { Buyer } } } } } ``` You can find the graphql query [here](https://ide.bitquery.io/Total-buy-sell-of-an-NFT-on-opensea). ## Specific Buyer stats of an NFT on Opensea This query retrieves the Specific Buyer stats of an NFT on Opensea. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {in: "seaport_v1.4"}}, Buy: {Currency: {SmartContract: {is: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"}}, Buyer: {is: "0x2f9ecaa66e12b6168996a6b80cda9bb142f80dd0"}}}, Transaction: {To: {is: "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"}}} orderBy: {descendingByField: "count"} limit: {count: 10} ) { count uniq_tx: count(distinct: Transaction_Hash) Block { first_date: Time(minimum: Block_Date) last_date: Time(maximum: Block_Date) } nfts: count(distinct: Trade_Buy_Ids) Trade { Buy { Buyer Currency { Name ProtocolName Symbol Fungible SmartContract } } } } } } ``` You can find the graphql query [here](https://ide.bitquery.io/Top-buyer-of-specific-NFT). ## Latest NFT Trades on Ethereum for Seaport protocol This query retrieves the latest NFT Trades on Ethereum for Seaport v1.4 protocol. Many marketplaces utilize the Seaport protocol, we can add a Smart contract in Trade → Dex → SmartContract to get a specific marketplace for this protocol. ```graphql query MyQuery { EVM { DEXTrades( limit: {offset: 0, count: 10} orderBy: {descendingByField: "Block_Time"} where: {Trade: {Dex: {ProtocolName: {is: "seaport_v1.4"}}}} ) { Trade { Dex { ProtocolName } Buy { Price Seller Buyer Currency { HasURI Name Fungible SmartContract } } Sell { Price Amount Currency { Name } Buyer Seller } } Transaction { Hash } Block { Time } } } } ``` You can find the graphql query [here](https://ide.bitquery.io/latest-NFT-trades-on-Ethereum-network). --- ## Ethereum NFT Transfer API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-transfer-api/ Ethereum NFT Transfer API: monitor Ethereum native and token transfers in real time with Bitquery GraphQL APIs. Copy GraphQL snippets for production apps. # NFT Transfer API The NFT Transfer API provides access to diverse NFT transfer data on supported blockchains and have various use cases. For instance we can retrieve daily transfers, monitor top NFT transfers, track the latest transfers of specific NFTs, and subscribe to real-time transfers for instant updates etc. ## Daily NFT Transfers Here's an example query that retrieves the daily NFT transfers, providing the quantity of transfers occurring on a day-to-day basis within a specified date range. ```graphql { EVM(dataset: combined, network: eth) { Transfers( orderBy: {ascending: Block_Date} where: {Block: {Date: {since: "2023-05-02", till: "2023-05-09"}}, Transfer: {Currency: {Fungible: false}}} ) { Block { Date } count } } } ``` **Parameters** - `network` : Specifies the Ethereum network. - `dataset` : Indicates the [combined](/docs/graphql/dataset/combined) dataset to be used. - `orderBy` : Orders the results in ascending order based on the Block_Date. - `where` : It filters the results based on the specified conditions. In this case, it selects transfers where currency is non-fungible and block date is between "2023-05-02" and "2023-05-09". **Returned Data** - `count` : The count of NFT transfers that occurred within the specified date range. - `Block` : The `date` specifies the date of the block associated with each transfer. You can find the graphql query [here](https://ide.bitquery.io/NFT-Token-Transfers-By-Date). ## Top Transferred NFT on Ethereum This query fetches the most frequently transferred NFTs on the Ethereum Blockchain within the specified date range. ```graphql { EVM(dataset: combined network: eth){ Transfers( orderBy: {descendingByField: "count"} limit: {offset: 10 count: 100} where: { Block: {Date: {since: "2023-05-02" till: "2023-05-09" }} Transfer: {Currency: {Fungible: false}}} ){ Transfer { Currency { Symbol SmartContract } } count senders: uniq(of: Transfer_Sender method: approximate) receivers: uniq(of: Transfer_Receiver method: approximate) ids: uniq(of: Transfer_Id method: approximate) } } } ``` You can find the graphql query [here](https://ide.bitquery.io/Top-transfered-NFT-tokens-in-network). ## Recent Transfers of an NFT Using this query, we can retrieve the most recent transfers of an NFT, ordered by block time. Includes details such as transfer amount, currency information, sender, receiver, transfer type, NFT ID, and more. ```graphql { EVM(dataset: archive, network: eth) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xdba45c28b32f2750bdc3c25d6a0118d8e1c8ca80"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Transfer { Amount Currency { Name Symbol } Receiver Sender Type Id URI Data } } } } ``` You can find the graphql query [here](https://ide.bitquery.io/latest-nft-transfers). ## Latest NFT transfers Involving Specific User This query retrieves the latest transfers of an NFT involving a specific user. The `sent` field retrieves transfers where the user is the sender, while the `recieved` field retrieves transfers where the user is the receiver. ```graphql { EVM(dataset: archive, network: eth) { sent: Transfers( where: {Transfer: {Sender: {is: "0x415bdfed5a7c490e1a89332648d8eb339d4eea69"}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Transfer { Amount Currency { Name Symbol } Receiver Sender Type Id URI } } recieved: Transfers( where: {Transfer: {Receiver: {is: "0x415bdfed5a7c490e1a89332648d8eb339d4eea69"}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Transfer { Amount Currency { Name Symbol } Receiver Sender Type Id URI } } } } ``` You can find the graphql query [here](https://ide.bitquery.io/latest-nft-transfers-by-a-user). ## Realtime NFT Transfer Subscriptions Using Streaming APIs, you can subscribe to real-time changes on blockchains. We use a GraphQL subscription,which function similarly to WebSockets. Below example, shows how to subscribe to the latest transfers of the NFT token with the smart contract address `0xdba45c28b32f2750bdc3c25d6a0118d8e1c8ca80`. ```graphql subscription { EVM(network: eth) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xdba45c28b32f2750bdc3c25d6a0118d8e1c8ca80"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Transfer { Amount Currency { Name Symbol } Receiver Sender Type Id URI Data } } } } ``` You can find the graphql query [here](https://ide.bitquery.io/Subscription-WebSocket---Latest-NFT-Transfers). --- ## Ethereum Pancakeswap API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/pancakeswap-api/ Ethereum Pancakeswap API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Great for bots, dashboards, and alerts. # PancakeSwap API Bitquery provides PancakeSwap data through APIs, Streams and Data Dumps. The below graphQL APIs and Streams are examples of data points you can get with Bitquery. If you have any question on other data points reach out to [support](https://t.me/Bloxy_info) Need zero-latency Pumpfun data? [Read about our Kafka Streams and Contact us for a Trial](/docs/streams/protobuf/chains/EVM-protobuf/). The PancakSwap DEX Data is also available for view as a dashboard [at DEXRABBIT](https://dexrabbit.bitquery.io/eth/dex_market/pancake_swap_v3) ## Latest Trades on PancakeSwap V3 on Ethereum > Note : You can change the network from "eth" to "bsc" to PancakeSwap data on BNB [Run Query ➤](https://ide.bitquery.io/Latest-Trades-on-PancakeSwap-V3-ETH)
Click to expand GraphQL query ```graphql query LatestTrades { EVM(network: eth) { DEXTradeByTokens( orderBy: {descending: Block_Time} limit: {count: 50} where: {TransactionStatus: {Success: true}, Trade: {Dex: {ProtocolName: {is: "pancake_swap_v3"}}}, Block: {Time: {since: "2025-06-17T09:50:13Z"}}} ) { Block { Time } Transaction { Hash } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } AmountInUSD Price Amount Side { Type Currency { Symbol SmartContract Name } AmountInUSD Amount } Currency { Symbol SmartContract Name } } } } } ```
## Top Traded Pairs on PancakeSwap V3 on ETH [Run Query ➤](https://ide.bitquery.io/Top-token-pairs-on-PancakeSwap-v3)
Click to expand GraphQL query ```graphql query pairs($min_count: String, $market: String, $network: evm_network, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime, $time_ago: DateTime, $eth: String!, $weth: String!, $usdc: String!, $usdt: String!) { EVM(network: $network) { DEXTradeByTokens( where: {TransactionStatus: {Success: true}, Block: {Time: {since: $time_ago}}, any: [{Trade: {Side: {Currency: {SmartContract: {is: $eth}}}}}, {Trade: {Side: {Currency: {SmartContract: {is: $usdt}}}, Currency: {SmartContract: {notIn: [$eth]}}}}, {Trade: {Side: {Currency: {SmartContract: {is: $usdc}}}, Currency: {SmartContract: {notIn: [$eth, $usdt]}}}}, {Trade: {Side: {Currency: {SmartContract: {is: $weth}}}, Currency: {SmartContract: {notIn: [$eth, $usdc, $usdt]}}}}, {Trade: {Side: {Currency: {SmartContract: {notIn: [$usdc, $usdt, $weth, $eth]}}}, Currency: {SmartContract: {notIn: [$usdc, $usdt, $weth, $eth]}}}}], Trade: {Success: true, Dex: {ProtocolName: {is: $market}}}} orderBy: {descendingByField: "usd"} limit: {count: 70} ) { Block { Time(maximum: Block_Time, selectWhere: {after: $time_1h_ago}) } Trade { Currency { Symbol Name SmartContract ProtocolName } Side { Currency { Symbol Name SmartContract ProtocolName } } price_last: PriceInUSD(maximum: Block_Number) price_10min_ago: PriceInUSD( maximum: Block_Number if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: PriceInUSD( maximum: Block_Number if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD( maximum: Block_Number if: {Block: {Time: {before: $time_3h_ago}}} ) } dexes: uniq(of: Trade_Dex_OwnerAddress) amount: sum(of: Trade_Side_Amount) usd: sum(of: Trade_Side_AmountInUSD) sellers: uniq(of: Trade_Seller) buyers: uniq(of: Trade_Buyer) count(selectWhere: {ge: $min_count}) } } } { "network": "eth", "market": "pancake_swap_v3", "eth": "0x", "usdc": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "usdt": "0xdac17f958d2ee523a2206206994597c13d831ec7", "weth": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "min_count": "100", "time_10min_ago": "2025-06-18T09:43:37Z", "time_1h_ago": "2025-06-18T08:53:37Z", "time_3h_ago": "2025-06-18T06:53:37Z", "time_ago": "2025-06-17T09:53:37Z" } ```
## Top Traders on PancakeSwap V3 on ETH [Run Query ➤](https://ide.bitquery.io/Top-Traders-of-a-token-on-PancakeSwap-on-ETH)
Click to expand GraphQL query ```graphql query topTraders { EVM(network: eth) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"}}, Dex: {ProtocolName: {is:"pancake_swap_v3"}}}} ) { Trade { Buyer } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ```
--- ## Ethereum Pepe API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/pepe-api/ PEPE coin on Ethereum: live trades and OHLCV, price on Uniswap V3, whale activity, volume by DEX, top buyers, sellers and holders, and wallet balances. # PEPE Coin API Query real-time and historical on-chain data for [PEPE](https://explorer.bitquery.io/ethereum/token/0x6982508145454ce325ddbe47a25d4ec3d2311933), a popular ERC-20 memecoin on Ethereum. All examples below target PEPE's contract address: `0x6982508145454ce325ddbe47a25d4ec3d2311933`. --- ## Real Time PEPE Trades Stream Every PEPE DEX trade as it is confirmed on-chain in real time using Bitquery subscription. [Run In IDE ➤](https://ide.bitquery.io/pepe-live-trades-stream) ```graphql subscription { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x6982508145454ce325ddbe47a25d4ec3d2311933" } } } } ) { Block { Time Number } Transaction { Hash } Trade { AmountInUSD Price Side { Type AmountInUSD Currency { Symbol } } Buyer Seller Dex { ProtocolName SmartContract } Currency { Symbol } } } } } ``` --- ## Real Time PEPE OHLCV Stream Stream live PEPE price data with 1-minute candles, moving averages, and USD volume. > Note: `Volume: { Usd: { gt: 5 } }` is included to filter outlier ticks; the stream already pre-filters outliers—this is an additional check. [Run In IDE ➤](https://ide.bitquery.io/pepe-ohlcv-stream) ```graphql subscription { Trading { Tokens( where: { Token: { Address: { is: "0x6982508145454ce325ddbe47a25d4ec3d2311933" } } Interval: { Time: { Duration: { eq: 60 } } } Volume: { Usd: { gt: 5 } } } ) { Token { Symbol Name Network Address } Block { Time Timestamp } Interval { Time { Start Duration End } } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving } } } } } ``` --- ## Historical PEPE OHLCV (Last 30 Days) Fetch hourly OHLCV candles for the past 30 days. Change `Duration` for different intervals, such as 60 (1 minute) or 300 (5 minutes). [Run In IDE ➤](https://ide.bitquery.io/pepe-historical-ohlcv-30days) ```graphql { Trading { Tokens( where: { Token: { Address: { is: "0x6982508145454ce325ddbe47a25d4ec3d2311933" } } Interval: { Time: { Duration: { eq: 3600 } } } Volume: { Usd: { gt: 5 } } Block: { Time: { since_relative: { days_ago: 30 } } } } limit: { count: 1000 } orderBy: { descending: Interval_Time_Start } ) { Interval { Time { Start End Duration } } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean ExponentialMoving SimpleMoving } } Volume { Usd } } } } ``` --- ## Monitor Whale Activities for PEPE in Real Time Subscribe to PEPE transfers above 1 billion tokens the moment they hit the chain. [Run In IDE ➤](https://ide.bitquery.io/pepe-whale-transfer-stream) ```graphql subscription { EVM(network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x6982508145454ce325ddbe47a25d4ec3d2311933" } } Amount: { ge: "1000000000000" } } } ) { Block { Time Number } Transaction { Hash } Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol } } } } } ``` --- ## Latest Trading Volume and Market Cap for PEPE This query provides the latest trade volume for the past one hour along with the latest market cap. [Run In IDE ➤](https://ide.bitquery.io/pepe-volume-marketcap) ```graphql { Trading { Tokens( where: { Token: { Address: { is: "0x6982508145454ce325ddbe47a25d4ec3d2311933" } } Interval: { Time: { Duration: { eq: 3600 } } } } orderBy: {descending: Interval_Time_End} limit: {count: 1} ) { Interval{ Time{ Start End } } Price { Ohlc { Close } } Volume { Usd Base Quote } Supply { TotalSupply MarketCap FullyDilutedValuationUsd } } } } ``` --- ## PEPE Volume by DEX (Last 24 Hours) Break down PEPE trading volume across all DEXs. [Run In IDE ➤](https://ide.bitquery.io/pepe-volume-by-dex) ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x6982508145454ce325ddbe47a25d4ec3d2311933" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } ) { Trade { Dex { ProtocolName ProtocolFamily SmartContract } } volumeUsd: sum(of: Trade_AmountInUSD) tradeCount: count(of: Transaction_Hash) } } } ``` --- ## Historical Daily Volume for 30 Days The below query returns the daily trading volume for the past 30 days. [Run In IDE ➤](https://ide.bitquery.io/pepe-daily-volume-30days) ```graphql query MyQuery { Trading { Trades( where: { Block: {Time: {since_relative: {days_ago: 30}}}, Pair: {Token: {Address: {is: "0x6982508145454ce325ddbe47a25d4ec3d2311933"}}} } orderBy: {ascending: Block_Date} ) { Block{ Date } volume: sum(of: AmountsInUsd_Base) trades: count traders: uniq(of: Trader_Address) } } } ``` --- ## Top PEPE Buyers for Last 24 Hours Rank wallets by total USD spent buying PEPE. [Run In IDE ➤](https://ide.bitquery.io/pepe-top-buyers-24h) ```graphql query MyQuery { Trading { Trades( where: { Block: {Time: {since_relative: {hours_ago: 24}}}, Pair: {Token: {Address: {is: "0x6982508145454ce325ddbe47a25d4ec3d2311933"}}}, Side: {is: "Buy"} } limit: {count: 20} orderBy: {descendingByField: "volume"} ) { Trader { Address } volume: sum(of: AmountsInUsd_Base) trades: count } } } ``` --- ## Top PEPE Sellers for Last 24 Hours Rank wallets by total USD value of PEPE sold. [Run In IDE ➤](https://ide.bitquery.io/pepe-top-sellers-24h) ```graphql query MyQuery { Trading { Trades( where: { Block: {Time: {since_relative: {hours_ago: 24}}}, Pair: {Token: {Address: {is: "0x6982508145454ce325ddbe47a25d4ec3d2311933"}}}, Side: {is: "Sell"} } limit: {count: 20} orderBy: {descendingByField: "volume"} ) { Trader { Address } volume: sum(of: AmountsInUsd_Base) trades: count } } } ``` --- ## PEPE Top Holders by Balance [Run In IDE ➤](https://ide.bitquery.io/pepe-top-holders_3) ```graphql query MyQuery { Trading { Trades( where: { Pair: {Token: {Address: {is: "0x6982508145454ce325ddbe47a25d4ec3d2311933"}}}, } limit: {count: 20} orderBy: {descendingByField: "holdings"} ) { Trader { Address } buy_volume: sum(of: AmountsInUsd_Base if: {Side: {is: "Buy"}}) sell_volume: sum(of: AmountsInUsd_Base if: {Side: {is: "Sell"}}) holdings: calculate(expression: "$buy_volume - $sell_volume") trades: count } } } ``` --- --- ## Ethereum Self-Destruct Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-self-destruct-balance-api/ Ethereum Self-Destruct Balance Tracker: stream Ethereum balance changes with reason codes using Bitquery GraphQL subscriptions. # Ethereum Self-Destruct Balance Tracker The Ethereum Self-Destruct Balance Tracker API provides real-time balance updates for contracts that self-destruct and addresses that receive funds from self-destructed contracts. This API helps you monitor contract destruction events, track ephemeral contracts (like MEV bots), and analyze security incidents. ## What is Self-Destruct? The `selfdestruct` opcode allows a smart contract to permanently remove its bytecode from the blockchain and send its remaining ETH balance to a specified recipient address. Once a contract self-destructs, it can no longer execute code or receive transactions. ### Common Use Cases - **MEV Builder Payments**: Ephemeral contracts created to pay MEV builders/block builders (e.g., `quasarbuilder.eth`) as part of the Proposer-Builder Separation (PBS) infrastructure, then immediately self-destructed - **Ephemeral MEV/Arbitrage Executors**: Contracts created and destroyed within the same transaction to execute atomic profit extraction - **Security Incidents**: Malicious actors destroying contracts - **Emergency Shutdowns**: Contract owners destroying contracts to reclaim funds or retire functionality - **Upgrade Patterns**: Destroying old contract versions during upgrades - **Paymasters/Relayers**: Short-lived helper contracts that clean up after sponsoring gas ## Balance Change Reason Codes The API tracks self-destruct events using specific balance change reason codes: - **Code 12**: `BalanceIncreaseSelfdestruct` - Balance added to the recipient as indicated by a self-destructing account - **Code 13**: `BalanceDecreaseSelfdestruct` - Balance deducted from a contract due to self-destruct - **Code 14**: `BalanceDecreaseSelfdestructBurn` - ETH sent to an already self-destructed account within the same transaction ## Track All Self-Destruct Event Balances Monitor all contract self-destruct event balances in real-time using this GraphQL subscription. [Run Stream](https://ide.bitquery.io/All-Self-Destruct-Event-Balances-Stream) You can also run this as a query by replacing the word `subscription` with `query` ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [12, 13, 14] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Track Contract Self-Destruct Balance Decrease Monitor contract balance decrease when contracts are self-destructing. [Run Query](https://ide.bitquery.io/Self-Destruct-Balance-Decrease-API) ```graphql { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 13 } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } TokenBalance { Currency { Symbol SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Track Recipients of Self-Destructed Fund Balances Monitor contract balance increase when contracts are self-destructing. [Run query](https://ide.bitquery.io/Self-Destruct-Balance-Increase-API) ```graphql { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 12 } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } TokenBalance { Currency { Symbol SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Track Self-Destruct Balance Changes for Specific Address Monitor self-destruct balance changes for a specific contract address using this GraphQL query: Try the API [here](https://ide.bitquery.io/Track-Self-Destruct-Balance-Changes-for-Specific-Address). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Address: { is: "0x863DF6BFa4469f3ead0bE8f9F2AAE51c91A907b4" } BalanceChangeReasonCode: { in: [12, 13, 14] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Track Large Self-Destruct Transaction Balances Monitor significant self-destruct balance changes (e.g., > $1000 USD) using this subscription: Try the API [here](https://ide.bitquery.io/Track-Large-Self-Destruct-Transaction-Balances). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [12, 13] } PostBalanceInUSD: { gt: "1000" } } } ) { Block { Time Number } TokenBalance { Currency { Symbol SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Track Ephemeral MEV Contract Balance Changes Monitor balance changes for short-lived contracts that are created and destroyed in the same transaction (typical pattern for MEV bots) using this subscription: Try the API [here](https://ide.bitquery.io/Track-Ephemeral-MEV-Contract-Balance-Changes). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 13 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash From To } } } } ``` ## Aggregate Self-Destruct Statistics Calculate total ETH destroyed or received from self-destructs using aggregation functions: Try the API [here](https://ide.bitquery.io/Aggregate-Self-Destruct-Statistics). ```graphql { EVM(dataset: realtime, network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [12, 13] } } } ) { TokenBalance { Currency { Symbol SmartContract } } totalDestroyed: sum(of: TokenBalance_PostBalance) destructCount: count } } } ``` ## Self-Destruct Usecase Examples ### 1. MEV Builder Payment (Ephemeral Executor) A common pattern in the MEV ecosystem involves **ephemeral contracts** that are created to pay MEV builders/block builders, then immediately self-destruct. This pattern is part of the **Proposer-Builder Separation (PBS)** infrastructure. Contrack Flow: Deploy → Transfer to MEV builder → Self-destruct **What's happening:** 1. A searcher/bundler deploys a temporary helper contract 2. The contract holds the exact ETH amount owed as a fee/bribe to the MEV builder 3. The contract transfers ETH to the builder 4. The contract immediately self-destructs, cleaning up and leaving minimal trace **Why this pattern:** - **Ephemeral by design** - avoids leaving identifiable payment trails per bundle - **Safety** - one-use contract prevents reuse or exploitation - **Gas efficiency** - minimal runtime deployment is cheaper than maintaining reusable state - **Privacy** - prevents tracking of bundle logic across blocks **API Subscription: Track payments to known MEV builders:** Try the API [here](https://ide.bitquery.io/Track-payments-to-known-MEV-builders). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 12 } Address: { in: [ "0x396343362be2A4dA1cE0C1C210945346fb82Aa49" # Add other known MEV builder addresses ] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash From To } } } } ``` ### 3. Ephemeral MEV/Arbitrage Contracts Many MEV bots and arbitrage executors create contracts that are destroyed within the same transaction. These short-lived contracts are used for: - Atomic multi-swap execution - Flash loan arbitrage - Obfuscation of execution patterns - Cleanup of bytecode footprint **API Query: Track recent ephemeral contract patterns:** Try the API [here](https://ide.bitquery.io/Track-recent-ephemeral-contract-patterns_1). ```graphql { EVM(dataset: realtime, network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 13 } } } limit: { count: 100 } orderBy: { descendingByField: "Block_Time" } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash From To } } } } ``` ## API Use Cases ### Security Monitoring - Track Malicious Self-Destructs Track self-destruct events to identify potential security incidents or malicious contract destruction: Try the API [here](https://ide.bitquery.io/Track-Malicious-Self-Destructs). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 13 } PostBalanceInUSD: { gt: "10000" } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash From } } } } ``` ## Notes - **Balance Change Reason Codes 12, 13, and 14** are only available for native currency (ETH) transactions, not for fungible tokens or NFTs - Code 12 indicates funds **received** from a self-destructed contract - Code 13 indicates funds **destroyed** from a self-destructing contract - Code 14 indicates ETH sent to an already self-destructed account within the same transaction - Self-destructed contracts cannot be recovered or interacted with after destruction - The `PreBalance` field shows the balance before the self-destruct, and `PostBalance` shows the balance after (typically 0 for the destroyed contract) --- ## Ethereum Smart Contract Calls API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/calls/smartcontract/ Ethereum smart contract calls: query the most recent contract calls and the calls that created new contracts on mainnet, with ready-to-run GraphQL examples. # Ethereum Smart Contract Calls API ## Smart Contract Calls API Guide > **Before you start**: Not sure when to use Calls vs Transfers vs Events vs DexTrades? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. This API helps retrieve information about smart contract transactions, including details about the contract function that was called, the input and output parameters, and more. With this data, you can build applications that interact with smart contracts, perform analytics on contract activity, and more. ## Recent Smart Contract Calls This query retrieves the most recent smart contract calls on the Ethereum network, focusing on contract creation calls. It provides comprehensive information about the call details, transaction data, and block information.
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: eth) { Calls( limit: {count: 10} orderBy: {descending: Block_Time} ) { Call { LogCount InternalCalls Create EnterIndex ExitIndex } Transaction { Gas Hash From To Type Index } Block { Date } } } } ```
## Recent Smart Contract Creation Calls This GraphQL query fetches data from the "eth" network about the 10 most recent calls made in Ethereum that were contract creation calls. You can run the query [here](https://ide.bitquery.io/smart-contract-creation-on-EVM-chains) ```graphql query MyQuery { EVM(dataset: realtime, network: eth) { Calls( limit: {count: 10} orderBy: {descending: Block_Time} where: {Call: {Create: true}} ) { Call { LogCount InternalCalls Create EnterIndex ExitIndex } Transaction { Gas Hash From To Type Index } Block { Date } } } } ``` --- ## Ethereum Smartcontract Filterby URL: https://docs.bitquery.io/docs/blockchain/Ethereum/calls/smartcontract-filterby/ Ethereum smart contract calls filtered by method signature, opcode or call arguments, with GraphQL query examples for each filter type. # SmartContract API ## Smart Contract Calls by Method Signature This query retrieves the 10 most recent smart contract calls that match a specific function signature (harvest()) on the Binance Smart Chain (BSC) network. It also includes transaction and block data associated with each call. You can find the GraphQL query [here](https://ide.bitquery.io/Calls-by-Method-Signature) ```graphql query MyQuery { EVM(dataset: archive, network: bsc) { Calls( limit: {count: 10} orderBy: {descending: Block_Date} where: {Call: {Signature: {Signature: {is: "harvest()"}}}, Block: {Date: {after: "2023-01-01"}}} ) { Call { LogCount InternalCalls } Transaction { Gas Hash From To Type Index } Block { Date } } } } ``` **Parameters** - `EVM(dataset: archive, network: bsc)`: This parameter specifies the blockchain network and dataset to query. In this case, we are querying the Binance Smart Chain network with the [combined](/docs/graphql/dataset/combined) dataset. - `Calls`: This parameter retrieves the list of smart contract calls that match the specified conditions. - `limit`: \{count: 10\}: This parameter limits the number of results returned to 10. - `orderBy`: \{descending: Block_Date\}: This parameter orders the results in descending order based on the block date of the calls. - `where: {Call: {Signature: {Signature: \{is: "harvest()"\}}}, Block: {Date: \{after: "2023-01-01"\}}}:` This parameter specifies the conditions to filter the smart contract calls. In this case, we filter calls based on the function signature harvest() and a block date after January 1, 2023. **Returned Data** The query returns the following data for each smart contract call: - `Call.LogCount`: The number of log entries emitted by the call. - `Call.InternalCalls`: The list of internal calls made by the call. - `Gas`: The amount of gas used by the transaction. - `Hash`: The hash of the transaction. - `From`: The address of the sender of the transaction. - `To`: The address of the receiver of the transaction. - `Type`: The type of the transaction (e.g., contract creation or message call). - `Index`: The index of the transaction within the block. - `Block.Date`: The date and time when the block was added to the blockchain. ## Smart Contract Calls by Opcode This GraphQL query retrieves information about the latest STATICCALL EVM (Ethereum Virtual Machine) calls on the Binance Smart Chain network. You can find the GraphQL query [here](https://ide.bitquery.io/Smart-Contract-Calls-by-Opcode) ```graphql query MyQuery { EVM(dataset: archive, network: bsc) { Calls( limit: {count: 10} orderBy: {descending: Block_Date} where: {Block: {Date: {after: "2023-01-01"}}, Call: {Opcode: {Name: {is: "STATICCALL"}}}} ) { Call { LogCount InternalCalls Opcode { Name } } Transaction { Gas Hash From To Type Index } Block { Date } } } } ``` **Parameters** - `dataset` parameter specifies the dataset to be queried, which is set to combined. - `network` parameter specifies the network to be queried, which is set to bsc. - `limit` parameter is used to limit the number of results returned and is set to 10. - `orderBy` parameter is used to sort the results by the Block_Date field in descending order. - `where` parameter is used to filter the results based on certain conditions. In this case, the where parameter filters the results to include only STATICCALL calls made after January 1st, 2023. **Returned Data** - `Call`: Returns information about the STATICCALL call, including the number of logs generated, internal calls made, and the name of the opcode used. - `Transaction`: Returns information about the transaction that contains the STATICCALL call, including the gas used, transaction hash, sender address, recipient address, transaction type, and transaction index. - `Block`: Returns the date of the block in which the STATICCALL call was made. ## Smart Contract Calls by Arguments The Array-like structure of [Arguments and Returns](/docs/schema/evm/arguments/) in Smart Contract Calls allows us to insert specific filters, enabling us to effectively narrow down our search. Further we can better understand the details of smart contract interactions in specific contexts. **Example 1** This [query](https://ide.bitquery.io/smart_contract_argument_transfer) demonstrates how we can trace transfer calls to a particular token contract, Matic Token in this case, that are being transferred to a specified wallet address. This is useful for monitoring the inflow of a specific token to a certain wallet. ```graphql query MyQuery { EVM(dataset: archive, network: eth) { Calls( where: {Call: {Signature: {Name: {is: "transfer"}}, To: {is: "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"}}, Arguments: {includes: {Index: {eq: 0}, Name: {is: "to"}, Type: {is: "address"}, Value: {Address: {is: "0xB53E1f6322629b9435E95AeC13eC34aF9C8fB8bA"}}}}} limit: {count: 10} ) { Arguments { Name Value { ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Returns { Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` **Parameters** - `dataset` : parameter specifies the combined dataset and `network` parameter specifies the network. - `where` : parameter sets filters on the function calls and arguments. The 'Signature' filter specifies "transfer" function calls made to Matic's token contract. The 'includes' filter under Arguments targets the recipient of the transfer (argument with index 0) with a specific wallet address. **Returned Data** The response includes the first 10 matching calls along with the arguments details and the return values for each call. As usual, you can adjust the filter values and arguments based on your specific use case. **Example 2** Let's consider a scenario where we're interested in tracking large liquidity additions to a specific Uniswap pair, like the ETH/USDT pair. By [this](https://ide.bitquery.io/addLiquidityETH_function) query, We can track calls to the function ` addLiquidityETH ` which is a common function used in Uniswap for adding liquidity to a pool. ```graphql query MyQuery { EVM(dataset: archive, network: eth) { Calls( where: {Transaction: {Hash: {is: "0x60ce9acd0053f20092e7871868afe5187c95ff6d7750ad65a8d4ff99a052c357"}}, Call: {Signature: {Name: {is: "addLiquidityETH"}}}, Arguments: {length: {eq: 6}, includes: [{Index: {eq: 0}, Value: {Address: {is: "0x9cbc0be914e480beee4014e190fdbfc48ed5a4a8"}}}, {Index: {eq: 3}, Value: {BigInteger: {ge: "1000000000000000000"}}}, {Index: {eq: 5}, Value: {BigInteger: {ge: "1690878863"}}}]}} limit: {count: 10} ) { Arguments { Index Name Type Path { Name Index Type } Name Value { ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { Signature { Name Signature } } } } } ``` **Parameters** - `dataset` : parameter specifies the combined dataset and `network` parameter specifies the network - `where` : parameter mentions the filters on the Call and Arguments. The 'Signature' filter specifies that we want function calls where the function name is "addLiquidityETH".The 'includes' filter under Arguments specifies that we want the first argument (Index 0) to be the specific token contract address, the third argument (Index 3) 'uint256' value greater than or equal to 1000000000000000000, and the last argument (Index 5) to be a deadline timestamp that is greater than or equal to "1690878863". **Returned Data** The response will contain the first 10 calls that match these filter conditions, along with the details of the arguments and the function signature of each call. --- ## Ethereum Token Balance API: ERC-20 Balances, Supply and Market Cap URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/token-balance-api/ ERC-20 balances on Ethereum with Bitquery GraphQL: one token for a wallet, every token a wallet holds, several wallets, history, supply and market cap. # Ethereum Token Balance API: ERC-20 Balances, Supply and Market Cap Every transaction that moves an ERC-20 token writes one row per affected address into the `TransactionBalances` cube, with the balance after the transaction, its USD value, and the token's total supply and on-chain market cap at that moment. That makes the cube a balance API for any wallet that has been active recently: the newest row for a wallet and a token is its current balance. Token rows carry no reason code and no pre-balance; those belong to native ETH rows, covered on the [transaction balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-transaction-balance-tracker). The cube holds the recent realtime window only, so a wallet that has not moved a token inside it has no row; for those use the [Balances cube](/docs/cubes/balances-cube), which does not depend on recent activity. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked wallet is a busy one that moves stablecoins and meme tokens all day, `0x9642b23Ed1E01Df1092B92641051881a322F5D4E`, and the worked token is USDT, `0xdac17f958d2ee523a2206206994597c13d831ec7`. ## Balance of one token for one wallet Filter on the wallet and the token contract and take the newest row. Saved query [here](https://ide.bitquery.io/Get-Latest-Token-Balance-for-an-Address). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x9642b23Ed1E01Df1092B92641051881a322F5D4E" } Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD Currency { Symbol Name SmartContract Decimals } } Transaction { Hash } } } } ``` ## Every token a wallet holds `limitBy` on the token contract keeps the newest row per token, so one query returns the wallet's current balance in every token it moved inside the window, largest USD value first once you sort the rows. Saved query [here](https://ide.bitquery.io/Get-All-Token-Balances-for-an-Address). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 50 } limitBy: { by: TokenBalance_Currency_SmartContract, count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x9642b23Ed1E01Df1092B92641051881a322F5D4E" } Currency: { Native: false, Fungible: true } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD Currency { Symbol SmartContract } } } } } ``` Add `PostBalanceInUSD: { gt: "1000000" }` inside `TokenBalance` to keep only positions worth more than a million dollars, which is the saved [minimum balance](https://ide.bitquery.io/Filter-Tokens-by-Minimum-Balance) query. ## Several wallets at once `in` takes a list of addresses; with the token fixed and `limitBy` on the address, the result is the latest USDT balance of each wallet in one call. Saved query [here](https://ide.bitquery.io/Get-Token-Balances-for-Multiple-Addresses). ```graphql { EVM(network: eth) { TransactionBalances( limitBy: { by: TokenBalance_Address, count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { in: [ "0x9642b23Ed1E01Df1092B92641051881a322F5D4E" "0xf977814e90da44bfa03b6295a0616a897441acec" ] } Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Time } TokenBalance { Address PostBalance PostBalanceInUSD } } } } ``` ## Balance history of one token Every row for the wallet and token, newest first, is the balance after each transaction that touched it. Saved query [here](https://ide.bitquery.io/Get-Token-Balance-History). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 100 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0x9642b23Ed1E01Df1092B92641051881a322F5D4E" } Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } ) { Block { Time Number } TokenBalance { PostBalance PostBalanceInUSD } Transaction { Hash } } } } ``` ## Total supply and market cap of a token Token rows carry `TotalSupply` and `TotalSupplyInUSD` as of that transaction, so the newest row for a token, from any wallet, is its current supply and on-chain market cap. Saved query [here](https://ide.bitquery.io/Get-Token-Total-Supply-and-Market-Cap). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } ) { Block { Time } TokenBalance { Currency { Symbol Name } TotalSupply TotalSupplyInUSD } } } } ``` ## Stream balance changes of a token The token filter as a subscription delivers a row for every address whose USDT balance changes, as each transaction is indexed. Add the wallet to the filter to follow one holder. Saved stream [here](https://ide.bitquery.io/Track-Token-Balance-Changes-by-Transaction). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } ) { Block { Time } TokenBalance { Address PostBalance PostBalanceInUSD } Transaction { Hash From To } } } } ``` ## Related pages - [Ethereum transaction balance tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-transaction-balance-tracker) - [Ethereum NFT balance API](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/nft-balance-api) - [Balances and Holders cubes](/docs/cubes/balances-cube) - [Ethereum token market cap API](/docs/blockchain/Ethereum/token-supply/ethereum-token-marketcap-api) --- ## Ethereum Token Holder API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/token-holders/token-holder-api/ Rank Ethereum token holders with the Bitquery Holders cube: top holders, holder counts, dated snapshots, balance thresholds and distribution statistics. # Token Holders API :::note Holder rankings, snapshots and distribution stats are productized in the [Token Holder API](https://bitquery.io/products/token-holder-api) — see the page for chains, plans and trial access. ::: The **Holders** API returns token holder data for ERC-20 tokens on Ethereum: top holders, holder counts, and balance thresholds. Non-zero balances use `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | |---------|-------------| | **`combined`** | Latest holder count, top holders, and balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Addresses not recently active (not in the realtime window). | Examples: [Top Holders](#top-holders-of-a-currency-current) · [Holder Count](#token-holder-count-for-an-erc-20-token) · [Whales](#holder-count-with-balance-above-a-threshold) · [Historical Top Holders](#historical-top-holders-by-date) · [Holder Activity](#token-holder-activity) · [Statistics](#token-holder-statistics) ## Top Holders of a Currency (Current) The most common starting point for traders and analysts: who holds the most of a token right now. Use `dataset: combined` for the latest top holders (realtime + archive). [Run in IDE](https://ide.bitquery.io/ethereum-holders-top)
Click to expand GraphQL query ```graphql { EVM(network: eth, dataset: combined) { Holders( date: "2026-06-30" where: {Currency: {SmartContract: {is: "0x54D2252757e1672EEaD234D27B1270728fF90581"}}} orderBy: {descending: Balance_Amount} limit: {count: 10} ) { Holder { Address } Balance { Amount(selectWhere: {gt: "0"}) FirstChangeTime LastChangeTime } } } } ```
## Token Holder Count for an ERC-20 Token How many wallets hold a token. Count distinct addresses with `uniq(of: Holder_Address)` and `dataset: combined`. [Run in IDE](https://ide.bitquery.io/ethereum-holders-count-combined)
Click to expand GraphQL query ```graphql query { EVM(network: eth, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } ) { uniq(of: Holder_Address) } } } ```
## Token Holder Snapshot The number of unique holders, token supply, and Gini coefficient for the balance amount before a specific timestamp can be derived using the query below. These stats provide a useful holder snapshot for any given time. [Run in IDE](https://ide.bitquery.io/token-holder-snapshot_1)
Click to expand GraphQL query ```graphql query MyQuery($network: evm_network!, $address: String!) { EVM(network: $network, dataset: archive) { Holders( where: { Currency: {SmartContract: {is: $address}}, Balance: { Amount: {gt: "0"}, LastChangeTime: {till: "2026-05-20T00:00:00Z"} }, Holder: {Address: {not: "0x"}}} ) { Balance { LastChangeTime(maximum: Balance_LastChangeTime) } holders: uniq(of: Holder_Address) supply: sum(of: Balance_Amount) gini(of: Balance_Amount) } } } ``` ```json { "network": "eth", "address": "0x00000000001594c61dd8a6804da9ab58ed2483ce" } ```
## Holder Count with Balance Above a Threshold Count holders above a minimum balance (whale / large-holder filters). Use `uniq(of: Holder_Address, if: { Balance: { Amount: { gt: "..." } } })` with your threshold. [Run in IDE](https://ide.bitquery.io/count-ethereum-holders-count-above-threshold)
Click to expand GraphQL query ```graphql query { EVM(network: eth, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } ) { uniq( of: Holder_Address if: { Balance: { Amount: { gt: "10000000" } } } ) } } } ```
## Track Whale Wallets and Token Holdings For whale monitoring, combine **[Top Holders](#top-holders-of-a-currency-current)** (`orderBy: { descending: Balance_Amount }`, `limit`) with **[Holder Count Above a Threshold](#holder-count-with-balance-above-a-threshold)**. Pair with [ERC-20 transfers](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api) to see recent inflows and outflows from large wallets. ## Historical Top Holders by Date The **Holders** cube does not support `Block.Date`. Filter by `Balance.LastChangeTime` using datetime format (for example `"2026-05-01T00:00:00Z"`). For address balances on a calendar date, use the [Balances API](/docs/blockchain/Ethereum/balances/balance-api/#balance-on-a-specific-date) with `Block.Date`. [Run in IDE](https://ide.bitquery.io/ethereum-holders-top-by-date)
Click to expand GraphQL query ```graphql query { EVM(network: eth, dataset: combined) { Holders( where: { Balance: { LastChangeTime: { till: "2026-05-01T00:00:00Z" } } Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } orderBy: { descending: Balance_Amount } limit: { count: 100 } ) { Holder { Address } Balance { Amount(selectWhere: { gt: "0" }) LastChangeTime } } } } ```
## Token Holder Count History Over Time Build holder-count time series by running the count query with `Balance.LastChangeTime.till` at different timestamps, then aggregating in your app or scheduler. [Run in IDE](https://ide.bitquery.io/ethereum-holders-count-by-date)
Click to expand GraphQL query ```graphql query { EVM(network: eth, dataset: combined) { Holders( where: { Balance: { LastChangeTime: { till: "2026-05-01T00:00:00Z" } } Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } ) { uniq(of: Holder_Address) } } } ```
## Wallet Balance at a Point in Time One wallet’s balance for a token on a given date uses the **[Balances API](/docs/blockchain/Ethereum/balances/balance-api/)**, not Holders: set `Balance.Address`, `Currency.SmartContract`, and `Block.Date.till`. Use `dataset: archive`, `orderBy: { descending: Block_Date }`, and `limit: { count: 1 }`. [Run in IDE](https://ide.bitquery.io/ethereum-wallet-balance-token-at-date) · [Balances API docs](/docs/blockchain/Ethereum/balances/balance-api/#wallet-balance-for-a-specific-token-on-a-date)
Click to expand GraphQL query ```graphql query { EVM(network: eth, dataset: archive) { Balances( where: { Block: { Date: { till: "2026-05-05" } } Balance: { Address: { is: "0xA46320Aa0b4877b9a46a07B4F3DB93719bd422dE" } } Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } limit: { count: 1 } orderBy: { descending: Block_Date } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ```
## Token Holder Activity Drill into a **specific wallet** for a token: transfer count and first/last activity times. Uses the **Holders** API (`UpdateCount`, `FirstChangeTime`, `LastChangeTime`). ### Count of Transactions for a Token from a Token Holder [Run in IDE](https://ide.bitquery.io/Number-of-token-transactions-for-a-wallet)
Click to expand GraphQL query ```graphql query { EVM(network: eth, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } Holder: { Address: { is: "0xB953E202C5E51C7C010E80402a63C02f37F14059" } } } ) { Balance { UpdateCount } } } } ```
### First and Last Transfer Dates for a Token Holder [Run in IDE](https://ide.bitquery.io/Frst-and-last-date-time-for-token-holder)
Click to expand GraphQL query ```graphql query { EVM(network: eth, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } Holder: { Address: { is: "0xB953E202C5E51C7C010E80402a63C02f37F14059" } } } ) { Balance { UpdateCount LastChangeTime FirstChangeTime } } } } ```
## Token Holder Statistics Distribution metrics (average, median, Gini, Nakamoto index, and more) come from aggregate functions on the **`Holders`** cube. See [statistics docs](/docs/graphql/metrics/statistics/) for the full metric list, and the [Balances & Holders cubes](/docs/cubes/balances-cube) reference for how `Holders` differs from `Balances`. ### Average Balance of a Token Holder [Run in IDE](https://ide.bitquery.io/avg-usdt-balance-on-ethereum-using-token-holders-api)
Click to expand GraphQL query ```graphql { EVM(dataset: archive, network: eth) { Holders( date: "2026-05-01" where: { Currency: { SmartContract: { is: "0xdAC17F958D2ee523a2206206994597C13D831ec7" } }, Balance: { Amount: { ge: "0" } } } ) { average(of: Balance_Amount) } } } ```
### Median Balance of a Token Holder [Run in IDE](https://ide.bitquery.io/median-balance-of-usdt-holders-on-ethereum-with-token-holders-api)
Click to expand GraphQL query ```graphql { EVM(dataset: archive, network: eth) { Holders( date: "2026-05-01" where: { Currency: { SmartContract: { is: "0xdAC17F958D2ee523a2206206994597C13D831ec7" } }, Balance: { Amount: { ge: "0" } } } ) { median(of: Balance_Amount) } } } ```
## Find Token Holders Outside a Certain Range Advanced filter: holders with balance above an upper bound or below a lower bound (e.g. excluding mid-tier wallets). [Run in IDE](https://ide.bitquery.io/Find-holders-outside-a-range)
Click to expand GraphQL query ```graphql { EVM(dataset: archive) { Holders( date: "2026-05-01" where: { Currency: { SmartContract: { is: "0x0fcbd68251819928c8f6d182fc04be733fa94170" } }, any: [ { Balance: { Amount: { gt: "100" } } } { Balance: { Amount: { lt: "20" } } } ] Balance: { Amount: { gt: "0" } } } orderBy: { descending: Balance_Amount } limit: { count: 10 } ) { Balance { Amount } Holder { Address } Currency { Name Symbol } } } } ```
## Video Tutorial on How to Identify Top Token Holders for Any Cryptocurrency --- ## Ethereum Token Market Cap API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/token-supply/ethereum-token-marketcap-api/ Ethereum Token Market Cap API: stream Ethereum market cap, FDV, supply, and price using Bitquery Trading GraphQL APIs. See examples in the Bitquery IDE. # Ethereum Token Market Cap API Use Bitquery’s **Trading** API **`Tokens`** cube to stream or query **market cap**, **fully diluted valuation (USD)**, **total supply**, **price** (OHLC and averages), and **volume** for tokens traded on **Ethereum**. Rows are tied to a time **interval**; filter Ethereum assets via token/currency **`Id`** (for example `eth:` plus the contract address). For schema details and field meanings, see the **[Tokens cube](/docs/trading/crypto-price-api/tokens)** and **[Supply fields](/docs/trading/crypto-price-api/supply-fields)**. :::note Trading API and EVM addresses In the **Trading** API, use **lowercase** hex for EVM contract addresses in token/currency **`Id`** values (e.g. `eth:0xabc…`, not checksum `0xAbC…`). ::: ## Related APIs - **[Base Token Market Cap API](/docs/blockchain/Base/base-token-marketcap-api)** — same **`Trading.Tokens`** patterns on Base (`base:` ids) - **[Arbitrum Token Market Cap API](/docs/blockchain/Arbitrum/arbitrum-token-marketcap-api)** — same **`Trading.Tokens`** patterns on Arbitrum (`arbitrum:` ids) - **[Polygon (Matic) Token Market Cap API](/docs/blockchain/Matic/matic-token-marketcap-api)** — same **`Trading.Tokens`** patterns on Polygon (`matic:` ids) - **[BSC Token Market Cap API](/docs/blockchain/BSC/bsc-token-marketcap-api)** — same **`Trading.Tokens`** patterns on BNB Smart Chain (`bsc:` ids) - **[Solana Token Market Cap API](/docs/blockchain/Solana/solana-token-marketcap-api)** — same **`Trading.Tokens`** patterns on Solana (`solana:` ids) - **[EVM Token Supply API](/docs/blockchain/Ethereum/token-supply/evm-token-supply)** — on-chain total supply via `EVM` / `TransactionBalances` - **[Crypto Price API — Tokens](/docs/trading/crypto-price-api/tokens)** — full `Tokens` cube reference --- ## How do I stream live Ethereum token market cap, price, and volume? Subscribe to **`Tokens`** updates for assets whose **currency id** includes **`eth`** (Ethereum), with an **interval duration** greater than **1** (second). Each payload can include **token metadata**, **block time**, **supply** (including **MarketCap** and **FullyDilutedValuationUsd**), **price** (OHLC and average mean), and **volume**. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/ethereum-token-marketcap-stream_1). ```graphql subscription MyQuery { Trading { Tokens( where: { Currency: { Id: { includes: "eth" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` --- ## How do I get the latest market cap for a specific Ethereum token? Return the **most recent** row for one token by **`Token.Id`** (e.g. `eth:` + **lowercase** contract address). Use **`limit: { count: 1 }`** and **`orderBy: { descending: Block_Time }`**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/specific-ethereum-token-latest-marketcap_1). ```graphql query { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { includes: "eth:0xe53ec727dbdeb9e2d5456c3be40cff031ab40a55" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` Replace the `includesCaseInsensitive` value with your token’s **`eth:`** id. --- ## How do I stream Ethereum tokens with market cap above $1 million? Subscribe to **`Tokens`** where the token id matches Ethereum (**`eth`**) and **`Supply.MarketCap`** is **greater than 1,000,000** (USD). The example selects **currency**, **supply**, and **market cap** fields suitable for dashboards and alerts. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-stream-ethereum-tokens-with-marketcap-above-1-million). ```graphql subscription { Trading { Tokens( where: { Token: { Id: { includes: "eth" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 1000000 } } } ) { Currency { Name Id Symbol } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` :::tip Threshold and interval Adjust **`Supply.MarketCap`** and **`Interval.Time.Duration`** filters to match your use case. See **[Tokens cube](/docs/trading/crypto-price-api/tokens)** for other filter fields. ::: --- ## How do I get top Ethereum tokens by market cap? This query ranks **Ethereum** tokens by **`Supply.MarketCap`** (latest in the window). It uses data from roughly the **last 24 hours** (`since_relative: { hours_ago: 24 }`), **1-second** intervals (`Duration: { eq: 1 }`), at least **$1,000** **USD volume**, **`limitBy`** one row per **`Token_Id`**, and returns up to **50** tokens. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Ethereum). ```graphql { Trading { Tokens( limit: { count: 50 } limitBy: { count: 1, by: Token_Id } orderBy: { descending: Supply_MarketCap } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 1000 } } Token: { Network: { is: "Ethereum" } } } ) { Currency { Id Name Symbol } Price { Average { Mean(maximum: Block_Time) } } Volume { Base(maximum: Block_Time) Quote(maximum: Block_Time) Usd(maximum: Block_Time) } Token { Network Symbol Address } Supply { MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) TotalSupply(maximum: Block_Time) } } } } ``` --- ## How do I get top Ethereum tokens by market cap change in 1 hour? This query uses a **1-hour** OHLC interval (`Duration: { eq: 3600 }`) and orders by a calculated field **`change_mcap`**: **(close − open) × total supply**, approximating **USD market cap change** over the period. Filter **`Token.Network`** is **Ethereum**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/top-Eth-tokens-by-Market-Cap-Change-1h_1). ```graphql { Trading { Tokens( limit: { count: 50 } orderBy: { descendingByField: "change_mcap" } where: { Interval: { Time: { Duration: { eq: 3600 } } } Token: { Network: { is: "Ethereum" } } } ) { Currency { Id Name Symbol } Token { Network Symbol Address } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } change_mcap: calculate( expression: "($Price_Ohlc_Close-$Price_Ohlc_Open) * Supply_TotalSupply" ) Price { Ohlc { Open Close } } } } } ``` ## Video tutorial --- ## Ethereum Token Trades APIs URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/token-trades-apis/ Ethereum Token Trades Apis: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. See examples in the Bitquery IDE. # Token Trades API :::tip Need real-time token trade data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview): [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered token trade swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use the `EVM` queries on this page for raw per-swap detail or call and event context. An `EVM` query without a `dataset` argument runs on the realtime dataset, which holds only the last few days; add `dataset: combined` or `dataset: archive` for **historical token trade data**, as several examples below do. ::: We have three main APIs to get DEX trading data. - DEXTrades - DEXTradeByTokens - Trades cube Read [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) to get a better understanding on when to use which cube. ## Subscribe to realtime DEXTrades on Ethereum Mainnet This subscription streams [every DEX trade on Ethereum mainnet as it happens](https://ide.bitquery.io/subscribe-to-dex-trades-on-ethereum-mainnet_2).
Subscription: every Ethereum DEX trade as it happens ```graphql subscription MyQuery { EVM(network: eth) { DEXTrades { Block { Time Number } Transaction { Hash } Call { Signature { Name Signature } } Log { Index SmartContract Signature { Signature Name } } Trade { Sender Buy { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } Dex { SmartContract ProtocolName ProtocolVersion } Sell { Buyer AmountInUSD Amount Seller PriceInUSD Price Currency { Name Symbol SmartContract } } } } } } ```
## Get the Buys, Sells, Buy Volume, Sell Volume and Makers Fetch buys, sells, volumes, and the number of makers for a specific pool (`0x842293fa6ee0642bf61ebf8310e7e546039ba7f4`). A [video walks through building DexScreener-style trade stats with this query](https://www.youtube.com/watch?v=K_H3to_nIdY).
Buys, sells, volume and makers for one pool, with variables ```graphql query MyQuery( $network: evm_network $token: String $pairAddress: String $min5_timestamp: DateTime $hr1_timestamp: DateTime ) { EVM(dataset: realtime, network: $network) { DEXTradeByTokens( where: { TransactionStatus: { Success: true } Trade: { Currency: { SmartContract: { is: $token } } Dex: { SmartContract: { is: $pairAddress } } } Block: { Time: { since: $hr1_timestamp } } } ) { Trade { Currency { Name SmartContract Symbol } startPrice: PriceInUSD(minimum: Block_Time) Price_at_min5: PriceInUSD( minimum: Block_Time if: { Block: { Time: { after: $min5_timestamp } } } ) current_price: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily SmartContract } Side { Currency { Symbol Name SmartContract } } } makers: count(distinct: Transaction_From) makers_5min: count( distinct: Transaction_From if: { Block: { Time: { after: $min5_timestamp } } } ) buyers: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: sell } } } } ) buyers_5min: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { after: $min5_timestamp } } } ) sellers: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: buy } } } } ) sellers_5min: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { after: $min5_timestamp } } } ) trades: count trades_5min: count(if: { Block: { Time: { after: $min5_timestamp } } }) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { after: $min5_timestamp } } } ) buy_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { after: $min5_timestamp } } } ) sell_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { after: $min5_timestamp } } } ) buys: count(if: { Trade: { Side: { Type: { is: sell } } } }) buys_5min: count( if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { after: $min5_timestamp } } } ) sells: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells_5min: count( if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { after: $min5_timestamp } } } ) } } } ``` ```json { "network": "eth", "token": "0x6982508145454Ce325dDbE47a25d4ec3d2311933", "pairAddress": "0xA43fe16908251ee70EF74718545e4FE6C5cCEc9f", "hr1_timestamp": "2024-11-14T03:20:00Z", "min5_timestamp": "2024-11-14T04:15:00Z" } ```
## Get the Buys, Sells, Buy Volume, Sell Volume and Makers of Multiple Tokens Same metrics as above, but for multiple pools at once.
The same metrics for several pools, with variables ```graphql query MyQuery( $network: evm_network, $token: String, $pairAddress: [String!], $min5_timestamp: DateTime, $hr1_timestamp: DateTime ) { EVM(dataset: realtime, network: $network) { DEXTradeByTokens( where: { TransactionStatus: { Success: true }, Trade: { Dex: { SmartContract: { in: $pairAddress } }, Side: { Currency: { SmartContract: { is: $token } } } }, Block: { Time: { since: $hr1_timestamp } } } ) { /* same fields as previous */ } } } ``` ```json { "network": "eth", "token": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "pairAddress": [ "0x055FB841Cce69000FBAFF2691Ad39Fa6E23826a1", "0x8d345583C9289D69d4a55797CcadC5A1eA150A44" ], "hr1_timestamp": "2025-06-18T07:34:00Z", "min5_timestamp": "2025-06-18T08:28:00Z" } ```
## Get First 500 Buyers of a specific token This returns the [first 500 buyers of an ERC-20 token](https://ide.bitquery.io/first-500-buyers-of-a-ERC20-token_1#), `0x3c3a81e81dc49A522A592e7622A7E711c06bf354` in this example.
First 500 buyers of an ERC-20 token ```graphql query MyQuery { EVM(network: eth, dataset: combined) { DEXTrades( limit: { count: 500 } orderBy: { ascending: Block_Time } limitBy: { count: 1, by: Trade_Sell_Buyer } where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x3c3a81e81dc49A522A592e7622A7E711c06bf354" } } } } } ) { Block { Time } Trade { Sell { Buyer } } Transaction { From Hash } } } } ```
## Historical Token Trades & Price API Use the DEXTrades API for historical buyside and sellside trades of BLUR token by the 1inch router.
BLUR trades routed through 1inch, from the archive (fields omitted) ```graphql { EVM(dataset: archive, network: eth) { buyside: DEXTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } Seller: { is: "0x1111111254eeb25477b68fb85ed929f73a960582" } } } Block: { Time: { since: "2023-03-03T01:00:00Z", till: "2023-03-05T05:15:23Z" } } } ) { /* buyside fields */ } sellside: DEXTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } Buyer: { is: "0x1111111254eeb25477b68fb85ed929f73a960582" } } } Block: { Time: { since: "2023-03-03T01:00:00Z", till: "2023-03-05T05:15:23Z" } } } ) { /* sellside fields */ } } } ```
## Get Price Change 5min, 1h, 6h and 24h of a specific token This returns the [price change over 5 minutes, 1, 6 and 24 hours for one token](https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_1#). Change `Currency{SmartContract}` and `Dex{SmartContract}` to your token and pool.
Price change over 5 minutes, 1, 6 and 24 hours ```graphql query MyQuery { EVM(dataset: combined) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0x4393b54385e91824A2Ae5DFd35e226A3313A1a18"}}, Dex: {SmartContract: {is: "0x2bE4042B40359555b41C1A8b80bf604267DE0C5A"}}}, TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ){ Trade { Price_5min_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{minutes_ago:5}}}}) Price_1h_ago: PriceInUSD(minimum:Block_Number if:{Block:{Time:{since_relative:{hours_ago:1}}}}) Price_6h_ago: PriceInUSD(minimum: Block_Number if:{Block:{Time:{since_relative:{hours_ago:6}}}}) Price_24h_ago: PriceInUSD(minimum: Block_Number) CurrentPrice: PriceInUSD(maximum: Block_Number) } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum( of: Trade_Side_AmountInUSD ) Price_Change_5min: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100") Price_Change_1h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100") Price_Change_6h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100") Price_Change_24h: calculate(expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100") } } } ```
## Top 10 Eth Tokens by Price Change in last 1h This returns the [10 Ethereum tokens with the biggest price change in the last hour](https://ide.bitquery.io/Top-10-eth-tokens-by-price-change-in-last-1-hr_2).
Ten Ethereum tokens with the biggest 1-hour price change ```graphql query MyQuery { EVM(dataset: combined) { DEXTradeByTokens( limit: {count: 10} orderBy: {descendingByField: "Price_Change_1h"} where: {TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}, Trade: {Side: {Currency: {SmartContract: {is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}}}}} ) { Trade { Currency { Name Symbol SmartContract } Price_5min_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} selectWhere:{ne:0} ) Price_1h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 1}}}} selectWhere:{ne:0} ) Price_6h_ago: PriceInUSD( minimum: Block_Number if: {Block: {Time: {since_relative: {hours_ago: 6}}}} selectWhere:{ne:0} ) Price_24h_ago: PriceInUSD(minimum: Block_Number selectWhere:{ne:0}) CurrentPrice: PriceInUSD(maximum: Block_Number selectWhere:{ne:0}) Side { Currency { Name Symbol SmartContract } } Dex { SmartContract } } volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) volume_1h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 1}}}} ) volume_6h: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {since_relative: {hours_ago: 6}}}} ) volume_24h: sum(of: Trade_Side_AmountInUSD) Price_Change_5min: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100" ) Price_Change_1h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100" ) Price_Change_6h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100" ) Price_Change_24h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100" ) } } } ```
## Latest Trades of a Token Fetch the most recent 50 trades for a given token:
The 50 latest trades of one token ```graphql query LatestTrades { EVM(network: eth) { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Trade: { Currency: { SmartContract: { is: "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } } Price: { gt: 0 } } } ) { Block { allTime: Time } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } AmountInUSD Buyer Seller Side { Type Buyer Seller } Price Amount Side { Currency { Symbol SmartContract Name } AmountInUSD Amount } } } } } ```
![DEXrabbit's WBTC Latest Trades tab listing each trade's time, side, price, both currencies and amounts, and USD value](https://github.com/user-attachments/assets/e4273aea-bf8d-41e4-80e8-b676005e0ce7) Our DEX Dashboard gives you a easier way to check the data -> [DEXrabbit](https://dexrabbit.bitquery.io/eth/token/0x2260fac5e5542a773aa44fbcfedf7c193bc2c599#last_trades). ## Latest Trades of Multiple Tokens [Run Query](https://ide.bitquery.io/latest-trades-of-multiple-tokens-against-weth-usdt)
{" "} Latest trades of WBTC and LINK ```graphql query LatestTrades { EVM(network: eth) { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { TransactionStatus: { Success: true } Trade: { Side: { Currency: { SmartContract: { in: [ "0x", "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "0xdac17f958d2ee523a2206206994597c13d831ec7" ] } } } Currency: { SmartContract: { in: [ "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599", "0x514910771af9ca656af840dff83e8264ecf986ca" ] } } Success: true } Block: { Time: { since: "2025-08-17T08:55:31Z" } } } ) { Block { Time } Transaction { Hash } Trade { Dex { SmartContract ProtocolFamily ProtocolName } AmountInUSD Buyer Seller Side { Type Buyer Seller } PriceInUSD Amount Side { Currency { Symbol SmartContract Name } AmountInUSD Amount } } } } } ```
## Token Trade Analytics Trade totals for one BNB Chain token over its full history: pairs, DEXs, amount and USD volume, and the number of accounts that bought and sold it. The USD sums leave out mispriced trades.
Pairs, DEXs, volume and traders for one BNB Chain token ```graphql { EVM(network: bsc, dataset: combined) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xc342774492b54ce5f8ac662113ed702fc1b34972" } } } } orderBy: { descendingByField: "usd" } limit: { count: 1000 } ) { Trade { Currency { Decimals Symbol SmartContract Fungible Name } Amount(maximum: Block_Number) AmountInUSD(maximum: Block_Number) } pairs: uniq(of: Trade_Side_Currency_SmartContract) dexes: uniq(of: Trade_Dex_OwnerAddress) amount: sum(of: Trade_Amount) usd: sum(of: Trade_AmountInUSD, if: { Trade: { PriceAsymmetry: { lt: 0.1 } } }) usd2: sum(of: Trade_Side_AmountInUSD, if: { Trade: { PriceAsymmetry: { lt: 0.1 } } }) buyers: uniq(of: Transaction_From, if: { Trade: { Side: { Type: { is: sell } } } }) sellers: uniq(of: Transaction_From, if: { Trade: { Side: { Type: { is: buy } } } }) count } } } ```
## Aggregated Token Data (Volume & Price, Last 24h) Use this API to get historical price and volume for a specific token (example: bid:solana:9WHhgXJBGgxghkh5wAUWJFHVbnsRbonRYTnH2EChpump) over the past 24 hours, with 1h, 4h, and 24h breakdowns. Try it on IDE: [Historical Price & Volume API](https://ide.bitquery.io/historical-price-and-historical-volume)
Trading.Tokens volume and price for the past 24 hours ```graphql { Trading { Tokens( where: { Interval: { Time: { Duration: { eq: 1 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } Token: { Id: { in: ["bid:solana:9WHhgXJBGgxghkh5wAUWJFHVbnsRbonRYTnH2EChpump"] } } } ) { Currency { Id Name Symbol } Price { Average { currentPrice: Mean(maximum: Block_Time) H1Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) H4Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 4 } } } } ) H24Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) } } v1h: sum( of: Volume_Usd if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) v4h: sum( of: Volume_Usd if: { Block: { Time: { since_relative: { hours_ago: 4 } } } } ) v24h: sum(of: Volume_Usd) } } } ```
## Top Traders of a Token Returns the top 100 traders of a token by USD volume. It ranks `Transaction.From`, the account that sent each swap, since on a sale `Trade.Buyer` is the pool or a router. `Side.Type` describes the counter-side of each trade, so `bought` sums the rows where `Side.Type` is `sell`. `PriceAsymmetry: { lt: 0.1 }` leaves out trades whose two sides disagree on value ([PriceAsymmetry reference](/docs/graphql/metrics/priceAsymmetry/)).
Top 100 traders of a token, with variables ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Currency: { SmartContract: { is: $token } }, PriceAsymmetry: { lt: 0.1 } } } ) { Transaction { From } bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "eth", "token": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } ```
You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth/token/0x2260fac5e5542a773aa44fbcfedf7c193bc2c599#top_traders). ## Get all Trading Pairs data of a specific token
Pairs a token trades in, with variables ```graphql query tokenTrades( $network: evm_network, $token: String, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime ) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "usd" } where: { Trade: { Currency: { SmartContract: { is: $token } } }, Block: { Time: { after: $time_3h_ago } } } limit: { count: 200 } ) { Trade { Currency { Symbol Name SmartContract Fungible } Side { Currency { Symbol Name SmartContract } } price_usd: PriceInUSD(maximum: Block_Number) price_last: Price(maximum: Block_Number) price_10min_ago: Price( maximum: Block_Number if: { Block: { Time: { before: $time_10min_ago } } } ) price_1h_ago: Price( maximum: Block_Number if: { Block: { Time: { before: $time_1h_ago } } } ) price_3h_ago: PriceInUSD(minimum: Block_Number) } usd: sum(of: Trade_AmountInUSD) count } } } { "network": "eth", "token": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599", "time_10min_ago": "2024-09-22T12:39:26Z", "time_1h_ago": "2024-09-22T11:49:26Z", "time_3h_ago": "2024-09-22T09:49:26Z" } ```
![DEXrabbit's WBTC Traded Pairs tab with last price, USD price, 10-minute, 1-hour and 3-hour change, daily volume and daily trades per pair](https://github.com/user-attachments/assets/dfe5ad4b-cb32-4a53-a52c-3985d438da2b) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth/token/0x2260fac5e5542a773aa44fbcfedf7c193bc2c599#token_trades). ## Get all DEXs where a specific token is listed
DEXs that trade a token, with variables ```graphql query tokenDexMarkets($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "amount" } where: { Trade: { Currency: { SmartContract: { is: $token } } } } ) { Trade { Dex { ProtocolFamily ProtocolName } } amount: sum(of: Trade_Amount) pairs: uniq(of: Trade_Side_Currency_SmartContract) trades: count } } } { "network": "eth", "token": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } ```
![DEXrabbit's WBTC DEX Markets tab listing each DEX and protocol with its trade count, pair count and WBTC volume](https://github.com/user-attachments/assets/f0de1013-b634-4058-8423-78d7130fcc10) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth/token/0x2260fac5e5542a773aa44fbcfedf7c193bc2c599#token_dex_list). ## Latest Trades of a Token pair
Latest trades of one pair, with variables ```graphql query LatestTrades($network: evm_network, $token: String, $base: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Trade: { Side: { Amount: { gt: "0" }, Currency: { SmartContract: { is: $base } } }, Currency: { SmartContract: { is: $token } }, Price: { gt: 0 } } } ) { Block { allTime: Time } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } Currency { Symbol SmartContract Name } Price AmountInUSD Amount Side { Type Currency { Symbol SmartContract Name } AmountInUSD Amount } } } } } { "network": "eth", "token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "base": "0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098" } ```
![DEXrabbit's WETH / MISHA Latest Trades tab with time, side, price, WETH and MISHA amounts, and USD value](https://github.com/user-attachments/assets/b06fe6ff-e8ba-43f7-b9de-22666dde7bc6) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth/pair/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2/0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098#pair_latest_trades). ## Get OHLC data for a particular token pair
Five-minute USD candles for one pair, with variables ```graphql query tradingViewPairs($network: evm_network, $token: String, $base: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: { ascendingByField: "Block_Time" } where: { Trade: { Side: { Amount: { gt: "0" }, Currency: { SmartContract: { is: $base } } }, Currency: { SmartContract: { is: $token } }, PriceAsymmetry: { lt: 0.5 } } } ) { Block { Time(interval: { count: 5, in: minutes }) } Trade { open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) max: PriceInUSD(maximum: Trade_PriceInUSD) min: PriceInUSD(minimum: Trade_PriceInUSD) } volume: sum(of: Trade_Side_Amount) } } } { "network": "eth", "token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "base": "0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098" } ```
![DEXrabbit's 5-minute candlestick chart for WETH / MISHA with volume bars](https://github.com/user-attachments/assets/33af35df-4a9b-4ec8-a26b-d4770c2e7c96) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth/pair/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2/0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098). ## Top Traders of a token pair The same ranking for one pair: accounts that sent swaps between WETH and the base token, with `bought` and `sold` counted the same way.
Top 100 traders of one pair, with variables ```graphql query pairTopTraders($network: evm_network, $token: String, $base: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Currency: { SmartContract: { is: $token } }, Side: { Amount: { gt: "0" }, Currency: { SmartContract: { is: $base } } }, PriceAsymmetry: { lt: 0.1 } } } ) { Transaction { From } bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "eth", "token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "base": "0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098" } ```
You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth/pair/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2/0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098#pair_top_traders). ## Get all DEXs where a specific token pair is listed
DEXs that trade one pair, with variables ```graphql query pairDexList( $network: evm_network, $token: String, $base: String, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime ) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "amount" } where: { Trade: { Currency: { SmartContract: { is: $token } }, Side: { Amount: { gt: "0" }, Currency: { SmartContract: { is: $base } } } }, Block: { Time: { after: $time_3h_ago } } } ) { Trade { Dex { ProtocolFamily ProtocolName } price_last: PriceInUSD(maximum: Block_Number) price_10min_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_10min_ago } } } ) price_1h_ago: PriceInUSD( maximum: Block_Number if: { Block: { Time: { before: $time_1h_ago } } } ) price_3h_ago: PriceInUSD(minimum: Block_Number) } amount: sum(of: Trade_Side_Amount) pairs: uniq(of: Trade_Side_Currency_SmartContract) trades: count } } } { "network": "eth", "token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "base": "0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098", "time_10min_ago": "2024-09-22T13:10:42Z", "time_1h_ago": "2024-09-22T12:20:42Z", "time_3h_ago": "2024-09-22T10:20:42Z" } ```
![DEXrabbit's WETH / MISHA DEX Markets tab: Uniswap v2 and v3 rows with trades, last price, 10-minute, 1-hour and 3-hour change and daily volume](https://github.com/user-attachments/assets/a652f6de-1066-49b6-87f7-b05e481565bf) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth/pair/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2/0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098#pair_dex_list). ## Top Gainers Pairs ranked by USD price change over the last hour, among pairs with at least 100 trades in that hour. A pair can appear twice, once for each of its tokens. `buyers` and `sellers` count the accounts that sent those swaps.
Pairs ranked by 1-hour price gain, with variables ```graphql query ($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "change_1h" } limit: { count: 100 } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Trade: { PriceAsymmetry: { lt: 0.1 } } } ) { Trade { Currency { Symbol Name SmartContract } Side { Currency { Symbol Name SmartContract } } price_last: PriceInUSD(maximum: Block_Number) price_1h_ago: PriceInUSD(minimum: Block_Number) } change_1h: calculate(expression: "($Trade_price_last - $Trade_price_1h_ago) / $Trade_price_1h_ago * 100") dexes: uniq(of: Trade_Dex_OwnerAddress) amount: sum(of: Trade_Side_Amount) usd: sum(of: Trade_Side_AmountInUSD) buyers: uniq(of: Transaction_From, if: { Trade: { Side: { Type: { is: sell } } } }) sellers: uniq(of: Transaction_From, if: { Trade: { Side: { Type: { is: buy } } } }) count(selectWhere: { ge: "100" }) } } } { "network": "eth" } ```
![DEXrabbit's Top Gainers table for Ethereum pairs with last price, 1-hour change, daily volume and daily trades](https://github.com/user-attachments/assets/9b501fe8-fb44-4796-a3d4-4084f230e626) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth). ## Top Bought tokens Tokens ranked by USD bought. Buys are the rows where `Side.Type`, the counter-side, is `sell`, and the `PriceAsymmetry` filter keeps mispriced trades out of the totals.
Tokens ranked by USD bought, with variables ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "buy" } limit: { count: 100 } where: { Trade: { PriceAsymmetry: { lt: 0.1 } } } ) { Trade { Currency { Symbol Name SmartContract } } buy: sum( of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } } ) sell: sum( of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } } ) } } } { "network": "eth" } ```
![DEXrabbit's Top Bought table for Ethereum tokens with USD bought and sold](https://github.com/user-attachments/assets/ef9e8091-0460-4208-841e-4595269d5b84) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth). ## Top Sold tokens Tokens ranked by USD sold, where sales are the rows with `Side.Type` set to `buy`.
Tokens ranked by USD sold, with variables ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "sell" } limit: { count: 100 } where: { Trade: { PriceAsymmetry: { lt: 0.1 } } } ) { Trade { Currency { Symbol Name SmartContract } } buy: sum( of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } } ) sell: sum( of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } } ) } } } { "network": "eth" } ```
You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth). ## Latest Token Trades In `DEXTrades` on EVM chains, `Buy` and `Sell` are the pool's side of the trade ([DEXTrades cube](/docs/cubes/dextrades)): `buyside` below holds trades where the pool received the token, that is, traders sold it, and `sellside` trades where traders bought it.
Buy side and sell side of one token's trades (fields omitted) ```graphql { EVM(dataset: archive, network: eth) { buyside: DEXTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } } } ) { /* fields */ } sellside: DEXTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } } } ) { /* fields */ } } } ```
The IDE has the [full latest-trades query with every field](https://ide.bitquery.io/latest-trades-for-a-token---both-buy-and-sell). ## Token trade from a specific DEX
Uniswap v3 trades in which traders sold WETH (fields omitted) ```graphql { EVM(dataset: archive, network: eth) { buyside: DEXTrades( limit: { count: 5 } orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } Dex: { ProtocolName: { is: "uniswap_v3" } } } } ) { /* fields */ } } } ```
The IDE has the [full DEX-filtered version](https://ide.bitquery.io/token-trades-for-a-specific-DEX_1). ## Subscribe to new token trades (WebSocket)
Subscription: new WETH trades each block (fields omitted) ```graphql subscription { EVM(network: eth) { buyside: DEXTrades( orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } } ) { /* fields */ } sellside: DEXTrades( orderBy: { descending: Block_Time } where: { Trade: { Sell: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } } ) { /* fields */ } } } ```
The IDE has the [full subscription](https://ide.bitquery.io/latest-token-trades-subscription). ## OHLC in USD of a Token Hourly open, high, low and close prices in USD for USDT, from its trades against WETH.
Hourly USD candles for USDT ```graphql { EVM(network: eth, dataset: realtime) { DEXTradeByTokens( orderBy: { descendingByField: "Block_testfield" } where: { Trade: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } PriceAsymmetry: { lt: 0.1 } Side: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } } limit: { count: 10 } ) { Block { testfield: Time(interval: { in: hours, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) } count } } } ```
## Get Token Metadata
Name, symbol and decimals of a token ```graphql query MyQuery { EVM(network: eth, dataset: combined) { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { SmartContract: { is: "0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE" } } } } ) { Trade { Currency { Name Symbol SmartContract ProtocolName HasURI Fungible Decimals } } } } } ```
## Top Buyers of a Token
Ten largest buyers of a token by USD ```graphql { EVM { DEXTradeByTokens( orderBy: { descendingByField: "bought" } limit: { count: 10 } where: { Trade: { Currency: { SmartContract: { is: "0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39" } } } } ) { Trade { Buyer Currency { Symbol Name SmartContract } } bought: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ```
## Top Sellers of a Token
Ten largest sellers of a token by USD ```graphql { EVM { DEXTradeByTokens( orderBy: { descendingByField: "sold" } limit: { count: 10 } where: { Trade: { Currency: { SmartContract: { is: "0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39" } } } } ) { Trade { Buyer Currency { Symbol Name SmartContract } } sold: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) } } } ```
## Get trading volume, buy volume, sell volume of a token This returns the traded, buy and sell volume in USD of BNB's ERC-20 contract on Ethereum (`0xB8c77482e45F1F44dE1745F52C74426C631bDD52`), across every DEX, over the last 24 hours. `PriceAsymmetry: { lt: 0.1 }` drops mispriced trades, which would otherwise skew the USD sums.
24-hour traded, buy and sell volume of one token ```graphql query MyQuery { EVM { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xB8c77482e45F1F44dE1745F52C74426C631bDD52" } } PriceAsymmetry: { lt: 0.1 } } TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract } } traded_volume_in_usd: sum(of: Trade_Side_AmountInUSD) sell_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ```
## Stablecoin Peg Health (Latest Price Across All DEXs) Get the **latest price of a stablecoin across all EVM DEXs**. Returns one row per DEX protocol with the most recent trade price. Useful for monitoring peg health and identifying which exchanges have the stablecoin trading closest to its target peg (e.g., $1.00 for USD-pegged stablecoins). Browse multi-chain stablecoin DEX prices on [DEXrabbit's Stablecoins category](https://dexrabbit.bitquery.io/categories/stablecoins). [Run in Bitquery IDE](https://ide.bitquery.io/evm-peg-health_1)
Latest stablecoin price on each DEX ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descending: Block_Time } limitBy: { count: 1, by: Trade_Dex_SmartContract } where: { Trade: { Currency: { SmartContract: { is: "CZzgUBvxaMLwMhVSLgqJn3npmxoTo6nzMNQPAnwtHF3s" } } } } ) { Block { Time } Transaction { Hash } Trade { Amount AmountInUSD Price PriceInUSD Currency { Name SmartContract Symbol } Dex { ProtocolName ProtocolFamily SmartContract } Side { Type Currency { Name SmartContract Symbol } AmountInUSD Amount } } } } } ```
## Realised PnL, buy volume, sell volume Get realised PnL, buy volume, and sell volume for a token on EVM of a trader for over a time window. [Run in Bitquery IDE](https://ide.bitquery.io/Realised-Pnl-Buy-volume-Sell-Volume-Ethereum)
One trader's realised PnL and buy and sell volume, with variables ```graphql query ($trader: String) { EVM(network: eth, dataset: combined) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x80029DBba7FA84bb16724a9fF6eE11c367D2FcfB" } } } any: [ { Trade: { Buyer: { is: $trader } } } { Trade: { Seller: { is: $trader } } } ] TransactionStatus: { Success: true } Block: { Date: { since: "2026-03-11", till: "2026-03-13" } } } ) { Trade { Currency { Name Symbol SmartContract } } buy_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Buyer: { is: $trader }, Side: { Type: { is: sell } } } } ) sell_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Seller: { is: $trader }, Side: { Type: { is: buy } } } } ) buy_volume: sum( of: Trade_Amount if: { Trade: { Buyer: { is: $trader }, Side: { Type: { is: sell } } } } ) sell_volume: sum( of: Trade_Amount if: { Trade: { Seller: { is: $trader }, Side: { Type: { is: buy } } } } ) PnL: calculate(expression: "$sell_volume_usd - $buy_volume_usd") trades: count } } } ``` ```json { "trader": "0x0a62Bd9Ee12119a5aC4807C0970fed8B71E83163" } ```
## Getting OHLC and Distinct Buys/Sells Daily OHLC, priced in WBNB, with buy and sell counts for Aave Token against WBNB on BNB Chain from 1 July to 1 August 2023. A buy is a row where `Side.Type` is `sell`; `buyers` and `sellers` count the distinct accounts that sent those swaps.
Daily candles with buy and sell counts ```graphql { EVM(dataset: archive, network: bsc) { daily: DEXTradeByTokens( limit: { count: 30 } orderBy: { descendingByField: "Block_time_field" } where: { Trade: { Side: { Currency: { SmartContract: { is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" } } Amount: { ge: "0" } } Currency: { SmartContract: { is: "0xfb6115445bff7b52feb98650c87f44907e58f802" } } PriceAsymmetry: { lt: 0.1 } } Block: { Date: { since: "2023-07-01", till: "2023-08-01" } } } ) { Block { time_field: Time(interval: { in: days, count: 1 }) } volume: sum(of: Trade_Amount) buyers: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: sell } } } } ) sellers: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: buy } } } } ) distinctTransactions: count(distinct: Transaction_Hash) total_buys: count(if: { Trade: { Side: { Type: { is: sell } } } }) total_sales: count(if: { Trade: { Side: { Type: { is: buy } } } }) total_count: count Trade { Currency { Name } Side { Currency { Name } } high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } } } } ```
## Get Least Traded Token
The 10 least traded tokens in one November 2023 week ```graphql query MyQuery { EVM(dataset: archive, network: eth) { DEXTradeByTokens( limit: { count: 10 } where: { Block: { Time: { after: "2023-11-20T00:00:00Z" before: "2023-11-27T00:00:00Z" } } } orderBy: { ascendingByField: "count" } ) { Trade { Currency { Name SmartContract } } count } } } ```
## First X Buyers of a Token The first 10 accounts to buy BLUR. Buyers of a token sit on the pool's `Sell` side, where the pool paid the token out, so the filter is on `Trade.Sell.Currency`. `Trade.Sell.Buyer` is often a router, so the buyer is `Transaction.From`.
First 10 buyers of BLUR ```graphql { EVM(dataset: archive, network: eth) { buyside: DEXTrades( limit: { count: 10 } limitBy: { by: Transaction_From, count: 1 } orderBy: { ascending: Block_Time } where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } } } ) { Block { Number Time } Transaction { From To Hash } Trade { Sell { Amount Buyer Currency { Name Symbol } Seller Price } } } } } ```
## Volume of Multiple Tokens Across Different Chains Get volume and price change data for multiple tokens trading on different chains (Solana, Ethereum, BSC, Tron) in a single query using the Trading API. Returns volume for 1h, 4h, and 24h periods, plus price change percentages for the same intervals. :::note EVM address format For **EVM chains** (Ethereum, BSC, etc.) in the Trading API, use **all lowercase addresses** in the token ID format (e.g., `bid:eth:0x...` with lowercase hex). Mixed-case addresses may not match. ::: [Run in Bitquery IDE](https://ide.bitquery.io/volume-of-a-token_1)
Volume and price change for tokens on four chains ```graphql query { TokenAsBase: Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } Price: { IsQuotedInUsd: true } Token: { Id: { in: [ "bid:solana:CZzgUBvxaMLwMhVSLgqJn3npmxoTo6nzMNQPAnwtHF3s" "bid:eth:0xfaf0cee6b20e2aaa4b80748a6af4cd89609a3d78" "bid:bsc:0xfaf0cee6b20e2aaa4b80748a6af4cd89609a3d78" "bid:tron:TXL6rJbvmjD46zeN1JssfgxvSo99qC8MRT" ] } } Market: { Protocol: { notIn: ["jupiter", "dex_solana_v3"] } } } ) { Token { Name Symbol Id } Price { Average { currentPrice: Mean(maximum: Block_Time) H1Ago: Mean( maximum: Block_Time if: { Block: { Time: { till_relative: { hours_ago: 1 } } } } ) H4Ago: Mean( maximum: Block_Time if: { Block: { Time: { till_relative: { hours_ago: 4 } } } } ) H24Ago: Mean( minimum: Block_Time if: { Block: { Time: { after_relative: { hours_ago: 24 } } } } ) } } Price_change_1h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H1Ago ) / $Price_Average_H1Ago ) * 100" ) Price_change_4h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H4Ago ) / $Price_Average_H4Ago ) * 100" ) Price_change_24h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H24Ago ) / $Price_Average_H24Ago ) * 100" ) v1h: sum( of: Volume_Usd if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) v4h: sum( of: Volume_Usd if: { Block: { Time: { since_relative: { hours_ago: 4 } } } } ) v24h: sum(of: Volume_Usd) } } } ```
--- ## Trader-Focused Trade APIs (with USD Price, Market Cap & Supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get All DEX Trades on Ethereum With Price, Market Cap, and Supply Stream **all Ethereum DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Network: Ethereum`** to capture every swap across all Ethereum DEXs in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Ethereum-with-Price-Marketcap-supply).
Subscription: Ethereum trades with USD price, market cap and supply ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Ethereum" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
### Top Traders by PnL for a Specific Pool (Last 30 Minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Program`** (the pool; for Uniswap v3, `Pair.Market.Address` is the factory and would cover every v3 pool), last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-eth-pool_1).
Ten traders with the highest PnL in one pool over 30 minutes ```graphql { Trading { Trades( limit: { count: 10 } orderBy: { descendingByField: "PnL" } where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Network: { is: "Ethereum" } Program: { is: "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
--- ## Video Tutorial | How to get Token Trade Stats for EVM chains like DexScreener shows --- ## Ethereum Trades Of An Address API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/trades-of-an-address-api/ Ethereum Trades Of An Address API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. # Address Trades API ## How do I get trades made by a specific wallet on a DEX? This GraphQL query retrieves the latest trades executed by a particular maker on the Ethereum network. You can view the query in the IDE [here](https://ide.bitquery.io/latest-trades-by-market-maker) On **EVM**, use the chain-specific **DEXTrades** cube (GraphQL: `EVM { DEXTrades }`) or **`DEXTradeByTokens`** for a token-centric view. Filter by the wallet as transaction sender or as **`Trade.Sender`** / buyer–seller fields depending on protocol. The [DEXTrades example](#latest-trades-by-address) filters `Transaction.From` on Ethereum; adjust `network`, `dataset`, and DEX filters for BSC, Base, etc. For **Solana**, see [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/). ### Stream wallet swaps on Ethereum [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api): filter **`Pair.Market.Network: Ethereum`** and **`Trader.Address`**. More examples: [Trades API](/docs/trading/crypto-trades-api/trades-api), [trader + token (IDE)](https://ide.bitquery.io/trades-of-a-specific-trader-of-a-specific-token). [Bitquery IDE](https://ide.bitquery.io) ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Ethereum" } } } Trader: { Address: { is: "0x9d6581468F04e5E55876a2660b5AeAbC12e3EFa0" } } } ) { Side Trader { Address } AmountsInUsd { Base Quote } TransactionHeader { Hash } Block { Time } Pair { Token { Symbol Address } QuoteToken { Symbol Address } } PriceInUsd } } } ``` ### Latest trades by address The query below uses the chain-specific **DEXTrades** cube on EVM (`EVM { DEXTrades }` with `network` and `dataset` for your chain). ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Transaction: {From: {is: "0x9d6581468F04e5E55876a2660b5AeAbC12e3EFa0"}}} limit: {count: 10} orderBy: {descending: Block_Number} ) { Transaction { Hash From To } Trade { Sender Buy { Buyer Seller Currency { Name SmartContract } Amount Price } Sell { Currency { Name SmartContract } Buyer Amount Seller Price } } Block { Number Time } } } } ``` **Parameters** - `limit`: retrieve only 10 trades - `orderBy`: sort the trades by Block Number in descending order - `where`: retrieve trades where the address was a maker **Returned Data** For each trade, the query retrieves the following data: - `Block`: block number and timestamp of the block in which the trade occurred. - `Transaction`: addresses of the transaction sender and receiver, and the transaction hash. - `Trade`: details of the trade, including the amount of the currency bought and sold, the buyer and seller addresses, the currency name, symbol, and smart contract address, and the price of the trade. ## Buys and Sells of a Specific Token Pair by an Address You can view the query in the IDE [here](https://ide.bitquery.io/latest_buys_and_sell_) ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Sells: DEXTrades( where: {Transaction: {From: {is: "0x9d6581468F04e5E55876a2660b5AeAbC12e3EFa0"}}, Trade: {Buy: {Currency: {SmartContract: {is: "0x7E744BBB1a49A44dfCC795014a4BA618E418FbBE"}}}, Dex: {SmartContract: {is: "0x8C13d5a6635216513EbFB4483397bE14D494aD76"}}}} limit: {count: 10} orderBy: {descending: Block_Number} ) { Transaction { Hash From To } Block{ Time Number } Trade { Sender Buy { Buyer Seller Currency { Name SmartContract } Amount } } } Buys: DEXTrades( where: {Transaction: {From: {is: "0x9d6581468F04e5E55876a2660b5AeAbC12e3EFa0"}}, Trade: {Sell: {Currency: {SmartContract: {is: "0x7E744BBB1a49A44dfCC795014a4BA618E418FbBE"}}}, Dex: {SmartContract: {is: "0x8C13d5a6635216513EbFB4483397bE14D494aD76"}}}} limit: {count: 10} orderBy: {descending: Block_Number} ) { Transaction { Hash From To } Block{ Time Number } Trade { Sell { Buyer Seller Currency { Name SmartContract } Amount } } } } } ``` The "EVM" field contains two sub-queries: "Buys" and "Sells." The "Buys" sub-query retrieves the 10 most recent trades where the specified address was the maker and the token was purchased. The "Sells" sub-query retrieves the 10 most recent trades where the specified address was the maker and the token was sold. **Parameters** - `limit`: retrieve only 10 trades - `orderBy`: sort the trades by Block_Number in descending order - `where`: retrieve trades where the maker address matches "0x9d6581468F04e5E55876a2660b5AeAbC12e3EFa0" and token SmartContract and pair address is "0x7E744BBB1a49A44dfCC795014a4BA618E418FbBE" and "0x8C13d5a6635216513EbFB4483397bE14D494aD76" respectively **Returned Data** For each trade, the query retrieves the following data: - `Block`: block number and timestamp of the block in which the trade occurred. - `Transaction`: The sender, reciever and the transaction hash - `Trade`: details of the trade, including the amount of the currency bought and sold, the buyer and seller addresses, the currency name, symbol, and smart contract address, and the price of the trade. ## Subscribe to latest trades for a given address You can check this query [here](https://ide.bitquery.io/Real-time-trades-of-an-ethereum-address). ```graphql subscription { EVM(network: eth) { DEXTrades( orderBy: { descending: Block_Time } where: { any: [ { Trade: { Buy: { Buyer: { is: "0x152a04d9fde2396c01c5f065a00bd5f6edf5c88d" } } } } { Trade: { Buy: { Seller: { is: "0x152a04d9fde2396c01c5f065a00bd5f6edf5c88d" } } } } { Transaction: { From: { is: "0x152a04d9fde2396c01c5f065a00bd5f6edf5c88d" } } } ] } ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price } Sell { Amount Currency { Name SmartContract Symbol } Price } } } } } ``` ## Trades Where the Address is Buyer OR Seller The below query gives you trades where the specified address is either as a buyer or a seller. This is achieved by utilizing the `any` filter, which acts as an OR condition to encompass both buyer and seller roles in the results. You can find the query [here](https://ide.bitquery.io/Address-is-Buyer-or-Seller-V2) ```graphql query MyQuery { EVM(dataset: archive, network: eth) { DEXTrades( where: {any: [{Trade: {Buy: {Buyer: {is: "0xacefce78e31332cf2d1b9e770d609c31d26afc09"}}}}, {Trade: {Buy: {Seller: {is: "0xacefce78e31332cf2d1b9e770d609c31d26afc09"}}}}]} limit: {count: 10} orderBy: {descending: Block_Time} ) { Trade { Buy { Buyer Amount Currency { Name } } Dex { ProtocolName } Sell { Buyer Price Currency { Name } } } Transaction { Hash } } } } ``` ## Top Trader for a given token for a pair (Trade's PnL analysis) To get top traders of a given token and analyze their profit and loss, you can use the following query. Run this query [using this link](https://ide.bitquery.io/Top-traders-in-eth_1). ```graphql query TopTraders($token: String) { EVM(network: eth, dataset: combined) { DEXTradeByTokens( orderBy: {descendingByField: "volume"} limit: {count: 20} where: {Trade: {Currency: {SmartContract: {is: $token}}}, TransactionStatus: {Success: true}} ) { Transaction { From } Trade { Dex { ProtocolName ProtocolFamily } Currency { Symbol Name SmartContract } Side { Currency { Name Symbol SmartContract } } } bought: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} selectWhere: {gt: "0"} ) sold: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} selectWhere: {gt: "0"} ) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } variables: { "token": "0xC90242Cd9959b7Be6EC01B5e99702Ee21161f3Ad" } ``` ## Total Volume, Buy Volume, Sell Volume, and PnL for a Trader on a Specific Token This query returns comprehensive trading statistics for a specific trader's activity on a particular token, including total volume, buy/sell volumes in both token amounts and USD, trade counts, and PnL calculations over the last 24 hours. You can run this query [here](https://ide.bitquery.io/total-volume-buy-volume-sell-volume-PnL). ```graphql query MyQuery($trader: String, $token: String) { EVM(dataset: combined, network: eth) { DEXTradeByTokens( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Trade: { Currency: { SmartContract: { is: $token } } } Transaction: { From: { is: $trader } } } ) { Block { last_active_time: Time(maximum: Block_Time) } total_volume: sum(of: Trade_Amount) buy_volume: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) sell_volume: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) total_volume_usd: sum(of: Trade_Side_AmountInUSD) sell_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) total_buys: count( distinct: Transaction_Hash if: { Trade: { Side: { Type: { is: sell } } } } ) total_sells: count( distinct: Transaction_Hash if: { Trade: { Side: { Type: { is: buy } } } } ) PnL_usd: calculate(expression: "$sell_volume_usd - $buy_volume_usd") } } } ``` ```json { "token": "0xacba65D610B066443CB211E120835315361e4FCA", "trader": "0x782c362fbf71f939445e6902a064f7e9384f47e2" } ``` --- ## Ethereum Trading Pairs API: Every Pool a Token Trades In URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/get-trading-pairs-of-token/ Every trading pair of an Ethereum token with Bitquery GraphQL: pools across DEXs, pools on one protocol, pair stats, reserves, the tokens behind a pool. # Ethereum Trading Pairs API: Every Pool a Token Trades In A token trades in many places at once: a Uniswap v3 pool against WETH, a v2 pair, a v4 pool, maybe a Curve or Balancer pool. To follow all of its trading you first need that list, and the `DEXTradeByTokens` cube produces it in one query, because every swap is stored once per token with the other token and the pool alongside. From there a pair's stats, a pool's reserves and the two tokens behind a pool address are each one more query. Every example runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. The worked token is BLUR, `0x5283d291dbcf85356a21ba090e6db59121208b44`, whose pools are spread across Uniswap v2, v3 and v4. ## Every pair of a token across all DEXs Group by the other token and the pool over a month on the `combined` dataset. Each row is one pool with its protocol, trade count and USD volume in the window. Saved query [here](https://ide.bitquery.io/Pair-tokens-for-BLUR-token-for-all-DEXs_1). ```graphql { EVM(dataset: combined, network: eth) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } Block: { Time: { since_relative: { days_ago: 30 } } } } orderBy: { descendingByField: "trades" } limit: { count: 50 } ) { Trade { Side { Currency { Symbol SmartContract } } Dex { ProtocolName SmartContract } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` `Dex.SmartContract` is the pool for v2 and v3 pairs and the PoolManager for Uniswap v4, where pools are told apart by `Trade.PoolId` instead. ## The pairs on one protocol Add the protocol name to the filter. The saved query used the Uniswap v3 factory as an owner filter; the protocol name does the same with less to remember. Saved query [here](https://ide.bitquery.io/pairs-of-blur-token-new-dataset_1). ```graphql { EVM(dataset: combined, network: eth) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } Dex: { ProtocolName: { is: "uniswap_v3" } } } Block: { Time: { since_relative: { days_ago: 30 } } } } orderBy: { descendingByField: "trades" } limit: { count: 20 } ) { Trade { Side { Currency { Symbol SmartContract } } Dex { SmartContract } } trades: count } } } ``` ## Stats of one pair Fix both tokens and a window: trades, distinct buyers and sellers, USD volume, and how much of the token was bought and sold. `Side.Type` describes the counter-side of each trade, so the token was bought where the side was sold, which is why the two conditions look reversed. ```graphql { EVM(network: eth, dataset: combined) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } Side: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { trades: count buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Reserves of a pool A pool's reserves are its token balances. The `Balances` cube returns them for the pool address; the example is the Uniswap v3 USDC/USDT pool, `0x7858E59e0C01EA06Df3aF3D20aC7B0003275D4Bf`. Saved query [here](https://ide.bitquery.io/liquidity-of-token-pair-on-ethereum). ```graphql { EVM(dataset: combined, network: eth) { Balances( where: { Balance: { Address: { is: "0x7858E59e0C01EA06Df3aF3D20aC7B0003275D4Bf" } } Currency: { SmartContract: { in: [ "0xdAC17F958D2ee523a2206206994597C13D831ec7" "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" ] } } } orderBy: { descending: Balance_Amount } ) { Currency { Symbol SmartContract } Balance { Amount } } } } ``` For reserves that update on every swap with USD values and spot prices, use the [DEXPools cube](/docs/cubes/evm-dexpool/). ## The two tokens behind a pool address One trade from the pool names both sides. Saved query [here](https://ide.bitquery.io/tokens-in-a-given-pair-token). ```graphql { EVM(dataset: combined, network: eth) { DEXTrades( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Dex: { SmartContract: { is: "0x7858E59e0C01EA06Df3aF3D20aC7B0003275D4Bf" } } } } ) { Trade { Dex { ProtocolName } Buy { Currency { Symbol SmartContract } } Sell { Currency { Symbol SmartContract } } } } } } ``` ## Related pages - [Ethereum DEX trades API](/docs/blockchain/Ethereum/dextrades/dex-api) - [Uniswap v4 on Ethereum](/docs/blockchain/Ethereum/dextrades/uniswap-v4-api) - [DEXPools cube](/docs/cubes/evm-dexpool/) - [Balances and Holders cubes](/docs/cubes/balances-cube) --- ## Ethereum Transaction Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-transaction-balance-tracker/ Ethereum Transaction Balance Tracker: stream Ethereum balance changes with reason codes using Bitquery GraphQL subscriptions. # Ethereum Transaction Balance Tracker The Ethereum Transaction Balance Tracker API provides real-time balance updates for all addresses involved in transactions on the Ethereum blockchain, including detailed information about the reason for each balance change. ## Subscribe to All Transaction Balances This subscription provides real-time balance updates for all addresses involved in transactions on the Ethereum network. Try the API [here](https://ide.bitquery.io/Subscribe-to-All-Transaction-Balances). ```graphql subscription { EVM(network: eth) { TransactionBalances { Block { Time } TokenBalance { Currency { Symbol HasURI SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode TotalSupplyInUSD TotalSupply TokenOwnership { Owns Id } PostBalanceInUSD } Transaction { Hash } } } } ``` ## Subscribe to Transaction Balances for a Specific Address This subscription filters transaction balances for a specific address. Try the API [here](https://ide.bitquery.io/Subscribe-to-Transaction-Balances-for-a-Specific-Address). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xYourAddressHere" } } } ) { Block { Time } TokenBalance { Currency { Symbol HasURI SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode TotalSupplyInUSD TotalSupply TokenOwnership { Owns Id } PostBalanceInUSD } Transaction { Hash } } } } ``` ## Latest native balance of an address This API gives you latest balance of a specific address (here in example `0xd194daef0cd90675a3b823fcda248f76fccb49f3`) for the native currency. Try it out [here](https://ide.bitquery.io/Latest-native-balance-of-an-address). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0xd194daef0cd90675a3b823fcda248f76fccb49f3" } Currency: { Native: true } } } ) { Block { Time } TokenBalance { Currency { Symbol HasURI SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode TotalSupplyInUSD TotalSupply TokenOwnership { Owns Id } PostBalanceInUSD } Transaction { Hash } } } } ``` ## Latest balance of an address for a specific token This API gives you latest balance of a specific address (here in example `0xd194daef0cd90675a3b823fcda248f76fccb49f3`) for a specific token (here we have taken example of USDC `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`). Try it out [here](https://ide.bitquery.io/Latest-balance-of-an-address-for-a-specific-token). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Address: { is: "0xd194daef0cd90675a3b823fcda248f76fccb49f3" } Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } } } ) { Block { Time } TokenBalance { Currency { Symbol HasURI SmartContract } PreBalance PostBalance Address BalanceChangeReasonCode TotalSupplyInUSD TotalSupply TokenOwnership { Owns Id } PostBalanceInUSD } Transaction { Hash } } } } ``` ## Latest liquidity of EVM Pool This API provides the latest liquidity information for multiple EVM pools in one API call. The example shows results for two pool addresses using a query updated to support multiple addresses. You can try 500 as well,just put them as a list in `where` clause. Try it out [here](https://ide.bitquery.io/latest-liquidity-of-multiple-pools#). ```graphql { EVM(network: base) { TransactionBalances( limitBy: { by: TokenBalance_Address, count: 2 } orderBy: { descendingByField: "TokenBalance_PostBalanceInUSD" } where: { TokenBalance: { Address: { in: [ "0x3f0296BF652e19bca772EC3dF08b32732F93014A" "0x22AEe3699b6A0fEd71490C103Bd4E5f3309891D5" ] } } } ) { TokenBalance { Currency { Symbol HasURI SmartContract } PostBalance(maximum: Block_Time) PostBalanceInUSD(maximum: Block_Time) Address } } } } ``` ## Latest Supply and Marketcap of a specific token on EVM This API gives you latest Supply and Marketcap of a token on EVM (here as example we have taken BITGET Token `0x54D2252757e1672EEaD234D27B1270728fF90581` ). Try it out [here](https://ide.bitquery.io/Total-Supply-and-onchain-Marketcap-of-a-specific-token). ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Currency: { SmartContract: { is: "0x54D2252757e1672EEaD234D27B1270728fF90581" } } } } ) { Block { Time Number } TokenBalance { Currency { Symbol HasURI SmartContract } TotalSupplyInUSD TotalSupply } } } } ``` --- ## Ethereum Transaction Balance Tracker API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/ Ethereum Transaction Balance Tracker API: stream Ethereum balance changes with reason codes using Bitquery GraphQL subscriptions. # Ethereum Transaction Balance Tracker API - Complete Guide ## What is Transaction Balance Tracker? The **Ethereum Transaction Balance Tracker API** provides real-time balance updates for all addresses involved in transactions on the Ethereum blockchain. Unlike traditional balance APIs that only show current balances, our Transaction Balance Tracker captures every balance change with detailed information about the reason for each change, making it perfect for building comprehensive transaction monitoring, portfolio tracking, and blockchain analytics applications. Our Transaction Balance Tracker APIs track balance changes across different scenarios including regular transactions, validator rewards, miner rewards, MEV activities, and contract self-destruct events. Each balance change is enriched with reason codes, pre/post balances, USD values, and transaction context. ## Key Features - **Real-time Balance Updates**: Stream balance changes as they happen via GraphQL subscriptions - **Balance Change Reason Codes**: Understand why each balance changed (transfers, rewards, gas, self-destruct, etc.) - **Comprehensive Coverage**: Track native ETH, ERC-20 tokens, ERC-721, and ERC-1155 NFTs - **Recent History**: The API holds a recent realtime window for this cube. For older balance changes, record the stream or ask about a [Data Store export](https://bitquery.io/datastore) - **USD Values**: Get balance values in USD for portfolio tracking and analytics - **Multiple Use Cases**: Monitor validators, miners, MEV bots, self-destruct events, and more ## Getting Started New to Transaction Balance Tracker? Here's how to get started: 1. **[Create a free account](https://ide.bitquery.io/)** - Get instant access to our GraphQL IDE 2. **[Generate your API key](/docs/authorization/how-to-generate/)** - Required for API access 3. **[Run your first query](/docs/start/first-query/)** - Learn the basics in 5 minutes 4. **[Explore examples](#ethereum-transaction-balance-tracker-apis)** - Copy-paste ready queries below Need help crafting a query or subscription? Message us on [support](https://t.me/Bloxy_info). ## How is it different from regular Balance APIs? - Real-time streaming of all balance changes - Pre/post balance values for every change - Balance change reason codes explain why balance changed - Track all addresses in transactions automatically - A recent realtime window via the API; older changes by recording the stream or through a Data Store export - Support for native currency, tokens, and NFTs ## Real-time Data & Streaming Get live Ethereum balance updates through our streaming solutions: - **GraphQL Subscriptions**: Convert any query to a live stream by changing `query` to `subscription` - **Kafka Streaming**: High-throughput streaming for enterprise applications See examples and code snippets [here](/docs/subscriptions/websockets/) for GraphQL subscription implementation, and learn about [Kafka streaming](/docs/streams/kafka-streaming-concepts/) for high-volume use cases. ## Ethereum Transaction Balance Tracker APIs ### [Ethereum Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-transaction-balance-tracker) The core Transaction Balance Tracker API provides real-time balance updates for all addresses involved in transactions on the Ethereum network, including detailed information about the reason for each balance change. Track native ETH, ERC-20 tokens, and NFTs with pre/post balances, USD values, and balance change reason codes. **Key Features:** - Subscribe to all transaction balances in real-time - Filter by specific addresses or tokens - Get balance change reason codes for native currency - Track ERC-20, ERC-721, and ERC-1155 tokens - Access pre and post balance values ### [Ethereum Transaction Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-transfer-balance-tracker) Transfer Balance Tracker API provides real-time balance updates for all addresses involved in transfer of Native Currency on the Ethereum network. **Key Features:** - Subscribe to all transfer balances in real-time - Filter by specific addresses - Access pre and post balance values ### [Ethereum Validator Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-validator-balance-tracker) Track Ethereum validator balances, staking rewards, and withdrawals from the beacon chain. Monitor validator activity including block rewards, withdrawal events, and transaction fee rewards. **Key Features:** - Track validator staking rewards (Code 2) - Monitor beacon chain withdrawals (Code 3) - Track transaction fee rewards (Code 5) - Filter by specific validator addresses - Real-time validator balance updates ### [Ethereum Gas Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-gas-balance-tracker) Track Ethereum balance changes for gas burn, unused gas returned for unused gas at the end of execution, and transaction tips. **Key Features:** - Track transaction tips (Code 5) - Track gas burnt (Code 6) - Track gas returned for unused gas at the end of execution (Code 7) ### [Ethereum Miner Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-miner-balance-tracker) Monitor Ethereum miner balances, mining rewards, uncle block rewards, and transaction fee rewards. Track historical and real-time mining activity across the Ethereum network. **Key Features:** - Track block mining rewards (Code 2) - Monitor uncle block rewards (Code 1) - Track transaction fee rewards (Code 5) - Filter by specific miner addresses - Historical mining reward data ### [Ethereum MEV Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-mev-balance-tracker) Track MEV (Maximal Extractable Value) related balance changes including transaction fee rewards, block builder rewards, and other MEV extraction activities. Monitor MEV bots and block builders in real-time. **Key Features:** - Track transaction fee rewards (Code 5) - Monitor block builder rewards - Filter by MEV bot or builder addresses - Track large MEV transactions - Aggregate MEV reward statistics ### [Ethereum Self-Destruct Balance Tracker](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-self-destruct-balance-api) Monitor contract self-destruct events, ephemeral contracts (like MEV bots), and security incidents. Track contracts that self-destruct and addresses that receive funds from self-destructed contracts. **Key Features:** - Track contract self-destruct events (Codes 12, 13, 14) - Monitor ephemeral MEV contracts - Track MEV builder payments - Security incident monitoring - Aggregate self-destruct statistics ### [Ethereum Token Balance API](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/token-balance-api) Track ERC-20 fungible token balances, total supply, and market capitalization for any address on Ethereum. Monitor token holdings, portfolio values, and token balance changes in real-time. **Key Features:** - Get latest token balance for an address - Retrieve all token balances for an address - Track token balance history over time - Get token total supply and market cap - Filter tokens by minimum balance threshold - Stream token balance updates in real-time - Monitor token balance changes by transaction ### [Ethereum NFT Balance API](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/nft-balance-api) Track ERC-721 and ERC-1155 non-fungible token balances, ownership, and token IDs for any address on Ethereum. Monitor NFT collections, ownership changes, and specific token ownership in real-time. **Key Features:** - Get latest NFT balance for an address - Retrieve all NFT collections for an address - Get NFT owner for specific token ID - Track NFT ownership history - Get NFT balances for multiple addresses - Stream NFT balance updates in real-time - Monitor NFT balance changes by collection ## Balance Change Reason Codes The Transaction Balance Tracker API uses numeric codes to indicate why a balance changed. These codes are only available for native currency (ETH) transactions, not for fungible tokens or NFTs. | **Code** | **Reason** | **Description** | | -------- | ----------------------------------- | -------------------------------------------------------------------------- | | 0 | BalanceChangeUnspecified | Unspecified balance change reason | | 1 | BalanceIncreaseRewardMineUncle | Reward for mining an uncle block | | 2 | BalanceIncreaseRewardMineBlock | Reward for mining a block | | 3 | BalanceIncreaseWithdrawal | ETH withdrawn from the beacon chain | | 4 | BalanceIncreaseGenesisBalance | ETH allocated at the genesis block | | 5 | BalanceIncreaseRewardTransactionFee | Transaction tip increasing block builder's balance | | 6 | BalanceDecreaseGasBuy | ETH spent to purchase gas for transaction execution | | 7 | BalanceIncreaseGasReturn | ETH returned for unused gas at the end of execution | | 8 | BalanceIncreaseDaoContract | ETH sent to the DAO refund contract | | 9 | BalanceDecreaseDaoAccount | ETH taken from a DAO account to be moved to the refund contract | | 10 | BalanceChangeTransfer | ETH transferred via a call | | 11 | BalanceChangeTouchAccount | Transfer of zero value to touch-create an account | | 12 | BalanceIncreaseSelfdestruct | Balance added to the recipient as indicated by a self-destructing account | | 13 | BalanceDecreaseSelfdestruct | Balance deducted from a contract due to self-destruct | | 14 | BalanceDecreaseSelfdestructBurn | ETH sent to an already self-destructed account within the same transaction | | 15 | BalanceChangeRevert | Balance reverted back to a previous value due to call failure | ## Field Availability by Currency Type The availability of fields in the `TokenBalance` object depends on the type of currency being tracked: ### Native Currency (ETH) - **Available**: `BalanceChangeReasonCode`, `PreBalance`, `PostBalance`, `PostBalanceInUSD` - **Not Provided**: `TotalSupply`, `TokenOwnership` ### Fungible Tokens (ERC-20) - **Available**: `PostBalance`, `PostBalanceInUSD`, `TotalSupply`, `TotalSupplyInUSD` - **Not Provided**: `PreBalance`, `BalanceChangeReasonCode`, `TokenOwnership` ### NFTs (ERC-721 / ERC-1155) - **Available**: `PostBalance`, `TokenOwnership` - **Not Provided**: `PreBalance`, `BalanceChangeReasonCode`, `TotalSupply`, `TotalSupplyInUSD`, `PostBalanceInUSD` --- ## Ethereum Transfer Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-transfer-balance-tracker/ Ethereum Transfer Balance Tracker: monitor Ethereum native and token transfers in real time with Bitquery GraphQL APIs. See examples in the Bitquery IDE. # Ethereum Transfer Balance Tracker The Ethereum Transfer Balance Tracker API provides real-time balance updates for all addresses involved in Transfers on the Ethereum blockchain, and provides option to filter out based on the direction of transfer you want to target. The Ethereum Transfer Balance is tracked by marking the the `BalanceUpdateReason` equals `10`. :::note The queries covered this section are only valid for the Native Currency Transfer. ::: ## Get Balance Info for an Address after Transfer [This](https://ide.bitquery.io/balance-update-from-transfer-for-an-address#) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a particular address after a transfer, irrespective of the direction of transfer.
Click here to expand ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e"}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Stream Balance Info for Transfer in Real Time [This](https://ide.bitquery.io/balance-update-from-transfer-for-an-address--stream#) subscription allows us to stream Balance Updates for an address due to transfer in Real Time.
Click here to expand ```graphql subscription { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e"}}} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Get Balance Info for Multiple Addresses after Transfer [This](https://ide.bitquery.io/balance-update-from-transfer-for-multiple-addresses#) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a list of addresses after a transfer, irrespective of the direction of transfer.
Click here to expand ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {in: ["0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e", "0x5b43453fce04b92e190f391a83136bfbecedefd1"]}}} orderBy: {descending: Block_Time} limitBy: {by:TokenBalance_Address count: 1} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Stream Balance Update due to Transfer for Multiple Addresses in Real Time [This](https://ide.bitquery.io/balance-update-from-transfer-for-multiple-addresses--stream#) subscription allows us to stream Balance Updates for a list of addresses due to transfer in Real Time.
Click here to expand ```graphql subscription { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {in: ["0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e", "0x5b43453fce04b92e190f391a83136bfbecedefd1"]}}} ) { Block { Time } TokenBalance { PostBalance PostBalanceInUSD PreBalance PreBalanceInUSD } amt: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) amt_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) Transaction { From To } } } } ```
## Get Balance Info for an Address after Transfer Sent [This](https://ide.bitquery.io/Balance-update-after-transfer-sent_2) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a particular address after it sends a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {is: "0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e"}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Transfer Sent in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-sent--stream_3) subscription allows us to stream Balance Updates for a transfer sent by an address in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {is: "0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e"}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Info for Multiple Addresses after Transfer Sent [This](https://ide.bitquery.io/Balance-update-after-transfer-sent-from-multiple-addresses) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a list of addresses after they send a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {in: ["0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e", "0x5b43453fce04b92e190f391a83136bfbecedefd1"]}}} orderBy: {descending: Block_Time} limitBy: {by:Transaction_From count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Multiple Addresses for Transfer Sent in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-sent-from-multiple-addresses--stream#) subscription allows us to stream Balance Updates for a list of addresses due to transfer sent in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {From: {in: ["0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e", "0x5b43453fce04b92e190f391a83136bfbecedefd1"]}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Info for an Address after Transfer Recieved [This](https://ide.bitquery.io/Balance-update-after-transfer-received_1) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a particular address after it recieves a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {is: "0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e"}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Transfer Recieved in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-received--stream) subscription allows us to stream Balance Updates for a transfer recieved by an address in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {is: "0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e"}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Info for Multiple Addresses after Transfer Recieved [This](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses_2) query returns the Balance Info such as PreBalance, PostBalance, Balances in USD and transfer amount for a list of addresses after they recieve a transfer.
Click here to expand ```graphql query MyQuery { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {in: ["0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e", "0x5b43453fce04b92e190f391a83136bfbecedefd1"]}}} orderBy: {descending: Block_Time} limitBy: {by:Transaction_To count: 1} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Stream Balance Info for Multiple Addresses for Transfer Recieved in Real Time [This](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses--stream) subscription allows us to stream Balance Updates for a list of addresses due to transfer recieved in Real Time.
Click here to expand ```graphql subscription { EVM { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}}, Transaction: {To: {in: ["0xafd8cd311c7bf2635573ebebb97c1a3c7e90f00e", "0x5b43453fce04b92e190f391a83136bfbecedefd1"]}}} ) { Block{ Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction{ From To Hash } amount:calculate(expression: "$TokenBalance_PreBalance - $TokenBalance_PostBalance") amount_usd:calculate(expression: "$TokenBalance_PreBalanceInUSD - $TokenBalance_PostBalanceInUSD") } } } ```
## Get Balance Updates for the Last 24 hours Use [this](https://ide.bitquery.io/Balance-Updates-for-transfer-in-last-24-hours) API endpoint for getting Balance Updates due to Transfers for a particular address irrespective of the direction of Transfer. This could be used in applications that maintains a record for a wallet.
Click here to expand ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {is: "0xdadb0d80178819f2319190d340ce9a924f783711"}}, Block: {Time: {since_relative: {hours_ago: 24}}}} orderBy: {descending: Block_Time} ) { Block { Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction { From To Hash } transfer_amount: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) transfer_amount_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ```
## Get Balance Updates for the Last 24 hours Use [this](https://ide.bitquery.io/Balance-Updates-for-multiple-addresses-transfer-in-last-24-hours) API endpoint for getting Balance Updates due to Transfers for a list of addresses irrespective of the direction of Transfer. This could be used in Dashboard Applications that shows record for multiple wallets.
Click here to expand ```graphql query MyQuery { EVM(network: eth) { TransactionBalances( where: {TokenBalance: {BalanceChangeReasonCode: {eq: 10}, Address: {in: ["0xdadb0d80178819f2319190d340ce9a924f783711", "0x396343362be2a4da1ce0c1c210945346fb82aa49"]}}, Block: {Time: {since_relative: {hours_ago: 24}}}} orderBy: {descending: Block_Time} ) { Block { Time } TokenBalance { PreBalance PostBalance PreBalanceInUSD PostBalanceInUSD } Transaction { From To Hash } transfer_amount: calculate( expression: "$TokenBalance_PostBalance - $TokenBalance_PreBalance" ) transfer_amount_usd: calculate( expression: "$TokenBalance_PostBalanceInUSD - $TokenBalance_PreBalanceInUSD" ) } } } ```
--- ## Ethereum Uniswap API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/uniswap-api/ Query Uniswap v1-v4 on Ethereum with Bitquery GraphQL: real-time trades, TradingView-ready OHLC streams across chains, per-pair trades and top traders. # Uniswap API Uniswap is a decentralized exchange on Ethereum for trading ERC-20 tokens. Bitquery’s APIs support Uniswap trades, pool creations, and active user metrics across v1, v2, v3 and v4 in real-time and across archive data since genesis. :::tip Real-time data or the last 30 days? Use the Trading cube For real-time trades and anything from the last 30 days, use the [Trading cube](/docs/trading/trading-data-overview): [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns MEV-filtered swaps with a USD price on every row. Use the `EVM` queries on this page for raw per-swap detail or call and event context. An `EVM` query without a `dataset` argument runs on the realtime dataset, which holds only the last few days; add `dataset: combined` or `dataset: archive` for older history. ::: The same schema powers our multi-chain [DEX API](https://bitquery.io/products/dex), so these queries also run on other EVM exchanges, such as PancakeSwap or SushiSwap, once you change the DEX filter. For Uniswap v3 positions, see the [Uniswap position API examples](/docs/blockchain/Ethereum/dextrades/uniswap-position-api/) You can also explore Uniswap APIs on other chains: - [BNB Smart Chain](/docs/blockchain/BSC/bsc-uniswap-api/) - [Base](/docs/blockchain/Base/base-uniswap-api/) - [Polygon](/docs/blockchain/Matic/matic-uniswap-api/) ## Uniswap contract addresses on Ethereum Core contracts on Ethereum mainnet. Every address below was read from indexed mainnet logs rather than copied from a reference, and each one is the contract that actually emits the events in the next table. | Version | Contract | Address | | --- | --- | --- | | v2 | Factory | `0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f` | | v3 | Factory | `0x1f98431c8ad98523631ae4a59f267346ea31f984` | | v3 | NonfungiblePositionManager | `0xc36442b4a4522e871399cd717abdd847ab11fe88` | | v4 | PoolManager (singleton) | `0x000000000004444c5dc75cb358380d2e3de08a90` | | v4 | PositionManager | `0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e` | ## Uniswap event signatures and topic0 hashes `topic0` is the first log topic, the keccak-256 hash of the event signature. Use it to match raw logs when you are reading them outside Bitquery's decoded schema. | Version | Event | Signature | topic0 | | --- | --- | --- | --- | | v2 | PairCreated | `PairCreated(address,address,address,uint256)` | `0x0d3648bd0f6ba80134a33ba9275ac585d9d315f0ad8355cddefde31afa28d0e9` | | v2 | Swap | `Swap(address,uint256,uint256,uint256,uint256,address)` | `0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822` | | v3 | PoolCreated | `PoolCreated(address,address,uint24,int24,address)` | `0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118` | | v3 | Swap | `Swap(address,address,int256,int256,uint160,uint128,int24)` | `0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67` | | v4 | Initialize | `Initialize(bytes32,address,address,uint24,int24,address,uint160,int24)` | `0xdd466e674ea557f56295e2d0218a125ea4b4f0f6f3307b95f85e6110838d6438` | | v4 | Swap | `Swap(bytes32,address,int128,int128,uint160,uint128,int24,uint24)` | `0x40e9cecb9f5f1f1c5b9c97dec2917b7ee92e57ba5563708daca94dd84ad7112f` | | v4 | ModifyLiquidity | `ModifyLiquidity(bytes32,address,int24,int24,int256,bytes32)` | `0xf208f4912782fd25c7f114ca3723a2d5dd6f3bcc3ac8db5af63baa85f711d5ec` | ### A topic0 does not identify Uniswap The v2 and v3 contracts are the most forked code on Ethereum, and a fork keeps the ABI, so it keeps the hash. Matching logs on topic0 alone gives you every fork as well as Uniswap. SushiSwap's factory at `0xc0aee478e3658e2610c5f7a4a2e1777ce9e4f2ac` emits exactly the `PairCreated` signature and topic0 in the table above. On the v3 side, at least four other Ethereum factories emitted the identical `PoolCreated` in the last 30 days. Any indexer keyed on topic0 alone will report those as Uniswap. To isolate Uniswap's own pools, pair the topic0 with the factory that created them, listed in the first table. ### Filter decoded trades by factory Bitquery's decoded trades have the same catch. `Trade.Dex.ProtocolName` records which code a pool runs, and a fork runs the same code, so `uniswap_v2` also returns SushiSwap and the other v2 forks. In Bitquery's trade data for 18 September 2026, 21% of Ethereum transactions carrying a `uniswap_v2` trade touched another factory's pools, and SushiSwap's factory was in about three in five of those. Count trades rather than transactions and the share rises to 26%, because a routed swap can touch a Uniswap pool and a fork in the same transaction. The `uniswap_v3` label is cleaner, under 2%, and every `uniswap_v4` trade came from the PoolManager. To keep only Uniswap's own pools, filter on the contract that owns them: | Version | Field | Value on Ethereum | | --- | --- | --- | | v2 | `Trade.Dex.OwnerAddress` | `0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f` | | v3 | `Trade.Dex.OwnerAddress` | `0x1f98431c8ad98523631ae4a59f267346ea31f984` | | v4 | `Trade.Dex.SmartContract` | `0x000000000004444c5dc75cb358380d2e3de08a90` | `OwnerAddress` is the factory that deployed the pool. v4 pools have no factory, so their `OwnerAddress` is the zero address and the PoolManager is the `SmartContract`. In the Trading cube, the same contracts are `Market.Address` (the v2 or v3 factory) and `Market.Program` (the v4 PoolManager). The [active traders query](#active-traders-on-uniswap-in-the-last-7-days) below uses the v3 filter. ### Two more differences worth knowing In v2 and v3 the `Swap` event is emitted by the pair or pool contract itself, so the pool is identified by the log's own address, and mainnet has thousands of distinct emitters. In v4 every pool lives inside the one PoolManager, so every v4 `Swap` log carries the same emitter address and the pool is identified by the `bytes32` PoolId in the event's first argument. Filtering v4 swaps by a pool address does not work; filter by PoolId. Liquidity positions are represented differently in each version. v2 gives a depositor fungible ERC-20 LP tokens minted by the pair itself. v3 and v4 both issue an ERC-721: one `tokenId` per position, from the NonfungiblePositionManager in v3 and the PositionManager in v4. Where they differ is which contract reports the liquidity change. The v3 manager emits `IncreaseLiquidity`, `DecreaseLiquidity` and `Collect` itself, so the position lifecycle is readable from that one contract. The v4 PositionManager emits no liquidity events. Its logs on Ethereum are the ERC-721 `Transfer`, `Approval` and `ApprovalForAll`, and the liquidity change is emitted by the PoolManager as `ModifyLiquidity`. Reading a v4 position therefore means joining the NFT to the PoolManager's events by PoolId. ## Realtime Uniswap v1, v2, v3, v4 Trades Track live trades across all Uniswap versions: [Run Stream](https://ide.bitquery.io/uniswap-all-versions-trades-stream_1) The stream filters on `ProtocolName`, so it also returns forks such as SushiSwap. To keep only Uniswap's own pools, use the filters in [Filter decoded trades by factory](#filter-decoded-trades-by-factory).
Click to expand GraphQL subscription ```graphql subscription { EVM(network: eth) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { in: ["uniswap_v4", "uniswap_v3", "uniswap_v2", "uniswap_v1"] } } } } ) { Block { Number Time } Transaction { From To Hash } Trade { Dex { Delegated DelegatedTo OwnerAddress Pair { Decimals Name SmartContract } ProtocolFamily ProtocolName ProtocolVersion SmartContract } Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price } Sell { Amount Buyer Currency { Name SmartContract Symbol } Seller Price } } } } } ```
## TradingView OHLC Stream on Uniswap Across Chains The new [Price Index Stream](/docs/trading/crypto-price-api/) helps you get token-level, pair-level, and market-level OHLC data for 1 sec interval( or higher), in real-time across all chains. These also include trading metrics like SMA, EMA, VWAP, and more. The `Market.Protocol` filter matches forks as well. In the Trading cube, PancakeSwap V2 on BNB Chain, QuickSwap on Polygon and SushiSwap on Ethereum all carry the `uniswap_v2` label. To keep Uniswap's own pools, filter `Market.Address` to the v2 or v3 factory, or `Market.Program` to the v4 PoolManager. The addresses differ by chain; Ethereum's are in [Filter decoded trades by factory](#filter-decoded-trades-by-factory). [Run Stream](https://ide.bitquery.io/Stream-all-Uniswap-Seconds-OHLC-Kline_1)
{" "} Click to expand GraphQL query ```graphql subscription { Trading { Pairs( where: {Market: {Protocol: {in: ["uniswap_v4","uniswap_v3", "uniswap_v2", "uniswap_v1"]}}, Interval: {Time: {Duration: {eq: 1}}}} ) { Currency { Name Id } Market { Name NetworkBid Network Address } Price { IsQuotedInUsd Average { Mean } } QuoteCurrency { Id Symbol Name } QuoteToken { Symbol Name Id NetworkBid Network Did Address } Token { Name Id NetworkBid } } } } ```
## Latest Trades of a Pair on Uniswap Retrieve the 50 most recent WETH/USDC trades in pools labelled Uniswap v1–v4, forks included, [Run query](https://ide.bitquery.io/Latest-Trades-of-a-Pair-on-Uniswap). Add the [factory filters](#filter-decoded-trades-by-factory) to keep Uniswap's own pools only:
Click to expand GraphQL query ```graphql query LatestTrades { EVM(network: eth) { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Trade: { Side: { Amount: { gt: "0" } Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } } Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } Dex: { ProtocolName: { in: ["uniswap_v4", "uniswap_v3", "uniswap_v2", "uniswap_v1"] } } } } ) { Block { allTime: Time } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } Currency { Symbol SmartContract Name } Price AmountInUSD Amount Side { Type Currency { Symbol SmartContract Name } AmountInUSD Amount } } } } } ```
## Top Traders of a Token Identify the top 100 USDC traders by USD volume in pools labelled Uniswap v1–v4, forks included ([saved query](https://ide.bitquery.io/Top-Traders-of-a-Token_8)). It ranks `Transaction.From`, the account that sent each swap, since on a sale `Trade.Buyer` is the pool or a router. `Side.Type` describes the counter-side of each trade, so `bought` sums the rows where `Side.Type` is `sell`. `PriceAsymmetry: { lt: 0.1 }` drops trades whose two sides disagree badly on value ([PriceAsymmetry reference](/docs/graphql/metrics/priceAsymmetry/)), which would otherwise inflate the USD totals:
Click to expand GraphQL query ```graphql query topTraders { EVM(network: eth) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } Dex: { ProtocolName: { in: ["uniswap_v4", "uniswap_v3", "uniswap_v2", "uniswap_v1"] } } PriceAsymmetry: { lt: 0.1 } } } ) { Transaction { From } bought: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) sold: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ```
## Uniswap v2 Pair Trade Stats Get CHEFDOG/WETH v2 pooled stats (volume, bought, sold). As above, `bought` counts rows where `Side.Type` is `sell`:
Click to expand GraphQL query ```graphql query pairTopTraders { EVM(network: eth, dataset: combined) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Dex: { Pair: { SmartContract: { is: "0x4ba1970f8d2dda96ebfbc466943fb0dfaab18c75" } } } } } ) { Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) sold: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ```
## Stream Latest Pool Creation on Uniswap V2, V3 [Run Stream ➤](https://ide.bitquery.io/stream-pool-and-pair-creation-on-ethereum_1) It covers v4 as well: the PoolManager is in the contract list, and v4 pools are created by `Initialize`. [Run Query ➤](https://ide.bitquery.io/query-pool-and-pair-creation-on-ethereum_1)
Click to expand GraphQL query ```graphql subscription { EVM(network: eth) { Events( where: { Log: { SmartContract: { in: [ "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f" "0x1f98431c8ad98523631ae4a59f267346ea31f984" "0x000000000004444c5dc75cB358380D2e3dE08A90" ] } Signature: { Name: { in: ["PoolCreated", "PairCreated", "Initialize"] } } } } ) { Log { SmartContract } Transaction { Hash } Arguments { Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } Name } Block { Time } } } } ```
## Latest Pools Created on Uniswap V2 Track the last 10 `PairCreated` events from the Uniswap V2 factory:
Click to expand GraphQL query ```graphql { EVM(dataset: combined, network: eth) { Events( orderBy: { descending: Block_Number } limit: { count: 10 } where: { Log: { SmartContract: { is: "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f" } Signature: { Name: { is: "PairCreated" } } } } ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Type Value { ... on EVM_ABI_Address_Value_Arg { address } } } } } } ```
## Latest Pools Created on Uniswap V4 Track the last 10 `Initialize` events from the Uniswap V4 factory:
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: eth) { Events( orderBy: { descending: Block_Number } limit: { count: 10 } where: { Log: { SmartContract: { is: "0x000000000004444c5dc75cB358380D2e3dE08A90" } Signature: { Name: { is: "Initialize" } } } } ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } } } } } ```
## Active Traders on Uniswap in the Last 7 Days Rank the 100 accounts that sent the most Uniswap v3 swaps on Ethereum in the last 7 days. It groups by `Transaction.From`, since `Trade.Seller` is often the pool, and sets `dataset: combined` because the default realtime dataset holds only the last few days:
Click to expand GraphQL query ```graphql query ActiveUniswapTraders { EVM(network: eth, dataset: combined) { DEXTradeByTokens( where: { Trade: { Dex: { OwnerAddress: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } limit: { count: 100 } orderBy: { descendingByField: "tradeCount" } ) { Transaction { From } tradeCount: count uniqueTokens: count(distinct: Trade_Currency_SmartContract) } } } ```
## Get Latest Trading Price for a Uniswap Token Pair We launched the [Price Index](/docs/trading/crypto-price-api/) in August 2025, allowing you to track price for any onchain token pair. Here's an example of tracking Uniswap token pair trading price. `ProtocolFamily: "Uniswap"` also matches SushiSwap's WETH/USDC pools; filter `Market.Address` or `Market.Program` instead when you need Uniswap's own pools. Uniswap Token Pair Price API [Run Query ➤](https://ide.bitquery.io/latest-trade-price-of-uniswap-pair#)
Click to expand GraphQL query ```graphql query MyQuery { Trading(dataset: realtime) { Pairs( where: { Token: { Address: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } QuoteToken: { Address: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } Market: { Network: { is: "Ethereum" } ProtocolFamily: { is: "Uniswap" } } Interval: { Time: { Duration: { eq: 60 } } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Block { Time } Price { Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving } } Market { Address ProtocolFamily Protocol Program } } } } ```
## Get OHLC for a Pair on Uniswap [Run Query](https://ide.bitquery.io/OHLC-price-of-an-uniswap-pair) to get `1 minute` OHLC data for a given pair of currencies. Like the price example above, it filters `ProtocolFamily`, so fork pools are included.
Click to expand GraphQL query ```graphql query MyQuery { Trading(dataset: realtime) { Pairs( where: { Token: { Address: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } QuoteToken: { Address: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } Market: { Network: { is: "Ethereum" } ProtocolFamily: { is: "Uniswap" } } Interval: { Time: { Duration: { eq: 60 } } } } orderBy: { descending: Interval_Time_End } ) { Interval { Time { Start End } } Price { Ohlc { Open High Low Close } } Market { Address ProtocolFamily Protocol Program } QuoteToken { Address Name Symbol } Token { Address Name Symbol } } } } ```
## Uniswap Kafka Streams You can get Uniswap data with sub-second latency via Kafka Streams. Read about [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/) Contact us on our telegram channel for a trial credentials. --- ## Ethereum Uniswap v4 API: Swaps, PoolIds, Pool Stats, Traders and Reserves URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/uniswap-v4-api/ Uniswap v4 on Ethereum with Bitquery GraphQL: swaps with trader and market cap, raw PoolManager swaps, pools by PoolId, pool stats, top traders, reserves. # Ethereum Uniswap v4 API: Swaps, PoolIds, Pool Stats, Traders and Reserves Uniswap v4 replaced one contract per pool with one contract for all pools. On Ethereum that contract is the PoolManager at `0x000000000004444c5dc75cB358380D2e3dE08A90`; a pool is a `PoolId`, the hash of its two tokens, fee, tick spacing and hook, and swaps, deposits and withdrawals all surface as events of the PoolManager. Bitquery decodes those into the same cubes as every other DEX, with two things to know. `Trade.PoolId` is how you pick a pool, since `Dex.SmartContract` is always the PoolManager. And on raw `DEXTrades` rows the buyer and seller are both the PoolManager, because it settles both sides; the trader is `Transaction.From`, or the `Trader` field of the Trading cube. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked pool is ETH/USDC, `PoolId 0x00b9edc1583bf6ef09ff3a09f6c23ecb57fd7d0bb75625717ec81eed181e22d7`, and the worked token is USDC, `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`. ## Live swaps with trader, USD and market cap For a live feed with the trader, USD amounts and the token's supply and market cap on every row, use the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) of the Trading cube and filter the market to Ethereum and `uniswap_v4`. `Pair.Pool.Id` is the PoolId and `Pair.Pool.Address` the PoolManager. The Trading cube keeps about 30 days; the chain cubes below reach further back. Saved stream [here](https://ide.bitquery.io/Uniswap-v4-trades-with-pool-id-and-mcap). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Ethereum" }, Protocol: { is: "uniswap_v4" } } } } ) { Block { Time } Side Trader { Address } Amounts { Base Quote } AmountsInUsd { Base Quote } Supply { CirculatingSupply MarketCap } Pair { Currency { Symbol Id } QuoteCurrency { Symbol } Pool { Id Address } } TransactionHeader { Sender } } } } ``` ## Raw swaps from the PoolManager The chain-specific `DEXTrades` cube gives the pool-side view of each swap: what the pool received and what it paid out, with USD on both sides. Filter on the protocol name and subscribe, or add a `PoolId`. Saved stream [here](https://ide.bitquery.io/Real-time-trades-on-uniswap-v4----subscription). ```graphql subscription { EVM(network: eth) { DEXTrades(where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } } }) { Block { Time } Trade { PoolId Buy { Currency { Symbol SmartContract } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol SmartContract } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Every v4 pool of a token Group `DEXTradeByTokens` by `PoolId` with the token in `Currency`. Each row is one pool with its counter token, trade count and USD volume in the window; this is the lookup that gives you a `PoolId`. Saved query [here](https://ide.bitquery.io/All-Pool_Ids-for-currency). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "count" } limit: { count: 20 } ) { Trade { PoolId Side { Currency { Symbol SmartContract } } } count volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Latest swaps in one pool Saved query [here](https://ide.bitquery.io/Latest-trades-for-a-Pool-Id-on-uniswap-v4). ```graphql { EVM(network: eth) { DEXTrades( where: { Trade: { PoolId: { is: "0x00b9edc1583bf6ef09ff3a09f6c23ecb57fd7d0bb75625717ec81eed181e22d7" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Currency { Symbol } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Pool stats for the last 24 hours Trades, distinct buyers and sellers, and USD volume split by direction for the token you name. Saved query [here](https://ide.bitquery.io/uniswap-v4-stats---Volume-bought-and-sold). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x00b9edc1583bf6ef09ff3a09f6c23ecb57fd7d0bb75625717ec81eed181e22d7" } Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol } Side { Currency { Symbol } } } trades: count buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) volumeUsd: sum(of: Trade_Side_AmountInUSD) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) } } } ``` ## Top traders of the pool Rank by `Transaction.From`, the account that sent the swap. `bought` sums the token the trader received and `sold` the token it paid; `Side.Type` describes the counter-side of each trade, which is why the two conditions are the other way round. Saved queries: [top buyers](https://ide.bitquery.io/Top-Buyers-of-a-currency-on-uniswap-v4), [top sellers](https://ide.bitquery.io/Top-Sellers-of-a-currency-on-uniswap-v4). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x00b9edc1583bf6ef09ff3a09f6c23ecb57fd7d0bb75625717ec81eed181e22d7" } Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 20 } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Reserves of a v4 pool `DEXPoolEvents` rows carry the reserves the PoolManager holds for the pool after each change, rebuilt from the concentrated positions around the current price and priced in USD. Filter by `PoolId` for one pool, or keep only the protocol name to stream them all. Saved streams: [all v4 pools](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4_6), [by PoolId](https://ide.bitquery.io/uniswap-v4-pool-liquidity-by-poolid-ethereum). ```graphql { EVM(network: eth) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0x00b9edc1583bf6ef09ff3a09f6c23ecb57fd7d0bb75625717ec81eed181e22d7" } } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } } } } ``` ## Related pages - [Ethereum DEX trades API](/docs/blockchain/Ethereum/dextrades/dex-api) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) - [Uniswap v4 on Base](/docs/blockchain/Base/uniswap-v4-api) - [Uniswap v4 on Arbitrum](/docs/blockchain/Arbitrum/uniswap-v4-api) - [Uniswap v4 on Optimism](/docs/blockchain/Optimism/uniswap-v4-api) --- ## Ethereum Validator Balance Tracker URL: https://docs.bitquery.io/docs/blockchain/Ethereum/balances/transaction-balance-tracker/eth-validator-balance-tracker/ Ethereum Validator Balance Tracker: stream Ethereum balance changes with reason codes using Bitquery GraphQL subscriptions. # Ethereum Validator Balance Tracker The Ethereum Validator Balance Tracker API provides real-time balance updates for Ethereum validators, tracking their staking rewards, withdrawals, and balance changes. For a sample application, see the [Validators Rewards Tax Calculator](https://docs.bitquery.io/crypto-reward-tax-calculator). ## Track Validator Balance Updates Monitor balance changes for Ethereum validators, including staking rewards and withdrawals from the beacon chain. Try the API [here](https://ide.bitquery.io/Track-Validator-Balance-Updates). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 3 } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` **Note:** BalanceChangeReasonCode 3 corresponds to `BalanceIncreaseWithdrawal` - ETH withdrawn from the beacon chain. ## Track Validator Rewards Track validator rewards and balance increases from staking activities. Try the API [here](https://ide.bitquery.io/Track-Validator-Rewards). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { in: [2, 5] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` **Balance Change Reason Codes for Validators:** - **Code 2**: `BalanceIncreaseRewardMineBlock` - Reward for mining a block - **Code 3**: `BalanceIncreaseWithdrawal` - ETH withdrawn from the beacon chain - **Code 5**: `BalanceIncreaseRewardTransactionFee` - Transaction tip increasing block builder's balance ## Filter by Validator Address Track balance changes for a specific validator address: Try the API [here](https://ide.bitquery.io/Filter-by-Validator-Address). ```graphql subscription { EVM(network: eth) { TransactionBalances( where: { TokenBalance: { Address: { is: "0xValidatorAddressHere" } BalanceChangeReasonCode: { in: [2, 3, 5] } } } ) { Block { Time Number } TokenBalance { Currency { Symbol } PreBalance PostBalance Address BalanceChangeReasonCode PostBalanceInUSD } Transaction { Hash } } } } ``` ## Top Validators by Total Tips earned in last 24 hrs Ranks validators by cumulative priority fees (reason code 5) received in the last 24 hours. Test the query [here](https://ide.bitquery.io/top-validators-by-total-tips-in-last-24-hrs#). ```graphql query MyQuery { EVM(network: eth, dataset: realtime) { TransactionBalances( limit: { count: 10 } orderBy: { descendingByField: "Total_tip_native" } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { TokenBalance { Address BalanceChangeReasonCode Currency { Name Symbol SmartContract } } Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count } } } ``` ## Total Tips earned by a Validator in last 24 hrs Returns the total priority fees (native and USD) earned by a specific validator over the last 24 hours. Test the query [here](https://ide.bitquery.io/total-tips-received-by-a-validator-in-last-24-hrs#). ```graphql query MyQuery { EVM(network: eth, dataset: realtime) { TransactionBalances( where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } Address: { is: "0x4838b106fce9647bdf1e7877bf73ce8b0bad5f97" } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { TokenBalance { Address BalanceChangeReasonCode Currency { Name Symbol SmartContract } } Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count } } } ``` ## Avg Tip in last 10 Blocks Calculates the average tip for each of the last 10 blocks. Test the query [here](https://ide.bitquery.io/last-10-blocks-avg-tip-in-native-eth_3). ```graphql query MyQuery { EVM(network: eth, dataset: realtime) { TransactionBalances( limit: { count: 10 } orderBy: { descending: Block_Number } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } } ) { Block { Number } TokenBalance { BalanceChangeReasonCode Currency { Name Symbol SmartContract } } Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count avg_tip_in_this_block: calculate( expression: "$Total_tip_native / $number_of_tips" ) avg_tip_usd_in_this_block: calculate( expression: "$Total_tip_usd / $number_of_tips" ) } } } ``` ## Avg Tip given in terms of Avg Gas Fees in last 10 blocks Compares average user tip to average total gas fee per block across the last 10 blocks. Test the query [here](https://ide.bitquery.io/Average-Tip-in-terms-of-avg-gas-Fee_4). ```graphql query MyQuery { EVM(network: eth, dataset: realtime) { TransactionBalances( limit: { count: 10 } orderBy: { descending: Block_Number } where: { TokenBalance: { BalanceChangeReasonCode: { eq: 5 } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Block { Number } TokenBalance { BalanceChangeReasonCode Currency { Name Symbol SmartContract } } avg_gasfees_in_this_block: average(of: Fee_SenderFee) Post: sum(of: TokenBalance_PostBalance) Post_USD: sum(of: TokenBalance_PostBalanceInUSD) Pre: sum(of: TokenBalance_PreBalance) Pre_USD: sum(of: TokenBalance_PreBalanceInUSD) Total_tip_native: calculate(expression: "$Post - $Pre") Total_tip_usd: calculate(expression: "$Post_USD - $Pre_USD") number_of_tips: count avg_tip_in_this_block: calculate( expression: "$Total_tip_native / $number_of_tips" ) avg_tip_usd_in_this_block: calculate( expression: "$Total_tip_usd / $number_of_tips" ) tip_in_terms_of_gasfees: calculate( expression: "( $avg_gasfees_in_this_block - $avg_tip_in_this_block ) / $avg_gasfees_in_this_block" ) } } } ``` ## Video Tutorial --- ## Example: Build an OHLC Candle Chart for Any Token URL: https://docs.bitquery.io/docs/mcp/trading/examples/token-ohlc-chart/ Example: Build an OHLC Candle Chart for Any Token with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Build an OHLC Candle Chart for Any Token > **The trader question:** *"Give me the last 24 hours of price action for WSOL so I can eyeball the trend."* The same pre-built candles feed Bitquery's [TradingView integration](/docs/usecases/tradingview-subscription-realtime/getting-started/), Telegram bots, and Kafka streams. Through the MCP, your agent can pull them on demand for **any token, any chain, any interval**. ## Ask the Agent > *"Using the Bitquery MCP, pull hourly OHLC + USD volume for WSOL (`So11111111111111111111111111111111111111112`) on Solana for the last 24 hours and render it as a markdown table I can paste into a chart."* ## Result (live data, 2026-04-23 snapshot) ![WSOL hourly candles for the last 24 hours](/img/mcp/charts/wsol-24h-candles.svg) The 24h move on this snapshot: **$88.59 → $86.04 (−2.88%)**. Note the volume spike on the down-leg around hour 11 (`$26.5M`) — classic capitulation-then-stabilisation pattern. | Time (UTC) | Open | High | Low | Close | Volume | |---|---:|---:|---:|---:|---:| | 00:00 | 88.59 | 89.18 | 88.48 | 89.13 | $20.0M | | 01:00 | 89.13 | 89.33 | 88.53 | 88.77 | $21.1M | | 02:00 | 88.79 | 88.81 | 88.08 | 88.24 | $18.3M | | 03:00 | 88.23 | 88.48 | 87.56 | 87.67 | $12.8M | | 04:00 | 87.70 | 88.04 | 87.65 | 87.84 | $11.4M | | … | … | … | … | … | … | | 11:00 | 86.88 | 87.17 | **86.01** | 86.89 | **$26.5M** | | … | … | … | … | … | … | | 22:00 | 85.48 | 85.92 | 85.41 | 85.86 | $7.1M | | 23:00 | 85.86 | 86.10 | 85.84 | **86.04** | $30.2M | ## What This Tells a Trader - **Candles are pre-built.** Bitquery rolls up trades into 1-minute, 5-minute, hourly, and daily candles automatically — the agent picks the bucket size you asked for and returns clean rows. - **Token-level vs pool-level.** This chart aggregates **every WSOL pool across Solana** into one view. To chart a single pool (say WIF/USDC on Raydium) instead, just say *"chart it for pool `
`"* and the agent narrows the lookup. - **Always fresh.** The data updates as blocks land — re-run the same prompt 30 seconds later and you'll get the next candle. ## Trader Playbook | You want to … | Just ask the agent | |---|---| | **Daily candles** for back-testing | *"Same chart but daily candles, last 90 days."* | | **Multiple price averages** for indicator overlays | *"Add 7-period SMA and 14-period EMA columns to each row."* | | **Realised vs estimated price** divergence | *"For the same window, also include Bitquery's estimated price — flag any candles where they diverge by more than 1%."* | | **Volume profile** by price bucket | *"Bucket the last 24h of trades into $0.50 price bins and sum the USD volume per bin."* | | **Live chart** that auto-updates | The dataset updates in near real time — re-run the prompt on a 5–10s interval and the result is always fresh. | | **Compare two tokens** on one chart | *"Compare 1h close prices of WSOL and ETH for the last 24h on the same scale."* | ## Variations the Agent Handles in One Sentence - *"Show me 1-minute candles for the last 60 minutes for `` and tell me the max drawdown."* - *"For pool ``, plot the divergence between OHLC close and the volume-weighted moving average."* - *"Find every 1h candle in the last 24h where the high-to-low range exceeds 5% — those are the volatile hours."* - *"Bucket today's candles into hourly groups and tell me the most volatile hour of the day."* ## Take It Further - Plug the result straight into [TradingView Advanced Charts](/docs/usecases/tradingview-subscription-realtime/getting-started/) — same data, prettier UI. - For per-trade replay (bigger granularity), ask the agent for the raw trades instead of candles — *"show me every WSOL trade in the last 5 minutes"*. See the [trading overview](/docs/mcp/trading/overview/) for what's on every trade row. - Background on price derivation: [Crypto Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm/). - Find tokens worth charting first with [Hottest Solana Tokens](/docs/mcp/trading/examples/top-tokens-discovery/), or check which DEX has the deepest pool with [Solana DEX Market Share](/docs/mcp/trading/examples/solana-dex-market-share/). --- ## Example: Cross-Chain DEX Volume Snapshot URL: https://docs.bitquery.io/docs/mcp/trading/examples/cross-chain-snapshot/ Example: Cross-Chain DEX Volume Snapshot with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Cross-Chain DEX Volume Snapshot > **The trader question:** *"Where is the action right now? Which chain is the most liquid, the most active, and has the most distinct traders?"* A single MCP query returns the answer for **all chains at once** — no per-chain GraphQL juggling. ## Ask the Agent > *"Using the Bitquery MCP, give me a 24h cross-chain DEX snapshot: USD volume, total trade count, and unique traders per chain. Sort by volume."* ## Result (live data, 2026-04-23 snapshot) ![24h DEX volume share across chains](/img/mcp/charts/cross-chain-volume.svg) | Chain | 24h Volume (USD) | Trades | Unique Traders | Avg trade size | |---|---:|---:|---:|---:| | Solana | **$25.97 B** | 50.5 M | 1,259,514 | $514 | | BNB Smart Chain | $5.39 B | 10.6 M | 452,085 | $510 | | Ethereum | $2.99 B | 946 K | 55,229 | $3,160 | | Base | $1.52 B | 2.55 M | 35,901 | $596 | | Polygon (Matic) | $0.57 B | 14.1 M | 379,596 | $40 | | Arbitrum | $0.47 B | 726 K | 9,283 | $650 | | Tron | $0.10 B | 16 K | 1,208 | $6,229 | | Optimism | $0.03 B | 282 K | 1,836 | $115 | The "average trade size" column tells its own story: **Tron** has the largest typical trade (whales / OTC-style flow), while **Polygon** is dominated by tiny on-chain payments. ## What This Tells a Trader - **Where the flow really is.** Solana is now ~5× the next chain by USD volume — and ~25× by trade count. Most retail attention is there. - **Where the price-takers are.** Ethereum's average trade size ($3,160) is 5–8× larger than Solana / Base — a sign that institutional and large-portfolio activity still concentrates on EVM L1. - **Where the bots are.** Polygon's microscopic average trade size ($40) means most volume there is from automated payment / aggregator flow, not discretionary trading. ## Trader Playbook | You want to … | Just ask the agent | |---|---| | **Spot a chain rotation** | *"Compare today's volume per chain with the same window 7 days ago. Where is volume rotating to?"* | | **Filter to memecoin chains only** | *"Same snapshot, but only Solana, Base, and BNB Smart Chain."* | | **Compare protocols across chains** | *"For each chain, show the top 3 DEXs by 24h volume."* — see [Solana DEX market share](/docs/mcp/trading/examples/solana-dex-market-share/) for a chain-specific cut. | | **Track a stablecoin's flow** | *"Same snapshot, but only count trades where the quote token is USDC or USDT."* | | **Find the chain with the cleanest data** | *"Run this twice: all flow vs only clean (non-wash-traded) flow. Show the % drop per chain."* | ## Variations the Agent Handles in One Sentence - *"Same snapshot but bucketed every 4 hours for the last 24h, so I can see when each chain peaked."* - *"Plot a stacked area chart of hourly USD volume per chain for the last 7 days."* (paste output into your analysis tool) - *"Which chain has the highest ratio of unique traders to total trades? That's the most retail-driven."* - *"For each chain, show the top 3 quote tokens by volume."* ## Take It Further - Drill into one chain's DEX breakdown with [Solana DEX Market Share Battle](/docs/mcp/trading/examples/solana-dex-market-share/). - Track new-token velocity per chain by re-using the launch-counting pattern from [Pump.fun Launch Pulse](/docs/mcp/trading/examples/pumpfun-launch-pulse/). - For a tour of what's in the trading dataset, see the [trading overview](/docs/mcp/trading/overview/). --- ## Example: Decode a Whale Wallet's 24h Activity URL: https://docs.bitquery.io/docs/mcp/trading/examples/whale-wallet-decode/ Example: Decode a Whale Wallet's 24h Activity with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Decode a Whale Wallet's 24h Activity > **The trader question:** *"Who is `MfDuWeqS…` and what are they doing? Are they accumulating, distributing, or making markets?"* A common trader workflow: Etherscan / Solscan shows you transactions, but it doesn't aggregate USD flow per token by direction. The MCP makes that one query. ## How to Find a Wallet to Investigate We pulled this wallet from the **top traders by USD volume on WSOL in the last 24h**: > *"Using the Bitquery MCP, find the top 5 wallets that traded WSOL on Solana in the last 24 hours, sorted by total USD volume."* That returned `MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa` at #1 with **$83.6M** in WSOL volume across **49,385** trades in 24 hours. That density (~34 trades / minute) is a giveaway: it's an aggregator / market-maker bot. Let's dissect it. ## Ask the Agent > *"Using the Bitquery MCP, for wallet `MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa`, break down 24h activity per token: trade count, USD bought, USD sold, and net flow."* ## Result (live data, 2026-04-23 snapshot) ![Whale wallet 24h buy vs sell volume per token](/img/mcp/charts/whale-portfolio.svg) | Token | Trades | Bought (USD) | Sold (USD) | Net flow (USD) | Behavioural read | |---|---:|---:|---:|---:|---| | **WSOL** | 49,405 | $39.2M | $44.5M | **−$5.3M** | Net distributing — a few % of WSOL out of the wallet. | | **cbBTC** | 16,740 | $7.0M | $6.4M | +$0.6M | Roughly balanced, slight accumulation. | | **WETH** | 9,190 | $3.9M | $5.2M | −$1.3M | Net distributing. | | **MET** | 25,517 | $4.2M | $4.2M | ~$0 | Pure two-sided market making. | | **TRUMP** | 997 | $3.3M | $1.2M | **+$2.1M** | Strong directional accumulation. | | EURC | 1,837 | $1.0M | $1.1M | ~$0 | Stablecoin pass-through. | | WBTC | 2,948 | $1.2M | $0.7M | +$0.5M | Moderate accumulation. | | JLP | 7,023 | $0.9M | $1.0M | ~$0 | Two-sided. | **Behavioural signature:** the wallet is overwhelmingly two-sided on WSOL/cbBTC/WETH/MET/EURC (classic market-maker profile), but takes a clear **directional long on TRUMP**. That's the kind of mixed strategy you'd want to copy-trade selectively, not blindly. ## What This Tells a Trader - **Spot bots vs humans.** A wallet with thousands of trades on a handful of tokens at near-balanced buy/sell is almost certainly a bot. A wallet with a few large directional trades is a discretionary actor. - **Find directional whales worth copying.** The MM-style flow on this wallet is noise — but the TRUMP position is signal. The same wallet can produce both. - **Audit a token's "smart money".** Ask the agent: *"For token X, who were the top 10 wallets by USD volume in the last 24h, and what's their net flow?"* You'll see whether smart money is accumulating or distributing. - **Wallet lookups are instant.** Even a wallet with 50,000 trades a day comes back in well under a second. ## Trader Playbook | You want to … | Just ask the agent | |---|---| | **Realised PnL** instead of flow | *"For wallet ``, compute realised USD PnL per token in the last 7 days."* | | **Mark-to-market unrealised PnL** | *"…and value any open position at the latest token price."* | | **First and last trade** of each token | *"Per token, when did this wallet first buy and last touch it?"* | | **DEX preference** for the wallet | *"Which DEXs does this wallet use the most, by volume?"* | | **Build a copy-trading shortlist** | *"Find wallets that bought any new Pumpfun token in its first 60 seconds in the last 24h, then sold higher within 10 minutes. Rank by hit rate."* | ## Variations the Agent Handles in One Sentence - *"Same wallet, same breakdown, but for the last 7 days bucketed daily."* - *"For wallet ``, show every trade in the last 24h ordered by time, and flag any larger than $500K USD."* - *"For the top 20 wallets by 24h USD volume on Solana, show their net flow per token — find the most directional ones."* - *"Did wallet `` ever buy ``? What was the average entry price?"* ## Take It Further - For wallet-centric trade analytics in GraphQL, see the [Traders API](/docs/trading/crypto-trades-api/traders-api/). - To stream a wallet's trades in real time, use the [GraphQL subscriptions](/docs/subscriptions/websockets/) or [Solana Kafka stream](/docs/streams/real-time-solana-data/). - Pick a high-volume token from [Hottest Solana Tokens](/docs/mcp/trading/examples/top-tokens-discovery/) and re-run this analysis on its top traders. - Spot whales who buy launches first by combining this pattern with [Pump.fun Launch Pulse](/docs/mcp/trading/examples/pumpfun-launch-pulse/). - For copy-trading at production latency, see the [copy-trading bot](/docs/usecases/copy-trading-bot/) and [gRPC copy-trading bot](/docs/grpc/solana/examples/grpc-copy-trading-bot/) walkthroughs. --- ## Example: Find the Hottest Solana Tokens of the Day URL: https://docs.bitquery.io/docs/mcp/trading/examples/top-tokens-discovery/ Example: Find the Hottest Solana Tokens of the Day with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Find the Hottest Solana Tokens of the Day > **The trader question:** *"What are the most-traded Solana tokens right now — without the wash-trading noise?"* This is the "morning coffee" query for any Solana trader: a clean, ranked list of tokens that actually moved real volume in the last 24 hours. ## Ask the Agent Paste this into Claude / Cursor / ChatGPT once the [Bitquery MCP](/docs/mcp/mcp-server/) is connected: > *"Using the Bitquery MCP, show me the top 10 Solana tokens by USD volume in the last 24 hours. Skip wash-traded pools. Include latest market cap and price."* ## Result (live data, 2026-04-23 snapshot) ![Top 10 Solana tokens by 24h volume](/img/mcp/charts/top-tokens-solana-24h.svg) | # | Symbol | Address | 24h Volume (USD) | Market Cap | Price | |---|---|---|---:|---:|---:| | 1 | MakeTokabu | `1S2eqGRM…rEG6cGheqnjrp2` | $319.5M | $659K | $0.000659 | | 2 | WSOL | `So11111…111112` | $299.2M | $49.5B | $86.04 | | 3 | MakeAliens | `DKRd5Nb…7npuqHCWR7rw5` | $291.2M | $615K | $0.000615 | | 4 | MakeAliens | `7pyntNT…CAEC43RTAo3YRC` | $290.8M | $1.1M | $0.001146 | | 5 | C0IN | `CoDzhTh…2FbJudFUptuqrP` | $226.4M | $62.4M | $0.062 | | 6 | SpaceX | `G7MiJL7…HAiRYoXHa14JY6` | $153.8M | $133K | $0.000134 | | 7 | MakeAliens | `3qtAHDr…3K3v5zVY9D7LHL` | $111.5M | $645K | $0.000645 | | 8 | MakeAliens | `AB763tw…83K3v5zVY9D7LH` | $111.2M | $612K | $0.000612 | | 9 | U.S MAGA | `A3R7y1K…dLHsVt14qxJViu` | $107.1M | $1.2B | $0.012 | | 10 | MakeAliens | `BwpnLEv…HsVt14qxJVlunm` | $87.0M | $1.2B | $0.012 | Notice how **MakeAliens** appears five times — that's the same currency trading across five distinct token contracts (different launch versions / forks). The MCP shows them separately because they really are separate tokens on-chain. ## Why Bitquery's Outlier Filter Matters Asking the agent to "skip wash-traded pools" makes it apply Bitquery's [price-index ranking](/docs/trading/crypto-price-api/price-index-algorithm/) automatically. Without it, the top of the list would be dominated by suspect-volume pools — exactly the kind of noise that fakes you out on which token is "really" trending. ## Trader Playbook | You want to … | Just ask the agent | |---|---| | Build a **watchlist** for the next session | *"Give me the top 25 instead of 10, and include the contract addresses so I can copy them."* | | Find **emerging tokens** (skip blue-chips) | *"Same list but only tokens with market cap below $10M."* | | Compare to **prior day** | *"Run the same query for yesterday too and show the change in volume."* | | Run it on **Ethereum / Base / BSC** instead | *"Same list but for Base."* | | **Stricter** noise filter | *"Use a stricter wash-trade filter."* (loose: many tokens; strict: only the cleanest pools) | ## Variations the Agent Handles in One Sentence - *"Same list but only memecoins (exclude WSOL, USDC, USDT)."* - *"Top 10 Base tokens by buyer count instead of volume."* - *"Same list but limit to tokens younger than 7 days."* - *"Same list but show me 1h volume change from the previous hour."* ## Take It Further - For wallet-centric analysis of one of these tokens, see [Decode a Whale Wallet](/docs/mcp/trading/examples/whale-wallet-decode/). - To pull a candle chart for any of these tokens, see [Build an OHLC Candle Chart](/docs/mcp/trading/examples/token-ohlc-chart/). - For a tour of what's in the trading dataset, see the [trading overview](/docs/mcp/trading/overview/). --- ## Example: Pump.fun Launch Pulse — Tokens Launched per Hour URL: https://docs.bitquery.io/docs/mcp/trading/examples/pumpfun-launch-pulse/ Example: Pump.fun Launch Pulse — Tokens Launched per Hour with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Pump.fun Launch Pulse — New Tokens per Hour > **The trader question:** *"Is launchpad activity heating up or cooling down? When are people actually deploying tokens?"* A single sentence to the agent gives you the answer for any launchpad on any chain. For live DEX prices across Pump.fun tokens after launch, see [DEXrabbit's Pump.fun category](https://dexrabbit.bitquery.io/categories/pump-fun). For the underlying launch/trade/graduation feed itself, see the [Pump.fun API product page](https://bitquery.io/products/pumpfun-api). ## Ask the Agent > *"Using the Bitquery MCP, count distinct new tokens that traded on Pump.fun per hour over the last 36 hours. Plot the trend."* ## Result (live data, 2026-04-23 snapshot, last 36 hours) ![Pump.fun new tokens per hour, last 36 hours](/img/mcp/charts/pumpfun-launches-hourly.svg) | Window (UTC) | Avg new tokens / hr | Peak hour | Peak count | |---|---:|---:|---:| | Day -1 (00:00 → 23:59) | **2,108** | 20:00 | **2,698** | | Day 0 (00:00 → now) | 1,489 | 11:00 | 1,736 | Two patterns emerge from the chart: 1. **Strong diurnal cycle** — launches cluster around **15:00–22:00 UTC** (US morning + EU evening), tail off through the Asia overnight. 2. **Day-over-day deceleration** — Day 0 is running ~30% slower than Day −1. That's the kind of signal a discretionary trader would pair with sentiment data to call a meta cooldown. ## What This Tells a Trader - **Launchpad activity is your meta thermometer.** Sustained launch counts above the baseline suggest fresh capital and risk-on sentiment; falling counts often precede a quieter trading session. - **There's a clock to launches.** US morning + EU evening hours produce the most activity. If you're sniping or providing liquidity to fresh launches, that's when to focus. - **You can apply the same lens to any launchpad.** Just say *"do the same for LetsBonk"* or *"compare Pump.fun and FourMeme"* — see the [Solana](/docs/blockchain/Solana/) and [BSC](/docs/blockchain/BSC/) sections for the full set. ## Trader Playbook | You want to … | Just ask the agent | |---|---| | **Catch a launch wave early** | *"Alert me whenever the last hour's new-token count is more than 1.5× the trailing 24h average."* (poll the agent every minute) | | **Filter to "successful" launches only** | *"Of the tokens launched on Pump.fun in the last 24h, how many crossed $10K in cumulative USD volume in their first hour?"* | | **Compare two launchpads** | *"Plot hourly new-token counts for Pump.fun vs LetsBonk for the last 7 days."* | | **Heatmap by hour-of-day × day-of-week** | *"Build a 7×24 grid of average new-token count per hour-of-day per weekday for Pump.fun."* | | **Quantify graduation flow** | *"What percentage of Pump.fun-launched tokens in the last 24h ever traded on Pumpswap?"* | ## Variations the Agent Handles in One Sentence - *"For each launchpad on Solana, show today's new-token count and yesterday's, side by side."* - *"Show me the 10 most-traded tokens that were launched on Pumpfun in the last 6 hours."* - *"What % of Pumpfun-launched tokens in the last 24h ever traded on Pumpswap (i.e. graduated)?"* - *"Plot the cumulative number of new Pumpfun tokens this week vs last week."* ## Take It Further - For deeper Pumpfun coverage in GraphQL — including bonding-curve progress, market cap snapshots, and Pumpfun → Pumpswap migration — see the [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/), [Pump.fun ↔ Pump-swap migration](/docs/blockchain/Solana/Pumpfun/pump-fun-to-pump-swap/), and [Bonding-Curve Market Cap API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-Marketcap-Bonding-Curve-API/). - Build a real-time sniper from the same data via [Solana sniper bot](/docs/usecases/solana-sniper-bot/). - See where Pumpfun sits in the wider Solana DEX landscape: [Solana DEX Market Share](/docs/mcp/trading/examples/solana-dex-market-share/). - Identify the wallets sniping fresh launches by combining this pattern with [Decode a Whale Wallet](/docs/mcp/trading/examples/whale-wallet-decode/). - For a tour of what's in the trading dataset, see the [trading overview](/docs/mcp/trading/overview/). --- ## Example: Solana DEX Market Share URL: https://docs.bitquery.io/docs/mcp/trading/examples/solana-dex-market-share/ Example: Solana DEX Market Share with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Solana DEX Market Share Battle > **The trader question:** *"Which Solana DEX is winning today's volume? Where is liquidity actually flowing?"* Every trade row in the dataset is tagged with its DEX — so a single sentence to the agent ranks the entire venue landscape. ## Ask the Agent > *"Using the Bitquery MCP, show me the top 10 Solana DEXs by 24h USD volume, with trade counts. Sort by volume."* ## Result (live data, 2026-04-23 snapshot) ![Solana DEX market share — 24h USD volume](/img/mcp/charts/solana-dex-share.svg) | # | DEX | 24h Volume (USD) | Trades | Vol / trade | |---|---|---:|---:|---:| | 1 | **Meteora** (DLMM, DAMM, DBC) | $15.97 B | 22.4 M | $712 | | 2 | **Pumpswap** | $8.29 B | 19.5 M | $425 | | 3 | Raydium | $704.9 M | 3.0 M | $231 | | 4 | OrcaWhirlpool | $318.5 M | 1.1 M | $295 | | 5 | Manifest | $197.0 M | 293 K | $673 | | 6 | GoonFi | $123.5 M | 545 K | $227 | | 7 | AlphaQ | $109.9 M | 402 K | $273 | | 8 | Pumpfun | $105.1 M | 2.6 M | $40 | | 9 | SolFi | $88.1 M | 262 K | $336 | | 10 | PancakeSwap | $51.1 M | 302 K | $169 | **Two clear stories:** 1. **Meteora dominates** by a wide margin — the combined DLMM + DAMM v2 + Dynamic Bonding Curve product family is now ~58% of all Solana DEX volume in this snapshot. 2. **Pumpfun's per-trade size ($40)** confirms the meme-launch / micro-trade reality of the bonding-curve venue, while **Pumpswap** ($425) is where graduated tokens get serious flow. Browse live Pump.fun token prices on [DEXrabbit's Pump.fun category](https://dexrabbit.bitquery.io/categories/pump-fun). ## What This Tells a Trader - **Routing matters.** If you're trading a major Solana pair, ignoring Meteora pools means leaving liquidity (and likely better pricing) on the table. - **Bonding-curve graduation is real.** The Pumpfun → Pumpswap funnel is visible right in the volume gap — early discovery happens on Pumpfun, but serious flow lives on Pumpswap. - **The long tail is alive.** GoonFi, AlphaQ, SolFi, Manifest each move $80M–200M / day — small enough to be ignored by aggregators, large enough to source unique flow. For deeper per-DEX coverage in GraphQL, see [Raydium](/docs/blockchain/Solana/Solana-Raydium-DEX-API/), [Meteora DLMM](/docs/blockchain/Solana/Meteora-DLMM-API/), [Meteora DAMM v2](/docs/blockchain/Solana/Meteora-DAMM-v2-API/), [Meteora Dynamic Bonding Curve](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/), [Pump.fun](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/), [PumpSwap](/docs/blockchain/Solana/Pumpfun/pump-swap-api/), [Orca Whirlpool](/docs/blockchain/Solana/solana-orca-dex-api/). ## Trader Playbook | You want to … | Just ask the agent | |---|---| | **Track DEX market share over time** | *"Plot hourly USD volume per DEX for the last 24h as a stacked area."* | | **Find the cheapest venue** for a given pair | *"For pair `` / USDC on Solana, show me each DEX with its 1h volume, average trade size, and average realised price."* | | **Spot a routing arbitrage** | *"In the last 5 minutes, what's the average price for `` on each DEX? Flag the biggest spread."* | | **Compare clean vs noisy volume per DEX** | *"Run the DEX share table twice: all volume vs only clean (non-wash-traded) volume. Show the % drop per DEX."* | | **Volume by DEX × token category** | *"For each DEX, what % of volume is in stablecoin pairs vs SOL pairs vs memecoin pairs?"* | ## Variations the Agent Handles in One Sentence - *"Same chart but for Ethereum: Uniswap vs PancakeSwap vs 1inch vs Curve."* - *"Show me Meteora's product split — DLMM vs DAMM v2 vs Dynamic Bonding Curve volume in the last 24h."* - *"Which DEX has the highest unique-trader-to-trade ratio? That's where the most distinct people are trading, not bots."* - *"Plot hourly Pumpswap volume vs Pumpfun volume to see graduation flow."* ## Take It Further - Drill into a single DEX by asking for per-pool OHLC: *"For pool `
`, give me 1-minute OHLC for the last hour."* See the [trading overview](/docs/mcp/trading/overview/) for what's available. - Cross-chain version of the same question: [Cross-Chain DEX Snapshot](/docs/mcp/trading/examples/cross-chain-snapshot/). - Track new launches inside the leading DEX in [Pump.fun Launch Pulse](/docs/mcp/trading/examples/pumpfun-launch-pulse/). --- ## Export GraphQL Code from the IDE URL: https://docs.bitquery.io/docs/ide/code/ Export GraphQL Code from the IDE in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Export Code The IDE will allow you to get the code in the language of your choice, so you can test your queries quickly. To do this you must go to the top right side of the screen ![Export code](/img/ide/Code_export.png) To use the Export Code feature, follow the steps below: 1. Write your query in the IDE as you normally would. 2. Once you have written your query, go to the top right side of the screen. 3. Click on the "Export Code" button. 4. A dropdown menu will appear, allowing you to choose the language in which you would like to export the code. 5. Select the desired language from the dropdown menu. 6. The code for your query will be displayed in the selected language. 7. You can now copy and paste the code snippet into your application or test environment. --- ## Extract Transfers from a Solana Block URL: https://docs.bitquery.io/docs/data-lake/extract-transfers-solana/ Transfer extraction from streamed Solana blocks: native SOL and SPL token transfers from System Program and Token Program instructions, owners, mints and decimals. # Extract Transfers from a Solana Block This page shows how to pull transfers out of a **Solana block** read from the data lake. It builds on the streaming and decoding steps from the [overview](./index.md). For Ethereum, Base and other EVM chains, see [Extract Transfers from an EVM Block](./extract-transfers-evm.md). ## Where transfers live in a Solana block Solana has no event logs like EVM `Transfer` events. A transfer is an **instruction** that a program executes. Two programs cover almost all of them: 1. **Native SOL.** The System Program (`11111111111111111111111111111111`) moves lamports with its `Transfer` instruction. 2. **SPL tokens.** The Token Program (`TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`) and Token-2022 (`TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`) move tokens with `Transfer` and `TransferChecked`. In the decoded `BlockMessage` from the `solana` module of `bitquery-pb2-kafka-package`: - `block.Transactions` holds every transaction. `tx.Status.Success` tells you if it landed. Failed transactions move nothing, so skip them. - `tx.Header.Accounts` is the transaction's account list. Instructions point into it by index. - `tx.Instructions` is a flat list of **top-level and inner instructions**. Inner instructions are the cross-program calls (CPI) that a DEX or aggregator makes, so swap legs are in this list too. `NestingLevel` and `CallerIndex` tell you where each one sits. - Each instruction has `ProgramAccountIndex` (the program that ran), `AccountIndexes` (the accounts it used) and `Data` (the raw instruction bytes). A note on bytes: addresses, signatures and `Data` are raw bytes in the decoded object. Solana shows addresses and signatures as **base58** strings, so the parser includes a small base58 encoder. ## How the instructions are shaped | Instruction | Program | `Data` layout | Accounts | | --- | --- | --- | --- | | `Transfer` | System | `u32` index `2`, then `u64` lamports | `[from, to]` | | `Transfer` | Token / Token-2022 | `u8` `3`, then `u64` amount | `[source, destination, authority]` | | `TransferChecked` | Token / Token-2022 | `u8` `12`, then `u64` amount, then `u8` decimals | `[source, mint, destination, authority]` | All integers are little-endian. SPL tokens are not held by wallets directly. They sit in **token accounts**, and each token account has an owner wallet and a mint. The block already carries this for you: for every token account in `tx.Header.Accounts`, `Account.Token` holds the `Mint`, the `Owner` wallet and the `Decimals`. So you get the wallet-to-wallet view and the token decimals without extra lookups. ## The parser ```python from solana.block_message_pb2 import BlockMessage B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def b58(raw): # Solana addresses and signatures are base58 strings of raw bytes n, s = int.from_bytes(raw, "big"), "" while n: n, r = divmod(n, 58) s = B58[r] + s return "1" * (len(raw) - len(raw.lstrip(b"\0"))) + s SYSTEM_PROGRAM = "11111111111111111111111111111111" TOKEN_PROGRAMS = { "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", # SPL Token "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", # Token-2022 } def u64(data, offset): return int.from_bytes(data[offset:offset + 8], "little") def transfers_from_block(block): out = [] for tx in block.Transactions: if not tx.Status.Success: # failed transactions move nothing continue sig = b58(tx.Signature) accounts = tx.Header.Accounts for ix in tx.Instructions: # top-level and inner (CPI) instructions program = b58(accounts[ix.ProgramAccountIndex].Address) data, idx = ix.Data, ix.AccountIndexes # 1. native SOL: System Program Transfer, u32 index 2 + u64 lamports if program == SYSTEM_PROGRAM: if len(data) >= 12 and int.from_bytes(data[:4], "little") == 2: out.append({ "type": "sol", "tx": sig, "mint": None, "from": b58(accounts[idx[0]].Address), "to": b58(accounts[idx[1]].Address), "amount": u64(data, 4), "decimals": 9, }) # 2. SPL tokens: Transfer (3) and TransferChecked (12) elif program in TOKEN_PROGRAMS and data: if data[0] == 3 and len(data) >= 9: # source, dest, authority src, dst = accounts[idx[0]], accounts[idx[1]] elif data[0] == 12 and len(data) >= 10: # source, mint, dest, authority src, dst = accounts[idx[0]], accounts[idx[2]] else: continue token = src.Token if src.Token.Mint else dst.Token out.append({ "type": "spl", "tx": sig, "mint": b58(token.Mint), # token accounts hold the balance; Token.Owner is the wallet "from": b58(src.Token.Owner or src.Address), "to": b58(dst.Token.Owner or dst.Address), "amount": u64(data, 1), "decimals": token.Decimals, }) return out ``` ## Run it Save the parser as `solana_transfers.py`, and this runner next to it as `extract.py`: ```python from solana_transfers import transfers_from_block, BlockMessage path = sys.argv[1] mint = sys.argv[2] if len(sys.argv) > 2 else None block = BlockMessage() block.ParseFromString(lz4.frame.decompress(open(path, "rb").read())) transfers = transfers_from_block(block) counts = collections.Counter(t["type"] for t in transfers) print(f"slot {block.Header.Slot}: {len(transfers)} transfers {dict(counts)}\n") if mint: transfers = [t for t in transfers if t["mint"] == mint] for t in transfers[:3]: human = t["amount"] / 10 ** t["decimals"] print(f"[{t['type']}] {t['mint'] or 'SOL'} {t['from']} -> {t['to']} amount {t['amount']} ({human:g})") ``` Pass it a Solana `.block.lz4` file streamed from the lake. Add a mint address to see only that token: ```bash # all transfers, print a breakdown and the first 3 python extract.py 000457030560_9WrSdMdyUBjf6NewzfntaKBDwZRmg7EuEW6WPPXwnx5P_<...>.block.lz4 # only USDC python extract.py 000457030560_9WrSdMdyUBjf6NewzfntaKBDwZRmg7EuEW6WPPXwnx5P_<...>.block.lz4 EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v ``` Against Solana slot 457,030,560 this is what comes back: ``` slot 457030560: 1395 transfers {'sol': 194, 'spl': 1201} [sol] SOL AxiomRXZAq1Jgjj9pHmNqVP7Lhu67wLXZJZbaK87TTSk -> 31LuZVPmU3G8RUUJgdTjwtEwP5KqF82sRgxtyEBQWk3M amount 67357050 (0.0673571) [sol] SOL stnkwFt5Ao6Kq9QqfuLchMHJDxBSD6sqeJfiqM3aAKr -> 4TQLFNWK8AovT1gFvda5jfw2oJeRMKEmw7aH6MGBJ3or amount 1000000 (0.001) [sol] SOL H4vdB2pcMhzyVgEqMXwboRTebTtQGSN8nK4CANBq1Zck -> 3fVJdx56wq5CNRPRttFUGpZi3FNfPzhjStLeopzXYQRU amount 650240 (0.00065024) ``` And with the USDC filter: ``` [spl] EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v 9JBv6vySuNHniJfRpDMd3xnnAqRb973ks4U7T9ac3Be -> 8ekCy2jHHUbW2yeNGFWYJT9Hm9FW7SvZcZK66dSZCDiF amount 2538506 (2.53851) [spl] EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v 9JBv6vySuNHniJfRpDMd3xnnAqRb973ks4U7T9ac3Be -> R4rNJHaffSUotNmqSKNEfDcJE8A7zJUkaoM5Jkd7cYX amount 100000 (0.1) [spl] EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v 9JBv6vySuNHniJfRpDMd3xnnAqRb973ks4U7T9ac3Be -> AhGsEjoU6mNqNB64XsdARDvCmwmt3scsHU7b5WL7CeKQ amount 0 (0) ``` The slot holds 1,860 transactions, and 1,576 of them succeeded. Among those, the parser finds 1,395 transfers: 194 native SOL and 1,201 SPL token transfers. Most SPL transfers are wrapped SOL (`So11111111111111111111111111111111111111112`), which DEX swaps move as a token. To call the function yourself on a decoded block: ```python from solana_transfers import transfers_from_block transfers = transfers_from_block(block) # block is a decoded solana BlockMessage ``` ## Turning raw amounts into human values `amount` is the raw integer in the token's smallest unit. Divide by `10 ** decimals` to get a human value. Unlike EVM blocks, a Solana block carries the decimals: `Account.Token.Decimals` for SPL tokens, and SOL always has 9 (1 SOL = 109 lamports). So `67357050` lamports is about `0.0674` SOL, and `2538506` USDC units with 6 decimals is about `2.54` USDC. ## Extending the parser - **Balance changes instead of instructions.** Each instruction also carries `BalanceUpdates` (SOL) and `TokenBalanceUpdates` (SPL), with the pre and post balance per account. Use them to catch value moved by programs that do not call the Token Program the usual way, or to check your transfer totals. - **More System Program moves.** `CreateAccount` (index `0`) and `TransferWithSeed` (index `11`) also move lamports. Add them if you want rent deposits and seeded transfers. - **Mints and burns.** `MintTo` (`7`), `MintToChecked` (`14`), `Burn` (`8`) and `BurnChecked` (`15`) change token supply. They use the same account and `Data` pattern as above. - **Token-2022 extensions.** Tokens with a transfer fee use `TransferCheckedWithFee` from the transfer fee extension. Add it if you track Token-2022 tokens with fees. - **Token accounts without owner info.** If a token account has no `Token` data, the parser falls back to the token account address. You can resolve its owner later from another transaction that touches it. The lake gives you the full block, and the protobuf schema describes every field, so a Solana transfer extractor is a short pass over the instructions. If you want parsed Solana transfers datasets without writing a parser, including history, they are available as [Data Store exports](https://bitquery.io/datastore). --- ## Extract Transfers from an EVM Block URL: https://docs.bitquery.io/docs/data-lake/extract-transfers-evm/ Transfer extraction from streamed EVM blocks (Ethereum, Base, BNB Chain, Polygon and other EVM chains): where transfers live, decoding Transfer events, and converting raw amounts. # Extract Transfers from an EVM Block This page shows how to pull transfers out of an **EVM block** read from the data lake. It applies to every EVM chain in the lake, such as Ethereum, Base, BNB Chain, Polygon, Arbitrum and Optimism. For Solana, see [Extract Transfers from a Solana Block](./extract-transfers-solana.md). It builds on the streaming and decoding steps from the [overview](./index.md), so it assumes you already have a decoded `BlockMessage`. ## Where transfers live in a block A block does not carry a ready-made "transfers" list. Transfers are derived from two places: 1. **Native transfers.** The value moved by a transaction itself sits in `TransactionHeader.Value`, moving from `From` to `To`. Value moved by internal calls sits inside `Trace`. 2. **Token transfers.** ERC-20 and ERC-721 transfers are emitted as `Transfer` events in each transaction's receipt logs. You recognize them by the event signature in the first topic. The token case is the common one, so we focus on it and cover native transfers at the end. ## How a token Transfer event is shaped Every ERC-20 and ERC-721 `Transfer(address,address,uint256)` event has the same log layout: - `Topics[0]` is the event signature hash, always `0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef`. - `Topics[1]` is the sender, and `Topics[2]` is the recipient. An indexed address is right-aligned in a 32-byte topic, so the address is the last 20 bytes. - For **ERC-20**, the amount is the 32-byte `LogHeader.Data`. There are exactly 3 topics. - For **ERC-721**, there is a 4th topic, `Topics[3]`, holding the token id, and `Data` is empty. - `LogHeader.Address` is the token contract that emitted the event. A note on bytes: in the decoded protobuf object these fields are raw bytes. The base64 you see in JSON output is only how JSON renders bytes. ## The parser ```python from evm.block_message_pb2 import BlockMessage # Transfer(address,address,uint256) event signature TRANSFER = bytes.fromhex( "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" ) def topic_address(topic): # an indexed address is the last 20 bytes of a 32-byte topic return "0x" + topic[-20:].hex() def transfers_from_block(block): out = [] for tx in block.Transactions: th = tx.TransactionHeader tx_hash = "0x" + th.Hash.hex() # 1. native transfer carried by the transaction itself value = int.from_bytes(th.Value, "big") if value > 0: out.append({ "type": "native", "tx": tx_hash, "token": None, "from": "0x" + th.From.hex(), "to": "0x" + th.To.hex(), "amount": value, }) # 2. token transfers emitted as Transfer events in the logs if not tx.HasField("Receipt"): continue for log in tx.Receipt.Logs: t = log.Topics if len(t) < 3 or t[0].Hash != TRANSFER: continue token = "0x" + log.LogHeader.Address.hex() frm, to = topic_address(t[1].Hash), topic_address(t[2].Hash) if len(t) == 3: # ERC-20: amount is in data out.append({ "type": "erc20", "tx": tx_hash, "token": token, "from": frm, "to": to, "amount": int.from_bytes(log.LogHeader.Data, "big"), }) elif len(t) == 4: # ERC-721: token id is topic 3 out.append({ "type": "erc721", "tx": tx_hash, "token": token, "from": frm, "to": to, "token_id": int.from_bytes(t[3].Hash, "big"), }) return out ``` ## Run it In the [sample repo](https://github.com/bitquery/blockchain-data-lake-sample) this parser lives in `transfers.py`, and `stream.py` calls it behind a `--transfers` flag, so you can run it directly against a streamed block: ```bash # extract transfers, print a breakdown and the first 10 python stream.py --bucket archive --key "$KEY" --transfers # only a given token, print the first 5 python stream.py --bucket archive --key "$KEY" --transfers 5 --token 0x4200000000000000000000000000000000000006 ``` Against the sample Base block this is what comes back: ``` 469 transfers {'erc20': 422, 'native': 28, 'erc721': 19} [erc20] 0x4200000000000000000000000000000000000006 0x498581ff718922c3f8e6a244956af099b2652b2b -> 0xbf4195ab0b03e1eb3345dd1e83bed7650b1ed123 amount 3390958905493657 [erc20] 0x4200000000000000000000000000000000000006 0xbf4195ab0b03e1eb3345dd1e83bed7650b1ed123 -> 0xf60633d02690e2a15a54ab919925f3d038df163e amount 3221410960218975 ``` The block holds 469 transfers in total: 422 ERC-20, 28 native, and 19 ERC-721. The token `0x4200000000000000000000000000000000000006` is WETH on Base. To call the function yourself on a decoded block: ```python from transfers import transfers_from_block transfers = transfers_from_block(block) # block is a decoded BlockMessage ``` ## Turning raw amounts into human values `amount` is the raw integer in the token's smallest unit. To get a human-readable value, divide by `10 ** decimals`, where `decimals` is a property of the token contract. WETH has 18 decimals, so `3390958905493657 / 10**18` is about `0.00339` WETH. The block does not carry token decimals, so you keep a small lookup of token metadata, or read `decimals()` from the contract once and cache it. ## Extending the parser - **Native internal transfers.** Value moved by internal calls is in `tx.Trace`. Walk the calls and read the value on each `CALL` that carries one. The execution detail in the trace lets you attribute these precisely. - **Wrapped-native deposits and withdrawals.** WETH-style contracts emit `Deposit` and `Withdrawal` events rather than `Transfer`, so add those signatures if you want to capture wrapping. - **Other chains.** The same approach works with the matching schema module: `solana`, `tron`, or `utxo` from `bitquery-pb2-kafka-package`. The log and event model differs per chain, so the topic filtering above is EVM-specific. Solana has its own walkthrough in [Extract Transfers from a Solana Block](./extract-transfers-solana.md). The point is that the lake gives you the full block, and the protobuf schema describes every field, so a transfer extractor is a short, self-contained pass over the decoded message. If you want parsed Transfers datasets without writing a parser, including history, they are available as [Data Store exports](https://bitquery.io/datastore). --- ## FOMO App Trades API: Wallets, Tokens and Fees on Solana URL: https://docs.bitquery.io/docs/blockchain/Solana/fomo-api/ Query FOMO app trades on Solana with Bitquery GraphQL: live trades, one wallet's trades, top tokens, active wallets, fees and daily activity. Not affiliated with FOMO. # FOMO App Trades API: Wallets, Tokens and Fees on Solana [FOMO](https://fomo.family) is a social trading app and website: users follow other traders and buy memecoins and other tokens without paying gas themselves. FOMO does not list a public API on fomo.family (checked 29 September 2026). This page shows how to read FOMO's Solana trades straight from the chain with Bitquery GraphQL. Bitquery is not affiliated with FOMO. This page covers Solana only. FOMO also lets users buy tokens on EVM chains. On Robinhood Chain, which we checked, those orders are filled by Relay's solver and look like any other Relay fill; we could only tell them apart using Relay's own order records. :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## How Bitquery finds FOMO trades FOMO uses one wallet to sign, and pay gas for, every trade its users make. Its fees arrive in USDC at a separate account: | Role | Address | | --- | --- | | Signer and fee payer on every FOMO trade | `AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51` | | FOMO fee account (USDC token account) | `HrTf9CzXR1dRH4Sof5QrpmGWwpwAf3qZzwCsEjQpXcSq` | | Owner of the fee account | `R4rNJHaffSUotNmqSKNEfDcJE8A7zJUkaoM5Jkd7cYX` | Bitquery identified these addresses from on-chain activity. FOMO has not published or confirmed them. If FOMO moves to new addresses, the queries on this page will return nothing, so run the check below first. Three things to know before you read the results: - **Not every signed transaction is a trade.** Between 12:00 and 13:00 UTC on 29 September 2026 the signer signed about 33,600 transactions, and about 26,000 of them contained a DEX trade. Count trades from DEX trade data, not from everything the signer signs. - **Most FOMO trades go through the DFlow aggregator.** In that hour, about 22,000 of the 26,000 trades did. The DFlow row carries the user's own wallet in `Trade.Account.Owner`; in a sample of 1,166 trades it matched the wallet that paid the app's fee 94% of the time. Rows for the individual pools along the route can show a temporary token account instead, so the wallet queries on this page filter on DFlow. - **Signer and fee payer fields always show FOMO.** FOMO pays the gas, so `Transaction.Signer` and `Transaction.FeePayer` never hold the user's wallet. ### Check that the signer is still active This returns the latest transaction the signer has signed. A timestamp from the last few minutes means the signer is still in use. Run it in the [IDE: signer check](https://ide.bitquery.io/fomo-signer-check). ```graphql query FomoSignerCheck { Solana { Transactions( limit: {count: 1} orderBy: {descending: Block_Time} where: {Transaction: {Signer: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}} ) { Block { Time } Transaction { Signature } } } } ``` ## How far back the data goes - The trade-level queries on this page read Solana DEX trades, which cover about the last 12 hours. - The daily query at the end uses the [Trading API](/docs/trading/trading-data-overview), which keeps about 30 days. It has no user wallet field: on every trade from the app its `Trader.Address` is the signer. - Counts for a finished hour can still move by a few trades as recent data settles, so the figures on this page are rounded. - The queries return USD values per trade, but this page quotes no USD totals. A single mispriced trade can distort a sum, so check outliers before you add values up. ## Latest trades This returns the 10 most recent trades made in the app, with the token sold, the token bought and the user's wallet. Run it in the [IDE: latest trades](https://ide.bitquery.io/fomo-latest-trades). To stream new trades as they happen, change `query` to `subscription` and remove the `limit` and `orderBy` lines. ```graphql query FomoLatestTrades { Solana { DEXTrades( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Signer: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}, Trade: {Dex: {ProtocolName: {is: "dflow"}}}} ) { Block { Time } Transaction { Signature } Trade { Buy { Amount AmountInUSD Account { Owner } Currency { Symbol MintAddress } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } } } } } } ``` `Buy` is what the user received and `Sell` is what they paid. Most balances in the app are held in USDC, so one side is usually USDC. ## One wallet's trades Paste a Solana wallet address into the `wallet` variable to list that wallet's recent trades in the app. The `not: ""` condition stops the query from matching trades with a blank owner if the wallet value is mistyped. Run it in the [IDE: one wallet's trades](https://ide.bitquery.io/fomo-wallet-trades). ```graphql query FomoWalletTrades($wallet: String) { Solana { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Transaction: {Signer: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}, Trade: {Dex: {ProtocolName: {is: "dflow"}}, Buy: {Account: {Owner: {is: $wallet, not: ""}}}}} ) { Block { Time } Transaction { Signature } Trade { Buy { Amount Currency { Symbol MintAddress } } Sell { Amount Currency { Symbol MintAddress } } } } } } ``` ```json { "wallet": "PASTE_A_SOLANA_WALLET_ADDRESS" } ``` ## Top tokens bought This ranks tokens by how many app users bought them in the last hour. USDC, which users pay with, and wrapped SOL are left out. Run it in the [IDE: top tokens bought](https://ide.bitquery.io/fomo-top-tokens-bought). ```graphql query FomoTopTokensBought { Solana { DEXTradeByTokens( limit: {count: 10} orderBy: {descendingByField: "buyers"} where: {Transaction: {Signer: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}, Trade: {Dex: {ProtocolName: {is: "dflow"}}, Side: {Type: {is: buy}}, Currency: {MintAddress: {notIn: ["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "So11111111111111111111111111111111111111112"]}}}, Block: {Time: {since_relative: {hours_ago: 1}}}} ) { Trade { Currency { Symbol Name MintAddress } } buys: count(distinct: Transaction_Signature) buyers: count(distinct: Trade_Account_Owner) } } } ``` ## Most active wallets This lists the 10 wallets with the most trades in the app in the last hour, with how many different tokens each one traded. Run it in the [IDE: most active wallets](https://ide.bitquery.io/fomo-most-active-wallets). ```graphql query FomoMostActiveWallets { Solana { DEXTradeByTokens( limit: {count: 10} orderBy: {descendingByField: "trades"} where: {Transaction: {Signer: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}, Trade: {Dex: {ProtocolName: {is: "dflow"}}}, Block: {Time: {since_relative: {hours_ago: 1}}}} ) { Trade { Account { Owner } } trades: count(distinct: Transaction_Signature) tokens: count(distinct: Trade_Currency_MintAddress) } } } ``` ## Fees paid to the app This counts the USDC fee payments that reached the fee account in the last hour, and how many wallets paid them. Some trades also send a second, smaller fee to another account, which this query does not include. Run it in the [IDE: fees paid](https://ide.bitquery.io/fomo-fees). ```graphql query FomoFees { Solana { Transfers( where: {Transfer: {Receiver: {Address: {is: "HrTf9CzXR1dRH4Sof5QrpmGWwpwAf3qZzwCsEjQpXcSq"}}}, Block: {Time: {since_relative: {hours_ago: 1}}}} ) { fee_payments: count paying_wallets: count(distinct: Transfer_Sender_Owner) usdc_total: sum(of: Transfer_Amount) } } } ``` In that same 12:00 to 13:00 UTC hour on 29 September 2026, the fee account received about 25,900 payments, close to one per trade. ## Trades and traders per hour This shows activity for each hour of the last 12. The first list counts all trades. The second counts distinct user wallets, using the DFlow rows. Run it in the [IDE: activity per hour](https://ide.bitquery.io/fomo-hourly-activity). ```graphql query FomoHourlyActivity { Solana { trades: DEXTradeByTokens( orderBy: {descendingByField: "Block_Time"} where: {Transaction: {Signer: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}, Block: {Time: {since_relative: {hours_ago: 12}}}} ) { Block { Time(interval: {in: hours, count: 1}) } trades: count(distinct: Transaction_Signature) } traders: DEXTradeByTokens( orderBy: {descendingByField: "Block_Time"} where: {Transaction: {Signer: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}, Trade: {Dex: {ProtocolName: {is: "dflow"}}}, Block: {Time: {since_relative: {hours_ago: 12}}}} ) { Block { Time(interval: {in: hours, count: 1}) } traders: count(distinct: Trade_Account_Owner) } } } ``` ## Trades per day This uses the [Trading API](/docs/trading/trading-data-overview) to count trades and distinct tokens for each of the last 7 days. The Trading API can store more than one row per trade and repeats a small share of rows, so the query counts distinct transactions. The first day in the window is partial. Run it in the [IDE: trades per day](https://ide.bitquery.io/fomo-daily-activity). ```graphql query FomoDailyActivity { Trading { Trades( orderBy: {descendingByField: "Block_Date"} where: {Trader: {Address: {is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51"}}, Block: {Time: {since_relative: {days_ago: 7}}}} ) { Block { Date } trades: count(distinct: TransactionHeader_Hash) tokens: count(distinct: Pair_Token_Id) } } } ``` From 23 to 28 September 2026, the Trading API counted between about 925,000 and 1.21 million FOMO trades on Solana per day. For the 12:00 to 13:00 UTC hour on 29 September, this API counted about 25,600 trades against about 26,000 in the Solana DEX data above. The Trading API covers a curated set of DEXs, so expect it to run slightly lower. ## What this page cannot do - **Link usernames to wallets.** Profiles live in the app, not on-chain. - **Track the app's EVM-chain orders.** On Robinhood Chain they are filled by a bridge solver, and only the bridge's own records show which fills came from FOMO. - **Show one wallet's history older than about 12 hours.** The Trading API keeps 30 days but records the app's signer as the trader, not the user. ## Related pages - [Trading API overview](/docs/trading/trading-data-overview) - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades) - [Solana Transfers API](/docs/blockchain/Solana/solana-transfers) - [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [GMGN Solana API](/docs/blockchain/Solana/solana-gmgn-api) --- ## Fetching Real-time OHLC URL: https://docs.bitquery.io/docs/usecases/tradingview-subscription-realtime/realtime_OHLC/ Build Fetching Real-time OHLC: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Fetching Real-time OHLC We now use the new [Price Index Streams](/docs/trading/crypto-price-api/examples/#ohlc-stream-on-a-chain) to fetch **pre-aggregated OHLC data** directly from Bitquery's GraphQL WebSocket API. This removes the need to manually calculate candlesticks from raw trade data. To learn more about streaming data via graphQL, visit [Bitquery subscriptions](/docs/subscriptions/subscription/). ### Imports and Configuration ```javascript ``` - **createClient**: From the `graphql-ws` library, used to subscribe to GraphQL streams. - **config**: A local file storing your Bitquery API token. ```javascript let client; /** Last emitted bar time and close — used to stitch new candles to the previous close. */ let lastEmittedBarTime = null; let lastEmittedClose = null; const BITQUERY_ENDPOINT = "wss://streaming.bitquery.io/graphql?token=" + config.authtoken; ``` ### Subscription Query :::tip Charting one specific token? Prefer Pairs + rank 1 The subscription below uses the `Tokens` cube, whose price blends every pool where the token is base. For a chart of **one** token, subscribe to [`Pairs` with `Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) instead — the same `Price.Ohlc` fields, taken from the token's top market. Note that the top market can change during a stream, so read `Market.Address` from each message rather than assuming a fixed pool. ::: [Run Stream on IDE](https://ide.bitquery.io/1-second-crypto-price-stream) **We have used Solana as an example below, you can remove it and get data for all chains provided by the Price API** ```javascript const subscriptionQuery = ` subscription{ Trading { Tokens( where: {Token: {Network: {is: "Solana"}, Address: {is: "6ft9XJZX7wYEH1aywspW5TiXDcshGc2W2SqBHN9SLAEJ"}}, Interval: {Time: {Duration: {eq: 1}}}} ) { Block { Time } Price { Ohlc { Open High Low Close } } Volume { Base Quote } Supply { TotalSupply MarketCap FullyDilutedValuationUsd } } } } `; ``` - This query subscribes to **pre-aggregated 1-second OHLC bars** for a token on the Solana network (interval duration `1` in the `where` clause). - It requests: - **Block** — `Time` (bar timestamp) - **Price.Ohlc** — `Open`, `High`, `Low`, `Close` - **Volume** — `Base`, `Quote` - **Supply** — `TotalSupply`, `MarketCap`, `FullyDilutedValuationUsd` --- ### Subscribing to the Stream Keep the **last emitted bar’s time and close** in module-level variables. When the stream moves to a **new** candle (timestamp changes), set the new bar’s **open** to **last candle’s close** and widen **high** / **low** to include that price—same idea as [historical bar continuity](/docs/usecases/tradingview-subscription-realtime/bar-continuity/), but applied live as bars arrive. ```javascript export function subscribeToWebSocket(onRealtimeCallback) { lastEmittedBarTime = null; lastEmittedClose = null; client = createClient({ url: BITQUERY_ENDPOINT }); const onNext = (data) => { const tokenData = data.data?.Trading?.Tokens?.[0]; if (!tokenData) return; const bar = { time: new Date(tokenData.Block.Time).getTime(), open: tokenData.Price.Ohlc.Open, high: tokenData.Price.Ohlc.High, low: tokenData.Price.Ohlc.Low, close: tokenData.Price.Ohlc.Close, volume: tokenData.Volume.Base, }; const isNewCandle = lastEmittedBarTime !== null && bar.time !== lastEmittedBarTime; if (isNewCandle && lastEmittedClose != null) { bar.open = lastEmittedClose; bar.high = Math.max(bar.high, lastEmittedClose); bar.low = Math.min(bar.low, lastEmittedClose); } lastEmittedBarTime = bar.time; lastEmittedClose = bar.close; onRealtimeCallback(bar); }; client.subscribe( { query: subscriptionQuery }, { next: onNext, error: console.error } ); } ``` - **subscribeToWebSocket**: - Connects to Bitquery using `graphql-ws`. - On each message, normalizes the bar for continuity when the interval rolls forward, then passes it to `onRealtimeCallback`. ### Unsubscribing from the Stream ```javascript export function unsubscribeFromWebSocket() { if (client) { client.dispose(); } lastEmittedBarTime = null; lastEmittedClose = null; } ``` - **unsubscribeFromWebSocket**: Terminates the WebSocket connection and clears continuity state so a later reconnect does not stitch against stale closes. --- ## Fetching Solana DEX Trades for the Wash Trading Detector URL: https://docs.bitquery.io/docs/usecases/wash-trading-detector/prepare-data/getTrades/ Data collection for the Solana wash trading detector: a Bitquery GraphQL query for the latest DEX trades with both sides and USD prices, wrapped in Python. # Fetching Solana DEX Trades for the Wash Trading Detector The [wash trading detector](/docs/usecases/wash-trading-detector/overview) starts from a batch of recent Solana DEX trades. This module fetches them from Bitquery with one GraphQL query and returns them as a list of dictionaries that the [labelling rules](/docs/usecases/wash-trading-detector/prepare-data/rules) and the model read. Everything the rules need is in the row: the buy and sell side with the trading account, amount and USD price, the DEX, the block and the signature. The full project is on [GitHub](https://github.com/Kshitij0O7/wash-trading-detector). ## The query The newest successful trades across all Solana DEXs. `limit` bounds the batch; raise it for training runs and lower it for the live dashboard. Solana queries go to the `graphql` endpoint. Run it in the [IDE](https://ide.bitquery.io/Solana-dextrades) first. ```graphql { Solana { DEXTrades( limit: { count: 200 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } } ) { Trade { Dex { ProtocolName ProtocolFamily } Buy { Account { Address } Amount AmountInUSD Currency { Symbol Name MintAddress } PriceInUSD } Sell { Account { Address } Amount AmountInUSD Currency { Symbol Name MintAddress } PriceInUSD } } Block { Time Height } Transaction { Signature FeePayer } } } } ``` Both sides carry an `Account`, so the rules can compare buyer and seller, and `FeePayer` identifies who paid for the transaction, which is what a self-trade check needs. ## The `get_trades` function The function reads the access token from Streamlit secrets so the key never sits in the code, posts the query, and returns the list of trades or an empty list on any failure. Generate a token on the [access tokens page](https://account.bitquery.io/user/api_v2/access_tokens). ```python URL = "https://streaming.bitquery.io/graphql" QUERY = """ { Solana { DEXTrades( limit: { count: 200 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } } ) { Trade { Dex { ProtocolName ProtocolFamily } Buy { Account { Address } Amount AmountInUSD Currency { Symbol Name MintAddress } PriceInUSD } Sell { Account { Address } Amount AmountInUSD Currency { Symbol Name MintAddress } PriceInUSD } } Block { Time Height } Transaction { Signature FeePayer } } } } """ def get_trades(): headers = { "Content-Type": "application/json", "Authorization": f"Bearer {st.secrets['token']}", } try: response = requests.post(URL, headers=headers, data=json.dumps({"query": QUERY}), timeout=60) response.raise_for_status() return response.json()["data"]["Solana"]["DEXTrades"] except (requests.exceptions.RequestException, KeyError, json.JSONDecodeError) as err: print(f"Error fetching DEX trades: {err}") return [] ``` ## What the rest of the project does with the rows - The [labelling rules](/docs/usecases/wash-trading-detector/prepare-data/rules) flag trades where the same account is on both sides, repeated round trips between two accounts, and prices far from the token's recent range. - The [labelling module](/docs/usecases/wash-trading-detector/prepare-data/label) applies those rules and writes an `is_wash_trades` column. - [Training](/docs/usecases/wash-trading-detector/training) fits an XGBoost model on the labelled rows, and the [app](/docs/usecases/wash-trading-detector/app) scores fresh batches from this same function. ## Related pages - [Wash trading detector overview](/docs/usecases/wash-trading-detector/overview) - [Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades) - [WebSocket subscriptions](/docs/subscriptions/websockets/) --- ## Filing Data into Google BigQuery URL: https://docs.bitquery.io/docs/subscriptions/google-bigquery/bigquery/ Filing Data into Google BigQuery using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Filing Data into Google BigQuery In this part, we'll demonstrate how to set up Google BigQuery to store data from Google Pub/Sub. The incoming data will be stored in a BigQuery table called `newtrades`. We'll go step-by-step, covering table creation, schema definition, and configuring Pub/Sub to write directly to BigQuery. For managed datasets in BigQuery and Snowflake, see the [Blockchain Data Warehouse](https://bitquery.io/products/data-warehouse) product page. ### 1. Create a Table and Define the Schema #### Create a Dataset 1. Navigate to the [Google Cloud Console](https://console.cloud.google.com/). 2. Go to BigQuery and create a dataset (e.g., `trade_data`). - **Dataset ID:** `trade_data` - **Data Location:** Choose your preferred region. - **Default Table Expiration:** Leave it as the default or customize it. #### Create a Table 1. Inside the `trade_data` dataset, create a table called `newtrades`. 2. Define the schema for the `newtrades` table. Below is an example schema that aligns with the Pumpfun DEX trade data: | **Field Name** | **Type** | | --------------------- | --------- | | protocol_family | STRING | | protocol_name | STRING | | buy_amount | FLOAT | | buy_account | STRING | | sell_amount | FLOAT | | sell_account | STRING | | transaction_signature | STRING | 3. Click **Create Table**. --- ### 2. Configure Access for Pub/Sub Service Accounts To enable Pub/Sub to write data into BigQuery: 1. **Locate the Pub/Sub Service Account**: - Go to the IAM & Admin > Service Accounts page in Google Cloud Console. - Locate the service account associated with your Pub/Sub topic or subscription. 2. **Grant BigQuery Permissions**: - Assign the `BigQuery Data Editor` role to the Pub/Sub service account. This grants the service account permission to insert data into BigQuery tables. --- ### 3. Create a Subscriber on the Topic To ensure that Pub/Sub sends data to BigQuery: 1. **Go to the Pub/Sub Console**: - Navigate to your Pub/Sub topic (`bitquery-data-stream`). 2. **Create a Subscription**: - Click **Create Subscription**. - Set the following options: - **Subscription ID**: `pubsub-to-bigquery` - **Delivery Type**: Write to BigQuery - **BigQuery Table**: Select the `newtrades` table in the `trade_data` dataset. ![BigQuery table populated with streamed blockchain data](/img/diagrams/bigquery_table.png) 3. Click **Create**. --- ### 4. Verify BigQuery Integration 1. **Test Pub/Sub to BigQuery Flow**: - Run the Python script from Part 1 to publish test messages to Pub/Sub. ```bash python bitquery_pubsub.py ``` - Verify that the data appears in the `newtrades` table in BigQuery. --- ### 5. Debugging Tips - **Pub/Sub Logs**: - Use the Cloud Logging page to view detailed logs for your Pub/Sub topic and subscription. - **BigQuery Logs**: - Check the BigQuery audit logs to troubleshoot issues related to table writes or schema mismatches. - **Schema Validation**: - Ensure that the data being published to Pub/Sub matches the schema defined in BigQuery. Mismatches can cause message delivery failures. --- ### 6. Architecture Overview - **Pub/Sub Topic**: Receives live data from the Bitquery WebSocket API. - **Pub/Sub Subscription**: Configured to write data directly to BigQuery. - **BigQuery Table**: Stores the Pumpfun DEX trade data for analytics and reporting. --- ### 7. Next Steps - Build advanced dashboards with tools like [Google Data Studio](https://datastudio.google.com/) or Looker. - Use SQL queries to analyze trends in the trade data. - Automate data pipelines using Google Cloud Dataflow or scheduled BigQuery queries. --- ## Filtering JSON Arguments URL: https://docs.bitquery.io/docs/graphql/capabilities/json-filtering/ Filtering JSON Arguments in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Filtering JSON Arguments Starting October 2025, we support filtering of JSON arguments in Solana instructions. This feature allows you to query blockchain data based on the parsed argument values within program instructions. ## Overview JSON filtering enables you to filter Solana instructions by the values contained in their program arguments. This is particularly useful when you need to: - Find specific method calls with particular parameter values - Track authority changes on token accounts - Monitor transactions with specific argument patterns - Filter instructions based on complex argument conditions ## Example: Filtering setAuthority Instructions The following query demonstrates how to filter `setAuthority` method calls where the `authorityType` argument is either "0" or "1": ```graphql { Solana(network: solana) { Instructions( where: { Instruction: { Program: { Method: {is: "setAuthority"} Arguments: { includes: { Name: {is: "authorityType"} Value: {Json: {in: ["0", "1"]}} } } } } Transaction: {Result: {Success: true}} } limit: {count: 10} orderBy: {descending: Block_Slot} ) { Instruction { Program { Method Arguments { Name Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } Accounts { Address } } Transaction { Signature } } } } ``` ### Query Breakdown **Filtering Conditions:** - `Method: {is: "setAuthority"}` - Only returns instructions calling the `setAuthority` method - `Arguments: {includes: {...}}` - Filters arguments array to include entries matching the specified criteria - `Name: {is: "authorityType"}` - Looks for an argument named "authorityType" - `Value: {Json: {in: ["0", "1"]}}` - Checks if the JSON value is either "0" or "1" - `Transaction: {Result: {Success: true}}` - Only includes successful transactions **Return Fields:** - `Method` - The program method name - `Arguments` - Array of argument name-value pairs - `Accounts` - Array of account addresses involved in the instruction - `Transaction.Signature` - The transaction signature ## Filtering Options ### JSON Value Operators When filtering JSON arguments, you can use various operators: - `in: [value1, value2, ...]` - Matches if the JSON value is in the provided array - `is: "value"` - Exact match - `notIn: [value1, value2, ...]` - Matches if the JSON value is not in the provided array ### Argument Filtering The `includes` operator checks if the arguments array contains an entry matching all specified conditions: ```graphql Arguments: { includes: { Name: {is: "parameterName"} Value: {Json: {in: ["value1", "value2"]}} } } ``` ## Use Cases ### 1. Track Authority Revocations Find all instances where token authorities are being revoked (set to null): ```graphql Arguments: { includes: { Name: {is: "newAuthority"} Value: {Json: {is: "null"}} } } ``` ### 2. Monitor Specific Authority Types Filter by different authority types: - `authorityType: "0"` - Mint tokens authority - `authorityType: "1"` - Freeze account authority - `authorityType: "2"` - Account owner authority - `authorityType: "3"` - Close account authority ### 3. Combine Multiple Conditions You can combine multiple argument filters to create complex queries: ```graphql Arguments: { includes: [ {Name: {is: "authorityType"}, Value: {Json: {is: "0"}}} {Name: {is: "newAuthority"}, Value: {Json: {is: "null"}}} ] } ``` --- ## Filtering Kafka Streams: Keep Only the Programs, Tokens and DEXs You Need URL: https://docs.bitquery.io/docs/streams/protobuf/filtering_kafka_streams/ Bitquery Kafka topics carry every message for a chain, so filter in the consumer. Python patterns for a Solana program, a DEX, an EVM token and an EVM pool. # Filtering Kafka Streams: Keep Only the Programs, Tokens and DEXs You Need A Bitquery Kafka topic carries every message of its kind for a chain: every Solana transaction on `solana.transactions.proto`, every EVM token transfer on `eth.tokens.proto`. There is no server-side filter. Your consumer decodes each protobuf message, walks the repeated fields inside it, and keeps what matches. This page shows that pattern for four common cases. The snippets assume a working consumer from the [Python](/docs/streams/protobuf/kafka-protobuf-python), [Go](/docs/streams/protobuf/kafka-protobuf-go) or [JavaScript](/docs/streams/protobuf/kafka-protobuf-js) tutorial and the generated `_pb2` modules from the [protobuf schemas](https://github.com/bitquery/streaming_protobuf). Message layouts per chain are on the [Solana](/docs/streams/protobuf/chains/Solana-protobuf/), [EVM](/docs/streams/protobuf/chains/EVM-protobuf/), [Bitcoin](/docs/streams/protobuf/chains/Bitcoin-protobuf/) and [Tron](/docs/streams/protobuf/chains/Tron-protobuf/) pages. Two habits keep a filtering consumer fast. Compare addresses in one canonical form, base58 strings on Solana and lowercase hex on EVM chains, converted once per message rather than once per comparison. And stop walking a message as soon as it matches; `break` out of the inner loop and move on. ## One Solana program and its methods Topic `solana.transactions.proto`, message `ParsedIdlBlockMessage`. Each transaction holds `ParsedIdlInstructions`; an instruction's `Program` carries the program address and the decoded method name. ```python from solana import parsed_idl_block_message_pb2 TARGET_PROGRAM_ADDRESS = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # pump.fun TARGET_METHODS = {"buy", "sell"} def process_message(message): block = parsed_idl_block_message_pb2.ParsedIdlBlockMessage() block.ParseFromString(message.value()) for tx in block.Transactions: for instruction in tx.ParsedIdlInstructions: if not instruction.HasField("Program"): continue program = instruction.Program if ( base58.b58encode(program.Address).decode() == TARGET_PROGRAM_ADDRESS and program.Method in TARGET_METHODS ): print("match", base58.b58encode(tx.Signature).decode(), program.Method) break # one match is enough; stop walking this transaction ``` ## One DEX on Solana Topic `solana.dextrades.proto`, message `DexParsedBlockMessage`. Each transaction holds `Trades`; a trade's `Dex` carries the program address of the exchange. ```python from solana import dex_block_message_pb2 TARGET_DEX_PROGRAM = "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" # PumpSwap def process_message(message): block = dex_block_message_pb2.DexParsedBlockMessage() block.ParseFromString(message.value()) for tx in block.Transactions: for trade in tx.Trades: if not trade.HasField("Dex"): continue if base58.b58encode(trade.Dex.ProgramAddress).decode() == TARGET_DEX_PROGRAM: print("trade on target DEX", base58.b58encode(tx.Signature).decode()) break ``` To narrow to one market, compare the pool or market account on the trade as well; the [Solana stream page](/docs/streams/protobuf/chains/Solana-protobuf/) lists the fields under `DexTradeEvent`. ## One token contract on an EVM chain Topic `eth.tokens.proto` (or `bsc.tokens.proto`, `base.tokens.proto`), message `TokenBlockMessage`. The message is a flat list of `Transfers`; each transfer carries `Sender`, `Receiver`, `Amount` and a `Currency` with the token's `SmartContract` and `Decimals`. Addresses are raw bytes, so convert them to lowercase hex once. ```python from evm import token_block_message_pb2 TARGET_TOKEN = "0xdac17f958d2ee523a2206206994597c13d831ec7" # USDT on Ethereum def process_message(message): block = token_block_message_pb2.TokenBlockMessage() block.ParseFromString(message.value()) for transfer in block.Transfers: token = "0x" + transfer.Currency.SmartContract.hex() if token != TARGET_TOKEN: continue amount = int.from_bytes(transfer.Amount, "big") / 10 ** transfer.Currency.Decimals print( "0x" + transfer.Sender.hex(), "->", "0x" + transfer.Receiver.hex(), amount, transfer.Currency.Symbol, "0x" + transfer.TransactionHeader.Hash.hex(), ) ``` Swap the comparison for a set of wallet addresses to watch deposits and withdrawals; the [exchange wallet monitor](/docs/usecases/binance-exchange-wallet-monitoring) is a complete consumer built that way. ## One pool or protocol on an EVM chain Topic `eth.dextrades.proto`, message `DexBlockMessage`. The message is a flat list of `Trades`; each trade's `Dex` carries the pool contract in `SmartContract` plus `ProtocolName` and `ProtocolFamily`, and `Buy` and `Sell` each hold the counterparties and the assets that moved. ```python from evm import dex_block_message_pb2 TARGET_POOL = "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640" # Uniswap v3 USDC/WETH 0.05% def process_message(message): block = dex_block_message_pb2.DexBlockMessage() block.ParseFromString(message.value()) for trade in block.Trades: if "0x" + trade.Dex.SmartContract.hex() != TARGET_POOL: continue bought = trade.Buy.Assets[0] if trade.Buy.Assets else None print( trade.Dex.ProtocolName, "buyer", "0x" + trade.Buy.Buyer.hex(), "usd", bought.AmountInUSD if bought else None, "0x" + trade.TransactionHeader.Hash.hex(), ) ``` Filter on `trade.Dex.ProtocolFamily` instead of the pool to keep every trade of one protocol, or on `trade.Buy.Buyer` and `trade.Sell.Seller` to follow a trader. ## Related pages - [Kafka streams hub](/docs/category/kafka-streams) - [Python Kafka tutorial](/docs/streams/protobuf/kafka-protobuf-python) - [EVM protobuf streams](/docs/streams/protobuf/chains/EVM-protobuf/) - [Solana protobuf streams](/docs/streams/protobuf/chains/Solana-protobuf/) - [Sniper trade with Kafka](/docs/streams/sniper-trade-using-bitquery-kafka-stream) --- ## Flap.sh API - BSC Launchpad Token Analytics and Trading Data URL: https://docs.bitquery.io/docs/blockchain/BSC/flap-sh/ Flap.sh launchpad on BNB Chain: new token creation, token tax details, latest trades, OHLCV in USD and BNB, and real-time price streams. # Flap.sh API Flap.sh is a token launchpad platform on BNB Smart Chain (BSC) that enables users to create and launch new tokens with unique features including tax tokens and vanity addresses. This comprehensive guide covers how to track, analyze, and monitor Flap.sh tokens using Bitquery's GraphQL APIs. ## Overview Flap.sh provides a decentralized token launchpad where users can create tokens with customizable features. The platform supports standard tokens and tax tokens (v1 and v2), each with distinct contract addresses and token suffix patterns. ### Key Features - **Token Creation Tracking** – Monitor new token launches in real-time - **Tax Token Support** – Track both standard and tax-enabled tokens - **Vanity Addresses** – Tokens with custom suffixes (8888 for standard, 7777 for tax) - **Trading Analytics** – Comprehensive DEX trade data and OHLCV analysis - **Real-Time Streaming** – Live price and trade updates via GraphQL subscriptions ## Contract Addresses ### Core Contracts | Contract Type | Address | Description | |---------------|---------|-------------| | **Launchpad Contract** | `0x1de460f363AF910f51726DEf188F9004276Bf4bc` | Main launchpad contract for token creation | | **Portal Contract** | `0xe2cE6ab80874Fa9Fa2aAE65D277Dd6B8e65C9De0` | Portal contract for token management and events | ### Token Contract Templates | Token Type | Contract Address | Suffix Pattern | |------------|------------------|----------------| | **Tax Token V1** | `0x29e6383F0ce68507b5A72a53c2B118a118332aA8` | `7777` | | **Tax Token V2** | `0xae562c6A05b798499507c6276C6Ed796027807BA` | `7777` | | **Standard Token** | Various | `8888` | ### Documentation Resources - **Official Flap.sh Docs**: [https://docs.flap.sh/flap/](https://docs.flap.sh/flap/) - **Deployed Contract Addresses**: [https://docs.flap.sh/flap/developers/deployed-contract-addresses](https://docs.flap.sh/flap/developers/deployed-contract-addresses) - **ABI Information**: Available on the deployed contract addresses page ## Token Creation Tracking ### New Flap.sh Tokens Created Using Transfers API Track newly created Flap.sh tokens by monitoring transfers from the zero address with token addresses ending in the vanity suffix. **Try it live:** [Latest Flap.sh Token Created](https://ide.bitquery.io/New-Flapsh-Tokens-Created-Using-Transfers-API) ```graphql { EVM(network: bsc) { Transfers( where: {TransactionStatus: {Success: true}, any: [{Transfer: {Currency: {SmartContract: {endsWith: "7777"}}}} {Transfer: {Currency: {SmartContract: {endsWith: "8888"}}}} ], Transfer: {Sender: {is: "0x0000000000000000000000000000000000000000"}}} limit: {count: 100} orderBy: {descending: Block_Time} ) { Transaction { Hash } Transfer { Amount Sender Receiver Currency { Symbol Name SmartContract } } Block { Time Number } } } } ``` **Note:** For standard tokens, change the suffix from `"7777"` to `"8888"` in the query. ### Token Creation Using Events API Monitor token creation events directly from the Flap.sh portal contract for more detailed information. **Try it live:** [Latest Flap.sh Token Created Using Events](https://ide.bitquery.io/Latest-flapsh-token-created-using-events-data_1) ```graphql { EVM(dataset: realtime, network: bsc) { Events( orderBy: { descending: Block_Time } where: { LogHeader: { Address: { is: "0xe2ce6ab80874fa9fa2aae65d277dd6b8e65c9de0" } } Log: { SmartContract: { in: ["0xdda462c04e09abec8b90c879f039762552011d5a"] } Signature: { Name: { in: [ "TokenCreated", "TokenCurveSetV2", "TokenDexSupplyThreshSet", "TokenVersionSet", "TokenQuoteSet", "TokenMigratorSet", "TokenDexPreferenceSet", "FlapTokenTaxSet" ] } } } } ) { Block { Number Time } Transaction { Hash From To Type } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } LogHeader { Address } Log { Signature { Name Signature } SmartContract } } } } ``` ### Specific Token Creation Details Get detailed information about a specific token's creation and configuration events within a time range. **Try it live:** [Getting Details of Specific Flap.sh Token Creation](https://ide.bitquery.io/Getting-details-of-specific-flapsh-token-creation-using-the-events-api_4) ```graphql { EVM(dataset: combined, network: bsc) { Events( where: { Block: { Date: { since_relative: { days_ago: 5 } } } LogHeader: { Address: { is: "0xe2ce6ab80874fa9fa2aae65d277dd6b8e65c9de0" } } Log: { SmartContract: { in: ["0xdda462c04e09abec8b90c879f039762552011d5a"] } Signature: { Name: { in: [ "TokenCreated", "TokenCurveSetV2", "TokenDexSupplyThreshSet", "TokenVersionSet", "TokenQuoteSet", "TokenMigratorSet", "TokenDexPreferenceSet", "FlapTokenTaxSet" ] } } } Arguments: { includes: { Name: { is: "token" } Value: { Address: { is: "0x7e39a0fff2c6860d30bdd8e1133665b0a4b47777" } } } } } ) { Block { Number Time } Transaction { Hash From To Type } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Log { Signature { Name Signature } } } } } ``` ### Token Tax Details Retrieve tax configuration details for specific Flap.sh tokens. **Try it live:** [Getting Flap.sh Token Tax Details](https://ide.bitquery.io/Getting-Flapsh-token-tax-details-using-events-api_1) ```graphql { EVM(dataset: combined, network: bsc) { Events( where: { Block: { Date: { since_relative: { days_ago: 5 } } } LogHeader: { Address: { is: "0xe2ce6ab80874fa9fa2aae65d277dd6b8e65c9de0" } } Log: { SmartContract: { in: ["0xdda462c04e09abec8b90c879f039762552011d5a"] } Signature: { Name: { in: [ "TokenCreated", "TokenCurveSetV2", "TokenDexSupplyThreshSet", "TokenVersionSet", "TokenQuoteSet", "TokenMigratorSet", "TokenDexPreferenceSet", "FlapTokenTaxSet" ] } } } Arguments: { includes: { Name: { is: "token" } Value: { Address: { is: "0x7e39a0fff2c6860d30bdd8e1133665b0a4b47777" } } } } Transaction: { Hash: { is: "0x89491e82ed4a8b12408924992cb0c2359e443aed4e6c18eed87b0e7356f49cf9" } } } ) { Block { Number Time } Transaction { Hash From To } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Log { Signature { Name Signature } } } } } ``` ## Trading Analytics ### Latest Flap.sh Trades Monitor all recent trades across Flap.sh tokens using the DEXTrades API. **Try it live:** [Latest Flap.sh Trades Using DEXTrades API](https://ide.bitquery.io/Latest-Flapsh-trades-using-DEXTrades-API) ```graphql { EVM(dataset: realtime, network: bsc) { DEXTrades( limit: { count: 20 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Dex: { SmartContract: { is: "0xe2ce6ab80874fa9fa2aae65d277dd6b8e65c9de0" } } } } ) { Block { Time Number } Transaction { Hash From To Gas Cost CostInUSD } Trade { Buy { Amount AmountInUSD Buyer Seller Currency { Decimals Name Symbol SmartContract } Price PriceInUSD } Sell { Amount AmountInUSD Buyer Seller Currency { Name Symbol SmartContract } Price PriceInUSD } Dex { ProtocolName SmartContract OwnerAddress } } } } } ``` ### Trades for Specific Token Get trading activity for a specific Flap.sh token using DEXTradeByTokens API. **Try it live:** [Latest Flap.sh Trades for a Specific Token](https://ide.bitquery.io/Latest-Flapsh-trades-for-a-specific-token) ```graphql { EVM(dataset: realtime, network: bsc) { DEXTradeByTokens( limit: { count: 20 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Side: { Currency: { SmartContract: { is: "0x2fd5b2deae6002d924e3ff8b0f438dfac3a97777" } } } Dex: { SmartContract: { is: "0xe2ce6ab80874fa9fa2aae65d277dd6b8e65c9de0" } } } } ) { Block { Time Number } Transaction { Hash From To } Trade { Amount AmountInUSD Price PriceInUSD Buyer Seller Sender Currency { Name Symbol SmartContract } Side { Amount AmountInUSD Type Currency { Name Symbol SmartContract } } Dex { ProtocolName ProtocolFamily } Fees { Amount AmountInUSD Payer Recipient } } } } } ``` ## Price and OHLCV Data ### OHLCV Data in USD Get OHLCV (Open, High, Low, Close, Volume) data for Flap.sh tokens quoted in USD. **Try it live:** [OHLCV Data for Specific Flap.sh Token in USD](https://ide.bitquery.io/OHLCV-data-for-specific-Flapsh-token-in-USD) ```graphql { Trading { Tokens( where: { Token: { Id: { is: "bid:bsc:0x2fd5b2deae6002d924e3ff8b0f438dfac3a97777" } } Interval: { Time: { Duration: { eq: 1 } } } } limit: { count: 100 } orderBy: { descending: Block_Time } ) { Token { Address Id Name Symbol Network } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean SimpleMoving ExponentialMoving WeightedSimpleMoving } } } } } ``` ### OHLCV Data Against BNB Get OHLCV data for Flap.sh tokens paired with BNB. **Try it live:** [OHLCV Data for Specific Flap.sh Token Against BNB](https://ide.bitquery.io/OHLCV-data-for-specific-Flapsh-token-against-BNB) ```graphql { Trading { Pairs( where: { Token: { Id: { is: "bid:bsc:0x2fd5b2deae6002d924e3ff8b0f438dfac3a97777" } } Interval: { Time: { Duration: { eq: 1 } } } } limit: { count: 100 } orderBy: { descending: Block_Time } ) { Token { Address Id Name Symbol Network } QuoteToken { Address Id Name Symbol Network } Market { Program Name } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean SimpleMoving ExponentialMoving WeightedSimpleMoving } } } } } ``` ## Real-Time Streaming ### Stream Latest Prices for Flap.sh Tokens Subscribe to real-time price updates for all Flap.sh tokens. **Try it live:** [Stream for Latest Prices for Flap.sh Tokens](https://ide.bitquery.io/Stream-for-latest-prices-for-Flapsh-tokens) ```graphql subscription { Trading { Pairs( where: { Market: { Id: { is: "bid:bsc:0xe2ce6ab80874fa9fa2aae65d277dd6b8e65c9de0" } } Interval: { Time: { Duration: { eq: 1 } } } } ) { Token { Address Id Name Symbol Network } QuoteToken { Address Id Name Symbol Network } Market { Program Name } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean SimpleMoving ExponentialMoving WeightedSimpleMoving } } } } } ``` ## Token Types and Suffixes ### Understanding Flap.sh Token Types Flap.sh supports multiple token types with distinct characteristics: #### Standard Tokens - **Suffix Pattern**: `8888` - **Description**: Standard ERC-20 compatible tokens without tax mechanisms - **Use Case**: Traditional token launches with no transfer fees #### Tax Tokens - **Suffix Pattern**: `7777` - **Versions**: - **Tax Token V1**: Contract `0x29e6383F0ce68507b5A72a53c2B118a118332aA8` - **Tax Token V2**: Contract `0xae562c6A05b798499507c6276C6Ed796027807BA` - **Description**: Tokens with built-in transfer tax mechanisms - **Use Case**: Revenue-generating tokens with automatic fee collection ### Identifying Token Types You can identify Flap.sh tokens by checking the last 4 characters of their contract address: - Tokens ending in `8888` are standard tokens - Tokens ending in `7777` are tax tokens ## Use Cases ### Token Launch Monitoring - Track new token launches in real-time - Monitor token creation events and configurations - Analyze launch patterns and trends ### Trading Analytics - Monitor trading volume and liquidity - Track price movements and volatility - Analyze trader behavior and patterns ### Tax Token Analysis - Monitor tax token performance - Compare tax token vs standard token metrics - Analyze fee collection and distribution ### Portfolio Tracking - Track holdings across multiple Flap.sh tokens - Monitor portfolio performance in real-time - Calculate P&L for Flap.sh token investments ### Arbitrage Detection - Identify price discrepancies across markets - Monitor cross-DEX arbitrage opportunities - Track flash loan usage on Flap.sh tokens ## Best Practices 1. **Use Real-Time Dataset for Live Data**: Use `dataset: realtime` for current token creation and trading activity 2. **Use Combined Dataset for Historical Analysis**: Use `dataset: combined` for comprehensive historical data 3. **Filter by Token Type**: Use suffix patterns (`7777` or `8888`) to filter by token type 4. **Monitor Portal Contract Events**: Track portal contract events for detailed token configuration changes 5. **Implement Rate Limiting**: Respect API limits when building applications 6. **Cache Frequently Used Data**: Store token metadata locally to reduce API calls ## Related Documentation - [BSC Blockchain API](/docs/blockchain/BSC/) – BNB Smart Chain documentation - [DEX Trades API](/docs/schema/evm/dextrades) – DEX trading data documentation - [Events API](/docs/schema/evm/events) – Smart contract events documentation - [Transfers API](/docs/schema/evm/transfers) – Token transfer tracking - [Trading APIs](/docs/trading/crypto-price-api/) – Price and OHLCV data - [GraphQL Subscriptions](/docs/subscriptions/subscription) – Real-time data streaming ## Support For questions or issues: - [Bitquery Documentation](https://docs.bitquery.io) - [Flap.sh Official Documentation](https://docs.flap.sh/flap/) - [Bitquery IDE](https://ide.bitquery.io) --- ## Flap.sh API on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/flap-sh-api/ Flap.sh API on Robinhood Chain: TokenCreated launches, bonding-curve buys and sells, DEX graduations and flap_v5 trades via Bitquery GraphQL and WebSocket. # Flap.sh API on Robinhood Chain **Flap.sh** is a token launchpad on the **Robinhood** network. This guide shows how to track **newly launched Flap.sh tokens**, **Flap.sh trades**, and **lifecycle events** — token graduations, bonding-curve progress, supply changes, tax paid, vanity tokens, and social messages — with Bitquery GraphQL APIs, using the `EVM(network: robinhood)` and `Trading` cubes. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) - [Pons Launchpad API on Robinhood Chain](/docs/blockchain/robinhood/pons-api) — bonding-curve launchpad, graduations, Uniswap v4 pools - [Pools.trade API on Robinhood](/docs/blockchain/robinhood/pools-trade-api) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers) - [WebSocket subscriptions](/docs/subscriptions/websockets/) ::: --- ## Flap.sh contracts Flap.sh is **not a single contract**. A router takes the user's transaction, a factory mints the token, and a separate bonding-curve engine handles every buy and sell. Each role emits a different set of events from a different address, and more than one address is live in each role. | Role | Address | Emits | | --- | --- | --- | | **Router proxy** (entry point and log emitter) | `0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09` | **Every Flap.sh event.** `LogHeader.Address` is this proxy on `TokenCreated`, `TokenBought`, `TokenSold`, progress, supply and tax events; it is also `Transaction.To` on launch and trade transactions. | | **Token factory implementations** (`Log.SmartContract`, more exist) | `0x78eb178d94739b8adf199543924e47e9547c4924`
`0x549574ddf0d72928f2041c17daab2097dd46d815` | `TokenCreated`, `TokenCurveSetV2`, `FlapTokenTaxSet`, `TokenQuoteSet`, `TokenVersionSet`, `TokenDexPreferenceSet`, `TokenDexSupplyThreshSet`, `TokenMigratorSet` | | **Vanity token factory implementations** (`Log.SmartContract`) | `0xa2fb48fefb15f777ec6ac3857164550ee93c1f25`
`0x52e3eb4f18dfb8215e17d27dee5718075f6c2639` | `VanityTokenCreated`, plus the same `TokenCreated` / `TokenCurveSetV2` pair | | **Bonding-curve engine implementations** (`Log.SmartContract`, more exist) | `0x87a697bf7fbe28dc1eccc4d9b4bd1cfa76885f93`
`0x2a50c45b5cbb9e5c735f094c6386c39f8ffbc655` | `TokenBought`, `TokenSold`, `TaxV2OnBondingCurvePaid`, `FlapTokenProgressChanged`, `FlapTokenCirculatingSupplyChanged` | | Field | Value | | --- | --- | | **Launch mint `Amount`** | `1000000000` (1 billion, decimal-normalized) | :::info The router proxy is the emitter; the implementations rotate `0x26605f32…` is the `LogHeader.Address` of every Flap.sh event and the `Transaction.To` of every launch and trade, so it is the right address to pin queries to. The factory and curve-engine contracts are implementations behind that proxy: they show up as `Log.SmartContract`, more than one is live per role, and new ones appear when Flap.sh upgrades. Match events by `Log.Signature.Name` with `LogHeader.Address` pinned to the proxy, and read `Log.SmartContract` only when you need to know which implementation handled a row. Launches also arrive through vanity routers; pin `Transaction.To` to the router only for mint-transfer queries. ::: :::note Datasets Transfers, Events and Calls queries default to the realtime dataset, which holds only the most recent days on Robinhood; add `dataset: combined` or `dataset: archive` for history. Flap.sh trades also appear in the `Trading` cube as `Protocol: flap_v5`, which holds a rolling window of roughly the last 30 days. ::: --- ## Newly launched tokens Flap.sh launches can be detected via decoded **`TokenCreated`** events or via **mint transfers** from the zero address. ### Flap.sh newly created tokens using logs (`TokenCreated`) Filter Flap.sh `TokenCreated` events and decode argument values (token address, metadata fields, and related parameters). ▶️ [Run in IDE](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-logs-TokenCreated) · [WebSocket stream](https://ide.bitquery.io/Flap-sh-Newly-created-tokens-using-logs-TokenCreated---Websocket) ```graphql { EVM(network: robinhood) { Events( limit: {count: 10} where: { Log: {Signature: {Name: {is: "TokenCreated"}}} LogHeader: {Address: {is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"}} } ) { Transaction { Hash From To } Log { Signature { Name } SmartContract } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ### Flap.sh newly created tokens using transfer data Track Flap.sh mints as transfers from the zero address with amount `1000000000` in transactions sent to the Flap.sh contract. ▶️ [Run in IDE](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-transfer-data) · [WebSocket stream](https://ide.bitquery.io/Flap-Sh-Newly-created-tokens-using-transfer-data---Websocket) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` :::note Amounts are decimal-normalized Bitquery's `Transfer.Amount` is already adjusted for the token's `Decimals`, so `1000000000` means 1 billion whole tokens — not the raw on-chain integer. Compare against the normalized value, not the raw one. ::: --- ## Flap.sh trades Query trades on Flap.sh markets using the `Trading.Trades` cube, scoped by the Flap.sh contract as `Pair.Market.Program`. This example returns trades from the last hour. ```graphql { Trading { Trades( limit: {count: 10} where: {Pair: {Market: {Program: {is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"}}}, Block: {Time: {since_relative: {hours_ago: 1}}}} ) { Side Supply { CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Market { Protocol ProtocolFamily Address Program Network } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } } } } ``` :::tip Stream the same query Change the operation type from a query to a `subscription` in the Bitquery IDE to receive Flap.sh trades in real time over WebSocket. ::: --- ## Event-specific APIs Beyond buy/sell trades, Flap.sh emits lifecycle events across several contracts (bonding-curve engine, factories, and the router). Because a given event is emitted by more than one contract, filter these queries by `Log.Signature.Name` rather than a single address. Each event includes a `token` argument identifying the affected token, so you can add `Arguments: {includes: {Name: {is: "token"}, Value: {Address: {is: "0x..."}}}}` to scope any query to one token. :::tip Stream any event Every query below can be run as a real-time stream — change the operation type to `subscription` in the Bitquery IDE. ::: ### Raw bonding-curve trades (`TokenBought` / `TokenSold`) The bonding-curve engine emits its own decoded trade events on the Flap.sh contract with on-chain-exact values. `TokenBought` arguments: `ts`, `token`, `buyer`, `amount`, `eth`, `fee`, `postPrice` — swap the signature name to `TokenSold` for sells. Use these when you need the exact fee and post-trade curve price; use `Trading.Trades` (above) for decimal-normalized, USD-priced trades. ```graphql { EVM(network: robinhood) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { Log: {Signature: {Name: {is: "TokenBought"}}} LogHeader: {Address: {is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"}} } ) { Block { Time } Transaction { Hash From } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } } } } } } ``` ### Token graduations (`LaunchedToDEX`) The most important lifecycle signal: a token completed its bonding curve and was **launched to a DEX**. The event returns the new `pool` address (use it with the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) to follow post-graduation trading), the migrated token `amount`, and the `eth` seeded into the pool. :::caution `LaunchedToDEX` is not exclusive to Flap.sh Other Robinhood Chain launchpads emit an event with this same name. The query below returns graduations across all of them. To keep the feed Flap.sh-only, add a `LogHeader.Address` filter for the curve engines listed in [Flap.sh contracts](#flapsh-contracts), or check the graduated `token` against a Flap.sh `TokenCreated` / `TokenCurveSetV2` pair before acting on it. ::: ```graphql { EVM(network: robinhood) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "LaunchedToDEX"}}}} ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` Arguments: `token` (graduated token), `pool` (new DEX pool address), `amount` (tokens moved to the pool), `eth` (native seeded into the pool). ### Bonding-curve progress (`FlapTokenProgressChanged`) Track how close a token is to graduation. `newProgress` is scaled to `1e18`, so `562290208719467141` ≈ **56.2%**. Great for progress bars and "about to graduate" alerts. ```graphql { EVM(network: robinhood) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "FlapTokenProgressChanged"}}}} ) { Block { Time } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` Arguments: `token`, `newProgress` (fraction of the curve completed, scaled by `1e18` → divide by `1e18` for a `0–1` ratio, or `×100` for a percentage). ### Circulating supply changes (`FlapTokenCirculatingSupplyChanged`) Live circulating-supply updates for a token — useful for accurate off-chain market-cap math. `newSupply` is the raw on-chain integer (divide by the token's `1e18` decimals). ```graphql { EVM(network: robinhood) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "FlapTokenCirculatingSupplyChanged"}}}} ) { Block { Time } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` Arguments: `token`, `newSupply` (new circulating supply, raw integer). ### Bonding-curve tax paid (`TaxV2OnBondingCurvePaid`) Tax/fee revenue paid on the bonding curve, per token. Aggregate `amount` over time (or per token) for fee analytics. ```graphql { EVM(network: robinhood) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "TaxV2OnBondingCurvePaid"}}}} ) { Block { Time } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` Arguments: `token`, `amount` (tax paid in native units, raw integer). ### Vanity tokens created (`VanityTokenCreated`) A separate creation channel for **vanity tokens** — those with custom address suffixes (`8888`, `7777`). Complements the standard `TokenCreated` event on the [launches page](/docs/blockchain/robinhood/robinhood-meme-coin-launches). ```graphql { EVM(network: robinhood) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "VanityTokenCreated"}}}} ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } } } } } } ``` Arguments: `token` (new vanity token), `creator`, `beneficiary`. ### Social messages (`MsgSent`) Flap.sh links social content to tokens through `MsgSent`. The `message` string carries structured commands such as `ADD_TWEET::`, tying a token to a tweet or other social metadata. ```graphql { EVM(network: robinhood) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "MsgSent"}}}} ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } } } } } ``` Arguments: `sender`, `token`, `message` (e.g. `ADD_TWEET::2077406373457871178`). --- ## FAQ ### How do I detect a newly launched Flap.sh token? Use the **`TokenCreated`** event on the Flap.sh contract (`0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09`) for decoded arguments, or the **mint-transfer** pattern — a transfer from the zero address with `Amount` `1000000000` where `Transaction.To` is the Flap.sh contract. ### How do I get Flap.sh trades? Query `Trading.Trades` filtered by `Pair.Market.Program: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"`. Add a `Block.Time` filter to scope to a time window, or switch the operation to `subscription` to stream trades live. ### How do I know when a Flap.sh token graduates to a DEX? Filter events by `Log.Signature.Name: "LaunchedToDEX"`. Each event gives the graduated `token`, the new `pool` address, and the token/native `amount` seeded into the pool. Run it as a `subscription` for real-time graduation alerts. ### How do I track a token's bonding-curve progress? Use the `FlapTokenProgressChanged` event. `newProgress` is scaled by `1e18`, so divide by `1e18` for a `0–1` ratio (or `×100` for a percentage). Scope to a single token by matching the `token` argument. ### Why do the event queries filter by `Log.Signature.Name` instead of a contract address? Flap.sh emits its events from several contracts — separate factories, vanity factories, and bonding-curve engines, each with more than one live address (see [Flap.sh contracts](#flapsh-contracts)). Filtering by the signature name captures the event across all of them. Add an `Arguments.includes` filter on the `token` argument to scope to one token. ### Can a signature-name filter pick up other protocols? Yes, for generic names. `TokenCreated` in particular is emitted by several unrelated launchpads on Robinhood Chain, and `LaunchedToDEX` is emitted by protocols other than Flap.sh. Names carrying the `Flap` prefix — `FlapTokenProgressChanged`, `FlapTokenCirculatingSupplyChanged`, `FlapTokenTaxSet` — are unambiguous; the generic ones are not. If a feed must be Flap.sh-only, add a `LogHeader.Address` filter pinned to the factory and curve addresses in [Flap.sh contracts](#flapsh-contracts), or cross-check the token against a `TokenCurveSetV2` event, which the Flap.sh factories always emit alongside `TokenCreated`. --- ## Next steps - Stream **`LaunchedToDEX`** for real-time graduation alerts, then follow the new pool with the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades). - Track other Robinhood launchpads and bots with the [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches). - Explore prices, OHLCV, whale trades, and top traders in the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades). - Inspect holder and wallet flows with [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers). --- ## Four Meme API — BSC Trades, Bonding Curve & Prices URL: https://docs.bitquery.io/docs/blockchain/BSC/four-meme-api/ Four Meme on BSC: get trades, prices, bonding curve progress, PancakeSwap migrations, top traders and top tokens, plus the exchange contract address. # Four Meme API :::note For launch tracking, trades and graduation coverage with plans and trial access, see the [Four.meme API](https://bitquery.io/products/fourmeme-api) product page. ::: :::tip Need real-time Four.meme data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Four.meme examples using `Trading.Trades` are also shown in the **"Trader-Focused Trade APIs"** section below. Use the raw chain-level queries on this page when you need **historical Four.meme data older than ~30 days** or call / event context. ::: Bitquery exposes **four.meme (Four Meme)** on **BNB Chain** through GraphQL: **live trades** (`fourmeme_v1`), **TokenCreate** events on the exchange proxy, **bonding curve** math from proxy balances, **migrations** to PancakeSwap, **OHLCV**, **liquidity** events, and **leaderboards**. Use **subscriptions** for real-time streams and **`dataset: combined`** for history. The Four Meme exchange proxy used in examples is **`0x5c952063c7fc8610ffdb798152d69f0b9550762b`** (see below). The sections below are example queries and streams. For other fields, contact [support](https://t.me/Bloxy_info). Need low-latency BSC data? See [Streams](/docs/streams/) and contact us for a trial. For **mempool (pre-confirmation)** Four Meme data, see the dedicated [Four Meme Mempool API](/docs/blockchain/BSC/four-meme-mempool-API/) page. For live DEX prices and 24h volume across Four.meme tokens, see [DEXrabbit's Four.meme category](https://dexrabbit.bitquery.io/categories/four-meme-ecosystem). You may also be interested in: - [Crypto Price API ➤](/docs/trading/crypto-price-api/) - [BSC Pancake Swap APIs ➤](/docs/blockchain/BSC/pancake-swap-api/) - [BSC DEX Trades ➤](/docs/blockchain/BSC/bsc-dextrades/) - [Pump.fun API ➤](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) :::note To query or stream data via GraphQL outside the Bitquery IDE, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token](/docs/authorization/how-to-generate/) ::: ## What is the Four Meme exchange contract address on BSC? {#what-is-the-four-meme-exchange-contract-address-on-bsc} The **Four Meme / four.meme exchange proxy** on BNB Chain is: `0x5c952063c7fc8610ffdb798152d69f0b9550762b` Use it in **`Transaction.To`**, **`LogHeader.Address`**, or **`Balance.Address`** filters when you listen for **TokenCreate**, **LiquidityAdded**, or **migration**-related logs. **`DEXTrades`** for the launchpad use **`Dex.ProtocolName: { is: "fourmeme_v1" }`**. --- ### Table of Contents ### 1. Four Meme Trading & Market Data (BSC) - [What is the Four Meme exchange contract address on BSC? ➤](#what-is-the-four-meme-exchange-contract-address-on-bsc) - [How do I get live Four Meme trades using Bitquery? ➤](#subscribe-the-latest-trades-on-four-meme) - [Get Latest Buys and Sells for a Four Meme Token ➤](#get-latest-buys-and-sells-for-a-four-meme-token) - [Get Trade Metrics of a Four Meme Token ➤](#get-trade-metrics-of-a-four-meme-token) - [Get Metadata for a Newly Created Four Meme Token ➤](#metadata-for-a-newly-created-token) - [Get latest price of a Four.meme token ➤](#get-latest-price-of-a-fourmeme-token) - [Get ATH price of a Four Meme Token ➤](#get-ath-price-of-a-four-meme-token) - [Get Price Change Percentage for a Four Meme Token ➤](#get-price-change-percentage-for-a-four-meme-token) - [How do I get Four Meme OHLCV data for a token? ➤](#get-ohlcv-data-of-a-four-meme-token) - [Get Trade Volume and Number of Trades for a Four Meme Token ➤](#get-trade-volume-and-number-of-trades-for-a-four-meme-token) ### 2. Token Lifecycle, Liquidity & Migrations - [How do I get newly created tokens on Four Meme? ➤](#get-newly-created-tokens-on-four-meme) - [How do I stream Four Meme token creation events in real time? ➤](#how-do-i-stream-four-meme-token-creation-events-in-real-time) - [Get Four.Meme Tokens created by a specific Dev ➤](#get-fourmeme-tokens-created-by-a-specific-dev) - [Get Dev Address of a Four.meme token ➤](#get-dev-address-of-a-fourmeme-token) - [Get Dev Token Holding percentage ➤](#get-dev-token-holding-percentage) - [Get Top 10 Holders percentages ➤](#get-top-10-holders-percentages) - [How do I detect Four Meme token migrations to PancakeSwap? ➤](#track-all-four-meme-tokens-that-have-migrated-to-pancakeswap) - [How do I get bonding curve progress for a Four Meme token? ➤](#bonding-curve-progress-api-for-fourmeme-token) - [Get Four Meme Tokens which are above 95% Bonding Curve Progress ➤](#get-four-meme-tokens-which-are-above-95-bonding-curve-progress) - [Get liquidity of a Four Meme token ➤](#get-liquidity-of-a-four-meme-token) - [Track Liquidity Add Events for All Tokens on Four Meme ➤](#track-liquidity-add-events-for-all-tokens-on-four-meme) - [Track Liquidity Add Events for a Token on Four Meme ➤](#track-liquidity-add-events-for-a-token-on-four-meme) - [Check if a Four.meme Token is Phishy ➤](#check-if-a-fourmeme-token-is-phishy) ### 3. Trader Insights - [Monitor trades of traders on Four meme ➤](#monitor-trades-of-traders-on-four-meme) - [Track Latest and Historical Trades of a Four Meme User ➤](#track-latest-and-historical-trades-of-a-four-meme-user) - [Top Buyers for a Token on Four Meme ➤](#top-buyers-for-a-token-on-four-meme) - [Top Traders of a token ➤](#top-traders-of-a-token) ### 4. Top Tokens & Getting Started - [Get Realtime Market Cap and Price of a Four Meme Token ➤](#get-realtime-market-cap-and-price-of-a-four-meme-token) - [Top Tokens by marketcap ➤](#top-tokens-by-marketcap) - [Top Tokens by launch marketcap ➤](#top-tokens-by-launch-marketcap) - [How do I get top tokens by volume on Four Meme? ➤](#top-tokens-by-buys-sells-volume-price-change-buyers-sellers) - [Top Four Meme tokens by realtime market cap (activity filter) ➤](#top-four-meme-tokens-by-realtime-marketcap) - [Top Tokens by liquidity ➤](#top-tokens-by-liquidity) - [Bitquery DEX Data Access Options ➤](#bitquery-dex-data-access-options) - [Getting Started with Bitquery ➤](#getting-started-with-bitquery) ### 5. Frequently asked questions (AEO) - [Four Meme on Bitquery — quick answers ➤](#frequently-asked-questions-four-meme-bitquery) ### 6. Video Tutorials - [Video Tutorial | How to get Bonding Curve Progress of any Four Meme Token ➤](#video-tutorial--how-to-get-bonding-curve-progress-of-any-four-meme-token) - [Video Tutorial | How to track the Four Meme Tokens which are about to Graduate in Realtime ➤](#video-tutorial--how-to-track-the-four-meme-tokens-which-are-about-to-graduate-in-realtime) - [Video Tutorial | How to get Liquidity of a Four Meme Token ➤](#video-tutorial--how-to-get-liquidity-of-a-four-meme-token) - [Video Tutorial | How to get Top Traders of a Four Meme Token on Solana Four Meme DEX ➤](#video-tutorial--how-to-get-top-traders-of-a-four-meme-token-on-solana-four-meme-dex) - [Video Tutorial | How to Get the OHLCV Data of a token on Four Meme DEX ➤](#video-tutorial--how-to-get-the-ohlcv-data-of-a-token-on-four-meme-dex) ### 7. Real World Projects - [Real World Projects with Four Meme API ➤](#real-world-projects-with-four-meme-api) ## Bitquery DEX Data Access Options - **GraphQL APIs**: Query historical and real-time EVM data with flexible filtering and aggregation - **Real-time Streams**: Subscribe to live EVM blockchain events via WebSocket subscriptions - **Data Store exports**: parsed Parquet you download from S3 or Cloudflare R2; custom exports can go to your own bucket or warehouse. See the [Bitquery Data Store](https://bitquery.io/datastore). - **Kafka Streams**: High-throughput data streaming for enterprise applications ## Getting Started with Bitquery: - [Learning Track](/docs/start/learning-path/): Learning track to get started with Bitquery GraphQL APIs and streams. - [BSC DEX Trades](/docs/blockchain/BSC/bsc-dextrades/): Real time DEX Trading data via examples. - [BSC Uniswap APIs](/docs/blockchain/BSC/bsc-uniswap-api/): Uniswap Trades on BSC network with the help of examples. - [BSC Pancake Swap APIs](/docs/blockchain/BSC/pancake-swap-api/): Pancake swap Trades on BSC network with the help of examples. - [Trade APIs](/docs/trading/crypto-price-api/examples/): Multi-chain Trade API Examples. ## How do I detect Four Meme token migrations to PancakeSwap? {#track-all-four-meme-tokens-that-have-migrated-to-pancakeswap} This query tracks four meme token migrations to Pancakeswap in realtime by monitoring transactions sent to the Four Meme factory address (`0x5c952063c7fc8610ffdb798152d69f0b9550762b`) and filtering for `PairCreated` and `PoolCreated` events. These events are emitted when a token graduates from Four Meme and migrates to Pancakeswap. Test it [here](https://ide.bitquery.io/four-meme-migration-to-pancakeswap).
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { Events( where: { Log: { Signature: { Name: { in: ["PairCreated"] } } } Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } } ) { Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } } } Transaction { Hash } } } } ```
## Check if a four meme token has migrated or not {#check-if-a-four-meme-token-has-migrated-or-not} Below query will only show response if a the mentioned four meme tokens have migrated to Pancakeswap. Note: Please use a `Block{Date}` filter to minimize the data processing and hence the query processing time and get fast responses. Try the query [here](https://ide.bitquery.io/if-token-migrated-from-four-meme-or-not_4).
Click to expand GraphQL query ```graphql { EVM(network: bsc, dataset: combined) { DEXTradeByTokens( where: {Block: {Date: {since: "2025-10-10"}}, Trade: {Dex: {OwnerAddress: {in: ["0xca143ce32fe78f1f7019d7d551a6402fc5350c73"]}}, Currency: {SmartContract: {in: ["0xfe9936abb3c0659733ff0d03cf41d17b04c84444", "0x9cb5ae8ec79c72bd70b415efb7ff936e707f4444"]}}}} ) { count Trade { Currency { SmartContract } } } } } ```
## How do I get bonding curve progress for a Four Meme token? {#bonding-curve-progress-api-for-fourmeme-token} Below query will give you amount of `left tokens` put it in the below given simplied formulae and you will get Bonding Curve progress for the token. ### Bonding Curve Progress Formula - **Formula**: BondingCurveProgress = 100 - ((leftTokens \* 100) / initialRealTokenReserves) Where: - leftTokens = realTokenReserves - reservedTokens - initialRealTokenReserves = totalSupply - reservedTokens - **Definitions**: - `initialRealTokenReserves` = `totalSupply` - `reservedTokens` - `totalSupply`: 1,000,000,000 (Four meme Token) - `reservedTokens`: 200,000,000 - Therefore, `initialRealTokenReserves`: 800,000,000 - `leftTokens` = `realTokenReserves` - `reservedTokens` - `realTokenReserves`: Token balance at the market address. :::note **Simplified Formula**: BondingCurveProgress = 100 - (((balance - 200000000) \* 100) / 800000000) ::: ### Additional Notes - **Balance Retrieval**: - The `balance` is the four meme token balance at this Four Meme: Proxy address (0x5c952063c7fc8610FFDB798152D69F0B9550762b). - Use this query to fetch the balance:
Click to expand GraphQL query ```graphql query MyQuery($token: String) { EVM(network: bsc) { Balances( where: { Balance: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } Currency: { SmartContract: { is: $token } } } ) { Currency { Name Symbol } Balance { Amount } } } } ```
Click to expand Query Varibles (Paste this in variables section on IDE) ```json { "token": "0x13378bcbbc386eea99f09bc716f2c80979484444" } ```
## Get Four Meme Tokens which are above 95% Bonding Curve Progress Using the above Bonding Curve formula, we can calculate the token balances for the Four Meme Proxy contract (0x5c952063c7fc8610FFDB798152D69F0B9550762b) corresponding to approximately 95% to 100% progress along the bonding curve, that comes out to be `200,000,000` to `240,000,000`. The tokens in the response are arranged in the ascending order of Bonding Curve Percentage, i.e., 95% to 100%.
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc) { Balances( limit: { count: 100 } where: { Balance: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } } orderBy: { descending: Balance_Amount } ) { Currency { SmartContract Name } Balance { Amount(selectWhere: { ge: "200000000", le: "240000000" }) } } } } ```
## How do I get newly created tokens on Four Meme? {#get-newly-created-tokens-on-four-meme} [Run Query](https://ide.bitquery.io/track-Four-meme-token-creation-using-events) This query retrieves newly created tokens on Four Meme by listening to the `TokenCreate` event. The response provides: **Token Information:** - **creator**: Wallet address of the token creator - **token**: Contract address of the newly created token - **name**: Token name - **symbol**: Token symbol/ticker - **totalSupply**: Total supply **Launch Details:** - **requestId**: Unique identifier for the token creation - **launchTime**: Unix timestamp of when the token launched - **launchFee**: Fee paid
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: bsc) { Events( where: { Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Log: { Signature: { Name: { is: "TokenCreate" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Log { Signature { Name Signature } } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } Name Type } Transaction { Hash To From } } } } ```
### How do I stream Four Meme token creation events in real time? {#how-do-i-stream-four-meme-token-creation-events-in-real-time} Use a **GraphQL subscription** on `EVM(network: bsc)` with the same `TokenCreate` filter as the query above. Each matching log is pushed as it appears. You can start from the same saved query in the IDE and change the operation type to **subscription**: [Token creation (IDE)](https://ide.bitquery.io/track-Four-meme-token-creation-using-events).
Click to expand GraphQL subscription ```graphql subscription { EVM(network: bsc) { Events( where: { Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Log: { Signature: { Name: { is: "TokenCreate" } } } } ) { Log { Signature { Name Signature } } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } Name Type } Transaction { Hash To From } } } } ```
You can refer to this [example](/docs/blockchain/BSC/four-meme-api/#subscribe-the-latest-trades-on-four-meme) to track latest trades of a token on other particular DEX's such as Pancake Swap. ## Get Four.Meme Tokens created by a specific Dev This API fetches Four.Meme tokens created by a specific dev on BSC by tracking token minting transfers signed by a particular dev. `Dev Address` here in example is `0x9c75588640605d46b42f2d64c5c2e993de251210`. Use a date filter based on your needs — shorter time ranges mean faster execution and reduced query time. [Run Query](https://ide.bitquery.io/token-created-by-specific-dev)
Click to expand GraphQL query ```graphql { EVM(network: bsc, dataset: combined) { Transfers( where: { Block: { Date: { since: "2025-08-01" } } Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } } Transaction: { From: { in: ["0x9c75588640605d46b42f2d64c5c2e993de251210"] } } } ) { Transaction { From To } Transfer { Sender Receiver Amount Currency { Name Symbol SmartContract } } } } } ```
## Get Dev Address of a Four.meme token Fetches the developer address that created a specific Four.Meme token on BSC by tracing the minting transfer (from the zero address) of that token’s smart contract. Use a date filter based on your needs — shorter time ranges make the query execute faster and return results more efficiently. Token Address in this example is 0xd284aa8910fe1dcac70f3e28ddd8cc61dac94444. [Run Query](https://ide.bitquery.io/check-who-created-this-token)
Click to expand GraphQL query ```graphql { EVM(network: bsc, dataset: combined) { Transfers( where: { Block: { Date: { since: "2025-08-01" } } Transfer: { Currency: { SmartContract: { is: "0xd284aa8910fe1dcac70f3e28ddd8cc61dac94444" } } Sender: { is: "0x0000000000000000000000000000000000000000" } } } ) { Transaction { From To } Transfer { Sender Receiver Amount Currency { Name Symbol SmartContract } } } } } ```
## Get Dev Token Holding percentage Calculates what percentage of total token supply is held by the developer address for a specified Four Meme token. [Run Query](https://ide.bitquery.io/dev-holding-percent#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { Address: { is: "0x749ca8e9fcfaf40796e8654ae7624b738c0b9a9d" } Currency: { SmartContract: { is: "0x4dE1486E27237F170Cd92fF1Efb17eF4c2C74444" } } } TransactionStatus: { Success: true } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { TokenBalance { Address Currency { Name Symbol SmartContract } Balance: PostBalance PostBalanceInUSD TotalSupply TotalSupplyInUSD } holding_percentage: calculate( expression: "$TokenBalance_Balance / 10000000" ) } } } ```
## Get Top 10 Holders percentages Calculates the percentage of total supply held by the top 10 holders of a specific Four Meme token on BSC. [Run Query](https://ide.bitquery.io/top-10-holders-percentage#)
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc) { TransactionBalances( where: { TokenBalance: { Currency: { SmartContract: { is: "0x4dE1486E27237F170Cd92fF1Efb17eF4c2C74444" } } } TransactionStatus: { Success: true } } limit: { count: 10 } orderBy: { descendingByField: "holding_percentage" } ) { TokenBalance { Address Currency { Name Symbol SmartContract } Balance: PostBalance(maximum: Block_Time) } holding_percentage: calculate( expression: "$TokenBalance_Balance / 10000000" ) } } } ```
## How do I get live Four Meme trades using Bitquery? {#subscribe-the-latest-trades-on-four-meme} Using subscriptions you can subscribe to the latest trades on Four Meme as shown in this [example](https://ide.bitquery.io/Latest-trades-on-fourmeme). The subscription returns latest trade info such as buyers and sellers, buy and sell currency details and amount of currency.
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } } } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount } Sell { Seller Currency { Name Symbol SmartContract } Amount } } Transaction { Hash } } } } ```
## Get Latest Buys and Sells for a Four Meme Token [This](https://ide.bitquery.io/Latest-buys-and-sells-for-a-four-meme-coin_1) query retrieves the most recent token buy and sell trades of a specific token on Four Meme Exchange.
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc, dataset: combined) { buys: DEXTrades( where: { Trade: { Buy: { Currency: { SmartContract: { is: $currency } } } Dex: { ProtocolName: { is: "fourmeme_v1" } } } } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Amount Buyer Price PriceInUSD Seller } Sell { Currency { Name Symbol SmartContract } } } } sells: DEXTrades( where: { Trade: { Sell: { Currency: { SmartContract: { is: $currency } } } Success: true Dex: { ProtocolName: { is: "fourmeme_v1" } } } } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Currency { Name Symbol SmartContract } } Sell { Amount Buyer Price PriceInUSD Seller } } } } } ``` ```json { "currency": "0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40" } ```
You can also check if the token is listed on other DEX using this [example](/docs/blockchain/BSC/bsc-dextrades/#get-all-dexs-where-a-specific-token-is-listed). ## Get Trade Metrics of a Four Meme Token Use the below query to get trade metrics like volume and trades for a token in different time frames, such as `24 hours`, `1 hour` and `5 minutes`. Test it [here](https://ide.bitquery.io/volume-and-trades-for-a-token-in-different-time-frames_3).
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } }, Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract } } volume_24hr: sum(of: Trade_Side_AmountInUSD) volume_1hr: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) trades_24hr: count trades_1hr: count( if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) trades_5min: count( if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) } } } ``` ```json { "currency": "0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40" } ```
## Get latest price of a Four.meme token Use the [Price Index](/docs/trading/crypto-price-api/) to track the price of any token trading on-chain. Here's an example of [tracking Four.meme token prices](https://ide.bitquery.io/latest-token-price-on-four-meme-dex).
Click to expand GraphQL query ```graphql { Trading { Pairs( where: {Price: {IsQuotedInUsd: false}, Market: {Network: {is: "Binance Smart Chain"}, Program: {is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b"}}, Token: {Address: {is: "0x2157de505dfaa51676d6d22c0424551fbeaf4444"}}, Interval: {Time: {Duration: {eq: 60}}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { Market { Address Network Program Protocol ProtocolFamily } Price { Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } Ohlc { Close High Low Open } } Token { Address Name Symbol } QuoteToken { Address Name Symbol } Volume { Base Usd } } } } ```
## Get ATH price of a Four Meme Token Fetches the All-Time High (ATH) price of a specific Four.Meme token on BSC, using the `DEXTradeByTokens` dataset to calculate the 98th percentile of trade prices (approximate ATH). Try the API [here](https://ide.bitquery.io/four-meme---token-ATH-price). **Tune the parameters `level: 0.98` and Date as necessary to filter outliers.**
Click to expand GraphQL query ```graphql query tradingView( $network: evm_network $dataset: dataset_arg_enum $token: String ) { EVM(network: $network, dataset: $dataset) { DEXTradeByTokens( limit: { count: 1 } where: { Block: { Date: { since: "2025-10-10" } } TransactionStatus: { Success: true } Trade: { Side: { Currency: { SmartContract: { is: "0x" } } } Currency: { SmartContract: { is: $token } } } } ) { max: quantile(of: Trade_PriceInUSD, level: 0.98) Block { Time } } } } ``` ```json { "network": "bsc", "token": "0xe59ecb01d56a7f1e66276c1bc885d64c92614444", "dataset": "combined", "local": "EVM", "interval": 60 } ```
## Get Price Change Percentage for a Four Meme Token Use the below query to get the price change in percentage for various time fields including `24 hours`, `1 hour` and `5 minutes`. Try it [here](https://ide.bitquery.io/Percentage-price-change-for-a-token).
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract } price_24hr: PriceInUSD(minimum: Block_Time) price_1hr: PriceInUSD( if: { Block: { Time: { is_relative: { hours_ago: 1 } } } } ) price_5min: PriceInUSD( if: { Block: { Time: { is_relative: { minutes_ago: 1 } } } } ) current: PriceInUSD } change_24hr: calculate( expression: "( $Trade_current - $Trade_price_24hr ) / $Trade_price_24hr * 100" ) change_1hr: calculate( expression: "( $Trade_current - $Trade_price_1hr ) / $Trade_price_1hr * 100" ) change_5min: calculate( expression: "( $Trade_current - $Trade_price_5min ) / $Trade_price_5min * 100" ) } } } ``` ```json { "currency": "0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40" } ```
## How do I get Four Meme OHLCV data for a token? {#get-ohlcv-data-of-a-four-meme-token} Use the below query to get four meme token OHLCV data. Test it [here](https://ide.bitquery.io/OHLC-for-a-four-meme-token).
Click to expand GraphQL query ```graphql query tradingView($network: evm_network, $token: String) { EVM(network: $network, dataset: combined) { DEXTradeByTokens( limit: { count: 10 } orderBy: { descendingByField: "Block_Time" } where: { Trade: { Currency: { SmartContract: { is: $token } } PriceAsymmetry: { lt: 0.1 } Dex: { ProtocolName: { is: "fourmeme_v1" } } } } ) { Block { Time(interval: { count: 5, in: minutes }) } Trade { open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) max: PriceInUSD(maximum: Trade_PriceInUSD) min: PriceInUSD(minimum: Trade_PriceInUSD) } volumeUSD: sum(of: Trade_Side_AmountInUSD, selectWhere: { gt: "0" }) } } } ``` ```json { "network": "bsc", "token": "0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40" } ```
## Monitor trades of traders on Four meme You can use our streams to monitor real time trades of a trader on Four Meme, for example run [this stream](https://ide.bitquery.io/monitor-trades-of-a-trader-on-four-meme).
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } } Transaction: { From: { is: "0x7db00d1f5b8855d40827f34bb17f95d31990306e" } } } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount Price PriceInUSD } Sell { Seller Currency { Name Symbol SmartContract } Amount } } Transaction { Hash } } } } ```
You can also get the trade activities of a user on Pancake Swap using our [Pancake Swap](/docs/blockchain/BSC/pancake-swap-api/) APIs. ## Track Four Meme Tokens in 14k to 18k Marketcap Tracks live Four Meme tokens on BSC with a market cap between $14K–$18K, filtered by 14k to 18k Marketcap. Useful for spotting emerging small-cap meme tokens in real time. Try the query [here](https://ide.bitquery.io/Four-meme-tokens-in-14K-to-17K-Marketcap).
Click to expand GraphQL query ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true Average: { Mean: { gt: 0.000014, le: 0.000018 } } } Market: { Protocol: { is: "fourmeme_v1" } Network: { is: "Binance Smart Chain" } } Volume: { Usd: { gt: 5 } } } ) { Token { Name Symbol Address } Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } marketcap: calculate(expression: "$Price_Average_Mean * 1000000000") Price { Average { Mean } Ohlc { Close High Low Open } } } } } ```
## Track Latest and Historical Trades of a Four Meme User You can use DEX Trades API with combined dataset to get latest and historic trades of a user. Run [this query](https://ide.bitquery.io/Get-all-trades-of-a-trader-on-four-meme) for example.
Click to expand GraphQL query ```graphql query MyQuery($address: String) { EVM(dataset: combined, network: bsc) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } } Transaction: { From: { is: $address } } } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount Price PriceInUSD } Sell { Seller Currency { Name Symbol SmartContract } Amount } } Transaction { Hash } } } } ``` ```json { "address": "0x7db00d1f5b8855d40827f34bb17f95d31990306e" } ```
## Top Buyers for a Token on Four Meme [This](https://ide.bitquery.io/Top-buyers-of-a-four-meme-token) query returns top buyers of a particular token on Four Meme, with currency smart contract as `0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40` for this example.
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc, dataset: combined) { DEXTrades( where: { Trade: { Buy: { Currency: { SmartContract: { is: $currency } } } Dex: { ProtocolName: { is: "fourmeme_v1" } } } } limit: { count: 100 } ) { Trade { Buy { Buyer } } trades: count bought: sum(of: Trade_Buy_Amount) } } } ``` ```json { "currency": "0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40" } ```
## Get Trade Volume and Number of Trades for a Four Meme Token [This](https://ide.bitquery.io/volume-and-trades-for-a-token-in-different-time-frames_1) query returns the traded volume and number of trades for a particular Four Meme token in different time frames, namely 24 hours, 1 hour and 5 minutes.
Click to expand GraphQL query ```graphql query MyQuery($currency: String) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Name Symbol SmartContract } } volume_24hr: sum(of: Trade_Side_AmountInUSD) volume_1hr: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) trades_24hr: count trades_1hr: count( if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) trades_5min: count( if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) } } } ``` ```json { "currency": "0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40" } ```
## Get Realtime Market Cap and Price of a Four Meme Token To get the market cap of a token we need two things, the latest `PriceInUSD` and `total supply` of the token. Total Supply is 1,000,000,000 (1B) for four meme tokens so we just need to get price and multiply it with 1B. [This](https://ide.bitquery.io/Real-Time-Marektcap-and-price-of-a-four-meme-token) query helps with getting the latest USD price of a token and hence its latest Marketcap. ``` Market Cap = Total Supply * PriceInUSD ```
Click to expand GraphQL query ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true } Market: { Protocol: { is: "fourmeme_v1" } Network: { is: "Binance Smart Chain" } } Volume: { Usd: { gt: 5 } } Token: { Address: { is: "0xf5bc78c8c762e4003742dacc31f3ba7091be4444" } } } ) { Token { Name Symbol Address } Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } marketcap: calculate(expression: "$Price_Average_Mean * 1000000000") Price { Average { Mean } Ohlc { Close High Low Open } } } } } ```
## Top Tokens by marketcap Below API can be used to get top four meme tokens by marketcap. You can get all the data through us and create a min and max marketcap filter in your application. Try the API [here](https://ide.bitquery.io/top-tokens-by-marketcap-on-fourmeme). ``` Market Cap = Total Supply * PriceInUSD ```
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( limit: { count: 100 } orderBy: { descendingByField: "Marketcap" } where: { TransactionStatus: { Success: true } Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } Side: { AmountInUSD: { gt: "20" } Currency: { SmartContract: { in: [ "0x" "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c" "0x55d398326f99059fF775485246999027B3197955" "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d" "0x17EAfd08994305D8AcE37EfB82F1523177eC70EE" "0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d" ] } } } } } ) { Trade { Currency { Name Symbol SmartContract } PriceInUSD(maximum: Block_Time) Side { Currency { Name Symbol SmartContract } } } Transaction { Hash(maximum: Block_Time) } Marketcap: calculate(expression: "$Trade_PriceInUSD * 1000000000") } } } ```
## Top Tokens by launch marketcap Below API can be used to get top four meme tokens by launch marketcap (marketcap at the time of launching). You can get all the data through us and create a min and max marketcap filter in your application. Try the API [here](https://ide.bitquery.io/top-tokens-by-launch-marketcap-on-fourmeme_1). ``` Market Cap = Total Supply * PriceInUSD ```
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( limit: { count: 100 } orderBy: { descendingByField: "Marketcap" } where: { TransactionStatus: { Success: true } Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } Side: { AmountInUSD: { gt: "20" } Currency: { SmartContract: { in: [ "0x" "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c" "0x55d398326f99059fF775485246999027B3197955" "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d" "0x17EAfd08994305D8AcE37EfB82F1523177eC70EE" "0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d" ] } } } } } ) { Trade { Currency { Name Symbol SmartContract } PriceInUSD(minimum: Block_Time) Side { Currency { Name Symbol SmartContract } } } Transaction { Hash(minimum: Block_Time) } Marketcap: calculate(expression: "$Trade_PriceInUSD * 1000000000") } } } ```
## How do I get top tokens by volume on Four Meme? {#top-tokens-by-buys-sells-volume-price-change-buyers-sellers} Below API can be used to get top Four Meme tokens by **buys, sells, volume, price change, buyers, and sellers** over rolling windows (for example 1h / 24h). You can apply min/max market cap filters in your application on top of this data. Try the API [here](https://ide.bitquery.io/top-tokens-by-price-change-volume-buys-sells-buyers-sellers_1).
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc, dataset: combined) { DEXTradeByTokens( limit: { count: 100 } orderBy: { descendingByField: "buys_1hr" } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } TransactionStatus: { Success: true } Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } Side: { Currency: { SmartContract: { in: [ "0x" "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c" "0x55d398326f99059fF775485246999027B3197955" "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d" "0x17EAfd08994305D8AcE37EfB82F1523177eC70EE" "0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d" ] } } } } } ) { Trade { Currency { Name Symbol SmartContract } price_24hr: Price(minimum: Block_Time) price_1hr: Price( maximum: Block_Time if: { Block: { Time: { till_relative: { hours_ago: 1 } } } } ) price_5min: Price( maximum: Block_Time if: { Block: { Time: { till_relative: { minutes_ago: 5 } } } } ) current: Price(maximum: Block_Time) Side { Currency { Name Symbol SmartContract } } } buyers_24hr: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: buy } } } } ) sellers_24hr: count( distinct: Transaction_From if: { Trade: { Side: { Type: { is: sell } } } } ) buys_1hr: count( if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { till_relative: { hours_ago: 1 } } } } ) buys_24hr: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells_1hr: count( if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { till_relative: { hours_ago: 1 } } } } ) sells_24hr: count(if: { Trade: { Side: { Type: { is: sell } } } }) volume_1hr: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { till_relative: { hours_ago: 1 } } } } ) volume_24hr: sum(of: Trade_Side_AmountInUSD) change_24hr: calculate( expression: "( $Trade_current - $Trade_price_24hr ) / $Trade_price_24hr * 100" ) change_1hr: calculate( expression: "( $Trade_current - $Trade_price_1hr ) / $Trade_price_1hr * 100" ) change_5min: calculate( expression: "( $Trade_current - $Trade_price_5min ) / $Trade_price_5min * 100" ) } } } ```
## Top Four Meme tokens by realtime market cap (activity filter) {#top-four-meme-tokens-by-realtime-marketcap} This query uses **`dataset: realtime`** and **`DEXTradeByTokens`** ordered by a calculated **marketcap** field, with a minimum **trade size in USD** on the filter. Use it when you want a **live-oriented** leaderboard; for volume / buy-sell breakdowns use the [previous section](#top-tokens-by-buys-sells-volume-price-change-buyers-sellers). Try the API [here](https://ide.bitquery.io/top-tokens-by-launch-marketcap-on-fourmeme_1).
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( limit: { count: 100 } orderBy: { descendingByField: "Marketcap" } where: { TransactionStatus: { Success: true } Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } Side: { AmountInUSD: { gt: "20" } Currency: { SmartContract: { in: [ "0x" "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c" "0x55d398326f99059fF775485246999027B3197955" "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d" "0x17EAfd08994305D8AcE37EfB82F1523177eC70EE" "0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d" ] } } } } } ) { Trade { Currency { Name Symbol SmartContract } PriceInUSD(minimum: Block_Time) Side { Currency { Name Symbol SmartContract } } } Transaction { Hash(minimum: Block_Time) } Marketcap: calculate(expression: "$Trade_PriceInUSD * 1000000000") } } } ```
## Top Tokens by liquidity Below API can be used to get top four meme tokens by liquidity between 800M and 900M token liquqidity. You can create a min and max liquidity filter in your application using this API.
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc) { Balances( limit: { count: 100 } where: { Balance: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } } orderBy: { descending: Balance_Amount } ) { Currency { Name Symbol SmartContract } Balance { Amount(selectWhere: { gt: "800000000", le: "900000000" }) } } } } ```
## Track Liquidity Add Events for All Tokens on Four Meme This query tracks all liquidity addition events on the Four Meme Exchange. It listens for `LiquidityAdded` events emitted from the four meme exchange's smart contract (0x5c952063c7fc8610ffdb798152d69f0b9550762b) You can run the query [here](https://ide.bitquery.io/Liquidity-Added-to-specific-tokens-on-Four-meme)
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: bsc) { Events( limit: {count: 20} where: {LogHeader: {Address: {is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b"}}, Log: {Signature: {Name: {is: "LiquidityAdded"}}}} ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ```
## Track Liquidity Add Events for a Token on Four Meme This query tracks liquidity addition events for a specific token on the Four Meme Exchange. It listens for `LiquidityAdded` events emitted from the exchange's smart contract (`0x5c952063c7fc8610ffdb798152d69f0b9550762b`) BNB network In this example, the query monitors liquidity events for a specific token (`0x5a49ce64a1e44f6fce07e9ff38f54dde8a8a0e94`) by filtering the event arguments to only include actions related to this token. You can run the query [here](https://ide.bitquery.io/Liquidity-Added-to-specific-tokens-on-Four-meme)
Click to expand GraphQL query ```graphql { EVM(dataset: realtime, network: bsc) { Events( limit: {count: 20} where: {LogHeader: {Address: {is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b"}}, Log: {Signature: {Name: {is: "LiquidityAdded"}}}, Arguments: {includes: {Name: {is: "token1"}, Value: {Address: {is: "0x5a49ce64a1e44f6fce07e9ff38f54dde8a8a0e94"}}}}} ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ```
## Check if a Four.meme Token is Phishy This elaborative API approach uses two queries to detect if a Four Meme token is potentially phishy by analyzing the relationship between token transfers and trades. This approach helps identify tokens where recipients received tokens without purchasing them, which is a common pattern in phishing or airdrop scams. ### How It Works The detection method works by: 1. **First Query**: Get the first transfers of a token to addresses - this provides the timestamp of when each address first received the token. 2. **Second Query**: Check if those addresses ever bought the token and when - pass the address list from the first query as a variable to check their purchase history. 3. **Analysis**: Compare transfer times and trade times in your code: - If an address **never bought** the token, it's suspicious. - If an address's **first buy time is later than the first transfer time**, it indicates the token was received before being purchased, which is a red flag for phishing behavior. Above analysis means someone else transferred the token to them which is phishy because devs often send token to famous KOLs or Influential People in crypto space to misguide traders. We are taking here example of `0x35a7bb282d8caafe71617c9d52ee30f1adfe4444` token, this may or may not be phishy as we are not running the further comparison between timestamps. Here we are just demonstrating that how you can get data from Bitquery and later run basic analysis on it. ### Query 1: Get First Transfers of a Token to Addresses This query retrieves the first transfer of a token to each address, providing the timestamp when each address first received the token. [Run Query](https://ide.bitquery.io/first-transfers-of-a-token_5)
Click to expand GraphQL query ```graphql query MyQuery($token: String) { EVM(network: bsc, dataset: combined) { Transfers( limit: { count: 1000 } orderBy: { ascendingByField: "Block_first_transfer" } where: { TransactionStatus: { Success: true } Transfer: { Receiver: { notIn: [ "0x5c952063c7fc8610ffdb798152d69f0b9550762b" "0x757eba15a64468e6535532fcF093Cef90e226F85" ] } Currency: { SmartContract: { is: $token } } } } ) { Transfer { Receiver } Block { first_transfer: Time(minimum: Block_Time) } total_transferred_amount: sum(of: Transfer_Amount) } } } ``` ```json { "token": "0x35a7bb282d8caafe71617c9d52ee30f1adfe4444" } ```
### Query 2: Get First Buys of an Address List for a Specific Token This query checks if the addresses from Query 1 ever bought the token and when. Pass the address array from Query 1 as a variable to this query. [Run Query](https://ide.bitquery.io/get-first-buys-of-an-address-list-of-a-specific-token_2)
Click to expand GraphQL query ```graphql query MyQuery($token: String!, $buyersList: [String!]) { EVM(network: bsc, dataset: combined) { DEXTradeByTokens( orderBy: { ascendingByField: "Block_first_buy" } where: { Trade: { Currency: { SmartContract: { is: $token } } Dex: { ProtocolFamily: { is: "FourMeme" } } Side: { Type: { is: buy } } Buyer: { in: $buyersList } } TransactionStatus: { Success: true } } ) { Trade { Buyer Currency { Name Symbol SmartContract } Side { Type } } Block { first_buy: Time(minimum: Block_Time) } total_bought_amount: sum(of: Trade_Amount) } } } ``` ```json { "token": "0x35a7BB282d8CAAFe71617c9d52EE30F1adFe4444", "buyersList" : [Pass the Address list you getting in Query 1] } ```
### Implementation Notes - Extract the address list and first transfer timestamps from Query 1 - Pass the address array as a variable to Query 2 - Compare the timestamps for all addresses: - If `firstTransferTime < firstBuyTime` or `firstBuyTime` is null → **Phishy indicator** - If `firstBuyTime <= firstTransferTime` → **Normal behavior** - You can implement this logic in your application code to automatically flag suspicious tokens ## Metadata for a Newly Created Token This query will fetch you trade metrics, such as marketcap, trade volume, token holders and creation time for a newly created Four Meme token on BSC network.
Click to expand GraphQL query ```graphql query MyQuery($token: String!) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $token } } } } ) { Block { createdAt: Time(minimum: Block_Time) } volume: sum(of: Trade_Side_AmountInUSD) } } holders: EVM(network: bsc, dataset: combined) { Holders( where: { Currency: { SmartContract: { is: $token } } Balance: { Amount: { gt: "0" } } } ) { count: uniq(of: Holder_Address) } } marketCap: Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Market: { Network: { is: "Binance Smart Chain" } } Volume: { Usd: { gt: 5 } } Token: { Address: { is: $token } } } orderBy: { descending: Interval_Time_Start } limit: { count: 1 } ) { Price { Average { Mean } } marketcap: calculate(expression: "Price_Average_Mean * 1000000000") } } } ```
## Top Traders of a token This query will fetch you top traders of a Four Meme token for the BSC network. You can test the query [here](https://ide.bitquery.io/top-traders-of-a-four-meme-token_1).
Click to expand GraphQL query ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network, dataset: combined) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}, Dex: {ProtocolName: {is: "fourmeme_v1"}}}} ) { Trade { Buyer Dex { OwnerAddress ProtocolFamily ProtocolName } } buyVolume: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sellVolume: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "bsc", "token": "0x37e3a59843b056e063780402ef25e12dca394444" } ```
## Get liquidity of a Four Meme token Using below API you can get the liquidity of a four meme token. Subtract `200000000` from the Balance that this query returns because 200M tokens are reserved which gets transferred to pancakeswap when this fourmeme token graduates.
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc) { Balances( where: { Balance: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } Currency: { SmartContract: { is: "0x87c5b3da05b062480b55c2dbf374ccd084f74444" } } } ) { Currency { Name } Balance { Amount } } } } ```
--- ## Trader-Focused Trade APIs (with USD Price, Market Cap & Supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get All DEX Trades on FourMeme With Price, Market Cap, and Supply Stream **all FourMeme DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Protocol: FourMeme`** to capture every swap across FourMeme in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/Get-All-DEX-Trades-on-Four-meme-With-Price-Market-Cap-and-Supply).
Click to expand GraphQL query ```graphql subscription { Trading { Trades( where: { Pair: { Market: { ProtocolFamily: { is: "FourMeme" } } } } ) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } Currency { Symbol Id Name } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
### Top Traders by PnL for a Specific FourMeme Token (Last 30 Minutes) Rank traders by **`PnL`** on specific bonding curve: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **curve-specific trader analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-token_2).
Click to expand GraphQL query ```graphql { Trading { Trades( limit: { count: 10 } orderBy: { descendingByField: "PnL" } where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Token: { Address: { is: "0x1f60df4bf4f08498ee4a111058c99774b81e4444" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
--- ## Frequently asked questions (Four Meme + Bitquery) {#frequently-asked-questions-four-meme-bitquery} These mirror common “answer engine” questions. Each item points to the section on **this page** unless noted. | Question | Where it is answered | | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | How do I get live Four Meme trades using Bitquery? | [Live trades subscription](#subscribe-the-latest-trades-on-four-meme) (`fourmeme_v1` + `DEXTrades`) | | How do I detect Four Meme token migrations to PancakeSwap? | [Migration subscription](#track-all-four-meme-tokens-that-have-migrated-to-pancakeswap) and [check if migrated](#check-if-a-four-meme-token-has-migrated-or-not) | | How do I get bonding curve progress for a Four Meme token? | [Bonding curve formula + balance query](#bonding-curve-progress-api-for-fourmeme-token) | | What is the Four Meme exchange contract address on BSC? | [Contract address](#what-is-the-four-meme-exchange-contract-address-on-bsc) | | How do I get newly created tokens on Four Meme? | [TokenCreate query](#get-newly-created-tokens-on-four-meme) | | How do I stream Four Meme token creation events in real time? | [TokenCreate subscription](#how-do-i-stream-four-meme-token-creation-events-in-real-time) | | How do I get top tokens by volume on Four Meme? | [Top tokens by volume / activity](#top-tokens-by-buys-sells-volume-price-change-buyers-sellers) and [realtime market cap leaderboard](#top-four-meme-tokens-by-realtime-marketcap) | | Can I monitor Four Meme transactions in the BSC mempool before confirmation? | **Separate guide:** [Four Meme Mempool API](/docs/blockchain/BSC/four-meme-mempool-API/) (not duplicated on this page) | | How do I get Four Meme OHLCV data for a token? | [OHLCV query](#get-ohlcv-data-of-a-four-meme-token) | | Can the API return four.meme token volume changes every second? | Yes. The `Trading.Pairs` subscription streams 1-second intervals with USD volume — see [realtime market cap and price](#get-realtime-market-cap-and-price-of-a-four-meme-token). | ## Video Tutorial | How to get Bonding Curve Progress of any Four Meme Token ## Video Tutorial | How to track the Four Meme Tokens which are about to Graduate in Realtime ## Video Tutorial | How to get Liquidity of a Four Meme Token ## Video Tutorial | How to get Top Traders of a Four Meme Token on Solana Four Meme DEX ## Video Tutorial | How to Get the OHLCV Data of a token on Four Meme DEX ## Real World Projects with Four Meme API ### Building a Four Meme Dashboard - [Tutorial](https://learnblockchain.cn/article/12532) - [Source Code](https://github.com/Kshitij0O7/four-meme-dashboard) - [Video](https://youtu.be/mwmoZAo7oFE?si=_-4n2fL-lH6la-8i) ### Four Meme Sniper Bot - [Tutorial](/docs/streams/sniper-trade-using-bitquery-kafka-stream/) - [Source Code](https://github.com/Kshitij0O7/evm-sniper) - [Video](https://youtu.be/vgOHgqTJmj0?si=yfUguMWdMtxRJMvg) --- ## Four Meme Mempool API URL: https://docs.bitquery.io/docs/blockchain/BSC/four-meme-mempool-API/ Four Meme Mempool API: watch BNB Chain pending transactions before confirmation with Bitquery GraphQL subscriptions. Built for traders and analytics teams. # Four Meme Mempool API - Real-Time Pre-Confirmation Monitoring :::tip Need real-time Four.meme data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Four.meme swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Four.meme data older than ~30 days**, raw per-swap detail, or call / event context. ::: Monitor Four Meme memecoin activity in the BSC mempool before transactions are confirmed on-chain. Track pending trades, new token launches, bonding curve progress, and detect MEV opportunities with Bitquery's ultra-low latency Mempool APIs and Kafka Streams. Get ahead of the market by monitoring mempool activity for Four Meme tokens before they hit the blockchain. Perfect for MEV bots, sniper bots, and advanced trading strategies. For live DEX prices and volume after tokens trade on-chain, browse [DEXrabbit's Four.meme category](https://dexrabbit.bitquery.io/categories/four-meme-ecosystem). :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ## Table of Contents ### 1. [How Mempool Monitoring Works](#how-mempool-monitoring-works) ### 2. Mempool Trading & Market Data - [Stream Four Meme Trades in Mempool ➤](#stream-four-meme-trades-in-mempool---detect-early) - [Monitor Specific Token Trades in Mempool ➤](#monitor-specific-token-trades-in-mempool) - [Track Large Buys in Mempool ➤](#track-large-buys-in-mempool) - [Track Large Sells in Mempool ➤](#track-large-sells-in-mempool) ### 3. Token Creation & Launches - [Stream Four Meme Token Creation in Mempool ➤](#stream-four-meme-token-creation-in-mempool---be-first) - [Monitor Token Launches with Metadata ➤](#monitor-token-launches-with-metadata) ### 4. Liquidity & Migrations - [Track Liquidity Add Events in Mempool ➤](#track-liquidity-add-events-in-mempool) - [Monitor Token Migrations to PancakeSwap ➤](#monitor-token-migrations-to-pancakeswap-in-mempool) - [Track Bonding Curve Completion in Mempool ➤](#track-bonding-curve-completion-in-mempool) ### 5. Advanced Mempool Strategies - [Monitor Wallet Activity in Mempool ➤](#monitor-wallet-activity-in-mempool) - [Track Smart Money Trades in Mempool ➤](#track-smart-money-trades-in-mempool) - [Detect Potential Rug Pulls in Mempool ➤](#detect-potential-rug-pulls-in-mempool) ### 6. [Kafka Streams for Ultra-Low Latency](#kafka-streams-for-ultra-low-latency) ### 7. [Use Cases & Trading Strategies](#use-cases--trading-strategies) --- ## How Mempool Monitoring Works When a transaction is broadcasted to the BSC network but not yet included in a block, Bitquery captures and processes it through mempool monitoring: - **Transaction Simulation**: The transaction is executed in the EVM using the current pending block context - **Data Extraction**: The system captures the simulated receipt, trace, and event logs - **Real-time Streaming**: Data is made available instantly through GraphQL subscriptions and Kafka streams - **Block Context**: Each batch of simulated transactions includes the block header used as execution context **Why Monitor Mempool?** - **First-mover Advantage**: Detect opportunities before they're confirmed on-chain - **MEV Opportunities**: Identify profitable front-running and back-running opportunities - **Sniper Bots**: Be first to trade newly launched tokens - **Risk Management**: Detect large sells or potential rug pulls before execution - **Market Intelligence**: Monitor smart money and whale activity in real-time :::tip We provide both GraphQL streams (easy to use) and Kafka streams (ultra-low latency) for mempool monitoring. For production MEV and sniper bots, we recommend Kafka streams. Read more: [Kafka Protobuf Streams for EVM ➤](/docs/streams/protobuf/chains/EVM-protobuf/) ::: --- ## Mempool Trading & Market Data ### Stream Four Meme Trades in Mempool - Detect Early Monitor all Four Meme DEX trades in real-time as they appear in the mempool, before they are confirmed on-chain. This allows you to detect trading opportunities early and execute front-run or back-run strategies. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-mempool-trades)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } } } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount Price PriceInUSD } Sell { Seller Currency { Name Symbol SmartContract } Amount Price PriceInUSD } Dex { ProtocolName ProtocolFamily } } Transaction { Hash From To Gas GasPrice } Block { Time } } } } ```
### Monitor Specific Token Trades in Mempool Track pending trades for a specific Four Meme token. Perfect for monitoring price impact before large trades execute. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-specific-token-mempool-trades_3)
Click to expand GraphQL query ```graphql subscription($token: String) { EVM(network: bsc mempool:true) { DEXTrades( where: {Trade:{Dex:{ProtocolFamily:{is:"FourMeme"}}} any:[{Trade:{Buy:{Currency:{SmartContract:{is:$token}}}}},{Trade:{Sell:{Currency:{SmartContract:{is:$token}}}}}]} ) { Block{ Time } Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount Price PriceInUSD } Dex{ ProtocolFamily } Sell { Seller Currency { Name Symbol SmartContract } Amount PriceInUSD } } Transaction { Hash From Gas GasPrice } } } } { "token": "0x444416a582466fdae0f2fcdf0a859675f8ff6e9f" } ```
### Track Large Buys in Mempool Monitor large buy orders in the mempool to detect whale activity and potential price pumps. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-large-buys-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } Buy: { AmountInUSD: { gt: "1000" } } } } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount AmountInUSD Price PriceInUSD } Sell { Currency { Name Symbol } Amount } } Transaction { Hash From Gas GasPrice } Block { Time } } } } ```
### Track Large Sells in Mempool Detect large sell orders before they execute to protect against price dumps. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-large-sells-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } Sell: { AmountInUSD: { gt: "1000" } } } } ) { Trade { Buy { Currency { Name Symbol } Amount } Sell { Seller Currency { Name Symbol SmartContract } Amount AmountInUSD Price PriceInUSD } } Transaction { Hash From Gas GasPrice } } } } ```
--- ## Token Creation & Launches ### Stream Four Meme Token Creation in Mempool - Be First Track new Four Meme token creations in the mempool instantly. Be the absolute first to know when a new token is being created, before it's confirmed on-chain. Critical for sniper bots. [Run Stream ➤](https://ide.bitquery.io/track-Four-meme-token-creation-in-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { Events( where: { Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Log: { Signature: { Name: { is: "TokenCreate" } } } } ) { Log { Signature { Name Signature } } Arguments { Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } Name Type } Transaction { Hash To From Gas GasPrice } Block { Time } } } } ```
### Monitor Token Launches with Metadata Get complete token information including name, symbol, and creator details from mempool. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-token-creation-with-metadata-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { Events( where: { Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Log: { Signature: { Name: { is: "TokenCreate" } } } } ) { Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } Transaction { Hash From } Block { Time } } } } ```
--- ## Liquidity & Migrations ### Track Liquidity Add Events in Mempool Monitor when liquidity is being added to Four Meme tokens before confirmation. Important for detecting graduation events. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-liquidity-add-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { Events( where: { LogHeader: { Address: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Log: { Signature: { Name: { is: "LiquidityAdded" } } } } ) { Log { Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } } } Transaction { Hash From } Block { Time } } } } ```
### Monitor Token Migrations to PancakeSwap in Mempool Track when Four Meme tokens are graduating to PancakeSwap before the migration completes. Critical for trading strategies. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-migration-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { Events( where: { Log: { Signature: { Name: { in: ["PairCreated", "PoolCreated"] } } } Transaction: { To: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } } ) { Log { Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } Transaction { Hash From To Gas GasPrice } } } } ```
### Track Bonding Curve Completion in Mempool Monitor tokens that are about to complete their bonding curve (near graduation) in the mempool. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-bonding-curve-completion-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { Events( where: { LogHeader: { Address: { is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b" } } Log: { Signature: { Name: { in: ["LiquidityAdded", "TokenGraduated", "PairCreated"] } } } } ) { Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } } Transaction { Hash From } } } } ```
--- ## Advanced Mempool Strategies ### Monitor Wallet Activity in Mempool Track specific wallet addresses (smart money, whales, or known traders) and their pending Four Meme trades. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-wallet-monitoring-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } } Transaction: { From: { is: "0x7db00d1f5b8855d40827f34bb17f95d31990306e" } } } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount AmountInUSD } Sell { Seller Currency { Name Symbol SmartContract } Amount AmountInUSD } } Transaction { Hash From Gas GasPrice } } } } ```
### Track Smart Money Trades in Mempool Monitor multiple smart money wallets simultaneously for their Four Meme trading activity in mempool. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-smart-money-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } } Transaction: { From: { in: [ "0x7db00d1f5b8855d40827f34bb17f95d31990306e" "0x1234567890123456789012345678901234567890" "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" ] } } } ) { Trade { Buy { Buyer Currency { Name Symbol SmartContract } Amount AmountInUSD } Sell { Currency { Name Symbol } Amount } } Transaction { Hash From } } } } ```
### Detect Potential Rug Pulls in Mempool Monitor for suspicious activity like developers selling large amounts in mempool. [Run Stream ➤](https://ide.bitquery.io/Four-Meme-rug-pull-detection-mempool)
Click to expand GraphQL query ```graphql subscription { EVM(network: bsc, mempool: true) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "fourmeme_v1" } } Sell: { AmountInUSD: { gt: "5000" } } } } ) { Trade { Sell { Seller Currency { Name Symbol SmartContract } Amount AmountInUSD } Buy { Currency { Name Symbol } } } Transaction { Hash From Gas GasPrice } Block { Time } } } } ```
--- ## Kafka Streams for Ultra-Low Latency For production-grade applications like MEV bots and sniper bots, we recommend using Kafka streams instead of GraphQL subscriptions. Kafka streams provide: - **Sub-second Latency**: Faster than GraphQL streams - **Higher Throughput**: Handle thousands of transactions per second - **Better Reliability**: Built-in retry and error handling - **Scalability**: Horizontal scaling for high-volume applications **Protobuf Message Format:** ```protobuf message BroadcastedTransactionsMessage { Chain Chain = 1; BlockHeader Header = 2; repeated Transaction Transactions = 3; } ``` ### Benefits for Trading Bots: - **MEV Bots**: Execute front-running and back-running strategies with minimal latency - **Sniper Bots**: Be first to trade newly launched tokens - **Arbitrage Bots**: Detect and execute arbitrage opportunities instantly - **Monitoring Bots**: Track market activity with enterprise-grade reliability **Learn More:** - [Kafka Protobuf Streams Documentation ➤](/docs/streams/kafka-streaming-concepts/) - [Building a Sniper Bot with Kafka ➤](/docs/streams/sniper-trade-using-bitquery-kafka-stream/) - [Contact Us for Kafka Stream Access ➤](https://t.me/Bloxy_info) --- ## Use Cases & Trading Strategies ### Sniper Bot Strategy 1. Monitor token creation events in mempool 2. Analyze token metadata and creator 3. Execute buy immediately after confirmation 4. Set take-profit and stop-loss levels ### Front-Running Strategy 1. Detect large buy orders in mempool 2. Calculate potential price impact 3. Execute buy with higher gas price 4. Sell after original transaction confirms ### Rug Pull Protection 1. Monitor developer wallet activity 2. Detect large sells in mempool 3. Execute sell before rug pull completes 4. Protect your investment ### Smart Money Following 1. Track known profitable wallets 2. Copy their trades in mempool 3. Execute simultaneously or front-run 4. Profit from their market insights ### Graduation Trading 1. Monitor bonding curve progress 2. Detect imminent graduations in mempool 3. Position before PancakeSwap migration 4. Capture migration price pump --- ## Related Resources You may also be interested in: - [Four Meme API Documentation ➤](/docs/blockchain/BSC/four-meme-api/) - [BSC Mempool Stream ➤](/docs/blockchain/BSC/bsc-mempool-stream/) - [BSC DEX Trades API ➤](/docs/blockchain/BSC/bsc-dextrades/) - [Kafka Protobuf Streams ➤](/docs/streams/protobuf/chains/EVM-protobuf/) - [WebSocket Subscriptions ➤](/docs/authorization/websocket/) - [Building a Sniper Bot Tutorial ➤](/docs/streams/sniper-trade-using-bitquery-kafka-stream/) ## Need Help? If you have any questions or need assistance with Four Meme mempool monitoring, reach out to our [Telegram support](https://t.me/Bloxy_info). For enterprise solutions and Kafka stream access, contact our team for a custom plan. --- ## GMGN API Alternative: Solana Trending Tokens, Trades, OHLC URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-gmgn-api/ GMGN API alternative for Solana: trending tokens, real-time pair trades, buy and sell volume, top pairs, OHLC, wallet portfolios and top traders over GraphQL, with full history and no per-key limits. # GMGN API Alternative: Solana Trending Tokens, Trades, OHLC :::tip Need real-time GMGN-style trader data or anything from the last ~30 days? For **real-time trader and wallet data over the last ~30 days** across **10 chains in one API**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **`Trader.Address`** as a first-class filter plus **USD price, market cap, and supply on every row**. Use this page when you need **historical GMGN-style trader data older than ~30 days**, raw per-swap detail, or call / event context. ::: Replicate **GMGN**-style **Solana** analytics with Bitquery: **trending tokens**, **top DEX pairs**, **aggregate stats** (buys, sells, buy/sell volume, makers, buyers, sellers), **live trades per pair**, **OHLC** for charts, **volume by token**, and **top traded pairs**. Uses **`DEXTradeByTokens`** and **`Solana`** GraphQL, some patterns work as **queries** only when they rely on heavy aggregates (see notes below). :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## GMGN OpenAPI vs Bitquery GMGN now ships its own [Agent API / OpenAPI](https://docs.gmgn.ai/) for trading bots and AI agents. It is built around executing trades through GMGN; this page is for reading the market. Use GMGN's API when you want to route swaps through their router. Use Bitquery when you want the data GMGN's screener is built from, without the limits of a trading product: | | GMGN OpenAPI | Bitquery | | --- | --- | --- | | Purpose | Trade execution, agent skills, wallet signing | Market data: trades, tokens, pairs, wallets, OHLC | | History | Recent activity per token or wallet | Full Solana history on the `archive` dataset, ~30 days on `realtime` | | Scope per request | One token, pair or wallet | Any filter: aggregate across all tokens, pairs, makers or programs in one query | | Delivery | REST | GraphQL, WebSocket subscriptions, Kafka and gRPC streams | | Access | API key tied to a GMGN account and trading volume | Free developer tier, usage-based plans, no trading account required | | Chains | Solana plus the chains GMGN trades on | Solana here, same schema on Ethereum, BSC, Base and other EVM chains ([EVM GMGN API](/docs/blockchain/Ethereum/dextrades/evm-gmgn-api)) | Every query below runs as written in the [Bitquery IDE](https://ide.bitquery.io). Start with the [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) and [DEXScreener API](/docs/blockchain/Solana/DEXScreener/solana_dexscreener/) pages for the launch and pair views GMGN shows on its home page. ## Related APIs - **[GMGN API for Ethereum & EVM](/docs/blockchain/Ethereum/dextrades/evm-gmgn-api)**: **GMGN**-style **trending pairs**, token stats, **OHLC**, and **liquidity** on **Ethereum** and other **EVM** chains. - **[Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades)**: Core **`DEXTrades`** / streaming patterns for **Solana** swaps and pair activity. - **[Raydium DEX API](/docs/blockchain/Solana/Solana-Raydium-DEX-API)**: **Raydium** pools, trades, and liquidity, a common source for **Solana** screener UIs. - **[Solana DEXScreener API](/docs/blockchain/Solana/DEXScreener/solana_dexscreener)**: **DEXScreener**-style Solana **pair** and **price** examples. - **[Solana Token Price API](/docs/blockchain/Solana/solana-token-price-api)**: latest **USD price**, live **price stream** and **OHLC** for any **SPL token**. - **[Solana GeckoTerminal API](/docs/blockchain/Solana/solana-geckoterminal-api)**: **GeckoTerminal**-style charts and **OHLC** on **Solana**. ## GMGN Trending API The query will give you the Top 10 trending tokens on GMGN in last 1 hour. You can find the query [here](https://ide.bitquery.io/gmgn-trending-api_1) ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Transaction: { Result: { Success: true } } Trade: { Side: { Currency: { MintAddress: { in: [ "So11111111111111111111111111111111111111112" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" ] } } } Currency: { MintAddress: { notIn: [ "So11111111111111111111111111111111111111112" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" ] } } } } limit: { count: 10 } orderBy: { descendingByField: "trades_count" } ) { Trade { Currency { Name Symbol MintAddress } Dex { ProtocolName ProtocolFamily } Market { MarketAddress } Side { Currency { Name Symbol MintAddress } } } trades_count: count } } } ``` ## Get Trade Transactions of GMGN for a particular pair in realtime The query will subscribe you to real-time trade transactions for a Solana pair, providing a continuous stream of data as new trades are processed and recorded. You can find the query [here](https://ide.bitquery.io/Get-Solana-pair-trades-data) ```graphql subscription MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Currency { Name Symbol } Amount PriceAgainstSideCurrency: Price PriceInUSD Side { Currency { Name Symbol } Amount Type } } Transaction { Maker: Signer Signature } } } } ``` ## Get Buy Volume, Sell Volume, Buys, Sells, Makers, Total Trade Volume, Buyers, Sellers of a specific Token of GMGN The below query gives you the essential stats for a token such as buy volume, sell volume, total buys, total sells, makers, total trade volume, buyers, sellers (in last 5 min, 1 hour) of a specific token. You can run the query [here](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair) ```graphql query MyQuery($token: String!, $side_token: String!, $pair_address: String!, $time_5min_ago: DateTime!, $time_1h_ago: DateTime!) { Solana(dataset: realtime) { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: $token}}, Side: {Currency: {MintAddress: {is: $side_token}}}, Market: {MarketAddress: {is: $pair_address}}}, Block: {Time: {since: $time_1h_ago}}} ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after: $time_5min_ago}}} ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) makers_5min: count( distinct: Transaction_Signer if: {Block: {Time: {after: $time_5min_ago}}} ) buyers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}} ) buyers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sellers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}} ) sellers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) trades: count trades_5min: count(if: {Block: {Time: {after: $time_5min_ago}}}) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {after: $time_5min_ago}}} ) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) buys: count(if: {Trade: {Side: {Type: {is: buy}}}}) buys_5min: count( if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sells: count(if: {Trade: {Side: {Type: {is: sell}}}}) sells_5min: count( if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) } } } { "token":"token mint address", "side_token": "So11111111111111111111111111111111111111112", "pair_address": "4AZRPNEfCJ7iw28rJu5aUyeQhYcvdcNm8cswyL51AY9i", "time_5min_ago":"2024-11-06T15:13:00Z", "time_1h_ago": "2024-11-06T14:18:00Z" } ``` ## Get Top Pairs on Solana on GMGN The query will give the top 10 pairs on Solana network in descending order of their total trades happened in their pools in last 1 hour. This query will get you all the data you need such as total trades, total buys, total sells, total traded volume, total buy volume Please change the `Block: {Time: {since: "2024-08-15T04:19:00Z"}}` accordingly when you try out the query. Keep in mind you cannot use this as a websocket subscription becuase aggregate functions like `sum` doesn't work well in `subscription`. You can find the query [here](https://ide.bitquery.io/GMGN--All-in-One-query_1) ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } Block: { Time: { since: "2024-08-15T04:19:00Z" } } } orderBy: { descendingByField: "total_trades" } limit: { count: 10 } ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: { Block: { Time: { after: "2024-08-15T05:14:00Z" } } } ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) total_trades: count total_traded_volume: sum(of: Trade_Side_AmountInUSD) total_buy_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) total_sell_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) total_buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) total_sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) } } } ``` ## Get OHLC for a token pair You can use the below query to build charts like how you see on BullX. You will get OHLC data for a token pair using below query. Test the API [here](https://ide.bitquery.io/Solana-OHLC-Query_5) ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } PriceAsymmetry: { lt: 0.1 } } } limit: { count: 10 } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get Top Traded Pairs This query will give you top traded pairs data. You can find the query [here](https://ide.bitquery.io/top-trading-pairs?_gl=1*131rbu4*_ga*MTU0ODE3ODUxMy4xNzM5Nzg0Njcw*_ga_ZWB80TDH9J*MTc0MjQ2MjAwNi43Ny4xLjE3NDI0NjIwNDQuMC4wLjA.). ```graphql query ($time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { Solana { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Block: {Time: {after: $time_3h_ago}}, any: [{Trade: {Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}}}, {Trade: {Currency: {MintAddress: {not: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}}, {Trade: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}, Side: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}}}}]} orderBy: {descendingByField: "usd"} limit: {count: 100} ) { Trade { Currency { Symbol Name MintAddress } Side { Currency { Symbol Name MintAddress } } price_last: PriceInUSD(maximum: Block_Slot) price_10min_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Slot) } dexes: uniq(of: Trade_Dex_ProgramAddress) amount: sum(of: Trade_Side_Amount) usd: sum(of: Trade_Side_AmountInUSD) traders: uniq(of: Trade_Account_Owner) count(selectWhere: {ge: "100"}) } } } { "time_10min_ago": "2024-09-19T12:26:17Z", "time_1h_ago": "2024-09-19T11:36:17Z", "time_3h_ago": "2024-09-19T09:36:17Z" } ``` ## Get trading volume, buy volume, sell volume of a token This sums what a token traded against WSOL across every Solana venue, split by side. It reads the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`: each row carries a vetted USD price, and the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so totals taken from them read low. The example uses PUMP; swap the base address for the mint you want. Open it in the [Bitquery IDE](https://ide.bitquery.io/trade_volume_Solana#). ```graphql { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } } Token: { Address: { is: "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } } QuoteToken: { Address: { is: "So11111111111111111111111111111111111111112" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) traders: count(distinct: Trader_Address) } } } ``` ## Which DEX markets trade a token? Lists **Solana DEX programs** where a mint trades against a **base** (e.g. **WSOL**), with **volume**, **trade count**, **unique counter-currencies**, and **price** snapshots. Swap the variable mint for your token. [Run in Bitquery IDE](https://ide.bitquery.io/DEX-Markets-for-a-token) ```graphql query ( $token: String $base: String $time_10min_ago: DateTime $time_1h_ago: DateTime $time_3h_ago: DateTime ) { Solana { DEXTradeByTokens( orderBy: { descendingByField: "amount" } where: { Trade: { Currency: { MintAddress: { is: $token } } Side: { Amount: { gt: "0" } Currency: { MintAddress: { is: $base } } } } Transaction: { Result: { Success: true } } Block: { Time: { after: $time_3h_ago } } } ) { Trade { Dex { ProtocolFamily ProtocolName } price_last: PriceInUSD(maximum: Block_Slot) price_10min_ago: PriceInUSD( maximum: Block_Slot if: { Block: { Time: { before: $time_10min_ago } } } ) price_1h_ago: PriceInUSD( maximum: Block_Slot if: { Block: { Time: { before: $time_1h_ago } } } ) price_3h_ago: PriceInUSD(minimum: Block_Slot) } amount: sum(of: Trade_Side_Amount) pairs: uniq(of: Trade_Side_Currency_MintAddress) trades: count } } } ``` ```json { "token": "59VxMU35CaHHBTndQQWDkChprM5FMw7YQi5aPE5rfSHN", "base": "So11111111111111111111111111111111111111112", "time_10min_ago": "2024-09-19T10:45:46Z", "time_1h_ago": "2024-09-19T09:55:46Z", "time_3h_ago": "2024-09-19T07:55:46Z" } ``` ## SPL tokens owned by a wallet (portfolio) **`BalanceUpdates`** for one **owner** address: current **post-balances** per mint, similar to a **wallet portfolio** view on explorers and terminal UIs. [Run in Bitquery IDE](https://ide.bitquery.io/tokens-owned-by-an-address) ```graphql query MyQuery { Solana { BalanceUpdates( where: { BalanceUpdate: { Account: { Owner: { is: "AtTjQKXo1CYTa2MuxPARtr382ZyhPU5YX4wMMpvaa1oy" } } } } orderBy: { descendingByField: "BalanceUpdate_Balance_maximum" } ) { BalanceUpdate { Balance: PostBalance(maximum: Block_Slot) Currency { Name Symbol } } } } } ``` ## Top buyers of a token Ranks **accounts** by **buy-side USD** for a fixed **mint** (example: **RAY**). Use for **whale / smart money** style leaderboards. [Run in Bitquery IDE](https://ide.bitquery.io/top-buyers-of-a-token_2) ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "buy" } where: { Trade: { Currency: { MintAddress: { is: "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R" } } } Transaction: { Result: { Success: true } } } limit: { count: 10 } ) { Trade { Account { Address Token { Owner } } Currency { Symbol Name MintAddress } } buy: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) sell: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ``` ## Top sellers of a token Same pattern as **top buyers**, ordered by **sell-side** flow for the same mint. [Run in Bitquery IDE](https://ide.bitquery.io/top-sellers-of-a-token_2) ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "sell" } where: { Trade: { Currency: { MintAddress: { is: "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R" } } } Transaction: { Result: { Success: true } } } limit: { count: 10 } ) { Trade { Account { Address Token { Owner } } Currency { Symbol Name MintAddress } } buy: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) sell: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) } } } ``` ## Video Tutorial ### Get GMGN Terminal Data with Bitquery API and Streams --- ## GMGN-style Token Discovery on Ethereum: New Tokens, Smart Money, DEX Activity URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/evm-gmgn-api/ GMGN-style token discovery on Ethereum via Bitquery GraphQL: new tokens' first trades, token stats and market cap, top bought and sold tokens, top traders. # GMGN-style Token Discovery on Ethereum: New Tokens, Smart Money, DEX Activity GMGN is a discovery screen: tokens that just started trading, the ones being bought and sold most, the wallets behind them, and a wallet's holdings when you click through. On Ethereum each of those is one query on Bitquery's `DEXTradeByTokens`, `Trading` and `Balances` cubes, and the same queries work on BSC, Base, Arbitrum and the other EVM chains with a network change. The worked token is Mog, `0xaaee1a9723aadb7afa2810263653a34ba2c21c7a`. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. Pair feeds and terminal-style data are on the [BullX-style page](/docs/blockchain/Ethereum/dextrades/evm-bullx-api/); pool analytics are on the [GeckoTerminal-style page](/docs/blockchain/Ethereum/dextrades/evm-geckoterminal-api/). ## Recommended: Trading API queries (real-time + last ~30 days) ### Live trades with USD price, market cap and supply Streams MEV-filtered trades across all 10 chains; the network filter scopes it to Ethereum. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Ethereum" } } } }) { Block { Time } Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol Network } QuoteToken { Symbol } Market { Protocol Network } } } } } ``` ### Most accurate token price with 1-minute OHLC (top market) Returns the token's price from its top-volume market via `Ranking: { Position: { eq: 1 } }`; swap the token address and network for your token. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Token-Price-Top-Market-Rank-1). ```graphql { Trading { Pairs( where: { Token: {Address: {is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a"}, Network: {is: "Ethereum"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } limit: {count: 1} orderBy: {descending: Block_Time} ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean } } Volume { Base Usd } Block { Time } } } } ``` ## Tokens that just started trading The first WETH-quoted trade of each token seen in the last six hours: `limitBy` keeps one row per token and the ascending order makes that row its earliest. Established tokens appear too, since the window only sees their first trade inside it; a token whose first trade ever falls in the window is new. ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Block: { Time: { since_relative: { hours_ago: 6 } } } Trade: { Side: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } } limitBy: { by: Trade_Currency_SmartContract, count: 1 } orderBy: { ascending: Block_Time } limit: { count: 50 } ) { Block { Time } Trade { Currency { Symbol SmartContract } Dex { ProtocolName SmartContract } PriceInUSD Side { AmountInUSD } } Transaction { From Hash } } } } ``` ## Token stats with market cap The Trading cube keeps hourly rows per token with the close price, USD volume and market cap; the latest row is the token card. Token ids are `bid:eth:`. ```graphql { Trading { Tokens( where: { Token: { Id: { is: "bid:eth:0xaaee1a9723aadb7afa2810263653a34ba2c21c7a" } } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since_relative: { hours_ago: 3 } } } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Block { Time } Token { Symbol Network } Price { Ohlc { Open High Low Close } } Volume { Usd } Supply { MarketCap } } } } ``` ## Most bought and most sold tokens USD bought and sold per token over the last day. `Side.Type` names the counter-side, so the token was bought where the side was sold; sort on `bought` or `sold`. The single-trade USD cap keeps mispriced rows out of the sums. ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descendingByField: "bought" } limit: { count: 20 } where: { Trade: { Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol SmartContract } } bought: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) trades: count makers: uniq(of: Transaction_From) } } } ``` ## Top traders of a token Rank by `Transaction.From`, the wallet that sent the swap, with what each bought and sold. Saved query [here](https://ide.bitquery.io/top-traders-of-a-token_7). ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 50 } where: { Trade: { Currency: { SmartContract: { is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## DEX activity across Ethereum Trades, USD volume and active pools per protocol over the last day. Saved query [here](https://ide.bitquery.io/dex-markets). ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descendingByField: "trades" } where: { Trade: { Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Dex { ProtocolName ProtocolFamily } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) pools: uniq(of: Trade_Dex_SmartContract) makers: uniq(of: Transaction_From) } } } ``` ## Trading pairs on one DEX The busiest Uniswap v3 pools of the last day, one row per pool. Saved query [here](https://ide.bitquery.io/trading-pairs-on-a-specific-dex). ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descendingByField: "trades" } limit: { count: 20 } limitBy: { by: Trade_Dex_SmartContract, count: 1 } where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v3" } } Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Dex { SmartContract } Currency { Symbol SmartContract } Side { Currency { Symbol } } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Latest trades on one DEX Both sides of the newest Uniswap v3 swaps with USD and the sender. Saved query [here](https://ide.bitquery.io/latest-trades_5). ```graphql { EVM(network: eth) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v3" } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Currency { Symbol } Amount AmountInUSD } Sell { Currency { Symbol } Amount AmountInUSD } Dex { SmartContract } } Transaction { From Hash } } } } ``` ## A wallet's token balances The `Balances` cube returns the current balance of every token a wallet holds; the example is a wallet from the whale feed. Saved query [here](https://ide.bitquery.io/balance-of-a-wallet_1). ```graphql { EVM(network: eth) { Balances( where: { Balance: { Address: { is: "0xae2fc483527b8ef99eb5d9b44875f005ba1fae13" } } } orderBy: { descending: Balance_Amount } limit: { count: 20 } ) { Currency { Symbol SmartContract } Balance { Amount } } } } ``` ## Related pages - [BullX-style EVM API](/docs/blockchain/Ethereum/dextrades/evm-bullx-api/) - [GeckoTerminal-style EVM API](/docs/blockchain/Ethereum/dextrades/evm-geckoterminal-api/) - [Latest trading pairs API](/docs/blockchain/Ethereum/dextrades/latest-trading-pairs-api) - [Ethereum token balance API](/docs/blockchain/Ethereum/balances/) --- ## GMX Staking API on Arbitrum URL: https://docs.bitquery.io/docs/blockchain/Arbitrum/gmx-api/ Query GMX staking positions, esGMX rewards, and related on-chain activity on Arbitrum with Bitquery GraphQL APIs. Works with WebSocket live subscriptions. # GMX API This section covers how to retrieve staking information on GMX. GMX is one venue within our [Arbitrum API](https://bitquery.io/blockchains/arbitrum-blockchain-api) coverage — the page lists DEX trades, transfers, NFTs and balances on Arbitrum One. You can read more about the [GMX ecosystem in this blog](https://bitquery.io/blog/gmx). ## Video Tutorial on GMX and esGMX ## New Positions by Trader The following query retrieves new positions created by a specific trader on the GMX DEX ```graphql { EVM(dataset: archive, network: arbitrum) { Events( where: { Log: { SmartContract: { is: "0x489ee077994B6658eAfA855C308275EAd8097C4A" }, Signature: { Name: { is: "IncreasePosition" } } }, Arguments: { includes: { Name: { is: "account" }, Value: { Address: { is: "0x92812499fF2c040f93121Aab684680a6e603C4A7" } } } } } orderBy: { descending: Block_Time } ) { Log { Signature { Name Parsed Signature } } Arguments { Name Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } } Block { Time } } } } ``` ## Latest Liquidated Positions The following query retrieves the latest liquidated positions on the GMX DEX, providing information on the account, collateral token, index token, position, reserve amount, realised PnL, and mark price. ```graphql { EVM(dataset: archive, network: arbitrum) { Events( where: { Log: { SmartContract: { is: "0x489ee077994B6658eAfA855C308275EAd8097C4A" }, Signature: { Name: { is: "LiquidatePosition" } } } } limit: { count: 100 } orderBy: { descending: Block_Time } ) { Log { Signature { Name Parsed Signature } } Block { Time } Call { Signature { Name } } Transaction { Hash } Arguments { Name Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } } } } } ``` ## Latest GMX Events You can run the query [here](https://ide.bitquery.io/latest-GMX-Events). The following query retrieves the latest GMX events on the Arbitrum network: ```graphql { EVM(network: arbitrum) { Events( where: { Log: { SmartContract: { is: "0x489ee077994B6658eAfA855C308275EAd8097C4A" } } } orderBy: { descending: Block_Time } limit: { count: 10 } ) { Log { Signature { Name Parsed Signature } } Arguments { Name Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } } Block { Time } } } } ``` These queries help you explore the latest activities and positions on the GMX protocol. --- ## GeckoTerminal-style Pool Data on Ethereum: Trending Pools, OHLC, Reserves URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/evm-geckoterminal-api/ GeckoTerminal-style pool pages on Ethereum via Bitquery GraphQL: trending pools, live pool trades, buys, sells and makers, hourly OHLC, reserves, new pools. # GeckoTerminal-style Pool Data on Ethereum: Trending Pools, OHLC, Reserves GeckoTerminal is organised around pools: a ranked list of them, and for each one the trades, the buy and sell counts, the makers, the candles and the reserves. Bitquery's `DEXTradeByTokens` cube keys Ethereum trades by pool contract, and `DEXPoolEvents` records reserves in USD after every change, so each panel is one query. The worked pool is Mog/WETH on Uniswap v2, `0xc2eab7d33d3cb97692ecb231a5d0e4a649cb539d`, with Mog at `0xaaee1a9723aadb7afa2810263653a34ba2c21c7a`. Every example runs in the [IDE](https://ide.bitquery.io) on a free account, and the same queries work on BSC, Base, Arbitrum and the other EVM chains by changing the network. The [Solana version](/docs/blockchain/Solana/solana-geckoterminal-api/) covers Solana pools. ## Recommended: Trading API queries (real-time + last ~30 days) ### Live trades with USD price, market cap and supply Every Ethereum DEX trade with the trader, USD amounts and the market on the row, MEV trades filtered out; drop the network filter for all ten chains. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Ethereum" } } } }) { Block { Time } Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol Network } QuoteToken { Symbol } Market { Protocol Network } } } } } ``` ### Most accurate token price with 1-minute OHLC (top market) `Ranking: { Position: { eq: 1 } }` picks the token's deepest market, so this is the price a pool list should show; change the token address and network for any other token. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Token-Price-Top-Market-Rank-1). ```graphql { Trading { Pairs( where: { Token: {Address: {is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a"}, Network: {is: "Ethereum"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } limit: {count: 1} orderBy: {descending: Block_Time} ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean } } Volume { Base Usd } Block { Time } } } } ``` ## Trending pools The pools with the most trades in the last day, one row per pool contract with the pair, the maker count and USD volume. The single-trade USD cap keeps mispriced thin-pool rows out of the sums. Saved query [here](https://ide.bitquery.io/List-of-trading-pairs-in-descending-order-of-trxns-in-last-24-hours). ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descendingByField: "trades" } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } TransactionStatus: { Success: true } Trade: { Side: { AmountInUSD: { lt: "10000000" } } } } limit: { count: 20 } limitBy: { by: Trade_Dex_SmartContract, count: 1 } ) { Trade { Dex { SmartContract ProtocolName } Currency { Symbol SmartContract } Side { Currency { Symbol SmartContract } } } trades: count makers: uniq(of: Transaction_From) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Live trades of a pool Each message is one swap in the pool with the amount, the USD price, the side and the wallet that sent it. Saved stream [here](https://ide.bitquery.io/Get-pair-trades-data-just-like-geckoterminal). ```graphql subscription { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { SmartContract: { is: "0xc2eab7d33d3cb97692ecb231a5d0e4a649cb539d" } } Currency: { SmartContract: { is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a" } } } } ) { Block { Time } Trade { Amount PriceInUSD Currency { Symbol } Side { Amount AmountInUSD Type Currency { Symbol } } } Transaction { Maker: From Hash } } } } ``` ## Buys, sells, makers and volume of a pool The stat block of a pool page: trades, buys, sells, makers, buyers, sellers and USD volume over the last day, each with a one-hour sub-window, plus the price at both ends of the window. `Side.Type` names the counter-side of a trade, so the token was bought where the side was sold, and wallets are counted by `Transaction.From`. Saved query [here](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-a-eth-pair). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { TransactionStatus: { Success: true } Trade: { Dex: { SmartContract: { is: "0xc2eab7d33d3cb97692ecb231a5d0e4a649cb539d" } } Currency: { SmartContract: { is: "0xaaee1a9723aadb7afa2810263653a34ba2c21c7a" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol SmartContract } Side { Currency { Symbol } } Dex { ProtocolName } start: PriceInUSD(minimum: Block_Number) end: PriceInUSD(maximum: Block_Number) } trades: count trades1h: count(if: { Block: { Time: { after_relative: { hours_ago: 1 } } } }) buys: count(if: { Trade: { Side: { Type: { is: sell } } } }) sells: count(if: { Trade: { Side: { Type: { is: buy } } } }) makers: uniq(of: Transaction_From) makers1h: uniq(of: Transaction_From, if: { Block: { Time: { after_relative: { hours_ago: 1 } } } }) buyers: uniq(of: Transaction_From, if: { Trade: { Side: { Type: { is: sell } } } }) sellers: uniq(of: Transaction_From, if: { Trade: { Side: { Type: { is: buy } } } }) volumeUsd: sum(of: Trade_Side_AmountInUSD) volumeUsd1h: sum(of: Trade_Side_AmountInUSD, if: { Block: { Time: { after_relative: { hours_ago: 1 } } } }) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Hourly OHLC of a pair Candles from the Trading cube for WETH against USDT, quoted in USD, one row per hour. Change the two token ids for any pair. Saved query [here](https://ide.bitquery.io/WETH-USDT-OHLC-on-Ethereum_1). ```graphql { Trading { Pairs( where: { Token: { Id: { is: "bid:eth:0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } QuoteToken: { Id: { is: "bid:eth:0xdac17f958d2ee523a2206206994597c13d831ec7" } } Interval: { Time: { Duration: { eq: 3600 } } } Price: { IsQuotedInUsd: true } } limit: { count: 24 } orderBy: { descending: Interval_Time_Start } ) { Interval { Time { Start } } Token { Symbol } QuoteToken { Symbol } Price { Ohlc { Open High Low Close } Average { Mean } } Volume { Base Usd } } } } ``` ## Reserves of a pool `DEXPoolEvents` emits both reserves in USD after every swap, mint or burn in the pool. The newest rows are the current liquidity. Saved query [here](https://ide.bitquery.io/Get-liquidity-of-a-pair_1). ```graphql { EVM(network: eth) { DEXPoolEvents( where: { PoolEvent: { Pool: { SmartContract: { is: "0xc2eab7d33d3cb97692ecb231a5d0e4a649cb539d" } } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { Pool { CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } } } } ``` ## New pools `PoolCreated` on the Uniswap v3 factory names both tokens, the fee tier and the pool address; the v2 factory at `0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f` emits `PairCreated` for the older design. New pools on Ethereum arrive minutes to hours apart, so query the last day rather than waiting on a stream. Saved query [here](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3_9). ```graphql { EVM(network: eth) { Events( where: { Log: { SmartContract: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } Signature: { Name: { is: "PoolCreated" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 50 } orderBy: { descending: Block_Time } ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` ## Related pages - [GeckoTerminal-style Solana API](/docs/blockchain/Solana/solana-geckoterminal-api/) - [BullX-style EVM API](/docs/blockchain/Ethereum/dextrades/evm-bullx-api/) - [Ethereum liquidity API](/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api) - [Ethereum DEX trades API](/docs/blockchain/Ethereum/dextrades/dex-api) --- ## GeckoTerminal-style Solana API: Pair Trades, Buys, Sells, Makers, Top Pairs URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-geckoterminal-api/ GeckoTerminal-style Solana pool data with Bitquery GraphQL: live pair trades, buys, sells, makers and volume, 1-minute candles, pool reserves, and top pairs. # GeckoTerminal-style Solana API: Pair Trades, Buys, Sells, Makers, Top Pairs A GeckoTerminal pool page is a handful of numbers over one market: the trades scrolling in, buys against sells, how many wallets made them, the volume, the candles and the reserves. Each of those is one Bitquery query over the Solana `DEXTradeByTokens` and `DEXPools` cubes, filtered on the pool's market address, and the same queries cover every Solana DEX Bitquery indexes. The worked pool is the WSOL/USDC Orca Whirlpool at `Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE`, one of the busiest markets on the chain, so every example returns rows at any hour. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; Solana queries go to the `graphql` endpoint. The [EVM version](/docs/blockchain/Ethereum/dextrades/evm-geckoterminal-api/) covers Ethereum and the other EVM chains. ## Recommended: Trading API queries (real-time + last ~30 days) ### Live trades with USD price, market cap and supply Streams MEV-filtered trades across all 10 chains; add `Network: {is: "Solana"}` inside `Pair.Market` to scope to one chain. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains). ```graphql subscription { Trading { Trades { Block { Time } Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol Network } QuoteToken { Symbol } Market { Protocol Network } } } } } ``` ### Most accurate token price with 1-minute OHLC (top market) Returns the token's price from its top-volume market via `Ranking: { Position: { eq: 1 } }`; swap the token address and network for your token. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Token-Price-Top-Market-Rank-1). ```graphql { Trading { Pairs( where: { Token: {Address: {is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"}, Network: {is: "Solana"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } limit: {count: 1} orderBy: {descending: Block_Time} ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean } } Volume { Base Usd } Block { Time } } } } ``` The chain-level queries below are the tool for history older than about 30 days and for per-pool detail. ## Live trades of a pool Filter `Trade.Market.MarketAddress` and put the token you want priced under `Trade.Currency`. Each message is one swap with the amount, the price in the counter token and in USD, the side and the signer. Saved stream [here](https://ide.bitquery.io/Get-Solana-pair-trades-data-just-like-geckoTerminal_1). ```graphql subscription { Solana { DEXTradeByTokens( where: { Trade: { Market: { MarketAddress: { is: "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE" } } Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Currency { Symbol } Amount Price PriceInUSD Side { Currency { Symbol } Amount Type } } Transaction { Maker: Signer Signature } } } } ``` ## Buys, sells, makers, buyers, sellers and volume of a pool The stat block of a pool page in one query: the last hour with a five-minute sub-window on every metric. `Side.Type` names the counter-side of each trade, so WSOL was bought where the side was sold, and wallets are counted by transaction signer. Saved query [here](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair00_2). ```graphql { Solana { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Market: { MarketAddress: { is: "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE" } } Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Trade { Currency { Symbol MintAddress } Side { Currency { Symbol } } start: PriceInUSD(minimum: Block_Slot) min5: PriceInUSD(minimum: Block_Slot, if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } }) end: PriceInUSD(maximum: Block_Slot) } trades: count trades5m: count(if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } }) buys: count(if: { Trade: { Side: { Type: { is: sell } } } }) sells: count(if: { Trade: { Side: { Type: { is: buy } } } }) makers: uniq(of: Transaction_Signer) makers5m: uniq(of: Transaction_Signer, if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } }) buyers: uniq(of: Transaction_Signer, if: { Trade: { Side: { Type: { is: sell } } } }) sellers: uniq(of: Transaction_Signer, if: { Trade: { Side: { Type: { is: buy } } } }) volumeUsd: sum(of: Trade_Side_AmountInUSD) volumeUsd5m: sum(of: Trade_Side_AmountInUSD, if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } }) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## One-minute candles for the pool Thirty one-minute candles with volume and trade count. `PriceAsymmetry` below 0.1 drops trades whose two sides disagree on price. ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Market: { MarketAddress: { is: "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE" } } Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } PriceAsymmetry: { lt: 0.1 } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { minutes_ago: 30 } } } } limit: { count: 30 } orderBy: { descendingByField: "Block_Timefield" } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Reserves of the pool The newest `DEXPools` row for the market carries both reserves after the last change, with the quote side in USD. ```graphql { Solana { DEXPools( where: { Pool: { Market: { MarketAddress: { is: "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE" } } } Transaction: { Result: { Success: true } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Block { Time } Pool { Dex { ProtocolName } Market { BaseCurrency { Symbol } QuoteCurrency { Symbol } } Base { PostAmount } Quote { PostAmount PostAmountInUSD PriceInUSD } } } } } ``` ## Top pairs on Solana The busiest WSOL-quoted markets of the last hour with the numbers a pair list shows. Aggregates only run as queries, so poll this rather than subscribing. Saved query [here](https://ide.bitquery.io/Get-Top-Pairs-on-Solana-on-GeckoTerminal_1). ```graphql { Solana { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } orderBy: { descendingByField: "trades" } limit: { count: 10 } ) { Trade { Currency { Name Symbol MintAddress } Market { MarketAddress } Dex { ProtocolName } start: PriceInUSD(minimum: Block_Slot) min5: PriceInUSD(minimum: Block_Slot, if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } }) end: PriceInUSD(maximum: Block_Slot) } makers: uniq(of: Transaction_Signer) trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) buys: count(if: { Trade: { Side: { Type: { is: sell } } } }) sells: count(if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Video Tutorial ### Get Gecko Terminal Data with Bitquery API and Streams ## Related pages - [Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades) - [GeckoTerminal-style EVM API](/docs/blockchain/Ethereum/dextrades/evm-geckoterminal-api/) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) - [Solana API hub](/docs/blockchain/Solana/) --- ## Generate a Bitquery API Token URL: https://docs.bitquery.io/docs/authorization/how-to-generate/ Generate a Bitquery API Token in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # How to Generate a Token In this section, we will see how OAuth is used to generate a token. ## Authorization menu (account UI) Sign in at [account.bitquery.io](https://account.bitquery.io/). In the top navigation bar, open **Authorization**. It is a dropdown with two entries: - **Applications** — list of your apps, token lifespan per app, **Tokens** / **Revoke** actions in each row, and **+ New Application** to create one. - **Tokens** — generate and copy access tokens for a chosen application. The page below shows **Authorization** with **Applications** selected (active tab). A short doc link appears above the table; use **+ New Application** to add an app. ![Authorization menu — Applications page at account.bitquery.io](/img/ide/authorization-applications.png) Direct links (same pages as the menu items): [Applications](https://account.bitquery.io/user/api_v2/applications) · [Access tokens](https://account.bitquery.io/user/api_v2/access_tokens). The first step is to create an application: 1. **Create an Application**: Open **Authorization → Applications** (or go to the [Applications](https://account.bitquery.io/user/api_v2/applications) page) and click **+ New Application**. Enter a name for your application and select an expiration time for the access tokens. Confirm creation. 2. **Generate Access Token**: We provide two methods to generate a token: - You can generate a token for your application with a set expiration time. - Or you can use your client ID-secret from your application to make a POST request to https://oauth2.bitquery.io/oauth2/token and get a token programmatically. Example: ```bash curl -X POST "https://oauth2.bitquery.io/oauth2/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "grant_type=client_credentials" \ --data-urlencode "client_id=YOUR_CLIENT_ID" \ --data-urlencode "client_secret=YOUR_CLIENT_SECRET" \ --data-urlencode "scope=api" ``` Sample response: ```json {"access_token":"","expires_in":17999,"scope":"api","token_type":"bearer"} ``` > **If you have no applications created, the `Bearer` token changes every 12 hours. If the token is invalid, you get "Unauthorized" message.** ## Generating a Token with Set Expiration Time 1. Open **Authorization → Applications** and click **Tokens** on the row for your application (or use **Authorization → Tokens** / the [Access tokens](https://account.bitquery.io/user/api_v2/access_tokens) page and choose the application). You will land on that app’s token page (URL like `/user/api_v2/applications/`), which lists **Manually created access tokens**, the access token lifespan, and actions for each token. ![Application token page — manually created access tokens, Generate New Token](/img/ide/authorization-application-tokens.png) 2. Click **Generate New Token** (or **Generate Access Token**, depending on the UI label). 3. For the new **Active** token, click **Copy** next to the token value (or copy the value safely another way) and store it in a secure location. ![Manually created access tokens — Copy button next to an active token](/img/ide/authorization-copy-token.png) **Using the token:** To utilize the token you've copied from the api_v2/access_tokens page, use the code generation feature on your IDE to obtain the code in your preferred programming language. However, **remember to paste the token you've copied from the api_v2/access_tokens page**. This is necessary because the IDE code generator only displays temporary tokens. ![temporary](/img/v2Access/temporarytoken.png) For example, you can include the token in the header as shown below: ``` Authorization: Bearer ``` Refer Postman examples [here](https://www.postman.com/interstellar-eclipse-270749/workspace/bitquery) **Revoking an Access Token** If you believe that your access token has been compromised, open **Authorization → Applications** and click **Revoke** on the row for that application (some rows also link to **Tokens** for that app). ![revoke](/img/v2Access/revoke.png) ## Generating a Token Programmatically Remember that this approach requires more effort to implement. It is suitable for applications with a high risk of token theft or misuse. This approach expects you to programmatically generate an access token using your client ID and client secret of an application. ![client](/img/v2Access/clientid_secret.png) **Using curl** Replace `YOUR_CLIENT_ID` and `YOUR_CLIENT_SECRET` with your application's client ID and client secret: ```bash curl -X POST "https://oauth2.bitquery.io/oauth2/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "grant_type=client_credentials" \ --data-urlencode "client_id=YOUR_CLIENT_ID" \ --data-urlencode "client_secret=YOUR_CLIENT_SECRET" \ --data-urlencode "scope=api" ``` **Using Python** Below is a code snippet in Python that shows you how to programmatically generate a token and use the API, replace the placeholders with actual information. Ensure that `scope=api` is mentioned in the payload, ```javascript def oAuth_example(): url = "https://oauth2.bitquery.io/oauth2/token" payload = 'grant_type=client_credentials&client_id=YOUR_ID_HERE&client_secret=YOUR_SECRET_HERE&scope=api' headers = {'Content-Type': 'application/x-www-form-urlencoded'} response = requests.request("POST", url, headers=headers, data=payload) resp = json.loads(response.text) print(resp) access_token=resp['access_token'] url_graphql = "https://streaming.bitquery.io/graphql" headers_graphql = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {access_token}' } //use the token to send a request oAuth_example() ``` The response will include details on `scope` and `expiration time` of the token. A sample response looks like this: ``` {'access_token': 'ory_at_sKK8sSq8', 'expires_in': 2627999, 'scope': 'api', 'token_type': 'bearer'} ``` **Deleting an Application** If you no longer need an application, open **Authorization → Applications** and remove it using the action shown for that row (for example **Delete** or **Revoke**, depending on application type). All tokens for that application will stop working. **Billing Considerations** - Billing remains consistent across API v1 and v2. - Purchase points once and utilize them for either v1 or v2 in any combination. --- ## Get API - Open the Coinpath Query Behind a MoneyFlow in the IDE URL: https://docs.bitquery.io/docs/moneyflow-lite/get-api-coinpath-query/ Use the Get API button in MoneyFlow Lite to open the Coinpath GraphQL query behind a trace in the Bitquery IDE, adjust inbound and outbound depth, and generate code in your language. # Get API: Open the Coinpath® Query in the IDE Every MoneyFlow is built from [Coinpath®](/docs/moneyflow-lite/coinpath-explained/overview) queries. The **Get API** button opens the query behind a panel in the [Bitquery IDE](https://ide.bitquery.io/), so you can reproduce the trace in code. ## Where the button is - **MoneyFlow chart** header: the query for the whole chart. - **Address details** or **Edge details** header: the query for the selected node or edge. - **Transactions** table header: the query for the rows shown. ## What opens Get API opens the IDE in a **new browser tab**. If nothing appears, allow pop-ups for lite.bitquery.io or pause your ad blocker for the site. The IDE loads with a Coinpath® query and the variables pre-filled from the MoneyFlow: network, origin address, inbound and outbound depth, and the date range. The endpoint selector is set to **API v1** and `https://graphql.bitquery.io`. ![Coinpath query opened from MoneyFlow Lite in the IDE](/img/moneyflow-lite/get-api-ide.jpg) This is the Bitcoin query the chart's Get API button generated for the trace used in this guide: ```graphql query btcPopulate( $network: BitcoinNetwork! $addresses: [String!] $inboundDepth: Int! $outboundDepth: Int! $from: ISO8601DateTime $till: ISO8601DateTime ) { bitcoin(network: $network) { inbound: coinpath( initialAddress: { in: $addresses } depth: { lteq: $inboundDepth } options: { direction: inbound, asc: "depth", desc: "amount" } date: { since: $from, till: $till } ) { sender { address } receiver { address } amount amountUSD: amount(in: USD) depth currency { address name decimals symbol tokenId } transactions { amount txHash txValue timestamp } } outbound: coinpath( initialAddress: { in: $addresses } depth: { lteq: $outboundDepth } options: { asc: "depth", desc: "amount" } date: { since: $from, till: $till } ) { sender { address annotation } receiver { address annotation } amount amountUSD: amount(in: USD) depth count currency { address name decimals symbol tokenId } transactions { amount txHash txValue timestamp } } } } ``` Variables: ```json { "network": "bitcoin", "addresses": ["bc1qwmcmp9usdjshjs5swt2us26uttffanre7hcx8e"], "currency": [], "outboundDepth": 1, "inboundDepth": 1, "from": "2025-01-08T18:30:00.000Z", "till": "2026-07-16T18:29:59.000Z" } ``` How the query maps to the app: - `inbound` and `outbound` are the two halves of the chart. `direction: inbound` walks senders; the default direction walks receivers. - `transactions { txHash amount txValue timestamp }` are the rows of the [transactions table](/docs/moneyflow-lite/transactions-table). `amount` is the tracing amount and `txValue` the full transaction amount. - `annotation` is the address label shown on nodes. - `from` and `till` are the trace's date range, converted to UTC. ## Change the depth The generated variables carry depth 1 on each side, which is the first hop of the trace. Edit `inboundDepth` and `outboundDepth` to reproduce a deeper trace, or to go further than the app did. Deep traces on busy addresses return a lot of rows, so add a `limit` in `options` when you raise the depth. ![Changing inbound and outbound depth](/img/moneyflow-lite/get-api-levels.png) ## Run the query Click **Run query**. The response lists each sender-receiver pair with the amount, the USD value, the depth and the transactions behind it. ## Generate code Click the **</>** icon at the right end of the IDE toolbar to generate a client in Python, JavaScript, Go, Java, curl and other languages. The generated code includes the query, the variables and the authorization header. ![Code generator in the IDE](/img/moneyflow-lite/get-api-code.png) Read [how to generate a token](/docs/authorization/how-to-generate) before you run the code outside the IDE. ## Related - [Bitcoin Coinpath API](/docs/blockchain/Bitcoin/bitcoin-coinpath-api) for more Bitcoin query examples. - [How to read a Coinpath graph](/docs/moneyflow-lite/coinpath-explained/how-to-read-coinpath-graph) for the query dimensions. --- ## Get Supply and Marketcap of a Token URL: https://docs.bitquery.io/docs/blockchain/Ethereum/transfers/total-supply/ Get Supply and Marketcap of a Token: monitor Ethereum native and token transfers in real time with Bitquery GraphQL APIs. # Get Supply and Marketcap of a Token We will use the [Transaction Balance Tracker APIs](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/) for this query. ```graphql { EVM(network: eth) { TransactionBalances( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenBalance: { Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } Fungible: true } } } ) { Block { Time Number } TokenBalance { Currency { Symbol Name SmartContract Decimals } TotalSupply Marketcap: TotalSupplyInUSD } } } } ``` ## Alternative Method Using Transfer Cube ### Get Supply of a Token ```graphql query MyQuery { EVM(network: eth, dataset: combined) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x582d872A1B094FC48F5DE31D3B73F2D9bE47def1" } } Success: true } } ) { minted: sum( of: Transfer_Amount if: { Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } } } ) burned: sum( of: Transfer_Amount if: { Transfer: { Receiver: { is: "0x0000000000000000000000000000000000000000" } } } ) } } } ``` ### Getting Marketcap ```graphql { EVM(dataset: combined) { Transfers( limit: {count: 1} where: {Call: {Create: true}, Transfer: {Currency: {SmartContract: {is: "0x0f7dc5d02cc1e1f5ee47854d534d332a1081ccc8"}}, Sender: {is: "0x0000000000000000000000000000000000000000"}}} ) { Transfer { Amount Sender Receiver } joinDEXTradeByTokens( limit: {count: 1} join: inner Trade_Currency_SmartContract: Transfer_Currency_SmartContract ) { Trade { Price(maximum: Block_Time) PriceInUSD } } } } } ``` First the query gets supply in the `amount` field then query uses join to get the `PriceInUSD`. Multiplying both of these will give you marketcap of the token. In this example, we are calculating marketcap of Pepes Dog (ZEUS) token which has smart contract address `0x0f7dC5D02CC1E1f5Ee47854d534D332A1081cCC8`. Try the query [here](https://ide.bitquery.io/supply-and-latest-price-of-token-to-get-marketcap). ## Video Tutorial --- ## Get the Latest Block Number with Bitquery Instead of eth_blockNumber URL: https://docs.bitquery.io/docs/blockchain/Ethereum/ethers-library/eth_blockNumber/ Latest Ethereum block number and time by GraphQL query or WebSocket stream, with the same call for BSC, Base and other EVM chains. # Get the Latest Block Number with Bitquery Instead of eth_blockNumber `eth_blockNumber` is the JSON-RPC call that returns the height of the newest block. On Bitquery the same answer comes from the `Blocks` cube in two shapes: a query that returns the newest block with its timestamp, and a subscription that pushes a row every time a block is produced, so you never poll. Both run on Ethereum and, by changing `network`, on BNB Chain, Base, Arbitrum, Optimism, Polygon, Robinhood Chain and Arc. No node, no RPC key: an access token from [account.bitquery.io](https://account.bitquery.io/) and the same query runs in the [IDE](https://ide.bitquery.io) on a free account. ## Latest block number as a query One row, sorted by block number descending. `Time` is the block timestamp, so the same row tells you how fresh the tip is. ```graphql { EVM(network: eth) { Blocks(limit: { count: 1 }, orderBy: { descending: Block_Number }) { Block { Number Time } } } } ``` ## Latest block number as a stream Every new Ethereum block arrives as one message. Open it in the IDE [here](https://ide.bitquery.io/eth_blockNumber-stream). ```graphql subscription { EVM(network: eth) { Blocks { Block { Number } } } } ``` ## Other EVM chains Change the network name and nothing else. This is the BNB Chain stream, saved [here](https://ide.bitquery.io/eth_blockNumber-stream-bsc); `base`, `arbitrum`, `optimism`, `matic`, `robinhood` and `arc` work the same way. ```graphql subscription { EVM(network: bsc) { Blocks { Block { Number } } } } ``` ## What else the Blocks cube returns Add fields to the same selection: `Block { Hash ParentHash Time Number GasUsed GasLimit BaseFee Difficulty }` and `TxCount`. That covers `eth_getBlockByNumber` for the header, without a second call. For the transactions inside a block, filter the `Transactions` cube on `Block: { Number: { is: "..." } }`; the [EVM blocks schema](/docs/schema/evm/blocks) lists every field. ## Related pages - [EVM blocks schema](/docs/schema/evm/blocks) - [debug_traceCall with Bitquery](/docs/blockchain/Ethereum/ethers-library/debug_traceCall) - [WebSocket subscriptions](/docs/subscriptions/subscription) - [Ethereum API hub](/docs/blockchain/Ethereum/) --- ## Getting Ethereum Data from AWS Bucket URL: https://docs.bitquery.io/docs/cloud/examples/s3-eth-tutorial/ Getting Ethereum Data from AWS Bucket: read and parse raw Protobuf blocks from the Bitquery data lake on S3 with Python. # Getting Ethereum Data from AWS Bucket This tutorial reads raw blocks from the [Bitquery data lake](/docs/data-lake/) on Amazon S3. These are raw Protobuf blocks that you decode and parse your own way, not the Parquet Data Store exports. Data on S3 uses the `Protobuf` schema that allows for more efficient data transfer and storage. To make things easier, I'll walk you through how to access the storage and parse the data in Python. You can access the product on the AWS Marketplace here: https://aws.amazon.com/marketplace/pp/prodview-oi4sbdu6zro3i For this tutorial, we'll be using readily available sample datasets. So, let's get started! ![marketplace](/img/aws/marketplace.png) ## What does this code do? This code performs the download and processing of two different files from an Amazon Web Services (AWS) S3 bucket. Specifically, it downloads two files, decompresses them, and extracts information from them using Protocol Buffers. You can access the complete Git repo here: https://github.com/bitquery/S3-Sample-Parse-Tutorial/tree/main ## Step-by-Step Implemention ### Import the necessary libraries ```python from google.protobuf.json_format import MessageToJson ``` ### Access S3 bucket For this step, you need to get your AWS Access Keys. - Go to your AWS Console https://aws.amazon.com/console/ - Navigate to your profile -> Security credentials -> Generate Access Key ![credentials](/img/aws/aws_cred.png) You can find the details of the demo buckets here https://github.com/bitquery/blockchain-data-lake-sample The first part of the code uses the boto3 library to connect to the S3 bucket with the specified credentials. It then defines two object keys, block_object_key which correspond to the S3 object keys for the two files to be downloaded. It also specifies two local file paths, blocks_local_path and dextrades_local_path, which are where the downloaded files will be saved on the local system. ```python s3 = boto3.client('s3', aws_access_key_id='YOUR ID', aws_secret_access_key='YOUR KEY', region_name='us-east-1') bucket_name = 'demo-streaming-eth' block_object_key = 'eth.blocks.s3/000016780000/000016780000_0xf127ae770b9b73af1be93e5a7ac19be5e3bac41673b2685c6b4619fb09af09f0_41452bd33251301d32c606c704120d027de580505d611e4fb1c5ff3ef51d0cb7.block.lz4' blocks_local_path = 'PATH TO YOUR FILE/s3downloadblocks.lz4' ``` ### Download the Files In this step we use **block_message_pb2** which are protobuf message files which contains the structure of the data. We use the s3.download_file() method to download the file specified by block_object_key from the S3 bucket and save it to the local file path specified by blocks_local_path. The downloaded file is in a compressed format, so the code then uses the lz4.frame.decompress() method from the lz4 library to decompress the data. ```python s3.download_file(bucket_name, block_object_key, blocks_local_path) with open(blocks_local_path, 'rb') as f: compressed_data = f.read() decompressed_data = lz4.frame.decompress(compressed_data) print('here') block_headers = block_message_pb2.BlockHeader() block_headers.ParseFromString(decompressed_data) print('here1') ``` ### Write to JSON files The decompressed data is then parsed using the block_message_pb2.BlockHeader() method, which returns an object containing information about the block headers. The code then converts this object to a JSON string using the MessageToJson() method from the google.protobuf.json_format library and saves it to a file named block_headers.json. ```python # Write block_headers to a file with open('block_headers.json', 'w') as f: json_string = MessageToJson(block_headers) f.write(json_string) ``` --- ## Getting Historical Data URL: https://docs.bitquery.io/docs/usecases/tradingview-subscription-realtime/historical_OHLC/ Build Getting Historical Data: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Getting Historical Data In this section, we will write the code to get historical OHLC data to populate a chart with candlesticks up to the current timestamp. Create a new file called `histOHLC.js` and add the following code. Each part of the code is explained below. ### Imports ```javascript ``` - **axios**: Axios is used to make HTTP requests to the Bitquery API. - **config**: A local JSON file storing your API token securely. - **connectBarContinuity**: Adjusts each bar’s open, high, and low so candles connect visually to the previous bar’s close (see [Bar continuity](/docs/usecases/tradingview-subscription-realtime/bar-continuity/)). ### API Endpoint and Query We are using the [Tokens Cube from the Crypto Price API](/docs/trading/crypto-price-api/) which gives you price of a token on different chains in **USD**. You can use Pairs Cube as well to get price against specific currency. :::tip Charting one specific token? Prefer Pairs + rank 1 The `Tokens` candle blends every pool where the token is base, so thin pools contribute to the bar. For a chart of **one** token, query [`Pairs` with `Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) instead — same `Price.Ohlc` fields, but taken from the token's top market. Keep the `Market.Address` from each row if you want to show which venue the candle came from. ::: [You can test the query here](https://ide.bitquery.io/Historical-price-data) **We have used Solana as an example below, you can remove it and get data for all chains provided by the Price API** ```javascript const endpoint = "https://streaming.bitquery.io/graphql"; ``` ```javascript const TOKEN_DETAILS = ` { Trading { Tokens( where: { Token: { Network: {is: "Solana"}, Address: {is: "6ft9XJZX7wYEH1aywspW5TiXDcshGc2W2SqBHN9SLAEJ"} }, Interval: {Time: {Duration: {eq: 60}}} }, orderBy: {descending: Block_Time}, limit: {count: 10000} ) { Token { Address Name Symbol Network } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { SimpleMoving ExponentialMoving } } } } } `; ``` - **TOKEN_DETAILS**: This GraphQL query fetches token trading data on the Solana blockchain for 1-minute intervals (`Duration: {eq: 60}`), including OHLC prices in USD. It’s scoped to a specific token by address: `6ft9XJZX7wYEH1aywspW5TiXDcshGc2W2SqBHN9SLAEJ` for the sake of this explanation. You can pass the variables `quote` from url and set it here. ### fetchHistoricalData Function ```javascript export async function fetchHistoricalData(from) { const requiredBars = 360; // Hardcoding the value ``` - **fetchHistoricalData**: Retrieves at least 360 one-minute OHLC bars, starting from the `from` timestamp. ### API Request ```javascript try { const response = await axios.post( endpoint, { query: TOKEN_DETAILS }, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${config.authtoken}`, }, } ); console.log("API called"); ``` - **axios.post**: Sends a POST request to Bitquery's streaming endpoint with the GraphQL query and an authorization token. - **Authorization**: Token is stored securely in `configs.json`. You can generate one by following [these instructions](/docs/authorization/how-to-generate/). ### Data Processing ```javascript const trades = response.data.data.Trading.Tokens; let bars = trades.map((trade) => { const blockTime = new Date(trade.Block.Time).getTime(); return { time: blockTime, open: trade.Price.Ohlc.Open || 0, high: trade.Price.Ohlc.High || 0, low: trade.Price.Ohlc.Low || 0, close: trade.Price.Ohlc.Close || 0, volume: trade.Volume.Base || 0, }; }); ``` - **Preprocessing the Data**: Maps the raw response into `bars`, where each bar has: - **time**: Unix timestamp in milliseconds. - **open/high/low/close**: OHLC prices. - **volume**: Trading volume in base tokens. ### Sorting the Data ```javascript bars.sort((a, b) => a.time - b.time); ``` Sorts the bars chronologically, as the API returns them in descending order by default. You can skip this step by changing query to return it in **ascending** order. ### Bar continuity (historical) Aggregated OHLC from the API does not always have **open = previous close** (interval boundaries, revisions, or how venues report bars). TradingView still draws each candle from the OHLC you provide, so gaps between the prior close and the next open can look like disjoint candles. After sorting, call `connectBarContinuity` so each bar’s **open** is set to the **previous bar’s close**, and **high** / **low** are expanded to include that price. This only affects presentation; it does not change the close or volume. ```javascript connectBarContinuity(bars); ``` Create `barContinuity.js` in the same folder as `histOHLC.js`: ```javascript /** * Forces each bar's open to the previous close so candles meet visually. * Mutates the array in place. */ export function connectBarContinuity(bars) { if (!bars || bars.length < 2) return bars; for (let i = 1; i < bars.length; i++) { const prevClose = bars[i - 1].close; const bar = bars[i]; bar.open = prevClose; bar.high = Math.max(bar.high, prevClose); bar.low = Math.min(bar.low, prevClose); } return bars; } ``` Run this **after** sorting and **before** any optional placeholder padding below. ### Handling Missing Bars The new price stream will handle all intervals, and this step can be skipped. ```javascript if (bars.length < requiredBars) { const earliestTime = bars[0]?.time || from; const missingBarsCount = requiredBars - bars.length; for (let i = 1; i <= missingBarsCount; i++) { bars.unshift({ time: earliestTime - i * 60000, open: 0, high: 0, low: 0, close: 0, volume: 0, count: 0, }); } } ``` - **Missing Bar Padding**: If fewer than 360 bars are returned, the function prepends placeholder bars (zero OHLC) so the chart has enough points for TradingView’s range request. That is **not** the same as OHLC continuity between real bars; use `connectBarContinuity` on the real API bars for that. ### Return the Processed Data ```javascript return bars; } catch (err) { console.error("Error fetching historical data:", err); throw err; } } ``` - Returns the final processed bar array or throws an error if the API request fails. --- ## Go Example to Use Kafka Protobuf Streams for Real-time Data URL: https://docs.bitquery.io/docs/streams/protobuf/kafka-protobuf-go/ Go Example to Use Kafka Protobuf Streams for Real-time Data with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading. # Go Example to Use Kafka Protobuf Streams for Real-time Data This guide explains how to consume **Bitquery Kafka** topics from **Go**, receive **Protocol Buffers** payloads, and decode **Solana** blocks as **`ParsedIdlBlockMessage`**. The **reference implementation** you run is the minimal app in **[`bitquery/kafka-streams-examples-usecases`](https://github.com/bitquery/kafka-streams-examples-usecases)** ([`go-consumer-example/`](https://github.com/bitquery/kafka-streams-examples-usecases/tree/main/go-consumer-example)): one process, **`.env`** configuration, **`Poll`** loop, stdout for decoded data and stderr for logs. Read the platform overview in **[Kafka streaming concepts — Protobuf streams](/docs/streams/kafka-streaming-concepts/#what-to-know-about-protobuf-streams)**. **`.proto` sources and generated Go types** live under **[Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf)** (Solana tree: [`solana/`](https://github.com/bitquery/streaming_protobuf/tree/main/solana)); this sample imports **`github.com/bitquery/streaming_protobuf/v2/solana/messages`**. **Default wire security:** **SASL** (**SCRAM-SHA-512**) over **Kafka without TLS** on port **9092** (`SASL_PLAINTEXT`). Optional **TLS** is **`SASL_SSL`** on **9093** with PEM files—see **[SSL (SASL_SSL)](/docs/streams/kafka-streaming-concepts/#ssl-connection-sasl_ssl-)**. The minimal example does not enable TLS until you extend **[`kafka.ConfigMap`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/go-consumer-example/main.go)**. > **Scaling:** The repository consumer is intentionally small. For production throughput, use **parallel partition readers**, **queues**, and/or **multiple consumer instances in the same group**, per Bitquery’s partition guidance in **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)**. A larger **Go** reference (YAML, partitioned consumers, worker-style processing) remains **[`stream_protobuf_example`](https://github.com/bitquery/stream_protobuf_example)**—a **different** layout than `go-consumer-example`. ### Prerequisites | # | Requirement | | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | 1 | **Bitquery Kafka access** — username and password for streams ([access](/docs/streams/kafka-streaming-concepts/#how-to-get-access-to-these-streams)). | | 2 | **Authorized topic** — default **`solana.transactions.proto`**; your contract must include the topic you set. | | 3 | **Go** **1.23+** — see [`go.mod`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/go-consumer-example/go.mod). | | 4 | **`confluent-kafka-go/v2`** with **CGO** and system **`librdkafka`** (e.g. macOS: `brew install librdkafka pkg-config`; Debian/Ubuntu: `librdkafka-dev`, `pkg-config`, `gcc`). | | 5 | **Git** — to clone the examples repository. | > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ### Key components (this repository) | Piece | Role | | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **`main.go`** | Loads **`.env`**, builds **`kafka.ConfigMap`**, **`Subscribe`**, **`Poll`** loop, **`proto.Unmarshal`** into **`ParsedIdlBlockMessage`**, prints tree to **stdout**, logs to **stderr**. | | **`printproto.go`** | Walks **protoreflect**; encodes **`bytes`** as **base58** (Solana-style). | | **`.env` / `.env.example`** | **`KAFKA_USERNAME`**, **`KAFKA_PASSWORD`**, optional topic, bootstrap, group id, offset reset. | ## Step by step ### 1. Clone the Go example ```bash git clone https://github.com/bitquery/kafka-streams-examples-usecases.git cd kafka-streams-examples-usecases/go-consumer-example ``` ### 2. Install modules ```bash go mod tidy ``` ### 3. Configure environment ```bash cp .env.example .env ``` Set at minimum: > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ```env KAFKA_USERNAME=your_kafka_username KAFKA_PASSWORD=your_kafka_password ``` Optional (defaults match the Python and Node baselines in the same repository): ```env # KAFKA_TOPIC=solana.transactions.proto # KAFKA_BOOTSTRAP_SERVERS=rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092 # KAFKA_GROUP_ID=my-username-stable-group # KAFKA_AUTO_OFFSET_RESET=latest ``` If **`KAFKA_GROUP_ID`** is omitted, the program generates **`{username}-group-{uuid}`** (see **`loadConfigFromEnv`** in **`main.go`**). Bitquery expects **`group.id`** to **start with your Kafka username** when you choose a stable id. ### 4. Run ```bash go run . ``` Stop with **Ctrl+C** (**`signal.NotifyContext`**). ### 5. Configuration map (as built in code) The following keys are set in **[`main.go`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/go-consumer-example/main.go)** (values from env where noted): ```go cm := kafka.ConfigMap{ "bootstrap.servers": cfg.bootstrap, "security.protocol": "SASL_PLAINTEXT", "sasl.mechanisms": "SCRAM-SHA-512", "sasl.username": cfg.username, "sasl.password": cfg.password, "group.id": cfg.groupID, "session.timeout.ms": 30_000, "enable.auto.commit": false, "ssl.endpoint.identification.algorithm": "none", "auto.offset.reset": cfg.autoOffset, } ``` ## Output and `bytes` fields - **Stdout:** decoded protobuf tree only (no partition/offset prefix). - **Stderr:** subscribe line, Kafka errors, decode errors, shutdown. > **Solana vs EVM `bytes`** > > This example prints **`bytes`** as **base58**, which matches typical **Solana** address / signature style. If you point the decoder at **EVM** protobuf types later, adjust **`printproto.go`** (or an equivalent printer) so **`bytes`** render as **hex** (commonly `0x`-prefixed) instead of base58. ## Changing topic or message type Updating **`KAFKA_TOPIC`** only works when the topic still decodes as **`ParsedIdlBlockMessage`**. Otherwise change the import and **`proto.Unmarshal` target** in **`main.go`** to the type that matches the topic schema (**[`pkg.go.dev` / streaming_protobuf/v2](https://pkg.go.dev/github.com/bitquery/streaming_protobuf/v2)**). ## TLS (optional) Follow **[SASL_SSL](/docs/streams/kafka-streaming-concepts/#ssl-connection-sasl_ssl-)** and extend **`kafka.ConfigMap`** (and broker list, usually **9093**). PEM filenames and fetch commands are summarized in the **[examples repository `README.md`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/README.md)** and **[`kafka-consumer-example`](https://github.com/bitquery/kafka-consumer-example)**. ## Troubleshooting | Symptom | Check | | ------------------------------ | ---------------------------------------------------------------------------------------------------- | | Consumer create / load failure | **`librdkafka`**, **`CGO_ENABLED=1`**, **`pkg-config`**. | | SASL / auth errors | Credentials, topic entitlement, reachability of **9092** (or **9093** if using TLS). | | Protobuf unmarshal errors | Message type does not match topic schema. | | Little or no stdout | Offset policy (**`latest`** vs **`earliest`**) and group id; see Bitquery retention and offset docs. | ## See also - **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)** - **[`stream_protobuf_example`](https://github.com/bitquery/stream_protobuf_example)** — optional advanced Go sample (not the same as `go-consumer-example`). --- ## GoonFi API: Solana Trades, Prices, OHLC and Volume URL: https://docs.bitquery.io/docs/blockchain/Solana/goonfi-api/ GoonFi API on Solana: stream v2 swaps with USD price and market cap, read OHLC candles, top traders and pool volume through Bitquery GraphQL. # GoonFi API: Solana Trades, Prices, OHLC and Volume :::tip Need real-time GoonFi data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered GoonFi swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical GoonFi data older than ~30 days**, raw per-swap detail, or call / event context. ::: ## GoonFi Trades in Real-Time This streams a message for every new GoonFi trade, carrying the buy and sell sides, the block and the transaction. Open it in the [Bitquery IDE: realtime GoonFi trades](https://ide.bitquery.io/Real-time-trades-on-goonfi-DEX-on-Solana_1). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ``` ## Market cap (Trading API) Use **Trading** **`Pairs`** with **`Market.Program`** **`goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE`** (GoonFi v2 DEX program) for aggregated **market cap**, **FDV**, **supply**, **price**, and **volume**. Replace **`solana:`** in **`Token.Id`** with your token. ### Get latest market cap for a specific GoonFi v2 token **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, **`Token.Id`** with **`includesCaseInsensitive`**, interval duration **> 1** second, **`Market.Program`** matching GoonFi v2. Open it in the [Bitquery IDE: GoonFi token market cap](https://ide.bitquery.io/specific-goonfi-v2-token-latest-marketcap).
Click to expand GraphQL query ```graphql { Trading { Trades( where: { Pair: { Market: { Program: { is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE" } Network: { is: "Solana" } } Token: { Address: { is: "So11111111111111111111111111111111111111112" } } QuoteToken: { Address: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Block: { Time: { since_relative: { days_ago: 1 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
### Stream GoonFi v2 tokens with market cap above $10K Subscribe when the token is on **Solana**, **`Market.Program`** is GoonFi v2, **`Supply.MarketCap`** **> 10,000** (USD), and interval duration **> 1** second. Adjust **`gt`** to change the threshold. Run the subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-stream-goonfi-v2-tokens-with-marketcap-above-10k-marketcap).
Click to expand GraphQL subscription ```graphql subscription { Trading { Pairs( where: { Token: { Id: { includesCaseInsensitive: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 10000 } } Market: { Program: { is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
## Latest Price of a Token on GoonFi This returns the most recent trade for a token on GoonFi, with the price in the quote token and in USD. Open it in the [Bitquery IDE: latest price of a GoonFi token](https://ide.bitquery.io/latest-price-of-a-token-on-GoonFi_1). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD Currency{ Name Symbol MintAddress } } } } } ``` ## Realtime Price feed of a Token on GoonFi The same filter as a subscription pushes a message on every new trade, giving a live price feed instead of a single reading. Open it in the [Bitquery IDE: GoonFi realtime price feed](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-GoonFi_1). ```graphql subscription{ Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProgramAddress: {is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Block { Time } Trade { Price PriceInUSD Currency{ Name Symbol MintAddress } } } } } ``` ## GoonFi OHLC API - query For OHLC candles on a GoonFi pair, use [this endpoint](https://ide.bitquery.io/GoonFi-OHLC-API_1) as query and not subscription websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProgramAddress: {is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## GoonFi Realtime OHLC, Price, Volume API - Crypto Price API Below API will give you realtime prices, OHLC, and volume data for all GoonFi trading pairs. We have selected `1` sec as the interval for the OHLC, volume or moving average calculation. You can select any other interval as well like 5 sec, 30 sec, 60 sec, 3600 sec, etc. Try the API [here](https://ide.bitquery.io/GoonFi-Realtime-OHLC-Price-Volume-API---Crypto-Price-API_1). ```graphql subscription MyQuery { Trading { Pairs( where: {Market: {Program: {is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE"}, Network: {is: "Solana"}}, Interval: {Time: {Duration: {eq: 1}}}} ) { Interval { Time { Duration Start End } } Market { Name Address Program } Token { Name Symbol Address } Price { Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } Ohlc { Open High Low Close } } Volume { Base Quote Usd } QuoteToken { Name Symbol Address } } } } ``` ## Get the Top Traders of a specific Token on GoonFi DEX This ranks the wallets trading a given token on GoonFi, here USDC (`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`). Run it as a plain request, not a WebSocket subscription: aggregates are recomputed per message on a subscription, so the totals come back wrong. Open it in the [Bitquery IDE: GoonFi top traders](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-GoonFi-DEX_1). ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProgramAddress: {is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } ``` ## Get trading volume, buy volume, sell volume of a token on GoonFi This uses the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`. Every Trading row carries a vetted USD price, and the cube covers roughly the last 30 days in full, while the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so volume totals taken from them read low. `Side` is the trader's own side. The pair is written WSOL/USDC because that is how the Trading cube orients this market; the USD total is the same either way, but the buy and sell split follows the base token. Widen `days_ago` for longer windows, and for spans beyond a few days prefer [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs/) with `sum(of: Volume_Usd)` over hourly intervals, which is pre-aggregated and much cheaper than scanning every trade. ```graphql { Trading { Trades( where: { Pair: { Market: { Program: { is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE" } Network: { is: "Solana" } } Token: { Address: { is: "So11111111111111111111111111111111111111112" } } QuoteToken: { Address: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) traders: count(distinct: Trader_Address) } } } ``` --- ## GraphQL Archive Dataset URL: https://docs.bitquery.io/docs/graphql/dataset/archive/ Query historical blockchain data with Bitquery’s archive dataset, including retention notes, limits, and GraphQL examples. # Archive Database Archive database contains the data with the **delay from tens of minutes to several hours**, depending on the blockchain. It contains the data from the first (genesis). You need to query it when you need: * statistics, where the latest data does not contribute much value * all the blocks including the blockchain * aggregated queries, like balances, counts, volumes :::tip Archive Database features: * includes all blocks from the genesis (first one) * has a strong consistency of the data * only trunk blocks included * has significant delay of data (from tens of minutes to hours) * queries need to be optimized, as the archive size quite significant ::: Also Check [Combined](/docs/graphql/dataset/combined) and [RealTime](/docs/graphql/dataset/realtime) dataset. ## Do I need anything to query the archive dataset? {#access} Yes. Self-serve plans query `realtime` by default. To run a query with `dataset: archive` or `dataset: combined` you add a **historical data add-on** for the chain you want, from **Account → Billing**. Without it the query is rejected with: ``` access restricted: your plan only allows "realtime", but the request uses "archive:eth:Transactions" ``` That message names exactly what you asked for, so it also tells you which add-on to buy. ### Chains with a self-serve historical add-on | Chain | Add-ons available | | --- | --- | | Ethereum, BNB Chain (BSC), Base, Arbitrum, Optimism, Polygon, Tron, Robinhood | Historical Trading Data · Historical Transfers + Balances + Holders | | Solana | Historical OHLCV & Token Price · Historical Token Transfers & Balances | | Bitcoin, Bitcoin Cash, Litecoin, Dogecoin, Dash, Zcash | Chain Data (historical included) | | Polymarket | Historical Data | Bundles cover all EVM chains at once, and all six UTXO chains at once. Current prices are on the [pricing page](https://bitquery.io/pricing). ### Chains sold as full data packs Bitcoin, Bitcoin Cash, Litecoin, Dogecoin, Dash and Zcash, plus Avalanche, Cardano, Ripple, Stellar, Algorand, Filecoin, Cronos, Klaytn and Celo, are sold as **self-serve data packs with complete history included**. There is no separate archive add-on for them. Buy a pack per chain in your account; prices are on the [pricing page](https://bitquery.io/pricing). Enterprise includes complete history on every chain. :::caution Archive is not deployed for every cube on every chain Even with the add-on, some cube and chain combinations have no archive table. Those return a ClickHouse error such as `no table can query ... consider use realtime dataset`. That is not a problem with your query. Check the [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/) for what exists where. ::: ## Does Bitquery have data for all historical blocks since genesis? {#does-bitquery-have-data-for-all-historical-blocks-since-genesis} Most supported chains have archive history from genesis for the core cubes. Not every cube has an archive: some cubes are realtime only, and some chains cap how far back the archive goes. Check the [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/) for each chain and cube. Where the API does not reach, history is available as Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore). For Solana, full historical token transfers are available via the V1 API. In V2, `DEXTradeByTokens` aggregates start on 1 June 2024 and `DEXTrades` holds individual trades on `archive` and `combined`, being backfilled toward 2024. --- ## GraphQL Calculations and Expressions URL: https://docs.bitquery.io/docs/graphql/calculations/ GraphQL Calculations and Expressions in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Calculations Attributes ```maximum``` ```minimum``` ```where``` can be appended to an element in query. They convert the value to the metric, calculated by the following rules: * if ```maximum``` or ```minimum``` is added, the element returns **its own value on the row where the provided argument is maximal / minimal**. This is an *argmax*, not the maximum of the argument itself: `Number(maximum: Block_GasUsed)` returns the block **number** of the highest-gas block, not the gas figure. * if ```where``` attribute is defined, then the value of element is taken with the provided condition * if ```where``` attribute is used with any of ```maximum``` or ```minimum```, then max / min taken conditionally :::caution On Trading cubes the argument is `if`, not `where` Field-level `where:` is **rejected** on the `Trading` cubes with `Unknown argument "where"`. Use `if:` instead, which takes the same filter shape: ``` Price { Ohlc { Close(maximum: Block_Time if: {Trade: {Side: {is: "Buy"}}}) } } ``` The always-true-`where` tip below therefore does not apply to Trading cubes. ::: ## Examples Maximum block number: ``` Number(maximum: Block_Number) ``` Number of the block with the maximum gas used: ``` Number(maximum: Block_GasUsed) ``` Number of the block with the given root hash: ``` Number(where: {Block: {Root: {is: "..."}}}) ``` Number of the block with the maximum gas used in specific date: ``` Number(maximum: Block_GasUsed where: {Block: {Date:{is: "2022-01-01"}}}) ``` :::note Selectors sharing one key resolve to the same row Several selectors keyed on the **same** argument all read from that one row, so they are mutually consistent. Mixing keys is what breaks coherence: `Open(minimum: Block_Time)` and `High(maximum: Price_Ohlc_High)` come from two different rows by design. ::: :::tip Use ```where``` with some always-true condition (say, ChainId equal 1) to get **any** value of element ::: :::tip Use [Aliases](/docs/graphql/metrics/alias) to name the elements if needed ::: --- ## GraphQL Count Metric URL: https://docs.bitquery.io/docs/graphql/metrics/count/ Use Bitquery’s count metric in GraphQL to aggregate blockchain events, trades, transfers, and other on-chain activity. See examples in the Bitquery IDE. # Count ```count``` element in the query returns the total count of elements **in each set of dimensions**. This query will count blocks by every date: ```graphql { EVM (dataset: archive){ Blocks { Block { Date } count } } } ``` --- ## GraphQL Dataset Options URL: https://docs.bitquery.io/docs/graphql/dataset/options/ Configure Bitquery GraphQL dataset options for archive, realtime, and combined modes when querying blockchain history live. # Options GraphQL interface hides the internal complexity of the datasets, integrating different blockchains, real time and archive data and different ways to query them. Top level element of the query (```EVM``` for Ethereum like blockchains) controls the dataset settings, applied to all the query below. Top level element of the query has 3 attributes, defining what is the source for the result data: 1. ```network``` - blockchain chain to query 2. ```dataset``` - what type of the database to query 3. ```select_blocks``` - which blocks (branches or trunk only) to include in results. The default is `tree`; filtering works on Solana only. See [Select Blocks](/docs/graphql/dataset/select-blocks/) ![Dataset options](/img/ide/dataset_options.png) :::note [subscription](/docs/subscriptions/subscription/) has a different set of top level elements. For example, the dataset for subscription is always real time and not controlled. ::: ## What is the default dataset if I do not set one? If you omit `dataset`, the query behaves as **`dataset: realtime`** — the rolling recent window, with all filters available. Set `dataset: archive` or `dataset: combined` explicitly when you need history, and note that aggregate datasets restrict which fields can be filtered: see [Filter limitations on aggregate datasets](/docs/blockchain/Solana/historical-aggregate-data/#filter-limitations-on-aggregate-datasets). --- ## GraphQL Distinct Metric URL: https://docs.bitquery.io/docs/graphql/metrics/distinct/ Distinct in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Keep queries fast with indexed filters. # Count Distinct ```count``` with ```distinct``` attribute calculates the unique values **in each set of dimensions**. This query will count miners (unique coinbase) by every date: ```graphql { EVM (dataset: archive){ Blocks { Block { Date } miners: count(distinct: Block_Coinbase) } } } ``` ## Count distinct on a list of fields `distinct` also accepts a **list of fields**. The metric then counts the distinct **combinations** of those fields in each set of dimensions. This query counts the distinct buy-token and sell-token combinations traded on Ethereum DEXs in the last hour, next to the distinct count of each side on its own: ```graphql { EVM(network: eth) { DEXTrades(where: {Block: {Time: {since_relative: {hours_ago: 1}}}}) { pairs: count( distinct: [Trade_Buy_Currency_SmartContract, Trade_Sell_Currency_SmartContract] ) buy_tokens: count(distinct: Trade_Buy_Currency_SmartContract) sell_tokens: count(distinct: Trade_Sell_Currency_SmartContract) } } } ``` A sample result shows that the list counts combinations, not the two fields added together: ```json { "EVM": { "DEXTrades": [ { "buy_tokens": "1019", "pairs": "2745", "sell_tokens": "918" } ] } } ``` The list can also be passed as a variable of type `[_EnumFields!]`: ```graphql query ($fields: [EVM_DEXTrade_EnumFields!]) { EVM(network: eth) { DEXTrades(where: {Block: {Time: {since_relative: {hours_ago: 1}}}}) { pairs: count(distinct: $fields) } } } ``` ```json { "fields": ["Trade_Buy_Currency_SmartContract", "Trade_Sell_Currency_SmartContract"] } ``` The `if` argument works with a list as well. [`uniq`](/docs/graphql/metrics/uniq/#uniq-on-a-list-of-fields) accepts the same list in its `of` argument. --- ## GraphQL Expressions URL: https://docs.bitquery.io/docs/graphql/capabilities/expression/ Expression in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Built for traders and analytics teams. # Expressions ## What is a Calculate Expression? An expression is a mathematical function that can be applied to metrics in a GraphQL query. Bitquery's v1 and v2 APIs support expressions to allow you to calculate custom metrics, such as `Price Change` or `Price Change Percentage`. You can create an expression in a query using `calculate()` function. ## Expressions API Examples ### Price Change Percentage of a Token This examples allows us to calculate the price change for a token in percentage over the last hour. ```graphql query MyQuery { Solana { DEXTrades( where: {Block: {Time: {after_relative: {hours_ago: 1}}}, Trade: {Buy: {Currency: {MintAddress: {is: "token_mint_address"}}}}} ) { Trade { Buy { start: PriceInUSD(minimum: Block_Time) end: PriceInUSD(maximum: Block_Time) } } percentage_change: calculate(expression: "100 * ($Trade_Buy_end-$Trade_Buy_start) / $Trade_Buy_start") } } } ``` ### Multiple Operators Inside Expression This example shows how multiple operators could be utilised inside expression at the same time. ```graphql query MyQuery { Trading { Currencies { a1:sum(of: Price_Average_WeightedSimpleMoving) a2:count a3:uniq(of: Currency_Id) a4:calculate(expression:"( 10 * ($a2 - $a1) + $a3 * $a1 ) / $a2") } } } ``` Click **[here](https://clickhouse.com/docs/sql-reference/functions/regular-functions)** to check the list of all available operators. ### Expression Nesting You can also use an expression inside an expression as shown in the example below. ```graphql query MyQuery { Trading { Currencies { a1:sum(of: Price_Average_WeightedSimpleMoving) a2:count a3:uniq(of: Currency_Id) a4:calculate(expression:"$a1 - $a2") a5: calculate(expression:"$a4 * $a3 / 100") } } } ``` Note that the `expression` using `calculate()` could be nested even further. :::note The time interval is derived using `after_relative` keyword with the option of `hours_ago` set as `1` to get all trades of the token in the last one hour. ::: ## Expressions in Streams The `calculate()` option could also be utilised for streams as shown in the example below. ```graphql subscription { Solana { Transactions { transactions:count signers: uniq(of: Transaction_Signer) averageTransactions: calculate(expression: "$transactions / $signers") } } } ``` :::caution In subscriptions every field reference needs a `$` prefix Inside a **subscription**, each field reference in an expression must carry the `$` sigil. A single unsigiled token makes the whole expression return `null` — silently, with no error — so a mixed expression such as `"$Price_Ohlc_Close - Price_Ohlc_Open"` fails just as completely as a fully bare one. Subscriptions also support **arithmetic operators only**. Function calls — `round()`, `floor()`, `abs()`, `plus()`, `greatest()` — evaluate to `null` in a stream while working normally in a query. Aliased results can still be referenced and chained (`$diff`). Queries are unaffected: bare field names and function calls both work there. ::: --- ## GraphQL Joins URL: https://docs.bitquery.io/docs/graphql/capabilities/joins/ Joins in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Includes filters and field selection tips. # GraphQL Joins Starting March 2025, Bitquery APIs support joins on the v2 endpoint. The `joinPLACEHOLDER` function enables you to **embed a subquery** within your main query, allowing data retrieval from the same or a different cube. This is functionally **equivalent to an SQL `JOIN` statement**, providing more efficient and structured data fetching. For example, ```graphql query MyQuery { EVM { DEXTradeByTokens{ # fields from main cube joinCalls{ # Additional fields from the joined cube } } } } ``` ## JOIN Type 4 types of joins are supported: - `left` ( default ) that returns all results from the query matched with all results from joined query. In case join query has no matching result, empty values are returned - `any` is the same as left, except that maximum one ( any ) result is returned from the joined query; - `inner` returns only matching results. If there are no matching results in joined query, the result is not returned; - `inner_any` returns only one ( any ) matching result. If there are no matching results in joined query, the result is not returned; ![GraphQL joins across cubes diagram](/img/joins.png) Here are the additional details from your document that you may want to include in your Markdown: ### 1. **Schemas Supported** - Joins are available for **EVM, Tron, and Solana schemas** in GraphQL v2. ### 2. **Join Query Structure** - The `joinPLACEHOLDER` function embeds a subquery into the main query, where `PLACEHOLDER` is the name of the cube being joined. - The joined query preserves the full schema of the joined cube, allowing: - Querying all fields & metrics - Using additional filters - Setting limits & aggregations ### 3. **Matching Conditions** - At least one attribute must be selected for matching between the main query and joined query. - Example: ```graphql query { EVM { Transfers { joinCalls(join: left, Call_To: Transfer_Receiver) { count } } } } ``` - The above example joins `Calls.Call_To` with `Transfers.Transfer_Receiver`. - **Multiple Matching Conditions** ```graphql query { EVM { Transfers { joinCalls( join: left Call_To: Transfer_Receiver Transaction_Hash: Transaction_Hash ) { count } } } } ``` - Ensures both `Call_To` matches `Transfer_Receiver` and `Transaction_Hash` matches. ### 4. **Other Attributes of Join Query** - **`where`**: Additional filtering - **`limit / limitBy`**: Restricting result sets - **`orderBy`**: Sorting the joined results - Example: ```graphql Transfers { joinCalls(join: left Call_To: Transfer_Receiver where: { Call: {Signature: {Name: {in: ["Transfer","TransferFrom"]}}} } ){ count } } ``` ### 5. **Performance Optimization** - **Use joins only when necessary**, as they are computationally expensive. - **Avoid unnecessary joins** when the same data can be retrieved via direct queries. - **Use pre-aggregated results** to reduce data load. - **Use join types `any` or `inner_any`** to limit excess data retrieval. ### 6. **Limitations** - **Joins only work in queries** (subscriptions not supported). - **Cannot join different datasets (say real-time and archive)**. - **Joins can only be applied at the first query level**. - **Cannot filter query results using join query fields**. ### 7. **Why a join returns empty fields** This is the most common problem with joins, and it does not look like an error. The query succeeds, the row comes back, and every field from the joined cube is blank: ```json { "trades": "1", "volumeUsd": "0", "joinTokenSupplyUpdates": { "TokenSupplyUpdate": { "PostBalance": "", "PostBalanceInUSD": "0", "Currency": { "Symbol": "" } } } } ``` Nothing is wrong with the syntax. `left` is the default join type, and a left join with no match returns the main row with empty values for the joined side. It is indistinguishable from a real result that happens to be zero. **Diagnose it by switching to `inner`.** An inner join drops rows that do not match, so the row count tells you the truth immediately: - Rows come back → the join matches, and your original empty values were genuine data. - **Zero rows** → nothing matched, and the left join was lying to you. **The usual cause is that the joined cube has no rows in the same window.** A join cannot span datasets, so both sides must exist in the dataset you queried. Cubes that only write on specific events are the common trap: - `TokenSupplyUpdates` only writes on mint and burn. An established token may go a long time without one, so joining it to recent trades to compute market cap matches nothing. The same join works well for a freshly launched token, which mints constantly. - Low-activity cubes generally will not have a row in a short retained window. Sanity-check a join against a pair you know matches before trusting it in production, and prefer `inner` or `inner_any` while developing so a mismatch is visible. A join that reliably matches, because the joined side is dense — checking whether a transfer recipient is a smart contract: ```graphql query IsReceiverAContract { EVM(network: eth) { Transfers( limit: { count: 10 } where: { Transfer: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } ) { Transfer { Receiver Amount } joinCalls(Call_To: Transfer_Receiver, join: inner, limit: { count: 1 }) { count } } } } ``` With `join: inner`, only transfers whose receiver has been called as a contract come back. Any receiver that survives is a contract, and any that disappears is an externally owned account. Swapping to the default `left` would return every transfer with an empty `joinCalls`, which tells you nothing. ### 8. **Example Use Cases** #### Example 1 : Check if an address is a smartcontract Take [this](https://ide.bitquery.io/check-if-an-address-is-a-smart-contract) query for example, it helps you detect if an address is a smart contract. ```graphql { EVM(dataset: archive, network: eth) { Transfers( where: {Transfer: {Sender: {is: "0xcf38be613203b39a14d2fb3c1a345122ec0a4351"}}, Block: {Date: {after: "2025-03-01"}}} ) { Transfer { Receiver } count joinCalls(Call_To: Transfer_Receiver, join: inner) { count } } } } ``` #### How This Works - The query finds all transfers from a specific sender - Then, it checks if the receivers of these transfers were later called as smart contracts. - Since only smart contracts can process function calls, it is likely a smart contract if an address appears in joinCalls.(since EOAs cannot process function calls) - The count in joinCalls shows how many times the receiver was called. #### Example 2: Get trades, volume and marketcap of a token [This](https://ide.bitquery.io/get-trades-volume-and-market-cap-of-a-token-in-one-query_1) query is a good example of how joins could be used to get mulltiple trade related matrixes with a single query. ```graphql query MyQuery($time_1hr: DateTime) { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "83vzRC3B9EQVjz8NDULhn7ywcX16TD8FsVFUAEE7pump"}}}, Block: {Time: {since: $time_1hr}}} limitBy: {by: Trade_Side_Currency_MintAddress, count: 1} ) { volume: sum(of: Trade_Side_AmountInUSD) trades: count joinBalanceUpdates( BalanceUpdate_Currency_MintAddress: Trade_Currency_MintAddress orderBy: {descending: Block_Time} ) { BalanceUpdate { PostBalanceInUSD PostBalance Currency { Name MintAddress Symbol } } } } } } ``` #### How this works - The query finds all the trades for the particular token after a given timestamp. - Then the query perform aggregates functions like `sum` and `count` to get `volume` and `trades` of a token after a given time. - Then it checks for the latest `BalanceUpdates` for the token. :::warning `joinBalanceUpdates` does not give you supply or market cap `BalanceUpdates` records a balance change for **one account**, so the joined `PostBalance` is whatever account happened to update most recently, not the token's total supply. `PostBalanceInUSD` is that account's holding value, not market cap. Checked against BONK: this join returns a `PostBalance` of a few million tokens worth tens of dollars, while the token's actual supply is ~88 trillion at a market cap in the hundreds of millions. The two are unrelated numbers. The join happens to approximate supply only for a token whose balance updates are dominated by a single supply-holding account, such as a launchpad bonding curve early in its life. Do not rely on it in general. **For supply and market cap, query `TokenSupplyUpdates` directly** rather than joining it. A `joinTokenSupplyUpdates` on this query returns empty fields, because the join finds no match in the same window (see [why a join returns empty fields](#7-why-a-join-returns-empty-fields)): ```graphql query TokenSupplyAndMarketCap { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { Currency: { MintAddress: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { TokenSupplyUpdate { PostBalance PostBalanceInUSD Currency { Symbol Name } } } } } ``` Here `PostBalance` is the circulating supply and `PostBalanceInUSD` is the market cap. ::: #### Example 3: Get latest price and liquidity of a token in token pair [This](https://ide.bitquery.io/get-latest-price-and-liquidity-of-a-token-in-token-pair) query is a good example of how joins could be used to get latest price and liquidity of a token in particular token pair. ```graphql query PoolLiquidityAndPrice { EVM(dataset: combined, network: eth) { Balances( where: { Balance: { Address: { is: "0x1bCd6B0E97B51D76FD1752111a1fe2b473F655eE" } } Currency: { SmartContract: { is: "0x6b175474e89094c44da98b954eedeac495271d0f" } } } limit: { count: 1 } ) { Balance { Amount } Currency { Symbol } joinDEXTradeByTokens( Trade_Currency_SmartContract: Currency_SmartContract limit: { count: 1 } ) { Trade { PriceInUSD } } } } } ``` #### How this works - `Balances` returns the pool address's current holding of the token directly. There is no summing step, because `Balances` is backed by an aggregate-state table rather than a log of changes. - The join then pulls a `DEXTradeByTokens` row for the same token to attach a USD price. :::caution Do not use this join to read a price `Balances` is daily-grained: it exposes `Block.Date` but not `Block.Time`, so `orderBy: { descending: Block_Time }` on the joined `DEXTradeByTokens` is rejected. With no time ordering available, the joined row is an **arbitrary** match — successive runs of this query return different values, including `PriceInUSD: 0`. The join is shown here because it demonstrates matching on `Currency_SmartContract` across cubes. For an actual price, query `DEXTradeByTokens` directly with an explicit `orderBy: { descending: Block_Time }` and combine the two results client-side. ::: --- ## GraphQL Metric Aliases URL: https://docs.bitquery.io/docs/graphql/metrics/alias/ Alias Bitquery GraphQL metrics to name aggregates, sort results cleanly, and return clearer API field names for apps. See examples in the Bitquery IDE. # Aliases Aliases is a part of the GraphQL [standard](https://spec.graphql.org/draft/#sec-Field-Alias) They become useful when you have the need to have two fields in the query **with the same name**. Most probable you will come to the following problem with metrics: ``` count(distinct: Block_GasUsed) count(distinct: Block_Date) ``` This query is not valid for GraphQL and will not execute. Use aliases to make the query valid and also more readable: ``` uniqueGasValues: count(distinct: Block_GasUsed) uniqueDates: count(distinct: Block_Date) ``` :::tip Aliases can also be used in [sorting](/docs/graphql/sorting) ::: --- ## GraphQL Metrics Overview URL: https://docs.bitquery.io/docs/graphql/metrics/metrics/ Metrics in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Built for traders and analytics teams. # Using Metrics Use metrics if you want to: * calculate some statistics over the results * aggregate the results in a smaller set Adding metrics make the query aggregate query, and it will return results, grouped by dimensions. Look [Query Aggregated Metrics](/docs/graphql/capabilities/aggregated_metrics/) for details. :::tip Consider using metrics in every query to the [archive database](/docs/graphql/dataset/archive/) ::: :::note Metrics can be also used in subscriptions, refer to [Subscription on Aggregated Metrics](/docs/graphql/capabilities/subscription_aggregates/) for details. ::: --- ## GraphQL Network Selection URL: https://docs.bitquery.io/docs/graphql/dataset/network/ Select the blockchain network in Bitquery GraphQL queries using the network attribute, with clear multi-chain examples. See examples in the Bitquery IDE. # Network Network attribute is a selection of the blockchain: * ```eth``` for Ethereum Mainnet * ```bsc``` for Binance Smart Chain * other blockchains are in progress to add to dataset If the attribute is missing, the default blockchain ```eth``` is used. In the resulting data, blockchain is identified by ChainId dimension of the query. There is a mapping of ChainId to the network as shown below: ``` eth: 1 bsc: 56 bsc_testnet: 97 goerli: 5 rinkeby: 4 ropsten: 3 sepolia: 11155111 classic: 61 mordor: 63 kotti: 6 astor: 212 polygon: 137 arbitrum: 42161 avalanche: 43114 optimism: 10 fantom: 250 cronos: 25 klaytn: 8217 fusion: 32659 huobi: 128 moonbeam: 1284 celo: 42220 canto: 7700 aurora: 1313161554 ``` --- ## GraphQL Price Asymmetry Metric URL: https://docs.bitquery.io/docs/graphql/metrics/priceAsymmetry/ Price Asymmetry in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Keep queries fast with indexed filters. # Price Asymmetry In this section, we will see how to use the `PriceAsymmetry` metric to filter results based on Price. ## Formula The Price Asymmetry is calculated using the following formula: ``` PriceAsymmetry = abs(BuyPrice - SellPrice) / (BuyPrice + SellPrice) ``` Where: - `BuyPrice` and `SellPrice` are the USD prices from both sides of a trade (what the wallet buys, the pool sells, and vice-versa) - The formula only calculates when USD prices are available for both tokens - If USD prices are not available for both tokens, the value returns `0` ## How to use PriceAsymmetry to filter anomalies and outliers in Trades ? The PriceAsymmetry metric is being used to filter outliers of anomalies. This means that trades that have a price asymmetry for example 0.1 will be excluded from the results. This helps to ensure that the results are more accurate and reliable, as it removes any trades that may have been caused by anomalies. The price Asymmetry value can only lie between 0 and 1. PriceAsymmetry measures how close the trade’s prices are to each other. If the price asymmetry is less than 0.01, then the difference between the prices is less than 1%. However, the value of 0.01 might be too small and could omit a lot of trades. To improve your anomaly filtering mechanism, , add another filter like `Trade_PriceInUSD: {gt: 100}` filter to only include trades with a trade amount of more than 100 USD. This metric operates consistently across various datasets, including archive, subscriptions and mempool. For live data streams or mempool transactions, the latest available prices from both sides of the trade are used as benchmarks. Use the PriceAsymmetry metric to filter the response. By comparing two values derived from market data, it effectively identifies and exclude trades outside the specified range. > Note: : If we do not know exchange prices for BOTH tokens of a trade pair we can not calculate priceAsymmetry, we set it to 0. Here's an example [query on ethereum trades](https://ide.bitquery.io/Price-based-on-DEX-trades-in-USD). ```graphql subscription { EVM { DEXTradeByTokens( where: { Trade: { Currency: { Symbol: { is: "WETH" } } PriceAsymmetry: { le: 0.1 } } } ) { Block { Time } median(of: Trade_PriceInUSD) } } } ``` Similarly, below is an example on solana trades. ```graphql subscription { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}, Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}, PriceAsymmetry: {lt: 0.9}}} ) { Block { Time } Trade { Price } } } } ``` --- ## GraphQL Quantile Metric URL: https://docs.bitquery.io/docs/graphql/metrics/quantile/ Quantile in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Scale further with Kafka streams, or gRPC on Solana. # Quantile Quantiles are useful in understanding the distribution of numerical data by dividing it into intervals. For example, the median represents the middle point of the data. Half of the responses had amounts lower than the median, and half had amounts higher. And the 75th percentile shows that 75% of the responses had values lower than this, while 25% of the values were higher. Bitquery APIs have the quantile metric, that can be used to provide insights into gas consumption, transaction amounts, or any other measurable field. ### Example 1: Querying Gas Consumption Quantiles The following query retrieves statistics on gas usage for calls on the BSC network. The result provides the 25th percentile (1st quartile), 50th percentile (median), and 75th percentile (3rd quartile) for gas consumption, helping to understand the spread of gas costs in recent calls. ```graphql query MyQuery { EVM(dataset: archive, network: bsc) { Calls( where: { Block: { Date: { after: "2024-07-12" } } } limit: { count: 10 } ) { Block { Date } quartile_gas: quantile(of: Call_Gas, level: 0.25) medium_gas: quantile(of: Call_Gas) three_fourth_gas: quantile(of: Call_Gas, level: 0.75) count } } } ``` ### Example 2: Querying Transfer Amount Quantiles This query provides insights into transfer amounts in USD by retrieving the lower quartile, median, and upper quartile for transfers on the BSC network. #### Query ```graphql query MyQuery { EVM(dataset: archive, network: bsc) { Transfers( where: { Block: { Date: { after: "2024-07-12" } } } limit: { count: 10 } orderBy: { descending: Block_Date } ) { Block { Date } quartile_amount: quantile(of: Transfer_AmountInUSD, level: 0.25) medium_amount: quantile(of: Transfer_AmountInUSD) three_fourth_amount: quantile(of: Transfer_AmountInUSD, level: 0.75) count } } } ``` - **Quartiles**: - `quartile_amount`: The 25th percentile (1st quartile) of the transfer amounts in USD. - `medium_amount`: The median (50th percentile) of transfer amounts. - `three_fourth_amount`: The 75th percentile (3rd quartile) of transfer amounts. - **Quartile Calculation**: A quartile splits data into four equal parts, with Q1 (1st quartile) representing the 25th percentile, Q2 (median) the 50th percentile, and Q3 (3rd quartile) the 75th percentile. ## Customizing Quantiles with the `level` Parameter In the queries, you can specify different quantiles by adjusting the `level` parameter in the `quantile` function. This parameter determines the percentile or quantile you want to calculate, allowing you to retrieve data that represents various parts of the distribution. For example: - **`level: 0.25`** returns the **25th percentile**, also known as the 1st quartile (Q1). - **`level: 0.50`** (default if not specified) returns the **50th percentile**, or the median (Q2). - **`level: 0.75`** returns the **75th percentile**, or the 3rd quartile (Q3). - You can adjust the `level` to other values (e.g., 0.1 for the 10th percentile or 0.9 for the 90th percentile) depending on the insights you want. --- ## GraphQL Query Capabilities: Filters, Windows, Aggregates, Joins URL: https://docs.bitquery.io/docs/category/capabilities/ What a Bitquery GraphQL query can do: filters, relative time windows, sorting, limits, aggregates, calculations, joins, JSON argument filters and subscriptions. # GraphQL Query Capabilities: Filters, Windows, Aggregates, Joins A Bitquery query is a GraphQL selection on a cube with four kinds of building blocks. Filters in `where` narrow rows by address, token, amount, date or a relative window such as the last 30 minutes. `orderBy` and `limit` shape the result, including sorting by an aggregate you define. Metrics such as `count`, `sum`, `uniq`, `quantile` and `calculate` turn rows into numbers, with `if` conditions so one query returns buys and sells side by side. Joins, array intersection and JSON argument filters reach across cubes and into decoded contract data. All of it runs as a query or a subscription, and the same syntax works on every chain. ## Pick the capability | You want to | Read | |---|---| | Filter by address, token, amount, block or transaction fields | [Query filters](/docs/graphql/filters) | | Filter by a date range | [Date and time filters](/docs/graphql/datetime) | | Filter by "the last N minutes" with no date to update | [Relative time filters](/docs/graphql/capabilities/relative-time) | | Sort by a field or by an aggregate | [Sorting results](/docs/graphql/sorting) | | Know the row and time limits a query can hit | [Query limits](/docs/graphql/limits) | | Sum, count, distinct, quantile, min and max over rows | [Aggregated metrics](/docs/graphql/capabilities/aggregated_metrics) | | Compute a new number from other fields or aggregates | [Calculations and expressions](/docs/graphql/calculations) and [Expressions](/docs/graphql/capabilities/expression) | | Return the rows themselves, not aggregates | [Fact records](/docs/graphql/capabilities/query_fact_records) | | Stream rows or aggregates over WebSocket | [Subscription on facts](/docs/graphql/capabilities/subscription_facts) and [Subscription on aggregates](/docs/graphql/capabilities/subscription_aggregates) | | Combine two cubes in one call | [Joins](/docs/graphql/capabilities/joins) | | Match rows whose array field overlaps a list | [Array intersection](/docs/graphql/capabilities/array-intersect) | | Filter on decoded contract arguments | [Filtering JSON arguments](/docs/graphql/capabilities/json-filtering) | | Use a combined dataset that stitches archive and realtime | [Combined dataset](/docs/graphql/combined) | | Know which fields are indexed for fast filters and sorts | [Indexed fields reference](/docs/graphql/indexed-fields-reference) | | Make a slow query fast | [Optimizing queries](/docs/graphql/optimizing-graphql-queries) | | Drop wash trades and bad prices | [Filtering abnormal prices](/docs/usecases/how-to-filter-anomaly-prices) | | Call the API from Postman | [GraphQL in Postman](/docs/graphql/postman) | | Understand the schema shape first | [Query principles](/docs/graphql/query) | ## Several capabilities in one query Relative time window, a success filter, two aggregated prices with aliases, a calculation over them and a sort by an aggregate: price change of WSOL against USDC per DEX over the last 30 minutes. Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account. ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Block: { Time: { since_relative: { minutes_ago: 30 } } } Transaction: { Result: { Success: true } } } orderBy: { descendingByField: "trades" } limit: { count: 3 } ) { Trade { Dex { ProtocolName } first: PriceInUSD(minimum: Block_Time) last: PriceInUSD(maximum: Block_Time) } trades: count change_pct: calculate(expression: "($Trade_last - $Trade_first) / $Trade_first * 100") } } } ``` Aliases inside `Trade` are referenced in `calculate` as `$Trade_`. The same shape works on `EVM(network: eth)` with `SmartContract` instead of `MintAddress`. ## Related pages - [Building GraphQL queries](/docs/category/building-queries) - [Understanding cubes](/docs/category/understanding-cubes) - [GraphQL metrics overview](/docs/graphql/metrics/metrics) - [Dataset options](/docs/graphql/dataset/options) --- ## GraphQL Query Filters URL: https://docs.bitquery.io/docs/graphql/filters/ Filter Bitquery GraphQL blockchain results with where clauses, comparisons, and indexed fields to keep queries fast and precise. # Filtering In most cases you do not need the full dataset, but just a portion, related to the entity or range you are interested in. Filtering can be applied to queries and subscriptions: - in query, filter defines what part of the dataset you need in results - with subscription, filter also determine when the updated data will be sent to you. If the new data does not match filter, update will not be triggered :::tip Use filters in subscription for notification services on specific type of events matching filter criteria ::: Filters are defined on the cube element level (Blocks, Transactions, so on) as a `where` attribute. ## Using the OR Condition In certain cases, you might want to execute a query that filters results based on one condition **OR** another. This type of query can be particularly useful when you need to retrieve records that meet at least one of multiple criteria. This can be achieved with the `any` operator. The below query for example, retrieves blocks from the Ethereum archive dataset where the block number is greater than `19111970` **OR** the transaction count within a block is greater than `100`. You can run the query [here](https://ide.bitquery.io/using-OR-condition-example-V2) > Note: The `any` filter must always be an array. ```graphql { EVM(dataset: archive, network: eth) { Blocks( where: { any: [ { Block: { Number: { gt: "19111970" } } }, { Block: { TxCount: { gt: 100 } } } ] } limit: { count: 10 } ) { Block { Bloom Date Time Root TxCount } } } } ```` ## Examples ```graphql { EVM { Blocks(where: { Block: { GasUsed: { ge: "14628560" } } }) { Block { Number } } } } ``` returns block numbers with gas used exceeding certain level. `where` attribute is structured, with the same levels as the query schema. This allows to build complex filters by combining criteria, as in the following example: ```graphql { EVM { Transactions( where: { Block: { GasUsed: { ge: "26000000" } } Transaction: { Gas: { ge: "16000000" } } } ) { Block { GasUsed } Transaction { Gas } } } } ``` ## Dynamic Where Filter You can pass the WHERE clause as a parameter to set dynamic conditions for filtering the response. In the below example, we are passing the WHERE clause as a parameter, where we use 'currency' as a filter. ```graphql query ($where: EVM_DEXTradeByToken_Filter) { EVM(dataset: archive) { DEXTradeByTokens( limit: {count: 10} where: $where orderBy: {descending: Block_Date} ) { Block { Date } sum(of: Trade_PriceInUSD) } } } ``` **Parameters:** ```json { "where": { "Trade": { "Currency": { "Symbol": { "is": "PEPE" } } } } } ``` ### Passing Each Criterion as a Filter Each condition can be passed as a parameter to allow for highly customizable queries. ```graphql query( $network: evm_network $mempool: Boolean $currency_filter: EVM_DEXTradeByToken_Input_Trade_Currency_InputType $amount_usd_filter: EVM_Amount_With_Decimals $price_usd_filter: OLAP_Float $price_assymetry_filter: OLAP_Float ) { EVM(network: $network mempool: $mempool) { DEXTradeByTokens( orderBy: {descending: Block_Number} limit: {count: 35} where: { Trade: { Currency: $currency_filter AmountInUSD: $amount_usd_filter PriceInUSD: $price_usd_filter PriceAsymmetry: $price_assymetry_filter } } ) { Block { Time } Transaction { Hash } Trade { Buyer Seller Amount AmountInUSD Currency { Symbol SmartContract } Price PriceInUSD PriceAsymmetry Side { Currency { SmartContract Symbol } } } } } } ``` **Parameters:** ```json { "network": "matic", "mempool": false, "currency_filter": { "SmartContract": { "is": "0x53e0bca35ec356bd5dddfebbd1fc0fd03fabad39"} }, "amount_usd_filter": {"ge": "2000.0"}, "price_usd_filter": {"ge": 13.59}, "price_assymetry_filter": {"ge": 0.001} } ``` ## Filter Types Depending on the data type of the element used in `where` filter, different operators can be applied. ### Numeric Filter Types For numeric data, the following operators applicable: * `eq` equals to * `ne` not equals to * `ge` greater or equal * `gt` greater than * `le` less or equal * `lt` less than ### String Filter Types For string data: * `is` * `not` * `in` * `notIn` * `includes` * `includesCaseInsensitive` * `notIncludes` * `notIncludesCaseInsensitive` * `like` * `likeCaseInsensitive` * `notLike` * `notLikeCaseInsensitive` * `startsWith` * `startsWithCaseInsensitive` * `endsWith` Examples: * `%` → Matches zero or more characters * `_` → Matches exactly one character ### Date and Time Filter Types * `is` * `not` * `after` * `since` * `till` * `before` ### Array Filter Types * `length` * `includes` * `excludes` * `startsWith` * `endsWith` * `notStartsWith` * `notEndsWith` Example: ```graphql { EVM { Calls( where: { Arguments: { length: {eq: 2} includes: { Index: {eq: 0} Name: {is: "recipient"} } } } limit: {count: 10} ) { Arguments { Index Name Type } Call { Signature { Signature } } } } } ``` Another example: ```graphql Arguments: { includes: [ { Index: {eq: 0} Name: {is: "recipient"} Value: {Address: {is: "0xa7f6ebbd4cdb249a2b999b7543aeb1f80bda7969"}} } { Name: {is: "amount"} Value: {BigInteger: {ge: "1000000000"}} } ] } ``` ## Filtering: Where vs selectWhere The `selectWhere` parameter functions similarly to the `HAVING` clause in SQL. ```graphql query { EVM(dataset: archive) { Blocks { Block { Date } sum(of: Block_TxCount selectWhere: {gt: "1500000"}) } } } ``` This example filters based on aggregated `sum`. Compare with: ```graphql query { EVM(dataset: archive) { Blocks(where: {Block: {TxCount: {gt: 1500000}}}) { Block { Date } } } } ``` `where` filters **before aggregation**, `selectWhere` filters **after aggregation**. ``` ## How do I use the 'since' and 'till' date filters in Bitquery GraphQL? Put **`since`** (start) and **`till`** (end) on **`Block.Time`**, **`Block.Date`**, or other **date/time filter** objects inside `where`. Example: `Block: { Time: { since: "2024-06-01T00:00:00Z", till: "2024-06-02T00:00:00Z" } }`. You can combine them with **`after`**, **`before`**, or **`is`** per field type. Full list: [Date and Time Filter Types](#date-and-time-filter-types). --- ## GraphQL Query Principles - Bitquery API Schema & Data URL: https://docs.bitquery.io/docs/graphql/query/ GraphQL Query Principles - Bitquery API Schema & Data in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Query Principles You query the data using [GraphQL](https://graphql.org/) language. Basically it defines simple rules how the schema is defined, and how to query the data using this schema. ## Schema Schema defines what data you can query and which options (arguments) you can apply to the query. Schema allows [IDE](/docs/start/first-query/) to create hints to build the query interactively. [IDE](/docs/start/first-query/) also shows the schema on query builder and in Document section. Only queries matching schema can be successfully executed. Schema for blockchain data is pretty complicated, but for your queries you do not need to see it full. You only need a portion of it related to your needs typically. ## Query vs Subscription Query is used to query the data. When you need to get updated results, you must query the endpoint again with the same or another query. Subscription is used to get data updates. You define a [subscription](/docs/subscriptions/subscription/), and after the new data appear, it will be delivered to you without any actions from your side. This defines the cases, when to use one or another: * use queries when you need data once, or the data not likely changed during its usage period * use subscriptions for the "live" data, or when data may be changed while using it Good news, that queries and [subscriptions](/docs/subscriptions/subscription/) use identical schemas, except some attributes of the top element, to define the [dataset](/docs/graphql/dataset/options) usage. It allows your applications to switch between pull and push modes of operation with a minimal changes of the code and queries. Compare the code in [the first query](/docs/start/first-query) and [the first subscription](/docs/start/getting-updates) to see the difference. This section describes principles that applies to subscriptions as well as to queries. We will show examples for queries, but remember that they applied to [subscriptions](/docs/subscriptions/subscription/) as well. ## Default filters (GraphQL v2) By default, **only successful data** is included in results. GraphQL v2 applies the following default filters to both queries and subscriptions. You can override any of them by specifying different values explicitly in your GraphQL filters. | Data type | Default filter(s) | |-----------|-------------------| | **Transactions** | `success = true` | | **Calls, Events, Transfers, Prediction market events, DEX pool events** | Call/event success **and** transaction success = `true` | | **DEX trades** | Trade `success = true` | | **Trade API market prices** | `Price_IsQuotedInUsd = true`, `Interval_VolumeBased = false` | To get failed or non-default data, add an explicit filter. For example, to query **failed DEX trades**, you must explicitly filter for them (e.g. [Failed trades example](https://ide.bitquery.io/Failed-trades)). For default **limits** (query and subscription), see [Limits](/docs/graphql/limits/) and [Subscription default parameters](/docs/subscriptions/subscription/#default-parameters-graphql-v2). ## Query Elements Consider the query: ```graphql query { EVM(dataset: archive network: bsc) { Blocks(limit: {count: 10}) { Block { Date } count } } } ``` ### Dataset Element Top element of the query is ```graphql EVM(dataset: archive network: bsc) { ``` which defines the type of schema used (```EVM```, Ethereum Virtual Machine). For different types of blockchains we use different schema. ```dataset: archive network: bsc``` is an attribute, defining how we query the [dataset](/docs/graphql/dataset/options). In this case, we query just archive (delayed) data on BSC (Binance Smart Chain) network. Refer to the [dataset](/docs/graphql/dataset/options) documentation for possible options to apply on this level. By selecting the top element ``` EVM ``` we completely define what we can query below this element. Apparently, Bitcoin and Ethereum have different schema and data, so we can not query them exactly the same way. ### Cube Element ```Blocks(limit: {count: 10})``` is what we call "Cube", particulary because we use [OLAP](https://wikipedia.org/wiki/OLAP) methodology, applying [metrics](/docs/graphql/metrics). Cube defines what kind of facts we want to query, in this case we interested in blocks. Cubes are generally different for different types of blockchains. ### Dimension Element ```graphql Block { Date } ``` is the dimension part of the query. It defines the granularity of the data that we query. This example queries the data per-date manner. If we would need to have it per block, we would use: ```graphql Block { Number } ``` Query can make many dimensions. Result will have granularity combined from all dimensions used. Query for transactions by block date and transaction hash will group all result by block **date** __AND__ by transaction **hash**: ```graphql Block { Date } Transaction { Hash } ``` ### Metric Element ```count``` is a [metric](/docs/graphql/metrics). It is optional, defines "what we want to measure". If it is missing, the results will give all data with the selected dimensions. Note that the presence of at least one [metric](/docs/graphql/metrics) changes the way how query operates. Compare these two queries: The following query returns as many entries as blocks we have, with the date for each block: ```graphql Block { Date } ``` This return counts of blocks **per every date** (aggregated by all blocks) : ```graphql Block { Date } count ``` Refer to the [metric](/docs/graphql/metrics/) tutorial for more details how you can use them. ### Attributes ```limit: {count: 10}``` is an attribute, defining [limit](/docs/graphql/limits) on the data result size. There are several types of attributes, described in the sections: * [limits](/docs/graphql/limits) * [ordering](/docs/graphql/sorting) * [filters](/docs/graphql/filters) * [calculations](/docs/graphql/calculations) ### Correctness To be correctly executed, the query must conform with the following requirements: 1. query must conform the schema. When you build query in the [IDE](/docs/start/first-query/), it will highlight all errors according to schema 2. query should not violate principles described above and some natural limitations of the database capabilities. For example, you can not fetch a million result in one query, you have to use offset and limits. 3. query should not consume more than available resources on the server. We use points to calculate consumed resources. If query can not execute, the result contains the ```errors``` in the results This screen shows the highlighted error in the query and the resulting response: ![IDE query error](/img/ide/query_error.png) --- ## GraphQL Statistics Metrics URL: https://docs.bitquery.io/docs/graphql/metrics/statistics/ Statistics in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Scale further with Kafka streams, or gRPC on Solana. # Statistics ## Over One Variable Elements that calculate different statistics with the self-descriptive names: * ```average``` calculates the arithmetic mean. * ```standard_deviation``` square root of dispersion for a set of values * ```dispersion``` dispersion for a set of values (Σ((x - x̅)^2) / n), , where n is the sample size and x̅ is the average value of x * ```median``` median of a numeric data sample * ```entropy``` calculates [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of a set of values * ```skew``` [skewness](https://en.wikipedia.org/wiki/Skewness) of a set of values * ```kurtosis``` [kurtosis](https://en.wikipedia.org/wiki/Kurtosis) of a set of values * ```quantile```approximate [quantile](https://en.wikipedia.org/wiki/Quantile) of a numeric data sequence (have ```level``` argument from 0 to 1, 0.5 is median) For example to calculate average reward: ``` average(of: Reward_Total) ``` ## Over Two Variables Some statistics require 2 variables. One variable is specified in ```of``` attribute, the other in ```with``` attribute, for example: ``` correlation(of: Reward_Total with: Block_GasUsed) ``` Elements that calculate different statistics with the self-descriptive names: * ```covariance``` value of Σ((x - x̅)(y - y̅)) / n * ```correlation``` pearson correlation coefficient: Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)^2) * Σ((y - y̅)^2)) * ```contingency``` calculates the [contingency coefficient](https://en.wikipedia.org/wiki/Contingency_table#Cram%C3%A9r's_V_and_the_contingency_coefficient_C), a value that measures the association between two columns in a table. The computation is similar to the cramersV function but with a different denominator in the square root. **Note that this coefficient does not reach 1 even for a near-deterministic relationship** — its maximum depends on the dimensions of the underlying table. On data where `cramers` approaches 1, this coefficient sits well below it. Do not read it on a 0–1 scale or compare it directly with Cramér's V; for association strength prefer `cramers_bias_corrected` * ```rank_correlation``` rank correlation coefficient of the ranks of x and y. The value of the correlation coefficient ranges from -1 to +1. The value close to +1 denotes a high linear relationship, and with an increase of one random variable, the second random variable also increases. The value close to -1 denotes a high linear relationship, and with an increase of one random variable, the second random variable decreases. The value close or equal to 0 denotes no relationship between the two random variables. * ```cramers``` [Cramér's V](https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V) (sometimes referred to as Cramér's phi) is a measure of association between two columns in a table. The result of the cramers function ranges from 0 (corresponding to no association between the variables) to 1 and can reach 1 only when each value is completely determined by the other. It may be viewed as the association between two variables as a percentage of their maximum possible variation. * ```cramers_bias_corrected``` Cramér's V is a measure of association between two columns in a table. The result of the cramersV function ranges from 0 (corresponding to no association between the variables) to 1 and can reach 1 only when each value is completely determined by the other. The function can be heavily biased, so this version of Cramér's V uses the bias correction. * ```theils_corrected``` calculates the [Theil's U uncertainty coefficient](https://en.wikipedia.org/wiki/Contingency_table#Uncertainty_coefficient), a value that measures the association between two columns in a table. A value of 0.0 indicates the absence of association, and the magnitude grows towards 1.0 as association strengthens. :::caution The metric is named `theils_corrected`, not `theils` Querying `theils` fails with `Cannot query field "theils"`. Note also that a strong association returns a value near **−1**, not +1 — interpret magnitude, not sign. ::: The following are also available and are not listed above: * ```gini``` Gini coefficient of the values — 0 is perfectly even, 1 is fully concentrated * ```theil_index``` Theil index, an entropy-based concentration measure * ```entropy``` Shannon entropy of the value distribution, in bits * ```nakamoto``` the number of rows that together account for `ratio` of the total of `of` (takes `ratio`, not `if`) * ```skew```, ```kurtosis```, ```dispersion```, ```median```, ```quantile``` distribution shape and position :::tip You can use a [condition](/docs/graphql/metrics/if) on any of these metrics **except `gini`, `nakamoto` and `theil_index`**, which do not accept an `if` argument. ::: --- ## GraphQL Subscriptions Guide URL: https://docs.bitquery.io/docs/subscriptions/subscription/ GraphQL Subscriptions Guide using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # What is a Subscription? Subscription is defined by the subscription type of GraphQL request: ```graphql subscription { eth: EVM(network: eth) { ... } } ``` Almost any query can be converted to a subscription just by replacing the `query` type with `subscription`. Trading cube queries are the main exception — see [What does not survive streaming](/docs/subscriptions/what-does-not-survive-streaming/). :::tip Streaming token trades or prices? Use the Trading API If your subscription is a `DEXTrades` / `DEXTradeByTokens` stream filtered to specific tokens just to get live trades or prices, use the **Trading API** (`Trading.Trades`, `Trading.Tokens`, `Trading.Pairs`, `Trading.Currencies`) instead. It covers 10 chains in one stream, has USD price, market cap, and supply on every row, is MEV/outlier-filtered, and ships pre-aggregated OHLC down to 1-second candles — so you stream far fewer rows for the same signal. See the [Trading Data Overview](/docs/trading/trading-data-overview/) for when to use which. ::: When creating queries for GraphQL subscriptions, here are some tips to consider: 1. **Avoid Limiting Results:** In most cases, you should avoid limiting the results of your subscription query. This is because subscriptions are meant to stream data in real-time and limiting the results could cause you to miss out on new data. 2. **Ordering Might Not Be Necessary:** Given that subscriptions are meant to provide real-time data, ordering might not be necessary or even meaningful since data is sent as it becomes available. 3. **Test Your Queries:** Before deploying your application, make sure to thoroughly test your subscription queries to ensure they return the data you expect and can handle high volumes of data. 4. **Modifying Subscriptions Does Not Work**: If you try to modify a running subscription, it will end the subscription. In addition, optimizing your queries can significantly enhance the performance of your subscriptions. For more insights on how to optimize your websocket queries, go [here](/docs/graphql/optimizing-graphql-queries/). Subscriptions are also priced using our point-based system. Read about it [here](/docs/ide/points/) ## Default Parameters (GraphQL v2) GraphQL v2 applies the following default to subscriptions. You can override it by specifying a different value explicitly in your GraphQL filters. | Parameter | Default value | |-----------|---------------| | **Subscription `limit`** | 800 (per message) | Each subscription message returns at most 800 items by default. Override this by specifying a different `limit` in your subscription filters if you need a different batch size. For **default success and other filters** (e.g. only successful transactions, calls, events, transfers, DEX trades; Trade API defaults), see [Default filters (GraphQL v2)](/docs/graphql/query/#default-filters-graphql-v2) in Query Principles. For default limits on **queries**, see [Limits](/docs/graphql/limits/). ## Creating Multiple Subscriptions in one Websocket It is possible—and often more efficient—to manage multiple subscriptions over a single WebSocket connection. This approach allows you to bundle various subscriptions, such as DEX Trades, Transactions, Blocks, and Transfers, into a single Websocket stream. However, it's important to note that your top-level element must be only one. ```graphql subscription{ EVM{ Transfers{ } Transactions{ } } } ``` ### Example: Tracking USDT Transfers on Ethereum In this graphQL stream, we see how to run multiple streams with a single WebSocket. This query will return two sets of transfer data for USDT on the Ethereum network: `transfers_above_10K` and `transfers_below_10K`. The `transfers_above_10K` data set includes all transfers with an amount greater than or equal to 10,000 USDT. The `transfers_below_10K` data set includes all transfers with an amount less than 10,000 USDT. Both data sets include the transaction hash, sender, receiver, and amount of each transfer. You can run the query [here](https://ide.bitquery.io/USDT-transfers-of-different-amounts-mempool) ```graphql subscription ($token: String!, $minamount: String!, $mempool: Boolean, $network: evm_network!) { usdt: EVM(network: $network, mempool: $mempool) { transfers_above_10K: Transfers( where: {Transfer: {Amount: {ge: $minamount}, Currency: {SmartContract: {is: $token}}}} ) { Transaction { Hash From Gas } Receipt { GasUsed } Transfer { Sender Receiver Amount } } transfers_below_10K: Transfers( where: {Transfer: {Amount: {lt: $minamount}, Currency: {SmartContract: {is: $token}}}} ) { Transaction { Hash From Gas } Receipt { GasUsed } Transfer { Sender Receiver Amount } } } } { "token": "0xdac17f958d2ee523a2206206994597c13d831ec7", "minamount": "10000", "mempool": true, "network": "eth" } ``` --- ## GraphQL Sum Metric URL: https://docs.bitquery.io/docs/graphql/metrics/sum/ Sum trade amounts and transfer volumes in Bitquery GraphQL aggregates to power clear blockchain analytics dashboards. See examples in the Bitquery IDE. # Sum ```sum``` element in the query returns the sum of elements **in each set of dimensions**. Example: ```graphql { EVM (dataset: archive){ MinerRewards { Block { Date } sum(of: Reward_Total) miners: count(distinct: Block_Coinbase) } } } ``` ```sum(of: Reward_Total)``` returns the sum of total rewards over every date. --- ## GraphQL Uniq Metric URL: https://docs.bitquery.io/docs/graphql/metrics/uniq/ Count unique addresses, tokens, or traders with Bitquery’s uniq metric inside GraphQL aggregate blockchain queries. Keep queries fast with indexed filters. # Uniq The `uniq` function is used to estimate the count of unique values in a dataset. It's particularly useful for analyzing large datasets where an exact count may not be necessary or where performance is a concern. Below is an example query using the `uniq` function with the EVM Holders API to get the number of unique token holders for a specific token on a given date. ### Example Query ```graphql { EVM(dataset: archive, network: eth) { Holders( date: "2024-03-04" where: { Currency: { SmartContract: { is: "0x95AD61B0A150D79219DCF64E1E6CC01F0B64C4CE" } }, Balance: {Amount: {gt: "0"}}} ) { exact: uniq(of: Holder_Address, method: exact) count(distinct: Holder_Address) approximate: uniq(of: Holder_Address, method: approximate) } } } ``` ### Result ```json { "EVM": { "Holders": [ { "approximate": "1373089", "count": "1378364", "exact": "1378364" } ] } } ``` ### Understanding Uniq Function Variants - **Estimate (`uniq`)**: The `uniq` function estimates the count of unique values. It uses an adaptive sampling algorithm. This approach is highly accurate and CPU-efficient for processing large datasets. - **Exact Count (`uniqExact`)**: For scenarios requiring precision, the `uniqExact` function calculates the exact number of unique values. Although more memory-intensive it guarantees accuracy. ### When to Use Each Variant - **Use `uniq` for Estimates**: Opt for the `uniq` function when an approximate count suffices. This function is ideal for large datasets where performance and efficiency are priorities. - **Use `uniqExact` for Precision**: Choose the `uniqExact` function when accuracy is non-negotiable. Keep in mind the potential for increased memory usage. ## Uniq on a list of fields `of` also accepts a **list of fields**. The metric then counts the distinct **combinations** of those fields, not the distinct values of each one. This query counts the distinct buy-mint and sell-mint combinations traded on Solana DEXs on 1 October 2026. `count(distinct: ...)` accepts the same list and returns the same number as `uniq` with `method: exact`. ```graphql query ($fields: [Solana_DEXTrade_EnumFields!]) { Solana(dataset: archive) { DEXTrades(where: {Block: {Date: {is: "2026-10-01"}}}) { count(distinct: $fields) uniq( of: [Trade_Buy_Currency_MintAddress, Trade_Sell_Currency_MintAddress] method: exact ) } } } ``` Variables: ```json { "fields": ["Trade_Buy_Currency_MintAddress", "Trade_Sell_Currency_MintAddress"] } ``` ### Result ```json { "Solana": { "DEXTrades": [ { "count": "402072", "uniq": "402072" } ] } } ``` - **Inline or variable**: write the list inline, or pass it as a variable of type `[_EnumFields!]`, for example `[Solana_DEXTrade_EnumFields!]` or `[EVM_DEXTrade_EnumFields!]`. - **Combinations, not a union**: over a 10-minute window the same query returned 2,750 distinct buy mints, 5,148 distinct sell mints and 11,614 distinct combinations of the two. - **Single field still works**: `uniq(of: Trade_Buy_Currency_MintAddress)` and `uniq(of: [Trade_Buy_Currency_MintAddress])` return the same number. - **`method`** works the same way with a list: `exact` for a precise count, `approximate` (the default) for an estimate. - It works on other cubes and chains too, such as `EVM.DEXTrades`, `EVM.Transfers` and `Solana.DEXTradeByTokens`. --- ## GraphQL Variables in Bitquery IDE URL: https://docs.bitquery.io/docs/ide/variables/ GraphQL Variables in Bitquery IDE in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Use Variables When creating a query you can pass parameters to it, this way you can create a more **organized**, **readable** and **maintainable** code. In the IDE there are two boxes that allow you to insert code, the first one is for queries and the second one is for variables. Below you will see a query that gets the details of a transaction, where the parameters are `network` and `tx_hash`. ![IDE Query Variables](/img/ide/query_variables.png) > You can obtain the code through this link [Transaction Detail EVM | BSC](https://ide.bitquery.io/Transaction-Detail-EVM--BSC) ## Variable types When we are going to pass the variables we have to define what type they are, some of them are: - `String` - `Int` - `evm_network` - `DateTime` - `Float` - `Boolean` :::tip You can make the variable required by adding an exclamation mark (`!`) at the end, if the variable is not defined, it will be counted as `null`. ::: --- ## Historical Individual Solana Trades on the API URL: https://docs.bitquery.io/docs/API-Blog/solana-individual-trades-history-api/ Individual Solana trades are now available on the DEXTrades archive and combined datasets, being backfilled toward 2024. What changed, the bound rule, the ordering rule, and ready-made queries. # Historical Individual Solana Trades on the API Until October 2026, individual Solana trades on the API lived in `Solana.DEXTrades` on the `realtime` dataset, which keeps about 12 hours. Anything older came as aggregates from `DEXTradeByTokens` on `archive`, or as per-trade rows from the [Trading API](/docs/trading/crypto-trades-api/trades-api/) for the last month. `Solana.DEXTrades` is now available on `dataset: archive` and `dataset: combined` too: individual trades, one row per swap, with the signature, signer, both legs of the trade, the DEX program and USD values. The archive is being enabled window by window and will reach back to 2024. Like every archive dataset, it is not included in the self-service plans by default: it is part of the **Solana Historical OHLCV & Token Price Data** add-on on the [pricing page](https://bitquery.io/pricing), the same add-on that unlocks `DEXTradeByTokens` history, so customers who already have it can run these queries today. The free trial is realtime only. ## What you get - Every trade of a token in a time window, with the wallet that made it. - Every trade a wallet signed, as far back as the archive reaches. - Trade counts and volumes by DEX inside any window. - Trades in a slot range, for reconciling against your own indexer. - With `combined`, one query that covers the archive and the current slot. ## Two rules The table is large and has no index on token or wallet columns, so two rules apply on `archive` and on the archive half of `combined`. Realtime is unchanged. **Every query needs a bound.** Put a `Block.Time`, `Block.Slot` or `Block.Date` filter at the top level of `where`. A mint or wallet filter on its own is rejected with: ``` DEXTrade from the API table dex_trades needs a filter on Block_Time or Block_Slot in the where clause ``` **Order by slot, not time.** Use `orderBy: {descending: Block_Slot}`. It is the first column of the primary key, so a limited query stops reading early. On `combined`, a recent window ordered by `Block_Time` times out. Keep the window narrow when you filter on an address. There is no index on mint, wallet or signer columns, so every trade in the window is read. An hour or a day works; a multi-day range with an address filter can time out. ## Example: a token's trades in one hour Run it [in the IDE](https://ide.bitquery.io/Solana-Historical-Token-Trades-archive). ```graphql { Solana(dataset: archive) { DEXTrades( limit: {count: 10} orderBy: {descending: Block_Slot} where: { Block: {Time: {since: "2026-09-01T00:00:00Z", till: "2026-09-01T01:00:00Z"}} Transaction: {Result: {Success: true}} Trade: {Buy: {Currency: {MintAddress: {is: "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"}}}} } ) { Block { Time Slot } Transaction { Signature Signer } Trade { Dex { ProtocolName ProtocolFamily } Buy { Amount AmountInUSD PriceInUSD Currency { Symbol MintAddress } Account { Address Owner } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } } } } } } ``` ## Example: a wallet's trades on one day Run it [in the IDE](https://ide.bitquery.io/Solana-Historical-Trades-by-Signer-archive). ```graphql { Solana(dataset: archive) { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Slot} where: { Block: {Time: {since: "2026-09-15T00:00:00Z", till: "2026-09-16T00:00:00Z"}} Transaction: {Signer: {is: "F7yD9Uk47rhxRwet5xh7t8rZS4wN5iE16y2o64KoiQYX"}} } ) { Block { Time } Transaction { Signature } Trade { Dex { ProtocolName } Buy { Amount AmountInUSD Currency { Symbol MintAddress } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } } } } } } ``` ## Example: latest trades up to the current slot `combined` adds the realtime tail on top of the archive. Run it [in the IDE](https://ide.bitquery.io/Solana-Latest-Token-Trades-combined). ```graphql { Solana(dataset: combined) { DEXTrades( limit: {count: 10} orderBy: {descending: Block_Slot} where: { Block: {Time: {since_relative: {hours_ago: 1}}} Trade: {Buy: {Currency: {MintAddress: {is: "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"}}}} } ) { Block { Time Slot } Transaction { Signature Signer } Trade { Dex { ProtocolName } Buy { Amount AmountInUSD PriceInUSD Currency { Symbol } } Sell { Amount Currency { Symbol } } } } } } ``` ## More queries - [Trades of a token by DEX](https://ide.bitquery.io/Solana-Token-Trades-by-DEX-archive): count, USD volume and distinct signers per DEX in a window. - [Wallet buys on a day](https://ide.bitquery.io/Solana-Historical-Wallet-Buys-archive): count and USD volume for one owner. - [Trades in a slot range](https://ide.bitquery.io/Solana-DEXTrades-Slot-Range-Count-archive): `Block.Slot` as the bound. - [Archive coverage](https://ide.bitquery.io/Solana-DEXTrades-Archive-Coverage): total count and first and last trade time, one of the few aggregates that runs without a bound. ## Which cube when | You need | Use | |---|---| | Live swaps or the last 30 days, with USD price and market cap on every row | [Trading API](/docs/trading/crypto-trades-api/trades-api/) | | Individual Solana trades, last 12 hours, no bound needed | `Solana(dataset: realtime)` `DEXTrades` | | Individual Solana trades, older than 12 hours | `Solana(dataset: archive)` or `combined` `DEXTrades` | | OHLCV, volume, buyers and sellers back to June 2024 | `Solana(dataset: archive)` `DEXTradeByTokens` | The full rule set, including how `Block.Date` is turned into a time range and which fields differ from realtime, is on the [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/#historical-dextrades-archive-combined) page. --- ## How Billing Works: Points, Plans & Limits URL: https://docs.bitquery.io/docs/plans/how-billing-works/ Understand Bitquery API points — how queries are priced, streams billing, overage, trials, and per-chain plan entitlements. # How Billing Works: Points, Plans & Limits Bitquery bills by **points**, not by raw request count, because queries differ enormously in the work they do. This page explains what a point is, how streams are billed separately, what happens when you run out, and why a query can fail on a chain you didn't purchase. :::note Check the pricing page for current numbers Plan prices and allowances can change — the [pricing page](https://bitquery.io/pricing) is the source of truth. The figures below were current at the time of writing. ::: ## Plans at a glance | Plan | Monthly | Annual (per mo) | Points / mo | Rate limit | Concurrent streams | |---|---|---|---|---|---| | Personal | $49/mo | $29/mo | 100K | 30 / min | — | | Pro | $99/mo | $69/mo | 1M | 90 / min | 100 | | Scale | $299/mo | $199/mo | 5M | 240 / min | 1,000 | | Enterprise | Custom | Custom | Custom | Custom | Unlimited | Annual billing saves 30% or more and locks the price for 12 months. **Self-service plans are real-time only** — no plan includes archive history. Archive access is bought per chain as an add-on; see [Upgrade to Paid Plan](/docs/ide/paid/#historical-data-add-ons). Points per call depend on query complexity, so simple calls stretch your points further than heavy ones. See the [pricing page](https://bitquery.io/pricing) for the latest. ## What is a point? **Points = resources consumed × price per unit.** A query that scans billions of rows costs more points than one served from a small indexed slice. The same query can even cost slightly different amounts run-to-run depending on how much data it touches. This is why two APIs with the same number of calls can have very different point costs. For the full model, see [IDE Points](/docs/ide/points/). Key consequences developers hit most often: - **A query's cost depends on its complexity**, including on `dataset: realtime`: how many records, fields and cubes it reads, and how much data it scans. Simpler queries cost less. Batching is efficient: one request filtering 50 addresses costs roughly the same as one for a single address — so prefer one batched query over 50 separate ones. - **There's a per-request record cap** (around 25,000 records). For larger result sets, paginate or use a stream/export. - **Points don't roll over.** Unused points expire at the end of the billing period; they do not carry forward. ## Streams are billed separately from points WebSocket subscriptions, Kafka, and gRPC streams are **not** paid for out of your query points. They use stream entitlements: - Stream **capacity** is measured in *stream-minutes* and *GB of stream data* (add-ons at checkout), and by **concurrent stream count** (Personal: none; Pro: 100; Scale: 1,000; Enterprise: unlimited). - **Each environment/consumer counts as its own stream.** Running the same Kafka topic from `dev`, `staging`, and `prod` (different consumer groups) counts as three streams. - Kafka access is a separate line item from your GraphQL plan. See [Rate Limits & Concurrency](/docs/plans/rate-limits/) for the concurrency caps and how they surface. ## Running out: overage, caps, and the 402 - When you exhaust your points, requests fail with a **`402` / `points limit exceeded`** error. Top up or upgrade from [Account → Billing](https://account.bitquery.io/user/upgrade). - Overage is billed per additional million points — **$50 per 1M points** (monthly billing) or **$35 per 1M points** (annual). - **After upgrading, regenerate your access token if you still see the old limit.** A token minted under the previous plan can keep returning `points limit exceeded` until you generate a fresh one. Check your live usage at [Account → Usage](https://account.bitquery.io/user/stats/queries) and via the [Usage API](/docs/authorization/usage-api/). ## Per-chain entitlements Plans grant access to a specific set of chains. **Querying a chain that isn't in your plan fails** — and the error can look like a data problem rather than a billing one. If a query works in the IDE but fails from your app (or vice-versa), confirm the chain is included in your plan. ## Trials The free trial runs for **7 days** and includes **1,000 API points, 100 MCP credits, 2 simultaneous streams, 17 stream-minutes, and 0.2 GB of stream data**, on **real-time data only**. Queries on the `archive` and `combined` datasets are not part of the trial. No card required. Want to look at historical data before you buy? Every dataset in the [Bitquery Data Store](https://bitquery.io/datastore/datasets?utm_source=docs&utm_medium=referral&utm_campaign=datastore&utm_content=billing-trial) has a free sample file. ## Paying by crypto Card payment is available on all plans; **crypto payment is available on annual plans**. For invoices, only pay against an invoice issued from `bitquery.io` — beware of impersonation. ## Next steps - [IDE Points (how points are calculated)](/docs/ide/points/) - [Upgrade to a paid plan](/docs/ide/paid/) - [Rate Limits & Concurrency](/docs/plans/rate-limits/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) --- ## How to Build a Solana Copy Trading Bot - Tutorial URL: https://docs.bitquery.io/docs/usecases/copy-trading-bot/ Build How to Build a Solana Copy Trading Bot - Tutorial: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # How to Build a Solana Copy Trading Bot - Tutorial This project is a Solana copy trading bot that allows users to replicate trades executed by a specified account on the Solana blockchain. The bot fetches trading data using the Bitquery API. For real-time price monitoring, consider using our [Crypto Price API](/docs/trading/crypto-price-api/). However since this is a tutorial project we don't execute a trade but rather store the trade info in an excel document. This is to provide an understanding on how Bitquery APIs could be used to build a full product. > Note: This material is for educational and informational purposes only and is not intended as investment advice. The content reflects the author's personal research and understanding. While specific investments and strategies are mentioned, no endorsement or association with these entities is implied. Readers should conduct their own research and consult with qualified professionals before making any investment decisions. Bitquery is not liable for any losses or damages resulting from the application of this information. ## How do I backtest a copy-trading strategy using Bitquery? **Backtesting** means replaying history: pull past **DEX trades** (or transfers) for the leader wallet and optionally **token prices** over the same windows, then simulate entries/exits in your code. Use **`Solana.DEXTrades`** / **`DEXTradeByTokens`** with **`Block.Time`** ranges and pagination. This tutorial shows how to **fetch** live trades; extend it with archived time ranges and your own PnL rules—Bitquery supplies data, not a built-in backtester. ## Understanding the Code You can view the entire codebase [here](https://github.com/Kshitij0O7/copy-trading-bot/tree/main). The major logical part is in the `main.py` file, so lets try to breakdown the code written here. ### Imports This code snippet will cover all the imports needed for running the script. ```python from constant import token ``` If any error is encountered due to import statement then try running the `pip install ...` command. ### Get Trades Function This function provides the trade info for a particular address, `HH3BmVQoVsH2c5H3nonkw2ySGogyohBXGGgF7vM7MRdk` in this case that could be stored in a doc or copied by adding custom logic. This function hits the Bitquery API with [this query](https://ide.bitquery.io/Get-Trade-Activities_1) to retrieve the latest trades by this account. ```python def getTrades(): ``` #### Declaring URL, payload and headers ```python url = "https://streaming.bitquery.io/graphql" payload = json.dumps({ "query": """subscription { Solana { DEXTrades( where: { Trade: {Buy: {Account: {Address: {is: "HH3BmVQoVsH2c5H3nonkw2ySGogyohBXGGgF7vM7MRdk"}}}}, Transaction: {Result: {Success: true}} } ) { Trade { Buy { Amount Currency { Name Symbol MintAddress } Price } Dex { ProtocolName ProgramAddress ProtocolFamily } Sell { Currency { MintAddress Name Symbol } Price Amount } } Transaction { Signature } } } }""", "variables": "{}" }) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } ``` #### Response Handling ```python response = requests.post(url, headers=headers, data=payload) if response.status_code == 200: return response.json() else: print(f"Error: {response.status_code}") return None ``` ### Execute Trades Function Note that the function doesn't actually execute/replicate the trades retrieved but stores it in an excel document. However, if you wish to build an actual bot or contribute to the project then you can easily do that by adding your own logic to the `executeTrades(trades_data)` function. ```python def executeTrades(trades_data): ``` #### Error Handling and Variable Declaration This snippet handles the case where empty `trades_data` is returned. Also, we define variables such as `dex_trades` to call data in a more direct manner and `trade_records` to mould data into the format of our dataframe. ```python if not trades_data or "data" not in trades_data or "Solana" not in trades_data["data"]: print("No trade data found.") return dex_trades = trades_data["data"]["Solana"]["DEXTrades"] # Prepare the data for DataFrame trade_records = [] ``` #### Iterating the Dex Trades In this section we are iterating the `dex_trades` and updating the `trade_records` simultaneously. ```python for trade in dex_trades: buy_currency = trade['Trade']['Buy']['Currency'] sell_currency = trade['Trade']['Sell']['Currency'] dex_info = trade['Trade']['Dex'] transaction_info = trade['Transaction'] trade_records.append({ 'Buy Amount': trade['Trade']['Buy']['Amount'], 'Buy Currency Name': buy_currency['Name'], 'Buy Currency Symbol': buy_currency['Symbol'], 'Buy Mint Address': buy_currency['MintAddress'], 'Buy Price': trade['Trade']['Buy']['Price'], 'Sell Amount': trade['Trade']['Sell']['Amount'], 'Sell Currency Name': sell_currency['Name'], 'Sell Currency Symbol': sell_currency['Symbol'], 'Sell Mint Address': sell_currency['MintAddress'], 'Sell Price': trade['Trade']['Sell']['Price'], 'Dex Protocol Name': dex_info['ProtocolName'], 'Dex Program Address': dex_info['ProgramAddress'], 'Dex Protocol Family': dex_info['ProtocolFamily'], 'Transaction Signature': transaction_info['Signature'] }) ``` #### Creating a DataFrame and Saving Trade Info to an Excel File ```python df = pd.DataFrame(trade_records) excel_file = 'trades_data.xlsx' df.to_excel(excel_file, index=False) print(f"Data saved to {excel_file}") ``` ### Running the Script This part of code actually runs the script and calls the functions. ```python trades_data = getTrades() executeTrades(trades_data) ``` To run this script enter the following command: ```bash python3 main.py ``` ## Video Tutorial --- ## How to Fetch Ethereum Data with AppSync and AWS Lambda URL: https://docs.bitquery.io/docs/cloud/examples/appsync/ How to Fetch Ethereum Data with AppSync and AWS Lambda: serve raw blocks from the Bitquery data lake on S3 through a GraphQL API. # How to Fetch Ethereum Data with AppSync and AWS Lambda We will be using Lambda functions to use raw Ethereum blocks from the [Bitquery data lake](/docs/data-lake/) S3 buckets with Appsync. S3 buckets often store sensitive or valuable data. By using AWS Lambda as an intermediary, you can enforce access control and implement specific permissions logic before retrieving data from the S3 bucket. This adds an extra layer of security to your data access. Lambda functions allow you to implement custom logic or preprocessing steps before fetching data from S3. This could involve data transformations, validations, or any other custom operations required before responding to the GraphQL query. ### Prerequisites: 1. An AWS account with permissions to access AWS AppSync and Lambda. 2. Existing Lambda function(s) to connect with AppSync. Read more on how to create Lambda function for blockchain data [here](/docs/cloud/examples/lambda-functions/) ### Steps: #### 1. Access AWS AppSync Console - Open your web browser and go to [AWS AppSync Console](https://us-east-1.console.aws.amazon.com/appsync/home?region=us-east-1#/apis) - Replace `us-east-1` in the URL with your desired AWS region if needed. ![appsync](/img/aws/appsync.png) #### 2. Create a Data Source using Lambda Function - In the AWS AppSync console, click on your API or create a new one if required. - Navigate to the "Data Sources" section. - Click on "Create data source". - Choose the type of data source. In this case, select "AWS_LAMBDA". - Provide a name for your data source (e.g., `get_blocks`) and specify the ARN of your Lambda function (`arn:aws:lambda:....:function:getBlocks`). ![AWS data source](/img/aws/appsync_datasources.png) #### 3. Define Schema - Go to the "Schema" section in your AWS AppSync API. - Design your schema using GraphQL SDL (Schema Definition Language). For instance: ```graphql type Block { id: ID! name: String! } type Query { getBlocks: Block } schema { query: Query } ``` ![schema](/img/aws/appsync_schema.png) #### 4. Attach Resolvers - In the "Resolvers" section of your AWS AppSync API, attach resolvers to your defined schema. - Click "Attach" for each field in the schema (`id`, `name`, `getBlocks`) to associate them with their respective data sources or resolvers. - For `getBlocks`, select the data source you created (`get_blocks`). - AWS AppSync will manage the mapping between your GraphQL schema and the Lambda function. #### 5. Save and Deploy - Save the schema changes and deploy your API. - AWS AppSync will generate the necessary GraphQL API endpoints and handle the communication between your GraphQL schema and the Lambda function(s) based on the resolvers you've set. #### 6. Test your GraphQL API - Once deployed, you can use the provided GraphQL endpoint to test your queries against the Lambda function integrated through AWS AppSync. - Try running queries against the `getBlocks` resolver and ensure that it retrieves the expected data from your Lambda function. Remember to replace the placeholders (`getBlocks`, Lambda ARN, etc.) with your actual resource names and ARNs as required in your AWS environment. This integration enables your GraphQL API to interact with your Lambda function(s), allowing you to perform operations defined in your schema using GraphQL queries. --- ## How to Filter Abnormal Prices URL: https://docs.bitquery.io/docs/usecases/how-to-filter-anomaly-prices/ Build How to Filter Abnormal Prices: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # How to Filter Abnormal Prices You might see abnormal prices when you fetch data from Bitquery APIs. There can be two possibilities as to why these abnormal prices associated with trades are appearing in your API response. - In the first case, the trade is correct (check this from any other explorer eg. Etherscan) but anomalous i.e. both tokens’ amounts in USDs are not near to equal (bots are generally responsible for this), we calculate the price using Amount in USD of both the tokens involved and that results in abnormal price. - In the second case, the Bitquery DB itself has incorrect trade data, then create a ticket [here](https://support.bitquery.io). In the first case, we are going to see 3 different methods to filter anomaly trades. Anomaly trades are the trades that result in abnormally high or low prices in USD. Bitquery provides raw trade data and does not omit any trades that are happening over the network. But this also results in some issues for the Bitquery data consumers if they are trying to build something around the Price of tokens, such as trying to get All time high price or building OHLC/K-line charts. For pre-filtered, clean price data, consider using our [Crypto Price API](/docs/trading/crypto-price-api/). 3 ways to omit these types of anomaly trades: ## 1. Using PriceAsymmetry Price Asymmetry represents the difference in TradeAmount in USD of main currency and side currency. We want to include the optimal trades which have approximately the same Amounts in USD on both sides. We generally use priceAsymmetry: \{lt: 0.1\} as a filter in our APIs as this will filter out trades with more than 10% difference in their trade amounts. Also, filter out low AmountinUSD trades from this, say `{Trade: {AmountInUSD: \{lt: "10"\}}}` Read more about Price Asymmetry [here](/docs/graphql/metrics/priceAsymmetry/). Here's an example [query on ethereum trades](https://ide.bitquery.io/Price-based-on-DEX-trades-in-USD). ```graphql subscription { EVM { DEXTradeByTokens( where: { Trade: { Currency: { Symbol: { is: "WETH" } } PriceAsymmetry: { le: 0.1 } } } ) { Block { Time } median(of: Trade_PriceInUSD) } } } ``` ## 2. Using Quantile Bitquery APIs have the quantile metric, that can be used to provide insights into gas consumption, transaction amounts, or any other measurable field. Quantiles are useful in understanding the distribution of numerical data by dividing it into intervals. For example, the median represents the middle point of the data. Half of the responses had amounts lower than the median, and half had amounts higher. The level: 0.75 represents the 75th percentile and it shows that 75% of the responses had values lower than this, while level: 0.25 represents the 25th percentile and it shows that 25% of the values were lower. Read more about quantile [here](/docs/graphql/metrics/quantile/). We can also remove anomaly trades using the quantile metric. Also add one more filter to remove low AmountinUSD trades from this, say `{Trade: {AmountInUSD: {lt: "10"}}}` **Strategy**: Remove extreme trades using quantile Find out `quantile(of: Transfer_AmountInUSD, level: 0.05)` & `quantile(of: Transfer_AmountInUSD, level: 0.95)` This is just an example that gives the 5th percentile and 95th percentile of Trade Price in USD, each token can have a different distribution of anomaly trades so try different levels. And then when you have figured out what is the optimum level, then remove the trades and get your desired data from the subset trades. **Usage Example**: Calculate All Time High Price using quantile Use `quantile(of: Trade_PriceInUSD, level: 0.85)` and `Side: {AmountInUSD: {gt: "10"}}`. Choose the appropriate `level` value, it might be the case that the last 5 percentile trades are too extreme i.e. anomalous in Trade PriceinUSDs so we are skipping that and just getting the 85th percentile Price in USD. ```graphql query AllTimeHighTokenPriceQuery( $tokenAddress: String! $startTime: DateTime! ) { EVM(dataset: archive, network: eth) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: \{ is: $tokenAddress \} } Side: { AmountInUSD: \{ gt: "10" \} } } Block: { Time: \{ since: $startTime \} } } limit: \{ count: 1 \} ) { quantile(of: Trade_PriceInUSD, level: 0.85) Trade { PriceInUSD Amount AmountInUSD Currency { Name } Side { Amount AmountInUSD Currency { Name } } } Transaction { Hash } } } } ``` ## 3. Get all trades and filter on your end Get all the trades from Bitquery API and then filter trades using your own custom logic so that you can remove the anomaly trades with abnormal prices. One such example we have shown [here](/docs/usecases/solana-ohlc-calculator/) where custom logic is a very basic one, fetching quantile values of Trade USD Price with level: 0.05 and level: 0.95 and then only fetching trades between these 2 Trade Prices and thus removing extremes. ## Conclusion Whenever you see abnormal trades with extremely high trade Prices in the API response, first try to get the transaction hash of it and check with another explorer whether the trade amounts are correct or not. If they are correct then apply above mentioned methods to omit these trades. And after clarifying you found that Bitquery gave the wrong Trade data, then create a ticket [here](https://support.bitquery.io) --- ## How to Find Out Where Bitcoin Was Sent Using MoneyFlow Lite URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/how-to-find-out-where-bitcoin-was-sent/ Video tutorial: create a Bitcoin MoneyFlow and use Trace Out to find the destination of funds, including exchange deposit addresses. # How to Find Out Where Bitcoin Was Sent Using MoneyFlow Lite This video shows how to enter a Bitcoin address, create a MoneyFlow and follow the outbound flows with **Trace Out** until the funds reach a labelled exchange address. Read [Trace In and Trace Out](/docs/moneyflow-lite/trace-in-and-trace-out) for the steps in text. --- ## How to Follow Bitcoin Transactions Through Multiple Wallets URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/follow-bitcoin-through-multiple-wallets/ Video tutorial: follow Bitcoin across several intermediate wallets in MoneyFlow Lite, reading the chart and the transactions table at each hop. # How to Follow Bitcoin Transactions Through Multiple Wallets This video follows one payment through a chain of intermediate wallets, selecting a node at each hop and tracing again. Read [How to read the MoneyFlow chart](/docs/moneyflow-lite/how-to-read-the-moneyflow-chart) for the chart elements. --- ## How to Read a Coinpath Graph - Nodes, Levels, Edges and Query Dimensions URL: https://docs.bitquery.io/docs/moneyflow-lite/coinpath-explained/how-to-read-coinpath-graph/ The Coinpath money flow graph is a directed acyclic multigraph. Learn what nodes, levels and edges mean, and how the transaction, transactions, initialAddress and finalAddress dimensions change query results. # How to Read a Coinpath Graph ## Components of the money flow graph Coinpath® models a money flow as a directed acyclic multigraph (DAG multigraph). - **Nodes** are entities. In a money flow they are addresses that send or receive tokens. - **Level** is the causal order, or how many hops a node is from the initial address. A higher level means the transfer happened later and needed more hops to reach. - **Edges** are relationships between nodes. In a money flow they are transfers between addresses. - **Multigraph** means two nodes can be joined by several edges, because one address can pay another in several transactions. - **Edge labels** carry the amount, the timestamp and other details of the transfer. ![Coinpath graph as a DAG](/img/moneyflow-lite/coinpath-dag.png) In the diagram: - Address 1 is the originating address. - It has two outbound transfers to Address 2 and one transfer to Address 3. - Address 4 receives from Address 2 and Address 3, and sends to Address 2. - Address 2 appears twice, on level 1 and on level 3. ### Example from the Explorer The Bitquery Explorer draws the same graph for an [Ethereum address](https://explorer.bitquery.io/ethereum/address/0xa3612cd978b28a36a906ccebfe0c48c2b170b168/graph). ![Explorer money flow graph](/img/moneyflow-lite/explorer-moneyflow-graph.png) - Inbound and outbound depth are both set to 1, so only immediate USDT transfers appear. - The address has three inbound transfers of 9.99972k, 21.9968k and 19.4366k USDT. - There is one outbound transfer of 51.4306k USDT. ## transaction versus transactions The `transaction` and `transactions` fields group results differently. Run both examples to see the difference. ### Group by transaction [Open in IDE](https://ide.bitquery.io/Group-coinpath-by-transacton) ```graphql query ($network: EthereumNetwork!, $address: String!, $inboundDepth: Int!, $limit: Int!, $currency: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) { ethereum(network: $network) { inbound: coinpath( initialAddress: {is: $address} currency: {is: $currency} depth: {lteq: $inboundDepth} options: {direction: inbound, asc: "depth", desc: "amount", limitBy: {each: "depth", limit: $limit}} date: {since: $from, till: $till} ) { transaction { hash time { time } value } sender { address annotation smartContract { contractType currency { symbol name } } } receiver { address annotation smartContract { contractType currency { symbol name } } } amount currency { symbol } depth count } } } ``` ```json { "inboundDepth": 1, "outboundDepth": 1, "limit": 10, "offset": 0, "network": "ethereum", "address": "0xbd3afb0bb76683ecb4225f9dbc91f998713c3b01", "currency": "ETH", "from": "2023-09-20", "till": "2023-09-27T23:59:59", "dateFormat": "%Y-%m-%d" } ``` The `transaction {}` field returns the full transaction object for each transfer, so the result has one row per transaction. ### Group by sender and receiver [Open in IDE](https://ide.bitquery.io/Group-coinpath-by-sender--receiver) ```graphql query ($network: EthereumNetwork!, $address: String!, $inboundDepth: Int!, $limit: Int!, $currency: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) { ethereum(network: $network) { inbound: coinpath( initialAddress: {is: $address} currency: {is: $currency} depth: {lteq: $inboundDepth} options: {direction: inbound, asc: "depth", desc: "amount", limitBy: {each: "depth", limit: $limit}} date: {since: $from, till: $till} ) { transactions { amount height timestamp txHash txValue } sender { address annotation smartContract { contractType currency { symbol name } } } receiver { address annotation smartContract { contractType currency { symbol name } } } amount currency { symbol } depth count } } } ``` ```json { "inboundDepth": 1, "outboundDepth": 1, "limit": 10, "offset": 0, "network": "ethereum", "address": "0xbd3afb0bb76683ecb4225f9dbc91f998713c3b01", "currency": "ETH", "from": "2023-09-20", "till": "2023-09-27T23:59:59", "dateFormat": "%Y-%m-%d" } ``` Here the rows are grouped by `sender.address` and `receiver.address`. Each row is one sender-receiver pair, and `transactions {}` lists the transactions that make up that pair. Use `transaction` when you need every transaction. Use `transactions` when you need the most active senders and receivers or the flow between address pairs. This is the view the MoneyFlow chart uses for its edges. ## initialAddress and finalAddress versus sender and receiver `initialAddress` together with `finalAddress` traces a **path** across several hops. `sender` and `receiver` return **direct transfers** only. ### Paths between two addresses This query returns every outbound path, including loops, from `0xa910f92acdaf488fa6ef02174fb86208ad7722ba` to `0x5265754ebfcfa800051df99ebaf6b4b41a5e0bb1` on Ethereum. ```graphql query ($network: EthereumNetwork!, $outboundDepth: Int!, $limit: Int!, $currency: String!) { ethereum(network: $network) { outbound: coinpath( initialAddress: {is: "0xa910f92acdaf488fa6ef02174fb86208ad7722ba"} finalAddress: {is: "0x5265754ebfcfa800051df99ebaf6b4b41a5e0bb1"} currency: {is: $currency} depth: {lteq: $outboundDepth} options: {direction: outbound, asc: "depth", desc: "amount", limitBy: {each: "depth", limit: $limit}} ) { sender { address annotation smartContract { contractType currency { symbol name } } } receiver { address annotation smartContract { contractType currency { symbol name } } } amount(in: USD) currency { symbol name } depth count } } } ``` ```json { "inboundDepth": 3, "outboundDepth": 3, "limit": 100, "offset": 0, "network": "ethereum", "currency": "ETH", "dateFormat": "%Y-%m" } ``` ### Direct transfers between two addresses This query returns only the direct transfers from the first address to the second, whatever depth you set. ```graphql query ($network: EthereumNetwork!, $outboundDepth: Int!, $limit: Int!, $currency: String!) { ethereum(network: $network) { inbound: coinpath( sender: {is: "0xa910f92acdaf488fa6ef02174fb86208ad7722ba"} receiver: {is: "0x5265754ebfcfa800051df99ebaf6b4b41a5e0bb1"} currency: {is: $currency} depth: {lteq: $outboundDepth} options: {direction: outbound, asc: "depth", desc: "amount", limitBy: {each: "depth", limit: $limit}} ) { sender { address annotation smartContract { contractType currency { symbol name } } } receiver { address annotation smartContract { contractType currency { symbol name } } } amount(in: USD) currency { symbol name } depth count } } } ``` ```json { "inboundDepth": 3, "outboundDepth": 3, "limit": 10, "offset": 0, "network": "ethereum", "currency": "ETH", "dateFormat": "%Y-%m" } ``` --- ## How to Read the MoneyFlow Chart - Nodes, Edges, Depth and Threshold URL: https://docs.bitquery.io/docs/moneyflow-lite/how-to-read-the-moneyflow-chart/ Learn to read the MoneyFlow Lite flow chart: inbound flows on the left, outbound on the right, edge widths by amount, depth levels, the threshold slider and the Depth-based Entity Split option. # How to Read the MoneyFlow Chart The **MoneyFlow chart** panel draws the trace as a flow diagram. Funds move from left to right. ![MoneyFlow chart with inbound and outbound flows](/img/moneyflow-lite/moneyflow-chart.jpg) ## Direction - The **origin** is the address you entered. It sits in the middle and is labelled `origin`. - Everything to the **left** of the origin is **inbound**: addresses that sent funds to the origin. Inbound flows are green. - Everything to the **right** is **outbound**: addresses that received funds from the origin. Outbound flows are red. ## Nodes Each vertical bar is a **node**. A node is one address, or a group of addresses that behave the same way (see Depth-based Entity Split below). The shortened address appears under the bar. Hover a node to see a summary: **In** amount, the address, how many addresses the node groups, and **Out** amount. Click a node to open its [address details](/docs/moneyflow-lite/address-details) in the right-hand panel. ## Edges Each band between two nodes is an **edge**: a transfer, or a set of transfers, from the left node to the right node. The label on the band shows the USD value and the amount in the traced currency, for example `$5.2K / BTC 0.058`. The **width** of a band is proportional to the amount. Wide bands are large transfers. Thin lines are small transfers. Click an edge to open [edge details](/docs/moneyflow-lite/edge-details) and the transactions behind it. ## Depth Each column of nodes is one **depth level**, or hop, away from the origin. - `in-1` is an address that sent directly to the origin. - `out-1` is an address that received directly from the origin. - `out-2` received from an `out-1` address, and so on. The trace starts with one level on each side. [Trace In and Trace Out](/docs/moneyflow-lite/trace-in-and-trace-out) add levels. The current depth is shown in the badge next to the version number, for example **In:1 – Out:2**. ![Depth levels in a Coinpath trace](/img/moneyflow-lite/depth-coinpath.png) ## Worked example This Ethereum trace starts at the Truebit exploiter wallet with a four-day date range. The green inbound band is the 8,535 ETH drained from the exploit contract. The three red outbound bands show the split: two large transfers of about 4,000 ETH each and a small one of 268 ETH. Each receiving address carries the label `hacker-truebit-hacker`, so the chart already tells you the funds stayed under the attacker's control at this hop. ![Annotated MoneyFlow chart of the Truebit exploit](/img/moneyflow-lite/trace-example-truebit.png) Payments under $1,000 were hidden with the threshold slider to keep the chart readable. ## Threshold slider The slider and the **Threshold** box above the chart hide small flows. Only edges at or above the USD value in the box are drawn. Drag the slider or type a value to declutter a busy chart. The threshold only affects the drawing. The transactions table and the trace itself keep every transfer. ## Depth-based Entity Split With **Depth-based Entity Split** checked, addresses at the same depth that show the same transfer behaviour are merged into one node. The node then represents an address group. The address details panel lists every address in the group. Uncheck it to show every address as its own node. ## Zoom, reset and full screen - **+** and **-** zoom the chart. You can also scroll inside the chart. - **Reset** returns to the default zoom and position and clears any search highlight. - The expand icon in the panel header opens the chart in full screen. - The download icon in the chart toolbar exports the chart. ## Search The **Search** box in the toolbar above the panels finds addresses in the trace. Type part of an address or a label to locate it in the chart. ## Colours - Green: inbound. - Red: outbound. - Blue highlight: the currently selected node. --- ## How to Stream Moonshot Live Prices URL: https://docs.bitquery.io/docs/usecases/streaming-moonshot-prices/ Build How to Stream Moonshot Live Prices: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Tutorial: How to Stream Moonshot Live Prices In this tutorial, you will learn how to create a simple React application to stream live prices from the Moonshot protocol using WebSocket and Bitquery's [Moonshot APIs](/docs/blockchain/Solana/Moonshot-API/). You can find the complete repo [here](https://github.com/Divyn/streaming-moonshot-prices) The final output would look something like this ![Streaming Moonshot token prices](/img/ApplicationExamples/moonshot.png) ### Prerequisites - Basic knowledge of React and JavaScript. - Node.js installed on your machine. - [Bitquery OAuth token.](/docs/authorization/how-to-generate/) ### Step 1: Setting Up the Project First, create a new React project if you don’t have one already: ``` npx create-react-app moonshot-stream cd moonshot-stream ``` ### Step 2: Install Required Packages Install the necessary dependencies for WebSocket support: ```bash npm install reconnecting-websocket ``` ### Step 3: Create the `useWebSocket` Hook The `useWebSocket` hook will manage the WebSocket connection, handle reconnection attempts, and process the incoming data. #### **1. `useWebSocket.js` - Custom WebSocket Hook** This file contains a custom React hook named `useWebSocket`, which manages the WebSocket connection. - **Step 1: Initialize State Variables** ```javascript const [data, setData] = useState(null); const [error, setError] = useState(null); const [isConnected, setIsConnected] = useState(false); const [retryCount, setRetryCount] = useState(0); ``` - `data`: Stores the incoming data from the WebSocket. - `error`: Stores any error messages that may occur during connection. - `isConnected`: Tracks whether the WebSocket is currently connected. - `retryCount`: Counts the number of reconnection attempts made. - **Step 2: Define the `useEffect` Hook** ```javascript useEffect(() => { const connectWebSocket = () => { const ws = new ReconnectingWebSocket(url, ["graphql-ws"], options); ``` - `useEffect` is used to initiate the WebSocket connection when the component mounts or when the `retryCount` changes. - `connectWebSocket` function is defined inside the `useEffect` to handle the connection logic. - **Step 3: Handle WebSocket Events** - **onopen Event** ```javascript ws.onopen = () => { setIsConnected(true); setRetryCount(0); ws.send(JSON.stringify({ type: "connection_init" })); setTimeout(() => { ws.send( JSON.stringify({ type: "start", id: "1", payload: { query }, }) ); }, 1000); }; ``` - `onopen`: Triggered when the WebSocket connection is established. - Sends an initial `connection_init` message. - Sends the GraphQL query after a short delay. - **onmessage Event** ```javascript ws.onmessage = (event) => { const response = JSON.parse(event.data); if (response.type === "data") { setData(response.payload.data); } }; ``` - `onmessage`: Triggered when a message is received from the server. - Parses the JSON data and updates the `data` state with the payload. - **onclose Event** ```javascript ws.onclose = () => { setIsConnected(false); if (retryCount < maxRetries) { setRetryCount(retryCount + 1); setTimeout(connectWebSocket, 2000); } else { setError("Max retry attempts reached. Could not connect to Bitquery."); } }; ``` - `onclose`: Triggered when the WebSocket connection is closed. - Attempts to reconnect if the maximum retry count has not been reached. - **onerror Event** ```javascript ws.onerror = (event) => { console.error("WebSocket Error:", event); setError("WebSocket error occurred. See console for details."); }; ``` - `onerror`: Triggered when an error occurs with the WebSocket. - Logs the error to the console and updates the `error` state. - **Step 4: Close Function** ```javascript return () => { ws.close(); }; ``` - Ensures that the WebSocket connection is properly closed when the component unmounts. - **Step 5: Return Values** ```javascript return { data, error, isConnected }; ``` - The hook returns the current state values (`data`, `error`, `isConnected`) to be used in the component. --- ### Step 4: `App.js` - Main Component This file contains the main React component that uses the `useWebSocket` hook to display the data. - **Step 1: Define the GraphQL Query** ```javascript const query = ` subscription MyQuery { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Moonshot" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Program { Method } } Trade { Dex { ProtocolFamily ProtocolName } Buy { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } Sell { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } } Transaction { Signature } } } } `; ``` - This query subscribes to real-time data from the Solana blockchain, filtering for DEX trades related to the "Moonshot" protocol. - **Step 2: Define the WebSocket URL and Options** ```javascript const url = "wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN"; const options = { maxReconnectionDelay: 10000, minReconnectionDelay: 1000, reconnectionDelayGrowFactor: 1.3, connectionTimeout: 5000, maxRetries: Infinity, debug: true, }; ``` - `url`: The WebSocket endpoint, including your Bitquery Token. - `options`: Configuration for the WebSocket connection, such as reconnection delays and retry limits. - **Step 3: Use the `useWebSocket` Hook** ```javascript const { data, error, isConnected } = useWebSocket(url, options, query); ``` - The hook is called with the `url`, `options`, and `query`, and returns the current connection status, any errors, and the received data. - **Step 4: Render the Component** ```javascript return (

Bitquery WebSocket

Status: {isConnected ? "Connected" : "Disconnected"}

{error &&

Error: {error}

} {data ? (
Protocol Family {data.Solana.DEXTrades[0].Trade.Dex.ProtocolFamily}
Protocol Name {data.Solana.DEXTrades[0].Trade.Dex.ProtocolName}
Buy Amount {data.Solana.DEXTrades[0].Trade.Buy.Amount}
Buy Currency {data.Solana.DEXTrades[0].Trade.Buy.Currency.Symbol}
Sell Amount {data.Solana.DEXTrades[0].Trade.Sell.Amount}
Sell Currency {data.Solana.DEXTrades[0].Trade.Sell.Currency.Symbol}
Transaction Signature {data.Solana.DEXTrades[0].Transaction.Signature}
) : (

Loading data...

)}
); ``` - The component renders the connection status, any errors, and the data in a table format if available. - If the data is not yet available, it displays a "Loading data..." message. --- ## How to Trace Bitcoin Funds Across 10 Levels URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/trace-bitcoin-across-10-levels/ Video tutorial: build a deep Bitcoin trace of ten hops in MoneyFlow Lite and keep the chart readable with the threshold and entity split options. # How to Trace Bitcoin Funds Across 10 Levels This video builds a ten-level trace one hop at a time and shows how the **Threshold** slider and **Depth-based Entity Split** keep a deep chart readable. Read [How to read the MoneyFlow chart](/docs/moneyflow-lite/how-to-read-the-moneyflow-chart) for those options. --- ## How to Track Ethereum Price in USD with Google Sheets URL: https://docs.bitquery.io/docs/usecases/real-time-historical-ethereum-price-excel-google-sheets/ Build How to Track Ethereum Price in USD with Google Sheets: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # How to Track Ethereum Price in USD with Google Sheets Below is a step-by-step tutorial on how to use Bitquery APIs to get token price information into a Google Sheets spreadsheet using Python. In this we code will authenticate with Google Sheets, create a new spreadsheet, fetch data from Bitquery, and then populate the spreadsheet with that data. Adjust the query and data fields according to your specific requirements. ### Prerequisites: - Google Developers account. - Bitquery API access token. - Python installed on your system. - Libraries: `gspread`, `oauth2client`, and `requests`. ### Step 1: Set up your Google Cloud project and service account 1. **Create a Google Cloud Project**: Go to https://console.cloud.google.com/ and create a new project. 2. **Enable the Google Sheets API**: In the API & Services section, enable the Google Sheets API and Google Drive API. 3. **Create a Service Account**: Create a new service account in the IAM & Admin section. 4. **Create and download a JSON key**: Generate a new JSON key for the service account and download it. Save this file as `google_sheets.json`. You will be able to download the JSON file on cloud console as shown Below ![Google Cloud Console API setup](/img/ApplicationExamples/google_cloud_console.png) ### Step 1: Install Required Libraries First, you need to install the necessary Python libraries if you haven't already: ```bash pip install gspread oauth2client requests ``` ### Step 2: Authenticate and Set Up Google Sheets Create a Python function to authenticate and set up Google Sheets: ```python from oauth2client.service_account import ServiceAccountCredentials def authenticate_gsheets(): # Define the scope of the application scope = [ "https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive" ] # Authenticate using the service account JSON key file creds = ServiceAccountCredentials.from_json_keyfile_name('google_sheets.json', scope) client = gspread.authorize(creds) # Create a new spreadsheet spreadsheet = client.create("test_bitquery_DEXTrades") worksheet = spreadsheet.sheet1 # Share the spreadsheet with your email spreadsheet.share('your-email@example.com', perm_type='user', role='writer') print(f"Spreadsheet URL: {spreadsheet.url}") return worksheet ``` ### Step 3: Fetch USD Price Data from Bitquery DEX Trades API Set up a function to fetch data from the Bitquery API using OAuth. In this query we fetch latest DEX Trades along with USD Price information. ```python def fetch_bitquery_data(): url = "https://streaming.bitquery.io/graphql" headers = { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN', 'Content-Type': 'application/json' } # GraphQL query query = """ { EVM(dataset: archive, network: eth) { DEXTrades(limit: {count: 10}, orderBy: {descending: Block_Time}) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } Sell { Amount Buyer Currency { Name SmartContract Symbol } Seller Price } Dex { ProtocolFamily ProtocolName SmartContract Pair { SmartContract } } } } } } """ response = requests.post(url, json={'query': query}, headers=headers) if response.status_code == 200: return json.loads(response.text) else: raise Exception(f"Query failed and return code is {response.status_code}. {response.text}") ``` ### Step 4: Write Data to Google Sheets Create a function to update the Google Sheet with the fetched data: ```python def update_sheet(worksheet, data): headers = [ "Block Time", "Transaction Hash", "Buy Price", "Buy Amount", "Buy Currency Symbol", "Sell Amount", "Sell Currency Symbol", "Dex Protocol Name" ] worksheet.update(['A1:H1'], [headers]) trades = data['data']['EVM']['DEXTrades'] for i, trade in enumerate(trades, start=2): values = [ trade['Block']['Time'], trade['Transaction']['Hash'], # Additional fields from your data ] worksheet.update(f'A{i}:H{i}', [values]) ``` ### Step 5: Run the Main Function Finally, set up your main function to orchestrate the flow: ```python def main(): worksheet = authenticate_gsheets() data = fetch_bitquery_data() update_sheet(worksheet, data) if __name__ == "__main__": main() ``` ### Final Output --- ## How to Use Bitquery API Token - Authorization Examples URL: https://docs.bitquery.io/docs/authorization/how-to-use/ How to Use Bitquery API Token - Authorization Examples in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # How to Use a Token Regardless of how you obtain your token, whether generated directly in the IDE or using a client ID-secret combination, the process for using the token remains consistent. - You mention the token in the headers like this `'Authorization': f'Bearer {access_token}'` OR - You attach the token in the URL `https://streaming.bitquery.io/graphql?token=ory_at_...` For the `wss` endpoint, the 2nd method is the only way, read more [here](/docs/authorization/websocket/) Below is an example in Python that mentions the token in the header. ```javascript def oAuth_example(): //access_token generated using either of the two approaches # Step 2: Make Streaming API query url_graphql = "https://streaming.bitquery.io/graphql" headers_graphql = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {access_token}' } graphql_query = ''' { EVM(mempool: true, network: eth) { DEXTrades(limit: {count: 10}) { Transaction { Hash } Trade { Buy { Amount Currency { Name } Buyer } Sell { Amount Currency { Name } Buyer } } } } } ''' payload_graphql = json.dumps({'query': graphql_query}) # Step 3: Make request to Streaming API response_graphql = requests.post(url_graphql, headers=headers_graphql, data=payload_graphql) # Print the response print(response_graphql.text) oAuth_example() ``` Remember to replace `{access_token}` with your actual access token. --- ## How to build a Crypto Price Change Signal Bot on Telegram URL: https://docs.bitquery.io/docs/usecases/price-change-signal-bot/ Build How to build a Crypto Price Change Signal Bot on Telegram: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application. # How to build a Crypto Price Change Signal Bot on Telegram This bot fetches real-time trading data from Bitquery and sends alerts on significant token price changes. For pre-aggregated price data with OHLC, consider using our [Crypto Price API](/docs/trading/crypto-price-api/). The bot is built using the `python-telegram-bot` library to handle interactions with Telegram users and `aiohttp` for making asynchronous API requests. Github Repository Link is available [here](https://github.com/bitquery/Price-Change-Signal-Telegram-Bot/tree/main) ## Tutorial Video ## Components 1. **Libraries and Dependencies** - `re`, `asyncio`, `json`, `logging`, `aiohttp`, `os`: For general utilities, asynchronous handling, JSON parsing, and logging. - Telegram Libraries (`telegram`, `ApplicationBuilder`, etc.): For Telegram bot interaction. - `datetime`: For time manipulation in API requests. 2. **Configuration and Constants** - `BOT_TOKEN`: The Telegram bot token from the BotFather. Get it from [here](https://telegram.me/BotFather) - `OAUTH_TOKEN`: The authorization token for the Bitquery API. Check out the steps on how to get it [here](/docs/authorization/how-to-generate/) - `logging.basicConfig`: Configures logging to track bot operations and potential errors. 3. **Helper Functions** - `split_text(text, max_length)` - **Purpose**: Splits long messages into smaller chunks to avoid Telegram's message length limit (4096 characters). - **Parameters**: - `text (str)`: Message to be split. - `max_length (int)`: Character limit. - **Returns**: List of text parts. - `send_long_message(update, context, long_message, max_message_length=4000)` - **Purpose**: Sends long messages in parts to avoid Telegram’s message length limit. - **Parameters**: - `update`, `context` (Telegram update and context). - `long_message (str)`: Message content. - `max_message_length` (default=4000). - **Operation**: Handles `RetryAfter` exceptions if Telegram’s flood control limit is reached, retrying after a delay. 4. **Core Functions** - `send_query_and_process(update, context)` - **Purpose**: Sends GraphQL query to Bitquery API, retrieves data, processes, and sends alerts. - **Operation**: - Creates a query with specified variables. - Sends a POST request to Bitquery. - Processes the response to calculate price changes over different timeframes (5 minutes and 1 hour). - Sorts and formats the data, then sends it to Telegram using `send_long_message`. - `calculate_percentage_change(start_price, end_price)` - **Purpose**: Calculates and formats the percentage change between two prices. - **Parameters**: - `start_price`, `end_price (float)`: Starting and ending prices. - **Returns**: Formatted string showing percentage change with symbols (📈 or 📉). - `format_message(data)` - **Purpose**: Formats the retrieved data for user-friendly display in Telegram. - **Parameters**: - `data (dict)`: JSON data from Bitquery API. - **Operation**: - Iterates over the trading data items. - Formats each data point with trade and volume information, using fallback values if data is missing. - Adds a "Trade Now" link for easy access to trading. 5. **Global Flag** - `is_task_running`: A global flag to prevent multiple instances of `send_query_and_process` from running concurrently, which could lead to excessive API calls or repeated messages. 6. **Command Handlers** - `start_regular_requests(update, context)` - **Purpose**: Starts a recurring task to fetch data every 30 minutes. - **Operation**: - Checks if a task is already running (using `is_task_running`). - Sets up a loop to call `send_query_and_process` every 30 minutes. - `start(update, context)` - **Purpose**: Command handler for `/start`. Triggers `start_regular_requests` to begin data polling. - **Usage**: Users send `/start` to the bot to start receiving regular updates. 7. **Main Execution Block** - **Purpose**: Initializes the Telegram bot using `ApplicationBuilder` and starts polling for incoming `/start` commands. ## How to Run 1. **Clone the Repository** ```bash git clone https://github.com/bitquery/Price-Change-Signal-Telegram-Bot.git ``` 2. **Set up virtual environment** ```bash python3 -m venv venv source venv/bin/activate # For Windows: venv\Scripts\activate ``` 3. **Install Dependencies** ```bash pip install -r requirements.txt ``` 4. **Run the bot** ```bash python bot.py ``` That's it for this tutorial. Happy coding, happy trading! --- ## Hyperliquid API Docs — Real-time Trades, Orders, Liquidations & Prices URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/ Query and stream Hyperliquid data with Bitquery: trades, orders, order book updates, OHLCV candles, liquidations, funding, positions, TWAPs, mark prices, signed actions, prediction markets and account state snapshots over GraphQL and WebSocket. # Hyperliquid API These are the Bitquery **Hyperliquid API docs**: how to query and stream trades, orders, the order book, candles, liquidations, funding and positions for every trader on the exchange, and how to read the full state of every account from snapshots. Bitquery indexes **Hyperliquid core** (the L1 order-book exchange) and exposes it through the `Hyperliquid` cube on the [streaming API](https://streaming.bitquery.io/graphql). Every event dataset is available both as a **GraphQL query** and as a **WebSocket subscription** (real-time stream) — change `query` to `subscription` and drop `limit`/`orderBy`. The state cubes — `CurrentPositions`, `MarkPrices` and the eleven `Snapshot*` cubes — are query-only. ## Video Tutorials :::info How far back the API goes The `Hyperliquid` cubes serve a **rolling window**: about **30 days** for `Trades`, `Candles`, `PerpLiquidations`, `PerpFundings`, `Twaps`, `PriceUpdates` and `TraderLeverageUpdates`, and about **7 days** for the densest feeds — `Orders`, `BookUpdates` and `SignedActions` — and for the `Snapshot*` cubes (a new snapshot about every 12.5 minutes). That covers live streaming and recent history, which is what most bots, dashboards and monitoring need. See [Data Coverage & Retention](/docs/graphql/data-coverage-retention/#hyperliquid) for the per-cube table. A query without a `Block: {Time: ...}` filter covers a shorter default window: the last 30 minutes on `Orders` and `BookUpdates`, the last 24 hours on `Trades` and `PriceUpdates`. For data older than the window, use [Parquet exports from the Bitquery Data Store](https://bitquery.io/datastore) (details on the [Hyperliquid export page](/docs/cloud/hyperliquid/)). Older ranges are available on request from [sales@bitquery.io](mailto:sales@bitquery.io). ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Available datasets ```graphql query { Hyperliquid { BookUpdates # order book deltas (new / change / remove) Candles # OHLCV candles per market and interval CurrentPositions # open position per trader and market (query only) MarkPrices # latest mark price per HIP-3 market (query only) Orders # order lifecycle: open, filled, canceled, triggered, rejected PerpFundings # per-trader funding payments PerpLiquidations # perp liquidations PriceUpdates # HIP-3 oracle and mark price updates SignedActions # signed L1 actions: rejects and non-order actions TraderLeverageUpdates # leverage / margin-mode changes Trades # fills with direction, fees, leverage, PnL, position size after Twaps # TWAP order lifecycle Snapshots # snapshots: height and time (query only) SnapshotMarkets # every market: prices, best bid / ask, open interest SnapshotPositions # every open perp position: entry, margin, unrealized PnL SnapshotAccounts # every account per perp dex: account value, margin SnapshotOrders # order book with owners and waiting trigger orders SnapshotBalances # every non-zero spot balance SnapshotLeverageSettings # leverage setting per account and market SnapshotVaults # every vault: equity, followers, terms SnapshotVaultFollowers # every vault depositor SnapshotEarnReserves # Earn pool per token: supplied, borrowed, rates SnapshotEarnPositions # Earn supply and borrow per account } } ``` | Page | Cubes covered | | --- | --- | | [Trades & Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) | `Trades`, `Candles` | | [Orders, Order Book & TWAPs](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) | `Orders`, `BookUpdates`, `Twaps` | | [Mark Prices & Price Updates](/docs/perpetuals/hyperliquid/hyperliquid-prices-api) | `MarkPrices`, `PriceUpdates` | | [Liquidations, Funding, Positions & Leverage](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api) | `PerpLiquidations`, `PerpFundings`, `CurrentPositions`, `TraderLeverageUpdates` | | [Signed Actions](/docs/perpetuals/hyperliquid/hyperliquid-signed-actions-api) | `SignedActions` | | [Snapshots](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api) | `Snapshots`, `SnapshotMarkets`, `SnapshotPositions`, `SnapshotAccounts`, `SnapshotOrders`, `SnapshotBalances`, `SnapshotLeverageSettings`, `SnapshotVaults`, `SnapshotVaultFollowers`, `SnapshotEarnReserves`, `SnapshotEarnPositions` | | Guide | What it covers | | --- | --- | | [Track Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet) | Market-maker tracking, cancel-to-fill ratios, wallet-level order lifecycles using L3 data | | [Funding Payments by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api) | Every funding payment a wallet paid or received, per-market totals, date ranges | | [Liquidation History by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-liquidation-history-by-wallet) | Every liquidation of one address, backstop liquidations, live alerts | | [Vaults API](/docs/perpetuals/hyperliquid/hyperliquid-vaults-api) | Vaults ranked by volume and PnL, vault fills, HLP deposits and withdrawals, vault liquidations | | [TWAP Orders & Child Fills](/docs/perpetuals/hyperliquid/hyperliquid-twap-fills) | Join a TWAP order to every child fill it produced | | [HIP-3 Stocks API](/docs/perpetuals/hyperliquid/hip3-stocks-api) | S&P 500, US stock and commodity perps deployed through HIP-3 | | [Prediction Markets API](/docs/perpetuals/hyperliquid/hyperliquid-prediction-markets-api) | HIP-4 outcome markets: names and answers, odds, top markets by volume, holders of each side | | [Track ZEC on Hyperliquid](/docs/perpetuals/hyperliquid/track-zec-on-hyperliquid) | Positions, liquidations, funding and whale trades for one market | | [Bitquery vs Hyperliquid's free data](/docs/perpetuals/hyperliquid/vs-hyperliquid-api) | What the native Info API and `s3://hyperliquid-archive` do and don't cover | ## Hyperliquid Info API vs Bitquery The [native Hyperliquid API](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket/subscriptions) is built for trading your own account. Bitquery is built for seeing the whole market: | Capability | Hyperliquid native WS | Bitquery | | --- | --- | --- | | Scope of user data (orders, fills, funding, TWAPs, positions) | Any single address you already know, one subscription each, at most 10 users per IP — no market-wide stream of orders, funding, TWAPs or positions | Every trader on the exchange in one stream, or filter to any list of addresses | | Order book | `l2Book`, aggregated (L2), 5–20 levels max | **L3 (market-by-order)** deltas, unlimited depth, order id + trader address on every order | | Liquidations | Per-address only, via `userEvents` — no exchange-wide feed | All liquidations exchange-wide, with liquidated user, method, mark price, leverage | | Open positions | Per-address snapshot (`clearinghouseState`) — cannot enumerate or rank the market | Whole market queryable (`CurrentPositions`): every open position, sortable and filterable; `SnapshotPositions` adds entry price, margin and unrealized PnL every ~12.5 minutes, with 7 days of history | | Account state | Margin, spot balances and open orders per address (`clearinghouseState`, `spotClearinghouseState`, `openOrders`), current only | Every account at once from snapshots: margin per dex, spot balances, resting and trigger orders with owners, vaults and their depositors, Earn | | Historical data | Live + snapshot only; separate REST with pagination limits. The public `s3://hyperliquid-archive` bucket holds **L2 book snapshots and asset contexts**, updated roughly monthly with no completeness guarantee; raw node fills and events sit in the requester-pays `s3://hl-mainnet-node-data` bucket; no candles | Same GraphQL query for history and live stream over a rolling window (~30 days; ~7 days for orders, book updates and signed actions). Older history is available as Parquet exports from the Data Store | | Filtering | Per-coin or per-user only | Any field: market, trader, side, size, leverage, status | | Fill context | Rich (PnL, direction) only on per-user feeds; the public `trades` feed carries price, size, side and the two addresses, without direction, fees or PnL | Direction, fees, leverage, position size before and after, realized PnL and execution order on every fill, market-wide | | Raw L1 actions | Not exposed | `SignedActions`: action type, signer vs user (agent wallets), bundle, broadcaster | | Delivery | WebSocket only; reconnect/gap handling yours; some feeds base64+DEFLATE encoded | GraphQL WS + Kafka (protobuf, offsets, consumer groups, no gaps), plus Parquet exports (download from S3 or R2, or custom delivery to your bucket or warehouse) | | Subscription model | One subscription per coin / per user, per-connection limits | One stream can carry everything unfiltered, or a list of values on any filter field (many markets or wallets in one stream); runs 1,000+ concurrent streams at scale | | Rate limits and keys | Per-IP weight limits on the REST Info API, per-connection subscription caps on WS; one API wallet per account | Limits are per plan, not per IP; one Bitquery key covers every market and wallet | | Latency at market scale | Fast for a single coin/user feed, but covering the whole market means hundreds of subscriptions, client-side merging and rate limits | Lowest latency for the entire market in one pipeline — Kafka delivers every event exchange-wide, keyed by block, with no fan-out to assemble | ## Markets: perp, spot and HIP-3 Every cube carries a `Market` object that identifies the instrument: | Field | Meaning | Example values | | --- | --- | --- | | `Symbol` | Human-readable market symbol; not unique — the same ticker can be a native perp and several HIP-3 markets | `BTC`, `HYPE/USDC`, `AAPL` | | `CoinRaw` | Raw Hyperliquid coin id, unique per market: a plain name for native perps, `@` for spot, `#` for outcome markets, and HIP-3 markets prefixed with their deployer namespace | `BTC`, `@107`, `#108130`, `xyz:SMSN`, `mkts:AAPL` | | `Kind` | Market class | `perp`, `hip3`, `spot`, `outcome` | | `IsPerp` | `true` for perpetual markets (native and HIP-3) | `true` / `false` | | `Protocol` | HIP-3 deployer namespace; `hypercore` for native markets | `xyz`, `mkts`, `hypercore` | | `MaxLeverage` | Maximum leverage allowed on the market; set on native perps, `0` elsewhere | `40` | | `Outcome` | Prediction markets only: `Headline` (the market), `Title` (the answer), `SideTitle` (the side), `Question { ... }` | `BTC above 78521 at 2026-10-31 06:00 UTC?`, `Yes` | **HIP-3** markets are builder-deployed perps — tokenized stocks (`mkts:AAPL`), indices (`xyz:KR200`, `para:TOTAL2`) and other synthetic assets trade alongside native Hyperliquid perps and appear in the same cubes with `Kind: hip3`. See the [HIP-3 Stocks API](/docs/perpetuals/hyperliquid/hip3-stocks-api) for queries. **Outcome** markets (`Kind: outcome`) are HIP-4 prediction markets priced between 0 and 1, named under `Market { Outcome { ... } }`; see the [Prediction Markets API](/docs/perpetuals/hyperliquid/hyperliquid-prediction-markets-api). Filter on `CoinRaw` when you mean one market. The spot pair `PURR/USDC` is filed with `Kind: perp` and `IsPerp: true` because its id is a plain name; it is a spot market. `ChainId` is `hyperliquid-core` on all event cubes. ## Common fields - `Block { Number Time }` — Hyperliquid L1 block height and timestamp; filter with `Block: {Time: {since_relative: {minutes_ago: 5}}}` or absolute `since`/`till`. - Order inside a block — every event of a block shares `Block.Time`, so sort by `Index` within it: `Trade.Execution.Index` and `Liquidation.Execution.Index` give the execution order (one sequence across the trades and liquidations of a block, from 1), `Order.Index` the order of status updates, `BookUpdate.Index` the order of book deltas. For example `orderBy: {descending: [Block_Time, Trade_Execution_Index]}`. `Execution.Tid` is a fill identifier (shared by the maker and taker rows of one fill), not a sequence. Fills and order updates written before about 09:40 UTC on 2026-10-13 have `Index` 0. - `Trader { Address Vault Signer Broadcaster SignedAt }` — the account behind an event. `Vault` is set when the action is performed on behalf of a vault; `Signer` is the signing key (may be an agent/API wallet distinct from `Address`). - Numeric amounts (price, size, PnL, fees) are returned as **strings** at native precision; candle OHLCV values are floats. ## WebSocket streams Any event query becomes a live stream over `wss://streaming.bitquery.io/graphql` (transport `graphql-transport-ws`): ```graphql subscription { Hyperliquid { Trades { Block { Time } Trade { Market { Symbol } Execution { Price Size Side Direction } } } } } ``` See [WebSocket subscriptions](/docs/subscriptions/websockets/) for connection details. ## Kafka streams (protobuf) For the lowest latency, the same data is available as Kafka streams: | Topic | Protobuf schema | | --- | --- | | `hyperliquid.candles.proto` | `CandlesBlockMessage` in [hyperliquid/candles.proto](https://github.com/bitquery/streaming_protobuf/blob/main/hyperliquid/candles.proto) | | `hyperliquidcore.messages.proto` | `HyperliquidCoreBlockMessage` in [hyperliquid/hyperliquid_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/hyperliquid/hyperliquid_block_message.proto) | A block can arrive as several `hyperliquidcore.messages.proto` messages (for example fills and order statuses separately); each carries `BlockNumber` and `BlockTime`. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts) for access and consumer setup. ## Historical data (Parquet exports) For backtesting and research — trades with realized PnL, liquidations, L4 order book updates, the full order lifecycle, oracle prices and hourly funding — Bitquery delivers the same data as [Parquet exports from the Bitquery Data Store](https://bitquery.io/datastore) ([technical details](/docs/cloud/hyperliquid/)) for S3, Snowflake, BigQuery, Athena, or DuckDB. The Parquet files and the live streams share field definitions, so backtest and production code decode identically. --- ## Hyperliquid Funding Payments API URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api/ Export every funding payment a Hyperliquid wallet paid or received: signed amount, funding rate, position size and market, per hourly funding tick, over GraphQL and WebSocket. # Hyperliquid Funding Payments API **In short:** Hyperliquid pays funding every hour. Each payment is `position size × oracle price × funding rate`, and the hourly rate is one eighth of the computed 8-hour rate. With Bitquery, the `PerpFundings` cube returns every payment a wallet paid or received, with the signed amount, the rate applied and the position size. Every hour, Hyperliquid settles funding between longs and shorts. Each settlement is a **transfer against a specific wallet**, not a market statistic — and it is one of the event types that goes missing most often when people export their history for accounting. This page covers the `PerpFundings` cube: the funding history of any address over the data window (about the last 30 days). The video ranks Hyperliquid markets by funding paid and by funding rate over one week. :::info Funding payments vs funding rates A **funding rate** is a market-level number traders use to size a position. A **funding payment** is what actually left or entered one wallet's account. This page is about payments. For the rate applied at each tick, read `Funding.Rate` on the same records. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Funding payments of one wallet `Amount` is signed: **negative means the trader paid funding**, positive means they received it. `Rate` is the funding rate applied at that tick and `Size` the position size it applied to. Run it in the IDE: [Hyperliquid Wallet Funding Payments ➤](https://ide.bitquery.io/hyperliquid-wallet-funding-payments) ```graphql query { Hyperliquid { PerpFundings( limit: {count: 100} orderBy: {descending: Block_Time} where: {Funding: {Trader: {Address: {is: "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2"}}}, Block: {Time: {since_relative: {days_ago: 3}}}} ) { Block { Time } Funding { Market { Symbol Kind } Amount Rate Size Trader { Address } } } } } ``` Sample response: ```json { "Block": { "Time": "2026-10-13T11:00:00.048588Z" }, "Funding": { "Market": { "Symbol": "XYZ100", "Kind": "hip3" }, "Amount": "-10.128628", "Rate": "0.00000625", "Size": "53.1425", "Trader": { "Address": "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2" } } } ``` ## Total funding paid and received per market Rather than paging every tick, aggregate them. This gives one row per market with the net funding and the number of ticks. `CoinRaw` is selected because HIP-3 tickers are not unique across deployers: `xyz:SNDK` and `io:SNDK` share the `Symbol` `SNDK`. Run it in the IDE: [Hyperliquid Funding Totals By Market ➤](https://ide.bitquery.io/hyperliquid-funding-totals-by-market) ```graphql query { Hyperliquid { PerpFundings( where: {Funding: {Trader: {Address: {is: "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2"}}}, Block: {Time: {since_relative: {days_ago: 3}}}} ) { Funding { Market { Symbol CoinRaw } } ticks: count net: sum(of: Funding_Amount) } } } ``` `net` is the signed total: a negative number is net funding **paid** over the whole period. ## Funding paid only Split the two directions by filtering on the sign of `Amount`. Use `lt: "0"` for funding paid, `gt: "0"` for funding received. Run it in the IDE: [Hyperliquid Funding Paid Only ➤](https://ide.bitquery.io/hyperliquid-funding-paid-only) ```graphql query { Hyperliquid { PerpFundings( where: { Funding: { Trader: {Address: {is: "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2"}} Amount: {lt: "0"} } Block: {Time: {since_relative: {days_ago: 3}}} } ) { Funding { Market { Symbol CoinRaw } } ticks: count paid: sum(of: Funding_Amount) } } } ``` ## Funding over a date range Add a `Block: {Time: ...}` filter to bound the export to a day, a week or any window inside the data Bitquery holds — about the last 30 days. A range older than that returns nothing; for longer history, see [Data Coverage & Retention](/docs/graphql/data-coverage-retention/). For older data, ask about a [Data Store export](https://bitquery.io/datastore). Run it in the IDE: [Hyperliquid Funding By Date Range ➤](https://ide.bitquery.io/hyperliquid-funding-by-date-range) ```graphql query { Hyperliquid { PerpFundings( limit: {count: 100} orderBy: {ascending: Block_Time} where: { Funding: {Trader: {Address: {is: "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2"}}} Block: {Time: {since: "2026-10-01T00:00:00Z", till: "2026-10-08T00:00:00Z"}} } ) { Block { Time } Funding { Market { Symbol } Amount Rate Size } } } } ``` ## Real-time funding stream Change `query` to `subscription` and drop `limit` and `orderBy` to receive each funding settlement as it happens. Run it in the IDE: [Hyperliquid Funding Payments Stream ➤](https://ide.bitquery.io/hyperliquid-funding-payments-stream) ```graphql subscription { Hyperliquid { PerpFundings( where: {Funding: {Trader: {Address: {is: "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2"}}}} ) { Block { Time } Funding { Market { Symbol } Amount Rate Size Trader { Address } } } } } ``` Drop the `where` clause entirely to stream funding for every trader on the exchange. ## Build on this Funding settles every hour, so a funding question is rarely answered once. The patterns that keep this cube open: - **Funding-arb and carry monitors.** Stream exchange-wide `PerpFundings` and aggregate `Rate` per market to see which perps are paying longs or shorts right now, then compare with spot on the same key — Bitquery's [Trading cube](/docs/trading/trading-data-overview) carries Solana, Ethereum, Base and BNB DEX prices in the same API. - **Position cost dashboards.** Pair this stream with the [Trades API](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) and periodic [`CurrentPositions`](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api#current-positions) queries (a state cube, not a stream) to show live PnL net of funding for any wallet or vault, not just your own. - **Watch a list of wallets.** Replace `is` with `in: ["0x…", "0x…"]` to follow several traders — copy-trading, vault monitoring, or a desk's own accounts — in one stream. - **Production delivery.** The same events arrive over [Kafka](/docs/streams/kafka-streaming-concepts) as protobuf for the lowest latency. ## Notes - Funding settles hourly. A wallet holding several perp positions produces one record per market per tick, so a busy account accumulates thousands of rows per month. - A market whose funding rate is zero in an hour is not charged that hour, so an open position on it has no record for that tick — a gap in the hourly series is not always missing data. - API history goes back about 30 days. For older data, ask about a [Data Store export](https://bitquery.io/datastore). - `Market.Kind` distinguishes native perps from HIP-3 builder markets — see the [HIP-3 stocks API](/docs/perpetuals/hyperliquid/hip3-stocks-api). - To pair funding with the fills that opened and closed the position, use the [Trades API](/docs/perpetuals/hyperliquid/hyperliquid-trades-api); for the currently open positions and their funding summed since the data window started, use `CurrentPositions` on the [perpetuals page](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api#current-positions). --- ## Hyperliquid HIP-3 Stocks API — S&P 500, US Equity & Commodity Perps URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hip3-stocks-api/ Query and stream Hyperliquid HIP-3 markets with Bitquery: S&P 500, NVDA, TSLA and other US stock perpetuals, plus gold, oil and FX. Trades, mark prices, oracle inputs, L4 order book, candles, funding and liquidations over GraphQL and WebSocket. # Hyperliquid HIP-3 Stocks API HIP-3 lets anyone deploy a perpetual market on Hyperliquid. In practice that has produced a full off-chain asset complex trading on-chain: **S&P 500, Nasdaq-100, individual US equities, country ETFs, gold, oil, natural gas and FX** — all as perps settled in USDC on HyperCore. Bitquery indexes every HIP-3 market alongside the native perps, in the same `Hyperliquid` cube. This page covers how to address those markets, and the queries that matter for pricing, market making and basis trading against the underlying. The video ranks the HIP-3 stock, index and commodity perps by volume and by number of traders over one week. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## How HIP-3 markets are addressed Every market carries a `Market` object. Three fields identify a HIP-3 market: | Field | Native perp | HIP-3 market | | --- | --- | --- | | `Kind` | `perp` | `hip3` | | `Protocol` | `hypercore` | the deployer, e.g. `xyz`, `io`, `para`, `mkts`, `hyna` | | `CoinRaw` | `BTC` | `xyz:SP500` — `deployer:symbol` | | `Symbol` | `BTC` | `SP500` — the bare symbol | Two consequences worth knowing before you write a filter: - **`Symbol` is not unique across deployers.** `SNDK` trades under both `xyz:` and `io:`, `AVGO` under both `xyz:` and `para:`, `UNITREE` under `xyz:` and `para:`. Filter on `CoinRaw` when you mean one specific market, and on `Symbol` only when you deliberately want every deployer's version of the same underlying. - **Filter the whole asset class with `Kind`,** not with a `Protocol` allowlist. New deployers appear without notice; `Kind: {is: "hip3"}` keeps working. ## List every HIP-3 market Ranks all HIP-3 markets by USD volume over the last 24 hours, with trade and distinct trader counts. Every match has a maker row and a taker row, so volume and trades count the taker side only. This is the discovery query — run it first to see what exists right now. Run it in the IDE: [Hyperliquid HIP-3 Markets ➤](https://ide.bitquery.io/hyperliquid-hip3-markets) ```graphql query { Hyperliquid { Trades( limit: {count: 300} orderBy: {descendingByField: "volumeUsd"} where: { Trade: {Market: {Kind: {is: "hip3"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Trade { Market { Symbol CoinRaw Protocol } } volumeUsd: sum(of: Trade_Execution_NotionalUSD, if: {Trade: {Execution: {IsAggressor: true}}}) trades: count(if: {Trade: {Execution: {IsAggressor: true}}}) traders: count(distinct: Trade_Trader_Address) } } } ``` Swap `Kind` for `Protocol: {is: "xyz"}` to scope to a single deployer. ## Trades on a stock market Every fill on `xyz:SP500`, both sides of each match. `IsAggressor` marks the taker, and a **negative `Fee` is a maker rebate**. `Execution.Index` is the fill's place in its block (all fills of a block share `Block.Time`), and `Position.Size` the account's position after the fill. Run it in the IDE: [Hyperliquid SP500 Perp Trades ➤](https://ide.bitquery.io/hyperliquid-sp500-trades) ```graphql query { Hyperliquid { Trades( limit: {count: 50} orderBy: {descending: [Block_Time, Trade_Execution_Index]} where: {Trade: {Market: {CoinRaw: {is: "xyz:SP500"}}}} ) { Block { Time } Trade { Market { Symbol CoinRaw Kind Protocol } Execution { Price Size Side Direction IsAggressor Index Oid Tid } Fees { Fee FeeToken BuilderFee } Position { Leverage IsCross SizeBefore Size RealizedPnl } Trader { Address } } } } } ``` Change `CoinRaw` to any market from the discovery query, such as `xyz:NVDA`, `xyz:TSLA`, `xyz:GOLD`, `io:NVDA`, `io:GPRO`. ## Mark prices across all HIP-3 markets `MarkPrices` is a **latest-state cube**: one row per market holding its current mark, not a time series. Use it for a pricing snapshot; use `Candles` or `Trades` for history. Run it in the IDE: [Hyperliquid HIP-3 Mark Prices ➤](https://ide.bitquery.io/hyperliquid-hip3-mark-prices) ```graphql query { Hyperliquid { MarkPrices( limit: {count: 200} orderBy: {descending: LastTime} where: {Market: {Kind: {is: "hip3"}}} ) { LastTime LastBlock Mark Market { Symbol CoinRaw Protocol } } } } ``` Note the field names differ from the other cubes: `LastTime` / `LastBlock` rather than `Block { Time }`, and the price is `Mark`. ## Basis: on-chain mark vs off-chain reference This is the query behind the HIP-3 arbitrage trade. `PriceUpdates` carries the oracle feed the market is priced against, and `Kind` separates the components: | `Kind` | Meaning | | --- | --- | | `spotInput` | the off-chain reference price for the underlying | | `markInput` | the input to the on-chain mark | | `mark` | the published mark price | | `oracle` | the published oracle price | | `extPerpInput` | external perp reference, where used | | `extPerp` | the published external perp price | Because `spotInput` is indexed alongside the mark, **the basis is computable from Bitquery alone** — you do not need to bring your own equities feed just to measure the spread. Run it in the IDE: [Hyperliquid HIP-3 Basis Spread ➤](https://ide.bitquery.io/hyperliquid-hip3-basis-spread) ```graphql query { Hyperliquid { PriceUpdates( limit: {count: 100} orderBy: {descending: Block_Time} where: {PriceUpdate: {Market: {CoinRaw: {is: "xyz:NVDA"}}}} ) { Block { Time } PriceUpdate { Market { Symbol CoinRaw } Kind Price DailyPx UpdateClass UpdateTime } } } } ``` Pair the `spotInput` series with `Trades` on the same market to see where fills landed relative to the reference, which is what decides whether a basis trade was actually capturable rather than just visible. ## OHLCV candles for a stock perp `Candles` are pre-aggregated. `Interval.Time.Duration` is in **seconds** — `60` for 1m, `300` for 5m, `900` for 15m, `3600` for 1h. Run it in the IDE: [Hyperliquid Stock Perp Candles ➤](https://ide.bitquery.io/hyperliquid-stock-perp-candles) ```graphql query { Hyperliquid { Candles( limit: {count: 60} orderBy: {descending: Interval_Time_Start} where: { Market: {CoinRaw: {is: "xyz:NVDA"}} Interval: {Time: {Duration: {eq: 60}}} } ) { Interval { Time { Start Duration } } Market { Symbol CoinRaw } Ohlc { Open High Low Close Volume } } } } ``` If you need an interval the `Candles` cube does not carry, aggregate `Trades` directly. Keep the taker side only, as `Candles` does, or every match counts twice in `volume`. `open` and `close` come from the first and last block of the interval; the fills of one block share `Block_Time`, so they can differ from the `Candles` values, which order fills by `Execution.Index`. Run it in the IDE: [Hyperliquid HIP-3 OHLC From Trades ➤](https://ide.bitquery.io/hyperliquid-hip3-ohlc-from-trades) ```graphql query { Hyperliquid { Trades( limit: {count: 100} orderBy: {descendingByField: "interval_Time"} where: { Trade: {Market: {CoinRaw: {is: "xyz:SP500"}}, Execution: {IsAggressor: true}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { interval: Block { Time(interval: {in: minutes, count: 30}) } open: Trade { Execution { Price(minimum: Block_Time) } } high: Trade { Execution { Price(maximum: Trade_Execution_Price) } } low: Trade { Execution { Price(minimum: Trade_Execution_Price) } } close: Trade { Execution { Price(maximum: Block_Time) } } volume: sum(of: Trade_Execution_Size) trades: count } } } ``` ## L4 order book for a stock perp `BookUpdates` are **per-order** deltas, not aggregated price levels. Each row names the order ID and the wallet behind it, so you can reconstruct the book at any instant and measure queue position, order lifetime and maker behaviour. Run it in the IDE: [Hyperliquid Stock Book Updates ➤](https://ide.bitquery.io/hyperliquid-stock-book-updates) ```graphql subscription { Hyperliquid { BookUpdates( where: {BookUpdate: {Market: {CoinRaw: {is: "xyz:NVDA"}}}} ) { Block { Time } BookUpdate { Market { Symbol CoinRaw } Kind Side Px Size SizeBefore Oid Trader { Address } } } } } ``` `Kind` is `new`, `update` or `remove`. **`Size` is empty on a `remove`** — the order is gone, so there is no resting size to report; use `Px`, `Side` and `Oid` to find the level it left. Change `subscription` to `query` and add `limit` / `orderBy` for history: without a `Block: {Time: ...}` filter the query covers the last 30 minutes, and about 7 days are kept. ## Funding on HIP-3 markets Funding is per trader, per market, and settles hourly. `Rate` is the funding rate applied and `Amount` the USDC paid or received. Run it in the IDE: [Hyperliquid HIP-3 Funding ➤](https://ide.bitquery.io/hyperliquid-hip3-funding) ```graphql query { Hyperliquid { PerpFundings( limit: {count: 50} orderBy: {descending: Block_Time} where: {Funding: {Market: {Kind: {is: "hip3"}}}, Block: {Time: {since_relative: {hours_ago: 2}}}} ) { Block { Time } Funding { Market { Symbol CoinRaw Protocol } Trader { Address } Rate Amount Size } } } } ``` Equity perps have no natural funding anchor overnight or at weekends, when the underlying market is closed. Funding is where that dislocation shows up, so this series is worth watching if you carry HIP-3 positions across a session boundary. ## Liquidations on HIP-3 markets Run it in the IDE: [Hyperliquid HIP-3 Liquidations ➤](https://ide.bitquery.io/hyperliquid-hip3-liquidations) ```graphql query { Hyperliquid { PerpLiquidations( limit: {count: 50} orderBy: {descending: [Block_Time, Liquidation_Execution_Index]} where: {Liquidation: {Market: {Kind: {is: "hip3"}}}} ) { Block { Time } Liquidation { Market { Symbol CoinRaw Protocol } LiquidatedUser Liquidator MarkPx Method Trader { Address } Execution { Price Size Side Index } Position { Leverage SizeBefore Size RealizedPnl } } } } } ``` `Method` distinguishes a `market` liquidation from a `backstop` one. Both sides of a forced fill are listed with the same `LiquidatedUser`: the row whose `Trader.Address` equals it is the liquidated account's own fill, the others are the accounts that took the other side. Sign a fill by `Execution.Side` (`Buy` adds, `Sell` subtracts). ## Top traders on a stock market Ranks wallets by traded size on one market, with realized PnL. Useful for copy-trading, market-maker identification and flow analysis. Run it in the IDE: [Hyperliquid HIP-3 Top Traders ➤](https://ide.bitquery.io/hyperliquid-hip3-top-traders) ```graphql query { Hyperliquid { Trades( limit: {count: 50} orderBy: {descendingByField: "volume"} where: { Trade: {Market: {CoinRaw: {is: "xyz:SP500"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Trade { Trader { Address } } volume: sum(of: Trade_Execution_Size) trades: count pnl: sum(of: Trade_Position_RealizedPnl) } } } ``` ## Field notes - **Prices and sizes are decimal strings**, not floats, in every cube except `Candles` (whose `Ohlc` fields are floats). Parse with `Decimal` where precision matters. - **A match produces two `Trades` rows**, one per counterparty. Key a trade on `(Block.Number, Market.CoinRaw, Execution.Tid)` — not on `Hash`, which spans many matches and is all zeroes on both sides of a TWAP fill. `Tid` is a hash, not a sequence: to order the fills of a block, use `Execution.Index` (`orderBy: {descending: [Block_Time, Trade_Execution_Index]}`). - **`Position.SizeBefore` and `Position.Size` are signed position sizes** before and after the fill, negative for short. They are not money; realized PnL is `Position.RealizedPnl`. - **`Direction`** takes values like `Open Long`, `Close Short` and `Short > Long` — a flip through flat is one fill, not two. - **Retention.** These cubes are served from realtime with roughly a 30-day window (about 7 days for `Orders`, `BookUpdates` and `SignedActions`). For longer ranges, see [Data Coverage & Retention](/docs/graphql/data-coverage-retention/). For older data, ask about a [Data Store export](https://bitquery.io/datastore). ## Tokenized stocks on other platforms HIP-3 stock markets are perpetual futures. To track the stock tokens themselves: - [xStocks API](/docs/blockchain/Solana/xstocks-api/): Backed's stock tokens on Solana, such as `TSLAx` and `AAPLx`. They trade in DEX pools and through RFQ quotes. - [Ondo Tokenized Stocks API](/docs/blockchain/robinhood/ondo-stocks-api/): Ondo's stock tokens on Robinhood Chain, such as `NVDAon` and `AAPLon`. - [Solana RFQ API](/docs/blockchain/Solana/solana-rfq-api/#tokenized-equities-on-rfq): Ondo's stock tokens on Solana. They see few trades, most of them through RFQ quotes. ## Related - [Hyperliquid API overview](/docs/perpetuals/hyperliquid) - [Trades & Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) - [Orders, Order Book & TWAPs](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) - [Mark Prices & Price Updates](/docs/perpetuals/hyperliquid/hyperliquid-prices-api) - [Liquidations, Funding, Positions & Leverage](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api) --- ## Hyperliquid Historical Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/hyperliquid/ Hyperliquid (HyperCore) Parquet exports from the Bitquery Data Store: trades from both sides, liquidations, L4 order book updates, the full order lifecycle, oracle prices and hourly funding. Older history is available on request. # Hyperliquid (HyperCore) Data Bitquery provides **Hyperliquid Core Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), designed for backtesting, market microstructure research, and data lake integrations. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, etc**. This dataset covers **HyperCore**, the L1 order-book exchange, not HyperEVM state. It is an **event stream, not a state chain**: there are no blocks, transactions or transfers tables. Every row is an exchange event (a fill, an order status change, a book delta, an oracle price, a funding payment), and every row carries `Block_Number` and `Block_Time`, so tables join on block without a separate blocks table. ## Coverage & Freshness - **History**: the Data Store lists the last 30 days on all seven tables. Older ranges are available on request from **sales@bitquery.io**. - **More order flow than the API**: the [Hyperliquid GraphQL API](/docs/perpetuals/hyperliquid/) keeps about 30 days of trades, liquidations, funding, TWAPs and prices, but only about 7 days of raw order updates and book updates. The Data Store listing has order and book updates as far back as trades. - **Freshness**: a delivery covers data up to the day before the files are prepared. - **Markets**: plain perpetuals, HIP-3 builder-deployed perps, spot pairs, and outcome/prediction tokens. See [Markets](#markets) for how they share one column. ## How Much History Is Included? The Data Store lists the last **30 days**, on every table, so you can replay roughly a month of live HyperCore, including any HIP-3 market that launched inside that window. Older ranges are available on request from **sales@bitquery.io**. The data has known gaps of about an hour each in September and October 2026, listed on request. The `Hyperliquid` API keeps about 30 days of trades, liquidations, funding, TWAPs, prices and candles, and about 7 days of raw orders, book updates and signed actions. A query for anything earlier returns an empty result. For older history, ask **sales@bitquery.io** for an older range as a Data Store export. ## How Is This Different From Hyperliquid's Free S3 Archive? Hyperliquid's own `s3://hyperliquid-archive` bucket (and free mirrors of it) publishes **L2 snapshots and asset contexts**. This dataset is a different shape: | | `hyperliquid-archive` and mirrors | Bitquery Data Store export | | ------------- | ------------------------------------------- | ------------------------------------------------------------------------------- | | Order book | L2 snapshots (price levels, fixed cadence) | **L4 per-order updates** with owner address and order id, every change | | Orders | Not included | **Full lifecycle**: opens, cancels, every reject reason, TP/SL children | | Fills | Not included | Both sides of every match, realized PnL, fees, builder and deployer fees | | Liquidations | Not included | Both sides, with the liquidated account, mark price and method | | Funding | Not included | Every account's payment at each hourly settlement | | Oracle | Not included | Mark, oracle and external perp prices per HIP-3 market, plus the inputs behind them | | History | Varies by bucket, no completeness guarantee | Last 30 days on the Data Store; older ranges on request | | Freshness | Roughly monthly uploads | Up to the day before delivery | Queue position, order lifetime, maker behaviour, spoofing patterns, and _why_ a liquidation fired are only recoverable from this shape of data. Hyperliquid's separate `s3://hl-mainnet-node-data` bucket does carry raw node fills and misc events (funding among them) as node JSON, but no order statuses or book diffs. ## Hyperliquid Data for Tax Reporting Tax reports need every trading event a wallet produced. The dataset carries fills, liquidations, TWAP fills and funding, so you, your accountant or your tax software can compute gains, losses and income for any wallet. The Data Store lists the last 30 days. A full tax year or other past range can be requested from **sales@bitquery.io**. | Tax input | Bitquery table | | ------------------------------------------------------- | --------------------------------------------------------------------------- | | Realized PnL on every closed position | `trades` and `perp_liquidations`: `*_Position_RealizedPnl` | | Trading fees, including builder and HIP-3 deployer fees | `trades` and `perp_liquidations`: `*_Fees_Fee`, `_FeeToken`, `_BuilderFee`, `_DeployerFee` | | Funding paid and received | `perp_fundings`: `Funding_Amount` | | Liquidations | `perp_liquidations` | | TWAP executions, fill by fill | `trades` where `Trade_TwapId > 0` (the TWAP owner's side; `Trade_IsTwap = 1` also marks the counterparty), with `twaps` for the parent order | | Spot buys and sells for cost basis | `trades` where `Trade_Market_Kind = 'spot'` | Deposits, withdrawals and transfers between accounts are **not** in the export today. Why teams use it for tax work: - **Nothing dropped from trading.** Funding, TWAP child fills and liquidations are included alongside regular trades, so PnL reconciles. - **Exact amounts.** Prices, sizes, PnL and fees are stored as decimal strings, so no precision is lost to floating point. - **Works with your stack.** Parquet files that load into S3, GCS, Snowflake or BigQuery. Query one wallet or thousands with SQL, then export to CSV for tax software. Built for tax platforms, accountants and funds reconciling Hyperliquid activity, as well as individual traders with high trade counts. To get the full dataset, [buy it from the Bitquery Data Store](https://bitquery.io/datastore/datasets?network=hyperliquid), email **sales@bitquery.io** or [fill the API form](https://bitquery.io/forms/api). ## Get Full Access A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=hyperliquid), contact **sales@bitquery.io** or [fill the API form](https://bitquery.io/forms/api). For the raw HyperCore feed from 17 July 2026, which you decode and parse your own way, see the [Blockchain Data Lake](/docs/data-lake/#hyperliquid). Datasets listed on the Data Store (last 30 days). Other ranges and table combinations are available on request: - [Hyperliquid](https://bitquery.io/datastore/datasets/hyperliquid): all seven tables - [Hyperliquid Trades](https://bitquery.io/datastore/datasets/hyperliquid-trades): `trades`, `perp_liquidations` and `twaps` - [Hyperliquid Order Book](https://bitquery.io/datastore/datasets/hyperliquid-order-book): `order_updates`, `book_updates` and `price_updates` - [Hyperliquid Funding](https://bitquery.io/datastore/datasets/hyperliquid-ledger): `perp_fundings` ## Available Hyperliquid Tables | Table | Grain | What it holds | | ------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `trades` | one row per side of each match, liquidations excepted | Price, size, direction, taker flag, fees, signed position before and after the fill, execution order, realized PnL, TWAP link | | `perp_liquidations` | one row per side of each liquidation match | The same fields as `trades`, plus the liquidated account, mark price and method | | `twaps` | one row per TWAP status change | Total size, executed size and notional, duration, status and error text | | `order_updates` | one row per order status change | Full lifecycle: `open`, `canceled`, `filled`, `triggered` and every `*Rejected` state, with TIF, triggers and TP/SL children | | `book_updates` | one row per L4 change of a single order | `new`, `update` or `remove`, each with the owning address, order id, price and size | | `price_updates` | one row per coin and price kind in each oracle push | Resulting mark, oracle and external perp prices, and the inputs behind them, for HIP-3 markets only | | `perp_fundings` | one row per account and market at each hourly settlement | Funding rate, signed position size, USDC paid or received | Pick `trades` for executed volume and realized PnL, `order_updates` for intent and rejection analysis, and `book_updates` when you need to rebuild the book at an arbitrary block. ### Why L4 Matters An L2 snapshot tells you the book was 12 deep at a price; an L4 stream tells you _which_ order moved and _whose_ it was. Likewise, `order_updates` includes orders that **never traded**. Rejects and cancels are invisible in any trades-only dataset, and in the sample below they are most of the order events. ## Sample Hyperliquid Cloud Dataset You can explore schemas and validate your tooling using the **public Hyperliquid sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/hyperliquid](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/hyperliquid) **Sample Parquet downloads (public S3)** Every sample has the same columns as a full delivery. | Table | Rows | Source | Download | | --------------- | ---: | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `trades` | 100 | first rows of pack `1165214000`–`1165214999` | [1165214001_1165214024.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/trades/1165214001_1165214024.parquet) | | `twaps` | 7 | every TWAP status in the same pack | [1165214012_1165214910.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/twaps/1165214012_1165214910.parquet) | | `perp_fundings` | 100 | the settlement in block `1165214467` | [1165214467_1165214467.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/perp_fundings/1165214467_1165214467.parquet) | | `order_updates` | 100 | first rows from block `1078000000` | [1078000000_1078000000.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/order_updates/1078000000_1078000000.parquet) | | `book_updates` | 100 | first rows from block `1078000000` | [1078000000_1078000001.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/book_updates/1078000000_1078000001.parquet) | | `price_updates` | 100 | first rows from block `1078000000` | [1078000012_1078000012.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/price_updates/1078000012_1078000012.parquet) | `perp_liquidations` has no public sample; liquidations are rare, and its columns match `trades` plus `Liquidation_MarkPx`, `Liquidation_Method` and `Liquidation_LiquidatedUser`. The samples were exported on 30 September 2026, before `Trade_Execution_Index`, `Liquidation_Execution_Index` and `Order_Index` existed and before `Trade_Position_Size` was filled in. New exports carry all four. The figures on this page come from the full export of two 1,000-block packs, not only the small samples: pack `1165214000`–`1165214999` (29 September 2026) held **11,082** trade rows, **7** TWAP statuses and one funding settlement of **411,880** rows across 327 markets, and pack `1078000000`–`1078000999` (19 July 2026) held **321,282** order updates, **193,903** book updates and **22,696** price updates. ## Hyperliquid Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── hyperliquid/ ├── trades/ ├── perp_liquidations/ ├── twaps/ ├── order_updates/ ├── book_updates/ ├── price_updates/ └── perp_fundings/ ├── _.parquet └── ... ``` Each file name gives the first and last block it holds. HyperCore produces roughly 14 blocks per second. File sizes track activity rather than block count, so size a download from the delivery manifest rather than from the block range. **A range with no events produces no file.** Sparse tables such as `twaps`, `perp_liquidations` and `perp_fundings` (one settlement an hour) skip ranges, so discover files under a prefix rather than generating names from a stride. ## Common Columns Every table starts with the same block columns and ends with the same bookkeeping columns: | Column | Type | Description | | ----------------------------------- | -------- | ------------------------------------------------------------- | | `ChainId` | `string` | Always `hyperliquid-core` | | `Block_Number` | `uint64` | HyperCore block height; the join key across tables | | `Block_Time` | `int64` | Block timestamp, **epoch nanoseconds** | | `Indexing_Time` | `int64` | When our pipeline indexed the block, epoch nanoseconds | | `Indexing_OnTree`, `Indexing_OnTrunk` | `uint8` | 1 when the block was on our block tree and finalized chain | | `Recording_Time` | `uint32` | When the row was written, epoch seconds | | `Recording_Hash` | `uint64` | Row hash used to drop duplicates | | `Block_Date` | `date` | UTC date of the block, handy for partitioning | Each table then prefixes its own fields with its entity name: `Trade_*`, `Liquidation_*`, `Twap_*`, `Order_*`, `BookUpdate_*`, `PriceUpdate_*`, `Funding_*`. Nested structures are flattened with `_`, for example `Trade_Execution_Price` and `Order_Market_CoinRaw`. The trading tables share these groups: | Group | Columns | | ------------ | ----------------------------------------------------------------------------- | | `_Trader_*` | `Address`, `Signer`, `Vault`, `Broadcaster`, `SignedAt` | | `_Market_*` | `Symbol`, `Kind`, `Protocol`, `CoinRaw`, `IsPerp`, `MaxLeverage` | | `_Position_*`| `Side`, `Size`, `SizeBefore`, `EntryPrice`, `RealizedPnl`, `Funding`, `Leverage`, `IsCross`, `Closed` | | `_Execution_*` (`trades`, `perp_liquidations`) | `Side`, `Direction`, `IsAggressor`, `Price`, `Size`, `Oid`, `Cloid`, `Tid`, `Hash`, `EventTime`, `Index` | Some of these are never filled in a given table (for example `Trade_Position_EntryPrice`, `Trade_Position_Funding` or `Trade_MarkPx`), and signer, vault and leverage fields are filled only when the source data carries them. The listing on the Data Store says, per column, when it can be empty. ## Correctness Notes Six things about this dataset will silently produce wrong numbers if you treat it like an EVM chain export. ### 1. Money Is Strings Prices, sizes, PnL, fees and funding amounts are stored as **decimal strings**, not numerics. This is deliberate: exchange decimals must not pass through a float. Block numbers, ids and timestamps are integers. Use `Decimal` rather than `float` for money: ```python from decimal import Decimal df["px"] = df.Trade_Execution_Price.map(Decimal) ``` Summing `Trade_Execution_Price` as float across a large export will drift; `Decimal` will not. ### 2. Every Match Appears Twice `trades` carries **one row per side**, so a single match produces two rows, one taker and one maker. In the 29 September pack, 11,082 trade rows are 5,548 with `Trade_Execution_IsAggressor = 1` and 5,534 with `0`, resolving to 5,555 unique `(Block_Number, Trade_Market_CoinRaw, Trade_Execution_Tid)` keys. Summing `Trade_Execution_Size` across the raw table **double-counts volume**. Filter to one side: ```sql SELECT SUM(CAST(Trade_Execution_Size AS DECIMAL(38,8))) FROM hyperliquid_trades WHERE Trade_Execution_IsAggressor = 1 -- taker side only ``` Liquidation fills are **not** in `trades`; they are only in `perp_liquidations`. Include both tables for complete volume and PnL. ### 3. `Trade_Execution_Hash` Is Not a Join Key One L1 transaction spans many matches, and TWAP fills carry 32 zero bytes. In the same pack, 11,082 rows share only 2,938 distinct hashes, and 1,296 rows (the TWAP fills, `Trade_IsTwap = 1`) have an all-zero hash. Key matches on **`(Block_Number, Trade_Market_CoinRaw, Trade_Execution_Tid)`** instead. The maker and taker rows of a match share the `Tid`. It identifies the match but is not a sequence number: see note 6 for ordering. ### 4. Rejected Orders Dominate `order_updates` `order_updates` is a record of _intent_, and most intent never trades. The 19 July pack's 321,282 order events break down as: | Status | Records | | --------------------------------- | ------: | | `badAloPxRejected` | 108,952 | | `open` | 95,735 | | `canceled` | 91,148 | | `perpMarginRejected` | 15,373 | | `reduceOnlyCanceled` | 3,875 | | `iocCancelRejected` | 3,505 | | `insufficientSpotBalanceRejected` | 1,299 | | `filled` | 1,118 | | `minTradeNtlRejected` | 121 | | `reduceOnlyRejected` | 101 | | `selfTradeCanceled` | 48 | | `tooManyOpenOrdersRejected` | 6 | | `triggered` | 1 | Only **1,118 of 321,282** events, about 0.35%, are `filled`. `badAloPxRejected` alone is a third of the file: post-only (`Alo`) orders priced through the book, rejected rather than crossed. `Alo` is 313,186 of the 321,282 `Order_Tif` values, so this table is dominated by market makers quoting and requoting. `Order_IsReject = 1` flags every `*Rejected` state. Filter on `Order_Status` for whatever you are measuring; never treat row count as order flow. ### 5. Time Units Differ by Field Two different epochs are in play, and mixing them is a factor-of-a-million error: | Field | Unit | | ------------------------------------------------------------- | ------------ | | `Block_Time`, `Order_EventTime`, `Twap_Interval_EventTime` | nanoseconds | | `Trade_Execution_EventTime`, `Liquidation_Execution_EventTime` | milliseconds | | `Order_PlacedTime`, `Twap_Interval_StartTime` | milliseconds | | `Recording_Time` | seconds | In the sample, the same fill carries `Block_Time = 1790672366376122193` and `Trade_Execution_EventTime = 1790672366376`. ### 6. Order Fills Inside a Block by Index, Not Tid All rows of one block share `Block_Time`, and `Trade_Execution_Tid` is a hash-like identifier, so sorting by either scrambles the fills of a busy block. The index columns give the exchange's own order: - `Trade_Execution_Index` and `Liquidation_Execution_Index` give the row's place in the block's fills, counting from 1. They form **one sequence across both tables**, so trades and liquidations of a block interleave correctly. Each side of a match has its own index. - `Order_Index` does the same for the order status changes of a block, which also share `Order_EventTime`. - `BookUpdate_Index` is the replay order of book changes. To replay an account's position, merge both fill tables and sort by block, then index: ```sql SELECT * FROM ( SELECT Block_Number, Trade_Execution_Index AS idx, 'trade' AS kind, Trade_Trader_Address AS account, Trade_Execution_Side AS side, Trade_Execution_Size AS size, Trade_Position_Size AS position_after FROM hyperliquid_trades WHERE Trade_Market_CoinRaw = 'BTC' UNION ALL SELECT Block_Number, Liquidation_Execution_Index, 'liquidation', Liquidation_Trader_Address, Liquidation_Execution_Side, Liquidation_Execution_Size, Liquidation_Position_Size FROM hyperliquid_perp_liquidations WHERE Liquidation_Market_CoinRaw = 'BTC' ) fills ORDER BY Block_Number, idx ``` ## Markets `*_Market_CoinRaw` covers four market types in one column, and `*_Market_Kind` names the type so you do not have to parse the prefix: | `CoinRaw` | `Kind` | Meaning | Trade rows (29 Sep pack) | Order events (19 Jul pack) | | ------------- | --------- | --------------------------- | -----------------------: | -------------------------: | | `HYPE`, `BTC` | `perp` | Plain perpetual | 6,406 | 258,980 | | `xyz:DRAM` | `hip3` | HIP-3 builder-deployed perp | 4,044 | 50,963 | | `@107` | `spot` | Spot pair, by index | 524 | 10,603 | | `#1890` | `outcome` | Outcome / prediction token | 108 | 736 | `*_Market_Protocol` is `hypercore` for plain perps, spot and outcome tokens, and the deploying dex (such as `xyz`) for HIP-3 markets. HIP-3 perps were 36% of trade rows in the 29 September pack, so leaving them in a "Hyperliquid perps" aggregate will not give you the numbers you expect. One exception: `PURR/USDC` is a spot pair, but its `Kind` reads `perp` and its `IsPerp` is 1. Exclude it by name when you need perpetuals only. ## Table Notes The full column list for every table, with a description of each column, is on the [Data Store listings](https://bitquery.io/datastore/datasets?network=hyperliquid). The points below are the ones that matter when you query. ### trades - `Trade_Execution_Side` is `Buy` or `Sell` for this side; `Trade_Execution_Direction` is the node's label: `Open Long`, `Close Short`, `Long > Short`, `Buy`, `Sell` and so on. - `Trade_Position_SizeBefore` is the **signed position before the fill** (negative is short), not money. `Trade_Position_RealizedPnl` is the realized PnL of the fill in USDC. It was non-zero on 5,277 of the 11,082 rows in the 29 September pack. - `Trade_Position_Size` is the **signed position after the fill**. For perps it is `SizeBefore` plus `Size` on a `Buy`, or minus it on a `Sell`. For spot it is the base-token balance after the fill, net of a fee charged in that token, and can be empty. - `Trade_Execution_Index` is the fill's place in its block; see [note 6](#6-order-fills-inside-a-block-by-index-not-tid). - `Trade_Fees_Fee` is negative when the maker received a rebate. `Trade_Fees_FeeToken` was `USDC` on 10,743 of those rows. - `Trade_TwapId` joins to `Twap_TwapId`. ### perp_liquidations - Each liquidation match has two rows, one for the liquidated account and one for the counterparty. `Liquidation_LiquidatedUser` names the liquidated account on both; keep the rows where `Liquidation_Trader_Address = Liquidation_LiquidatedUser` for the liquidated side only. - Sign a liquidation fill like a trade, by `Liquidation_Execution_Side`: a `Buy` adds to that row's account position and a `Sell` subtracts. `Liquidation_Position_SizeBefore` and `Liquidation_Position_Size` are the position before and after the fill. - `Liquidation_MarkPx` and `Liquidation_Method` (for example `market`) come from the node. `Liquidation_Liquidator` is always empty. ### twaps - `Twap_State_Status` is `activated`, `waitingForTrigger`, `finished`, `terminated`, `stopped` or `error`, with the error text in `Twap_State_StatusError`. - `Twap_Order_Size` is the total to execute; `Twap_State_ExecutedSize` and `Twap_State_ExecutedNotional` are the running totals. ### order_updates - `Order_Oid` joins to `Trade_Execution_Oid` and `BookUpdate_Oid`. - `Order_ParentOid` and `Order_Leg` link take-profit and stop orders to the order they are attached to. - `Order_Index` orders the status changes inside a block, where they all share `Order_EventTime`. ### book_updates - `BookUpdate_Kind` is `new` (95,060 rows in the 19 July pack), `remove` (95,456) or `update` (3,387). - `BookUpdate_Size` is the order's size on `new` and the size after the change on `update`; `BookUpdate_SizeBefore` is the size before an `update`. - Replay in `Block_Number` then `BookUpdate_Index` order to reconstruct the book at any block. ### price_updates - The table covers **HIP-3 markets only**: the node publishes oracle updates for builder-deployed dexes, not for plain perps such as `BTC` or `HYPE`. - `PriceUpdate_Kind` says which price the row is: `mark`, `oracle` or `extPerp` for the resulting prices, `markInput`, `spotInput` or `extPerpInput` for the inputs. - Oracle prices drive funding and liquidation, so for a HIP-3 market join these to `perp_liquidations` on `Block_Number` when reconstructing why a liquidation fired. ### perp_fundings - `Funding_Amount` is the USDC the account received, negative when it paid. `Funding_Size` is the signed position, negative for a short. With a positive `Funding_Rate`, longs pay shorts. ## Joining Tables Every table carries `Block_Number`, and the order id threads the trading tables together: ```sql -- taker fills of orders that reached 'filled' SELECT t.Trade_Market_CoinRaw, t.Trade_Execution_Price, t.Trade_Execution_Size, t.Trade_Position_RealizedPnl, o.Order_Tif, o.Order_ReduceOnly FROM hyperliquid_trades t JOIN hyperliquid_order_updates o ON t.Trade_Execution_Oid = o.Order_Oid AND o.Order_Status = 'filled' WHERE t.Trade_Execution_IsAggressor = 1 ``` Because one order produces many status events and many fills, join on the order id plus a status filter, or aggregate one side first; otherwise you get a cross product. ## Reading Files with DuckDB No key, no client library. Point DuckDB at the public sample directly: ```sql SELECT Trade_Market_CoinRaw, SUM(CAST(Trade_Execution_Size AS DECIMAL(38,8)) * CAST(Trade_Execution_Price AS DECIMAL(38,8))) AS notional FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/trades/1165214001_1165214024.parquet') WHERE Trade_Execution_IsAggressor = 1 -- taker side only, see Correctness Notes GROUP BY Trade_Market_CoinRaw ORDER BY notional DESC LIMIT 10; ``` ## Reading Files in Python ```python from decimal import Decimal BASE = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/" trades = pd.read_parquet(f"{BASE}trades/1165214001_1165214024.parquet") orders = pd.read_parquet(f"{BASE}order_updates/1078000000_1078000000.parquet") # taker side only: every match is in the file twice taker = trades[trades.Trade_Execution_IsAggressor == 1] taker = taker.assign( px=taker.Trade_Execution_Price.map(Decimal), sz=taker.Trade_Execution_Size.map(Decimal), ) print("matches:", len(taker), "of", len(trades), "trade rows") print("notional:", (taker.px * taker.sz).sum()) # realized PnL net of fees, by wallet net = trades.assign( pnl=trades.Trade_Position_RealizedPnl.map(Decimal) - trades.Trade_Fees_Fee.map(Decimal) ).groupby("Trade_Trader_Address").pnl.sum() print(net.sort_values().tail()) # order flow is mostly rejects, not trades print(orders.Order_Status.value_counts().head()) ``` ## Real-Time vs Batch Data Access Parquet exports are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming Hyperliquid data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - [**Hyperliquid APIs and streams**](/docs/perpetuals/hyperliquid/) The Parquet columns are the live stream's fields flattened with `_` (`Trade.Execution.Price` becomes `Trade_Execution_Price`), so logic written against one maps field for field onto the other. ## Buy the Full Dataset The public samples above are a few hundred rows. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. A Data Store purchase covers the last 30 days. Older history and custom ranges are available through **sales@bitquery.io**. - [Buy it from the Bitquery Data Store](https://bitquery.io/datastore/datasets?network=hyperliquid), or - Email **sales@bitquery.io**, or - [Fill the request form](https://bitquery.io/forms/api) --- ## Hyperliquid Historical Data — Bitquery vs Hyperliquid's Free API and S3 Archive URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/vs-hyperliquid-api/ An honest comparison of Hyperliquid's native Info API, its free s3://hyperliquid-archive bucket, and Bitquery: order book granularity (L2 vs L3), account state per address vs every account, what the archive actually contains, rate limits, history depth and cross-chain coverage. # Hyperliquid Historical Data: Bitquery vs Hyperliquid's free data Where to get Hyperliquid historical data depends on what you need: trades, candles, the order book or full archive history. Hyperliquid publishes its own API and its own historical archive, both free. Any honest evaluation should start there, so this page does. ## When you should just use Hyperliquid directly Use the [native Info API](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) if: - You are **trading your own account** and need your own orders, fills and positions. It is the canonical source, closest to the matching engine, with the lowest possible latency. - You need the **current** aggregated book for one or two coins, and 5–20 levels is enough. - You are building something small, single-venue, and free matters more than completeness. It is a good API. For those jobs nothing else will be better, and you should not pay for a substitute. Bitquery is for the jobs it is not built for: **seeing the whole market, at order granularity, over time, alongside other chains.** ## What Hyperliquid's free archive actually contains This is the part most evaluations get wrong. Hyperliquid publishes two public S3 buckets, and they are narrower than people assume: | Bucket / path | Contains | | --- | --- | | `s3://hyperliquid-archive/market_data/` | **L2 book snapshots** | | `s3://hyperliquid-archive/asset_ctxs/` | Asset contexts | | `s3://hl-mainnet-node-data/node_fills_by_block` (older data: `node_fills`, `node_trades`) | Fills, as written by a non-validating node | | `s3://hl-mainnet-node-data/misc_events_by_block` | Non-trade events: transfers, staking, funding | | `s3://hl-mainnet-node-data/explorer_blocks`, `replica_cmds` | Explorer blocks and L1 transactions | | Not provided | **Candles and spot asset data** — "no other historical data sets", per Hyperliquid | Hyperliquid's own documentation states that `hyperliquid-archive` is uploaded roughly **once a month**, with **no guarantee of timely updates**, and that **data may be missing**. On `hl-mainnet-node-data` the requester pays the transfer costs. So fills do exist for free — as raw node files you download, parse and index yourself. Candles, order statuses and per-order book changes are not in either bucket, and that is by design, not an oversight. ## The core difference: L2 vs L3 Hyperliquid's public market-wide book data — both the `l2Book` websocket channel and the S3 snapshots — is **L2**: size aggregated per price level. Order-level detail (`orderUpdates`, `userFills`) exists in the native API, but only **per address** — one address you already know per subscription, at most 10 users per IP. Bitquery serves the book market-wide at **L3 (market-by-order)**. | | Hyperliquid native (market-wide) | Bitquery | | --- | --- | --- | | Book grain | L2 — total size per price level | **L3 — one event per individual order** | | Order identity | — | `Oid`, joins `Orders` ↔ `BookUpdates` ↔ `Trades` | | Who placed the order | — | `Trader { Address }` | | Depth | 5–20 levels | Unlimited | | Order-level data for other traders | Only per address you already know | Every order, every trader | Because Hyperliquid settles on a transparent L1, the wallet behind each order is public. That makes this **L3 with named attribution** — something that does not exist on centralised venues, where exchanges anonymise L3 feeds. It is what makes market-maker tracking, cancel-to-fill analysis and wallet-level order flow possible at all. See [Track Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet). :::note This data is on-chain Hyperliquid is a transparent L1, so this information is *derivable* by anyone who indexes the chain — Bitquery's contribution is the indexing, normalisation and delivery, not exclusive access. The claim here is specifically that **Hyperliquid's own API does not serve it market-wide**, which is verifiable in their docs. ::: ## Account state: one address vs every account The Info API answers for one address at a time: `clearinghouseState` for its margin and positions, `spotClearinghouseState` for its spot balances, `openOrders` for its orders. That is all you need for your own account. To rank the biggest positions on a market, map where the stops sit, or list who holds a token, you would have to know every address first and query each one within the rate limits. Bitquery takes a snapshot of the full exchange state about every 12.5 minutes and serves it for **every account at once**: every open position with entry price, margin and unrealized PnL, margin per dex, spot balances, the order book with owners, waiting trigger orders, vaults and their depositors, Earn. The snapshots of the last 7 days are kept, so the state at a past moment is one query too. See the [Snapshots API](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api). | | HL Info API | Bitquery snapshots | | --- | --- | --- | | Scope | One address per request | Every account on the exchange | | Freshness | Now | The latest snapshot, up to ~12.5 minutes old | | History | Current state only | Every snapshot of the last 7 days, or the one at a given moment | | Filter and rank | Client-side, after fetching each address | Any field: market, size, entry price, leverage, trigger price, token | | Delivery | REST, per-IP weight limits | GraphQL query; no subscription | ## Full comparison | Capability | HL Info API | HL S3 archive | Bitquery | | --- | --- | --- | --- | | Cost | Free | Free | Paid | | Book granularity | L2 aggregated (order-level only per known address) | L2 snapshots | **L3 market-by-order, market-wide** | | Trades / fills market-wide | Price, size, side and both addresses (`trades`) | Raw node fills (requester pays) | Full: direction, fees, leverage, position size before and after, realized PnL, execution order in the block | | Candles | Via REST, pagination-limited | **Not provided** | `Candles` cube: 1m, 5m, 15m and 1h bars | | Spot markets | Yes | **No spot asset data** | Yes | | Liquidations market-wide | Per-address only | Inside raw node fills | Exchange-wide, with method, mark price, leverage | | Funding per trader | Per-address only | Raw node events (`misc_events_by_block`) | `PerpFundings`, market-wide | | Open positions | Per-address snapshot | Not provided | `CurrentPositions`, whole market, sortable; `SnapshotPositions` with entry price, margin and unrealized PnL, 7 days of snapshots | | Margin, spot balances, open orders, vaults | Per address (`clearinghouseState`, `spotClearinghouseState`, `openOrders`), current only | Not provided | `Snapshot*` cubes: every account, every ~12.5 minutes, 7 days | | Prediction market names | `outcomeMeta`, current markets | Not provided | On every trade, order and snapshot row (`Market { Outcome }`) | | Order statuses and per-order book changes | Per-address only (`orderUpdates`) | Not provided | `Orders` (rejects included) and `BookUpdates`, market-wide | | Raw L1 actions | Not exposed | Raw L1 transactions (`replica_cmds`) | `SignedActions`: rejects and non-order actions, with signer | | Update cadence | Real time | `hyperliquid-archive`: ~monthly, no guarantee | Real time | | Completeness guarantee | — | **Stated for `hyperliquid-archive`: data may be missing** | SLA available | | History depth | Snapshot + limited REST | Longer than Bitquery's window, as raw files | Rolling ~30 days via API (~7 days for orders, book updates and signed actions); older history as Parquet exports from the Data Store | | Delivery | WebSocket / REST | S3 files | GraphQL, WebSocket, Kafka (protobuf), Parquet exports | | Rate limits | Yes, per IP: connections, subscriptions, 10 users, REST weight | S3 transfer (requester pays on node data) | Plan-based, no per-coin fan-out | | Other chains | Hyperliquid only | Hyperliquid only | **Solana, EVM, Base, BNB, Tron, Bitcoin — same schema, same key** | ## Same question, both ways **"Give me 1-hour OHLCV for BTC-PERP."** Natively, candles are not in the archive, so you either page through the REST `candleSnapshot` endpoint within its limits, or collect trades live and aggregate them yourself, then persist them. With Bitquery it is one query: ```graphql query { Hyperliquid { Candles( limit: {count: 100} orderBy: {descending: Interval_Time_Start} where: { Market: {CoinRaw: {is: "BTC"}} Interval: {Time: {Duration: {eq: 3600}}} } ) { Interval { Time { Start Duration } } Market { Symbol Kind } Ohlc { Open High Low Close Volume } } } } ``` `CoinRaw: "BTC"` is the native BTC perp (`Symbol: "BTC"` would also match HIP-3 BTC markets). `Open` and `Close` are the first and last taker fill of the bar in execution order. The same query becomes a live stream by changing `query` to `subscription`. ## Where Bitquery is genuinely weaker Worth saying plainly: - **Latency to the matching engine.** For your own order placement and fills, the native API is closer to the source. Bitquery indexes blocks; there is a step in between. - **Cost.** Free is free. If your use case fits inside the native API, use it. - **Freshness of account state.** For one address, `clearinghouseState` answers with the state now. Bitquery's snapshots of every account are up to ~12.5 minutes old, are kept 7 days and cannot be subscribed to; between snapshots, the event cubes (`Trades`, `Orders`, `PerpLiquidations`) carry what changed. - **API history depth.** The GraphQL cubes serve a rolling ~30-day window (~7 days for orders, book updates and signed actions). Hyperliquid's free buckets go back further for L2 snapshots and raw fills, if you are willing to parse and index them yourself. For older Bitquery data, use [Parquet exports from the Bitquery Data Store](https://bitquery.io/datastore) ([details](/docs/cloud/hyperliquid/)); older ranges are available on request from [sales@bitquery.io](mailto:sales@bitquery.io). ## Where Bitquery is decisive - **L3 with wallet attribution, market-wide** — not available from the native API at all. - **The state of every account at once** — positions with entry price and unrealized PnL, stops, spot holders, vault depositors — where the native API answers one address at a time. - **Candles, order statuses and per-order book history** — absent from Hyperliquid's free buckets, which hold fills only as raw node files. - **One stream for the entire market** rather than per-coin, per-user subscriptions you merge client-side. - **Cross-chain.** A Hyperliquid-only provider can tell you a wallet was liquidated. Only a multi-chain provider can tell you where the money went afterwards. - **One plan, not a separate product.** Hyperliquid is served from the same real-time cubes as Solana, Ethereum, Base, BNB and Tron DEX data. There is no Hyperliquid add-on: any plan that covers your spot DEX data covers perps too, so a perps-vs-spot basis monitor or a cross-venue trader profile is one API key and one bill. ## Next steps **Start streaming** - [Real-time trades and candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api#real-time-trades-stream) — fills with PnL, direction and fees, market-wide - [Exchange-wide liquidation feed](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api#real-time-liquidation-alerts) — every liquidation as it happens - [Funding stream](/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api#real-time-funding-stream) — hourly settlements for every trader - [Kafka streams](/docs/streams/kafka-streaming-concepts) — protobuf delivery for production bots **Go deeper** - [Hyperliquid API overview](/docs/perpetuals/hyperliquid) — every cube - [L3 Order Book API](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) - [Snapshots API](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api) — every position, order, balance and vault, every ~12.5 minutes - [Track Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet) — including following a wallet to other chains - [Trading Data Overview](/docs/trading/trading-data-overview) — the cross-chain Trading cube Hyperliquid sits alongside - [Data Coverage & Retention](/docs/graphql/data-coverage-retention) — exact windows per cube --- ## Hyperliquid Liquidations — Liquidation History by Wallet URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-liquidation-history-by-wallet/ Pull every liquidation for a single Hyperliquid address: market, method, mark price, execution, the position size before it was closed, and fees, over GraphQL and WebSocket. # Hyperliquid Liquidations: History by Wallet Look up Hyperliquid liquidations for any address: every liquidated position, its market, method, mark price and size, as a query or a live stream. The [perpetuals page](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api#liquidations) covers the market-wide liquidation feed. This page is the other direction: **one address, its liquidation history** over the data window (about the last 30 days). That is the query you need to answer "was this position liquidated or did I close it", to reconstruct a blown-up account, or to fill the gap left when an export shows a position disappearing with no closing trade. :::tip Checking once, or watching continuously? Every query on this page becomes a live feed by changing `query` to `subscription` — see [real-time liquidation alerts](#real-time-liquidation-alerts-for-one-wallet) below. To watch a set of wallets, the whole exchange, or follow the liquidated funds to other chains, see [Build on this](#build-on-this). Hyperliquid is included in every Bitquery plan alongside Solana, Ethereum, Base, BNB and Tron. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Every liquidation of one address `LiquidatedUser` is the address whose position was closed. `Method` is `market` for an open-market liquidation and `backstop` when the backstop vault takes over. A forced fill is recorded for both sides: the liquidated account's own fill, and the fill of every account that took the other side. All of them carry the same `LiquidatedUser`, so the query filters `Trader.Address` as well to keep only the liquidated account's own rows. On those rows `Position.SizeBefore` and `Position.Size` are the signed size immediately before and after the fill — negative for a short, `0` once the position is fully closed; a partial liquidation leaves the rest open. Sign a fill by `Execution.Side` (`Buy` adds, `Sell` subtracts), as for a trade. Fills of one block share `Block.Time`; `Execution.Index` is their execution order, counted together with the trades of the block. Run it in the IDE: [Hyperliquid Wallet Liquidation History ➤](https://ide.bitquery.io/hyperliquid-wallet-liquidation-history) ```graphql query { Hyperliquid { PerpLiquidations( limit: {count: 100} orderBy: {descending: [Block_Time, Liquidation_Execution_Index]} where: { Liquidation: { LiquidatedUser: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"} Trader: {Address: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"}} } Block: {Time: {since_relative: {days_ago: 3}}} } ) { Block { Time } Liquidation { Market { Symbol Kind } Method MarkPx LiquidatedUser Execution { Price Size Side Direction Index Hash } Position { Leverage IsCross Side SizeBefore Size } Fees { Fee FeeToken } } } } } ``` Sample response: ```json { "Block": { "Time": "2026-10-13T11:03:08.025489Z" }, "Liquidation": { "Market": { "Symbol": "STX", "Kind": "hip3" }, "Method": "market", "MarkPx": "714.56", "LiquidatedUser": "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c", "Execution": { "Price": "710.96", "Size": "1.254", "Side": "Sell", "Direction": "Close Long", "Index": 44 }, "Position": { "Leverage": 10, "IsCross": false, "Side": "Long", "SizeBefore": "1.254", "Size": "0" }, "Fees": { "Fee": "0.080238", "FeeToken": "USDC" } } } ``` `Execution.Direction` reads `Close Long` because liquidating a long is a sell that closes it — the direction describes the effect on the liquidated position, not the trader's intent. `Position.Size` `0` means the whole position was closed by this fill. ## Liquidation totals per market One row per market and method, with the number of liquidation fills, the total size closed and the fees charged. Keep the `Trader.Address` filter: without it the counterparties' fills are summed in as well and the size doubles. Run it in the IDE: [Hyperliquid Wallet Liquidation Totals ➤](https://ide.bitquery.io/hyperliquid-wallet-liquidation-totals) ```graphql query { Hyperliquid { PerpLiquidations( where: { Liquidation: { LiquidatedUser: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"} Trader: {Address: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"}} } Block: {Time: {since_relative: {days_ago: 3}}} } ) { Liquidation { Market { Symbol } Method } fills: count size: sum(of: Liquidation_Execution_Size) fees: sum(of: Liquidation_Fees_Fee) } } } ``` ## Liquidations over a date range Bound the export to a day, a week, or the window around a specific market event. Liquidation history on the API goes back about 30 days; a range older than that returns nothing. For older data, ask about a [Data Store export](https://bitquery.io/datastore). Run it in the IDE: [Hyperliquid Liquidations By Date Range ➤](https://ide.bitquery.io/hyperliquid-liquidations-by-date-range) ```graphql query { Hyperliquid { PerpLiquidations( limit: {count: 100} orderBy: {ascending: [Block_Time, Liquidation_Execution_Index]} where: { Liquidation: { LiquidatedUser: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"} Trader: {Address: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"}} } Block: {Time: {since: "2026-10-01T00:00:00Z", till: "2026-10-08T00:00:00Z"}} } ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx Execution { Price Size Side Direction } Position { Leverage IsCross Side SizeBefore Size } Fees { Fee FeeToken } } } } } ``` ## Backstop liquidations only Filter on `Method` to isolate the liquidations the backstop vault absorbed rather than the open market. These carry their own `Execution.Direction` values: `Liquidated Isolated Long`, `Liquidated Isolated Short` or `Liquidated Cross Long` on the forced fill itself, `Auto-Deleveraging` on the rows of accounts whose opposite positions were auto-deleveraged against it, and `Partial Borrow Liquidation` for a spot-borrow liquidation on a spot market. Backstop liquidations are rare, so for most wallets this returns nothing — drop the `LiquidatedUser` filter to list them exchange-wide. Run it in the IDE: [Hyperliquid Backstop Liquidations By Wallet ➤](https://ide.bitquery.io/hyperliquid-backstop-liquidations-by-wallet) ```graphql query { Hyperliquid { PerpLiquidations( limit: {count: 100} orderBy: {descending: Block_Time} where: { Liquidation: { LiquidatedUser: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"} Method: {is: "backstop"} } Block: {Time: {since_relative: {days_ago: 30}}} } ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx Trader { Address } Execution { Price Size Side Direction } Position { Leverage IsCross SizeBefore Size } } } } } ``` ## Real-time liquidation alerts for one wallet Run it in the IDE: [Hyperliquid Wallet Liquidation Stream ➤](https://ide.bitquery.io/hyperliquid-wallet-liquidation-stream) ```graphql subscription { Hyperliquid { PerpLiquidations( where: { Liquidation: { LiquidatedUser: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"} Trader: {Address: {is: "0xb4f1d3e5153599cd9f59c686dbee4262ac87d75c"}} } } ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx LiquidatedUser Execution { Price Size Side Direction } Position { Leverage IsCross Side SizeBefore Size } } } } } ``` Drop the `where` clause to stream every liquidation on the exchange, or swap the address for a list to watch a set of accounts (`in: [...]` on both `LiquidatedUser` and `Trader.Address`). ## Build on this A one-off lookup answers "was I liquidated". The same cube, kept open as a stream, is what bots, risk desks and dashboards run on: - **Watch a list of wallets.** Replace `is` with `in: ["0x…", "0x…"]` in both filters of the subscription above to get one stream for every account you care about — your own, a vault's, a set of market makers. - **Exchange-wide liquidation feed.** Drop the `where` clause and you have every liquidation on Hyperliquid in real time — the input for cascade detection, liquidation heatmaps and Telegram alerts. The [perpetuals page](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api#real-time-liquidation-alerts) has the market-wide variant. - **Pair it with positions and funding.** Query [`CurrentPositions`](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api#current-positions) for the open positions of the accounts you watch (it is a state cube, not a stream), and stream [`PerpFundings`](/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api#real-time-funding-stream) for what the position cost to hold. - **Follow the money off Hyperliquid.** The liquidated address is an ordinary EVM wallet. The same API key covers Solana, Ethereum, Base, BNB, Tron and Bitcoin, so "where did the collateral come from, and where did the rest go" is one more query — see [Follow the wallet off Hyperliquid](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet#4-follow-the-wallet-off-hyperliquid). - **Lowest latency.** For production alerting, the same liquidations arrive over [Kafka](/docs/streams/kafka-streaming-concepts) as protobuf (`hyperliquidcore.messages.proto`). ## Notes - `Liquidator` is empty in practice — the feed does not name the liquidator. The accounts that took the other side of a forced fill are the rows with the same `LiquidatedUser` and `Execution.Tid` and a different `Trader.Address`. - A single blow-up can produce many records: one per fill — a liquidation is often filled against several makers — for every market the account held. - Rows written before about 09:40 UTC on 13 October 2026 have `Execution.Index` 0 and an empty `Position.Size`. - To see what the position looked like before it was closed, pair `Position.SizeBefore` here with the fills on the [Trades API](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) and the funding it accrued on the [Funding Payments API](/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api). --- ## Hyperliquid Liquidations, Funding, Positions & Leverage API URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api/ Stream Hyperliquid perp liquidations, per-trader funding payments and leverage changes, and query current open positions, with Bitquery GraphQL and WebSocket. # Hyperliquid Liquidations, Funding, Positions & Leverage API This page covers the perp risk cubes: `PerpLiquidations`, `PerpFundings`, `CurrentPositions` and `TraderLeverageUpdates`. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Liquidations Each liquidation includes the liquidated user, the `Method` (`market` for open-market liquidation, `backstop` when the backstop vault takes over), the mark price at liquidation and the actual execution. A forced fill has two sides and both are recorded: the liquidated account's own fill and the fill of every account that took the other side. All of them carry the same `LiquidatedUser`; `Trader.Address` tells them apart. Sign a liquidation fill by `Execution.Side` (`Buy` adds to the position, `Sell` subtracts), as for a trade. `Position.SizeBefore` and `Position.Size` are that account's signed size before and after the fill, and `Execution.Index` numbers the fill together with the trades of its block. For every liquidation of one address, see [Hyperliquid Liquidation History by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-liquidation-history-by-wallet). Run it in the IDE: [Hyperliquid Liquidations ➤](https://ide.bitquery.io/hyperliquid-liquidations) ```graphql query { Hyperliquid { PerpLiquidations(limit: {count: 50}, orderBy: {descending: [Block_Time, Liquidation_Execution_Index]}) { Block { Time } Liquidation { Market { Symbol Kind } Method MarkPx Liquidator LiquidatedUser Trader { Address } Execution { Price Size Side Direction Index Hash } Position { Leverage IsCross Side SizeBefore Size } Fees { Fee FeeToken } } } } } ``` ### Real-time liquidation alerts Run it in the IDE: [Hyperliquid Liquidations Stream ➤](https://ide.bitquery.io/hyperliquid-liquidations-stream) ```graphql subscription { Hyperliquid { PerpLiquidations { Block { Time } Liquidation { Market { Symbol } Method MarkPx LiquidatedUser Trader { Address } Execution { Price Size Side } Position { Leverage IsCross SizeBefore Size } } } } } ``` ## Funding payments `PerpFundings` records **per-trader funding transfers** at each hourly funding tick: the signed `Amount` (negative = the trader paid funding), the funding `Rate` applied and the position `Size` it applied to. A market whose funding rate is zero in an hour is not charged, so it has no rows for that tick. Run it in the IDE: [Hyperliquid Funding Payments ➤](https://ide.bitquery.io/hyperliquid-funding-payments) ```graphql query { Hyperliquid { PerpFundings( limit: {count: 50} orderBy: {descending: Block_Time} where: {Block: {Time: {since_relative: {hours_ago: 2}}}} ) { Block { Time } Funding { Market { Symbol Kind } Amount Rate Size Trader { Address } } } } } ``` Filter to one wallet with `where: {Funding: {Trader: {Address: {is: "0x..."}}}}` to compute its total funding paid/received. The [Hyperliquid Funding Payments API](/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api) page has ready-made wallet queries: per-market totals, paid-only, date ranges and a live stream. ## Current positions `CurrentPositions` is a **state cube**: one row per trader and market with the latest position — signed `Size` (negative = short, `"0"` = closed), leverage, margin mode, and the `Funding` and `RealizedPnl` summed since the data window started (about 30 days back), not over the account's lifetime. It can be queried but not streamed. - **Size is exact for perps** (native and HIP-3), even for a position opened before the data window: each hour the exchange charges funding on a market, it restates the size of every open position there, and the cube takes that size. A market whose funding rate is zero in an hour is not charged, so it is skipped that hour. - **Closed positions stay** with `Size` `"0"`; skip them on the client. - **Spot and outcome balances are in the cube too**, built only from trades inside the window. Filter `Market: {IsPerp: true}` for perps; note that `PURR/USDC` is a spot pair although its `Kind` reads `perp`. - `LastTime` / `LastBlock` is the latest event of any kind on the position, the hourly funding included, so for an open perp position it is at least the last funding hour. `LastTradeTime` / `LastTradeBlock` is the account's last fill on that market (`1970-01-01T00:00:00Z` / `0` when it has none in the window). Run it in the IDE: [Hyperliquid Current Positions ➤](https://ide.bitquery.io/hyperliquid-current-positions) ```graphql query { Hyperliquid { CurrentPositions( limit: {count: 50} orderBy: {descending: LastTradeTime} where: {Market: {Symbol: {is: "BTC"}}} ) { LastBlock LastTime LastTradeBlock LastTradeTime Market { Symbol Kind } Position { Size Leverage IsCross Funding RealizedPnl } Trader { Address } } } } ``` Swap the filter to `where: {Trader: {Address: {is: "0x..."}}, Market: {IsPerp: true}}` to get every perp position of one trader. For entry price, margin, unrealized PnL and funding over the position's life, and for the positions at a past moment, use [`SnapshotPositions`](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api#biggest-positions-with-entry-price-and-unrealized-pnl): every open position from a snapshot, about every 12.5 minutes, kept 7 days. Market-wide open interest is on [`SnapshotMarkets`](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api#open-interest-and-prices-of-every-market). ## Leverage updates `TraderLeverageUpdates` fires whenever a trader changes leverage or switches between cross and isolated margin on a market. Run it in the IDE: [Hyperliquid Leverage Updates ➤](https://ide.bitquery.io/hyperliquid-leverage-updates) ```graphql query { Hyperliquid { TraderLeverageUpdates(limit: {count: 50}, orderBy: {descending: Block_Time}) { Block { Time } LeverageUpdate { Leverage IsCross Market { Symbol } Trader { Address } } } } } ``` `PerpLiquidations`, `PerpFundings` and `TraderLeverageUpdates` stream over WebSocket with the same shape — change `query` to `subscription` and drop `limit`/`orderBy`. `CurrentPositions` is query-only. ## Related - [Liquidation History by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-liquidation-history-by-wallet) - [Funding Payments by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api) - [HIP-3 Stocks API](/docs/perpetuals/hyperliquid/hip3-stocks-api) — funding and liquidations on stock, index and commodity perps - [Track ZEC on Hyperliquid](/docs/perpetuals/hyperliquid/track-zec-on-hyperliquid) — positions, liquidations and funding for one market - [Snapshots API](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api) — every position, account, order and balance from snapshots --- ## Hyperliquid MCP Server for Claude, ChatGPT and Cursor URL: https://docs.bitquery.io/docs/mcp/hyperliquid/ Ask Claude, ChatGPT or Cursor about Hyperliquid in plain English: top markets, funding, open interest, liquidations, the best wallets and what they hold. Read-only, from on-chain data. # Hyperliquid MCP Server The Bitquery MCP server gives an AI client 18 tools for Hyperliquid data. You ask a question in Claude, ChatGPT, Cursor, VS Code or Codex, the agent picks a tool, and rows come back from Bitquery's index of the exchange's own blocks: perpetuals, spot pairs, markets listed by third parties, and outcome markets. It reads data only. It cannot place, change or cancel an order, and it never touches a key. To trade, use Hyperliquid's own API; to research markets and wallets, use this. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Other clients take the same URL. Steps for each are in the [MCP server install guide](/docs/mcp/mcp-server/). A 38-second demo, [Polymarket and Hyperliquid data in ChatGPT and Claude](https://www.youtube.com/watch?v=IwuIlcKsANk), shows the server answering questions like the ones below. Every figure on this page came from a call to the production server on 21 September 2026, between 10:21 and 10:25 UTC, on a morning when Bitcoin had risen 5.4% in a day. The one exception is the long / short split in the liquidation table: it was recounted later over the same window by the side of the liquidated account. Your numbers will differ. ## What can I ask? ### What is trading most on Hyperliquid? > *"What are the five most traded Hyperliquid markets in the last 24 hours?"* The agent calls `hyperliquid_markets`. | Market | Last price | 24h change | 24h volume | Wallets | |---|---:|---:|---:|---:| | BTC | 84,666 | +5.39% | $2,872,395,664 | 22,251 | | ETH | 2,719.7 | +5.66% | $1,776,080,523 | 10,550 | | ZEC | 1,517.4 | +5.46% | $600,636,368 | 7,799 | | HYPE | 95.244 | +4.96% | $430,607,975 | 7,935 | | NEAR | 4.2931 | +21.45% | $356,057,954 | 7,430 | BTC alone had 375,429 trades. Volume counts each fill once. The `Market` column is the id that every other tool takes, which matters because a ticker is not unique: BTC exists as the native perpetual and again on third-party venues. Which apps route that volume, and what the third-party venues earn, is covered in this video: ### Where are the big positions, and who is paying for them? > *"Show open interest, the long and short split, and funding for the biggest Hyperliquid perpetuals."* `hyperliquid_open_interest`, from the 10:00 UTC hourly settlement: | Market | Open interest | Long | Short | Funding per year | |---|---:|---:|---:|---:| | BTC | $1,865,713,119 | 21,904 | 11,693 | 78.64% | | ETH | $1,540,615,295 | 13,476 | 5,128 | 18.81% | | HYPE | $1,042,186,424 | 13,035 | 4,566 | 42.40% | | ZEC | $398,747,943 | 6,733 | 3,395 | 10.95% | | SOL | $351,305,718 | 9,886 | 2,885 | 10.95% | Long and Short are counts of accounts. On a perpetual the size held long always equals the size held short, so the crowd shows up in the count of accounts. On BTC 65% of accounts were long, and they were paying shorts at a rate worth 78.64% per year, $167,486 in that one hour. Funding is paid every hour; the yearly figure is the hourly rate times 24 times 365. ### How did funding get there? > *"How has BTC funding moved over the last 24 hours?"* `hyperliquid_funding_rates` returns one row per hourly settlement. | Hour (UTC) | Funding per year | Accounts short | Paid in that hour | Price | |---|---:|---:|---:|---:| | 20 Sep, 11:00 | 10.95% | 14,990 | $20,212 | 80,314 | | 21 Sep, 08:00 | 10.95% | 14,486 | $22,221 | 81,706 | | 21 Sep, 09:00 | 24.91% | 12,137 | $52,981 | 83,768 | | 21 Sep, 10:00 | 78.64% | 11,693 | $167,486 | 84,651 | For the first 22 hours of that window the rate sat at the same 10.95%. Then the price moved $2,945 in two hours, the count of short accounts fell by 2,793, and the hourly bill for longs went up more than seven times. ### Who was liquidated? > *"Which Hyperliquid markets had the most value liquidated in the last 24 hours, and on which side?"* `hyperliquid_liquidations`, grouped by market: | Market | Liquidations | Longs | Shorts | Value | |---|---:|---:|---:|---:| | BTC | 9,334 | 103 | 9,231 | $92,691,944 | | ETH | 2,234 | 40 | 2,194 | $25,332,321 | | NEAR | 1,299 | 148 | 1,151 | $2,863,062 | | xyz:CL | 316 | 314 | 2 | $2,403,537 | | XRP | 513 | 2 | 511 | $2,322,937 | Longs and Shorts count liquidated long and short positions. The liquidation table tells the same story from the other side. On BTC 98.9% of forced closes were shorts. None of the five markets needed the exchange's backstop, which is the tool's sign of real stress. Without the grouping, the same tool lists single liquidations, newest first. With a $100,000 floor, the newest rows were a run on a third-party market, `xyz:CL`: one account's long position was closed in four fills within three seconds at 10:17 UTC, worth $802,815 together. ### Who made the most on BTC? > *"Who made the most money trading BTC on Hyperliquid in the last 24 hours?"* `hyperliquid_top_traders` with the market set to BTC: | Account | Net result | Volume | Fills | Share as taker | |---|---:|---:|---:|---:| | `0xb1ec7feb...e86a` | $857,387 | $11,676,991 | 385 | 49.9% | | `0xe77cdee1...15db` | $819,890 | $38,134,857 | 1,066 | 10.6% | | `0x4044570e...794c` | $361,813 | $5,814,128 | 266 | 10.2% | | `0xe60dcdf2...7738` | $296,546 | $9,082,225 | 216 | 100% | | `0xb5a6924d...2f82` | $258,300 | $24,013,654 | 1,292 | 100% | Net result is closed profit plus funding minus fees. It leaves out open positions, so a wallet can rank high here and be deep under water on a trade it has not closed. Check the next tool before calling anyone a winner. The same question across the whole exchange, by profit and by volume, is answered in this video: ### What is the top wallet holding now? > *"What positions does 0xb1ec7febea4f841d525785955b7fe0e812d6e86a hold?"* `hyperliquid_trader_positions`, positions above $1 million: | Market | Side | Exposure | Position vs margin | |---|---|---:|---:| | BTC | Long 47.23 BTC | $3,998,475 | 40x | | HYPE | Long 21,298 HYPE | $2,023,857 | 10x | | xyz:SPCX | Short 12,887 | $1,990,058 | not observed | | LINK | Long 104,855 LINK | $1,357,129 | 10x | The day's best BTC account is still long $4.0 million of BTC, a position 40 times its margin. The tool returned no entry price or open profit for these rows. It rebuilds the entry price from the account's own fills, and only when the position was opened from zero inside its month of history and those fills add up to the current size; otherwise it leaves entry price and open profit empty rather than guess. The size is exact either way, because the exchange restates every open perpetual position each hour it charges funding. ## All 18 Hyperliquid tools | Tool | Use it for | |---|---| | `hyperliquid_markets` | List and rank markets, and turn a ticker into a market id | | `hyperliquid_price` | Current price of one market, with the source it came from | | `hyperliquid_candles` | Price bars of 1, 5, 15 or 60 minutes for one market | | `hyperliquid_recent_trades` | The latest fills on a market | | `hyperliquid_open_interest` | Open interest, account split and current funding across perpetuals | | `hyperliquid_funding_rates` | Hourly funding and open interest history of one perpetual | | `hyperliquid_liquidations` | Forced closes, one by one or totalled per market or account | | `hyperliquid_twaps` | Large orders being worked in slices, and how far along they are | | `hyperliquid_top_traders` | Accounts ranked by net result, volume or fills | | `hyperliquid_trader_summary` | One account's scorecard: profit, funding, fees, win rate | | `hyperliquid_trader_positions` | What an account holds now | | `hyperliquid_trader_fills` | An account's fill history with profit and fee per fill | | `hyperliquid_linked_accounts` | Accounts tied together by a shared signing wallet | | `hyperliquid_book_makers` | Which accounts post the resting orders on a market | | `hyperliquid_order_flow` | Orders placed, filled, cancelled and rejected, with the reason | | `hyperliquid_action_rejections` | Rejected account actions such as margin settings and transfers | | `hyperliquid_builders` | Volume and fees of the apps that route orders, and of third-party venues | | `hyperliquid_raw_sql` | Your own SQL over the Hyperliquid tables | ## What to know before you rely on it - **Read-only.** No order placement and no live order book depth. - **About a month of history.** Trades, funding, liquidations, TWAPs and price bars go back about 30 days, and most tools look back up to 720 hours. Order counts come from 10-minute totals kept about 30 days; individual orders are kept about 7 days. Rejected actions go back about 7 days, and the book tool looks back at most 24 hours. For older data, ask about a [Data Store export](https://bitquery.io/datastore). - **Rankings leave out open positions.** Read `hyperliquid_trader_positions` next to any profit ranking. - **Entry price can be empty.** It is rebuilt from the account's fills, so a position opened before the history window, or one whose fills in the window do not add up to its size, has no entry price or open profit. The size of a perpetual position is exact either way. Realized profit and funding per position are sums over the history window, not lifetime, and a spot balance shows only if it was bought inside the window. - **Fills are in execution order.** Inside a block the tools order fills by the exchange's execution index; the trade id is a hash and orders nothing. `hyperliquid_trader_fills` and `hyperliquid_recent_trades` page with the `Cursor` of the last row (`block:index:tid`); a cursor from one tool does not work in the other, and an older `block:tid` cursor is refused. A TWAP slice has no transaction of its own, so its `Tx_Hash` is empty, and `Position_Before` is empty where the fill reports no prior size, as on outcome markets. - **Funding and open interest are hourly.** They come from the hourly settlement, so they can be up to an hour old. - **Pin a market by its id.** Third-party markets carry a prefix such as `xyz:`, spot pairs start with `@` and outcome markets with `#`. One spot pair, `PURR/USDC`, uses its name as the id and is labelled perp. - **No transfer tracing.** The general token, price and wallet-tracing tools do not cover Hyperliquid. It has its own set. ## MCP, GraphQL or the official API? | You want to | Use | |---|---| | Place or cancel orders, read the live book | Hyperliquid's own API | | Ask questions in a chat, or let an agent research markets and wallets | This MCP server | | Build a dashboard, alert or bot in code | The [Bitquery Hyperliquid API](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api/), with WebSocket and Kafka streams | | Load Hyperliquid history into a warehouse | [Parquet exports from the Bitquery Data Store](/docs/cloud/hyperliquid/) | Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-hyperliquid#pricing). --- ## Hyperliquid Mark Prices & Price Updates API URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-prices-api/ Get real-time Hyperliquid mark prices and oracle price updates of HIP-3 builder-deployed markets, like tokenized stocks, with Bitquery GraphQL and WebSocket, and where to get prices for native perps and spot. # Hyperliquid Mark Prices & Price Updates API **In short:** the Hyperliquid mark price is what the exchange uses for margin, liquidations, TP/SL triggers and unrealized PnL. It updates about every 3 seconds and is the median of three prices: 1. The oracle price plus a 150-second EMA of (Hyperliquid mid price − oracle price) 2. The median of best bid, best ask and last trade on Hyperliquid 3. A weighted median of Binance, OKX, Bybit, Gate and MEXC perp mid prices That formula is for native perps. **HIP-3 markets** (builder-deployed perps such as tokenized stocks, commodities and indices) get their oracle and mark price inputs from the market's deployer. This page covers the `MarkPrices` and `PriceUpdates` cubes: the current mark price, and the oracle / mark price feed behind it. **Both carry HIP-3 markets only.** For native perps, spot and outcome markets, take the price from [Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api#ohlcv-candles) (the last bar's `Close`) or from the latest `Trades`. The oracle, mark and external perp prices of every perp market, native ones included, are also on [`SnapshotMarkets`](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api#open-interest-and-prices-of-every-market), once per snapshot (about every 12.5 minutes). :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Mark prices `MarkPrices` is a **state cube**: one row per HIP-3 market with the latest mark price and the block it was last updated at — tokenized stocks (`mkts:AAPL`, `xyz:GOOGL`), commodities and indices. It is query-only (no subscription); for a live feed, subscribe to `PriceUpdates` with `Kind` `mark`. Run it in the IDE: [Hyperliquid Mark Prices ➤](https://ide.bitquery.io/hyperliquid-mark-prices) ```graphql query { Hyperliquid { MarkPrices(limit: {count: 100}, orderBy: {descending: LastTime}) { LastBlock LastTime Mark Market { Symbol Kind IsPerp Protocol CoinRaw } } } } ``` Get one market with `where: {Market: {CoinRaw: {is: "xyz:AAPL"}}}`. Filter on `CoinRaw`, not `Symbol`: the same symbol is listed by several deployers (`xyz:AAPL`, `km:AAPL`, `mkts:AAPL`), and `Symbol: "BTC"` here matches HIP-3 BTC markets, not the native BTC perp. A deployer keeps publishing a mark for markets that no longer trade, so a fresh `LastTime` does not mean the market is active — check `Trades` or `Candles` for that. ## Price updates `PriceUpdates` is the event feed the mark prices are built from: every HIP-3 oracle update, one row per market and price kind. `Kind` is `oracle`, `mark` or `extPerp` for the resulting prices, and `markInput`, `spotInput` or `extPerpInput` for the inputs the deployer submitted; `DailyPx` carries the daily reference price when present. `UpdateClass` is `Normal` for prices the deployer pushes and `Fallback` for fallback updates; whole deployer DEXes (for example `hyna`, `flx`, `km`) are currently priced through fallback updates only. Run it in the IDE: [Hyperliquid Price Updates Stream ➤](https://ide.bitquery.io/hyperliquid-price-updates-stream) ```graphql subscription { Hyperliquid { PriceUpdates { Block { Time } PriceUpdate { Kind Price DailyPx UpdateClass UpdateTime Market { Symbol Kind } } } } } ``` The same shape works as a `query` with `limit`, `orderBy: {descending: Block_Time}` and a `where` filter for historical lookups, for example `where: {PriceUpdate: {Kind: {is: "mark"}, Market: {CoinRaw: {is: "xyz:AAPL"}}}}`. API history goes back about 30 days (for older data, ask about a [Data Store export](https://bitquery.io/datastore)); a query without a `Block: {Time: ...}` filter covers the last 24 hours. For tradeable OHLCV rather than oracle prices, and for markets outside HIP-3, use [Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api#ohlcv-candles): 1-minute, 5-minute, 15-minute and 1-hour bars built from taker fills, where `Open` and `Close` are the first and last fill of the bar in execution order. --- ## Hyperliquid Order Book API (L3) — Market-by-Order Data with Trader Attribution URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-orders-api/ Stream Hyperliquid's order book at L3 (market-by-order) granularity: every order delta carries its own order id and the wallet address behind it. Covers order lifecycle, book deltas and TWAPs over GraphQL and WebSocket. # Hyperliquid Order Book API (L3) Get the full Hyperliquid order book at order level, with the order id and wallet behind every change. This page covers the `Orders`, `BookUpdates` and `Twaps` cubes: the full order lifecycle, order-book deltas you can rebuild the book from, and TWAP order execution. :::info Data window `Orders` and `BookUpdates` keep a rolling **~7 days** of row-level data on the API; `Twaps` and `Trades` keep ~30 days. A query for an older date returns `[]` with HTTP 200, not an error. [Data Store exports](/docs/cloud/hyperliquid/) carry order and book updates older than the API window; the [Blockchain Data Lake](/docs/data-lake/#hyperliquid) holds the raw HyperCore feed from 17 July 2026, which you decode and parse your own way. Per-cube windows: [Data Coverage & Retention](/docs/graphql/data-coverage-retention/#hyperliquid). ::: ## L2 vs L3: what you get here Most order-book feeds — including Hyperliquid's own public `l2Book` websocket channel and the L2 snapshots in its `s3://hyperliquid-archive` bucket — are **L2**: resting size aggregated per price level. You see that 40 BTC sits at $95,000. You cannot see whether that is one order or twenty, whose it is, or which one was pulled a moment later. `BookUpdates` is **L3 (market-by-order)**. Every delta is a single order, and it carries: | | L2 (aggregated) | L3 (market-by-order) — Bitquery | | --- | --- | --- | | Grain | Total size per price level | One event per individual order | | Order identity | — | `Oid`, joinable to `Orders` and `Trades` | | Who placed it | — | `Trader { Address }` — the wallet itself | | Size change | Net level change only | `Size` and `SizeBefore` on that specific order | | Depth | Hyperliquid's `l2Book` returns 5–20 levels | Unlimited | Because Hyperliquid settles on a transparent L1, the wallet behind each order is public. That makes this L3 **with named attribution** — something that does not exist on centralised venues, where L3 feeds are anonymised by the exchange. Hyperliquid's own API exposes order-level detail only per address (`orderUpdates`, `userFills` for an address you already know, at most 10 users per IP); market-wide, it serves aggregated L2. This is what makes wallet-level analysis possible: watching a market maker quote and pull, reconstructing a trader's full order flow rather than just their fills, or spotting orders that were never intended to trade. See [Track Hyperliquid Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet) for worked examples. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Set the time window A query on `Orders` or `BookUpdates` without a `Block: {Time: ...}` filter covers only the last 30 minutes — set the window explicitly for anything longer, and add a market filter (`Market: {CoinRaw: ...}`) when you look back more than an hour or two. ::: ## Order updates Every order event carries `Status`, `OrderType` (`Limit`, `Market`, `Stop Market`, `Stop Limit`, `Take Profit Market`, `Take Profit Limit`, `Trailing Stop Market`), time-in-force `Tif` (`Alo`, `Ioc`, `Gtc`, `FrontendMarket`, `LiquidationMarket`; empty on a trigger order that has not fired), the limit price, the current and original size, and trigger settings for conditional orders. `Status` is `open`, `filled`, `canceled`, `triggered`, or a specific reason such as `badAloPxRejected`, `iocCancelRejected`, `perpMarginRejected`, `reduceOnlyCanceled` or `selfTradeCanceled`. `IsReject` is `true` on every rejected status — rejects are a large share of the feed, and public APIs drop them. Run it in the IDE: [Hyperliquid Recent Orders ➤](https://ide.bitquery.io/hyperliquid-recent-orders) ```graphql query { Hyperliquid { Orders( limit: {count: 50} orderBy: {descending: [Block_Time, Order_Index]} where: {Block: {Time: {since_relative: {minutes_ago: 1}}}} ) { Block { Time } Order { Market { Symbol Kind } Index Oid Status IsReject OrderType Tif Side LimitPx Size OrigSz IsTrigger TriggerPx TriggerCondition ReduceOnly Cloid Trader { Address } } } } } ``` - `Oid` links order events to fills (`Trade.Execution.Oid`) and book updates (`BookUpdate.Oid`); `Cloid` is the client-assigned order id. - `Index` is the status update's place in its block, from 1. All updates of a block share `Block.Time` (and `EventTime`), so `Index` is the only way to put them in order — for example several statuses of one order in the same block. Rows written before about 09:40 UTC on 2026-10-13 have `Index` 0. - `Size` is the remaining size, `OrigSz` the original size. - `IsTrigger`, `TriggerPx`, `TriggerCondition` describe stop / take-profit orders; `IsPositionTpsl` marks position-attached TP/SL. ### Real-time order stream Run it in the IDE: [Hyperliquid Orders Stream ➤](https://ide.bitquery.io/hyperliquid-orders-stream) ```graphql subscription { Hyperliquid { Orders(where: {Order: {Market: {Symbol: {is: "ETH"}}}}) { Block { Time } Order { Market { Symbol } Index Oid Status OrderType Tif Side LimitPx Size OrigSz IsTrigger ReduceOnly Trader { Address } } } } } ``` ## Order book updates `BookUpdates` streams **deltas of the on-chain order book**, one per order. `Kind` is `new` (order added to the book), `update` (its resting size changed, e.g. a partial fill) or `remove` (order left the book: canceled or fully filled); with `Px`, `Size` (size after the change, empty on `remove`), `SizeBefore` (on `update`), the order `Oid` and the trader behind the order. Consume the stream and apply the deltas in `(Block.Number, Index)` order to maintain a live book — `Index` is the delta's place in its block, and every delta of a block shares `Block.Time`. Run it in the IDE: [Hyperliquid Order Book Stream ➤](https://ide.bitquery.io/hyperliquid-orderbook-stream) ```graphql subscription { Hyperliquid { BookUpdates(where: {BookUpdate: {Market: {Symbol: {is: "BTC"}}}}) { Block { Number Time } BookUpdate { Index Kind Side Px Size SizeBefore Oid Market { Symbol } Trader { Address } } } } } ``` This is the L3 grain described above: unlike an aggregated L2 feed, each delta is attributable to an **individual order and trader address** — you can watch a specific market maker's quoting in real time by filtering on `BookUpdate: {Trader: {Address: {is: "0x..."}}}`. ### The whole book at a snapshot `SnapshotOrders` lists the entire book, order by order with its owner and its place in the queue (`QueuePosition`), at each [snapshot](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api#order-book-walls-and-their-owners), about every 12.5 minutes, kept 7 days: a starting point for a book you then keep with `BookUpdates`. It also lists every **waiting trigger order** (`IsTrigger: true`), stop-losses and take-profits that are not in the book yet and so never appear in `BookUpdates` until they fire. See the [stop-loss and take-profit map](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api#stop-loss-and-take-profit-map). ## TWAP orders `Twaps` tracks the lifecycle of TWAP orders: `State.Status` moves from `activated` (or `waitingForTrigger`) to `finished`, `terminated`, `stopped` or `error` (`StatusError` carries the reason), with executed size and notional so far. Run it in the IDE: [Hyperliquid TWAP Orders ➤](https://ide.bitquery.io/hyperliquid-twap-orders) ```graphql query { Hyperliquid { Twaps(limit: {count: 50}, orderBy: {descending: Block_Time}) { Block { Time } Twap { TwapId Market { Symbol } Order { Side Size ReduceOnly Randomize } Interval { DurationMinutes StartTime EventTime } State { Status StatusError ExecutedSize ExecutedNotional } Trader { Address } } } } } ``` `TwapId` matches `Trade.TwapId` on fills with `IsTwap: true`, so you can join a TWAP to its individual child fills. [Hyperliquid TWAP Orders & Child Fills](/docs/perpetuals/hyperliquid/hyperliquid-twap-fills) walks through that join, with per-wallet TWAP history and an execution summary. ## Related - [Track Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet) — market-maker tracking with L3 data - [Snapshots API](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api) — the full book with owners and every waiting trigger order at each snapshot - [TWAP Orders & Child Fills](/docs/perpetuals/hyperliquid/hyperliquid-twap-fills) - [HIP-3 Stocks API](/docs/perpetuals/hyperliquid/hip3-stocks-api) — order book for stock and commodity perps --- ## Hyperliquid Prediction Markets API — HIP-4 Outcome Markets, Prices, Trades and Holders URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-prediction-markets-api/ Query Hyperliquid prediction markets (HIP-4 outcome markets) with Bitquery: market names and answers, side prices as probabilities, the top markets by volume, live trades and the holders of each side over GraphQL and WebSocket. # Hyperliquid Prediction Markets API Hyperliquid prediction markets (HIP-4 outcome markets, `Market.Kind` `outcome`) trade on the same order book as spot. Each side of a market (`Yes` or `No`) is a market of its own, priced between 0 and 1: the price of a side reads as the market's probability of it. Every Bitquery cube with a `Market` names them under `Market { Outcome { ... } }` — the headline, the answer and the side — so a trade on `#14730` arrives as `2026/2027 English Premier League winner`, answer `Arsenal`, side `Yes`. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Two kinds of prediction market - A **standalone outcome** is one Yes / No market with no question, such as `BTC above 78521 at 2026-10-31 06:00 UTC?`. - A **question** has several answers, each an outcome with its own Yes / No market, plus a fallback answer, `Other`, that wins when no named answer does: `2026/2027 English Premier League winner` → `Arsenal`, …, `Other`. Each side is a separate market, `CoinRaw` `#` with `n = 10 × OutcomeId + Side`, so a standalone outcome is two markets and a question with three answers is eight (three answers and `Other`, two sides each). `Market.Outcome.Headline` names the market as a whole, whichever kind it is, so **group by `Headline`** to add up both sides and every answer: | Field | Standalone outcome | Answer of a question | | --- | --- | --- | | `Outcome.Headline` | `BTC above 77970 at 2026-10-30 06:00 UTC?` | `2026/2027 English Premier League winner` | | `Outcome.Title` | same as `Headline` | `Arsenal` (`Other` for the fallback) | | `Outcome.SideTitle` | `Yes` / `No` | `Yes` / `No` | | `Outcome.Question.Title` | empty: there is no question | same as `Headline` | ## Outcome fields | Field | Meaning | | --- | --- | | `Headline` | the market as a whole: a standalone outcome's `Title`, or the question's `Question.Title` | | `Title` | the outcome: a standalone outcome's text, or the answer of a question (`Arsenal`, `Other`) | | `SideTitle` | the side's display name: `Yes` / `No`, `Over` / `Under`, a team abbreviation (`LAR` / `LAC`) | | `OutcomeId`, `Side` | outcome id and side, `0` or `1`; the first side is `Side` `0` | | `SiblingCoin` | the other side of the same outcome, `#` | | `Name`, `Description`, `SideName` | raw fields (`template:sportsTournamentParticipant`, `participant:Arsenal`) the titles are built from | | `Question { QuestionId Title Name Description IsFallback IsSettled }` | the question the outcome answers; empty for a standalone outcome. `IsFallback` marks `Other`, `IsSettled` an answer already settled | `Market { Outcome }` is on `Trades`, `Orders`, `BookUpdates`, `Twaps`, `SnapshotMarkets`, `SnapshotOrders` and the other cubes with a `Market`. `Candles` and `CurrentPositions` have no `Outcome` fields: query them by `Market.CoinRaw`. ## Top prediction markets by volume Every fill is recorded twice, once for the buyer and once for the seller, so count volume and fills on the taker side only (`IsAggressor: true`). Without a `Block.Time` filter, `Trades` covers the last 24 hours. ```graphql query { Hyperliquid { Trades( where: {Trade: {Market: {Kind: {is: "outcome"}, Outcome: {Headline: {not: ""}}}}} orderBy: {descendingByField: "volumeUsd"} limit: {count: 20} ) { Trade { Market { Outcome { Headline Question { QuestionId Title } } } } volumeUsd: sum(of: Trade_Execution_NotionalUSD, if: {Trade: {Execution: {IsAggressor: true}}}) fills: count(if: {Trade: {Execution: {IsAggressor: true}}}) traders: uniq(of: Trade_Trader_Address) } } } ``` Add `Title` and `SideTitle` under `Outcome` to split each market by answer and side. ## Every open market with its prices `SnapshotMarkets` lists every market at the latest [snapshot](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api), about every 12.5 minutes. One row per outcome, its first side, with the best bid and ask and the last trade price: ```graphql query { Hyperliquid { SnapshotMarkets( where: {Market: {Kind: {is: "outcome"}, Outcome: {Side: {eq: 0}}}} limit: {count: 1000} ) { Block { Time } Market { CoinRaw Outcome { Headline Title SideTitle SiblingCoin Question { QuestionId IsFallback IsSettled } } } Book { BestBid BestAsk LastTradePx Orders } } } } ``` ## The answers of one market and their odds All answers and sides of one question, with prices. The midpoint of `BestBid` and `BestAsk` of a `Yes` side is the market's probability of that answer. ```graphql query { Hyperliquid { SnapshotMarkets( where: {Market: {Outcome: {Headline: {is: "2026/2027 English Premier League winner"}}}} ) { Block { Time Number } Market { CoinRaw Outcome { OutcomeId Side Title SideTitle Question { QuestionId IsFallback IsSettled } } } Book { BestBid BestAsk LastTradePx Orders } } } } ``` For the price history of an answer, use `Candles` with `Market: {CoinRaw: {is: "#..."}}`, the code of its side from this query. Add `Block: {Time: {since_relative: {days_ago: 3}}}` to the filter above for the odds at every snapshot of the last three days. ## Trades of one side ```graphql query { Hyperliquid { Trades( where: {Trade: {Market: {CoinRaw: {is: "#14730"}}, Execution: {IsAggressor: true}}} orderBy: {descending: [Block_Time, Trade_Execution_Index]} limit: {count: 50} ) { Block { Time } Trade { Market { CoinRaw Outcome { Headline Title SideTitle } } Execution { Price Size Side NotionalUSD } Trader { Address } } } } } ``` Market codes come and go as outcomes are listed and settled; take a current one from the queries above. ## Live prediction market trades ```graphql subscription { Hyperliquid { Trades(where: {Trade: {Market: {Kind: {is: "outcome"}}, Execution: {IsAggressor: true}}}) { Block { Time } Trade { Market { CoinRaw Outcome { Headline Title SideTitle } } Execution { Price Size Side NotionalUSD } Trader { Address } } } } } ``` ## Holders of a side A holding of a side is a spot balance of the side's token, `+` for market `#`, so its holders are in `SnapshotBalances`. One system address holds a negative balance equal to the whole supply; keep `Total` above zero. ```graphql query { Hyperliquid { SnapshotBalances( where: {Token: {is: "+14730"}, Total: {gt: "0"}} orderBy: {descending: Total} limit: {count: 50} ) { Block { Time } Trader { Address } Total EntryNotional } } } ``` `Total` is the number of contracts. `EntryNotional / Total` is the holder's average entry price, and `Total × price − EntryNotional` its unrealized PnL at the side's current price. The resting orders on a side, with their owners, are in `SnapshotOrders` with `Market: {CoinRaw: {is: "#14730"}}`. ## Pitfalls - **Two rows per fill.** Every fill has a buyer row and a seller row: count volume, fills and trades with `IsAggressor: true`, or you double them. - **Side names differ.** Not every market is `Yes` / `No`: sports markets use team abbreviations, others `Over` / `Under`. Use `Side` (`0` or `1`) when you need the position of a side, and `SideTitle` to show it. - **Complete sets.** Buying or selling both sides of an outcome at once produces one fill per side, under the two sibling markets, with the two prices summing to 1. - **Perp fields are empty.** `Prices`, `Margin` and `OpenInterest` on `SnapshotMarkets` are perp-only; take the price of a side (0 to 1) from `Book` or from its trades. ## Related - [Snapshots API](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api) — the snapshots behind `SnapshotMarkets`, `SnapshotBalances` and `SnapshotOrders` - [Trades & Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) - [Order Book API (L3)](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) - [Hyperliquid API overview](/docs/perpetuals/hyperliquid) --- ## Hyperliquid Signed Actions API URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-signed-actions-api/ Query and stream signed L1 actions on Hyperliquid with Bitquery: rejected actions with their error, modify, batchModify, updateLeverage, transfers and more, with signer, broadcaster, bundle hash and status. # Hyperliquid Signed Actions API `SignedActions` is the lowest-level Hyperliquid cube: **signed user actions** as the L1 consensus recorded them, with the key that signed each one. It holds every **rejected** action (with the error) and every accepted action except order placements and cancels (`order`, `cancel`, `cancelByCloid`) and `noop` — placements and cancels appear with more structure in [`Orders`](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) and `Trades`. Modifies, leverage updates, scheduled cancels, transfers, agent approvals, TWAP orders and the rest stay here. API history goes back about **7 days**. For older data, ask about a [Data Store export](https://bitquery.io/datastore). The query and the subscription serve this filtered view; the Kafka topic `hyperliquidcore.messages.proto` carries every signed action, accepted orders and cancels included. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Latest signed actions Run it in the IDE: [Hyperliquid Signed Actions ➤](https://ide.bitquery.io/hyperliquid-signed-actions) ```graphql query { Hyperliquid { SignedActions( limit: {count: 50} orderBy: {descending: Block_Time} where: {Block: {Time: {since_relative: {minutes_ago: 10}}}} ) { Block { Number Time } ActionType Status User Signer Nonce VaultAddress Bundle { Hash Broadcaster ActionIndex } Leverage { Asset Value IsCross } } } } ``` Field notes: - `ActionType` — the action name as submitted: `batchModify`, `modify`, `scheduleCancel`, `updateLeverage`, `updateIsolatedMargin`, `twapOrder`, `approveAgent`, `spotSend`, `evmRawTx` and other Hyperliquid exchange actions. `order` and `cancel` appear only when rejected. - `User` vs `Signer` — `User` is the account the action applies to; `Signer` is the key that signed it, which differs when an **agent / API wallet** acts for the account. `VaultAddress` is set for vault-scoped actions. - `Bundle` — actions arrive in broadcast bundles; `Hash` is the bundle hash, `Broadcaster` the node that broadcast it, `ActionIndex` the action's position in the bundle. - `Status` — `ok` for accepted actions, `err` for rejected ones; `Response` (raw string field) carries the node response — the error text when `Status` is `err`, for example `"Invalid leverage value"`. - `Action` — the raw action payload as a JSON string, when you need parameters beyond the typed fields. - `Leverage { Asset Value IsCross }` is populated for accepted `updateLeverage` actions; `Asset` is Hyperliquid's numeric asset index (`0` is BTC). Filter examples: - One account's activity: `where: {User: {is: "0x..."}}` - Only leverage updates: `where: {ActionType: {is: "updateLeverage"}}` - Failed actions: `where: {Status: {is: "err"}}` As with the other Hyperliquid event cubes, changing `query` to `subscription` (and dropping `limit`/`orderBy`) turns this into a real-time WebSocket stream — useful for monitoring an account's or broadcaster's full action flow live. ## Related - [Track Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet) — the order lifecycle behind a wallet's actions - [TWAP Orders & Child Fills](/docs/perpetuals/hyperliquid/hyperliquid-twap-fills) — what a `twapOrder` action produces - [Funding Payments by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-funding-payments-api) - [Liquidation History by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-liquidation-history-by-wallet) --- ## Hyperliquid Snapshots API — Every Position, Order, Balance and Vault on the Exchange URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api/ Query the full Hyperliquid exchange state with Bitquery: every open position with entry price, leverage and unrealized PnL, the order book with owners, waiting stop orders, spot balances, accounts, vaults and Earn, for all accounts at once, every ~12.5 minutes over the last 7 days. # Hyperliquid Snapshots API About every **12.5 minutes**, Bitquery takes a snapshot of the full Hyperliquid exchange state and serves it through eleven `Snapshot*` cubes: every open position with its entry price, leverage, margin and unrealized PnL, every account, every resting order with its owner, every waiting stop and take-profit order, every spot balance, every leverage setting, every vault with its depositors, and Earn. All accounts at once, kept for **7 days**. Hyperliquid's own info API returns this state one address at a time (`clearinghouseState`, `openOrders`, `spotClearinghouseState`), so you have to know the address first. Snapshots answer the market-wide questions: who holds the biggest positions and at what entry, how the crowd is positioned against the whales, where the stops sit, who owns the walls in the book, who holds a token. :::info Window and update rate Snapshots are kept for about **7 days**. A new snapshot appears about every 12.5 minutes. The cubes are **query-only**: there is no subscription, so poll at that pace and compare `Block.Number` to see whether a new snapshot has arrived. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## The snapshot cubes | Cube | One row per | Use it for | | --- | --- | --- | | `Snapshots` | snapshot | the list of snapshots in the window: `Block { Number Time }` | | `SnapshotMarkets` | market | mark, oracle and external perp prices, best bid and ask, last trade, open interest, number of positions, margin tiers, halts, prediction market names | | `SnapshotPositions` | open perp position (trader × market) | side, size, entry price, leverage, margin, position value, unrealized PnL, cumulative funding | | `SnapshotAccounts` | account × perp dex | account value, margin used, maintenance margin, notional, number of positions | | `SnapshotOrders` | resting order or waiting trigger order | the order book with owners (L4), queue position, stop-loss and take-profit orders | | `SnapshotBalances` | non-zero spot balance (trader × token) | token holders, spot portfolios, entry notional | | `SnapshotLeverageSettings` | trader × perp market the trader touched | leverage and margin mode set, and what the next trade gets | | `SnapshotVaults` | vault | name, leader, equity, number of followers, commission, parent and child vaults | | `SnapshotVaultFollowers` | depositor × vault | share, equity, net deposit, all-time PnL, lockup | | `SnapshotEarnReserves` | Earn token | supplied, borrowed, utilization, rate model | | `SnapshotEarnPositions` | trader × Earn token | supply and borrow, basis and value | A vault trades as its own account: its positions, margin and orders are the rows whose `Trader.Address` is the vault address, and `IsVault: true` marks them. ## Which snapshot a query reads The time filter on `Block.Time` decides which snapshots answer: | Filter | Reads | | --- | --- | | no `Block.Time` filter | the **latest** complete snapshot | | `Block: {Time: {at: "..."}}` with a time in the last 7 days | the latest complete snapshot at or before that time: the state at that moment | | `Block: {Time: {since: "...", till: "..."}}` (or any other range) | **every** complete snapshot in the range: a history | A query only ever sees complete snapshots. All rows of one snapshot share `Block.Number` and `Block.Time`, so add `Block { Number Time }` to know which one answered. A `Block.Number` filter narrows what `Block.Time` selected: on its own it meets only the latest snapshot, so for an older height add `Time` too, or use `at`. List the snapshots of the last few hours: ```graphql query { Hyperliquid { Snapshots( where: {Block: {Time: {since_relative: {hours_ago: 3}}}} orderBy: {descending: Block_Time} ) { Block { Number Time } } } } ``` ## Biggest positions with entry price and unrealized PnL The largest positions on BTC by value, long and short, with entry price, leverage, margin mode, unrealized PnL and the funding paid since the position was opened. `Position.Size` is signed (negative = short), so rank by `Valuation.PositionValue`, the position's USD value at the snapshot's mark price. ```graphql query { Hyperliquid { SnapshotPositions( where: {Market: {CoinRaw: {is: "BTC"}}} orderBy: {descending: Valuation_PositionValue} limit: {count: 20} ) { Block { Number Time } Trader { Address } IsVault Position { Side Size EntryPrice Leverage IsCross } Valuation { EntryNotional PositionValue UnrealizedPnl MarkPx } CumFunding { SinceOpen AllTime } Margin { MarginUsed MaintenanceMargin } } } } ``` - `CumFunding` is positive when the account **paid** funding and negative when it received it: the opposite sign to `Funding.Amount` on `PerpFundings`. - `Position.Leverage` is the leverage of the position, so grouping by it shows how leveraged a market is. `SnapshotLeverageSettings` is the per-account setting, including markets with no open position. - Filter `Position: {Side: {is: "Short"}}` for the shorts alone, or `Trader: {Address: {is: "0x..."}}` for one account. ## Crowd vs whales: the long / short split of a market Group the positions of one market by side: how many accounts are long and short, the total size and value of each side, and their unrealized PnL. A side with most of the accounts but a smaller share of the value is the crowd; the other is where the large positions are. ```graphql query { Hyperliquid { SnapshotPositions(where: {Market: {CoinRaw: {is: "BTC"}}}) { Position { Side } positions: count size: sum(of: Position_Size) value: sum(of: Valuation_PositionValue) upnl: sum(of: Valuation_UnrealizedPnl) } } } ``` The same split over time: with a `since` filter every snapshot answers, and grouping by `Block.Time` gives one row per snapshot. ```graphql query { Hyperliquid { SnapshotPositions( where: {Market: {CoinRaw: {is: "BTC"}}, Block: {Time: {since_relative: {days_ago: 3}}}} orderBy: {ascending: Block_Time} limit: {count: 2000} ) { Block { Time } longs: count(if: {Position: {Side: {is: "Long"}}}) shorts: count(if: {Position: {Side: {is: "Short"}}}) longValue: sum(of: Valuation_PositionValue, if: {Position: {Side: {is: "Long"}}}) shortValue: sum(of: Valuation_PositionValue, if: {Position: {Side: {is: "Short"}}}) } } } ``` ## Open interest and prices of every market `SnapshotMarkets` has one row per market: prices, the top of the book, open interest and the number of open positions. ```graphql query { Hyperliquid { SnapshotMarkets( where: {Market: {IsPerp: true}} orderBy: {descending: Positions} limit: {count: 50} ) { Block { Number Time } Market { Symbol CoinRaw Kind Protocol MaxLeverage } Prices { MarkPx OraclePx ExternalPerpPx } Book { BestBid BestAsk LastTradePx Orders } OpenInterest Positions IsHalted } } } ``` - **`OpenInterest` counts both sides**: it is longs plus shorts, in coins (the sum of the absolute size of every position), so it is twice the open interest of one side. Divide by 2 for the figure most venues quote, and multiply by `Prices.MarkPx` for USD. - `Margin`, `Prices` and `OpenInterest` are perp-only (native and HIP-3) and empty on spot and prediction markets. - `Margin { Tiers { LowerBound MaxLeverage MaintenanceDeduction } }` are the margin tiers: from `LowerBound` of position notional (USD) on, `MaxLeverage` applies. ## Stop-loss and take-profit map Waiting trigger orders (`IsTrigger: true`) are not in the public book, so no L2 feed shows them. In a snapshot every one is listed with its owner: where the stops and take-profits of a market sit, and whose they are. ```graphql query { Hyperliquid { SnapshotOrders( where: {Market: {CoinRaw: {is: "BTC"}}, IsTrigger: true, TriggerPx: {ge: "70000", le: "85000"}} orderBy: {descending: Size} limit: {count: 1000} ) { Block { Time } Trader { Address } Side OrderType TriggerPx TriggerCondition LimitPx Size OrigSz IsPositionTpsl ReduceOnly } } } ``` - `TriggerCondition` is text (`Price below 76000`); filter and sort on `TriggerPx`, the number. - A position TP/SL (`IsPositionTpsl: true`) closes the whole position, so its `Size` is `0`: take the size from the owner's position in `SnapshotPositions`. - Group by `TriggerPx` and `Side` with `count` and `sum(of: Size)` for a histogram of stop levels; position TP/SLs add to the count but not to the size. ## Order book walls and their owners Resting orders (`IsTrigger: false`) are the book at the snapshot, order by order, with the owner of each. The largest orders on each side: ```graphql query { Hyperliquid { SnapshotOrders( where: {Market: {CoinRaw: {is: "BTC"}}, IsTrigger: false} orderBy: {descending: Size} limit: {count: 50} ) { Block { Time } Trader { Address } IsVault Side LimitPx Size OrigSz OrderType Tif QueuePosition PlacedTime Oid } } } ``` `Side` is `Buy` (bid) or `Sell` (ask); `Size` is what remains, `OrigSz` what was placed. `QueuePosition` is the order's place at its price level, `1` being filled first. `PlacedTime` is epoch milliseconds. Between snapshots, follow the same orders by `Oid` on the [Orders and BookUpdates cubes](/docs/perpetuals/hyperliquid/hyperliquid-orders-api). ## Token holders `SnapshotBalances` lists every non-zero spot balance. The largest HYPE holders: ```graphql query { Hyperliquid { SnapshotBalances( where: {Token: {is: "HYPE"}} orderBy: {descending: Total} limit: {count: 100} ) { Trader { Address } Total Hold EntryNotional } } } ``` `Hold` is the part of `Total` locked in open orders; `EntryNotional` is the USDC paid for `Total`, so `EntryNotional / Total` is the average entry. There is no USD value: Hyperliquid publishes none. System addresses (`0x2222…2222`, `0xfefe…fefe`) can top the list. `count` with no other fields gives the number of holders. ## Vaults: equity, followers and positions ```graphql query { Hyperliquid { SnapshotVaults(orderBy: {descending: Summary_Equity}, limit: {count: 25}) { Vault Name Leader Summary { Equity Followers LeaderFraction } Terms { LeaderCommission LockupSeconds AllowDeposits IsClosed } Relationship { Type ChildVaults } } } } ``` The depositors of a vault are in `SnapshotVaultFollowers` (filter `Vault: {is: "0x..."}`: `Trader { Address }`, `IsLeader`, `Share { Fraction Equity NetDeposit AllTimePnl }`, `Times { EntryTime LockupUntil }`), and its open positions are `SnapshotPositions` with the vault address as `Trader.Address`. See the [Vaults API](/docs/perpetuals/hyperliquid/hyperliquid-vaults-api) for vault fills, deposits and liquidations. ## One account: its portfolio at a moment and its history Several cubes can go in one query: the account's margin per dex, its open positions, spot balances and orders at the latest snapshot. For the state at a past moment, add `Block: {Time: {at: "..."}}` with a time from the last 7 days to each cube, so all of them read the same snapshot. ```graphql query { Hyperliquid { SnapshotAccounts( where: {Trader: {Address: {is: "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"}}} ) { Block { Number Time } Protocol Collateral Total { AccountValue MarginUsed TotalNotional } Positions } SnapshotPositions( where: {Trader: {Address: {is: "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"}}} ) { Market { Symbol CoinRaw } Position { Side Size EntryPrice Leverage IsCross } Valuation { PositionValue UnrealizedPnl } } SnapshotBalances( where: {Trader: {Address: {is: "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"}}} ) { Token Total EntryNotional } SnapshotOrders( where: {Trader: {Address: {is: "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"}}} ) { Market { CoinRaw } Side OrderType LimitPx TriggerPx Size IsTrigger } } } ``` The native exchange (`Protocol` `hypercore`) and each HIP-3 dex keep separate margin, each in its own `Collateral` token, so an account has one `SnapshotAccounts` row per dex. `Total` is the account's margin summary, `Cross` the cross-margin part. The account value over the last week, one point per snapshot: ```graphql query { Hyperliquid { SnapshotAccounts( where: {Trader: {Address: {is: "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"}}, Protocol: {is: "hypercore"}, Block: {Time: {since_relative: {days_ago: 7}}}} orderBy: {ascending: Block_Time} limit: {count: 1000} ) { Block { Time } Total { AccountValue MarginUsed TotalNotional } Positions } } } ``` The account's vault shares are in `SnapshotVaultFollowers` and its Earn supply and borrow in `SnapshotEarnPositions`, both filtered by `Trader: {Address: {is: "0x..."}}`. ## Earn: supply, borrow and utilization ```graphql query { Hyperliquid { SnapshotEarnReserves { Block { Time } Token TotalSupplied TotalBorrowed Utilization Ltv RateModel { BaseRate KinkUtilization MaxRate ProtocolShare } } } } ``` Amounts are in the token. The borrow rate is `BaseRate` up to `KinkUtilization`, then rises linearly to `MaxRate` at full utilization; suppliers earn the borrow rate × `Utilization` × (1 − `ProtocolShare`). ## Snapshots vs CurrentPositions | | `SnapshotPositions` | [`CurrentPositions`](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api#current-positions) | | --- | --- | --- | | Freshness | the state at the latest snapshot, up to ~12.5 minutes old | updated with every fill and hourly funding | | Content | entry price, margin, position value, unrealized PnL, cumulative funding over the position's life | size, leverage, margin mode; funding and realized PnL summed over the data window | | History | every snapshot of the last 7 days, or the one at a moment | the latest state only | | Sorting by size | numeric | `Size` sorts as text | Use snapshots for the full state and its history, and the event cubes (`Trades`, `Orders`, `PerpLiquidations`) for what happened between two snapshots. ## Pitfalls - **Open interest is doubled.** `SnapshotMarkets.OpenInterest` adds longs and shorts; one side is half of it. - **Shorts are negative.** `Position.Size` is signed; sort by `Valuation.PositionValue` to rank by size, and do not sum `Position.Size` across both sides expecting open interest. - **Ranges multiply rows.** A `since` filter returns every snapshot in it, about 115 a day: aggregate (`count`, `sum`) per `Block.Time`, or use `at` for one moment. - **Only the address.** Snapshots carry the trader's address alone: `Trader { Signer Vault Broadcaster SignedAt }` are not available, except on `SnapshotOrders`, where they come from Bitquery's order attribution and can be empty. - **No liquidation price.** Positions carry margin and maintenance margin, but not the liquidation price or the withdrawable amount. - **Numbers are strings** at native precision, but filters, sorting and sums on them are numeric. - **Timestamps.** `Block.Time` is a date-time; the other time fields are raw epoch integers: `PlacedTime` in milliseconds, `CreateTime`, `Prices.UpdateTime`, `UpdateTime` and `Times.*` in nanoseconds. - **No subscription, 7 days.** Poll about every 12.5 minutes; snapshots older than 7 days are not in the API. ## Related - [Prediction Markets API](/docs/perpetuals/hyperliquid/hyperliquid-prediction-markets-api) — names, prices and holders of HIP-4 outcome markets, from the same snapshots - [Liquidations, Funding, Positions & Leverage](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api) - [Order Book API (L3)](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) - [Vaults API](/docs/perpetuals/hyperliquid/hyperliquid-vaults-api) - [Bitquery vs Hyperliquid's free data](/docs/perpetuals/hyperliquid/vs-hyperliquid-api) --- ## Hyperliquid TWAP Orders & Child Fills URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-twap-fills/ Reconstruct a Hyperliquid TWAP order end to end: the parent order lifecycle and every child fill it produced, joined on TwapId, with size, price, fees and realized PnL. # Hyperliquid TWAP Orders & Child Fills **In short:** a Hyperliquid TWAP splits one large order into suborders sent at a fixed interval (at least 30 seconds apart) over the running time you choose. Each suborder has a 3% max slippage, and if one under-fills, later suborders catch up, up to 3x the normal slice size. With Bitquery you can get every TWAP a wallet placed from the `Twaps` cube, and every fill it produced from `Trades` filtered on `TwapId`. A TWAP on Hyperliquid is one parent order that executes as many small child fills over a set duration. Tools that only read the parent order see a single line; tools that only read fills see dozens of unexplained trades. Neither reconciles. This page joins the two: the `Twaps` cube for the parent order lifecycle, and the `Trades` cube filtered on `TwapId` for every fill it produced. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## TWAP orders of one wallet `State.Status` moves from `activated` (or `waitingForTrigger`) to `finished`, `terminated`, `stopped` or `error` (`StatusError` carries the reason, e.g. `Insufficient margin to place order.`). Each status change is its own record, so a completed TWAP appears at least twice — once on activation with zero executed, once at the end with the final totals. API history goes back about 30 days. For older data, ask about a [Data Store export](https://bitquery.io/datastore). Run it in the IDE: [Hyperliquid Wallet TWAP Orders ➤](https://ide.bitquery.io/hyperliquid-wallet-twap-orders) ```graphql query { Hyperliquid { Twaps( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Twap: { Trader: { Address: { is: "0x3bcae23e8c380dab4732e9a159c0456f12d866f3" } } } Block: {Time: {since_relative: {days_ago: 30}}} } ) { Block { Time } Twap { TwapId Market { Symbol } Order { Side Size ReduceOnly Randomize } Interval { DurationMinutes StartTime } State { Status StatusError ExecutedSize ExecutedNotional } Trader { Address } } } } } ``` Sample response — the same TWAP at activation and at completion: ```json [ { "Block": { "Time": "2026-10-13T09:44:59.578059Z" }, "Twap": { "TwapId": "2311912", "Market": { "Symbol": "SMSN" }, "Order": { "Side": "Sell", "Size": "855.383", "ReduceOnly": true, "Randomize": true }, "Interval": { "DurationMinutes": 30, "StartTime": "1791884699578" }, "State": { "Status": "activated", "ExecutedSize": "0.0", "ExecutedNotional": "0.0" } } }, { "Block": { "Time": "2026-10-13T10:15:01.042325Z" }, "Twap": { "TwapId": "2311912", "Market": { "Symbol": "SMSN" }, "Order": { "Side": "Sell", "Size": "855.383", "ReduceOnly": true, "Randomize": true }, "Interval": { "DurationMinutes": 30, "StartTime": "1791884699578" }, "State": { "Status": "finished", "ExecutedSize": "855.383", "ExecutedNotional": "150042.98774" } } } ] ``` ## Every child fill of one TWAP `TwapId` on the parent matches `Trade.TwapId` on the fills. Filter the `Trades` cube on it to get the complete execution. Only the TWAP owner's side of each fill carries the `TwapId` (the makers on the other side do not), so add the owner's address too — fills are stored by trader, and the wallet filter keeps the query fast over the whole 30 days. Run it in the IDE: [Hyperliquid TWAP Child Fills ➤](https://ide.bitquery.io/hyperliquid-twap-child-fills) ```graphql query { Hyperliquid { Trades( limit: { count: 100 } orderBy: { ascending: [Block_Time, Trade_Execution_Index] } where: { Trade: { TwapId: {eq: "2311912"} Trader: {Address: {is: "0x3bcae23e8c380dab4732e9a159c0456f12d866f3"}} } Block: {Time: {since_relative: {days_ago: 30}}} } ) { Block { Time } Trade { TwapId Market { Symbol } Execution { Price Size Side Direction Index Tid } Fees { Fee FeeToken } Position { Size RealizedPnl } Trader { Address } } } } } ``` `TwapId` is a big integer, so the filter operator is `eq`, not `is`. One slice often fills against several resting orders in the same block, and every fill of a block shares `Block.Time`; `Execution.Index` is the fill's place in the block's execution order, so `[Block_Time, Trade_Execution_Index]` sorts the fills as they happened. `Position.Size` is the owner's position after each fill — for a reduce-only TWAP you can watch it shrink slice by slice. (`Tid` is a fill identifier, not a sequence.) A TWAP can produce more fills than one page holds — TWAP `2311912`, 30 minutes long, has 239. Raise `limit` or page through with `offset` when you need every one of them. ## TWAP execution summary Aggregate the child fills to reconcile against the parent order's `ExecutedSize` and `ExecutedNotional`. Run it in the IDE: [Hyperliquid TWAP Execution Summary ➤](https://ide.bitquery.io/hyperliquid-twap-execution-summary) ```graphql query { Hyperliquid { Trades( where: { Trade: { TwapId: {eq: "2311912"} Trader: {Address: {is: "0x3bcae23e8c380dab4732e9a159c0456f12d866f3"}} } Block: {Time: {since_relative: {days_ago: 30}}} } ) { Trade { TwapId Market { Symbol } } fills: count filled: sum(of: Trade_Execution_Size) avgPrice: average(of: Trade_Execution_Price) fees: sum(of: Trade_Fees_Fee) pnl: sum(of: Trade_Position_RealizedPnl) } } } ``` For TWAP `2311912` this returns 239 fills totalling exactly the 855.383 size on the parent order, with 8.10 USDC of fees and 2,906.85 of realized PnL. That reconciliation — parent `ExecutedSize` equals the sum of child fill sizes — is the check most exports fail. `average` is the plain mean of fill prices (175.406 here); the size-weighted price is the parent's `ExecutedNotional / ExecutedSize` (175.410). ## All TWAP fills of a wallet To pull every TWAP-produced fill for an address without going TWAP by TWAP, filter on `IsTwap` instead. Run it in the IDE: [Hyperliquid Wallet TWAP Fills ➤](https://ide.bitquery.io/hyperliquid-wallet-twap-fills) ```graphql query { Hyperliquid { Trades( limit: { count: 100 } orderBy: { descending: [Block_Time, Trade_Execution_Index] } where: { Trade: { IsTwap: true Trader: { Address: { is: "0x3bcae23e8c380dab4732e9a159c0456f12d866f3" } } } Block: {Time: {since_relative: {days_ago: 30}}} } ) { Block { Time } Trade { TwapId Market { Symbol } Execution { Price Size Side Direction Index Tid } Fees { Fee FeeToken } Position { Size RealizedPnl } } } } } ``` ## Real-time TWAP stream Run it in the IDE: [Hyperliquid TWAP Orders Stream ➤](https://ide.bitquery.io/hyperliquid-twap-orders-stream) ```graphql subscription { Hyperliquid { Twaps { Block { Time } Twap { TwapId Market { Symbol } Order { Side Size ReduceOnly Randomize } State { Status ExecutedSize ExecutedNotional } Trader { Address } } } } } ``` ## Notes - `Order.Randomize` indicates the TWAP randomises its slice sizes (by up to ±20%), which is why child fills are uneven. - `Interval.DurationMinutes` is the configured TWAP length; `StartTime` is a millisecond timestamp. - For non-TWAP order lifecycle and L3 book deltas, see the [Orders API](/docs/perpetuals/hyperliquid/hyperliquid-orders-api). --- ## Hyperliquid Trades & Candles API URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-trades-api/ Query and stream Hyperliquid trades (fills) and OHLCV candles with Bitquery GraphQL and WebSocket: price, size, direction, fees, leverage, realized PnL and per-interval OHLCV. # Hyperliquid Trades & Candles API This page covers the `Trades` and `Candles` cubes: every fill on Hyperliquid with full execution context, and OHLCV candles per market and interval. The video shows how a trading bot combines the trades, liquidations, funding and orders streams over one WebSocket. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Latest trades Each fill carries the execution (price, size, side, aggressor flag, place in the block), the position it changed (leverage, margin mode, size before and after, realized PnL) and fees. For perps `Direction` is `Open Long`, `Open Short`, `Close Long`, `Close Short`, or `Long > Short` / `Short > Long` when one fill flips the position through flat; spot and outcome fills read `Buy` / `Sell`. Run it in the IDE: [Hyperliquid Latest Trades ➤](https://ide.bitquery.io/hyperliquid-latest-trades) ```graphql query { Hyperliquid { Trades( limit: {count: 50} orderBy: {descending: [Block_Time, Trade_Execution_Index]} where: {Block: {Time: {since_relative: {minutes_ago: 10}}}} ) { Block { Number Time } Trade { Market { Symbol CoinRaw Kind IsPerp Protocol } Execution { Price Size Side Direction IsAggressor Index Oid Tid Hash } Fees { Fee FeeToken BuilderFee } IsTwap Position { Leverage IsCross Side SizeBefore Size RealizedPnl } Trader { Address Vault Signer } } } } } ``` Notes on the payload: - Every row of one block shares `Block.Time`. `Execution.Index` is the fill's place in its block — the execution order, from 1, one sequence across the trades and liquidations of the block — so order fills by `[Block_Time, Trade_Execution_Index]` as above. - `Execution.Tid` identifies the match: the maker and the taker of one fill share it, so pair the two sides on `(Block.Number, Market.CoinRaw, Tid)`. It is a hash, not a sequence — never order fills by it. `Oid` is the order id that got filled, `Hash` the transaction hash (all zeroes on TWAP fills). - `Fees.Fee` is in `FeeToken` (usually USDC); a **negative fee is a maker rebate**. - `Position.SizeBefore` and `Position.Size` are the account's signed position size before and after the fill (negative = short); `RealizedPnl` is the PnL realized by this fill. - Rows written before about 09:40 UTC on 13 October 2026 have `Index` 0 and an empty `Position.Size`. - `IsTwap: true` marks fills produced by a TWAP order (see [TWAPs](/docs/perpetuals/hyperliquid/hyperliquid-orders-api#twap-orders)). - Prediction market fills (`Kind: outcome`) carry the market's names under `Market { Outcome { Headline Title SideTitle } }`; see the [Prediction Markets API](/docs/perpetuals/hyperliquid/hyperliquid-prediction-markets-api). ### Trades of one market Run it in the IDE: [Hyperliquid BTC Perp Trades ➤](https://ide.bitquery.io/hyperliquid-btc-perp-trades) ```graphql query { Hyperliquid { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: {Trade: {Market: {Symbol: {is: "BTC"}}}} ) { Block { Time } Trade { Execution { Price Size Side Direction IsAggressor } Position { Leverage IsCross RealizedPnl } Trader { Address } } } } } ``` Filter by trader instead with `where: {Trade: {Trader: {Address: {is: "0x..."}}}}`. Without a `Block: {Time: ...}` filter, `Trades` covers the last 24 hours; add one (e.g. `since_relative: {days_ago: 7}`) to reach further back within the ~30-day window. ## Real-time trades stream Run it in the IDE: [Hyperliquid Trades Stream ➤](https://ide.bitquery.io/hyperliquid-trades-stream) ```graphql subscription { Hyperliquid { Trades { Block { Number Time } Trade { Market { Symbol Kind IsPerp } Execution { Price Size Side Direction IsAggressor Index Oid Tid } Fees { Fee FeeToken } IsTwap Position { Leverage IsCross Side Size RealizedPnl } Trader { Address } } } } } ``` ## OHLCV candles The `Candles` cube provides OHLCV per market and interval. `Interval.Time.Duration` is the candle length in **seconds** — `60`, `300`, `900` or `3600` — and `Start` the interval open time. OHLCV values are floats. Bars are built from taker fills, so each fill counts once in `Volume` (in base units); `Open` and `Close` are the first and last fill of the bar in execution order (block, then `Execution.Index`). Run it in the IDE: [Hyperliquid BTC OHLCV Candles ➤](https://ide.bitquery.io/hyperliquid-btc-ohlcv-candles) ```graphql query { Hyperliquid { Candles( limit: {count: 60} orderBy: {descending: Interval_Time_Start} where: {Market: {Symbol: {is: "BTC"}}, Interval: {Time: {Duration: {eq: 60}}}} ) { Interval { Time { Start Duration } } Market { Symbol Kind CoinRaw } Ohlc { Open High Low Close Volume } } } } ``` HIP-3 markets get candles too — e.g. `where: {Market: {CoinRaw: {is: "xyz:AAPL"}}}` for the tokenized-stock market. Filter on `CoinRaw` when a ticker exists on more than one market (`BTC` and `hyna:BTC`). ### Real-time candle stream Run it in the IDE: [Hyperliquid Candles Stream ➤](https://ide.bitquery.io/hyperliquid-candles-stream) ```graphql subscription { Hyperliquid { Candles(where: {Market: {Symbol: {is: "BTC"}}}) { Interval { Time { Start Duration } } Market { Symbol Kind } Ohlc { Open High Low Close Volume } } } } ``` Remove the `Symbol` filter to stream candle updates for every market. ## Related - [HIP-3 Stocks API](/docs/perpetuals/hyperliquid/hip3-stocks-api) — trades and candles for S&P 500, US stock and commodity perps - [Prediction Markets API](/docs/perpetuals/hyperliquid/hyperliquid-prediction-markets-api) — top HIP-4 markets by volume, live outcome trades - [TWAP Orders & Child Fills](/docs/perpetuals/hyperliquid/hyperliquid-twap-fills) — join fills with `IsTwap: true` to their parent TWAP - [Track ZEC on Hyperliquid](/docs/perpetuals/hyperliquid/track-zec-on-hyperliquid) — whale trades and candles for one market --- ## Hyperliquid Vaults API — Vault Trades, PnL, Deposits and Liquidations URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-vaults-api/ Track Hyperliquid vaults with Bitquery: vault equity and followers, vaults ranked by volume and PnL, every fill a vault made, HLP deposits and withdrawals, a live vault transfer stream and vault liquidations over GraphQL and WebSocket. # Hyperliquid Vaults API Hyperliquid vaults are accounts that trade with pooled deposits: HLP, the protocol's own liquidity vault, and user vaults run by individual traders. With Bitquery you can list every vault with its equity and depositors, rank vaults by volume and PnL, read each fill a vault made, follow deposits and withdrawals as they happen, and see when a vault position was liquidated. A fill or liquidation of an order placed for a vault carries the vault's address in `Trader.Vault` (equal to `Trader.Address`). Hyperliquid uses the same mechanism for sub-accounts, so `Trader.Vault` is set on sub-account fills too: a `Vault: {not: ""}` filter returns vaults and sub-accounts together. An address that receives `vaultTransfer` deposits ([below](#who-deposits-into-and-withdraws-from-a-vault)) is a vault; to keep vaults only, list such addresses with `Vault: {in: [...]}`. Everything below runs on the `Hyperliquid` cube at `https://streaming.bitquery.io/graphql` over the rolling window described on the [Hyperliquid API overview](/docs/perpetuals/hyperliquid). The worked vault is `0xc179e03922afe8fa9533d3f896338b9fb87ce0c8`, one of the most active user vaults, and the HLP vault is `0xdfc24b077bc1425ad1dea75bcb6f8158e10df303`. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Every vault with its equity and followers `SnapshotVaults` lists every vault at the latest [snapshot](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api) (about every 12.5 minutes): name, leader, equity, number of followers, terms and parent / child vaults. Unlike the fill-based queries below, it tells vaults from sub-accounts: only vaults are listed. ```graphql query HyperliquidVaultsByEquity { Hyperliquid { SnapshotVaults(orderBy: {descending: Summary_Equity}, limit: {count: 25}) { Block { Time } Vault Name Leader Summary { Equity Followers LeaderFraction } Terms { LeaderCommission LockupSeconds AllowDeposits IsClosed } Relationship { Type ChildVaults } } } } ``` `Relationship.ChildVaults` lists the child vaults of a parent vault such as HLP, which trades through them. `Followers` counts the depositors, leader included. The depositors of one vault, largest first, with their share, equity, net deposit and all-time PnL: ```graphql query HyperliquidVaultFollowers { Hyperliquid { SnapshotVaultFollowers( where: {Vault: {is: "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303"}} orderBy: {descending: Share_Equity} limit: {count: 50} ) { Trader { Address } IsLeader Share { Fraction Equity NetDeposit AllTimePnl } Times { EntryTime LockupUntil } } } } ``` `Times` are epoch nanoseconds. A vault's open positions are `SnapshotPositions` with the vault address as `Trader.Address`; with a `Block: {Time: {since: ...}}` filter, `SnapshotVaults` gives a vault's equity at every snapshot of the last 7 days. ## Which Hyperliquid vaults trade the most? Filter fills to those with a vault set and group by `Trader.Vault`. Each row is one vault or sub-account with its fills, markets traded, USD volume and realized PnL over the last day. Run it in the IDE: [Hyperliquid Top Vaults by Volume ➤](https://ide.bitquery.io/hyperliquid-top-vaults-by-volume) ```graphql query HyperliquidTopVaultsByVolume { Hyperliquid { Trades( limit: {count: 25} orderBy: {descendingByField: "volumeUsd"} where: { Trade: {Trader: {Vault: {not: ""}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Trade { Trader { Vault } } fills: count markets: uniq(of: Trade_Market_CoinRaw) volumeUsd: sum(of: Trade_Execution_NotionalUSD) realizedPnl: sum(of: Trade_Position_RealizedPnl) } } } ``` Sub-accounts often fill the top of this list, so check an address against the deposits below before calling it a vault. A vault with hundreds of thousands of fills and PnL near zero is a market-making vault. HLP trades through child vaults, so its activity appears under those addresses rather than the HLP address itself. ## Which vaults are the most profitable? Every closing fill carries `Position.NetPnl` (realized PnL minus the fee) and `Position.IsWin`. Group by `Trader.Vault` over a week to rank vaults and sub-accounts by net realized PnL and count winning closes. Run it in the IDE: [Hyperliquid Vault PnL Leaderboard ➤](https://ide.bitquery.io/hyperliquid-vault-pnl-leaderboard) ```graphql query HyperliquidVaultPnlLeaderboard { Hyperliquid { Trades( limit: {count: 25} orderBy: {descendingByField: "netPnl"} where: { Trade: {Trader: {Vault: {not: ""}}, Position: {IsClosing: true}} Block: {Time: {since_relative: {days_ago: 7}}} } ) { Trade { Trader { Vault } } closes: count wins: count(if: {Trade: {Position: {IsWin: true}}}) netPnl: sum(of: Trade_Position_NetPnl) volumeUsd: sum(of: Trade_Execution_NotionalUSD) } } } ``` Win rate is `wins / closes`. Order by `ascendingByField: "netPnl"` for the biggest losers. ## What did one vault trade? Filter on the vault address. Each row is a fill with market, price, size, direction, leverage, fee and realized PnL; `Trader.Vault` equals `Trader.Address`. Fills of one block share `Block.Time`, so the query orders them by `Execution.Index` inside it. Run it in the IDE: [Hyperliquid Vault Fills ➤](https://ide.bitquery.io/hyperliquid-vault-fills) ```graphql query HyperliquidVaultFills { Hyperliquid { Trades( limit: {count: 50} orderBy: {descending: [Block_Time, Trade_Execution_Index]} where: { Trade: {Trader: {Vault: {is: "0xc179e03922afe8fa9533d3f896338b9fb87ce0c8"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Block { Time } Trade { Market { Symbol Kind } Execution { Price Size Side Direction NotionalUSD } Position { Leverage RealizedPnl } Fees { Fee } Trader { Address Vault } } } } } ``` Change `query` to `subscription` and drop `limit` and `orderBy` to stream a vault's fills live. ## Who deposits into and withdraws from a vault? Deposits and withdrawals are `vaultTransfer` actions in the `SignedActions` cube, which keeps about the last 7 days on the API (for older data, ask about a [Data Store export](https://bitquery.io/datastore)). The `Action` payload holds the vault address, `isDeposit` and the amount in `usd` with six decimals, so `100000000` is 100 USDC. `User` is the depositor. The example follows the HLP vault; swap in any vault address. Run it in the IDE: [Hyperliquid Vault Deposits and Withdrawals ➤](https://ide.bitquery.io/hyperliquid-vault-deposits-withdrawals) ```graphql query HyperliquidVaultDepositsAndWithdrawals { Hyperliquid { SignedActions( limit: {count: 50} orderBy: {descending: Block_Time} where: { ActionType: {is: "vaultTransfer"} Action: {includes: "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303"} Block: {Time: {since_relative: {days_ago: 1}}} } ) { Block { Time } User Action Status Bundle { Hash } } } } ``` `Status` is `ok` for accepted transfers. Rejected ones stay in the data with an error status, which is useful for spotting withdrawals that hit a lock-up. ## Live vault deposits and withdrawals The same action as a WebSocket stream, across every vault, filtered to successful transfers. Run it in the IDE: [Hyperliquid Vault Transfers Stream ➤](https://ide.bitquery.io/hyperliquid-vault-transfers-stream) ```graphql subscription HyperliquidVaultTransfersStream { Hyperliquid { SignedActions(where: {ActionType: {is: "vaultTransfer"}, Status: {is: "ok"}}) { Block { Time } User Action Bundle { Hash } } } } ``` Parse `Action` on the client to alert on large deposits or on any transfer into a vault you follow. ## Which vault positions were liquidated? `PerpLiquidations` carries `Trader.Vault` too, but a liquidation is recorded for both sides of the forced fill, so this list holds two kinds of rows: those where `Trader.Address` equals `LiquidatedUser` are the vault's (or sub-account's) own position being liquidated; the rest are vaults or sub-accounts taking the other side of someone else's liquidation, which market makers such as HLP's child vaults do all the time. Run it in the IDE: [Hyperliquid Vault Liquidations ➤](https://ide.bitquery.io/hyperliquid-vault-liquidations) ```graphql query HyperliquidVaultLiquidations { Hyperliquid { PerpLiquidations( limit: {count: 50} orderBy: {descending: Block_Time} where: { Liquidation: {Trader: {Vault: {not: ""}}} Block: {Time: {since_relative: {days_ago: 7}}} } ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx LiquidatedUser Execution { Price Size Side } Position { Leverage SizeBefore Size } Trader { Address Vault } } } } } ``` To list only the liquidations of one vault's own positions, filter `Liquidation: {LiquidatedUser: {is: "0x..."}, Trader: {Address: {is: "0x..."}}}` with the vault address in both, or turn it into a subscription for live alerts. ## Related - [Hyperliquid API overview](/docs/perpetuals/hyperliquid) - [Liquidations, Funding, Positions & Leverage](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api) - [Signed Actions API](/docs/perpetuals/hyperliquid/hyperliquid-signed-actions-api) - [Snapshots API](/docs/perpetuals/hyperliquid/hyperliquid-snapshots-api) — vault positions, accounts and depositors at each snapshot - [Track Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet) - [Trades & Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) --- ## Indexed Fields Reference (where & orderBy) URL: https://docs.bitquery.io/docs/graphql/indexed-fields-reference/ Indexed Fields Reference (where & orderBy) in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Indexed Fields Reference for `where` and `orderBy` Use **indexed fields** in your `where` filters and `orderBy` clauses. Filtering or sorting on non-indexed fields can lead to slow queries, timeouts. This page lists the fields that are indexed for each cube, dataset, and chain type. Prefer these fields when building `where` and `orderBy` conditions. :::tip Best practice In `where`, filter on at least one indexed field (Index 1, 2, 3, or 4 where applicable). In `orderBy`, sort by an indexed field when possible. ::: --- ## EVM (Archive) | Cube | Index 1 | Index 2 | Index 3 | Index 4 | | -------------------- | ---------------------------- | ---------------------- | ----------------- | ------------------------------- | | **Balances** | Balance_Address | Currency_SmartContract | — | — | | **Blocks** | Block_Hash | Block_Number | — | — | | **Calls** | Call_From | Call_To | Transaction_Hash | — | | **DEXTrades** | Transaction_Hash | — | — | — | | **DEXTradeByTokens** | Trade_Currency_SmartContract | Trade_Side_Seller | — | — | | **Events** | Call_To | Transaction_Hash | — | — | | **MinerRewards** | Block_Coinbase | Block_Number | Block_Hash | — | | **Holders** | Currency_SmartContract | — | — | — | | **Transactions** | Transaction_From | Transaction_Hash | Transaction_To | — | | **Transfers** | Transaction_Hash | Transfer_Sender | Transfer_Receiver | Transfer_Currency_SmartContract | --- ## Tron (Archive) | Cube | Index 1 | Index 2 | Index 3 | Index 4 | | -------------------- | ---------------------------- | ---------------------- | ----------------- | ------------------------------- | | **Balances** | Balance_Address | Currency_SmartContract | — | — | | **Blocks** | Block_Hash | Block_Number | — | — | | **Calls** | Call_From | Call_To | Transaction_Hash | — | | **DEXTrades** | Transaction_Hash | — | — | — | | **DEXTradeByTokens** | Trade_Currency_SmartContract | Trade_Side_Seller | — | — | | **Events** | Call_To | Transaction_Hash | — | — | | **Holders** | Currency_SmartContract | — | — | — | | **Transactions** | Transaction_Hash | — | — | — | | **Transfers** | Transaction_Hash | Transfer_Sender | Transfer_Receiver | Transfer_Currency_SmartContract | --- ## Solana ### Solana Realtime | Cube | Index 1 | Index 2 | Index 3 | | -------------------- | -------------------------- | --------------------------- | --------------------- | | **DEXPools** | Pool_Market_MarketAddress | — | — | | **DEXTradeByTokens** | Trade_Currency_MintAddress | — | — | | **Instructions** | Transaction_Signer | Instruction_Program_Address | — | | **Transfers** | Transfer_Receiver_Owner | Transfer_Sender_Owner | Transaction_Signature | ### Solana Archive | Cube | Index 1 | Index 2 | Index 3 | | -------------------- | -------------------------- | ------------------- | ------- | | **DEXTradeByTokens** | Trade_Currency_MintAddress | Trade_Account_Owner | — | --- ## Trading (Realtime) | Cube | Index 1 | Index 2 | Index 3 | Index 4 | Index 5 | | -------------- | ------------------ | --------------------- | --------------------- | ------------------ | ------------ | | **Currencies** | Currency_Id | Interval_Time_Start | — | — | — | | **Tokens** | Token_Id | Interval_Time_Start | Currency_Id | Token_Address | — | | **Pairs** | Token_Id | Currency_Id | Interval_Time_Start | Token_Address | Pool_Address | | **Trades** | Trader_Address | Pair_Token_Address | Pair_Pool_Address | — | — | --- ## How to use this reference 1. **Identify your cube** — e.g. `EVM.Transactions`, `Solana.Transfers`, `Trading.Tokens`. 2. **Check chain and dataset** — EVM Archive, Tron Archive, Solana Realtime/Archive, or Trading Realtime. 3. **Use indexed fields in `where`** — Prefer filters on the indexed columns (Index 1, 2, 3, 4). Example: for `EVM(dataset: archive).Transactions`, filter on `Transaction_From`, `Transaction_Hash`, or `Transaction_To`. 4. **Use indexed fields in `orderBy`** — Sort by one of the indexed fields (e.g. `Block_Number`, `Transaction_Hash`) for predictable, fast ordering. Using fields that are **not** in these tables for filtering or sorting may work in some cases but can cause poor performance or unexpected behavior. When in doubt, stick to the indexed fields listed above. --- ## Investigating the $100 Million HECO Bridge Crypto Hack with MoneyFlow URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/heco-bridge-hack/ Investigation video: tracing the HECO Chain bridge and HTX exploit funds across Ethereum addresses with Bitquery MoneyFlow. # Investigating the $100 Million HECO Bridge Crypto Hack with MoneyFlow This investigation follows the funds from the HECO Chain bridge and HTX exploit of November 2023 through the attacker's Ethereum addresses. --- ## Investigating the $81M Orbit Bridge Hack Using MoneyFlow URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/orbit-bridge-hack/ Investigation video: following the $81 million stolen from the Orbit Chain bridge across wallets with Bitquery MoneyFlow. # Investigating the $81M Orbit Bridge Hack Using MoneyFlow This investigation follows the funds taken from the Orbit Chain bridge on 31 December 2023 and shows how the attacker split them across wallets. --- ## Investigating the Dough Finance Exploit with Bitquery MoneyFlow URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/dough-finance-exploit/ Investigation video: tracing the flash-loan exploit of Dough Finance and the attacker's fund movements with Bitquery MoneyFlow. # Investigating the Dough Finance Exploit with Bitquery MoneyFlow This investigation traces the funds from the Dough Finance flash-loan exploit of July 2024 and shows where the attacker moved them. --- ## Investigating the Indodax Hack with MoneyFlow URL: https://docs.bitquery.io/docs/moneyflow-lite/video-tutorials/indodax-hack/ Investigation video: tracing the funds stolen from the Indodax exchange hot wallets across chains with Bitquery MoneyFlow. # Investigating the Indodax Hack with MoneyFlow This investigation traces the funds taken from Indodax hot wallets in September 2024 and shows the consolidation addresses used by the attacker. --- ## Javascript Tutorial to Setup Solana Kafka Shred Stream URL: https://docs.bitquery.io/docs/streams/protobuf/kafka-protobuf-js/ Javascript Tutorial to Setup Solana Kafka Shred Stream with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. # Javascript Tutorial to Setup Solana Kafka Shred Stream This tutorial explains how to consume **Solana** protobuf messages from **Bitquery Kafka** using **JavaScript** (Node.js **CommonJS** — not a browser bundle), and print them with **`bytes`** fields decoded to **base58** where **`printProtobufMessage`** applies that encoding. **Streaming concepts:** **[Kafka streaming concepts — Protobuf streams](/docs/streams/kafka-streaming-concepts/#what-to-know-about-protobuf-streams)**. **Runnable project:** **[`bitquery/kafka-streams-examples-usecases`](https://github.com/bitquery/kafka-streams-examples-usecases)** — **[`js-consumer-example/`](https://github.com/bitquery/kafka-streams-examples-usecases/tree/main/js-consumer-example)** ([`src/index.js`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/src/index.js), [`src/config.js`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/src/config.js), [`package.json`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/package.json)). Use **[`bitquery-protobuf-schema npm Package`](https://www.npmjs.com/package/bitquery-protobuf-schema)** so you do **not** hand-manage `.proto` files—the package resolves the schema from **`KAFKA_TOPIC`**. > **Throughput:** Treat this repo as a **minimal** consumer. Saturating high-volume topics typically requires tuning **KafkaJS** parallelism, **partition-aware** runners, or **multiple consumers under one consumer group**. See **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)** for partition-oriented guidance. ## Prerequisites - **Node.js 18+** (`package.json` `engines`). - **npm** - Bitquery **Kafka username and password** for stream access. > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). Install all dependencies declared in **`package.json`**: ```bash npm install ``` Key runtime libraries: **`kafkajs`**, **`kafkajs-lz4@^1.2.1`** (+ **`lz4` / `lz4-asm`**), **`bitquery-protobuf-schema`**, **`dotenv`**, **`uuid`**, **`bs58`**. ## 1. Kafka client initialization (non-TLS baseline) The sample builds a **KafkaJS** client with **SASL SCRAM-SHA-512**, **no TLS** (**`ssl: false`**), and default Bitquery broker endpoints (overridable via **`KAFKA_BOOTSTRAP_SERVERS`**). Compression: **LZ4** codec registration matches Bitquery payloads. See the live **`createKafka`** helper in **`src/index.js`** and env loading in **`src/config.js`** on GitHub (**links above**). > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## 2. Protobuf traversal and `bytes` (Solana vs EVM) Printing is implemented in **`src/printProtobuf.js`** and mirrors the **recursive traversal** pattern from earlier Bitquery tutorials: nested objects descend; **`bytes`** are encoded with **`bs58`** when the printer runs in **`base58`** mode (Solana-focused default in **`index.js`**). > **Solana vs EVM `bytes`** > > Protobuf **`bytes`** often encode addresses, hashes, or signatures—the display encoding depends on the chain: > > - **Solana:** **base58** (this tutorial’s default path). > - **EVM (Ethereum, BSC, Base, etc.):** **hex**, typically **`0x` + buffer.toString("hex")** when you customize the printer. > > Example pattern for hex (not used in the default Solana tree): > > ```js > const hex0x = (buffer) => "0x" + Buffer.from(buffer).toString("hex"); > ``` ## 3. Consumer group and subscribe Group id: - Prefer **stable** **`KAFKA_GROUP_ID`** beginning with **your Kafka username** (Bitquery requirement for stable ids). - If unset, **`index.js`** uses **`${username}-group-${uuid}`** (hyphens stripped from uuid), matching the spirit of the older tutorial’s dynamic suffix. Subscribe uses **`fromBeginning`** from **`KAFKA_FROM_BEGINNING`** (boolean-style env parsing in **`config.js`**). > **Reminder vs Python / Go** > > Node uses **`KAFKA_FROM_BEGINNING`**. Python and Go in the **same repository** use **`KAFKA_AUTO_OFFSET_RESET`** (**`latest` / `earliest`**). Align env vars when you compare languages side by side. ## 4. Run stream: load proto, decode, LZ4-ready pipeline [`src/index.js`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/src/index.js): 1. **`await loadProto(cfg.topic)`** before consuming. 2. **`consumer.connect()`** → **`subscribe({ topic, fromBeginning })`**. 3. **`consumer.run({ autoCommit: false, eachMessage: ... })`**. 4. **`decode`** + **`toObject`** ( **`bytes`** as **`Buffer`** for the printer ). 5. **`printProtobufMessage`** to stdout; errors logged to stderr. KafkaJS timeouts in code: **`connectionTimeout: 10_000`**, **`requestTimeout: 60_000`**. ## Execution workflow 1. **Initialize client** — brokers from env or defaults; **`ssl: false`**; SCRAM SASL credentials. 2. **Resolve group id** — explicit **`KAFKA_GROUP_ID`** or generated **`username-group-uuid`**. 3. **`loadProto(topic)`** — bind decode type to **`KAFKA_TOPIC`**. 4. **Connect and subscribe** — optional **`fromBeginning`** for new consumer groups without committed offsets—understand semantics vs **`autoCommit: false`** in this baseline. 5. **Process messages** — **`eachMessage`** decodes protobuf, prints traversal. 6. **Compression** — LZ4 codec registered for Kafka compression on the wire. 7. **Errors** — caught per message where possible; fatal errors exit non-zero. **TLS:** baseline is **plaintext Kafka** on **9092**. For **`SASL_SSL`**, populate KafkaJS **`ssl`** objects and migrate brokers per **[Kafka streaming concepts — SASL_SSL](/docs/streams/kafka-streaming-concepts/#ssl-connection-sasl_ssl-)** plus **`js-consumer-example/README.md`**. ## Clone and run (quick reference) > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ```bash git clone https://github.com/bitquery/kafka-streams-examples-usecases.git cd kafka-streams-examples-usecases/js-consumer-example npm install cp .env.example .env # set KAFKA_USERNAME, KAFKA_PASSWORD npm start ``` Debug KafkaJS internals: ```bash npm run start:debug ``` ## Troubleshooting | Issue | Action | | ------------------------- | ---------------------------------------------------------------------------------------- | | Missing env vars | **`cp .env.example .env`**, validate names | | Auth / SASL failures | Credentials, **`scram-sha-512`** mechanism, broker connectivity **9092** | | LZ4 / native addon errors | Re-run **`npm install`**; verify Node version ≥ 18 | | Decode failures | Topic unsupported in your **`bitquery-protobuf-schema`** version or wrong topic spelling | ## See also - **[bitquery-protobuf-schema (npm package)](https://www.npmjs.com/package/bitquery-protobuf-schema)** - **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)** --- ## Kafka Operations Cookbook URL: https://docs.bitquery.io/docs/streams/kafka-operations/ Connect, authenticate, and operate Bitquery Kafka consumers — offsets, timestamps, retention, billing, and schema gotchas. # Kafka Operations Cookbook Practical operating guidance for Bitquery Kafka consumers: how to connect and authenticate, how offsets and timestamps behave, what retention to expect, and the schema traps that trip up new integrators. For the streaming concepts and topic catalogue, start with [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). :::caution Verify connection details for your account Broker hosts, ports, and credential rules are provisioned per account — use the values in your onboarding details. ::: ## Connection recipe - **Port:** `9092` - **Security protocol:** `SASL_PLAINTEXT` with your Kafka **username and password** (SASL/PLAIN) — no client TLS certificates required. - **Consumer group id:** use any stable `group.id` for your consumer. - Credentials for the chain topics (e.g. `solana.*`) and the `trading.*` topic family may differ — use the credential issued for the family you're consuming. See the language-specific starters: [Python](/docs/streams/protobuf/kafka-protobuf-python/), [JavaScript](/docs/streams/protobuf/kafka-protobuf-js/), [Go](/docs/streams/protobuf/kafka-protobuf-go/). ## Retention: Kafka is not a historical firehose Kafka delivers **realtime data plus a small backfill window (hours, not history)**. A fresh consumer sees recent messages forward — not the chain from genesis. For anything older, use GraphQL (within its [retention window](/docs/graphql/data-coverage-retention/)) or a [cloud/S3 export](/docs/cloud/). Two independent integrators have assumed Kafka replays genesis; it does not. ## Offsets and restart behavior Two common restart modes: - **Skip the backlog (only new messages):** reset the group to the latest offset — e.g. `auto.offset.reset=latest`, or an explicit reset to end on startup. - **Resume where you stopped (backfill the gap):** reuse the **same `group.id`** and resume from committed offsets. Commit periodically — but **not too frequently**, since very frequent commits create broker backpressure. - If you see **`Offset out of range`** (your committed offset aged out of the retention window), reset to `latest` and continue. ## Timestamps (especially Solana) - On Solana shred streams, a message carries its **slot**, but the **block timestamp is only populated on the final message of a block** (messages are pushed before the block finalizes). **Do not treat an empty/zero `BlockHeader.Timestamp` on non-final messages as staleness.** - Block time is rounded and propagation adds a small delay, so an event can carry a timestamp a second or two before it reaches your consumer. Budget for this when computing "latency". ## No server-side filtering Kafka topics are **firehoses** — there is no server-side filter. Consume the topic and filter client-side (by mint, program, pair, address, etc.). If you need server-side filtering, use GraphQL subscriptions or Solana gRPC (which requires at least one filter) instead. ## Billing: what counts as a "stream" Each **environment / consumer group** counts as its own stream. Running the same topic from `dev`, `staging`, and `prod` (three consumer groups) counts as three streams. Kafka capacity is billed separately from GraphQL query points. See [How Billing Works](/docs/plans/how-billing-works/). ## Schema gotchas - In `BlockHeader`, the fields **`TxHash`, `Root`, and `ReceiptHash` are block-level Merkle roots — not a transaction hash.** The actual transaction hash lives on the transaction record (`TransactionHeader`), not the block header. The `TxHash` name is a common source of confusion. - Message nesting generally goes block → transaction → event; consult the [protobuf schema](/docs/streams/protobuf/kafka-trading-topics-protobuf/) for the exact shape of each topic. ## Diagnosing lag If messages arrive late or pile up, check **consumer lag first** — it's usually the client (slow processing, too few partitions consumed, large payloads on some chains) rather than the broker. Scale consumers or parallelize partition consumption. ## Next steps - [Kafka Streaming Concepts & topic list](/docs/streams/kafka-streaming-concepts/) - [Protobuf schema reference](/docs/streams/protobuf/kafka-trading-topics-protobuf/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) - [Common errors — Kafka auth](/docs/start/errors/#kafka-auth-errors) --- ## Kafka Streaming Concepts URL: https://docs.bitquery.io/docs/streams/kafka-streaming-concepts/ Learn Bitquery Kafka stream concepts: topics, offsets, SASL auth, protobuf payloads, and when Kafka beats WebSockets for crypto data. # Bitquery Kafka Streams - Understanding Concepts Bitquery provides realtime data via Kafka as well in addition to GraphQL subscriptions. In this section, we'll see how Kafka-based streaming works and how to integrate it into your application using practical code examples. For price data streams, check out our [Crypto Price API](/docs/trading/crypto-price-api/) Kafka topic. ## How to Get Access to these Streams? IDE credentials will not work with our Kafka Streams. You need a separate username and password. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ### Pros and Cons Kafka provides faster and more reliable streams comparing to GraphQL subscriptions due to the following advantages: 1. It has lower latency due to the shorter data pipeline, as GraphQL subscriptions involve custom databases and additional logic to process, filter and format the data 2. Better reliability of the connection protocol compared to WebSocket interface, better optimized for persistent connections 3. Messages from Kafka topic can be read from the latest offset, it is possible to create consumers that have all messages without gaps and interruption. 4. Scalability is better as multiple consumers may split the load to consume one topic, automatically redistributing load on them There are some disadvantages however compared to GraphQL subscriptions: 1. There is no way to consume Kafka streams in browser. You can only use it only on server side. 2. It is not possible to pre-filter or re-format messages on Kafka streams, as schema is pre-defined, and you need to make all post-processing in your code. Some calculations, as usd value of trade have to be executed on client side as well 3. IDE does not support Kafka streams yet, debugging the code have to be done on consumer side Kafka streams contains same set of data as GraphQL subscriptions, and the decision which one to use dependent more on your application type. Consider the following factors when selecting which technology to use. ### Consider using GraphQL if: - You are building a prototype and the speed of development is a primary factor for you. Integrating GraphQL is easier, IDE helps to de-bug queries and see the data you receive in application; - Your application uses archive and real-time data altogether. GraphQL has a unified interface to query and subscribe the data streams, that makes such application easier to build and maintain; - Your application provides different data on web pages, for example show price diagrams for trading. Then GraphQL makes simpler to filter the data and make queries based on page content; - There is no server side for your application, or it is minimal. Then GraphQL can be integrated directlty to JS client code; ### Consider using Kafka if: - Latency is the most important factor and you building fast scalable application in cloud or on dedicated servers; - It is not acceptable to lose any single message from the stream, you need persistent reliability; - You have a complex calculations, filtering or formatting of the data that GraphQL does not deliver. Then instead of consuming unfiltered stream from GraphQL consider switch to Kafka. This decision sometimes not straightforward, consult our sales and support team, we will help you find optimal solution. ### Important Notes about Kafka Streams - Stream is not filtered, it contains all the messages with a complete data for every topic. It means you need to have a good throughput network, fast server and code to efficently consume and parse it; - Granularity of data message is different in topics, depending on the nature of the data. - It is **not** guaranteed that the message will come in sequence of the block number, time or any other attribute. - Messages in topic **may have** duplicates. If this is a problem, your code must have a storage or the cache to remember which messages are already processed to avoid double processing. - Large messages can be separated on smaller ones, as Kafka does not allow pass more than 1 Mbyte in one message. For example, first 1200 transaction may come in one message, and the remaining 1000 will follow in another. - **Transactions themselves will never be split**: each transaction record is always delivered in full. If a single transaction payload exceeds Kafka’s maximum message size, the producer will receive an error—Kafka will not peek inside the payload to automatically fragment it into multiple messages. ### Kafka Streams Lattency Topics for the same blockchain are not equal by latency. If you have requirements on latency, consider to select the proper stream for your application: 1. Broadcasted topics are available for most blockchains. They can be faster, as the transactions are not waiting till include and commit the block in the chain 2. Streams are chained while they are parsing, the closer the topic to the original blockchain node, the less is the latency. Consider selecting the closest topic that you can effectively parse. Every transformation introduces 100-1000 msec latency in the overall topic delay. The diagram shows the data pipeline of the streams on the way to KAFKA topics. Broadcasted and committed transaction datapipelines are identical: ![Topic Data Pipeline](/img/streams/latency.png) #### Measured Latency: Kafka vs GraphQL Subscription The table below compares end-to-end latency for **Solana token transfers** delivered over Kafka (`solana.tokens.proto`) and over a GraphQL subscription (WebSocket, `streaming.bitquery.io/graphql`). Both streams were consumed **simultaneously from the same server** over a 5-minute window, and both delivered the same volume of data (~1.227M transfers each, a 0.01% difference). Latency is measured from the **Solana block timestamp** to the moment the message is available to application code. | | p50 | p90 | p95 | p99 | mean | | ----------------------------------------------- | ------ | ------- | ------- | ------- | ------ | | **Kafka** (`solana.tokens.proto`) | 383 ms | 1450 ms | 1636 ms | 1847 ms | 495 ms | | **WebSocket** (`streaming.bitquery.io/graphql`) | 405 ms | 1488 ms | 1674 ms | 2013 ms | 530 ms | A few notes on how to read these numbers: - **Solana block timestamps have 1-second granularity.** This adds up to ±1s of quantization noise to every sample, which inflates the p90/p99 figures for both transports. The noise is identical for Kafka and WebSocket, so the comparison between them remains valid. - **Comparing arrival times slot-by-slot** removes that quantization entirely. On this basis Kafka arrived first for **77%** of slots, leading by a median of **~5 ms** and by **~64 ms** at p99. - **Measured on the Kafka side alone**, delivery from broker to consumer (using millisecond-precision Kafka record timestamps, so no quantization) was **17 ms at p50** and **141 ms at p99**. - **Bandwidth differs far more than latency.** Kafka transferred ~10.9 GB over the window against ~332 MB for the WebSocket subscription — roughly **33× more** for the same transfers. Kafka topics carry the complete `TokenBlockMessage` (balance updates, supply updates, token metadata), while a GraphQL subscription sends only the fields you request. Budget for this if you only need a narrow slice of the data. Latency and throughput both depend on your network, server and consumer code, so treat these figures as a reference point rather than a guarantee. ## Consuming Messages Your application must implement the code: - Connect to Kafka server; - Subscribe to particular topic(s); - Read and parse messages; ## Retention Period of Messages **Proto Streams**: Messages are retained for **4 hours**. ## Connect to Kafka Server To connect to Bitquery’s Kafka streaming service, you’ll need the following: 1. **Kafka Broker Addresses** Use the following server list: `rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092` 2. **Authentication Credentials** A **username** and **password** for **SASL over PLAINTEXT authentication** – provided by the Bitquery support team. ### Non-SSL Connection (SASL_PLAINTEXT ) If you prefer to connect without SSL, you can use **SASL_PLAINTEXT** on port `9092`. This does **not** require certificates: ```python sasl_conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092', 'security.protocol': 'SASL_PLAINTEXT', 'sasl.mechanism': 'SCRAM-SHA-512', 'sasl.username': '', 'sasl.password': '', } ``` > Use plaintext only in trusted or local environments, as the connection is not encrypted. ### SSL Connection (SASL_SSL ) If you prefer to connect with SSL, you can use **SASL_SSL** on port `9093`. This requires certificates which can be accessed [here](https://github.com/bitquery/kafka-consumer-example) ```python sasl_conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9093,rpk1.bitquery.io:9093,rpk2.bitquery.io:9093', 'security.protocol': 'SASL_SSL', 'sasl.mechanism': 'SCRAM-SHA-512', 'sasl.username': '', 'sasl.password': '', 'ssl.key.location': 'client.key.pem', 'ssl.ca.location': 'server.cer.pem', 'ssl.certificate.location': 'client.cer.pem', 'ssl.endpoint.identification.algorithm': 'none' } ``` ### Subscribe to particular topic(s) To receive messages you first create consumer and subscribe it to a topic or list of topics. General pattern of the topic name is: ``` . .broadcasted. ``` ### General Message Types MESSAGE_TYPE is specific on blockchain, most blockchain has topics for: - dextrades - events from DEX trading - transactions - events, calls, transactions - tokens - token and coin transfers events - raw - blocks or transactions directly from node Refer to [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf) schemas for structure. ### EVM Chains **Broadcasted (Mempool-level):** - `*.broadcasted.transactions.proto` → `ParsedAbiBlockMessage` - `*.broadcasted.tokens.proto` → `TokenBlockMessage` - `*.broadcasted.dextrades.proto` → `DexBlockMessage` - `*.broadcasted.raw.proto` → `BlockMessage` **Committed Blocks:** - `*.transactions.proto` - `*.tokens.proto` - `*.dextrades.proto` - `*.raw.proto` ## Complete List of Topics All topics deliver data in **protobuf** format. JSON samples for inspection: [kafka-data-sample](https://github.com/bitquery/kafka-data-sample). ### Multi-chain trading topics The **`trading`** namespace defines two Kafka topics. **Both use the same credentials** as your subscription: - **`trading.prices`** — Multi-chain [Price Index Streams](/docs/trading/crypto-price-api/). See the [Crypto Price API](/docs/trading/crypto-price-api/) for usage. - **`trading.trades`** — Real-time DEX trades aligned with the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api). Message structure is defined in [`market/trades.proto`](https://github.com/bitquery/streaming_protobuf/blob/main/market/trades.proto) in [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf). ### EVM chains **Committed** topics use: - **`*.transactions.proto`** → `ParsedAbiBlockMessage` - **`*.tokens.proto`** → `TokenBlockMessage` - **`*.dextrades.proto`** → `DexBlockMessage` - **`*.raw.proto`** → `BlockMessage` **Mempool / broadcasted** topics insert **`broadcasted`** immediately after the chain prefix (example: **`eth.broadcasted.transactions.proto`**). They use: - **`*.broadcasted.transactions.proto`** → `ParsedAbiBlockMessage` - **`*.broadcasted.tokens.proto`** → `TokenBlockMessage` - **`*.broadcasted.dextrades.proto`** → `DexBlockMessage` - **`*.broadcasted.raw.proto`** → `BlockMessage` **`*.dexpools.proto`** → `DexPoolBlockMessage`. See the [DEXPools Cube documentation](/docs/cubes/evm-dexpool) for details. #### Ethereum (`eth`) - `eth.transactions.proto` → `ParsedAbiBlockMessage` - `eth.tokens.proto` → `TokenBlockMessage` - `eth.dextrades.proto` → `DexBlockMessage` - `eth.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) - `eth.raw.proto` → `BlockMessage` - `eth.broadcasted.transactions.proto` → `ParsedAbiBlockMessage` - `eth.broadcasted.tokens.proto` → `TokenBlockMessage` - `eth.broadcasted.dextrades.proto` → `DexBlockMessage` - `eth.broadcasted.raw.proto` → `BlockMessage` #### BNB Chain (`bsc`) - `bsc.transactions.proto` → `ParsedAbiBlockMessage` - `bsc.tokens.proto` → `TokenBlockMessage` - `bsc.dextrades.proto` → `DexBlockMessage` - `bsc.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) Where enabled, **`bsc.broadcasted.*`** topics follow the same mapping as **`eth.broadcasted.*`**. #### Base (`base`) - `base.transactions.proto` → `ParsedAbiBlockMessage` - `base.tokens.proto` → `TokenBlockMessage` - `base.dextrades.proto` → `DexBlockMessage` - `base.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) Where enabled, **`base.broadcasted.*`** topics follow the same mapping as **`eth.broadcasted.*`**. #### Polygon (`matic`) - `matic.transactions.proto` → `ParsedAbiBlockMessage` - `matic.tokens.proto` → `TokenBlockMessage` - `matic.dextrades.proto` → `DexBlockMessage` - `matic.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) - `matic.predictions.proto` — prediction markets; decode using [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf) - `matic.broadcasted.predictions.proto` — prediction markets (broadcasted) Where enabled, **`matic.broadcasted.*`** topics for standard EVM **`transactions`**, **`tokens`**, **`dextrades`**, and **`raw`** streams follow the broadcasted mapping above. #### Optimism (`optimism`) - `optimism.transactions.proto` → `ParsedAbiBlockMessage` - `optimism.tokens.proto` → `TokenBlockMessage` - `optimism.dextrades.proto` → `DexBlockMessage` Where enabled, **`optimism.broadcasted.*`** topics follow the same mapping as **`eth.broadcasted.*`**. #### Arbitrum (`arbitrum`) - `arbitrum.transactions.proto` → `ParsedAbiBlockMessage` - `arbitrum.tokens.proto` → `TokenBlockMessage` - `arbitrum.dextrades.proto` → `DexBlockMessage` - `arbitrum.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) #### Robinhood (`robinhood`) - `robinhood.transactions.proto` → `ParsedAbiBlockMessage` - `robinhood.tokens.proto` → `TokenBlockMessage` - `robinhood.dextrades.proto` → `DexBlockMessage` - `robinhood.raw.proto` → `BlockMessage` - `robinhood.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) #### Arc Testnet (`arc-testnet`) - `arc-testnet.transactions.proto` → `ParsedAbiBlockMessage` - `arc-testnet.tokens.proto` → `TokenBlockMessage` - `arc-testnet.dextrades.proto` → `DexBlockMessage` - `arc-testnet.raw.proto` → `BlockMessage` Arc testnet is Circle's Arc Layer 1 test network (`EVM(network: arc_testnet)` in GraphQL). All `...InUSD` fields in its messages are 0 because a testnet has no token price index; native amounts are USDC, the chain's gas token. See the [Arc Testnet hub](/docs/blockchain/arc-testnet/). ### Bitcoin - `btc.transactions.proto` — decode using Bitquery Bitcoin protobuf definitions in [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf). ### Solana (`solana`) - `solana.transactions.proto` → `ParsedIdlBlockMessage` - `solana.tokens.proto` → `TokenBlockMessage` - `solana.dextrades.proto` → `DexParsedBlockMessage` ### Hyperliquid (`hyperliquid`) Message types are defined in [hyperliquid/hyperliquid_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/hyperliquid/hyperliquid_block_message.proto) and [hyperliquid/candles.proto](https://github.com/bitquery/streaming_protobuf/blob/main/hyperliquid/candles.proto). See the [Hyperliquid API documentation](/docs/perpetuals/hyperliquid) for the datasets these carry. - `hyperliquidcore.messages.proto` → `HyperliquidCoreBlockMessage` — trades, orders, book updates, liquidations, funding, TWAPs, price updates, leverage changes and signed actions, each in its own list - `hyperliquid.candles.proto` → `CandlesBlockMessage` — OHLCV candles per market and interval One block usually arrives as several `HyperliquidCoreBlockMessage` messages, each with only some lists filled, and all events of a block share its `BlockTime`. To order fills inside a block use `Execution.Index` (one sequence across `Trades` and `Liquidations`, from 1), and `OrderUpdate.Index` for order status updates; `Execution.Tid` is a hash that pairs the maker and taker rows of a fill and orders nothing. `Position.Size` on a trade or liquidation is the account's signed position size after that fill. ### Tron (`tron`) Message types per topic are defined in [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf) for Tron. - `tron.raw.proto` - `tron.transactions.proto` - `tron.tokens.proto` - `tron.dextrades.proto` - `tron.broadcasted.raw.proto` - `tron.broadcasted.transactions.proto` - `tron.broadcasted.tokens.proto` - `tron.broadcasted.dextrades.proto` Contact our support team for the topics that you can connect to for your specific needs. When subscribing, you also specify some important properties: - Configuration for offset management. It is done a bit differently in Kafka libraries, but the idea is that you have a choice of: 1. receiving only latest messages, the next time you re-connect it will re-wing to the last one. It is controlled by config: `autoCommit: false, fromBeginning: false, auto.offset.reset: latest` 2. or you want to consume all messages and do not lose any. Note that in this case when you re-start your server you will have a gap as it starts reading from the last message you received! You have to configure it as: `autoCommit: true, fromBeginning: false, auto.offset.reset: latest`. Check https://docs.confluent.io/platform/current/clients/consumer.html#offset-management-configuration for more info. - Group ID. Group ID you have to specify when creating a consumer. It **must** start with your username. In most cases you need just one group ID that can be set the same as username. You may need several group IDs in an advanced configuration when you using multiple independent applications consuming same stream. Note that you can deploy many instances of your application with same Group ID for fault tolerance and better performance. Then only one instance will receive the message from the topic, automatically re-distributing the load across your servers. Typicaly you need setup of one consumer per one topic, as the message parsing for them anyway will need different code. > Note: For Price of a Token in DEXTrades topic, you need to calculate it using the amounts. ## Read and parse messages Your consumer will read messages from the topic, and you will be able to parse them. - Depending on the setting you used to subscribe to topic, you will read the last message, or some message on the past that is the net message to read. - If you do not read messages fast enough, the lag will be accumulated, and the latency will grow. - Message in topic is Protobuf. Parse proto code is specific for programming language that you use, but should be very simple. - Message contains the list of objects on the top level. Structure of objects corresponds to the topic that you consume. General schema is described in https://github.com/bitquery/streaming_protobuf. ### What to Know About Protobuf Streams? - **Lower Latency:** These streams are delivered before the block closing message appears on the node, resulting in less lag from the transaction to the stream. - **Block Header Completeness:** The block header in messages may not be complete; only the `Slot` field is guaranteed to be correctly set. - **Compact Binary Format:** The streams use a binary protobuf format, which is more compact than JSON. - **Strict Schema:** Messages adhere to a strict schema defined in [Bitquery's Streaming Protobuf for Solana](https://github.com/bitquery/streaming_protobuf/tree/main/solana). - **Message Packing:** Transactions are packed in small chunks, with no more than 250 transactions per message. - **Message Expiration:** Topic messages expire after 24 hours in the stream. ## Best Practices {#best-practises} When working with Kafka streams, efficient message consumption and processing keep latency low and throughput high. Here are the best practices to follow: ### 1. Parallel Processing of Partitions Kafka topics are divided into partitions, and each partition must be read in parallel to maximize throughput and minimize latency. **How Partitioning Works:** - The Kafka producer sets the message key to: - **Block slot** (for Solana) - **Block hash** (for EVM chains) - This ensures that **all messages for a single block/slot are routed to the same partition**. - **Always read all partitions in parallel** to prevent message lag. - Assign **one thread per partition** to ensure balanced load distribution. ### 2. Continuous Message Consumption - Your consumer loop **should never stop** unless explicitly shutting down. - If message processing is needed, **process messages asynchronously** while keeping the reading loop running. - Avoid blocking the main consumption loop with heavy computations—delegate processing to worker threads. ### 3. Efficient Message Processing - **Batch processing** can help reduce overhead but should be balanced with latency considerations. - Use **channels and worker groups** in Golang for concurrent processing. ### Documentation References Kafka has a lot of documentation in public access, generic and programming-language-specific. Some links that you may find useful are: - [General Intro to Kafka and Concepts](https://docs.confluent.io/kafka/introduction.html) - [Javascript Guild Connecting To Kafka using KafkaJS](https://kafka.js.org/) - [Golang Client Library](https://github.com/confluentinc/confluent-kafka-go) - [Python Client Library](https://github.com/confluentinc/confluent-kafka-python) In addition, you may need a reference to Bitquery schema for messages: - [Schemas for Streaming](https://github.com/bitquery/streaming_protobuf) --- ## Kafka Streams for Blockchain Data: Topics, Setup and Examples URL: https://docs.bitquery.io/docs/category/kafka-streams/ Bitquery Kafka streams: protobuf topics for trades, transfers, balances and blocks per chain, four-hour replay, how to get access, and where each guide sits. # Kafka Streams for Blockchain Data: Topics, Setup and Examples Bitquery Kafka streams push every trade, transfer, balance change, transaction and block as protobuf messages on chain-specific topics, plus a multi-chain trading topic with USD prices. They carry the same data as the GraphQL subscriptions with a shorter pipeline, so latency is lower and a consumer can replay from an offset without gaps. Messages stay on the broker for four hours. Access uses separate SASL credentials issued by sales, not the IDE token, and Kafka is billed as its own line item, not from query points. Kafka runs server-side only; there is no browser client and no server-side filtering, so your consumer drops what it does not need. This page is the map of the Kafka section. Start with the concepts guide if Kafka is new to you, then jump to the chain and language you use. ## Which topics exist | Group | Topics | Guide | |---|---|---| | Multi-chain trading | Trades, token and pair prices with USD values across the Trading cube chains | [Multi-chain trading streams](/docs/streams/protobuf/kafka-trading-topics-protobuf) | | EVM chains | Transactions, calls, events, transfers, balances and blocks for Ethereum, BNB Chain, Base, Polygon, Optimism, Arbitrum, Robinhood Chain and Arc testnet | [EVM protobuf streams](/docs/streams/protobuf/chains/EVM-protobuf) | | Solana | Shred-level transactions, DEX trades, transfers and balances, ahead of block confirmation | [Solana shred streams](/docs/streams/protobuf/chains/Solana-protobuf) | | Solana perpetuals | Orders, fills, positions, PnL, liquidations and prices | [Solana perpetuals stream](/docs/streams/protobuf/chains/Solana-perpetual-protobuf) | | Tron | Transactions, transfers, balances and blocks | [Tron protobuf streams](/docs/streams/protobuf/chains/Tron-protobuf) | | Bitcoin | Blocks, transactions, inputs and outputs | [Bitcoin protobuf streams](/docs/streams/protobuf/chains/Bitcoin-protobuf) | | Hyperliquid | Trades, liquidations, orders, book updates, funding, TWAPs, prices, leverage changes and signed actions; OHLCV candles | [Hyperliquid Kafka streams](/docs/perpetuals/hyperliquid/#kafka-streams-protobuf) | The full topic list with names is in [Complete list of topics](/docs/streams/kafka-streaming-concepts#complete-list-of-topics). ## Pick the guide | You want to | Read | |---|---| | Understand topics, offsets, SASL auth and protobuf payloads | [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts) | | Connect, authenticate, handle offsets, timestamps and retention | [Kafka operations cookbook](/docs/streams/kafka-operations) | | Consume from Go | [Go example](/docs/streams/protobuf/kafka-protobuf-go) | | Consume from Python | [Python tutorial](/docs/streams/protobuf/kafka-protobuf-python) | | Consume from JavaScript | [JavaScript tutorial](/docs/streams/protobuf/kafka-protobuf-js) | | Keep only the messages you need | [Filtering Kafka streams](/docs/streams/protobuf/filtering_kafka_streams) | | Get Solana data before the block lands | [Real-time Solana data](/docs/streams/real-time-solana-data) | | Build your own indexer on the stream | [Real-time indexer with Kafka](/docs/streams/real-time-indexer-with-kafka-stream) | | Feed a trading bot | [Trading bot on Kafka streams](/docs/streams/sniper-trade-using-bitquery-kafka-stream) | ## Try the same data without Kafka credentials Every Kafka topic has a GraphQL subscription with the same rows, so you can see the shape of the data in the [Bitquery IDE](https://ide.bitquery.io) on a free account before asking for Kafka access. This stream is the WebSocket twin of the multi-chain trading topic, filtered to Ethereum: ```graphql subscription { Trading { Trades(where: { Pair: { Market: { NetworkBid: { is: "bid:eth" } } } }) { Block { Time } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } Side PriceInUsd AmountsInUsd { Base } } } } ``` Change `bid:eth` to `bid:solana`, `bid:bsc`, `bid:base` or another chain id from the [Crypto Price API](/docs/trading/crypto-price-api/) to switch chains. When the subscription does what you need and you want lower latency, replay from an offset or several consumers on one feed, move to the Kafka topic that carries the same rows. ## How access and billing work - Ask sales for Kafka credentials on the [official Telegram](https://t.me/Bloxy_info) or through the [website form](https://bitquery.io/forms/api). IDE tokens do not work on Kafka. - Kafka is a separate line item from the GraphQL plan. Streams are billed by simultaneous streams and stream time, not by query points; each consumer group counts as its own stream. Details are on [how billing works](/docs/plans/how-billing-works/). - Messages are kept for four hours. A consumer that is down longer than that misses data, so use offsets and monitor lag as the [operations cookbook](/docs/streams/kafka-operations) describes. ## Related pages - [Real-time blockchain data streaming: WebSocket, Kafka and gRPC compared](/docs/streams/) - [WebSocket subscriptions](/docs/subscriptions/subscription) - [Solana gRPC streams](/docs/grpc/solana/examples/pump-fun-grpc-streams/) - [Crypto Price API](/docs/trading/crypto-price-api/) --- ## Labelling Rules for Solana Wash Trades URL: https://docs.bitquery.io/docs/usecases/wash-trading-detector/prepare-data/rules/ Build Labelling Rules for Solana Wash Trades: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Labelling Rules for Solana Wash Trades This module implements a set of domain-specific rules to identify potentially suspicious DEX trades and label the column `is_wash_trades` as true against them. These rules will be applied to prepare labelled data on which the model training will occur. These rules will recieve a list of JSON objects and return a dataframe object. ## Detect Self Trades This rule flags the trades where the buyer and seller are the same wallet address(a classic wash trading indicator) as wash trades. ```py def detect_self_trades(df): return df[df["Trade.Buy.Account.Address"] == df["Trade.Sell.Account.Address"]] ``` ## Detect Repeated Pairs This rule flags wallet pairs that trade with each other more than threshold times, indicating collusion or repetitive trading behavior. ```py def detect_repeated_pairs(df, threshold=5): pairs = df.groupby([ "Trade.Buy.Account.Address", "Trade.Sell.Account.Address" ]).size().reset_index(name="count") return pairs[pairs["count"] > threshold] ``` ## Detect Loops This rule detects looped trades across different wallets, e.g., A → B → A, which may indicate sophisticated wash trading. ```py def detect_loops(df): merged = df.merge(df, left_on="Trade.Buy.Account.Address", right_on="Trade.Sell.Account.Address") loops = merged[merged["Trade.Sell.Account.Address_x"] == merged["Trade.Buy.Account.Address_y"]] return loops ``` ## Detect Spoofing This rule identifies trades with unusually large price spreads between buy/sell sides, possibly faking market depth or price manipulation. ```py def detect_spoofing(df, price_threshold=2.0): df["spread"] = abs(df["Trade.Buy.PriceInUSD"] - df["Trade.Sell.PriceInUSD"]) return df[df["spread"] > price_threshold] ``` ## Labeling Function This function combines all the above rule-based outputs, identifies wallets involved in any suspicious activity and returns the list of suspicious tokens, suspicious wallet addresses and suspicious transaction signatures. ```py def get_suspicious_summary(self_df, repeated_df, loops_df, spoofed_df, original_df): wallets = set(self_df["Trade.Buy.Account.Address"]) wallets |= set(repeated_df["Trade.Buy.Account.Address"]) wallets |= set(loops_df["Trade.Buy.Account.Address_x"]) wallets |= set(spoofed_df["Trade.Buy.Account.Address"]) suspicious_trades = original_df[ original_df["Trade.Buy.Account.Address"].isin(wallets) | original_df["Trade.Sell.Account.Address"].isin(wallets) ] suspicious_tokens = suspicious_trades["Trade.Buy.Currency.MintAddress"].unique().tolist() suspicious_tx = suspicious_trades["Transaction.Signature"].unique().tolist() return suspicious_tokens, suspicious_tx, wallets ``` --- ## LetsBonk.Fun API - Solana - New Tokens, Trades, Live Prices URL: https://docs.bitquery.io/docs/blockchain/Solana/letsbonk-api/ LetsBonk.fun on Solana: new tokens, bonding curve progress, about-to-graduate tokens, Raydium migrations, trades, prices, top buyers, OHLCV and liquidity. # LetsBonk.Fun API - Solana - New Tokens, Trades, Live Prices :::tip Need real-time LetsBonk.fun data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical LetsBonk.fun data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this document, we will explore several examples related to LetsBonk.fun. You can also check out our [Pump Fun API Docs](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) and [FourMeme API Docs](/docs/blockchain/BSC/four-meme-api/). For StonkFun launches on the same Raydium LaunchLab program, see the [StonkFun API](/docs/blockchain/Solana/stonkfun-api/) docs. For live DEX prices and volume across LetsBonk tokens, see [DEXrabbit's LetsBonk category](https://dexrabbit.bitquery.io/categories/letsbonk-fun-ecosystem). :::note **LetsBonk.fun tokens are created and traded on Raydium Launchlab.** ::: Need zero-latency LetsBonk.fun data? [Read about our Shred Streams and Contact us for a Trial](/docs/streams/real-time-solana-data/). :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: If you want fastest data without any latency, we can provide Kafka streams, please [fill this form](https://bitquery.io/forms/api) for it. Our Team will reach out. ## Track LetsBonk.fun Token Creation Using [this](https://ide.bitquery.io/latest-token-created-on-letsbonk-fun-in-realtime_2) query, we can get the realtime created LetsBonk.fun tokens.
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } Method: { is: "initialize_v2" } } Accounts: { includes: { Address: { is: "FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1" } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method Name } } Transaction { Signature Signer } } } } ```
## Bonding Curve Progress API Below query will give you the Bonding curve progress percentage of a specific LetsBonk.fun Token. ### Bonding Curve Progress Formula - **Formula**: BondingCurveProgress = 100 - ((leftTokens \* 100) / initialRealTokenReserves) Where: - leftTokens = realTokenReserves - reservedTokens - initialRealTokenReserves = totalSupply - reservedTokens - **Definitions**: - `initialRealTokenReserves` = `totalSupply` - `reservedTokens` - `totalSupply`: 1,000,000,000 (LetsBonk.fun Token) - `reservedTokens`: 206,900,000 - Therefore, `initialRealTokenReserves`: 793,100,000 - `leftTokens` = `realTokenReserves` - `reservedTokens` - `realTokenReserves`: Token balance at the market address. :::note **Simplified Formula**: BondingCurveProgress = 100 - (((balance - 206900000) \* 100) / 793100000) ::: ### Additional Notes - **Balance Retrieval**: - The `balance` is the token balance at the market address. - Use this query to fetch the balance and then we use `expressions` to calculate the bonding curve progress percentage in the query itself: [Query Link](https://ide.bitquery.io/bonding-curve-progress-percentage-of-a-letsbonkfun-token).
Click to expand GraphQL query ```graphql query GetBondingCurveProgressPercentage { Solana { DEXPools( limit: { count: 1 } orderBy: { descending: Block_Slot } where: { Pool: { Market: { BaseCurrency: { MintAddress: { is: "CctsjizSC6pwf2T8bhdHdZTEV4PEcfXoumjeK7FBbonk" } } } Dex: { ProgramAddress: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100-((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PriceInUSD PostAmountInUSD } Base { Balance: PostAmount } } } } } ```
## Track LetsBonk.fun Tokens above 95% Bonding Curve Progress in realtime We can use above Bonding Curve formulae and get the Balance of the Pool needed to get to 95% and 100% Bonding Curve Progress range. And then track liquidity changes which result in `Base{PostAmount}` to fall in this range. Run the query: [LetsBonk.fun tokens between 95–100% bonding-curve progress ➤](https://ide.bitquery.io/LetsBonkfun-Tokens-between-95-and-100-bonding-curve-progress_2).
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { DEXPools( where: { Pool: { Base: { PostAmount: { gt: "206900000", lt: "246555000" } } Dex: { ProgramAddress: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } } Market: { QuoteCurrency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" ] } } } } Transaction: { Result: { Success: true } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { BaseCurrency { MintAddress Name Symbol } MarketAddress QuoteCurrency { MintAddress Name Symbol } } Dex { ProtocolName ProtocolFamily } Base { Balance: PostAmount } Quote { PostAmount PriceInUSD PostAmountInUSD } } } } } ```
## Top 100 About to Graduate LetsBonk.fun Tokens We can use below query to get top 100 About to Graduate LetsBonk.fun Tokens. Run the query: [Top 100 tokens about to graduate (Raydium LaunchLab) ➤](https://ide.bitquery.io/Top-100-graduating-raydium-launchlab-tokens-in-last-5-minutes).
Click to expand GraphQL query ```graphql { Solana { DEXPools( limitBy: { by: Pool_Market_BaseCurrency_MintAddress, count: 1 } limit: { count: 100 } orderBy: { ascending: Pool_Base_PostAmount } where: { Pool: { Base: { PostAmount: { gt: "206900000" } } Dex: { ProgramAddress: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } } Market: { QuoteCurrency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" ] } } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { BaseCurrency { MintAddress Name Symbol } MarketAddress QuoteCurrency { MintAddress Name Symbol } } Dex { ProtocolName ProtocolFamily } Base { Balance: PostAmount(maximum: Block_Time) } Quote { PostAmount PriceInUSD PostAmountInUSD } } } } } ```
## Get all the instructions of Raydium LaunchLab Below query will get you all the instructions that the Raydium LaunchLab Program has. Run the query: [All instructions of Raydium LaunchLab program ➤](https://ide.bitquery.io/all-the-instructions-of-Raydium-LaunchLab).
Click to expand GraphQL query ```graphql query MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}}}} ) { Instruction { Program { Method } } count } } } ```
## Track LetsBonk.fun Token Migrations to Raydium DEX and Raydium CPMM in Realtime Using above `get all instructions` api, you will figure out that there are 2 instructions `migrate_to_amm`, `migrate_to_cpswap` whose invocations migrate the Raydium LaunchLab Token to Raydium V4 AMM and Raydium CPMM Dexs respectively. Thats why we have filtered for these 2 instructions in the below API, and tracking these. And `FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1` is the LetsBonk.fun Platform address, and we are filtering for the instructions where the above listed methods are invoked and the letsbonk.fun platform config address is present in Instruction Accounts Array. Run the stream: [Track LetsBonk.fun token migrations to Raydium ➤](https://ide.bitquery.io/Track-letsBonkfun-Token-Migrations-to-Raydium-DEX-and-Raydium-CPMM-in-realtime).
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["migrate_to_amm", "migrate_to_cpswap"]}}, Accounts: {includes: {Address: {is: "FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1"}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Program { Method AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } } Type Name } Name } Accounts { Address IsWritable Token { ProgramId Owner Mint } } } Transaction { Signature Signer } } } } ```
## Track LetsBonk.fun, Raydium Launchlab, Meteora DBC, Boop.fun and Moonshot Token Migrations in a single subscription Use this single subscription to stream real-time token migration events across Boop.fun, Raydium Launchlab, Meteora DBC, and Moonshot. It filters by the respective program IDs and migration methods, returning block time, program details, involved accounts, and transaction signatures as events occur. Try out the [API](https://ide.bitquery.io/Raydium-Launchlab-Meteora-DBC-BoopFun-Moonshot-LetsBonkfun-token-migrations-in-realtime_2) here on IDE.
Click to expand GraphQL query ```graphql subscription{ Solana { Instructions( where: {any: [{Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {is: "initialize_v2"}}}}, {Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "graduate"}}}}, {Instruction: {Program: {Address: {is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG"}, Method: {is: "migrateFunds"}}}}, {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["migrate_meteora_damm", "migration_damm_v2"]}}}}, {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["migrate_to_amm", "migrate_to_cpswap"]}}, Accounts: {includes: {Address: {is: "FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1"}}}}}], Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Launchlab # boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4 - boop.fun # MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG - Moonshot/Moonit # dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN - Meteora DBC # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Program Address and FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1(letsbonk.fun platform config addr) is present in Accounts array then its Letsbonk.fun migration Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method Name } } Transaction { Signature Signer } } } } ```
## Latest Trades of LetsBonk.fun Tokens using the Trading API This query fetches the most recent LetsBonk.fun trades from the [Trading cube](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) — by filtering on the Raydium LaunchLab program address. Every row includes the USD price and market cap of the token at the time of the trade. To narrow it down to a single token, add `Currency: { Id: { is: "token Mint Address" } }` inside the `Pair` filter. Run the query: [LetsBonk trades using Trading API ➤](https://ide.bitquery.io/Lets-bonk-using-Trading-API)
Click to expand GraphQL query ```graphql query LatestLetsBonkTrades { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } Program: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } } } } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Side Block { Time } Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Supply { MarketCap } Trader { Address } Pair { Currency { Symbol Name } QuoteCurrency { Symbol } Market { Address Program Network Protocol } } } } } ```
Note that in `Trading.Trades`, `Price` and `PriceInUsd` are plain float fields with no sub-selection. To get trades in real time, change `query` to `subscription` and remove the `orderBy` and `limit` arguments. The same can be tracked using [Bitquery Kafka Streams](/docs/streams/kafka-streaming-concepts/). ## Latest Price of a LetsBonk.fun Token on Raydium Lanchlab This query provides the most recent price data for a specific LetsBonk.fun token `token Mint Address` launched on Raydium Launchpad. You can filter by the token’s `MintAddress`, and the query will return the last recorded trade price. Run the query: [Latest price of a LetsBonk.fun token ➤](https://ide.bitquery.io/Latest-Price-of-a-LetsBonkfun-Token-on-Launchpad)
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 1 } where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token Mint Address" } } } } ) { Block { Time } Transaction { Signature } Trade { Market { MarketAddress } Dex { ProtocolName ProtocolFamily } AmountInUSD PriceInUSD Amount Currency { Name } Side { Type Currency { Symbol MintAddress Name } AmountInUSD Amount } } } } } ```
## Top Buyers of a LetsBonk.fun Token on LaunchPad [This](https://ide.bitquery.io/top-buyers-of-a-letsbonkfun-token-on-launchpad) API endpoint returns the top 100 buyers for a token, which is `token Mint Address` in this case.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token Mint Address" } } Side: { Type: { is: buy } } } } orderBy: { descendingByField: "buy_volume" } limit: { count: 100 } ) { Trade { Currency { MintAddress Name Symbol } } Transaction { Signer } buy_volume: sum(of: Trade_Side_AmountInUSD) } } } ```
## Top Sellers of a Token on LaunchPad Using [this](https://ide.bitquery.io/top-sellers-of-a-letsbonkfun-token-on-launchpad_1) query top 100 sellers for the token with `Mint Address` as `token Mint Address` could be retrieved.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token Mint Address" } } Side: { Type: { is: sell } } } } orderBy: { descendingByField: "sell_volume" } limit: { count: 100 } ) { Trade { Currency { MintAddress Name Symbol } } Transaction { Signer } sell_volume: sum(of: Trade_Side_AmountInUSD) } } } ```
## OHLCV for specific LetsBonk.fun Token on Raydium Launchlab [This](https://ide.bitquery.io/ohlc-for-letsbonkfun-token) API end point returns the OHLCV vlaues for a LetsBonk.fun token with the currency `mint address` as `token mint address` when traded against WSOL.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token Mint Address" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } Transaction: { Result: { Success: true } } } limit: { count: 100 } orderBy: { descendingByField: "Block_Timefield" } ) { Block { Timefield: Time(interval: { count: 1, in: minutes }) } Trade { open: Price(minimum: Block_Slot) high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) close: Price(maximum: Block_Slot) } volumeInUSD: sum(of: Trade_Side_AmountInUSD) count } } } ```
## Get Pair Address for a LetsBonk.fun Token [This](https://ide.bitquery.io/pool-address-for-letsbonkfun-token_1) query returns the pair address for the LetsBonk.fun token with `mint address` as `token Mint Address` on the LaunchPad exchange. The liquidity pool address is denoted by `MarketAddress`.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token Mint Address" } } } } ) { Trade { Market { MarketAddress } Currency { Name Symbol MintAddress } Side { Currency { Name Symbol MintAddress } } } count } } } ```
## Get Liquidity for a LetsBonk.fun Token Pair Address Using [this](https://ide.bitquery.io/liquidity-for-a-Letsbonkfun-token-pair_2) query we can get the liquidity for a LaunchPad Token Pair, where `Base_PostBalance` is the amount of LaunchPad tokens present in the pool and `Quote_PostBalance` is the amount of WSOL present in the pool. For the purpose of filtering we are applying the condition that the `MarketAddress` is `insert pool address`.
Click to expand GraphQL query ```graphql { Solana { DEXPools( where: { Pool: { Market: { MarketAddress: { is: "token pool address" } } } Transaction: { Result: { Success: true } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Pool { Base { PostAmount } Quote { PostAmount } Market { BaseCurrency { MintAddress Name Symbol } QuoteCurrency { MintAddress Name Symbol } } } } } } ```
### Video Tutorial | How to get Bonding Curve Progress of any LetsBonk.fun Token ### Video Tutorial | How to track LetsBonk.fun Token Migrations to Raydium in realtime ### Video Tutorial | How to get Top 100 About to Graduate LetsBonk.fun tokens --- ## LetsBonk.fun gRPC Streams - Real-time DEX Trades URL: https://docs.bitquery.io/docs/grpc/solana/examples/letsbonk-grpc-streams/ LetsBonk.fun gRPC Streams - Real-time DEX Trades for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # LetsBonk.fun gRPC Streams Real-time streaming of LetsBonk.fun DEX trades, orders, and transactions via CoreCast gRPC API. ## Repository 🔗 [**GitHub Repository**](https://github.com/bitquery/grpc-usecase-examples/tree/main/Solana/lets-bonk-fun-example) Clone and get started: ```bash git clone https://github.com/bitquery/grpc-usecase-examples.git ``` ## Introduction This Node.js client allows you to stream real-time trading data from LetsBonk.fun (Solana's memecoin launchpad built on Raydium LaunchLab) using the CoreCast gRPC API. Monitor token launches, track buying/selling pressure, detect whale activity, and analyze trading patterns in real-time. **Key Features:** - 🚀 Real-time trade streaming from LetsBonk.fun - 🎯 Flexible filtering by tokens, traders, and trade direction - 💰 Separate buy and sell trade monitoring - 📊 Performance metrics and statistics - 🔍 Detailed trade information including accounts and currencies - ⚡ High-performance with caching and buffering ## Quick Start ```bash # 1. Install dependencies npm install # 2. Get your API token # Visit: https://account.bitquery.io/user/api_v2/access_tokens # 3. Configure your filters in config.yaml # Edit the file to set your auth token and desired filters # 4. Run the client node index.js ``` ## What is LetsBonk.fun? LetsBonk.fun tokens are created and traded on **Raydium LaunchLab** (Program: `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj`). ## Trade Data Structure When you stream LetsBonk.fun trades, each message contains: ### Trade Event Structure ```javascript { Block: { Slot: 370485092 // Solana block slot number }, Transaction: { Index: 1, Signature: "5277PwHQ4PkKRExT45HV8X8XXDmQjWZzHK8dx5ru1eaA...", Status: { Success: true, ErrorMessage: null }, Header: { Fee: 5000, FeePayer: "8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m", Signer: "8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m" }, FeeInUsd: 0.00075 }, Trade: { InstructionIndex: 2, Dex: { ProgramAddress: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj", ProtocolName: "raydium_launchpad", ProtocolFamily: "raydium" }, Market: { MarketAddress: "YcQB1hGSR9hNbJ52zrCJyMvbRViQKiaLfenrgZR9BXY", BaseCurrency: { Symbol: "BONKTOKEN", Name: "Bonk Token", MintAddress: "CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk", Decimals: 6 }, QuoteCurrency: { Symbol: "SOL", MintAddress: "So11111111111111111111111111111111111111112", Decimals: 9 } }, Buy: { Amount: 100000000, Currency: { Symbol: "BONKTOKEN", MintAddress: "CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk", Decimals: 6 }, Account: { Address: "8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m", IsSigner: true, IsWritable: true } }, Sell: { Amount: 500000000, Currency: { Symbol: "SOL", MintAddress: "So11111111111111111111111111111111111111112", Decimals: 9 }, Account: { Address: "8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m", IsSigner: true, IsWritable: true } }, Fee: 0, Royalty: 0 } } ``` ### Key Fields | Field | Description | | -------------------------------- | --------------------------------- | | `Trade.Buy.Amount` | Amount of token being bought | | `Trade.Sell.Amount` | Amount of token being sold | | `Trade.Buy.Currency.MintAddress` | Token mint address | | `Trade.Buy.Account.Address` | Buyer's wallet address | | `Trade.Dex.ProgramAddress` | Raydium LaunchLab program address | | `Trade.Market.MarketAddress` | Market/pool address for the token | | `Transaction.Header.Fee` | Transaction fee in lamports | | `Transaction.FeeInUsd` | Transaction fee in US dollars | | `Block.Slot` | Solana block slot for timing | ## Configuration Options Edit `config.yaml` to configure your stream: ### Trade Filter Options ```yaml trade_filter: "alltrades" # or "buys" or "sells" ``` | Value | Description | | ----------- | ------------------------------------------------ | | `alltrades` | Show all trades (both buys and sells) | | `buys` | Show only trades where the token is being bought | | `sells` | Show only trades where the token is being sold | ### Available Filters | Filter | Description | Example | | ---------- | -------------------------------- | --------------------------------------------- | | `programs` | Filter by DEX program address | `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` | | `tokens` | Filter by token mint address(es) | Your token mint address | | `traders` | Filter by wallet address(es) | Specific trader wallets | ## Filter Examples ### 1. Monitor ALL trades for a specific token on LetsBonk.fun Track all trading activity (both buys and sells) for a specific token. ```yaml trade_filter: "alltrades" filters: programs: - "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" tokens: - "CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk" ``` **Use Case**: General market monitoring, volume analysis --- ### 2. Monitor only BUYS for a specific token on LetsBonk.fun Track buying pressure - see when traders are accumulating the token. ```yaml trade_filter: "buys" filters: programs: - "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" tokens: - "CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk" ``` **Use Case**: Track accumulation patterns, detect buying momentum --- ### 3. Monitor only SELLS for a specific token on LetsBonk.fun Track selling pressure - detect when traders are dumping the token. ```yaml trade_filter: "sells" filters: programs: - "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" tokens: - "CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk" ``` **Use Case**: Detect sell pressure, identify dumps, risk monitoring --- ### 4. Monitor multiple tokens on LetsBonk.fun Track trading activity across multiple tokens simultaneously. ```yaml trade_filter: "alltrades" filters: programs: - "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" tokens: - "CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk" - "4FBx5RBfEuuhkT5RB7kJ46WC6cL9J4SJNXyKeoDAbonk" ``` **Use Case**: Portfolio tracking, multi-token analysis --- ### 5. Monitor buying activity for a specific trader Track when a specific wallet buys a specific token. ```yaml trade_filter: "buys" filters: programs: - "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" tokens: - "CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk" traders: - "YourWalletAddressHere" ``` **Use Case**: Copy-trading specific whales, alpha signal detection ## Output Example When a trade matches your filters, you'll see: ``` ================================================================================ 🟢 BUY Trade ================================================================================ Block Slot: 370485092 Timestamp: 2025-10-01T13:11:32.922Z Instruction Index: 2 📍 DEX Info: Program: LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj Protocol: raydium_launchpad (raydium) 🏪 Market Info: Address: YcQB1hGSR9hNbJ52zrCJyMvbRViQKiaLfenrgZR9BXY Base Currency: BONKTOKEN Quote Currency: SOL 💰 Buy Side: Amount: 100000000 Currency: BONKTOKEN (Bonk Token) Mint: CHNxstQ6zsj9b7QMmCKbnJkhyKwoTL19bPe6VYoebonk Decimals: 6 Account: 8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m Is Signer: true Is Writable: true 💸 Sell Side: Amount: 500000000 Currency: SOL (Wrapped SOL) Mint: So11111111111111111111111111111111111111112 Decimals: 9 Account: 8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m Is Signer: true Is Writable: true 💵 Fee: 0 👑 Royalty: 0 ================================================================================ ``` --- ## Lighter Perp DEX on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/lighter-perp-dex-api/ Lighter perp DEX on Robinhood Chain: USDG margin deposits and withdrawals, ZkLighter rollup contract and batch commits via Bitquery GraphQL and WebSocket. # Lighter Perp DEX on Robinhood Chain [Lighter](https://lighter.xyz) is the perpetual-futures DEX integrated into Robinhood Wallet. When Robinhood Chain mainnet went live on July 1, 2026, Lighter launched alongside it as the venue behind in-app perps: eligible users post **USDG** margin from their wallet, and the funds are locked in Lighter's smart contract on Robinhood Chain while positions are managed by Lighter's zk engine. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). What actually lives on Robinhood Chain is a full **ZkLighter rollup contract** — not just a token vault. It receives every margin deposit, queues and pays withdrawals, and records the rollup's batch lifecycle (`commit → verify → execute`) at roughly **one batch per minute**. This page shows how to query and stream all of it with Bitquery's `EVM` cubes on `network: robinhood`. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Events API](/docs/blockchain/robinhood/robinhood-events-api/) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) - [Robinhood Calls API](/docs/blockchain/robinhood/robinhood-calls-api/) - [Robinhood Balances API](/docs/blockchain/robinhood/robinhood-balances-api/) - [EVM Events schema](/docs/schema/evm/events/) ::: **On this page:** [What is on-chain](#what-is-on-chain-and-what-is-not) · [Contracts](#contract-map) · [Event reference](#event-reference-topic0-map) · [Deposits](#track-margin-deposits) · [Withdrawals](#track-withdrawals) · [Margin flow & history](#usdg-margin-flow-full-history) · [Rollup heartbeat](#monitor-the-rollup-heartbeat) · [Deposit calls](#deposit-calls-by-selector) · [Decoding notes](#decoding-notes) --- ## What is on-chain (and what is not) Lighter's matching engine, order book, positions, funding, and liquidations run inside its zk rollup — they are **not** individual Robinhood Chain transactions. What settles on Robinhood Chain, and what Bitquery therefore indexes, is: | On Robinhood Chain (queryable here) | Inside the Lighter engine (not on-chain) | | --- | --- | | USDG margin **deposits** into the ZkLighter contract | Individual trades and fills | | **Withdrawal** queue events and USDG payouts back to users | Open positions and PnL | | Rollup **batch lifecycle**: commit, verification, execution, state roots | Funding payments (hourly, peer-to-peer) | | Priority requests (forced operations, key changes, escape hatches) | Order placement and cancellation (except the on-chain `cancelAllOrders` escape hatch) | | Market/asset registry events | Liquidation events themselves (only the margin effects appear) | This makes the on-chain data ideal for **money-flow questions** — who is depositing margin, how much, net flows, contract TVL, whether the rollup operator is alive — rather than trade-level analytics. --- ## Contract map | Role | Address | | --- | --- | | **ZkLighter proxy** — receives margin, pays withdrawals, emits every Lighter event | `0x94bab9693ba2f6358507effcbd372b0660afff9d` | | Current verified implementation (`ZkLighter`) | `0x82DE5B1161C93afDFE21bA0D5343f01Cd7401d90` | | USDG (Global Dollar, 6 decimals) — canonical currency address in Bitquery cubes | `0x5fc5360d0400a0fd4f2af552add042d716f1d168` | | Robinhood deposit router (sweeps in-app deposits into `deposit()`) | `0x8062df5b3220ad1f528365650a3eb3e8c7b0dad1` | :::info Filter by LogHeader.Address, not Log.SmartContract The ZkLighter proxy delegates to implementation modules, so `Log.SmartContract` shows the **implementation** address — and implementations rotate on upgrades (implementations rotate over time; older module addresses you may see in results include `0x1be72833…`, `0xe470e41c…`, and `0xda2b59ff…`). The stable anchor is `LogHeader.Address` = the proxy `0x94bab969…`, combined with the event's `SignatureHash` (topic0). Every query below follows that pattern. ::: --- ## Event reference (topic0 map) All events are emitted with the proxy as `LogHeader.Address`. Hash fields in Bitquery are hex strings **without** a `0x` prefix. | Event | topic0 (`Log.Signature.SignatureHash`) | | --- | --- | | `Deposit(uint48 toAccountIndex, address toAddress, uint16 assetIndex, uint8 routeType, uint128 baseAmount)` | `493c3b8240368e8343bcd42cac5f4b8b161c06d061710e542a72f06a40ddd9d1` | | `WithdrawPending(address indexed owner, uint16 assetIndex, uint128 baseAmount)` | `ef80235b5f4cf1822ad6a8621af41ac64372ff672c402874f507fc63dbe5e06f` | | `NewPriorityRequest(address sender, uint64 serialId, uint8 pubdataType, bytes pubData, uint64 expirationTimestamp)` | `efdd379e3e15772fcc7d2a67fa5bbb0790b932724153aded4648307094733b2f` | | `BatchCommit(uint64 batchNumber, uint32 batchSize, uint64 endBlockNumber)` | `181b25ea9d4d730f30d779f3d2099c03b26b653c889d33eef253d54baaacbd0d` | | `BatchVerification(uint64 batchNumber, uint32 batchSize, uint64 endBlockNumber)` | `5c836e1ff20ea85c52b6e3d2ef0124d3304bf3b37cc8fb0e2c84ae7d44c0593e` | | `BatchesExecuted(uint64 batchNumber, uint64 endBlockNumber)` | `5d490d991d08230b7690c7511bb854b7b8a05fb7c87e2348e1909384cb325511` | | `StateRootUpdate(uint64 batchNumber, bytes32 oldStateRoot, bytes32 newStateRoot)` | `645e0b8f839353842bdac87abd27fc8bdda536e0731cdb7cc75e4f0740b575ac` | | `CreateMarket((uint16,uint8,bytes), uint8 sizeDecimals, uint8 priceDecimals, bytes32 symbol)` | `134f63a6bbe3b3ef885ce4067eb2753fe1c912c51c4b8e0cc7966f21773c047e` | | `RegisterAssetConfig(uint16 assetIndex, address tokenAddress, …)` | `f1b24e81016b9f39e2290cf2a9303264a07534a569df7e6200a39573d7f26b0c` | The remaining admin events (`UpdateMarket`, `UpdateAssetConfig`, `BatchesRevert`, `DesertMode`, `TreasuryUpdate`, `InsuranceFundOperatorUpdate`, `Initialized`) exist in the ABI but fire rarely; the full verified ABI is on the [Robinhood Chain explorer](https://robinhoodchain.blockscout.com/address/0x82DE5B1161C93afDFE21bA0D5343f01Cd7401d90?tab=contract). --- ## Track margin deposits Every deposit into Lighter emits one `Deposit` event. This query returns the latest ones; turn it into a live stream by replacing `query` with `subscription` and dropping `dataset`/`limit`/`orderBy`. ```graphql { EVM(network: robinhood, dataset: realtime) { Events( limit: { count: 10 } orderBy: { descending: Block_Number } where: { LogHeader: { Address: { is: "0x94bab9693ba2f6358507effcbd372b0660afff9d" } } Log: { Signature: { SignatureHash: { is: "493c3b8240368e8343bcd42cac5f4b8b161c06d061710e542a72f06a40ddd9d1" } } } } ) { Block { Number Time } Transaction { Hash From } Log { SmartContract Signature { SignatureHash } } LogHeader { Address Data } } } } ``` `Deposit` has no indexed parameters, so all five fields sit in `LogHeader.Data` as 32-byte words, in ABI order: | Word | Field | Notes | | --- | --- | --- | | 0 | `toAccountIndex` | The user's Lighter account index | | 1 | `toAddress` | The wallet credited — for Robinhood-app deposits this is the user's deposit address, while the ERC-20 transfer arrives via the router `0x8062df5b…` | | 2 | `assetIndex` | `3` = USDG on this deployment | | 3 | `routeType` | `0` for ~98% of deposits | | 4 | `baseAmount` | Raw token units — divide by 10⁶ for USDG (verified to match the ERC-20 transfer in the same transaction) | --- ## Track withdrawals Withdrawals are two-step: the rollup queues the amount (`WithdrawPending`, with the receiving wallet **indexed** as `Topics[1]`), then operator transactions push the USDG payout to the user via `withdrawPendingBalance`. To watch the queue: ```graphql { EVM(network: robinhood, dataset: realtime) { Events( limit: { count: 10 } orderBy: { descending: Block_Number } where: { LogHeader: { Address: { is: "0x94bab9693ba2f6358507effcbd372b0660afff9d" } } Log: { Signature: { SignatureHash: { is: "ef80235b5f4cf1822ad6a8621af41ac64372ff672c402874f507fc63dbe5e06f" } } } } ) { Block { Number Time } Transaction { Hash } Topics { Hash } # Topics[1] = padded owner address LogHeader { Data } # [assetIndex, baseAmount(6dp)] } } } ``` The actual payout is a plain USDG transfer **from** the proxy, so the Transfers query below covers the money leg of withdrawals too. --- ## USDG margin flow (full history) The simplest lens on Lighter needs no event decoding at all: USDG transfers to the proxy are margin in, transfers from it are margin out. The `combined` dataset holds Robinhood Chain history back to the chain's start, so this works from Lighter's first deposit (June 26, 2026 — a soft start a few days before the public July 1 launch). Monthly deposit and withdrawal totals since launch: ```graphql { EVM(network: robinhood, dataset: combined) { deposits: Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Receiver: { is: "0x94bab9693ba2f6358507effcbd372b0660afff9d" } } } ) { Block { Date(interval: { count: 1, in: months }) } count sum(of: Transfer_Amount) } withdrawals: Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Sender: { is: "0x94bab9693ba2f6358507effcbd372b0660afff9d" } } } ) { Block { Date(interval: { count: 1, in: months }) } count sum(of: Transfer_Amount) } } } ``` Swap the monthly interval for a `days` interval for daily flow charts, or drop the aggregation and add `limit`/`orderBy` to list individual transfers with sender and receiver. The difference between lifetime deposits and withdrawals is the contract's standing USDG balance — Lighter-on-Robinhood's margin TVL. To size total activity, an aggregate probe over full history: ```graphql { EVM(network: robinhood, dataset: combined) { Events( where: { LogHeader: { Address: { is: "0x94bab9693ba2f6358507effcbd372b0660afff9d" } } Log: { Signature: { SignatureHash: { is: "493c3b8240368e8343bcd42cac5f4b8b161c06d061710e542a72f06a40ddd9d1" } } } } ) { count earliest: Block { Time(minimum: Block_Time) } latest: Block { Time(maximum: Block_Time) } } } } ``` --- ## Monitor the rollup heartbeat Lighter posts its zk batch lifecycle to Robinhood Chain about once a minute. Streaming the three lifecycle events is a ready-made **liveness monitor** for the venue — if commits stop, the engine or its operator has a problem: ```graphql subscription { EVM(network: robinhood) { Events( where: { LogHeader: { Address: { is: "0x94bab9693ba2f6358507effcbd372b0660afff9d" } } Log: { Signature: { SignatureHash: { in: [ "181b25ea9d4d730f30d779f3d2099c03b26b653c889d33eef253d54baaacbd0d" "5c836e1ff20ea85c52b6e3d2ef0124d3304bf3b37cc8fb0e2c84ae7d44c0593e" "5d490d991d08230b7690c7511bb854b7b8a05fb7c87e2348e1909384cb325511" ] } } } } ) { Block { Number Time } Transaction { Hash From } Log { Signature { SignatureHash } } LogHeader { Data } # batchNumber, batchSize, endBlockNumber } } } ``` Each of `commitBatch`, `verifyBatch`, and `executeBatches` is sent by a single operator EOA, so `Transaction.From` also identifies the Lighter operator. --- ## deposit() calls by selector The Calls cube gives the function-call view of the same activity — useful for catching deposits, forced withdrawals (`withdraw`, selector `d20191bd`), key registrations (`changePubKey`, `17010c68`), and escape-hatch cancels (`cancelAllOrders`, `a4b6f756`): ```graphql { EVM(network: robinhood, dataset: realtime) { Calls( limit: { count: 10 } orderBy: { descending: Block_Number } where: { Call: { To: { is: "0x94bab9693ba2f6358507effcbd372b0660afff9d" } Signature: { SignatureHash: { is: "8a857083" } } # deposit(address,uint16,uint8,uint256) } } ) { Block { Number Time } Call { From Value Signature { SignatureHash } } Transaction { Hash From } } } } ``` --- ## Decoding notes - **Signatures currently arrive unparsed** — `Log.Signature.Name` is empty for ZkLighter events until the ABI is registered in the decoding pipeline, so filter by `SignatureHash` (as every query on this page does) and decode `LogHeader.Data` client-side with the word layouts above. Once the ABI lands, the same queries also return decoded `Arguments`. - `LogHeader.Address` is the address a node's `eth_getLogs` would report; `Log.SmartContract` is the implementation behind the proxy and changes on upgrades. Pin queries to `LogHeader.Address`. - Amounts (`baseAmount` and USDG `Transfer.Amount`) are 6-decimal USDG units; `Transfer.Amount` in the API is already decimal-adjusted. - Robinhood in-app deposits are swept from per-user deposit addresses through the router `0x8062df5b…`, so the ERC-20 `Transfer.Sender` into the proxy is often the router while the credited wallet is `Deposit.toAddress`. Count depositors from the `Deposit` event, not from transfer senders. - For trade-level perps data (fills, positions, funding), use Lighter's own venue APIs — that activity never touches Robinhood Chain. On-chain data here answers flow, TVL, user-count, and liveness questions. Every query on this page was executed against the production `streaming.bitquery.io/graphql` endpoint before publishing. --- ## Limit Order Price API URL: https://docs.bitquery.io/docs/trading/crypto-price-api/limit-order-price-api/ A price feed for limit orders: Bitquery's aggregated Trading cube prices (blended tokens, rank-1 pairs, cross-chain currencies) instead of raw DEX trades, with queries, streams and a TradingView datafeed. # Limit Order Price API ## What it is Raw DEX trades make a bad trigger for limit orders: one swap in a thin pool, a sandwich leg or an MEV print can print far from the market and fire an order that should have stayed inactive. The Trading cubes give an aggregated price instead: OHLC and averages per interval, blended across a token's pools by liquidity, with outlier pools kept out of the blend. ## How to get it All three routes are on the Trading cubes at `https://streaming.bitquery.io/graphql`, as a query, a `subscription`, or the `trading.prices` Kafka topic. - **`Tokens`**: one price per token per interval, blended across every pool. Smoothest; thin pools still carry a small weight. - **`Pairs` with `Ranking: { Position: { eq: 1 } }`**: the price of the pool with the most weight in the blend, followed automatically as pools change. Closest to the price you can execute against. - **`Currencies`**: one price per asset across chains, such as `bid:bitcoin` or `bid:eth`. Set `Interval.Time.Duration` to one of `1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600` seconds. `Network` filters take display names (`"Ethereum"`, not `"ethereum"`). The rank-1 stream for SOL on Solana: [Try SOL rank-1 pair stream ➤](https://ide.bitquery.io/SOL-USDC-pair-trading-data) ```graphql subscription { Trading { Pairs( where: { Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 1}}} } ) { Block { Time } Market { Name } Pool { Address } QuoteToken { Symbol } Price { Ohlc { Close } } Volume { Base Quote Usd } Liquidity { Usd Source } Ranking { Position Weight } } } } ``` See [Getting the most accurate token price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) for how rank 1 behaves. **TradingView.** A datafeed over these streams gives live bars at every interval from 1 s to 1 h: [tutorial](/docs/usecases/tradingview-subscription-realtime/getting-started/), [repository and demo](https://github.com/bitquery/tradingview-subscription-realtime/tree/main#demo), [`@bitquery/tradingview-sdk`](https://www.npmjs.com/package/@bitquery/tradingview-sdk). ## How it is derived A `Tokens` row blends the interval's pool prices. Each pool is weighted by its liquidity after the staleness discount: a measured reserve where the index has one, a volume-derived estimate otherwise. Pools the blend rejects as outliers or ineligible contribute no price, and rank 1 on `Pairs` is the pool with the largest discounted liquidity share. Since 2026-10-19 the blend is liquidity-weighted; rows before that date in the 30-day history are volume-weighted. The full method, including which trades are filtered out, is on the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) page. ## Examples ### What does a raw trade feed look like next to the aggregated one? Raw trades from `DEXTradeByTokens` on the chain schema: ```graphql subscription { EVM { DEXTradeByTokens( where: {Trade: {Currency: {Symbol: {is: "WETH"}}}} ) { Trade { PriceInUSD AmountInUSD } Block { Time } } } } ``` [Run this query ➤](https://ide.bitquery.io/ETH-price-raw-trades) - Every swap prints, including sandwich legs, MEV prints and thin-pool fills. A limit order keyed to `PriceInUSD` fires on the first bad print. The same token through `Tokens` at 5-second intervals: ```graphql subscription { Trading { Tokens( where: { Token: {Symbol: {is: "WETH"}, Network: {is: "Ethereum"}} Interval: {Time: {Duration: {eq: 5}}} } ) { Price { Ohlc { Open High Low Close } Average { Mean SimpleMoving WeightedSimpleMoving } } Volume { Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` [Run this query ➤](https://ide.bitquery.io/ETH-aggregated-5s-intervals) - One row per 5 s with OHLC, `Average.Mean` and moving averages; key the order to `Average.Mean` or `Ohlc.Close`. - A single bad print in one pool is a small share of the liquidity-weighted blend, so it does not move the row to the trigger. - [Side-by-side comparison in the IDE ➤](https://ide.bitquery.io/raw-vs-aggregated-price-comparison) ### Which interval should a limit order watch? Available intervals: `1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600` seconds. - **1–3 s**: fast bots, minimal smoothing. - **5–10 s**: typical automated platforms. - **30–60 s**: swing trading and portfolio management. - **300 s and up**: position management. [Real-time 1-second price stream ➤](https://ide.bitquery.io/1-second-crypto-price-stream) and [multi-interval aggregation ➤](https://ide.bitquery.io/crypto-price-multiple-intervals). ### Can I aggregate by traded volume instead of time? Not as of October 2026: `Interval.VolumeBased` and `Interval.TargetVolume` exist in the schema but carry no rows, so filtering on them returns zero rows with HTTP 200 and no error. Approximate the intent with a time interval and a `Volume.Usd` floor: ```graphql subscription { Trading { Tokens( where: { Token: {Symbol: {is: "USDC"}} Interval: {Time: {Duration: {eq: 300}}} Volume: {Usd: {gt: 100000}} } ) { Price { Ohlc { Close } } Volume { Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` ### How do I get one price for an asset across chains? ```graphql subscription { Trading { Currencies( where: {Currency: {Id: {is: "bid:bitcoin"}}} ) { Price { Ohlc { Close } } Volume { Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` [Run cross-chain Bitcoin query ➤](https://ide.bitquery.io/bitcoin-cross-chain-price) - `bid:bitcoin` blends every covered chain's representation of bitcoin (WBTC and the like) into one price. - `Supply` on this row is the on-chain wrapped supply, not bitcoin's issued supply; see [supply fields](/docs/trading/crypto-price-api/supply-fields). ### Should I pin an order to one named pool? No. Pinning a limit order to a named pool reintroduces the single-pool risk above: that pool can thin out or stop being where the token trades. Use the rank-1 `Pairs` stream from [How to get it](#how-to-get-it) when you want the price you can execute against, and the blended `Tokens` price when you want smoothing across the whole market. ## Pitfalls - **History before 2026-10-19 is volume-weighted.** Those rows carry `Liquidity` fields of `0`. - **Volume-based intervals return zero rows silently.** No error, no data. - **`Network` is case-sensitive**: `"Ethereum"`, `"Solana"`, `"Binance Smart Chain"`. - **Rank 1 can be an estimated pool.** The leading pool can have `Liquidity.Source: "volume"`; read `Source` next to `Ranking.Position`. ## Related - [Crypto Price API](/docs/trading/crypto-price-api/): the section index. - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm): how the blend works. - [Pairs: ranking](/docs/trading/crypto-price-api/pairs#ranking-how-position-and-weight-behave): `Ranking { Position Weight }`. - [OHLC Candlestick API](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/), with a [live Bitcoin OHLC example ➤](https://ide.bitquery.io/bitcoin-currency-price-stream). - [DEX trade filtering guide](/docs/usecases/how-to-filter-anomaly-prices/): handling anomalies in raw trades. - [DEXTradeByTokens](/docs/cubes/dextradesbyTokens/): the raw trade cube. - Kafka topic `trading.prices`: [schema and SDKs](https://github.com/bitquery/streaming_protobuf/tree/main/market). [WebSocket guide](/docs/subscriptions/websockets/) for subscriptions. --- ## Liquidity, RankingDetail and LeadingPool Fields URL: https://docs.bitquery.io/docs/trading/crypto-price-api/liquidity-fields/ How Bitquery calculates pool and token liquidity (measured reserve vs volume estimate), why it is the price-blend weight, every Liquidity, RankingDetail and LeadingPool field, and runnable queries on the Trading Pairs, Tokens and Currencies cubes. # Liquidity, RankingDetail and LeadingPool fields ## What it is A pool holds two tokens, a pair. A `Pairs` row reads that pool from one side: `Token` is the token being priced, `QuoteToken` is the token it is priced in. `Liquidity.Usd` is the amount of money, in USD, that the pool holds in the row's quote token. That number is also the weight each pool gets in the token's price blend. `RankingDetail` says what the blend did with the pool's price, and `LeadingPool` names the pool that leads the blend. ## How to get it The three groups are selectable and filterable on the Trading cubes, in queries and subscriptions, and carried on the `trading.prices` Kafka topic (see [Kafka](#kafka-tradingprices)). | Group | `Currencies` | `Tokens` | `Pairs` | | --- | --- | --- | --- | | `Liquidity { … }` | yes (summed over pools) | yes (summed over pools) | yes (one pool) | | `RankingDetail { … }` | – | yes | yes | | `LeadingPool { … }` | – | yes | – | Select them next to `Price`, `Volume` and `Ranking`. Always set `Interval.Time.Duration` and a `Block.Time` window. When ranking or filtering on `Liquidity.Usd`, add `Liquidity.Source` and `RankingDetail.Verdict` filters; the [sample query](#sample-query) shows the shape. ## How it is derived {#how-liquidity-is-calculated} **Liquidity is the blend weight.** Since 2026-10-19 the price index weights each of a token's pools by its liquidity after the staleness discount: ``` Ranking.Weight = Liquidity.Usd × RankingDetail.StaleMultiplier ÷ Σ over the token's pools (Liquidity.Usd × StaleMultiplier) ``` Rows before 2026-10-19 in the 30-day history are volume-weighted and carry `Liquidity` fields of `0`. How the weighted prices become one token price is on the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) page. For every pool the index tries four cases in order and takes the first that applies. `Liquidity.Source` tells you which case produced the number, so always read `Source` next to `Usd`. | Case | When | `Usd` is | `Source` | | --- | --- | --- | --- | | 1 | reserve known | `QuoteReserve` × quote token USD price | `real`, `real_stale` | | 2 | launch curve, no reserve | `NetQuoteUsd` (quote paid in − quote paid out) | `migration`, `retired` | | 3 | reserve unknown | estimate from the last hour of trading | `volume` | | 4 | nothing traded in 1 h | 0 | `none` | Only case 1 is a measurement. Cases 2 and 3 are estimates. Never compare `Usd` across cases (see [the warning below](#usd-is-not-comparable-across-sources)). ### Case 1: the reserve is known (`real`, `real_stale`) The indexer watches the pool contract. Every swap, add or remove changes the pool's balances, and after each event it records how much of each of the pair's two tokens the pool holds. The balance of the row's quote token, times that token's USD price, is `Usd`. A SOL/USDC pool holding 1 000 000 USDC reports `Usd` of $1 000 000 on the row where USDC is the quote token. Nothing is estimated. - The snapshot is under an hour old: `Source` is `real`. - The snapshot is more than an hour old: `Source` is `real_stale`. The value is the same reserve, unchanged; only the label differs. A pool that stops trading loses weight through `RankingDetail.StaleMultiplier`, not through its liquidity. Two adjustments apply to a measured reserve. **Capped by depth.** If the snapshot carries a slippage table, `Usd` is capped at a multiple of the amount sellable within 1 % slippage, so liquidity parked far from the current price does not count in full. `QuoteReserveUsd` keeps the uncapped figure. Example: a Base cbBTC/WETH pool with `QuoteReserveUsd` of $2.07 B reports `Usd` of $306 M after the depth cap. **The quote token needs an independent price.** A reserve is only valued through a stablecoin, the chain's native coin or a listed currency. A pair whose quote token is anything else falls through to case 3. Example, on Solana: `real` rows have WSOL, USDC, USDT, PUMP, RAY and the like as quote token. `volume` rows are the ones whose quote token is a fresh meme token. ### Case 2: a launch curve with no reserve (`migration`, `retired`) Bonding curves (pump.fun, four.meme and the like) have no pool reserve to read, but every buy and sell is known. `Usd` is the curve's lifetime net quote in USD, quote paid in minus quote paid out, which is both its reserve and its progress to graduation. The same number is in `NetQuoteUsd`. The pool a curve has just graduated to is also `migration` until it has a reserve snapshot of its own. Once the token has moved on to a real pool, the curve row becomes `retired`: it keeps its last curve balance in `Usd`, but `Ranking.Weight` is `0` and it no longer prices the token. ### Case 3: the reserve is unknown (`volume`) {#how-an-estimate-is-made} There is no balance to read: the chain's pool events are not indexed (Tron, Arc), the "pool" is a router or order engine with no vault (Tessera on Solana), or the quote token has no USD price. The only thing known is the pool's trades, so liquidity is estimated from the last hour of trading, with recent trades counting more, valued at the token's reference price across all its pools rather than the pool's own last print, and scaled up by a turnover factor: how much reserve a typical pool holds per hour of trading. The factor is set per chain, and when the token has at least one pool with a measured reserve, that token's own measured turnover is used instead, so an unmeasured pool weighs against the measured ones in proportion to how much it trades against them. Reserve fields stay `0`. You can see the two regimes in the data: `Liquidity.Usd / Volume.Usd` on one-hour rows of tokens with **no** measured pool sits at one value per chain, while pools of tokens that **do** have a measured pool land anywhere from well below 1 to several thousand. :::caution The estimate is a ranking tool, not a measurement It orders the pools of one token well: the pool that trades more against the others gets more weight, which is what the price index needs it for. It cannot tell you how many dollars sit in a pool nobody has measured, and it should not be shown as such. On established pools the raw chain-factor estimate runs around a tenth of the real reserve; on brand-new pools it runs well above it. Filter on `Source: { in: ["real", "real_stale"] }` when you need a dollar figure. ::: ### Case 4: nothing traded (`none`) The pool traded nothing in the last hour and has no reserve snapshot. `Usd` is `0`. ### `Usd` is not comparable across sources {#usd-is-not-comparable-across-sources} :::danger A `volume` estimate is turnover-scaled and can be far larger than any reserve. Routers and order engines without a pool (Tessera on Solana, for example) report `volume` liquidity in the tens of millions on top-market pairs, and a dead pool whose quote token has a nonsense price can report billions. Rank or filter by `Liquidity.Usd` **only together with** `Source: { in: ["real", "real_stale"] }`, or at token level with a `RealShare` floor. ::: ### Token and currency level On a `Pair` the fields describe one pool, read from the row's quote token. The same pool appears once per quote token, so its two rows value different tokens and report different `QuoteReserve` and `Usd`. On a `Token` or `Currency`: - `Usd` is the **sum** over the pools the blend considered, including pools that did not trade in the interval and therefore have no `Pairs` row. Do not expect it to equal the sum of visible `Pairs` rows. - `Source` is the leading pool's source. A token can show `Source: "volume"` with `RealShare: 0.67`: two thirds of the sum is real reserves, but the pool that sets the price has none. - `RealShare` is the quality signal above pair level. `RealShare: 1` means every dollar is a measured reserve. - `UpdatedAt` is **`1970-01-01T00:00:00Z` on every token and currency row**. There is no single snapshot behind a sum. Filter on it at pair level only. - `BaseReserve`, `QuoteReserve`, `QuoteReserveUsd`, `DepthUsd` and `NetQuoteUsd` are `0`, not `null`. ### What `Liquidity` is not - **Not TVL.** `Usd` values one of the pool's two tokens, the row's quote token. A pool that explorers show at $2 M total value locked reports roughly $1 M here. The other token's balance is in `BaseReserve`, unvalued. - **Not a trust signal.** A token with $1 000 of real USDC-side reserve and a $80 000 price gets a market cap in the trillions. Pair `Liquidity.Usd` with `Supply.MarketCap` before showing either. - **Not the chain-level pool cube.** `DEXPools` on the chain schemas carries full pool state; this is the index's view of the reserve that prices the token. ## Fields {#fields} ### `Liquidity` | Field | Type | Meaning | | --- | --- | --- | | `Usd` | Float | USD liquidity: the pool's balance of the row's quote token, valued in USD, the depth that backs the price. Summed over pools at token and currency level. Calculated as described [above](#how-liquidity-is-calculated). | | `Source` | String | Which case produced `Usd`: `real`, `real_stale`, `migration`, `retired`, `volume` or `none`. At token and currency level it is the source of the leading (Position 1) pool. Details in [`Source` values](#source-values). | | `RealShare` | Float | Fraction of `Usd` backed by a reserve snapshot: `1` or `0` for a single pool, in between for a token or currency summed over pools. | | `BaseReserve` | Float | Post-event balance of the row's `Token`, the token being priced, as a UI amount. **Pair level only.** | | `QuoteReserve` | Float | Post-event balance of the row's `QuoteToken`, as a UI amount. **Pair level only.** | | `QuoteReserveUsd` | Float | `QuoteReserve` valued in USD, before any cap. Equals `Usd` for a single pool unless the depth cap applied. | | `UpdatedAt` | DateTime | Time of the reserve snapshot behind `Usd`, for judging freshness. **Pair level only.** | | `DepthUsd` | Float | How much quote, in USD, can be sold into the pool before the price moves 1 %. The pool pays that trade out in base, so the ceiling is the **base** leg, not `QuoteReserveUsd`: on a pegged pair (USDC/USDT, PYUSD/USDS) it is close to the whole base leg and can exceed `QuoteReserveUsd`; on a volatile pair the curve stops it far below either leg. `0` when the snapshot carried no slippage table. **Pair level only.** | | `NetQuoteUsd` | Float | A launch curve's lifetime net quote in USD (quote paid in minus quote paid out): for a bonding curve, its reserve and its progress to graduation. On a retired curve, the amount that migrated to the venue. `0` for a pool that is not a configured launcher. **Pair level only.** | ### `Source` values {#source-values} | Value | When it applies | What `Usd` is | Share of one-minute `Pairs` rows (8 chains, 5 min sample) | | --- | --- | --- | --- | | `real` | A reserve snapshot of the pool exists and is under an hour old. | The pool's balance of the row's quote token, valued in USD. | 82 % | | `real_stale` | The snapshot is more than an hour old. | The same reserve, unchanged; only the label differs. | 1.4 % | | `migration` | A launch curve (pump.fun, four.meme and the like) with no reserve snapshot, or the pool it just graduated to. | Money paid into the curve minus money taken out. `Usd` equals `NetQuoteUsd`. | 2.8 % | | `volume` | No reserve and not a launch curve. | An estimate from the last hour's trading, see [case 3](#how-an-estimate-is-made). | 14 % | | `none` | The pool traded nothing in the last hour. | `0` | 0.1 % | | `retired` | A launch curve whose token has moved on to a real pool. | Its last curve balance (see [pitfall 4](#pitfalls-to-design-around)). | < 0.1 % | | `impact` | Defined by engineering as depth estimated from net flow against the price move. Not observed in data as of October 2026. | – | not observed | ### `RankingDetail` Explains the `Ranking` a pool (or, on `Tokens`, a token's part in its currency) received. `Ranking { Position Weight }` is unchanged; `RankingDetail` says why. | Field | Type | Meaning | | --- | --- | --- | | `Verdict` | String | What happened to this part's price in the batch's blend. Values below. | | `StaleMultiplier` | Float | Staleness discount applied to the weight, in `(0, 1]`: `1` for a part trading at its own rhythm, falling the longer it stays quiet beyond that rhythm. `Ranking.Weight` is already the share of the **discounted** weights. Do not apply the multiplier again. | `Verdict` values: | Value | Meaning | Share of one-minute `Pairs` rows (10 min sample) | | --- | --- | --- | | `priced` | Accepted into the blend. | 97.2 % | | `clamped` | Accepted, but bounded to a cap around the recently-traded consensus. | < 0.1 % | | `outlier` | Rejected by the outlier band. Contributes neither price nor volume to the token. | < 0.1 % | | `ineligible` | Refused by the eligibility gate: too little money or history. Its volume still counts, its price does not. | 2.2 % | | `no_price` | No price in the window; ranked by weight 0. | 0.3 % | | `retired` | A launch curve its token has left. `Ranking.Weight` is `0`, `StaleMultiplier` is the floor (`2⁻²⁰`). | < 0.1 % | | `""` (empty) | The row was not ranked in this batch. `Ranking.Position` and `Weight` are `0` too. About 0.2 % of pair rows and 2 % of token rows. Treat as "unknown", not as a verdict. | 0.2 % | :::caution Rejected is not removed An `outlier` or `ineligible` pool still has a `Pairs` row, a `Ranking.Position` and a `Liquidity` block. Filter on `RankingDetail.Verdict` when you want only the pools whose price the token actually uses. ::: ### `LeadingPool` (Tokens only) Identifies the pair update that leads the token's blend, so a client can follow the token's price to the pool that sets it without joining to `Pairs`. | Field | Type | Meaning | | --- | --- | --- | | `MarketId` | String | `Market.Id` of the leading pool's pair. | | `QuoteTokenId` | String | `QuoteToken.Id` of that pair. | | `PoolAddress` | String | `Pool.Address` of that pair. Empty where the market has no pool address. | :::caution "Leading" means the most weight, not necessarily the deepest measured pool `LeadingPool` is the pool at `Ranking.Position: 1`: the pool with the most weight in the blend. Since 2026-10-19 that is the largest share of `Liquidity.Usd × StaleMultiplier` among the token's pools; on rows before that date it is the largest volume share. Estimates count, so the leading pool can be a router or order engine with no reserves at all (`Liquidity.Source: "volume"`) whose estimate outweighs the measured pools. It can change every batch. Match on **`MarketId` plus `QuoteTokenId`**, not on `PoolAddress`: the same pool address appears once per quote token, and `PoolAddress` is observed empty on some updates and filled on the next for the same market. ::: ## Examples ### Which pools price a token with measured liquidity? {#sample-query} Every pool pricing SOL on Solana with more than $10 000 of **measured** reserve in its quote token, accepted into the blend, deepest first. This is the shape to start from: it selects every `Liquidity` field, and the `where` clause applies the two filters that make `Usd` safe to rank on. [Run query ➤](https://ide.bitquery.io/Token-pools-with-real-liquidity) ```graphql query TokenPoolsWithRealLiquidity { Trading { Pairs( limit: {count: 10} orderBy: {descending: Liquidity_Usd} where: { Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Liquidity: {Usd: {gt: 10000}, Source: {in: ["real", "real_stale"]}} RankingDetail: {Verdict: {is: "priced"}} } ) { Block { Time } Market { Id Name } Pool { Address } QuoteToken { Symbol } Price { Ohlc { Close } } Volume { Usd } Liquidity { Usd BaseReserve QuoteReserve QuoteReserveUsd UpdatedAt Source RealShare DepthUsd NetQuoteUsd } Ranking { Position Weight } RankingDetail { Verdict StaleMultiplier } } } } ``` First row returned on 2026-10-22 (SOL/USDC on Raydium AMM v4): ```json { "Block": { "Time": "2026-10-22T05:38:51Z" }, "Market": { "Id": "bid:solana:675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8:58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2", "Name": "raydium_amm" }, "Pool": { "Address": "58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2" }, "QuoteToken": { "Symbol": "USDC" }, "Price": { "Ohlc": { "Close": 105.49534 } }, "Volume": { "Usd": 399.11612 }, "Liquidity": { "Usd": 9697858, "BaseReserve": 92157.13, "QuoteReserve": 9699468, "QuoteReserveUsd": 9697858, "UpdatedAt": "2026-10-22T05:38:51Z", "Source": "real", "RealShare": 1, "DepthUsd": 0, "NetQuoteUsd": 0 }, "Ranking": { "Position": 2, "Weight": 0.17664543 }, "RankingDetail": { "Verdict": "priced", "StaleMultiplier": 1 } } ``` How to read it: - `Source: "real"` means case 1 applied. The pool holds 9 699 468 USDC (`QuoteReserve`); at USDC's price of just under $1 that is `Usd` of $9 697 858. The 92 157 SOL on the other side (`BaseReserve`) is not valued. - `QuoteReserveUsd` equals `Usd` because no depth cap applied. `DepthUsd` is `0`: Solana snapshots carry no slippage table. - `UpdatedAt` is when the reserve was last read. Here it matches `Block.Time`; on a quiet pool it can be minutes earlier. - `Verdict: "priced"` means this pool's price went into SOL's token price, with `Weight` 0.18 of the blend at `Position` 2. Weight follows liquidity, not volume: the pool traded only $399 in the minute, but its $9.7 M reserve is what earns it 18 % of the blend. - `NetQuoteUsd` is `0` because this is an AMM pool, not a launch curve. `RealShare` is `1` on every pair row with a measured reserve. To make the same query estimate-tolerant, drop the `Source` filter and show `Source` next to `Usd` so a reader can tell a reserve from an estimate. To run it for another token, change `Token.Id`; the id carries the chain (`bid:solana:`, `bid:base:`, `bid:bsc:`), so no separate `Network` filter is needed. ### Which pool sets a token's price, and how much backs it? [Run query ➤](https://ide.bitquery.io/Token-leading-pool-and-liquidity) ```graphql query TokenLeadingPoolAndLiquidity { Trading { Tokens( limit: {count: 1} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} } ) { Block { Time } Token { Id Symbol } Price { Average { Mean } Ohlc { Close } } Liquidity { Usd RealShare Source } LeadingPool { MarketId PoolAddress QuoteTokenId } Ranking { Position Weight } RankingDetail { Verdict StaleMultiplier } } } } ``` - The row for SOL shows `LeadingPool` pointing at a Tessera market with `Source: "volume"` and `RealShare` around `0.6` (0.59 on 2026-10-22). - The pool that sets the price has no reserves; its volume-derived estimate outweighs the measured pools, while well over half of the summed liquidity is measured. ### Which tokens on a chain have the most measured liquidity? `RealShare: { ge: 0.9 }` keeps out tokens whose sum is mostly estimates. `limitBy` collapses to one row per token. [Run query ➤](https://ide.bitquery.io/Top-Solana-tokens-by-real-liquidity) ```graphql query TopSolanaTokensByRealLiquidity { Trading { Tokens( limit: {count: 20} limitBy: {by: Token_Id, count: 1} orderBy: {descending: Liquidity_Usd} where: { Token: {Network: {is: "Solana"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} Liquidity: {Source: {is: "real"}, RealShare: {ge: 0.9}} } ) { Token { Id Symbol } Price { Average { Mean } } Liquidity { Usd RealShare Source } LeadingPool { MarketId PoolAddress } } } } ``` ### How far along is a pump.fun curve? Live pump.fun curves, ordered by how much quote has flowed in net — the curve's progress to graduation. `Usd` equals `NetQuoteUsd` while `Source` is `migration`. [Run query ➤](https://ide.bitquery.io/Pump-fun-curve-progress-NetQuoteUsd) ```graphql query PumpFunCurveProgressNetQuoteUsd { Trading { Pairs( limit: {count: 20} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Liquidity_NetQuoteUsd} where: { Market: {Network: {is: "Solana"}, Protocol: {is: "pump"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} Liquidity: {Source: {is: "migration"}} } ) { Block { Time } Token { Id Symbol } Pool { Address } Price { Ohlc { Close } } Liquidity { Usd NetQuoteUsd Source RealShare UpdatedAt } Ranking { Position Weight } RankingDetail { Verdict } } } } ``` ### Which pools did the blend reject or bound? [Run query ➤](https://ide.bitquery.io/Pools-rejected-from-token-blend) ```graphql query PoolsRejectedFromTokenBlend { Trading { Pairs( limit: {count: 20} orderBy: {descending: Block_Time} where: { Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} RankingDetail: {Verdict: {in: ["outlier", "clamped", "ineligible"]}} } ) { Block { Time } Market { Network Name } Pool { Address } Token { Id Symbol } Price { Ohlc { Close } } Volume { Usd } Liquidity { Usd Source } Ranking { Position Weight } RankingDetail { Verdict StaleMultiplier } } } } ``` ### Which pools are losing weight for going quiet? Lowest `StaleMultiplier` first. `Liquidity.UpdatedAt` shows how long ago the reserve was last seen. [Run query ➤](https://ide.bitquery.io/Stale-pools-discounted-in-ranking) ```graphql query StalePoolsDiscountedInRanking { Trading { Pairs( limit: {count: 20} orderBy: {ascending: RankingDetail_StaleMultiplier} where: { Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} RankingDetail: {StaleMultiplier: {lt: 1}, Verdict: {is: "priced"}} Liquidity: {Usd: {gt: 1000}} } ) { Block { Time } Market { Network Name } Pool { Address } Token { Symbol } Liquidity { Usd UpdatedAt Source } Ranking { Position Weight } RankingDetail { Verdict StaleMultiplier } } } } ``` ### What reserves and depth do Ethereum's leading pools hold? `DepthUsd` is the quote amount, in USD, sellable within 1 % slippage. It can exceed `Usd` on a concentrated-liquidity pool. [Run query ➤](https://ide.bitquery.io/Ethereum-top-pools-reserves-and-depth) ```graphql query EthereumTopPoolsReservesAndDepth { Trading { Pairs( limit: {count: 10} limitBy: {by: Pool_Address, count: 1} orderBy: {descending: Liquidity_DepthUsd} where: { Market: {Network: {is: "Ethereum"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} Ranking: {Position: {eq: 1}} Liquidity: {Source: {is: "real"}, DepthUsd: {gt: 0}} } ) { Block { Time } Market { Name } Pool { Address } Token { Symbol } QuoteToken { Symbol } Price { Ohlc { Close } } Liquidity { Usd BaseReserve QuoteReserve QuoteReserveUsd DepthUsd UpdatedAt Source } Ranking { Position Weight } } } } ``` ### How much liquidity does a currency have across chains? [Run query ➤](https://ide.bitquery.io/Currency-liquidity-across-chains) ```graphql query CurrencyLiquidityAcrossChains { Trading { Currencies( limit: {count: 1} orderBy: {descending: Block_Time} where: { Currency: {Id: {is: "bid:bitcoin"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 10}}} } ) { Block { Time } Currency { Id Symbol } Price { Average { Mean } } Liquidity { Usd RealShare Source } } } } ``` ### How do I stream liquidity and verdicts for a token's pools? The same selections work in a subscription; `Block.Time` carries sub-second precision on the stream. [Run stream ➤](https://ide.bitquery.io/Token-pool-liquidity-stream) ```graphql subscription TokenPoolLiquidityStream { Trading { Pairs( where: { Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}} Interval: {Time: {Duration: {eq: 1}}} } ) { Block { Time } Market { Name } Pool { Address } QuoteToken { Symbol } Price { Ohlc { Close } } Liquidity { Usd QuoteReserveUsd UpdatedAt Source RealShare } Ranking { Position Weight } RankingDetail { Verdict StaleMultiplier } } } } ``` ## Pitfalls ### Chain coverage | Chain | Reserve data | Pools with a measured reserve (`real` + `real_stale`, pools that traded in a 5 min window) | | --- | --- | --- | | Solana | `real` on most rows | 81 % | | Ethereum, BSC, Arbitrum | `real` on most rows | 80–84 % | | Base, Optimism, Matic | `real` on most rows | 60–72 % | | Robinhood | `real` on most rows | small sample | | Arc | `volume` only | 0 | | Tron | `volume` only: no reserve events are indexed, so `RealShare` is `0` chain-wide | 0 | These shares count pools that traded recently; across all pools the index knows, including quiet ones, the measured share on EVM chains is lower. `DepthUsd` was non-zero only on EVM pools in the sample (Uniswap v2 / v3 families); Solana rows carry `0`. ### Pitfalls to design around {#pitfalls-to-design-around} 1. **Two timestamps.** `Block.Time` is the last write to the row (a trade or a re-rank); `Liquidity.UpdatedAt` is the reserve snapshot. They differ by minutes on quiet pools. 2. **`Network` filters take display names**, case-sensitive: `"Solana"`, `"Ethereum"`, `"Binance Smart Chain"`, `"Matic"`, `"Tron"`. `"solana"` returns nothing. 3. **Pump.fun's curve protocol is `pump`**; the post-graduation AMM is `pump_amm`. 4. **A retired curve keeps a non-zero `Liquidity.Usd`** (its last snapshot) with `Source: "retired"` and `Weight: 0`. Check `Verdict` / `Source`, not `Usd`, to know it is out of the price. 5. **Aggregates use field arguments**, as elsewhere on the Trading cubes: `Liquidity { Usd(maximum: Liquidity_Usd) }`, and `orderBy: { descending: Liquidity_Usd }` for ordering. 6. **Subscriptions return `null` for a whole group** from a producer that does not yet emit it. Null-check `Liquidity`, `RankingDetail` and `LeadingPool`; do not read a missing group as `0`. 7. **History before 2026-10-19 has no liquidity.** Rows older than that carry `Liquidity` fields of `0` and volume-based `Ranking.Weight`. ## Kafka: `trading.prices` {#kafka-tradingprices} The same groups are on the `trading.prices` topic, defined in [`market/price_index.proto`](https://github.com/bitquery/streaming_protobuf/blob/main/market/price_index.proto): | Message | Field | Number | | --- | --- | --- | | `PairUpdate` | `Liquidity Liquidity` | 11 | | `PairUpdate` | `RankingDetail RankingDetail` | 12 | | `TokenUpdate` | `Liquidity Liquidity` | 6 | | `TokenUpdate` | `RankingDetail RankingDetail` | 7 | | `TokenUpdate` | `LeadingPool LeadingPool` | 8 | | `CurrencyUpdate` | `Liquidity Liquidity` | 4 | Differences from GraphQL: - `Liquidity.UpdatedAt` is a `uint32` unix second (`0` at token and currency level). - `Source` and `Verdict` are plain strings with the same values as above; an unranked part has an empty `Verdict`. - A message from a producer that does not emit the group yet has the protobuf default — an unset message — not a zeroed one; check `HasField` before reading. On `trading.trades`, `TradeIndex` is field 4 of `TradeTransaction` in [`market/transaction.proto`](https://github.com/bitquery/streaming_protobuf/blob/main/market/transaction.proto), read as `Trade.Transaction.TradeIndex`. ## Related - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm): how the liquidity-weighted prices are blended across pools. - [Ranking on Pairs](/docs/trading/crypto-price-api/pairs#ranking-how-position-and-weight-behave): `Ranking { Position Weight }`. - [Liquidity queries](/docs/trading/crypto-price-api/liquidity-use-cases): ready-made questions (rug pull checks, best pool to trade, slippage depth). - [Trades of a transaction in execution order](/docs/trading/crypto-trades-api/trades-api#trades-of-a-transaction-in-execution-order-tradeindex): `TradeIndex`, released alongside these fields, on the `Trades` cube only. --- ## Live Reload Configuration for gRPC Streams URL: https://docs.bitquery.io/docs/grpc/solana/live-reload/ Live Reload Configuration for gRPC Streams for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Live Reload Configuration for gRPC Streams Live reload enables dynamic configuration changes without you having to restart your application. This feature automatically detects changes to your `config.yaml` file and restarts the stream with the new settings. ## Why Live Reload? Live reload is essential for: - **Testing different filters**: Quickly test various filter combinations without stopping and restarting your application - **Switching stream types**: Change between dex_trades, transactions, balances, and other stream types on the fly - **Dynamic monitoring**: Adjust which programs, pools, or traders to monitor in real-time - **Production updates**: Update filters in production without downtime - **Development efficiency**: Iterate faster during development and debugging ## How It Works The live reload system monitors your `config.yaml` file for changes using Node.js's `fs.watch()` API. When a change is detected: 1. The configuration file is reloaded 2. The current stream connection is gracefully stopped 3. If server settings changed, the gRPC client is reinitialized 4. A new stream is started with the updated configuration 5. All of this happens automatically without manual intervention ## Setup ### Prerequisites Install the required dependencies: ```bash npm install @grpc/grpc-js @grpc/proto-loader js-yaml bs58 ``` Or using package.json: ```json { "dependencies": { "@grpc/grpc-js": "^1.9.0", "@grpc/proto-loader": "^0.7.10", "js-yaml": "^4.1.0", "bs58": "^5.0.0" } } ``` ### Configuration File Create a `config.yaml` file with your stream settings: ```yaml server: address: "corecast.bitquery.io" authorization: "ory_YOUR_API_TOKEN_HERE" insecure: false stream: type: "dex_trades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Pump.fun ``` **Get your API token**: Generate one at [https://account.bitquery.io/user/api_v2/access_tokens](https://account.bitquery.io/user/api_v2/access_tokens) ## Implementation ### Basic Live Reload Setup Here's the core implementation for live reload functionality: ```javascript const fs = require('fs'); const yaml = require('js-yaml'); let config = null; let currentStream = null; let isReloading = false; // Load configuration from file function loadConfig() { try { const newConfig = yaml.load(fs.readFileSync('./config.yaml', 'utf8')); console.log('Configuration loaded successfully'); return newConfig; } catch (error) { console.error('✗ Failed to load configuration:', error.message); return null; } } // Watch config file for changes let watchTimeout = null; fs.watch('./config.yaml', (eventType, filename) => { if (eventType === 'change') { // Debounce multiple rapid file changes if (watchTimeout) { clearTimeout(watchTimeout); } watchTimeout = setTimeout(() => { reloadAndRestart(); watchTimeout = null; }, 300); // Wait 300ms after last change } }); console.log(' Watching config.yaml for changes...'); ``` ### Complete Live Reload Function The reload function handles the full lifecycle of stopping the old stream and starting a new one: ```javascript // Check if server configuration changed function hasServerConfigChanged(oldConfig, newConfig) { return oldConfig.server.address !== newConfig.server.address || oldConfig.server.authorization !== newConfig.server.authorization || oldConfig.server.insecure !== newConfig.server.insecure; } // Reload configuration and restart stream function reloadAndRestart() { if (isReloading) { return; // Prevent concurrent reloads } isReloading = true; console.log('\n Configuration changed, reloading...'); // Load new configuration const newConfig = loadConfig(); if (!newConfig) { console.error('Failed to reload configuration, keeping current settings'); isReloading = false; return; } // Check if we need to reinitialize the client const needsNewClient = hasServerConfigChanged(config, newConfig); // Stop current stream stopStream(); // Update configuration config = newConfig; // Reinitialize client if server settings changed if (needsNewClient) { console.log('Server configuration changed, reinitializing client...'); try { initializeClient(); } catch (error) { console.error('Failed to initialize client:', error.message); isReloading = false; return; } } // Start new stream try { startStream(); isReloading = false; } catch (error) { console.error(' Failed to start stream:', error.message); isReloading = false; } } // Stop current stream function stopStream() { if (currentStream) { try { currentStream.cancel(); console.log('Stream stopped'); } catch (error) { console.error('Error stopping stream:', error.message); } currentStream = null; } } ``` ### Graceful Shutdown Handle process termination properly: ```javascript // Handle process termination process.on('SIGINT', () => { console.log('\nShutting down gracefully...'); stopStream(); process.exit(0); }); process.on('SIGTERM', () => { console.log('\nShutting down gracefully...'); stopStream(); process.exit(0); }); ``` ## Usage Examples ### Example 1: Switching Between Stream Types Start with DEX trades: ```yaml stream: type: "dex_trades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" ``` Then modify the config to switch to transactions: ```yaml stream: type: "transactions" filters: signers: - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" ``` The stream will automatically restart with the new configuration. ### Example 2: Adding Multiple Program Filters Start monitoring one program: ```yaml filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Pump.fun ``` Add more programs without restarting: ```yaml filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Pump.fun - "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK" # Raydium CLMM - "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" # Raydium V4 ``` ### Example 3: Switching Filter Types Monitor by program: ```yaml filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" ``` Switch to monitoring specific pools: ```yaml filters: pool: - "5tUu7bX8d8Zz1v3v4Y9H9F6J7K8L9M0N1O2P3Q4R5S6T" - "7GJz9X7b1G9Nf1d5uQq2Z3B4nPq6F8d9LmNoPQrsTUV" ``` Or monitor specific traders: ```yaml filters: traders: - "7GJz9X7b1G9Nf1d5uQq2Z3B4nPq6F8d9LmNoPQrsTUV" ``` ### Example 4: Testing Multiple Configurations You can quickly test different configurations by editing the YAML file: ```yaml # Test 1: Monitor Pump.fun trades stream: type: "dex_trades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Test 2: Monitor specific wallet transactions # stream: # type: "transactions" # filters: # signers: # - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" # Test 3: Monitor token transfers # stream: # type: "transfers" # filters: # tokens: # - "So11111111111111111111111111111111111111112" # WSOL ``` Simply uncomment the configuration you want to test, and the stream will reload automatically. ## Available Stream Types You can switch between these stream types using live reload: - **`dex_trades`**: Real-time DEX trade/swap data - **`dex_orders`**: Order lifecycle updates - **`dex_pools`**: Pool creation and liquidity changes - **`transactions`**: Finalized transactions with instructions - **`transfers`**: Token transfer events - **`balances`**: Balance updates for accounts For detailed information on each stream type, see: - [DEX Trades](/docs/grpc/solana/topics/dextrades) - [Transactions](/docs/grpc/solana/topics/transactions) - [Balances](/docs/grpc/solana/topics/balance) ## Available Filters Different stream types support different filters: ### DEX Trades Filters ```yaml filters: programs: # DEX program addresses - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" pool: # Market/pool addresses - "5tUu7bX8d8Zz1v3v4Y9H9F6J7K8L9M0N1O2P3Q4R5S6T" traders: # Trader wallet addresses - "7GJz9X7b1G9Nf1d5uQq2Z3B4nPq6F8d9LmNoPQrsTUV" ``` ### Transaction Filters ```yaml filters: signers: # Transaction signers - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" ``` ### Transfer Filters ```yaml filters: tokens: # Token mint addresses - "So11111111111111111111111111111111111111112" # WSOL signers: # Transaction signers - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" ``` ## Debouncing The live reload implementation includes a 300ms debounce to handle multiple rapid file changes. This prevents unnecessary restarts when your editor makes multiple writes while saving a file. ```javascript // Debounce multiple rapid file changes if (watchTimeout) { clearTimeout(watchTimeout); } watchTimeout = setTimeout(() => { reloadAndRestart(); watchTimeout = null; }, 300); // Wait 300ms after last change ``` You can adjust this delay based on your needs: - **Shorter delay (100-200ms)**: Faster reloads, but might trigger multiple times - **Longer delay (500-1000ms)**: More stable, but slower to reflect changes ## Error Handling The live reload system includes comprehensive error handling: ### Configuration Errors If the new configuration is invalid, the system keeps the current working configuration: ``` Failed to reload configuration, keeping current settings ``` ### Stream Errors Stream errors during reload are logged but don't crash the application: ```javascript stream.on('error', (error) => { if (!isReloading) { console.error('Stream error:', error); } }); ``` The `isReloading` flag prevents error spam during normal reload operations. ## Best Practices 1. **Test changes locally first**: Validate your configuration changes work before deploying to production 2. **Use version control**: Keep your config.yaml in version control to track changes 3. **Comment your filters**: Add comments to document what each filter monitors 4. **Monitor reload events**: Log when reloads happen to track configuration changes 5. **Handle edge cases**: Ensure your application handles the brief disconnection during reload ### Environment Variables For sensitive data like API tokens, use environment variables: ```javascript function loadConfig() { const config = yaml.load(fs.readFileSync('./config.yaml', 'utf8')); // Override with environment variables if (process.env.BITQUERY_TOKEN) { config.server.authorization = process.env.BITQUERY_TOKEN; } return config; } ``` ## Logging Output When live reload is active, you'll see these messages: ``` Watching config.yaml for changes... Configuration loaded successfully Stream connected and listening for data... Configuration changed, reloading... Stream stopped Configuration loaded successfully Stream connected and listening for data... ``` ## Related Documentation - [Introduction to gRPC Streams](/docs/grpc/solana/introduction) - [Best Practices](/docs/grpc/solana/best_practices) - [Authorization](/docs/grpc/solana/authorization) - [Error Handling](/docs/grpc/solana/errors) ## Troubleshooting ### Stream Not Reloading If changes aren't being detected: 1. Check file permissions on `config.yaml` 2. Ensure the file is being saved properly by your editor 3. Look for configuration syntax errors in the console 4. Verify the debounce timeout hasn't been set too high ### Frequent Disconnections If the stream disconnects frequently during reloads: 1. Check your network connection stability 2. Verify your API token is valid 3. Ensure you're not hitting rate limits 4. Review your filter configuration for errors ### Memory Issues If you experience memory issues with live reload: 1. Ensure streams are properly cancelled before creating new ones 2. Clear any message buffers during reload 3. Monitor for event listener leaks 4. Use the provided cleanup functions ## Next Steps Now that you understand live reload, explore: - [Stream Topics](/docs/grpc/solana/topics/dextrades) - Different types of streams available - [Best Practices](/docs/grpc/solana/best_practices) - Production-ready patterns - [Examples](/docs/grpc/solana/examples/pump-fun-grpc-streams) - Real-world use cases --- ## Manage Your Bitquery Subscription URL: https://docs.bitquery.io/docs/plans/manage-subscription/ Video walkthroughs for paying, upgrading, downgrading and cancelling your Bitquery subscription — including pro-rata charges and what happens at renewal. # Manage Your Subscription Everything about your subscription — paying for a plan, buying add-ons, moving between tiers, and cancelling — is self-serve from [Account → Billing](https://account.bitquery.io/user/billing). The two walkthroughs below show the full flow end to end. For the written reference, see [Upgrade to Paid Plan](/docs/ide/paid/) and [How Billing Works](/docs/plans/how-billing-works/). ## Paying for Bitquery products Covers the four-step checkout — **Choose plan → Plan configuration → Review & pay → Done**: - Picking a tier, and switching between monthly and annual billing (annual saves 30% or more) - **Top-up credits** — API points, stream data, stream-minutes, and MCP credits. These are recurring: they refill each billing period rather than being a one-time bucket. - **Historical (archive) data add-ons**, bought per chain and dataset family. Your subscription covers realtime on a rolling window; the archive add-on is what unlocks full history. Use the ⓘ on any add-on to see the exact datasets, cubes and time scope it unlocks. - Reviewing the service agreement and paying by card through Stripe ## Upgrading, downgrading and cancelling Covers changing an existing subscription from the Billing page: - **Change Plan** — the tier comparison, and what moving up actually buys you (streaming, for example, is off on Personal and starts at Pro) - **Manage Add-Ons** — adding capacity or data access without changing tier - **Upgrades are charged pro rata.** When you upgrade or add an add-on mid-cycle, you are only charged for the days remaining in your current period, and the exact amount is finalized by Stripe before you pay. From your next renewal, the full amount bills as one normal monthly subscription. - **Downgrades take effect at your next renewal**, so you keep everything you have already paid for until the period ends. Nothing is charged at the time of the downgrade. - **Cancelling** stops the renewal — no further payments. Your current period and any remaining points stay available until the period end date shown on the cancellation page. No refund is issued for the current period. :::tip Before you cancel If the issue is price or volume rather than the product, a downgrade or a plan sized to your actual usage is usually the better answer. Unlimited streams, custom limits, private endpoints and chains that are not available self-serve are all part of Enterprise — [talk to sales](https://bitquery.io/forms/api) or email [sales@bitquery.io](mailto:sales@bitquery.io). ::: ## Related pages - [Upgrade to Paid Plan](/docs/ide/paid/) — plan table, add-ons and self-serve checkout in detail - [How Billing Works](/docs/plans/how-billing-works/) — points, streams billing and overage - [Manage Account](/docs/ide/account/) — dashboard, navigation and account settings - [Pricing](https://bitquery.io/pricing) — current prices and allowances Billing questions: [support@bitquery.io](mailto:support@bitquery.io). --- ## Manifest DEX API: Order Book Fills, Prices, 1-Minute OHLC and Top Traders URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-manifest-api/ Manifest, Solana's on-chain order book, via Bitquery GraphQL: live fills, USDT/USDC price and 1-minute candles, buy and sell volume and top traders. # Manifest DEX API: Order Book Fills, Prices, 1-Minute OHLC and Top Traders Manifest is an on-chain limit order book on Solana, program `MNFSTqtC93rEfYHB6hF82sKdZpUDFWkViLByLd1k1Ms`, and most of what trades on it is stablecoins: the USDT/USDC market at `8sjV1AqBFvFuADBCQHhotaRq5DFFYSjjg1jMyVWMqXvZ` is its busiest market by a wide margin. Because fills are matched orders rather than pool swaps, prices sit within a few basis points of parity and candles are tight, which makes Manifest a good reference market for stablecoin pricing. Bitquery records each fill in the Solana `DEXTrades` and `DEXTradeByTokens` cubes under `ProtocolFamily: "Manifest"` and `ProtocolName: "manifest"`. Every example runs in the [IDE](https://ide.bitquery.io) on a free account; Solana queries go to the `graphql` endpoint. Aggregates such as candles and rankings are queries; subscriptions are for the live fill and price feeds. ## Live fills Every Manifest fill as it lands, with both sides, the accounts and the market. Saved stream [here](https://ide.bitquery.io/manifest-dextrades). ```graphql subscription { Solana { DEXTrades(where: { Trade: { Dex: { ProtocolFamily: { is: "Manifest" } } } }) { Block { Time } Trade { Market { MarketAddress } Buy { Currency { Symbol MintAddress } Amount AmountInUSD Price Account { Address } } Sell { Currency { Symbol MintAddress } Amount AmountInUSD Account { Address } } } Transaction { Signature Signer } } } } ``` ## Price of USDT in USDC, right now The newest fill in the market. `Price` is the quote per unit of the token and `PriceInUSD` its dollar value. Saved query [here](https://ide.bitquery.io/token-price-on-manifest). ```graphql { Solana { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Dex: { ProtocolFamily: { is: "Manifest" } } Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } } ) { Block { Time } Trade { Price PriceInUSD Market { MarketAddress } } } } } ``` As a subscription the same filter is a price feed that ticks on every fill. Saved stream [here](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-Manifest). ```graphql subscription { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Manifest" } } Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } } ) { Block { Time } Trade { Price PriceInUSD Amount } } } } ``` ## One-minute candles USDT/USDC over the last hour, one row per minute with volume and fill count. `PriceAsymmetry` below 0.1 keeps fills whose two sides agree on price. Saved query [here](https://ide.bitquery.io/manifest-OHLC-API). ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Manifest" } } Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } PriceAsymmetry: { lt: 0.1 } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { hours_ago: 1 } } } } limit: { count: 60 } orderBy: { descendingByField: "Block_Timefield" } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Buy and sell volume of a token Totals for USDT on Manifest over the last hour, in USD, split by direction. `Side.Type` describes the counter-side, so USDT was bought where the side was sold. Saved query [here](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token_7). ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Manifest" } } Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { trades: count volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Top traders of a token Rank signers by USD volume over a day. Saved query [here](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-ManifestDEX). ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 50 } where: { Trade: { Dex: { ProtocolFamily: { is: "Manifest" } } Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Transaction { Signer } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## The busiest Manifest markets Group the last day by market and token pair. ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Manifest" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "fills" } limit: { count: 20 } ) { Trade { Market { MarketAddress } Currency { Symbol MintAddress } Side { Currency { Symbol MintAddress } } } fills: count volumeUsd: sum(of: Trade_Side_AmountInUSD) traders: uniq(of: Transaction_Signer) } } } ``` ## Related pages - [Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) - [Solana API hub](/docs/blockchain/Solana/) --- ## Meme Coin Launches on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-meme-coin-launches/ New token launches across every Robinhood Chain launchpad — Flap.sh, Doppler, Virtuals, Clanker, Klik, Bags.fm — via mint-transfer and TokenCreated queries. # Meme Coin Launches on Robinhood Chain Track **meme coin token launches on Robinhood** with Bitquery GraphQL APIs. This guide shows how to detect newly created tokens from popular Robinhood launchpads and bots — **hood.fun**, **LaunchHood**, **Virtuals**, **Flap.sh**, **Klik Finance**, **Doppler** (the Airlock that Bankr and other front-ends launch through), **Ape.store**, **Bags.fm**, and **Clanker** — using `EVM(network: robinhood)` Events and Transfers cubes. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). This page covers token launches only. For the full Robinhood Chain API — trades, transfers, balances, holders, transactions, events and live streams — start with the [Robinhood Chain API overview](/docs/blockchain/robinhood/). :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending) — new pools, trending tokens, pair lookup and token search - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers) - [Pons Launchpad API on Robinhood Chain](/docs/blockchain/robinhood/pons-api) — bonding-curve launchpad, graduations, Uniswap v4 pools - [Pools.trade API on Robinhood](/docs/blockchain/robinhood/pools-trade-api) - [Flap.sh API on Robinhood](/docs/blockchain/robinhood/flap-sh-api) - [trench.today API on Robinhood](/docs/blockchain/robinhood/trench-today-api) - [Bags.fm API on Robinhood](/docs/blockchain/robinhood/bags-fm-api) - [WebSocket subscriptions](/docs/subscriptions/websockets/) ::: :::tip Stream the same query For each launch query below, open the matching **WebSocket** IDE link to run it as a real-time GraphQL subscription over WebSocket. You can also convert a query to a stream in the IDE by changing the operation type to `subscription`. ::: --- ▶️ Cross-launchpad stream: [New tokens on Robinhood Chain, all launchpads](https://ide.bitquery.io/stream-new-tokens-robinhood-chain) ## How token launches are detected Most Robinhood meme launch contracts mint tokens in a create transaction. You can detect those launches in two ways: | Method | Cube | Pattern | | --- | --- | --- | | **Events** | `EVM.Events` | Filter `LogHeader.Address` to the launch contract; for Flap.sh, also filter `Log.Signature.Name: TokenCreated` | | **Transfers** | `EVM.Transfers` | Mint from the zero address (`0x000…000`) to a receiver, with `Transaction.To` equal to the launch contract and a fixed launch mint `Amount` | Zero-address sender (`0x0000000000000000000000000000000000000000`) marks a mint. Pairing that with the launchpad contract as `Transaction.To` scopes results to that protocol’s creations. The fixed `Amount` in each transfer query is the **full initial token supply minted at launch** — `1000000000` (1 billion) for most launchpads and `100000000000` (100 billion) for Clanker. Filtering on this value isolates the launch mint from ordinary transfers, so adjust it if a protocol uses a different launch supply. :::note Amounts are decimal-normalized Bitquery's `Transfer.Amount` is already adjusted for the token's `Decimals`, so `1000000000` means 1 billion whole tokens — not the raw on-chain integer you'd see on a block explorer. Compare against the normalized value, not the raw one. ::: :::note `AmountInUSD` is `0` on launch mints On Robinhood, `Transfer.AmountInUSD` is populated only for native ETH transfers. A freshly minted token has no price, so every launch-mint row below shows `"AmountInUSD": "0"`; it is selected for consistency with other transfer queries, not because it carries a value here. ::: Flap.sh emits a decoded `TokenCreated` event, so it can be tracked via **Events** (richer, with decoded arguments) as well as transfers. The other launchpads and bots on this page are tracked via the **mint-transfer** pattern. ### Stream launches as they happen Launches are the case where polling is worst: a query tells you what already launched, and by the time you re-run it the opportunity has moved. The same mint-transfer filter works as a subscription, so you get each launch pushed at block time. ```graphql subscription NewRobinhoodLaunches { EVM(network: robinhood) { Transfers( where: { Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } } } ) { Block { Time } Transaction { Hash To } Transfer { Receiver Amount Currency { Name Symbol SmartContract Decimals } } } } } ``` This streams **every** mint on the chain. Narrow it the same way the queries below do — add `Transaction: { To: { is: "" } }` for one launchpad, and the launch-mint `Amount` if you want only the initial supply mint rather than every subsequent mint. :::note Do not add `dataset:` to a subscription Subscriptions always read the live stream. The `dataset: combined` tip above applies to queries reaching backwards, not to streams. ::: :::tip Reaching older launches These queries default to the **realtime** dataset — a rolling window of recent blocks whose depth varies. Launchpads with sparse recent activity can return few or no rows. To reach further back, add `dataset: combined` (or `archive`) on the `EVM` root plus a time filter — e.g. `EVM(network: robinhood, dataset: combined)` with `Block: {Time: {since_relative: {days_ago: 7}}}`. ::: --- ## Launchpad and bot contract map Every transfer query on this page is **identical except two values**: the launchpad address in `Transaction.To` and the launch-mint `Amount`. To track a different launchpad, copy any transfer query below and swap in the address (and, for Clanker, the amount) from this table. | Protocol | Contract → `Transaction.To` | Mint `Amount` | Queries | | --- | --- | --- | --- | | **hood.fun** | `0x5fcc1df0dc020cf454e742e9a8ae2554c37a452c` | `1000000000` | [Transfers](https://ide.bitquery.io/hoodfun-newly-creaed-tokens) ([WS](https://ide.bitquery.io/hoodfun-newly-creaed-tokens---Websocket)) | | **LaunchHood** | `0x62b33a039d289cbda50ebeb72fe4261449e61bcf` | `1000000000` | [Transfers](https://ide.bitquery.io/launchpad-newly-creaed-tokens) ([WS](https://ide.bitquery.io/launchpad-newly-creaed-tokens---Websocket)) | | **Virtuals** | `0xd4ccbfa37e2f35611b3042e4096ad7a3459bd007` | _any_ (no fixed supply) | [Transfers](https://ide.bitquery.io/Virtuals-Newly-created-tokens) | | **Flap.sh** | `0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09` | `1000000000` | [Events](https://ide.bitquery.io/All-events-from-Flapsh) · [TokenCreated](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-logs-TokenCreated) ([WS](https://ide.bitquery.io/Flap-sh-Newly-created-tokens-using-logs-TokenCreated---Websocket)) · [Transfers](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-transfer-data) ([WS](https://ide.bitquery.io/Flap-Sh-Newly-created-tokens-using-transfer-data---Websocket)) | | **Klik Finance** | `0x16cf6788b762ee8969744586ed16fc5705140dd7` | `1000000000` | [Transfers](https://ide.bitquery.io/Klik-Finance-Newly-created-tokens-using-transfers) ([WS](https://ide.bitquery.io/Klik-Finance-Newly-created-tokens-using-transfers-websocket)) | | **Doppler Airlock** (Bankr, Long.xyz and other front-ends) | `0xeb7c034704ef8dcd2d32324c1545f62fb4ad0862` (Airlock) · `0x22e99278308b393ea1260859b181ad7e78f5eeed` (launcher most front-ends call) | `1000000000` | [Transfers](https://ide.bitquery.io/Bankr-Bot-Newly-created-tokens) ([WS](https://ide.bitquery.io/Bankr-Bot-Newly-created-tokens---Websocket)) | | **Ape.store** | `0x6e4910ea5a04376032f6564da9a9e4e88b7a87c1` | `1000000000` | [Transfers](https://ide.bitquery.io/Apestore-Newly-created-tokens) ([WS](https://ide.bitquery.io/Apestore-Newly-created-tokens---Websocket)) | | **Bags.fm** | `0xe8cc4431adf8b5a847c113ef0c6af9043219cb37` | `1000000000` | [Transfers](https://ide.bitquery.io/Bagsfm-Newly-created-tokens) ([WS](https://ide.bitquery.io/Bagsfm-Newly-created-tokens---Websocket)) | | **Clanker** | `0xd3f2cc1731b7fd17f28798835c2e02f0a1839a94` | `100000000000` | [Transfers](https://ide.bitquery.io/Clanker-Newly-created-tokens) ([WS](https://ide.bitquery.io/Clanker-Newly-created-tokens---Websocket)) | | **Pons V2** | `0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e` (factory) · `0xe33e9e479df8802cb0866d5d05258bec4cf62948` (router) | `1000000000` | [Pons Launchpad API](/docs/blockchain/robinhood/pons-api) | | **pools.trade** | `0x0000ffffbe8efe702c8703ae3477ff5de3d319c0` · `0x00004c4ccc709ef590f7c81102c0689f0263d4e9` (entry contracts) | `1000000000` | [Pools.trade API](/docs/blockchain/robinhood/pools-trade-api) | | **trench.today** | `0x77dc6f6361b7b99456fc3761ce5b7dda80d83f9d` (factory proxy) | see guide | [trench.today API](/docs/blockchain/robinhood/trench-today-api) | _WS = WebSocket subscription (real-time stream of the same query)._ --- ## Compare launchpad activity One query across every launchpad: count zero-address mints per launch contract over a window (`Transaction.To` in the contract-map list) and group by contract. `tokens` counts distinct minted token contracts. This matches mints of **any** amount — Clanker's different launch supply included — so treat it as an activity overview rather than an exact per-protocol launch count. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( limit: { count: 10 } orderBy: { descendingByField: "launches" } where: { Block: { Time: { since_relative: { days_ago: 7 } } } Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } } Transaction: { To: { in: [ "0x5fcc1df0dc020cf454e742e9a8ae2554c37a452c" "0x62b33a039d289cbda50ebeb72fe4261449e61bcf" "0xd4ccbfa37e2f35611b3042e4096ad7a3459bd007" "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09" "0x16cf6788b762ee8969744586ed16fc5705140dd7" "0xeb7c034704ef8dcd2d32324c1545f62fb4ad0862" "0x6e4910ea5a04376032f6564da9a9e4e88b7a87c1" "0xe8cc4431adf8b5a847c113ef0c6af9043219cb37" "0xd3f2cc1731b7fd17f28798835c2e02f0a1839a94" ] } } } ) { Transaction { To } launches: count tokens: uniq(of: Transfer_Currency_SmartContract) } } } ``` ### Launches per day for one launchpad Bucket a launchpad's mints into daily counts — a launch-rate series (example: Flap.sh). ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( limit: { count: 7 } orderBy: { descendingByField: "Block_Time" } where: { Block: { Time: { since_relative: { days_ago: 7 } } } Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } } Transaction: { To: { is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09" } } } ) { Block { Time(interval: { in: days, count: 1 }) } launches: count } } } ``` --- ## hood.fun **[hood.fun](https://hood.fun/)** was one of the first fair-launch memecoin launchpads on the Robinhood network. Every token launches with a fixed **1 billion** supply on a bonding curve, so newly created tokens can be detected as mint transfers from the zero address where `Transaction.To` is the hood.fun contract. :::note Contract generations The current hood.fun launch contract is `0x5fcc1df0dc020cf454e742e9a8ae2554c37a452c`. The previous generation, `0x6a63d96ef77ae569fcb85934cf1bd1ec7fe9b33d`, still has tokens trading — swap the address in `Transaction.To` to query it. Older generations' launch history sits outside the realtime window, so query them with `dataset: combined` or `archive`. ::: ### hood.fun Newly created tokens :::caution hood.fun has stopped launching hood.fun has produced no launch since mid-July 2026, so on the default realtime dataset this query returns nothing. It is pinned to `dataset: archive` below to return the historical launches; re-check realtime before assuming the launchpad is gone for good. ::: ▶️ [Run in IDE](https://ide.bitquery.io/hoodfun-newly-creaed-tokens) · [WebSocket stream](https://ide.bitquery.io/hoodfun-newly-creaed-tokens---Websocket) ```graphql { EVM(network: robinhood, dataset: archive) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0x5fcc1df0dc020cf454e742e9a8ae2554c37a452c"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## LaunchHood **[LaunchHood](https://launchhood.com/)** is a memecoin launchpad on the Robinhood network where every coin lists directly on Uniswap at creation, with a fixed **1 billion** supply. Detect new LaunchHood tokens as mint transfers from the zero address where `Transaction.To` is the LaunchHood factory contract. ### LaunchHood Newly created tokens :::caution LaunchHood has stopped launching LaunchHood has produced no launch since mid-August 2026, so on the default realtime dataset this query returns nothing. It is pinned to `dataset: archive` below to return the historical launches. ::: ▶️ [Run in IDE](https://ide.bitquery.io/launchpad-newly-creaed-tokens) · [WebSocket stream](https://ide.bitquery.io/launchpad-newly-creaed-tokens---Websocket) ```graphql { EVM(network: robinhood, dataset: archive) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0x62b33a039d289cbda50ebeb72fe4261449e61bcf"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## Virtuals **[Virtuals Protocol](https://virtuals.io/)** launches on Robinhood can be detected as mint transfers from the zero address where `Transaction.To` is the Virtuals contract. Unlike the other launchpads on this page, Virtuals tokens don't use a fixed launch supply, so this query omits the `Transfer.Amount` filter and matches on the zero-address mint alone. ### Virtuals Newly created tokens ▶️ [Run in IDE](https://ide.bitquery.io/Virtuals-Newly-created-tokens) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0xd4ccbfa37e2f35611b3042e4096ad7a3459bd007"}} Transfer: {Sender: {is: "0x0000000000000000000000000000000000000000"}} } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## Flap.sh Flap.sh launches on Robinhood can be monitored via contract events and mint transfers. ### All events from Flap.sh List event signatures emitted by the Flap.sh contract to discover which logs are available for indexing. ▶️ [Run in IDE](https://ide.bitquery.io/All-events-from-Flapsh) ```graphql { EVM(network: robinhood) { Events( limit: {count: 100} where: {LogHeader: {Address: {is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"}}} ) { count Log { Signature { Name } SmartContract } } } } ``` ### Flap.sh Newly created tokens using logs (`TokenCreated`) Filter Flap.sh `TokenCreated` events and decode argument values (token address, metadata fields, and related parameters). ▶️ [Run in IDE](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-logs-TokenCreated) · [WebSocket stream](https://ide.bitquery.io/Flap-sh-Newly-created-tokens-using-logs-TokenCreated---Websocket) ```graphql { EVM(network: robinhood) { Events( limit: {count: 10} where: { Log: {Signature: {Name: {is: "TokenCreated"}}} LogHeader: {Address: {is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"}} } ) { Transaction { Hash From To } Log { Signature { Name } SmartContract } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ### Flap.sh Newly created tokens using transfer data Track Flap.sh mints as transfers from the zero address with amount `1000000000` in transactions sent to the Flap.sh contract. ▶️ [Run in IDE](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-transfer-data) · [WebSocket stream](https://ide.bitquery.io/Flap-Sh-Newly-created-tokens-using-transfer-data---Websocket) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ```
Sample response Each row is one newly launched token. `Transfer.Sender` is the zero address (the mint), `Transfer.Receiver` is the deployer/first holder, and `Currency.SmartContract` is the new token address. ```json { "EVM": { "Transfers": [ { "Block": { "Number": "12873456", "Time": "2026-07-15T11:42:08Z" }, "Transaction": { "Hash": "0x9f2c...a41b", "From": "0x39d83c23dbf34fa574b9afbb0c0e364bdfd97099", "To": "0x26605f322f7ff986f381bb9a6e3f5dab0beaeb09" }, "TransactionStatus": { "Success": true }, "Transfer": { "Amount": "1000000000", "AmountInUSD": "0", "Sender": "0x0000000000000000000000000000000000000000", "Receiver": "0x39d83c23dbf34fa574b9afbb0c0e364bdfd97099", "Currency": { "Name": "Example Meme", "Symbol": "MEME", "SmartContract": "0x9077841e155faaf4e4e89470822c2187eeef7777", "Decimals": 18, "Fungible": true, "Native": false, "ProtocolName": "" } } } ] } } ```
--- ## Klik Finance Detect **[Klik Finance](https://klik.finance/)** token launches on Robinhood by filtering mint transfers where `Transaction.To` is the Klik Finance contract. ### Klik Finance Newly created tokens using transfers ▶️ [Run in IDE](https://ide.bitquery.io/Klik-Finance-Newly-created-tokens-using-transfers) · [WebSocket stream](https://ide.bitquery.io/Klik-Finance-Newly-created-tokens-using-transfers-websocket) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0x16cf6788b762ee8969744586ed16fc5705140dd7"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## Doppler Airlock `0xeb7c034704ef8dcd2d32324c1545f62fb4ad0862` is the **Doppler Airlock**, the launch contract behind [Bankr](https://bankr.bot/), Long.xyz and other front-ends on Robinhood Chain, and one of the largest launch sources on the network. Its source is verified on the [chain explorer](https://robinhoodchain.blockscout.com/address/0xeb7c034704ef8dcd2d32324c1545f62fb4ad0862) under the contract name `Airlock`. It emits `Create` for every launch and `Migrate` when a token moves to its final pool. | Role | Address | Notes | | --- | --- | --- | | **Airlock** (launch contract) | `0xeb7c034704ef8dcd2d32324c1545f62fb4ad0862` | Emits `Create`, `Migrate`, `Collect` | | **Doppler hook / initializer** | `0x4e3468951d49f2eea976ed0d6e75ffcb44a9a544` | Verified as `DopplerHookInitializer`. It is both the initializer named in every `Create` and the `hooks` address on the resulting Uniswap v4 pool, which makes it the filter for finding those pools | | **LongLauncher** (front-end launcher) | `0x22e99278308b393ea1260859b181ad7e78f5eeed` | Verified as `LongLauncher`. Most launches are routed through it rather than sent to the Airlock directly | Because most launches arrive through the launcher, **filter `Transaction.To` on both the Airlock and the launcher**; a filter on the Airlock alone misses the majority. Attribute a launch to a front-end by the launcher contract it came through, not by this page's label. :::caution The `Create` event's argument **names** are wrong — read by position The Airlock is indexed with the wrong ABI, so `Arguments.Name` returns names from an unrelated contract. The verified source declares: ```solidity event Create(address asset, address indexed numeraire, address initializer, address poolOrHook); ``` Until the ABI is corrected, map the arguments by **`Arguments.Index`**: | `Arguments.Index` | Name the API returns | What it actually is | | --- | --- | --- | | `0` | `caller` | **`numeraire`** — the quote asset the token launched against (USDG, GLD, NVDA and other tokenized stocks) | | `1` | `token0` | **`asset`** — the newly launched token | | `2` | `token1` | **`initializer`** — always `0x4e346895…`, the `DopplerHookInitializer` | | `3` | `optionPair` | **`poolOrHook`** — duplicates the asset on every launch checked (120 of 120, and `LongLauncher` reports the same pair of values in its own event). The pool's actual hook is a separate contract, below | The raw log confirms the shape: two topics (the signature plus one indexed argument) and three data words, so index `0` is the indexed `numeraire` from `topic1` and indexes `1`–`3` are the data words in order. One more trap: an `Arguments: {includes: {Value: {Address: …}}}` filter matches an address in **any** position, so on its own it cannot prove a token was launched here — it also matches when your address was merely the quote asset. Tokenized stocks are common numeraires, so a popular one shows up against hundreds of launches it did not produce. ::: ### Finding a Doppler token's Uniswap v4 pool Every Doppler launch opens a Uniswap v4 pool with a consistent shape: the **numeraire is `currency0`**, the **asset is `currency1`**, `hooks` is always the `DopplerHookInitializer`, and `fee` is `8388608` — Uniswap v4's dynamic-fee flag rather than a fixed rate. That makes the hook a clean filter for every Doppler pool on the chain: ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} Arguments: {includes: { Name: {is: "hooks"} Value: {Address: {is: "0x4e3468951d49f2eea976ed0d6e75ffcb44a9a544"}} }} } ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` The `id` argument is the v4 pool id, which the [New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending#v4-pool-id) uses to look a v4 pair up — v4 pools share one contract address, so the id is the only per-pool handle. :::note `LaunchCreated` is richer, but not yet decoded `LongLauncher` emits `LaunchCreated(poolOrHook, asset, numeraire, poolInitializer, launcher, tickerKey, deployedAt, reservedUntil, normalizedTicker)`, which carries the ticker string the Airlock's `Create` does not. That event is **not decoded** in the index today — it appears only under its topic0 `adc6f1f726f7c710…` with no argument names. Until it is decoded, use the Airlock's `Create`, or match the topic0 and decode the payload client-side. ::: ### Doppler newly created tokens ▶️ [Run in IDE](https://ide.bitquery.io/Bankr-Bot-Newly-created-tokens) · [WebSocket stream](https://ide.bitquery.io/Bankr-Bot-Newly-created-tokens---Websocket) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {in: ["0xeb7c034704ef8dcd2d32324c1545f62fb4ad0862", "0x22e99278308b393ea1260859b181ad7e78f5eeed"]}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## Ape.store Monitor **[Ape.store](https://ape.store/)** meme coin launches on Robinhood with the same mint-transfer pattern. ### Ape.store Newly created tokens ▶️ [Run in IDE](https://ide.bitquery.io/Apestore-Newly-created-tokens) · [WebSocket stream](https://ide.bitquery.io/Apestore-Newly-created-tokens---Websocket) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0x6e4910ea5a04376032f6564da9a9e4e88b7a87c1"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## Bags.fm Query **[Bags.fm](https://bags.fm/)** newly created tokens on Robinhood by mint amount and Bags.fm contract address. ### Bags.fm Newly created tokens ▶️ [Run in IDE](https://ide.bitquery.io/Bagsfm-Newly-created-tokens) · [WebSocket stream](https://ide.bitquery.io/Bagsfm-Newly-created-tokens---Websocket) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0xe8cc4431adf8b5a847c113ef0c6af9043219cb37"}} Transfer: { Amount: {eq: "1000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## Clanker Track **[Clanker](https://clanker.world/)** token launches on Robinhood. Clanker mints use amount `100000000000` (different from the `1000000000` used by the other launchpads above). ### Clanker Newly created tokens ▶️ [Run in IDE](https://ide.bitquery.io/Clanker-Newly-created-tokens) · [WebSocket stream](https://ide.bitquery.io/Clanker-Newly-created-tokens---Websocket) ```graphql { EVM(network: robinhood) { Transfers( orderBy: {descending: Block_Time} limit: {count: 50} where: { Transaction: {To: {is: "0xd3f2cc1731b7fd17f28798835c2e02f0a1839a94"}} Transfer: { Amount: {eq: "100000000000"} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time Number } Transaction { Hash From To } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } } } } } ``` --- ## FAQ ### How do I track new Robinhood meme coin launches in real time? Open any **WebSocket** link in the [contract map](#launchpad-and-bot-contract-map) above, or take a launch query on this page and change its operation type from a query to a `subscription` in the Bitquery IDE. Each new launch is then pushed to your client as it is mined. ### Which launchpads and bots does this page cover? Virtuals, Flap.sh, Klik Finance, the Doppler Airlock (Bankr and other front-ends), Ape.store, Bags.fm, and Clanker on the Robinhood network, plus hood.fun and LaunchHood for history. Pons, pools.trade and trench.today have their own guides. Each has its own contract address and mint amount listed in the contract map. ### How do I track a launchpad that isn't listed here? Copy any transfer query on this page and replace the address in `Transaction.To` with the launchpad's contract. Keep the `Transfer.Sender` zero-address filter (it isolates mints) and set `Transfer.Amount` to that launchpad's initial mint supply. ### Why do the queries filter transfers by a fixed `Amount`? The `Amount` is the full initial token supply minted at launch (`1000000000` for most launchpads, `100000000000` for Clanker). Combined with the zero-address sender, it isolates the launch mint from ordinary transfers. `Transfer.Amount` is already decimal-normalized, so compare against the whole-token value, not the raw on-chain integer. ### How do I compare launch activity across launchpads? Use the [cross-launchpad query](#compare-launchpad-activity): filter zero-address mints where `Transaction.To` is in the contract-map list, group by `Transaction.To`, and `count`. Add `dataset: combined` and a `Block.Time` window for full coverage. ### Should I use the Events or Transfers method? Use **Events** when a launchpad emits a decoded creation event (like Flap.sh's `TokenCreated`) and you want the decoded arguments. Use **Transfers** — the mint-transfer pattern — for launchpads that don't expose a convenient event, which covers every protocol on this page. --- ## Next steps - Use the **WebSocket stream** links above (or switch the query to `subscription` in the IDE) for real-time launch alerts. - Track a launchpad not listed here by swapping `Transaction.To` and `Amount` per the [contract map](#launchpad-and-bot-contract-map). - Follow new tokens into markets with the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades). - Inspect holder and wallet flows with [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers). ## Video Tutorial | Most Traded Robinhood Chain Meme Coins This Week, and Who Is Really Trading Them --- ## Mempool Data API Overview URL: https://docs.bitquery.io/docs/start/mempool/ Use Bitquery mempool APIs to watch pending transactions before confirmation across supported chains with GraphQL queries and streams. # Getting Mempool Data In the previous section, we saw how to write a subscription query. Now, let's examine the process of obtaining mempool data. Before any information can be written on a block, it must first go through the mempool, which acts as a waiting room for transactions. All unconfirmed transactions are held here. By using the following query format, you can access all information about broadcasted transactions, including events, trades, and balances: ```graphql query{ EVM(mempool: true){ } } ``` And below format for subscriptions ```graphql subscription { EVM(mempool: true) { } } ``` You can find Mempool API examples [here](/docs/blockchain/Ethereum/mempool/mempool-api/) --- ## Mempool Transaction Fee Explorer URL: https://docs.bitquery.io/docs/usecases/mempool-transaction-fee/ Build Mempool Transaction Fee Explorer: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Mempool Transaction Fee Explorer In the world of cryptocurrency, understanding transaction fees and their dynamics is crucial for traders, investors, and blockchain enthusiasts alike. Ethereum, one of the leading blockchain platforms, relies on a concept known as the "Mempool" to manage pending transactions and determine their associated fees. The [Mempool API](https://bitquery.io/products/mempool-api) provides developers with a convenient interface to access real-time data from the Ethereum Mempool. By using the Mempool API, developers can get details about transactions, monitor how transaction fee changes, and learn more about what's happening on the Ethereum network. In this blog, we'll explore the concept of the Mempool, delve into the functionalities of the Mempool API, and embark on a practical journey of building a transaction fee analysis dashboard using Python, Streamlit, and the Mempool API. ## Building a Mempool Transaction Fee Analysis Dashboard with Streamlit In this tutorial, we'll focus on a practical use case of utilizing the Mempool API to build a transaction fee analysis dashboard. This dashboard will offer users a comprehensive view of recent Ethereum transactions, including details such as transaction hashes, block numbers, sender and receiver addresses, transaction costs, and associated fees. Moreover, we'll visualize key metrics such as burnt fees and priority fees per gas over time, allowing users to track fee trends and make informed decisions regarding transaction prioritization and fee optimization. By the end of this tutorial, readers will have a solid understanding of how to interact with the Mempool API, fetch real-time transaction data, process it using Python libraries like Pandas and Matplotlib, and present it in an interactive dashboard using Streamlit. ### Step 1: Importing Libraries and Defining Constants ```python ``` In this section, we import necessary libraries: streamlit, requests, pandas, and matplotlib. These libraries will help us build our Streamlit web application and handle data visualization. ### Step 2: Defining Constants and GraphQL Query ```python ACCESS_TOKEN = "Your_v2_Access_Token" MEMPOOL_API_URL = "https://streaming.bitquery.io/graphql" GRAPHQL_QUERY = """ { EVM(mempool: true) { Transactions(limit: {count: 200}) { Block { Time Number } Transaction { Hash Cost To From } Fee { Burnt SenderFee PriorityFeePerGas MinerReward GasRefund EffectiveGasPrice Savings } } } } """ ``` Here, we define constants such as ACCESS_TOKEN for the Mempool API and MEMPOOL_API_URL for its endpoint. We also define the GraphQL query (GRAPHQL_QUERY) that will retrieve transaction data from the Mempool API. ### Step 3: Function to Fetch Data from the Mempool API ```python def fetch_data_from_mempool_api(): headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {ACCESS_TOKEN}' } response = requests.post(MEMPOOL_API_URL, json={"query": GRAPHQL_QUERY}, headers=headers) data = response.json() return data['data']['EVM']['Transactions'] ``` This function fetch_data_from_mempool_api() sends a POST request to the Mempool API endpoint with the GraphQL query and access token. It then returns the transaction data obtained from the response. ### Step 4: Creating the Streamlit App ```python def main(): ``` #### Set page title ``` st.title("Transaction Fee Analysis Dashboard") ``` ## Fetch data from Mempool API ```python try: transactions_data = fetch_data_from_mempool_api() except Exception as e: st.error(f"Error fetching data from Mempool API: {str(e)}") return ``` Here, we define the main function main() where we set the page title for our Streamlit app and attempt to fetch data from the Mempool API. We handle any exceptions that may occur during data retrieval. ### Step 5: Processing and Displaying Data #### Initialize lists to store data ```python block_time = [] block_number = [] transaction_hash = [] transaction_cost = [] transaction_to = [] transaction_from = [] fee_burnt = [] fee_sender = [] fee_priority = [] fee_miner = [] fee_refund = [] fee_effective_gas = [] fee_savings = [] ``` #### Extract data from JSON and store in lists ```python for transaction in transactions_data: block_time.append(transaction['Block']['Time']) block_number.append(transaction['Block']['Number']) transaction_hash.append(transaction['Transaction']['Hash']) transaction_cost.append(transaction['Transaction']['Cost']) transaction_to.append(transaction['Transaction']['To']) transaction_from.append(transaction['Transaction']['From']) fee_burnt.append(transaction['Fee']['Burnt']) fee_sender.append(transaction['Fee']['SenderFee']) fee_priority.append(transaction['Fee']['PriorityFeePerGas']) fee_miner.append(transaction['Fee']['MinerReward']) fee_refund.append(transaction['Fee']['GasRefund']) fee_effective_gas.append(transaction['Fee']['EffectiveGasPrice']) fee_savings.append(transaction['Fee']['Savings']) ``` #### Create DataFrame ```python df = pd.DataFrame({ 'Block Time': block_time, 'Block Number': block_number, 'Transaction Hash': transaction_hash, 'Transaction Cost': transaction_cost, 'Transaction To': transaction_to, 'Transaction From': transaction_from, 'Fee Burnt': fee_burnt, 'Fee Sender': fee_sender, 'Fee Priority': fee_priority, 'Fee Miner': fee_miner, 'Fee Refund': fee_refund, 'Fee Effective Gas': fee_effective_gas, 'Fee Savings': fee_savings }) ``` #### Display DataFrame ```python st.subheader("Latest Transactions and Fee Details") st.write(df) ``` In this section, we process the fetched transaction data by extracting relevant information and storing it in lists. Then, we create a Pandas DataFrame (df) to organize the data and display it using Streamlit. ### Step 6: Visualizing Data #### Initialize lists for fee data ```python timestamps = [] burnt_fees = [] priority_fees = [] ``` #### Extract fee data from transactions ```python for transaction in transactions_data: timestamps.append(pd.to_datetime(transaction['Block']['Time'])) burnt_fees.append(float(transaction['Fee']['Burnt'])) priority_fees.append(float(transaction['Fee']['PriorityFeePerGas'])) ``` #### Create DataFrame ```python df = pd.DataFrame({ 'Timestamp': timestamps, 'Burnt Fee': burnt_fees, 'Priority Fee': priority_fees }) ``` #### Set index to Timestamp for time-based plotting ``` df.set_index('Timestamp', inplace=True) ``` #### Display DataFrame ``` st.subheader("Latest Transactions and Fee Details") st.write(df) ``` #### Plot bar chart for burnt fee over time ```python st.subheader("Burnt Fee over Time") plt.figure(figsize=(10, 6)) plt.scatter(df.index, df['Burnt Fee'], color='blue') plt.xlabel('Timestamp') plt.ylabel('Burnt Fee') plt.xticks(rotation=45) st.pyplot(plt) ``` #### Plot bar chart for priority fee per gas over time ```python st.subheader("Priority Fee per Gas over Time") plt.figure(figsize=(10, 6)) plt.scatter(df.index, df['Priority Fee'], color='red') plt.xlabel('Timestamp') plt.ylabel('Priority Fee per Gas') plt.xticks(rotation=45) st.pyplot(plt) ``` Here, we prepare fee data for visualization by extracting timestamps and fee values from transactions. We create another DataFrame (df) for visualization purposes, set the index to timestamps, and display it using Streamlit. Additionally, we plot bar charts for burnt fee and priority fee per gas over time using Matplotlib. ### Step 7: Running the Streamlit App ``` if **name** == "**main**": main() ``` Finally, we run the Streamlit app by calling the main() function if the script is executed directly. This is the entry point of our application. ## Output When you run the Streamlit app generated by the code, here's what you can expect to see: - Latest Transactions and Fee Details: You will see a table displaying details of the latest transactions fetched from the Mempool API. The table includes information such as block time, block number, transaction hash, transaction cost, sender, receiver, and various fee details. ![Mempool transaction fee analysis, step 1](/img/mempool-transaction-fee/image-001.png) - Burnt Fee over Time: A scatter plot will show the burnt fee (the fee consumed by the network) over time. The x-axis represents the timestamp of transactions, and the y-axis represents the burnt fee value. ![Mempool transaction fee analysis, step 2](/img/mempool-transaction-fee/image-002.png) - Priority Fee per Gas over Time: Another scatter plot will display the priority fee per gas (the fee paid by the user for faster confirmation) over time. Similarly, the x-axis represents the timestamp, and the y-axis represents the priority fee per gas. ![Mempool transaction fee analysis, step 3](/img/mempool-transaction-fee/image-003.png) When interacting with the dashboard, users can analyze transaction data, identify patterns, and make informed decisions regarding transaction prioritization and fee management. Overall, the dashboard offers a user-friendly interface for exploring and understanding Ethereum transaction fees in real-time, facilitating better decision-making in the realm of cryptocurrency transactions. --- ## Meteora DAMM v1 API: Dynamic AMM Trades and Pools URL: https://docs.bitquery.io/docs/blockchain/Solana/Meteora-DYN-API/ Meteora DAMM v1 (Dynamic AMM) API on Solana: swaps with USD price, OHLC candles, top traders, volume and pool liquidity on the amm program via Bitquery. # Meteora DAMM v1 API Meteora DAMM v1 is the Dynamic AMM, Meteora's original constant-product pool program on Solana, at `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB`. It runs stable pools for pegged assets, LST pools for staked SOL, and full-range pools whose idle reserves can earn extra yield through Meteora's Dynamic Vaults. Bitquery reads its swaps, prices, candles, traders and reserves over GraphQL, WebSocket, Kafka and gRPC. Meteora files DAMM v1 under legacy products. The pools that exist keep trading, and the deepest of them are still meaningful markets for staked SOL and stablecoins, but **new DAMM v1 pools are no longer being created**: new launches go to DAMM v2, and Dynamic Bonding Curve graduations now migrate into DAMM v2 as well. Plan integrations around the pools that exist rather than around pool creation. :::note This page was previously published as the Meteora DYN API "DYN" was our shorthand, not a Meteora product name. The program, the URL and every query here are unchanged; only the naming now matches [Meteora's own documentation](https://docs.meteora.ag/legacy-products/damm-v1/what-is-damm-v1). ::: :::tip Start with the Trading API The [**Trading API**](/docs/trading/trading-data-overview) answers most questions on this page fastest. [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns **MEV-filtered swaps with USD price, market cap and supply on every row**, and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) gives pre-aggregated OHLC per pool down to one second. Filter either with `Market: { Protocol: { is: "amm" } }` and `Network: { is: "Solana" }` for DAMM v1. Drop to the chain-level cubes for pool reserves and for history older than about 30 days. ::: :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## What is the Meteora DAMM v1 program ID on Solana? {#track-latest-created-pools-on-meteora-dyn} The Dynamic AMM program is `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB` on Solana mainnet, and Meteora uses the same address on devnet. Two related programs sit beside it: Dynamic Vault at `24Uqj9JCLxUeoC3hGfh5W3s9FM9uCHDS2SG3LYwBpyTi`, which earns yield on idle reserves, and Farming at `FarmuwXPWXvefWUeqFAa5w6rifLkq5X6E8bimYvrhCB1`. ``` Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB ``` In the Trading cubes DAMM v1 is `Market.Protocol` `amm`. In the Solana chain-level cubes the rows carry `Dex.ProtocolName` `amm` and `Dex.ProtocolFamily` `Meteora`. Method names on this program are camelCase, as on DLMM: swaps are `swap`, liquidity moves are `addBalanceLiquidity` and `removeBalanceLiquidity`. DAMM v2 and DBC use snake_case instead, so do not copy method spellings between Meteora pages. Meteora runs four trading programs on Solana, each with its own Bitquery page: | Meteora program | Program ID | Protocol name | Bitquery page | | --- | --- | --- | --- | | DAMM v1, the legacy Dynamic AMM | `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB` | `amm` | This page | | DAMM v2, constant-product pools with position NFTs | `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG` | `cp_amm` | [Meteora DAMM v2 API](/docs/blockchain/Solana/Meteora-DAMM-v2-API/) | | DLMM, concentrated liquidity in price bins | `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo` | `lb_clmm` | [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API/) | | Dynamic Bonding Curve, launches that graduate to a DAMM pool | `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` | `dynamic_bonding_curve` | [Meteora DBC API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) | ## Does Meteora have an API? Yes, for pool-level data. Meteora publishes a free REST [DAMM v1 Data API](https://docs.meteora.ag/developer-guides/damm-v1/api-reference/overview) at `https://damm-api.meteora.ag`, limited to 10 requests a second with no key, covering pool state and related vault data. It has no per-swap trade endpoint, no per-wallet swap history and no streaming. Bitquery reads the same activity from the chain: swaps as individual rows with the trader and a USD price, reserves after every liquidity change, and history back to mid-2024. ## Which DAMM v1 pools are still active Since new pools are not being created, the useful starting point is a ranking of the pools that exist. This returns the busiest DAMM v1 markets over the last 24 hours by USD volume. ```graphql { Trading { Pairs( limit: { count: 25 } orderBy: { descendingByField: "usd" } where: { Market: { Protocol: { is: "amm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Market { Address } Token { Symbol Address } QuoteToken { Symbol } usd: sum(of: Volume_Usd) } } } ``` The examples below use JitoSOL (`J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn`), whose WSOL pool `ERgpKaq59Nnfm9YRVAAhnq16cZhHxGcDoDWCzXbhiaNw` is the deepest DAMM v1 market and one of the LST pools the program was built for. ## Meteora DAMM v1 trades in real time {#meteora-dyn-trades-in-real-time} Stream every decoded DAMM v1 swap with the trader, both amounts and the USD price. ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "amm" }, Network: { is: "Solana" } } } } ) { Block { Time } Side Price PriceInUsd Trader { Address } Amounts { Base Quote } AmountsInUsd { Base Quote } TransactionHeader { Hash } Pair { Market { Address Protocol } Token { Symbol Address } QuoteToken { Symbol Address } } } } } ``` Add `Pair: { Token: { Address: { is: "" } } }` to follow one token. For the lowest latency the same swaps are on the Kafka topic `solana.dextrades.proto` and the [gRPC DEX trades topic](/docs/grpc/solana/topics/dextrades/); filter on `ProtocolName` `amm` in the consumer. ## Latest price of a token on Meteora DAMM v1 {#latest-price-of-a-token-on-meteora-dyn} `Trading.Pairs` returns the latest interval for the pool with OHLC, average price and volume already computed. `Price: { IsQuotedInUsd: true }` matters: every market publishes each interval twice, once in USD and once in the quote token. ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn" } } Market: { Protocol: { is: "amm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 60 } } } } ) { Block { Time } Token { Symbol Address } QuoteToken { Symbol } Market { Address } Price { Ohlc { Open High Low Close } Average { Mean } } Volume { Usd Base } } } } ``` This is the price **on DAMM v1**. For a token's price across every venue, weighted to its deepest market, drop the protocol filter and add `Ranking: { Position: { eq: 1 } }` as described in [most accurate token price](/docs/trading/crypto-price-api/pairs/#most-accurate-token-price). On a legacy program the two often differ, because the token's main market has usually moved elsewhere. ## Real-time price feed of a token on Meteora DAMM v1 {#realtime-price-feed-of-a-token-on-meteora-dyn} The same filter as a subscription, at one-second intervals. ```graphql subscription { Trading { Pairs( where: { Token: { Address: { is: "J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn" } } Market: { Protocol: { is: "amm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 1 } } } } ) { Block { Time } Token { Symbol } QuoteToken { Symbol } Market { Address } Price { Ohlc { Open High Low Close } } Volume { Usd } } } } ``` ## Meteora DAMM v1 OHLC API {#meteora-dyn-ohlc-api} Candles come pre-built from `Trading.Pairs`. Set `Interval.Time.Duration` in seconds: 1, 60 or 3600. ```graphql { Trading { Pairs( limit: { count: 30 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn" } } Market: { Protocol: { is: "amm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 3600 } } } } ) { Block { Time } Market { Address } QuoteToken { Symbol } Price { Ohlc { Open High Low Close } } Volume { Usd Base Quote } } } } ``` ## Top traders of a token on Meteora DAMM v1 {#get-the-top-traders-of-a-specific-token-on-meteora-dyn-dex} Ranks wallets by USD volume over the last 24 hours, one row per wallet, with the USD each bought and sold. :::note Run this as a query, not a subscription. Aggregates over WebSocket return partial results. ::: ```graphql query TopTraders($token: String) { Trading { Trades( limit: { count: 100 } orderBy: { descendingByField: "volumeUsd" } where: { Pair: { Market: { Protocol: { is: "amm" }, Network: { is: "Solana" } } Token: { Address: { is: $token } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trader { Address } volumeUsd: sum(of: AmountsInUsd_Base) bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) trades: count } } } { "token": "J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn" } ``` ## Trading volume, buy volume and sell volume {#get-trading-volume-buy-volume-sell-volume-of-a-token} Seven-day totals on DAMM v1: USD volume, the buy and sell split, trade counts and distinct wallets. Drop the `Token` filter for the whole program. ```graphql { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "amm" }, Network: { is: "Solana" } } Token: { Address: { is: "J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) traders: count(distinct: Trader_Address) } } } ``` ## Liquidity of a Meteora DAMM v1 pool `DEXPools` records reserves after each swap, deposit or withdrawal it decodes. This returns the latest state of the JitoSOL/WSOL pool. :::note `DEXPools` is a realtime-only cube: it keeps roughly the last 12 hours and has no archive dataset. See [data coverage and retention](/docs/graphql/data-coverage-retention/). ::: ```graphql { Solana { DEXPools( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Pool: { Market: { MarketAddress: { is: "ERgpKaq59Nnfm9YRVAAhnq16cZhHxGcDoDWCzXbhiaNw" } } Dex: { ProgramAddress: { is: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB" } } } } ) { Block { Time } Pool { Market { MarketAddress BaseCurrency { Symbol MintAddress } QuoteCurrency { Symbol MintAddress } } Dex { ProtocolName ProtocolFamily } Base { ChangeAmount PostAmount PostAmountInUSD } Quote { ChangeAmount PostAmount PostAmountInUSD PriceInUSD } } } } } ``` Liquidity still moves on DAMM v1 through `addBalanceLiquidity` and `removeBalanceLiquidity`, though rarely. To watch it, subscribe to the same cube filtered by the program and keep rows where either reserve moved, using `any` over `Base` and `Quote`. ## Historical Meteora DAMM v1 trades The Trading cubes hold about 30 days. For older data use `DEXTradeByTokens` with `dataset: archive`, which reaches back to mid-2024. This returns monthly trade counts and JitoSOL volume on DAMM v1. :::caution Aggregate in native amounts on `archive` and `combined`, not USD Summing `Trade_Side_AmountInUSD` on the Solana `archive` and `combined` datasets does not aggregate cleanly: adding it to a grouped query shatters one row per month into many partial rows, and `combined` also returns fewer trades than `realtime` over the same window. Aggregate `Trade_Amount` instead, and take USD figures from the Trading cubes. ::: ```graphql { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { descendingByField: "Block_month" } where: { Block: { Time: { since: "2025-01-01T00:00:00Z" } } Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn" } } Dex: { ProgramAddress: { is: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB" } } } } ) { Block { month: Time(interval: { in: months, count: 1 }) } volume_jitosol: sum(of: Trade_Amount) trades: count } } } ``` ## API key, free trial and pricing Create an access token at [account.bitquery.io](https://account.bitquery.io/) and follow [how to generate a token](/docs/authorization/how-to-generate/). The free trial runs for seven days and includes 1,000 API points, 100 MCP credits and two simultaneous streams. Request rate limits by plan are 30 a minute on Personal, 90 on Pro and 240 on Scale, with custom limits on Enterprise; see [rate limits](/docs/plans/rate-limits/). Plan prices are on the [Solana DEX API product page](https://bitquery.io/products/solana-dex-api) and the [pricing page](https://bitquery.io/pricing). ## Related documentation - [Meteora DAMM v2 API](/docs/blockchain/Solana/Meteora-DAMM-v2-API/), the current AMM - [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API/) - [Meteora Dynamic Bonding Curve API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) - [Trading API overview](/docs/trading/trading-data-overview/), [Trades cube](/docs/trading/crypto-trades-api/trades-api/) and [Pairs cube](/docs/trading/crypto-price-api/pairs/) - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) - [Data coverage and retention](/docs/graphql/data-coverage-retention/) - [gRPC DEX trades topic](/docs/grpc/solana/topics/dextrades/) and [real-time Solana streams over Kafka](/docs/streams/real-time-solana-data/) - [API Authorization](/docs/authorization/how-to-use/) ## Support For technical support and questions contact our support team via telegram or create a ticket [here](https://support.bitquery.io/) --- ## Meteora DAMM v2 API: Trades, Prices, OHLC and Pools URL: https://docs.bitquery.io/docs/blockchain/Solana/Meteora-DAMM-v2-API/ Meteora DAMM v2 API on Solana: cp_amm swaps with USD price and market cap, OHLC candles, new pools, top traders, volume and pool liquidity via Bitquery. # Meteora DAMM v2 API Meteora DAMM v2 is Meteora's current constant-product AMM on Solana, built on the `cp_amm` program at `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG`. Positions are NFTs, ranges can be concentrated, and the program carries an anti-sniper fee schedule. Bitquery reads its activity into GraphQL queries, WebSocket subscriptions, Kafka and gRPC streams: swaps with USD price and market cap, new pools, prices, OHLC candles, top traders, volume and pool reserves. Every query below runs as written in the [Bitquery IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. If you arrived looking for the DAMM v2 SDK or IDL, those build and sign transactions. This page is the other half: reading what those transactions did, across every DAMM v2 pool at once. :::tip Start with the Trading API Most questions on this page are answered fastest by the [**Trading API**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns **MEV-filtered swaps with USD price, market cap and supply on every row**, across **10 chains in one API**, and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) gives pre-aggregated OHLC per pool down to one second. Filter either with `Pair: { Market: { Protocol: { is: "cp_amm" } } }` for DAMM v2. Drop to the chain-level cubes further down when you need what the Trading API does not carry: **history older than about 30 days**, pool reserves, or per-instruction detail such as pool creation. ::: :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## What is the Meteora DAMM v2 program ID on Solana? The Meteora DAMM v2 program, `cp_amm`, is deployed at `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG` on Solana mainnet, and Meteora uses the same address on devnet. Its pool authority PDA is `HLnpSz9h2S4hiLQ43rnSD9XkcUThA7B8hQMKmDaiTLcC`. ``` cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG ``` In the Trading cubes DAMM v2 is `Market.Protocol` `cp_amm`. In the Solana chain-level cubes the same rows carry `Dex.ProtocolName` `cp_amm` and `Dex.ProtocolFamily` `Meteora`. Meteora runs four trading programs on Solana, each with its own Bitquery page: | Meteora program | Program ID | Protocol name | Bitquery page | | --- | --- | --- | --- | | DAMM v2, constant-product pools with position NFTs | `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG` | `cp_amm` | This page | | DLMM, concentrated liquidity in price bins | `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo` | `lb_clmm` | [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API/) | | DAMM v1, the legacy Dynamic AMM | `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB` | `amm` | [Meteora DAMM v1 API](/docs/blockchain/Solana/Meteora-DYN-API/) | | Dynamic Bonding Curve, launches that graduate to a DAMM pool | `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` | `dynamic_bonding_curve` | [Meteora DBC API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) | DAMM v2 method names keep the IDL's snake_case spelling, so pool creation is `initialize_pool`, not `initializePool`. DLMM is the odd one out with camelCase. Rows whose method starts with `Evt`, such as `EvtSwap2` and `EvtInitializePool`, are the program's event logs emitted as inner instructions beside the real instruction; they carry no account names, so read accounts from the instruction itself. ## Does Meteora have an API? Yes, for pool-level data. Meteora publishes a free REST [DAMM v2 Data API](https://docs.meteora.ag/developer-guides/damm-v2/api-reference/overview) at `https://damm-v2.datapi.meteora.ag`, limited to 10 requests a second with no key, covering pools and pool groups, per-pool OHLCV and volume history, and protocol stats. It has no per-swap trade endpoint, no per-wallet swap history and no streaming. Bitquery reads the same activity from the chain: swaps as individual rows with the trader and a USD price, new pools the moment they are created, reserves after every liquidity change, and history back to mid-2024. | | Meteora DAMM v2 Data API | Bitquery Meteora DAMM v2 API | | --- | --- | --- | | Access | REST, no key, 10 requests a second | GraphQL, WebSocket, Kafka and gRPC with an access token; seven-day free trial | | Pools | Paginated pool list and single-pool state | New pools as they are created; reserves after each decoded swap, deposit or withdrawal | | Trades | No per-swap endpoint | Swaps as individual rows with trader, amounts, USD price, market cap and signature | | Candles and volume | Per-pool OHLCV and volume history | Pre-built candles from `Trading.Pairs`; any interval from `DEXTradeByTokens` | | Traders | Not served | Top traders, buy and sell volume per wallet, PnL | | History | Per-pool candles and volume | About 30 days on the Trading cubes, back to mid-2024 on the Solana archive | | Rate limits | 10 requests a second | 30, 90 or 240 query requests a minute by plan, custom on Enterprise; streams metered separately | ## Real-time Meteora DAMM v2 trades Stream every decoded DAMM v2 swap with the trader, both amounts, the USD price and the token's market cap and circulating supply. `Side` is the trader's own side. This is the query most integrations start from. ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "cp_amm" }, Network: { is: "Solana" } } } } ) { Block { Time } Side Price PriceInUsd Trader { Address } Amounts { Base Quote } AmountsInUsd { Base Quote } Supply { MarketCap CirculatingSupply } TransactionHeader { Hash } Pair { Market { Address Protocol } Token { Symbol Address } QuoteToken { Symbol Address } } } } } ``` Add `Pair: { Token: { Address: { is: "" } } }` to follow one token, or `AmountsInUsd: { Base: { gt: 10000 } }` to watch only large trades. The same body runs as a query with `limit`, `orderBy: { descending: Block_Time }` and a `Block: { Time: { since_relative: { minutes_ago: 10 } } }` filter. For the lowest latency the same swaps are on the Kafka topic `solana.dextrades.proto` and the [gRPC DEX trades topic](/docs/grpc/solana/topics/dextrades/); filter on `ProtocolName` `cp_amm` in the consumer. ## Latest price and market cap of a token on Meteora DAMM v2 The token examples below use MET (`METvsvVRapdj9cFLzq4Tr43xK4tAjQfwX76z3n6mWQL`), Meteora's own token, which has traded on DAMM v2 since October 2025. `Trading.Pairs` returns the latest interval for the pool with OHLC, average price, volume and market cap already computed. `Price: { IsQuotedInUsd: true }` matters: every market publishes each interval twice, once in USD and once in the quote token. ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "METvsvVRapdj9cFLzq4Tr43xK4tAjQfwX76z3n6mWQL" } } Market: { Protocol: { is: "cp_amm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 60 } } } } ) { Block { Time } Token { Symbol Address } QuoteToken { Symbol } Market { Address Protocol } Price { Ohlc { Open High Low Close } Average { Mean } } Volume { Usd Base } Supply { MarketCap FullyDilutedValuationUsd } } } } ``` This gives the price **on DAMM v2**, which is what you want on a venue page. For a token's price across every venue, weighted to its most liquid market, drop the protocol filter and add `Ranking: { Position: { eq: 1 } }` as described in [most accurate token price](/docs/trading/crypto-price-api/pairs/#most-accurate-token-price). The two differ whenever a token's deepest pool sits on another program: MET itself is priced from a DLMM pool by that measure. ## Real-time price feed of a token on Meteora DAMM v2 The same filter as a subscription. Each message is one interval of the MET pool on DAMM v2 with fresh OHLC and market cap. ```graphql subscription { Trading { Pairs( where: { Token: { Address: { is: "METvsvVRapdj9cFLzq4Tr43xK4tAjQfwX76z3n6mWQL" } } Market: { Protocol: { is: "cp_amm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 1 } } } } ) { Block { Time } Token { Symbol } QuoteToken { Symbol } Market { Address } Price { Ohlc { Open High Low Close } } Volume { Usd } Supply { MarketCap } } } } ``` ## Meteora DAMM v2 OHLC API `Trading.Pairs` serves candles at any interval you ask for, so there is nothing to aggregate. Set `Interval.Time.Duration` in seconds: 1 for one-second candles, 60 for one-minute, 3600 for hourly. ```graphql { Trading { Pairs( limit: { count: 30 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "METvsvVRapdj9cFLzq4Tr43xK4tAjQfwX76z3n6mWQL" } } Market: { Protocol: { is: "cp_amm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 3600 } } } } ) { Block { Time } Market { Address } QuoteToken { Symbol } Price { Ohlc { Open High Low Close } } Volume { Usd Base Quote } } } } ``` ## Top traders of a token on Meteora DAMM v2 Ranks wallets by USD volume on DAMM v2 over the last 24 hours, one row per wallet, with the USD each bought and sold. `Trading.Trades` reports `Side` from the trader's point of view, so the split needs no field gymnastics. :::note Run this as a query, not a subscription. Aggregates over WebSocket return partial results. ::: ```graphql query TopTraders($token: String) { Trading { Trades( limit: { count: 100 } orderBy: { descendingByField: "volumeUsd" } where: { Pair: { Market: { Protocol: { is: "cp_amm" }, Network: { is: "Solana" } } Token: { Address: { is: $token } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trader { Address } volumeUsd: sum(of: AmountsInUsd_Base) bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) trades: count } } } { "token": "METvsvVRapdj9cFLzq4Tr43xK4tAjQfwX76z3n6mWQL" } ``` Subtracting `bought` from `sold` gives a rough realised PnL for the window. The [wallet PnL guide](/docs/trading/crypto-trades-api/wallet-pnl/) covers the full method. ## Trading volume, buy volume and sell volume on Meteora DAMM v2 Seven-day totals for MET on DAMM v2: USD volume, the buy and sell split, trade counts and the number of distinct wallets. Change `days_ago` for other windows, up to the roughly 30-day Trading window. ```graphql { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "cp_amm" }, Network: { is: "Solana" } } Token: { Address: { is: "METvsvVRapdj9cFLzq4Tr43xK4tAjQfwX76z3n6mWQL" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) traders: count(distinct: Trader_Address) } } } ``` Drop the `Token` filter to get the same totals for the whole DAMM v2 program. ## New Meteora DAMM v2 pools in real time Pool creation is per-instruction detail, so this one uses the chain-level `Instructions` cube. DAMM v2 creates pools through three instructions: `initialize_pool_with_dynamic_config` carries most of the traffic, with `initialize_pool` and `initialize_customizable_pool` behind it. Match all three. `Program.AccountNames` names each entry of `Instruction.Accounts` in order: `creator` and `payer` are the wallets, `pool` is the new pool address, `token_a_mint` and `token_b_mint` the pair, `token_a_vault` and `token_b_vault` the reserves, and `position_nft_mint` the NFT minted for the creator's opening position. :::note Filter the instructions, not the `EvtInitializePool` event. The event fires once per pool as well, but its row carries a single account and an empty `AccountNames` list, so you cannot read the mints or vaults off it. ::: ```graphql subscription { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG" } Method: { in: [ "initialize_pool" "initialize_pool_with_dynamic_config" "initialize_customizable_pool" ] } } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Method Name } } Transaction { Signature Signer } } } } ``` Swap `subscription` for a query and add `Block: { Time: { since_relative: { hours_ago: 24 } } }` with `limit` to list the day's new pools instead of waiting for the next one. ## Liquidity of a Meteora DAMM v2 pool `DEXPools` records a pool's reserves after each swap, deposit or withdrawal it decodes. `Base.PostAmount` and `Quote.PostAmount` are the balances after the event, `PostAmountInUSD` their USD value, and `ChangeAmount` the signed change that event caused. This returns the latest state of the MET/USDC pool. :::note `DEXPools` is a realtime-only cube: it keeps roughly the last 12 hours and has no archive dataset, so use it for current reserves and live liquidity events rather than TVL history. See [data coverage and retention](/docs/graphql/data-coverage-retention/). ::: ```graphql { Solana { DEXPools( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Pool: { Market: { MarketAddress: { is: "BnztueWcXv93mgW7yJe8WYpnCxpz34nujPhfjQT6SLu1" } } Dex: { ProgramAddress: { is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG" } } } } ) { Block { Time } Pool { Market { MarketAddress BaseCurrency { Symbol MintAddress } QuoteCurrency { Symbol MintAddress } } Dex { ProtocolName ProtocolFamily } Base { ChangeAmount PostAmount PostAmountInUSD } Quote { ChangeAmount PostAmount PostAmountInUSD PriceInUSD } } } } } ``` To stream liquidity changes across all DAMM v2 pools, subscribe to the same cube and keep rows where either reserve moved, using `any` over `Base` and `Quote`. ## Historical Meteora DAMM v2 trades The Trading cubes hold about 30 days. For anything older, use the chain-level `DEXTradeByTokens` cube with `dataset: archive`, which reaches back to mid-2024. This returns monthly trade counts and volume in MET for the token on DAMM v2 since it started trading. :::caution Aggregate in native amounts on `archive` and `combined`, not USD Summing `Trade_Side_AmountInUSD` on the Solana `archive` and `combined` datasets does not aggregate cleanly: adding it to a grouped query shatters one row per month into hundreds of partial rows, and `combined` also returns fewer trades than `realtime` over the same window. Aggregate `Trade_Amount` instead, and take USD figures from the Trading cubes, where every row carries a vetted USD price. ::: ```graphql { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { descendingByField: "Block_month" } where: { Block: { Time: { since: "2025-10-01T00:00:00Z" } } Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "METvsvVRapdj9cFLzq4Tr43xK4tAjQfwX76z3n6mWQL" } } Dex: { ProgramAddress: { is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG" } } } } ) { Block { month: Time(interval: { in: months, count: 1 }) } volume_met: sum(of: Trade_Amount) trades: count } } } ``` The chain-level cubes also carry per-swap detail the Trading cubes leave out, such as the exact instruction that produced a swap and the token accounts on each side. The [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) covers those fields, and [DEXTrades vs DEXTradeByTokens vs Trading.Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades/) explains when each one is the right tool. ## Locked liquidity on Meteora DAMM v2 Liquidity providers can lock a DAMM v2 position, with a vesting schedule or permanently. A lock is the on-chain answer to "can this liquidity be pulled?". `EvtLockPosition` carries the `pool`, `position`, `owner`, the `vesting` account, the `cliff_point` (Unix time when the first part unlocks), `period_frequency` and `number_of_period`. `EvtPermanentLockPosition` marks liquidity that can never be withdrawn. The liquidity amounts on these events are 128-bit integers that come back empty; use the `pool` and `position` to look up the position's size. [Run it in the IDE ➤](https://ide.bitquery.io/Meteora-DAMM-v2-liquidity-locks) ```graphql query DammV2LiquidityLocks { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}, Method: {in: ["EvtLockPosition", "EvtPermanentLockPosition"]}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Method Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` To check one pool, add `Arguments: {includes: {Name: {is: "pool"}, Value: {Address: {is: ""}}}}` to the `Program` filter. ## Position fee claims on Meteora DAMM v2 `EvtClaimPositionFee` logs every fee claim by a liquidity provider: the `pool`, `position`, `owner` and the amounts claimed of each pool token, `fee_a_claimed` and `fee_b_claimed`, in each token's smallest unit. This query keeps claims that paid out token B. [Run it in the IDE ➤](https://ide.bitquery.io/Meteora-DAMM-v2-position-fee-claims) ```graphql query DammV2PositionFeeClaims { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}, Method: {in: ["EvtClaimPositionFee"]}, Arguments: {includes: {Name: {is: "fee_b_claimed"}, Value: {BigInteger: {gt: "0"}}}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Method Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` ## API key, free trial and pricing Create an access token at [account.bitquery.io](https://account.bitquery.io/) and follow [how to generate a token](/docs/authorization/how-to-generate/). The free trial runs for seven days and includes 1,000 API points, 100 MCP credits and two simultaneous streams. Request rate limits by plan are 30 a minute on Personal, 90 on Pro and 240 on Scale, with custom limits on Enterprise; see [rate limits](/docs/plans/rate-limits/). Points and streams are explained on [how billing works](/docs/plans/how-billing-works/), and plan prices are on the [Solana DEX API product page](https://bitquery.io/products/solana-dex-api) and the [pricing page](https://bitquery.io/pricing). Kafka access is a separate line item from the GraphQL plan. ## Related documentation - [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API/) - [Meteora DAMM v1 API](/docs/blockchain/Solana/Meteora-DYN-API/) - [Meteora Dynamic Bonding Curve API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) - [Trading API overview](/docs/trading/trading-data-overview/), [Trades cube](/docs/trading/crypto-trades-api/trades-api/) and [Pairs cube](/docs/trading/crypto-price-api/pairs/) - [Wallet PnL](/docs/trading/crypto-trades-api/wallet-pnl/) - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) - [DEXTrades vs DEXTradeByTokens vs Trading.Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades/) - [Data coverage and retention](/docs/graphql/data-coverage-retention/) - [gRPC DEX trades topic](/docs/grpc/solana/topics/dextrades/) and [real-time Solana streams over Kafka](/docs/streams/real-time-solana-data/) - [Schema overview](/docs/schema/schema-intro/) - [API Authorization](/docs/authorization/how-to-use/) ## Support For technical support and questions contact our support team via telegram or create a ticket [here](https://support.bitquery.io/) --- ## Meteora DBC API: Dynamic Bonding Curve Launches, Trades, Graduations URL: https://docs.bitquery.io/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/ Meteora DBC API (Dynamic Bonding Curve): stream DBC launches, curve trades with USD price and market cap, graduations to DAMM, top traders and migrations. # Meteora DBC API: Dynamic Bonding Curve Launches, Trades, Graduations The Meteora Dynamic Bonding Curve (DBC) is Meteora's launch program on Solana, at `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN`. A team configures a curve, buyers trade against it, and once the quote threshold is met the token graduates into a DAMM pool. Launchpads including Jupiter Studio and Believe run on it. Bitquery reads that whole lifecycle: new launches, every curve trade with a USD price and market cap, graduations, top traders and migrations, over GraphQL, WebSocket, Kafka and gRPC. Meteora publishes REST data APIs for DLMM, DAMM v1 and DAMM v2, but **none for the Dynamic Bonding Curve**. There is an SDK and an IDL for building transactions, and nothing that serves launches, trades or curve state. That gap is what this page fills. :::tip Start with the Trading API DBC tokens live and die in hours, so the fastest path is the [**Trading API**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns **MEV-filtered curve trades with USD price, market cap and supply on every row**, and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) gives OHLC and market cap per curve down to one second. Filter either with `Market: { Protocol: { is: "dynamic_bonding_curve" } }`. Use the chain-level `Instructions` cube further down for the events the Trading cubes do not model: launches, graduations and migration checks. ::: :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## What is the Meteora DBC program ID on Solana? The Dynamic Bonding Curve program is `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` on Solana mainnet, and Meteora uses the same address on devnet. Its pool authority PDA is `FhVo3mqL8PW5pH5U2CN4XE33DokiyZnUwuGpH2hmHLuM`. ``` dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN ``` In the Trading cubes DBC is `Market.Protocol` `dynamic_bonding_curve`. In the Solana chain-level cubes the rows carry `Dex.ProtocolName` `dynamic_bonding_curve` and `Dex.ProtocolFamily` `Meteora`. DBC method names keep the IDL's snake_case spelling. Rows whose method starts with `Evt`, such as `EvtSwap` and `EvtCurveComplete`, are event logs emitted beside the real instruction. Meteora runs four trading programs on Solana, each with its own Bitquery page: | Meteora program | Program ID | Protocol name | Bitquery page | | --- | --- | --- | --- | | Dynamic Bonding Curve, launches that graduate to a DAMM pool | `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` | `dynamic_bonding_curve` | This page | | DAMM v2, constant-product pools with position NFTs | `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG` | `cp_amm` | [Meteora DAMM v2 API](/docs/blockchain/Solana/Meteora-DAMM-v2-API/) | | DLMM, concentrated liquidity in price bins | `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo` | `lb_clmm` | [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API/) | | DAMM v1, the legacy Dynamic AMM | `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB` | `amm` | [Meteora DAMM v1 API](/docs/blockchain/Solana/Meteora-DYN-API/) | ## Picking an example token Every query below that takes a mint uses a placeholder, because a bonding curve that is busy this hour is usually empty tomorrow. Run this first and paste one of the mints it returns into the examples. ```graphql { Trading { Trades( limit: { count: 10 } orderBy: { descendingByField: "usd" } where: { Pair: { Market: { Protocol: { is: "dynamic_bonding_curve" } Network: { is: "Solana" } } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } ) { Pair { Token { Symbol Address } QuoteToken { Symbol } Market { Address } } usd: sum(of: AmountsInUsd_Base) trades: count } } } ``` `Pair.Token.Address` is the mint and `Pair.Market.Address` the curve. ## Meteora DBC trades in real time {#meteora-dbc-trades-in-real-time} Stream every decoded curve trade with the trader, both amounts, the USD price and the token's market cap. This one subscription covers all DBC launches at once, so it is the usual starting point for launch bots and screeners. ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "dynamic_bonding_curve" } Network: { is: "Solana" } } } } ) { Block { Time } Side Price PriceInUsd Trader { Address } Amounts { Base Quote } AmountsInUsd { Base Quote } Supply { MarketCap CirculatingSupply TotalSupply } TransactionHeader { Hash FeePayer } Pair { Market { Address Protocol } Token { Symbol Name Address } QuoteToken { Symbol Address } } } } } ``` Add `AmountsInUsd: { Base: { gt: 1000 } }` to watch only meaningful size, or `Pair: { Token: { Address: { is: "" } } }` to follow one curve. ## Market cap and price of a Meteora DBC token {#market-cap-trading-api} `Trading.Pairs` carries market cap, fully diluted valuation, supply, OHLC and volume per curve, already computed. Replace the mint with one from the [example query above](#picking-an-example-token). `Price: { IsQuotedInUsd: true }` matters: every market publishes each interval twice, once in USD and once in the quote token. DBC curves are quoted in SOL, USDC, JUP and other tokens, so without that filter you may read a price in the wrong unit. ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "" } } Market: { Protocol: { is: "dynamic_bonding_curve" } Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 60 } } } } ) { Block { Time } Token { Symbol Name Address } QuoteToken { Symbol } Market { Address } Price { Ohlc { Open High Low Close } Average { Mean } } Volume { Usd Base } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } } } } ``` ### Stream Meteora DBC tokens above a market cap threshold The screener query: every DBC curve whose market cap crosses your floor, live. Change `gt` to move the threshold. ```graphql subscription { Trading { Pairs( where: { Market: { Protocol: { is: "dynamic_bonding_curve" } Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Supply: { MarketCap: { gt: 10000 } } Interval: { Time: { Duration: { eq: 60 } } } } ) { Block { Time } Token { Symbol Name Address } QuoteToken { Symbol } Market { Address } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } Price { Ohlc { Close } } Volume { Usd } } } } ``` ## Meteora DBC OHLC API {#meteora-dbc-ohlc-api} `Trading.Pairs` serves candles at whatever interval you ask for, so there is nothing to aggregate. Set `Interval.Time.Duration` in seconds: 1 for one-second candles, 60 for one-minute. One-second candles matter on a bonding curve, where a token's whole life can be shorter than an hour. ```graphql { Trading { Pairs( limit: { count: 30 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "" } } Market: { Protocol: { is: "dynamic_bonding_curve" } Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 1 } } } } ) { Block { Time } Market { Address } QuoteToken { Symbol } Price { Ohlc { Open High Low Close } } Volume { Usd Base } } } } ``` ## Top traders of a Meteora DBC token {#get-the-top-traders-of-a-specific-token-on-meteora-dbc} Ranks wallets on one curve by USD volume, one row per wallet, with the USD each bought and sold and a realised PnL for the window. `Trading.Trades` reports `Side` from the trader's own point of view, so no field gymnastics are needed. :::note Run this as a query, not a subscription. Aggregates over WebSocket return partial results. ::: ```graphql query TopTraders($token: String) { Trading { Trades( limit: { count: 100 } orderBy: { descendingByField: "pnl" } where: { Pair: { Market: { Protocol: { is: "dynamic_bonding_curve" } Network: { is: "Solana" } } Token: { Address: { is: $token } } } } ) { Trader { Address } bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) pnl: calculate(expression: "$sold - $bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) volumeUsd: sum(of: AmountsInUsd_Base) } } } { "token": "" } ``` `pnl` here is realised in the window only: a wallet still holding its bag shows a negative number. The [wallet PnL guide](/docs/trading/crypto-trades-api/wallet-pnl/) covers unrealised positions. ## Track new Meteora DBC launches {#track-latest-created-pools-on-meteora-dbc} Launches are per-instruction detail, so this uses the chain-level `Instructions` cube. A curve is created by one of two instructions, and **you need both**: `initialize_virtual_pool_with_spl_token` for standard SPL tokens and `initialize_virtual_pool_with_token2022` for Token-2022 mints. Token-2022 launches are a large minority of DBC traffic, so filtering only the SPL variant silently hides a third of new tokens. `Program.AccountNames` names each entry of `Instruction.Accounts` in order: `base_mint` is the new token, `quote_mint` the token the curve is priced in, `pool` the curve address, `creator` the launching wallet, and `base_vault` and `quote_vault` the reserves. ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { in: [ "initialize_virtual_pool_with_spl_token" "initialize_virtual_pool_with_token2022" ] } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Method Name } } Transaction { Signature Signer FeePayer } } } } ``` ## Track Meteora DBC graduations {#track-latest-migrated-meteora-dbc-tokens} When a curve completes, a keeper migrates the liquidity into a DAMM pool. `migration_damm_v2` is the instruction in use today; `migrate_meteora_damm` is the older path into DAMM v1 and still appears in historical data, so keep both when querying the archive. ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { in: ["migration_damm_v2", "migrate_meteora_damm"] } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Method Name } } Transaction { Signature Signer } } } } ``` Meteora runs the migration keepers itself, so the signer is usually a Meteora address rather than the token creator. Graduation thresholds are set per curve config; Meteora's published keeper `Asi5DTGEeiso6k7ya6ndDabEZ7DRCgfTpCBLPH5E3aQs` handles configs with a threshold of 10 SOL, 750 USDC or 1500 JUP. ## Track migrations across DBC, LetsBonk.fun, Raydium LaunchLab, Boop.fun and Moonit {#track-meteora-dbc-letsbonkfun-raydium-launchlab-boopfun-and-moonit-token-migrations-in-a-single-subscription} One subscription covering graduations on five launchpads. Each branch matches that program's own migration method, and the LetsBonk.fun branch is identified by its platform config address appearing in the accounts of a Raydium LaunchLab migration. ```graphql subscription { Solana { Instructions( where: { any: [ { Instruction: { Program: { Address: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } Method: { is: "initialize_v2" } } } } { Instruction: { Program: { Address: { is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4" } Method: { is: "graduate" } } } } { Instruction: { Program: { Address: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } Method: { is: "migrateFunds" } } } } { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { in: ["migrate_meteora_damm", "migration_damm_v2"] } } } } { Instruction: { Program: { Address: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } Method: { in: ["migrate_to_amm", "migrate_to_cpswap"] } } Accounts: { includes: { Address: { is: "FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1" } } } } } ] Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Method Name } } Transaction { Signature Signer } } } } ``` Read the program address on each row to tell the launchpads apart: `dbcij3…` is Meteora DBC, `LanMV9…` is Raydium LaunchLab, `boop8h…` is Boop.fun, `MoonCV…` is Moonit, and a LaunchLab row carrying `FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1` in its accounts is a LetsBonk.fun graduation. ## Check whether a list of tokens has graduated from Meteora DBC {#check-if-the-list-of-tokens-has-migrated-from-meteora-dbc} Pass up to a few hundred mints and get back a row for each one that has migrated. Tokens with no row have not graduated. Add `Block: { Time: { since_relative: { days_ago: 7 } } }` to bound the scan. ```graphql query MyQuery($tokenAddresses: [String!]) { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { in: ["migration_damm_v2", "migrate_meteora_damm"] } } Accounts: { includes: { Address: { in: $tokenAddresses } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Address Token { Mint } } Program { AccountNames Method } } Transaction { Signature } } } } { "tokenAddresses": ["", "", ""] } ``` ## Latest price of a token on Meteora DBC {#latest-price-of-a-token-on-meteora-dbc} If you want a single price rather than a candle, read the last trade from `Trading.Trades`. `PriceInUsd` is the USD price of that print and `Supply.MarketCap` the market cap at that moment. ```graphql { Trading { Trades( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Pair: { Market: { Protocol: { is: "dynamic_bonding_curve" } Network: { is: "Solana" } } Token: { Address: { is: "" } } } } ) { Block { Time } Price PriceInUsd Side Supply { MarketCap } Pair { Token { Symbol } QuoteToken { Symbol } Market { Address } } } } } ``` ## Raw curve trades and history The chain-level cubes carry per-swap detail the Trading cubes leave out, such as the exact instruction behind a trade and the token accounts on each side. `Solana.DEXTrades` keeps roughly 12 hours on `realtime`, and individual trades are also on `archive` and `combined`, being backfilled toward 2024, with a required time or slot bound. `Solana.DEXTradeByTokens` keeps about 7 days on `realtime` and reaches back to mid-2024 on `archive`. For bulk history, use Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signature Signer } Trade { Dex { ProgramAddress ProtocolName ProtocolFamily } Market { MarketAddress } Buy { Currency { Name Symbol MintAddress } Amount AmountInUSD Account { Address Owner } Price PriceInUSD } Sell { Currency { Name Symbol MintAddress } Amount AmountInUSD Account { Address Owner } Price PriceInUSD } } } } } ``` :::caution Aggregate in native amounts on `archive` and `combined`, not USD Summing `Trade_Side_AmountInUSD` on the Solana `archive` and `combined` datasets does not aggregate cleanly: adding it to a grouped query shatters one row into many partial rows, and `combined` also returns fewer trades than `realtime` over the same window. Aggregate `Trade_Amount` instead, and take USD figures from the Trading cubes, where every row carries a vetted USD price. ::: ## API key, free trial and pricing Create an access token at [account.bitquery.io](https://account.bitquery.io/) and follow [how to generate a token](/docs/authorization/how-to-generate/). The free trial runs for seven days and includes 1,000 API points, 100 MCP credits and two simultaneous streams. Request rate limits by plan are 30 a minute on Personal, 90 on Pro and 240 on Scale, with custom limits on Enterprise; see [rate limits](/docs/plans/rate-limits/). Points and streams are explained on [how billing works](/docs/plans/how-billing-works/), and plan prices are on the [Solana DEX API product page](https://bitquery.io/products/solana-dex-api) and the [pricing page](https://bitquery.io/pricing). ## Related documentation - [Meteora DAMM v2 API](/docs/blockchain/Solana/Meteora-DAMM-v2-API/), where graduated DBC tokens land - [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API/) - [Meteora DAMM v1 API](/docs/blockchain/Solana/Meteora-DYN-API/) - [Jupiter Studio API](/docs/blockchain/Solana/jupiter-studio-api/) and [Believe API](/docs/blockchain/Solana/Believe-API/), launchpads built on DBC - [Trading API overview](/docs/trading/trading-data-overview/), [Trades cube](/docs/trading/crypto-trades-api/trades-api/) and [Pairs cube](/docs/trading/crypto-price-api/pairs/) - [Wallet PnL](/docs/trading/crypto-trades-api/wallet-pnl/) - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) - [Data coverage and retention](/docs/graphql/data-coverage-retention/) - [gRPC DEX trades topic](/docs/grpc/solana/topics/dextrades/) and [real-time Solana streams over Kafka](/docs/streams/real-time-solana-data/) - [API Authorization](/docs/authorization/how-to-use/) ## Support For technical support and questions contact our support team via telegram or create a ticket [here](https://support.bitquery.io/) --- ## Meteora DLMM API: Trades, Pools, Prices & OHLC on Solana URL: https://docs.bitquery.io/docs/blockchain/Solana/Meteora-DLMM-API/ Meteora DLMM API on Solana: swaps, new pools, prices, OHLC candles, top traders, volume and pool liquidity via Bitquery GraphQL, WebSocket and Kafka. # Meteora DLMM API Meteora DLMM (Dynamic Liquidity Market Maker) is Meteora's concentrated-liquidity DEX on Solana. It runs on the `lb_clmm` program at `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo`, holds liquidity in discrete price bins, and raises fees when volatility rises. Bitquery reads that program's activity into GraphQL queries, WebSocket subscriptions, Kafka and gRPC streams: live swaps, new pools, token prices, OHLC candles, pool reserves, top traders and volume. Every query below runs as written in the [Bitquery IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. Meteora's own [DLMM Data API](#does-meteora-have-an-api) serves pool state, positions and per-pool candles but has no trade feed and no streaming; the queries below cover both, with history back to mid-2024. :::tip Start with the Trading API The [**Trading API**](/docs/trading/trading-data-overview) answers most questions on this page fastest. [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns **MEV-filtered swaps with USD price, market cap and supply on every row**, across **10 chains in one API**, and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) gives pre-aggregated OHLC per DLMM pool down to one second. Drop to the chain-level cubes further down for what the Trading API does not carry: **history older than about 30 days**, pool reserves, and per-instruction detail such as pool creation. ::: :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## What is the Meteora DLMM program ID on Solana? The Meteora DLMM program, `lb_clmm`, is deployed at `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo` on Solana mainnet, and Meteora uses the same address on devnet. ``` LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo ``` Filter the Solana trade cubes with `Trade: { Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } }` and the `Instructions` cube with `Instruction: { Program: { Address: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } }`. DLMM rows carry `ProtocolName` `lb_clmm` and `ProtocolFamily` `Meteora`; in the cross-chain Trading cube the venue is `Market.Protocol` `lb_clmm`. Meteora runs four trading programs on Solana, each with its own Bitquery page: | Meteora program | Program ID | `ProtocolName` / `Market.Protocol` | Bitquery page | | --- | --- | --- | --- | | DLMM, concentrated liquidity in price bins | `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo` | `lb_clmm` | This page | | DAMM v2, constant-product pools with position NFTs | `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG` | `cp_amm` | [Meteora DAMM v2 API](/docs/blockchain/Solana/Meteora-DAMM-v2-API/) | | DAMM v1, the legacy Dynamic AMM | `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB` | `amm` | [Meteora DYN API](/docs/blockchain/Solana/Meteora-DYN-API/) | | Dynamic Bonding Curve, token launches that graduate to a DAMM pool | `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` | `dynamic_bonding_curve` | [Meteora DBC API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) | Method names follow each program's IDL as Bitquery loaded it. DLMM methods are camelCase (`initializeLbPair2`, `swapExactOut2`) even though Meteora's current IDL file spells them `initialize_lb_pair2` and `swap_exact_out2`, while DBC and DAMM v2 methods are snake_case (`initialize_virtual_pool_with_spl_token`, `claim_position_fee`), so copy the spelling from the examples on each page. Rows named `Swap`, `LbPairCreate` or `EvtSwap` are the programs' event logs, emitted as inner instructions next to the real instruction. The trade cubes decode DLMM `swap` and `swap2` instructions wherever they run, including as inner instructions of aggregator routes through Jupiter and other routers, so filter trades by program address rather than by method. ## Does Meteora have an API? Yes, for pool-level data. Meteora publishes a free REST [DLMM Data API](https://docs.meteora.ag/developer-guides/dlmm/api-reference/overview) at `https://dlmm.datapi.meteora.ag`, limited to 30 requests a second with no key, covering pools and pool groups, per-pool OHLCV and volume history, wallet portfolios, positions and PnL, limit orders and protocol stats. It has no per-swap trade endpoint, no per-wallet swap history and no streaming. The older `dlmm-api.meteora.ag` host and its `/pair/all` route have been superseded by it. Bitquery reads the same activity from the chain: swaps as individual rows, new pools the moment they are created, reserves after every liquidity change, and history back to mid-2024. | | Meteora DLMM Data API | Bitquery Meteora DLMM API | | --- | --- | --- | | Access | REST, no key, 30 requests a second | GraphQL, WebSocket, Kafka and gRPC with an access token; seven-day free trial | | Pools | Paginated pool list with search and windowed sorting; single-pool state | New pools as they are created; reserves after each decoded swap, deposit or withdrawal | | Trades | No per-swap endpoint | Swaps as individual rows with trader, amounts, price, USD value and signature | | Candles and volume | Per-pool OHLCV and volume history | OHLC at any interval from `DEXTradeByTokens`; pre-built candles from `Trading.Pairs` | | Traders | Portfolio, positions and limit orders per wallet | Top traders, buy and sell volume per wallet, PnL from `Trading.Trades` | | History | Per-pool candles and volume; depth not stated in the reference | `DEXTradeByTokens` back to mid-2024 on the `archive` dataset; realtime cubes hold hours to days | | Rate limits | 30 requests a second | 30, 90 or 240 query requests a minute by plan, custom on Enterprise; streams are metered by stream entitlements, not per request | ## Real-time Meteora DLMM trades {#subscribe-to-realtime-dlmm-trades} Stream every decoded DLMM swap with the trader, both amounts, the USD price and the token's market cap and circulating supply. `Side` is the trader's own side. This is where most integrations start. ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "lb_clmm" }, Network: { is: "Solana" } } } } ) { Block { Time } Side Price PriceInUsd Trader { Address } Amounts { Base Quote } AmountsInUsd { Base Quote } Supply { MarketCap CirculatingSupply } TransactionHeader { Hash } Pair { Market { Address Protocol } Token { Symbol Address } QuoteToken { Symbol Address } } } } } ``` Add `Pair: { Token: { Address: { is: "" } } }` to follow one token, or `AmountsInUsd: { Base: { gt: 10000 } }` to watch only large trades. The same body runs as a query with `limit`, `orderBy: { descending: Block_Time }` and a `Block: { Time: { since_relative: { minutes_ago: 10 } } }` filter. For the lowest latency the same swaps are on the Kafka topic `solana.dextrades.proto` and the [gRPC DEX trades topic](/docs/grpc/solana/topics/dextrades/); filter on `ProgramAddress` or on `ProtocolFamily` `Meteora` in the consumer. See the [Solana protobuf reference](/docs/streams/protobuf/chains/Solana-protobuf/) and [real-time Solana streams](/docs/streams/real-time-solana-data/). :::note Some DLMM swaps are not decoded yet The trade cubes decode DLMM `swap` and `swap2` instructions, including inside aggregator routes through Jupiter and other routers. Swaps sent as `swapExactOut`, `swapExactOut2` or `swapWithPriceImpact2` do not currently produce trade rows in either the chain-level or the Trading cubes, so DLMM volume read from any cube is lower than the on-chain total. ::: ## Latest price of a token on Meteora DLMM {#latest-price-of-a-token-on-meteora-dlmm} The token examples below use TRUMP (`6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN`), which has traded on Meteora DLMM since its launch in January 2025; where a pool address is needed they use a TRUMP/USDC DLMM pool, `3C5YE97HADPDxZehYq9Cis8AXr9aNyrUsczKzE1nDbW9`. `Trading.Pairs` returns the latest interval for the pool with OHLC, average price, volume and market cap already computed. `Price: { IsQuotedInUsd: true }` matters: every market publishes each interval twice, once in USD and once in the quote token. ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Market: { Protocol: { is: "lb_clmm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 60 } } } } ) { Block { Time } Token { Symbol Address } QuoteToken { Symbol } Market { Address Protocol } Price { Ohlc { Open High Low Close } Average { Mean } } Volume { Usd Base } Supply { MarketCap FullyDilutedValuationUsd } } } } ``` This gives the price **on DLMM**, which is what you want on a venue page. For a token's price across every venue, weighted to its deepest market, drop the protocol filter and add `Ranking: { Position: { eq: 1 } }` as described in [most accurate token price](/docs/trading/crypto-price-api/pairs/#most-accurate-token-price). ## Real-time price feed of a token {#realtime-price-feed-of-a-token-on-meteora-dlmm} The same filter as a subscription, at one-second intervals. ```graphql subscription { Trading { Pairs( where: { Token: { Address: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Market: { Protocol: { is: "lb_clmm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 1 } } } } ) { Block { Time } Token { Symbol } QuoteToken { Symbol } Market { Address } Price { Ohlc { Open High Low Close } } Volume { Usd } Supply { MarketCap } } } } ``` ## Meteora DLMM OHLC API {#meteora-dlmm-ohlc-api} `Trading.Pairs` serves candles at whatever interval you ask for, so there is nothing to aggregate. Set `Interval.Time.Duration` in seconds: 1 for one-second candles, 60 for one-minute, 3600 for hourly. ```graphql { Trading { Pairs( limit: { count: 30 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Market: { Protocol: { is: "lb_clmm" }, Network: { is: "Solana" } } Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 3600 } } } } ) { Block { Time } Market { Address } QuoteToken { Symbol } Price { Ohlc { Open High Low Close } } Volume { Usd Base Quote } } } } ``` ## Top traders of a token on Meteora DLMM {#get-the-top-traders-of-a-specific-token-on-meteora-dlmm-dex} Ranks wallets by USD volume on DLMM over the last 24 hours, one row per wallet, with the USD each bought and sold. `Trading.Trades` reports `Side` from the trader's point of view, so the split needs no field gymnastics. :::note Run this as a query, not a subscription. Aggregates over WebSocket return partial results. ::: ```graphql query TopTraders($token: String) { Trading { Trades( limit: { count: 100 } orderBy: { descendingByField: "volumeUsd" } where: { Pair: { Market: { Protocol: { is: "lb_clmm" }, Network: { is: "Solana" } } Token: { Address: { is: $token } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trader { Address } volumeUsd: sum(of: AmountsInUsd_Base) bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) trades: count } } } { "token": "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } ``` Subtracting `bought` from `sold` gives a rough realised PnL for the window. The [wallet PnL guide](/docs/trading/crypto-trades-api/wallet-pnl/) covers the full method. ## Trading volume, buy volume and sell volume of a token {#get-trading-volume-buy-volume-sell-volume-of-a-token} Seven-day totals for TRUMP on DLMM: USD volume, the buy and sell split, trade counts and the number of distinct wallets. Change `days_ago` for other windows, up to the roughly 30-day Trading window. Drop the `Token` filter for the whole DLMM program. ```graphql { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "lb_clmm" }, Network: { is: "Solana" } } Token: { Address: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) traders: count(distinct: Trader_Address) } } } ``` ## Chain-level DLMM data The sections above cover trades, prices, candles, traders and volume through the Trading cubes. Three things live only in the Solana chain-level cubes: pool creation, pool reserves, and history older than the roughly 30-day Trading window. See [DEXTrades vs DEXTradeByTokens vs Trading.Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades/) for the full comparison. ### New Meteora DLMM pools in real time {#latest-pool-creation-on-meteora-dlmm} Every DLMM pool is an `LbPair` account created by one of the pool-creation instructions: `initializeLbPair2` for standard permissionless pools, `initializeCustomizablePermissionlessLbPair2` for pools with custom parameters, `initializePermissionLbPair` for permissioned launches, and the un-numbered legacy SPL-Token-only forms. This subscription emits one row per new pool. `Program.AccountNames` gives the meaning of each entry in `Instruction.Accounts` in order: the first account is the new pool address (`lbPair`), `tokenMintX` and `tokenMintY` are the two token mints, `reserveX` and `reserveY` the pool vaults, and `funder` the wallet that paid for the pool's creation. Pool creation is far less frequent than swaps, so expect this stream to stay quiet for minutes at a time. To list recent pools instead, run the same filter as a query with `Block: { Time: { since_relative: { hours_ago: 24 } } }`. You can test the subscription [in the Bitquery IDE](https://ide.bitquery.io/Track-Latest-created-pools-on-Meteora-DLMM_1). ```graphql subscription { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } Method: { in: [ "initializeLbPair2", "initializeCustomizablePermissionlessLbPair2", "initializePermissionLbPair", "initializeLbPair", "initializeCustomizablePermissionlessLbPair" ] } } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Method Name Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } Transaction { Signature Signer } } } } ``` ### Liquidity of a Meteora DLMM pool `DEXPools` records a pool's reserves after each swap, deposit or withdrawal it decodes. `Base.PostAmount` and `Quote.PostAmount` are the balances after the event, `PostAmountInUSD` their USD value, and `ChangeAmount` the signed change that event caused. :::note `DEXPools` is a realtime-only cube: it keeps roughly the last 12 hours and has no archive dataset, so use it for current reserves and live liquidity events rather than TVL history. See [data coverage and retention](/docs/graphql/data-coverage-retention/). ::: ```graphql { Solana { DEXPools( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Pool: { Market: { MarketAddress: { is: "3C5YE97HADPDxZehYq9Cis8AXr9aNyrUsczKzE1nDbW9" } } Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } } } ) { Block { Time } Pool { Market { MarketAddress BaseCurrency { Symbol MintAddress } QuoteCurrency { Symbol MintAddress } } Dex { ProtocolName ProtocolFamily } Base { ChangeAmount PostAmount PostAmountInUSD } Quote { ChangeAmount PostAmount PostAmountInUSD PriceInUSD } } } } } ``` To stream liquidity changes across all DLMM pools, subscribe to the same cube and keep rows where either reserve moved. DLMM deposits are often one-sided, so filter on `Base` or `Quote` with `any` rather than on `Base` alone. ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } } any: [ { Pool: { Base: { ChangeAmount: { ne: "0" } } } } { Pool: { Quote: { ChangeAmount: { ne: "0" } } } } ] Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signature } Pool { Market { MarketAddress BaseCurrency { Symbol MintAddress } QuoteCurrency { Symbol MintAddress } } Base { ChangeAmount PostAmount PostAmountInUSD } Quote { ChangeAmount PostAmount PostAmountInUSD PriceInUSD } } } } } ``` ### Historical Meteora DLMM trades For anything older than the Trading window, use `DEXTradeByTokens` with `dataset: archive`, which reaches back to mid-2024. This returns monthly trade counts and TRUMP volume on DLMM. :::caution Aggregate in native amounts on `archive` and `combined`, not USD Summing `Trade_Side_AmountInUSD` on the Solana `archive` and `combined` datasets does not aggregate cleanly: adding it to a grouped query shatters one row per month into many partial rows, and `combined` also returns fewer trades than `realtime` over the same window. Aggregate `Trade_Amount` instead, and take USD figures from the Trading cubes, where every row carries a vetted USD price. ::: ```graphql { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { descendingByField: "Block_month" } where: { Block: { Time: { since: "2025-01-01T00:00:00Z" } } Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } } } ) { Block { month: Time(interval: { in: months, count: 1 }) } volume_trump: sum(of: Trade_Amount) trades: count } } } ``` The chain-level cubes also carry per-swap detail the Trading cubes leave out, such as the exact instruction behind a swap and the token accounts on each side; the [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) documents those fields. ## Limit orders on Meteora DLMM Meteora DLMM pools take on-chain limit orders. `PlaceLimitOrderEvt` carries the pool (`lbPair`), the `owner`, the `limitOrder` account, the pool's `activeId` bin and `params`, a JSON object with `isAskSide` and the bins the order sits in. `CancelLimitOrderEvt` returns the cancelled `amounts` and bins; `CloseLimitOrderEvt` closes the order account. The feature is new: a few dozen orders an hour on 2026-10-26. [Run it in the IDE ➤](https://ide.bitquery.io/Meteora-DLMM-limit-orders) ```graphql query DlmmLimitOrders { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo"}, Method: {in: ["PlaceLimitOrderEvt", "CancelLimitOrderEvt", "CloseLimitOrderEvt"]}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Method Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` ## API key, free trial and pricing Create an access token at [account.bitquery.io](https://account.bitquery.io/) and follow [how to generate a token](/docs/authorization/how-to-generate/); there is no approval step. The free trial runs for seven days and includes 1,000 API points, 100 MCP credits and two simultaneous streams. Request rate limits by plan are 30 a minute on Personal, 90 on Pro and 240 on Scale, with custom limits on Enterprise; see [rate limits](/docs/plans/rate-limits/). Points and streams are explained on [how billing works](/docs/plans/how-billing-works/), and plan prices are on the [Solana DEX API product page](https://bitquery.io/products/solana-dex-api) and the [pricing page](https://bitquery.io/pricing). Kafka access is a separate line item from the GraphQL plan. ## Related documentation - [Meteora DAMM v2 API](/docs/blockchain/Solana/Meteora-DAMM-v2-API/) - [Meteora DYN API (DAMM v1)](/docs/blockchain/Solana/Meteora-DYN-API/) - [Meteora DBC API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) (Dynamic Bonding Curve launches and graduations) - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) - [Trading API overview](/docs/trading/trading-data-overview/), [Trades cube](/docs/trading/crypto-trades-api/trades-api/) and [Pairs cube](/docs/trading/crypto-price-api/pairs/) - [DEXTrades vs DEXTradeByTokens vs Trading.Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades/) - [Data coverage and retention](/docs/graphql/data-coverage-retention/) - [gRPC DEX trades topic](/docs/grpc/solana/topics/dextrades/) and [real-time Solana streams over Kafka](/docs/streams/real-time-solana-data/) - [Believe API](/docs/blockchain/Solana/Believe-API/) and [Jupiter Studio API](/docs/blockchain/Solana/jupiter-studio-api/), launchpads that trade on Meteora DBC - [Solana Token Holders API](/docs/blockchain/Solana/solana-token-holders/) - [Schema overview](/docs/schema/schema-intro/) - [API Authorization](/docs/authorization/how-to-use/) ## Support For technical support and questions contact our support team via telegram or create a ticket [here](https://support.bitquery.io/) --- ## Migrate from Bitquery API v1 to v2 URL: https://docs.bitquery.io/docs/API-Blog/migrate-v1-v2/ Migrate Bitquery GraphQL apps from API v1 to v2 covering schema changes, streaming datasets, authentication updates, and code examples. # Migrating from API v1 to v2 ## Overview V2 APIs are designed to provide real-time blockchain data without any delay. It combines both real-time and historical data. You can read more on the differences [here](https://docs.bitquery.io/v1/docs/graphql-ide/v1-and-v2) Below, you'll find key changes and instructions on how to adapt your existing v1 queries to the v2 format. ## Authentication in v1 vs v2 One of the major differences between v1 and v2 is the way API is authenticated. In v1, you use a API-KEY to authenticate your requests to `graphql.bitquery.io`. And in v2, you use OAuth token mentioned as `Bearer ory_...yourtoken` and authenticate your requests to `streaming.bitquery.io/graphql`. Read more on how to generate token [here](/docs/authorization/how-to-generate/). ## Changes in Network Specification - **v1:** Specified using a generic identifier within a function, e.g., `ethereum(network: ethereum)`. - **v2:** Now requires a more specific `network` identifier and inclusion of a `dataset`. Example: `EVM(network: eth, dataset: combined)`. **Example Conversion:** - **v1 Query:** ```graphql query MyQuery { ethereum(network: ethereum) { blocks { count } } } ``` - **v2 Query:** ```graphql query { EVM(network: eth, dataset: combined) { Blocks { count } } } ``` ## Schema and Data Access The v2 API maintains a similar schema structure but integrates new data cubes such as `balanceUpdates`, `tokenHolders`, and `DexTradeByTokens`. The ability to click-select in the schema builder is still available in v2, facilitating easier transition and query building. If you're new to v2, check more examples on: [TokenHolder APIs](/docs/blockchain/Ethereum/token-holders/token-holder-api/) [balanceUpdates](/docs/blockchain/Ethereum/balances/balance-api/) [DexTradeByTokens](/docs/blockchain/Ethereum/dextrades/token-trades-apis/) ## Smart Contract Interactions - **v1:** Data is accessed through `smartContractCalls` and `smartContractEvents`. - **v2:** Simplified to `Calls` and `Events`. ## Handling Arguments and Values One of the major differences in v2 is how arguments and their values are handled and accessed. - **v1:** Arguments and values are accessed using filters based on the argument name. ```graphql token0: any(of: argument_value, argument: { is: "token0" }) ``` - **v2:** Arguments are explicitly defined by data type, providing more structured access and clearer query definitions. ```graphql Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } ``` ## Aggregation : From v1 to v2 Let's take this query in v1, where we get total number of unique currencies traded on Ethereum on a particular day. The `count` and `sum` aggregation is available in both v1 and v2. ```graphql query MyQuery { ethereum(network: ethereum) { dexTrades(date: {is: "2024-01-01"}) { Unique_tokens_bought: count(uniq: buy_currency) Unique_tokens_sold: count(uniq: sell_currency) } } } ``` - **Date Filtering**: Instead of a separate `date` field, v2 uses `Block.Date` for date filtering. - **Field Mapping**: The `buy_currency` and `sell_currency` fields in v1 are mapped to `Trade_Buy_Currency_SmartContract` and `Trade_Sell_Currency_SmartContract` respectively in v2. ```graphql query MyQuery { EVM(network: eth, dataset: combined) { DEXTrades(where: {Block: {Date: {is: "2024-01-01"}}}) { Unique_tokens_bought:count(distinct: Trade_Buy_Currency_SmartContract) Unique_tokens_sold:count(distinct:Trade_Sell_Currency_SmartContract) } } } ``` ## Decimals & Precision In API v1, the decimal precision was low at the GraphQL layer. While the data was saved accurately with all decimals, it would lose precision when processed through GraphQL. To avoid this issue, in API v2, values are now represented as strings, allowing for exact precision up to 18 decimal places without any loss of accuracy. ## Migrating Complex Queries from v1 to v2 Let's take the below query which fetches the latest token details including USD values. ```graphql { ethereum(network: ethereum) { dexTrades( options: {desc: ["block.height", "tradeIndex"], limit: 1, offset: 0} buyCurrency: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"} ) { block { timestamp { time(format: "%Y-%m-%d %H:%M:%S") } height } tradeIndex protocol exchange { fullName } buyAmount buyCurrency { symbol } buy_amount_usd: buyAmount(in: USD) sellAmount sellCurrency { symbol } sell_amount_usd: sellAmount(in: USD) priceInUSD: expression(get: "buy_amount_usd / buyAmount") } } } ``` Now to convert this to v2, let's first tackle the filters. ``` options: {desc: ["block.height", "tradeIndex"], limit: 1, offset: 0} buyCurrency: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"} ``` In v2, the same filters would be: ``` limit: {count: 1} orderBy: {descending: Block_Number} where: {Trade: {Buy: {Currency: {SmartContract: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}}}}} ``` There is no separate filter called `options` **Notice we use `.` in v1 to access inner fields while we use `_` in v2.** Next, we select the fields in the response ```graphql { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount AmountInUSD Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } Sell { Amount AmountInUSD Buyer Currency { Name SmartContract Symbol } Seller Price PriceInUSD } } } ``` In v1, we had fields labelled as `buyCurrency`, `sellAmount` and so on but in v2 we have nested schema, where we choose ``` Buy{ Currency {} } ``` The nested schema in v2 requires accessing fields through specific paths, e.g., `Trade.Buy.Currency.SmartContract`. ## Where do I find my Bitquery API v1 key? {#where-do-i-find-my-bitquery-api-v1-key} To find your Bitquery API v1 key, log in to your [Bitquery account](https://account.bitquery.io/), navigate to [Applications](https://account.bitquery.io/user/api_v2/applications), and create a new application if needed. Then, visit the [Access Tokens](https://account.bitquery.io/user/api_v2/access_tokens) page to generate a new access token. This token serves as your API key for authentication. When creating a token, be sure to set an appropriate lifespan to avoid unnecessary interruptions or the need for frequent regeneration. ## V1 vs V2 : Data Points ![Bitquery v1 to v2 API comparison](/img/v1v2.png) --- ## Migrating from Alchemy to Bitquery URL: https://docs.bitquery.io/docs/migration/from-alchemy/ Map Alchemy Transfers, Token, and NFT API calls to Bitquery GraphQL cubes for decoded, multi-chain data. # Migrating from Alchemy to Bitquery Alchemy is node-and-enhanced-API centric; Bitquery is a decoded, multi-chain data layer queried with GraphQL. This guide maps the common enhanced-API calls. :::note Verify chain/cube coverage against the [coverage matrix](/docs/graphql/data-coverage-retention/). ::: ## Concept mapping | Alchemy | Bitquery (GraphQL) | |---|---| | `alchemy_getAssetTransfers` | `EVM { Transfers(...) }` | | Token balances / metadata | `EVM { Balances(...) }`, Currency fields | | NFT API | [NFT API](/docs/blockchain/Ethereum/nft/nft-api/) | | `eth_getLogs` (raw) | `EVM { Events(...) }` (decoded) | | Webhooks / Notify | [WebSocket subscriptions](/docs/subscriptions/websockets/) / [Kafka](/docs/streams/kafka-operations/) | | Trace/debug for internal txs | `EVM { Calls(...) }` (decoded internal calls) | ## Example: asset transfers for an address ```graphql { EVM(network: eth, dataset: combined) { Transfers( where: { Transfer: { Receiver: { is: "0x..." } } } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Amount Currency { Symbol SmartContract } Sender } Transaction { Hash } } } } ``` ## What differs - **Decoded, not raw.** Events and internal calls come decoded, so you often skip client-side log parsing. - **Multi-chain in one schema.** The same cube shape works across supported EVM chains (and Solana/Tron have parallel cubes). - **Delivery.** Real-time via WebSocket subscriptions or Kafka. gRPC (CoreCast) is available on Solana only. ## Next steps - [Getting started](/docs/start/first-query/) - [Smart contract calls](/docs/blockchain/Ethereum/calls/smartcontract/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) --- ## Migrating from GoldSky Subgraphs to Bitquery URL: https://docs.bitquery.io/docs/migration/from-goldsky/ Move from GoldSky/subgraph indexing to Bitquery's prebuilt decoded cubes — no subgraph deployment required. # Migrating from GoldSky Subgraphs to Bitquery Subgraphs require you to define a schema, write mappings, and deploy an indexer per protocol. Bitquery gives you prebuilt, decoded cross-chain cubes you query directly — no subgraph to author or operate. :::note Verify chain/cube coverage in the [coverage matrix](/docs/graphql/data-coverage-retention/). ::: ## Concept mapping | GoldSky / subgraph | Bitquery | |---|---| | Define GraphQL schema + mappings | Prebuilt cubes — no schema authoring | | Deploy & sync a subgraph | Nothing to deploy; query immediately | | Entity queries | Cube queries (`EVM { ... }`, `Solana { ... }`, `Trading { ... }`) | | Subgraph webhooks / streams | [WebSocket](/docs/subscriptions/websockets/) / [Kafka](/docs/streams/kafka-operations/) / [gRPC](/docs/grpc/solana/introduction/) (Solana only) | | Mirror / warehouse pipelines | Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore) | | Custom protocol decoding | Ask support to index a protocol's ABIs/IDL | ## Example: pair-creation events (a common subgraph use case) ```graphql { EVM(network: eth, dataset: combined) { Events( where: { Log: { Signature: { Name: { is: "PairCreated" } } } } orderBy: { descending: Block_Time } limit: { count: 100 } ) { Block { Time } Log { Signature { Name } SmartContract } Transaction { Hash } } } } ``` ## What differs - **No indexer to run.** You skip subgraph authoring, deployment, and re-syncs. - **Cross-chain in one place.** The same query shapes span supported chains. - **Rate limits & cost** are point-based rather than per-subgraph — see [How Billing Works](/docs/plans/how-billing-works/). - **Custom protocols.** If a protocol isn't decoded yet, ask support to index its ABIs/IDL. ## Next steps - [Smart contract events](/docs/blockchain/Ethereum/events/events-api/) - [How Billing Works](/docs/plans/how-billing-works/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) --- ## Migrating from Helius to Bitquery (Solana) URL: https://docs.bitquery.io/docs/migration/from-helius/ Map Helius Solana APIs — enhanced transactions, DAS, and webhooks — to Bitquery Solana cubes, Kafka, and gRPC. # Migrating from Helius to Bitquery (Solana) Both cover Solana; Bitquery adds a decoded GraphQL layer plus Kafka and gRPC streams, and cross-chain coverage in one schema. :::note Solana retention differs sharply by cube — check the [coverage matrix](/docs/graphql/data-coverage-retention/) before assuming deep history. ::: ## Concept mapping | Helius | Bitquery | |---|---| | Enhanced/parsed transactions | `Solana { Transactions / Instructions / DEXTradeByTokens }` | | Webhooks | [WebSocket subscriptions](/docs/subscriptions/websockets/), [Kafka](/docs/streams/kafka-operations/), [gRPC](/docs/grpc/solana/introduction/) | | Token / DAS metadata | Solana token + [Crypto Price API](/docs/trading/crypto-price-api/) | | pump.fun / launchpad data | [Solana launchpad pages](/docs/blockchain/Solana/) | | Low-latency streaming | [Solana gRPC (CoreCast)](/docs/grpc/solana/introduction/) | ## Example: DEX trades for a mint ```graphql { Solana(dataset: realtime) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "" } } } } orderBy: { descending: Block_Time } limit: { count: 100 } ) { Trade { Amount Price Side { Type } Dex { ProtocolName } } Transaction { Signature } Block { Time } } } } ``` ## What differs - **Query language.** Decoded GraphQL cubes rather than parsed-transaction REST responses. - **Streaming options.** WebSocket, Kafka, and gRPC — pick by latency and filtering needs. gRPC requires at least one filter. - **History.** Individual Solana trades are on `DEXTrades` with `dataset: archive` or `combined`. The archive is being enabled window by window toward 2024 and is part of the Solana history add-on. OHLCV and volume aggregates are on `DEXTradeByTokens`. For bulk history, use Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore). See the matrix. - **Note:** the API does not serve deep historical Solana *instructions by signature*. For older instruction history, ask about a [Data Store export](https://bitquery.io/datastore) or the raw [data lake](/docs/data-lake/). For new data, consume instructions in real time via Kafka or gRPC. ## Next steps - [Solana gRPC (CoreCast)](/docs/grpc/solana/introduction/) - [Solana DEX trades](/docs/blockchain/Solana/solana-dextrades/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) --- ## Migrating from Moralis to Bitquery URL: https://docs.bitquery.io/docs/migration/from-moralis/ Map common Moralis calls — token prices, transfers, balances, and holders — to Bitquery GraphQL cubes and streams. # Migrating from Moralis to Bitquery A concept map for teams moving REST-style Moralis calls to Bitquery's GraphQL cubes. Instead of one endpoint per resource, you compose a single GraphQL query against the cube you need. :::note Capability comparisons below describe Bitquery's model; verify exact coverage for your chains against the [coverage matrix](/docs/graphql/data-coverage-retention/). ::: ## Concept mapping | Moralis (REST) | Bitquery (GraphQL) | |---|---| | Get wallet token balances | `EVM { Balances(...) }` — [Balances](/docs/blockchain/Ethereum/balances/balance-api/) | | Get wallet token transfers | `EVM { Transfers(...) }` — [Transfers](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api/) | | Get token price | [Crypto Price API](/docs/trading/crypto-price-api/) | | Get token holders | `EVM { Holders(...) }` — [Holders](/docs/blockchain/Ethereum/token-holders/token-holder-api/) | | Get DEX trades / swaps | `EVM { DEXTrades / DEXTradeByTokens }` — [DEX trades](/docs/blockchain/Ethereum/dextrades/dex-api/) | | Streams (webhooks) | [WebSocket subscriptions](/docs/subscriptions/websockets/) or [Kafka](/docs/streams/kafka-operations/) | ## Example: wallet token transfers ```graphql { EVM(network: eth, dataset: combined) { Transfers( where: { Transfer: { Sender: { is: "0x..." } } } orderBy: { descending: Block_Time } limit: { count: 100 } ) { Block { Time } Transfer { Amount Currency { Symbol SmartContract } Receiver } Transaction { Hash } } } } ``` ## What differs - **One flexible query vs many endpoints.** You select exactly the fields you need across a cube, rather than calling a fixed-shape endpoint. - **Dataset selection.** Choose `realtime` / `combined` explicitly for live vs historical data — see the [coverage matrix](/docs/graphql/data-coverage-retention/). - **Streaming.** Real-time delivery is via WebSocket subscriptions or Kafka rather than webhooks. gRPC (CoreCast) is available on Solana only. ## Next steps - [Getting started](/docs/start/first-query/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) - [First query](/docs/start/first-query/) --- ## Migrating from Yellowstone gRPC to Bitquery CoreCast URL: https://docs.bitquery.io/docs/migration/from-yellowstone/ Move from Yellowstone Geyser gRPC to Bitquery's Solana CoreCast gRPC — decoded streams, filters, and auth differences. # Migrating from Yellowstone gRPC to Bitquery CoreCast If you're streaming Solana over Yellowstone Geyser gRPC, Bitquery's **CoreCast** gRPC offers a decoded stream. The mental models differ, so read this before porting a Yellowstone client. :::note CoreCast is **not** a drop-in Yellowstone replacement — the protobuf schema and semantics differ. ::: ## Key differences - **Decoded, not raw.** CoreCast delivers decoded events (DEX trades, pools, transfers) rather than raw account/transaction updates you decode yourself. - **A filter is required.** A CoreCast subscription must include at least one filter; a fully-unfiltered "everything" stream is rejected. - **Multiple tokens per stream.** A single CoreCast stream can filter on many token/account addresses at once — you don't need one stream per token. - **Auth.** Uses a Bitquery-issued credential; errors surface as gRPC status codes — `16 UNAUTHENTICATED` (bad/missing/expired credential) vs `7 PERMISSION_DENIED` (valid but not entitled). See [common errors](/docs/start/errors/#grpc-auth-errors). ## Getting started See [Solana gRPC (CoreCast)](/docs/grpc/solana/introduction/) for the connection details, then the topic pages for the decoded event shapes. ## When to choose Kafka or WebSocket instead - Need multi-chain, not just Solana? Use [Kafka](/docs/streams/kafka-operations/). - Need simple browser/server subscriptions with server-side filtering? Use [WebSocket subscriptions](/docs/subscriptions/websockets/). ## Next steps - [Solana gRPC (CoreCast)](/docs/grpc/solana/introduction/) - [Kafka Operations Cookbook](/docs/streams/kafka-operations/) - [Common errors — gRPC auth](/docs/start/errors/#grpc-auth-errors) --- ## Minara Launchpad API on Arc: Tokens, Trades and OHLCV URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/minara-launchpad-api/ Track Minara.fun launches on Circle's Arc blockchain. Verify token creators and pools, then query trades, USD prices and OHLCV with Bitquery's Trading cubes. # Minara Launchpad API on Arc: Tokens, Trades and OHLCV Track [Minara.fun](https://minara.fun/) token launches on Arc, Circle's EVM blockchain. Verify each token's launch and creator from on-chain events, then use the Trading cubes for swaps, pool prices and token candles. Use `EVM.Events` for launch records. Trading examples use `Trading.Trades`, `Trading.Pairs` and `Trading.Tokens`, with the Arc network ID `bid:arc`. :::note API access and history Run the saved queries in the Bitquery IDE, or create an [API access token](/docs/authorization/how-to-generate/) for `https://streaming.bitquery.io/graphql`. Streams use `wss://streaming.bitquery.io/graphql` with [WebSocket authorization](/docs/authorization/websocket/). Leave `dataset` unset in these examples. A 24-hour filter does not promise 24 hours of indexed Arc history. Check [data coverage and retention](/docs/graphql/data-coverage-retention/) before requesting older launches. ::: ## Contracts and launch identity Minara's [contract list](https://api.minara.fun/minara-fun/contracts?chainId=5042) and [launch strategy list](https://api.minara.fun/minara-fun/launch-strategies?chainId=5042) publish these Arc addresses. Check the lists for new deployments and retain verified older addresses in your own registry. | Contract | Arc address | | --- | --- | | Liquidity Launcher, launch entry point | `0xb6c6f77ee74af874a183bfd77dd0176d1ac91de6` | | Current InstantLaunchStrategyWithHook | `0x4d3a3f4e1a918845c2038bc064c4d250822b203e` | | Shared UERC20Factory | `0xff99d8f6c994607576eb652edcf12e04a7ebfbf6` | | Minara fee hook | `0xb6a65950534f061618b4ae102fbcbb8541a8e0cc` | | Uniswap v4 PoolManager | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | The fee hook emits `PoolRegistered`, which records the pool ID, token and creator. The token factory is shared; its `TokenCreated` event alone cannot prove that a token came from Minara. A shared PoolManager address also cannot identify one pool. ### Find recent launches Filter by Minara's verified strategy address and its `TokenLaunched` signature. Success and revert checks exclude failed launches. This feed covers the listed strategy; it does not claim every historical Minara deployment. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-latest-launches) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { Block: {Time: {since_relative: {hours_ago: 24}}} TransactionStatus: {Success: true} Call: {Success: true, Reverted: false} LogHeader: {Address: {in: ["0x4d3a3f4e1a918845c2038bc064c4d250822b203e"]}, Removed: false} Log: {Signature: {SignatureHash: {is: "3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index Data} Log {Signature {SignatureHash}} Topics {Hash} } } } ``` In the zero-based `Topics` array: - `Topics[0].Hash` is the event signature. - `Topics[1].Hash` is the pool ID. - `Topics[2].Hash` is the token address, padded to 32 bytes. - `Topics[3].Hash` is `finalPositionRecipient`, the LP position recipient. Read the creator from `PoolRegistered`. Take the final 40 hex characters of the token topic and add `0x`. Prefix that address with `bid:arc:` for Trading queries. For `Trading` pool filters, keep all 64 hex characters of the pool topic and add `0x` if absent. Pass that value as `Pool.Id`. ## Verify a token, pool and creator The sample token is `0xa163d7624da3b5d9182c50eab5b8cd247ae861bb`, named Minara. A token's name is user-supplied and does not establish ownership by the platform. | Sample field | Verified value | | --- | --- | | Launch pool ID | `0xd77a1efbc8d143b100cf2496ff970da0a616a6796886e6ba1f45e7d7e09bb150` | | Creator at launch | `0x47ba13f9cc965fc89d7c7fb2f568fe873ad31751` | | Launch transaction | `0xf4bda4c4dc4b8a28f0367abe0587aa2de369e885a8b8ce56e32ebe65df11747b` | ### Read the launch receipt Fetch the four contract/event pairs from the same successful transaction. Compare their values using the checks below. To verify another launch, replace the transaction hash with one returned by the launch feed. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-launch-receipt) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {ascending: LogHeader_Index} where: { Transaction: {Hash: {is: "0xf4bda4c4dc4b8a28f0367abe0587aa2de369e885a8b8ce56e32ebe65df11747b"}} TransactionStatus: {Success: true} Call: {Success: true, Reverted: false} LogHeader: {Removed: false} any: [ {LogHeader: {Address: {in: ["0x4d3a3f4e1a918845c2038bc064c4d250822b203e"]}}, Log: {Signature: {SignatureHash: {is: "3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4"}}}} {LogHeader: {Address: {in: ["0xff99d8f6c994607576eb652edcf12e04a7ebfbf6"]}}, Log: {Signature: {SignatureHash: {is: "4ef8284ecf42d4cd19686572ffd87f630858c82398911e776cb831de35eddbf4"}}}} {LogHeader: {Address: {in: ["0x8366a39cc670b4001a1121b8f6a443a643e40951"]}}, Log: {Signature: {SignatureHash: {is: "dd466e674ea557f56295e2d0218a125ea4b4f0f6f3307b95f85e6110838d6438"}}}} {LogHeader: {Address: {in: ["0xb6a65950534f061618b4ae102fbcbb8541a8e0cc"]}}, Log: {Signature: {SignatureHash: {is: "a5cdccdb5046ff61139bbc5a059c0de074321d78f08066766c498ac1818e7f0e"}}}} ] } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index Data} Log {Signature {SignatureHash}} Topics {Hash} } } } ``` | Event and emitter | Values that must agree | | --- | --- | | `TokenLaunched`, verified strategy | Pool ID in topic 1; token in topic 2; hook in the fifth ABI data word | | `TokenCreated`, shared factory | Token in the last 20 bytes of the first ABI data word | | `Initialize`, PoolManager | Pool ID in topic 1; currencies in topics 2 and 3 include the token; hook in the third ABI data word | | `PoolRegistered`, Minara hook | Same pool ID in topic 1 and token in topic 2; creator in topic 3 | Topic positions in this table are zero-based. For raw `LogHeader.Data`, strip an optional `0x` and split into 64-character hex words. Addresses occupy each word's final 40 hex characters. The query returns candidate events; your application must check that the transaction, token, pool and hook agree. For the sample, all four events match. The LP position recipient is `0x000000000000000000000000000000000000dead`; the creator is the separate address above. Keep Bitquery's `LogHeader.Index` and Arc RPC's `logIndex` as separate fields. Their indexes differed for this sample, while the block hash, event addresses, topics and data matched. Compare those values within the same transaction when checking an RPC receipt. An old receipt may fall outside indexed history. An empty response then calls for a coverage check; it does not disprove the launch. ### Read pool creators and fee terms Filter the fee hook for `PoolRegistered`. These records give the creator at registration. The current creator role can change later; do not treat this feed as a current-owner list. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-pool-registrations) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { Block: {Time: {since_relative: {hours_ago: 24}}} TransactionStatus: {Success: true} Call: {Success: true, Reverted: false} LogHeader: {Address: {in: ["0xb6a65950534f061618b4ae102fbcbb8541a8e0cc"]}, Removed: false} Log: {Signature: {SignatureHash: {is: "a5cdccdb5046ff61139bbc5a059c0de074321d78f08066766c498ac1818e7f0e"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index Data} Log {Signature {SignatureHash}} Topics {Hash} } } } ``` `Topics[1].Hash` is the pool ID, `Topics[2].Hash` is the token and `Topics[3].Hash` is the creator. The first two ABI data words are `platformFeeBps` and `creatorFeeBps`. Decode them as unsigned integers; divide by 100 for percent. The sample records 75 and 25 basis points, or 0.75% and 0.25%. These are pool fee terms recorded at launch. They do not measure realized revenue or all fees and taxes a swap may pay. To attribute a launch to the listed strategy, also perform the four-event check. ### Stream new launches Subscribe with the same strategy and event filters. The decoded event name may be empty, so keep the signature and raw topics. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-launch-stream) ```graphql subscription { EVM(network: arc) { Events( where: { TransactionStatus: {Success: true} Call: {Success: true, Reverted: false} LogHeader: {Address: {in: ["0x4d3a3f4e1a918845c2038bc064c4d250822b203e"]}, Removed: false} Log: {Signature: {SignatureHash: {is: "3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index Data} Log {Signature {SignatureHash}} Topics {Hash} } } } ``` Save each token ID, pool ID, launch time, transaction hash and log index. Deduplicate Bitquery events by transaction hash and `LogHeader.Index`. Check the receipt to attach a verified creator. Trading subscriptions use fixed token filters. Resubscribe when your token list changes. Keep a checkpoint and query recent events after reconnecting to recover gaps. ## Trading queries The sample token trades on more than one pool. Token-wide turnover can include those other pools; select the pool ID when you need only the Minara launch pool. ### Recent trades for a Minara token Match the token as either `Pair.Token` or `Pair.QuoteToken`. The `Uniswap` family filter covers the observed v3/v4 markets; extend it only when you verify another venue. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-recent-trades) ```graphql query { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0xa163d7624da3b5d9182c50eab5b8cd247ae861bb"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0xa163d7624da3b5d9182c50eab5b8cd247ae861bb"}}}} ] } ) { Block {Time} TransactionHeader {Hash Index} Trader {Address} Side Amounts {Base Quote} AmountsInUsd {Quote} PriceInUsd Pair { Token {Id Symbol} QuoteToken {Id Symbol} Market {Network Protocol} Pool {Address Id} } } } } ``` `Side` and `PriceInUsd` refer to `Pair.Token`. Reverse Buy/Sell when the token you follow is `Pair.QuoteToken`. `PriceInUsd` is an indexed reference price; the amount ratio gives the executed price. `Pair.Pool.Address` is the shared PoolManager on v4, so also keep `Pair.Pool.Id`. Neither the market address nor PoolManager address proves the token's launchpad. ### Stream token trades Use the same token filters over WebSocket. This stream follows indexed Uniswap trades across the sample token's pools. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-trade-stream) ```graphql subscription { Trading { Trades( where: { Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0xa163d7624da3b5d9182c50eab5b8cd247ae861bb"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0xa163d7624da3b5d9182c50eab5b8cd247ae861bb"}}}} ] } ) { Block {Time} TransactionHeader {Hash Index} Trader {Address} Side Amounts {Base Quote} AmountsInUsd {Quote} PriceInUsd Pair { Token {Id Symbol} QuoteToken {Id Symbol} Market {Network Protocol} Pool {Address Id} } } } } ``` For a watchlist, change both token `is` filters to `in` lists. Keep both pair orientations. ### Launch-pool volume, trades and traders Filter by the PoolManager address and the exact v4 pool ID. This sample selects the token as `Pair.Token`, so Buy/Sell refers to Minara token units. It measures only this pool and pair orientation. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-pool-activity) ```graphql query { Trading { Trades( where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: { Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}} Pool: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}, Id: {is: "0xd77a1efbc8d143b100cf2496ff970da0a616a6796886e6ba1f45e7d7e09bb150"}} Token: {Id: {is: "bid:arc:0xa163d7624da3b5d9182c50eab5b8cd247ae861bb"}} } } ) { Pair {Token {Id Symbol} QuoteToken {Id Symbol} Pool {Address Id}} trades: count transactions: count(distinct: TransactionHeader_Hash) traders: count(distinct: Trader_Address) volumeUsd: sum(of: AmountsInUsd_Quote) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) } } } ``` Sum `AmountsInUsd.Quote` once per trade; adding base and quote USD amounts counts the same swap twice. A transaction may contain several swaps. Trader counts refer to wallet addresses, not people. Turnover is not profit, fee revenue or net inflow. :::caution Exact totals These aggregates count indexed rows. Check the [Trading Trades field notes](/docs/trading/crypto-trades-api/trades-api/#before-you-aggregate-three-things-about-a-trades-row) for duplicate-row limits. For audited totals, fetch the underlying trades and check their identities before summing. ::: ### Latest price from the launch pool Use `Trading.Pairs` for the selected pool's latest one-minute interval. The explicit pool filter keeps this query on the launch pool even if another market becomes the token's top market. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-pool-price) ```graphql query { Trading { Pairs( limit: {count: 1} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:arc:0xa163d7624da3b5d9182c50eab5b8cd247ae861bb"}} Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}} Pool: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}, Id: {is: "0xd77a1efbc8d143b100cf2496ff970da0a616a6796886e6ba1f45e7d7e09bb150"}} Block: {Time: {since_relative: {hours_ago: 24}}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } ) { Token {Id Symbol} QuoteToken {Id Symbol} Pool {Address Id} Market {Network Protocol} Interval {Time {Start End Duration}} Price {IsQuotedInUsd Ohlc {Close}} Volume {Usd} } } } ``` Check `Interval.Time.End` for freshness. A quiet pool can return an old interval or no result within the requested window. ### One-minute token OHLCV candles `Trading.Tokens` combines indexed pools for the token. This returns up to 120 rows of one-minute intervals within the requested window; it is not limited to the launch pool. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-minara-ohlcv-candles) ```graphql query { Trading { Tokens( limit: {count: 120} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:arc:0xa163d7624da3b5d9182c50eab5b8cd247ae861bb"}, NetworkBid: {is: "bid:arc"}} Block: {Time: {since_relative: {hours_ago: 24}}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } ) { Token {Id Symbol} Interval {Time {Start End Duration}} Price {IsQuotedInUsd Ohlc {Open High Low Close}} Volume {Base Usd} } } } ``` `Volume.Usd` is quoted USD volume and `Volume.Base` is token units. Missing intervals may be absent, and the current interval can change. Resolve repeated `Token.Id` / `Interval.Time.Start` keys before plotting from oldest to newest; do not sum repeated rows. See the [Tokens field notes](/docs/trading/crypto-price-api/tokens/#field-notes). To stream candles, change `query` to `subscription`, remove `limit`, `orderBy` and the historical `Block.Time` filter, and keep the token and interval filters. ## Next steps - [Arc Launchpads API](/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/) - [Tolly Launchpad API](/docs/blockchain/arc-mainnet/tolly-launchpad-api/) - [RadarDEX Launchpad API](/docs/blockchain/arc-mainnet/radardex-launchpad-api/) - [Arc Blockchain API](/docs/blockchain/arc-mainnet/) - [Trading Trades API](/docs/trading/crypto-trades-api/trades-api/) - [Minara docs](https://minara.fun/docs) --- ## MoneyFlow Lite - Trace Crypto Fund Flows Across Blockchains URL: https://docs.bitquery.io/docs/moneyflow-lite/intro/ MoneyFlow Lite is Bitquery's lightweight fund-flow tracing tool. Enter an address, pick a blockchain and follow where the money came from and where it went, with address labels and transaction evidence. # MoneyFlow Lite MoneyFlow Lite is the lightweight version of Bitquery's [MoneyFlow](https://bitquery.io/products/moneyflow) investigation tool. It runs in the browser at [lite.bitquery.io](https://lite.bitquery.io/). You enter one address and pick a blockchain. MoneyFlow Lite draws a flow chart of the funds that entered and left that address, lists every transaction behind the chart, and labels known entities such as exchange wallets. ![MoneyFlow chart for a Bitcoin address](/img/moneyflow-lite/moneyflow-chart.jpg) ## What you can do - **Trace funds step by step.** Start at one address and extend the trace one hop at a time with [Trace In and Trace Out](/docs/moneyflow-lite/trace-in-and-trace-out). - **See who the counterparties are.** Nodes and table rows carry [address labels](/docs/moneyflow-lite/address-labels) such as `bitmex-hot` or `bitkub-deposit`. - **Inspect the evidence.** Every edge in the chart is backed by rows in the [transactions table](/docs/moneyflow-lite/transactions-table) with hashes, amounts and USD values. - **Export and share.** Generate a report, share a public link, or open the underlying [Coinpath® query](/docs/moneyflow-lite/get-api-coinpath-query) in the Bitquery IDE. ## Supported blockchains The **Blockchain** dropdown on the create page lists these networks: | Account-based | UTXO | Ledger-based | | --- | --- | --- | | Algorand, Arbitrum One, Arc, Base, BNB Smart Chain, Ethereum Mainnet, Filecoin Mainnet, Optimism (OP Mainnet), Polygon (Matic) Mainnet, Robinhood Chain, TRON Mainnet | Bitcoin Mainnet, Cardano, Dash, Dogecoin, Litecoin | Ripple XRP Ledger | The list changes as Bitquery adds chains. Check the dropdown in the app for the current set. ## Who it is for - Compliance and AML teams checking the source of funds for a deposit. - Investigators following stolen or scammed funds to an exchange. - Analysts who want a visual trace before writing a [Coinpath® API](/docs/moneyflow-lite/coinpath-explained/overview) query. ## Sign in MoneyFlow Lite uses your Bitquery account. Sign in with the same credentials you use for the [IDE](https://ide.bitquery.io/). The **Account Settings** entry in the avatar menu opens [account.bitquery.io](https://account.bitquery.io/), where you manage your profile and billing. ## Where to go next 1. [Create a MoneyFlow](/docs/moneyflow-lite/create-a-moneyflow) 2. [How to read the MoneyFlow chart](/docs/moneyflow-lite/how-to-read-the-moneyflow-chart) 3. [Trace In and Trace Out](/docs/moneyflow-lite/trace-in-and-trace-out) If you hit a problem, use the **?** icon in the top bar. It opens the Bitquery support form. You can also reach us on [Telegram](https://t.me/Bloxy_info). --- ## Monitoring Solana at Scale: Managing 100s of Addresses URL: https://docs.bitquery.io/docs/usecases/monitoring-solana-at-scale-managing-hundreds-of-addresses/ Build Monitoring Solana at Scale: Managing 100s of Addresses: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Monitoring Solana at Scale: Managing 100s of Addresses This guide demonstrates how to monitor real-time token transfers and DEX trades for hundreds of blockchain addresses efficiently using WebSockets and Streamlit. Learn to dynamically track and display key transfer and trade details in a real-time dashboard. ## Monitoring 100s of Addresses on Solana Transfers in Real-Time This section walks through how to track real-time Solana token transfers using a WebSocket connection and display sender, receiver, amount, and time in a dynamic Streamlit dashboard. ### 1. Setting Up the Environment First, ensure that you have the necessary dependencies installed: ```bash pip install streamlit pandas gql ``` Then, import the following libraries: ```python from gql import Client, gql from gql.transport.websockets import WebsocketsTransport ``` Set your Bitquery API token: ```python TOKEN = "your_bitquery_api_token" ``` ### 2. Preparing the List of Addresses Define the list of Solana addresses you want to monitor: ```python addresses = [ "7Ppgch9d4XRAygVNJP4bDkc7V6htYXGfghX4zzG9r4cH", "G6xptnrkj4bxg9H9ZyPzmAnNsGghSxZ7oBCL1KNKJUza", # Add more addresses here... ] ``` ### 3. Creating the Transfer Subscription Query The following function dynamically generates a GraphQL query to monitor token transfers for the specified addresses: ```python def create_transfer_subscription_query(): address_list = ', '.join(f'"{addr}"' for addr in addresses) return gql(f""" subscription {{ Solana {{ Transfers( where: {{ Transfer: {{ Sender: {{ Address: {{ in: [ {address_list} ] }} }} }} }} ) {{ Transfer {{ Amount AmountInUSD Receiver {{ Address }} Sender {{ Address }} Currency {{ Symbol }} }} }} }} }} """) ``` ### 4. Monitoring Real-Time Transfers The `monitor_transfers` function sets up a WebSocket connection and subscribes to real-time transfer data. The results are displayed in real-time using a Streamlit dashboard. ```python async def monitor_transfers(): transport = WebsocketsTransport( url=f"wss://streaming.bitquery.io/graphql?token={TOKEN}", headers={"Sec-WebSocket-Protocol": "graphql-transport-ws"} ) await transport.connect() print("Connected to WebSocket for transfer monitoring.") transfers_df = pd.DataFrame() # Set up Streamlit display for transfers st.title("Solana Transfer Monitoring Dashboard") table = st.empty() # Initialize an empty Streamlit table try: query = create_transfer_subscription_query() async for result in transport.subscribe(query): if result.data: print("Transfer Data:", result.data) transfer_data = pd.json_normalize(result.data['Solana']['Transfers']) # Select only the relevant fields display_data = transfer_data[[ 'Transfer.Sender.Address', 'Transfer.Receiver.Address', 'Transfer.Amount', 'Transfer.AmountInUSD', 'Transfer.Currency.Symbol' ]] transfers_df = pd.concat([transfers_df, display_data], ignore_index=True) # Update the Streamlit table with the new data with st.spinner('Updating data...'): table.dataframe(transfers_df, use_container_width=True) except Exception as e: print("Error during transfer monitoring:", e) finally: await transport.close() ``` ### 5. Running the Transfer Monitoring Dashboard To run the real-time monitoring dashboard, use the following command: ```bash streamlit run your_script.py ``` The dashboard will open in your browser, where you will see real-time updates of Solana transfers for the specified addresses. ### Output This is how it will look. ## Scaling the Monitoring - Initial tests were conducted with 50 addresses, yielding fast response times. - Increased the number of addresses to 150, and the response speed remained consistent without any noticeable delay. - Further tested with over 500 addresses, and again, no visible latency was observed. - The response time remained relatively quick even as the number of addresses increased, demonstrating the scalability and efficiency of the system. ## Monitoring Solana DEX Trades for 100s of Addresses This section explains how to monitor real-time DEXTrades on Solana, displaying buy/sell data, trade prices, and other relevant trade information for hundreds of addresses. ### 1. Setting Up the Environment Ensure that you have the necessary libraries installed: ```bash pip install streamlit pandas gql ``` Import the necessary libraries: ```python from gql import Client, gql from gql.transport.websockets import WebsocketsTransport ``` Set your Bitquery API token: ```python TOKEN = "your_bitquery_api_token" ``` ### 2. Preparing the List of Addresses Define the list of Solana addresses you want to monitor for DEX trades: ```python addresses = [ "5qrvgpvr55Eo7c5bBcwopdiQ6TpvceiRm42yjHTbtDvc", "FpCMFDFGYotvufJ7HrFHsWEiiQCGbkLCtwHiDnh7o28Q", # Add more addresses here... ] ``` ### 3. Creating the DEXTrades Subscription Query This function dynamically generates a GraphQL query to monitor DEX trades involving the specified addresses: ```python def create_dex_trades_subscription_query(): address_list = ', '.join(f'"{addr}"' for addr in addresses) return gql(f""" subscription {{ Solana {{ DEXTrades(where: {{Trade: {{Buy: {{Account: {{Address: {{in: [{address_list}]}}}}}}}}}}) {{ Trade {{ Dex {{ ProgramAddress ProtocolName }} Buy {{ Amount Account {{ Address }} Currency {{ Symbol Name }} Price }} Sell {{ Account {{ Address }} Price }} }} }} }} }} """) ``` ### 4. Monitoring Real-Time DEXTrades The following function establishes a WebSocket connection and subscribes to real-time DEXTrades, displaying the results in a Streamlit dashboard: ```python async def monitor_dex_trades(): transport = WebsocketsTransport( url=f"wss://streaming.bitquery.io/graphql?token={TOKEN}", headers={"Sec-WebSocket-Protocol": "graphql-transport-ws"}, ) await transport.connect() print("Connected to WebSocket for DEXTrades monitoring.") dex_trades_df = pd.DataFrame() # Set up Streamlit display for DEXTrades st.title("Solana DEXTrades Monitoring Dashboard") table = st.empty() # Initialize an empty Streamlit table try: query = create_dex_trades_subscription_query() async for result in transport.subscribe(query): if result.data: print("DEXTrade Data:", result.data) dex_trade_data = pd.json_normalize(result.data["Solana"]["DEXTrades"]) # Select only the relevant fields display_data = dex_trade_data[[ 'Trade.Buy.Currency.Name', 'Trade.Buy.Currency.Symbol', 'Trade.Buy.Account.Address', 'Trade.Buy.Price', 'Trade.Sell.Account.Address', 'Trade.Sell.Price', 'Trade.Dex.ProgramAddress', 'Trade.Dex.ProtocolName' ]] dex_trades_df = pd.concat([dex_trades_df, display_data], ignore_index=True) # Update the Streamlit table with the new data with st.spinner("Updating data..."): table.dataframe(dex_trades_df, use_container_width=True) except Exception as e: print("Error during DEXTrades monitoring:", e) finally: await transport.close() ``` ### 5. Running the DEXTrades Monitoring Dashboard To run the real-time DEXTrades monitoring dashboard, use the following command: ```bash streamlit run your_script.py ``` The dashboard will open in your browser, showing real-time updates for DEXTrades involving the specified addresses. --- ### Conclusion This guide demonstrates how to efficiently monitor 100s of Solana addresses in real time using WebSockets and Streamlit. You can extend this code to handle additional blockchain events or customize the displayed data based on your specific needs. --- ## Monitoring the Solana Blockchain in Real Time URL: https://docs.bitquery.io/docs/usecases/monitoring-solana-blockchain-real-time-tutorial/ Build Monitoring the Solana Blockchain in Real Time: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Monitoring the Solana Blockchain in Real Time - Easy Tutorial Monitoring blockchain activities is crucial for developers, investors, and regulatory bodies. [Bitquery](https://bitquery.io) offers the infrastructure to monitor blockchain activities effectively. In this tutorial, we'll use [Bitquery Solana real-time data](https://bitquery.io/blockchains/solana-blockchain-api) and Python to build a real-time Solana DEX monitoring dashboard. We will create a dashboard that monitors **Solana DEX trades** and **Raydium DEX trades**. Here is a step-by-step guide to build this system. The code can be found [here on GitHub](https://gist.github.com/divyasshree-BQ/84bc875bf1c3c3e9088653d5c9b5d7eb). ## Prerequisites Ensure you have Python installed and pip configured correctly. Install the required libraries: ```bash pip install asyncio pandas streamlit gql websockets ``` ## Step 1: Import Necessary Libraries The first step is to import all necessary libraries that the script requires. These include libraries for asynchronous programming, data manipulation, creating the web interface, and handling GraphQL subscriptions over WebSockets. ```python from gql import Client, gql from gql.transport.websockets import WebsocketsTransport ``` ## Step 2: Set Up the WebSocket Connection To generate a token to run the subscription, check [the guide here](/docs/authorization/how-to-generate/). Define the asynchronous function `run_subscription` to establish and manage the WebSocket connection with Bitquery. This function will handle subscribing to the real-time data streams. ```python async def run_subscription(): # Setup WebSocket connection transport = WebsocketsTransport( url="wss://streaming.bitquery.io/graphql?token=", headers={"Sec-WebSocket-Protocol": "graphql-ws"} ) # Establish the connection await transport.connect() print("Connected to WebSocket") ``` ## Step 3: Handle User Input Use Streamlit's sidebar to allow users to choose between different datasets ('General' or 'Raydium'): ```python page = st.sidebar.radio("Select Page", ["General", "Raydium"]) general_df = pd.DataFrame() raydium_df = pd.DataFrame() ``` ## Step 4: Subscribe to GraphQL Queries Based on user selection, subscribe to the respective GraphQL queries to receive real-time data. Process the incoming data and update the dashboard accordingly. ## All DEX Trades: ```python if page == "General": st.subheader("General Table") table = st.table(general_df) while True: async for result in transport.subscribe( gql(""" subscription { Solana { General: DEXTradeByTokens { Block { Time } Trade { Amount Price Currency { Symbol Name } Side { Amount Currency { Symbol Name MetadataAddress }} Dex { ProgramAddress ProtocolFamily ProtocolName } Market { MarketAddress } Order { LimitAmount LimitPrice OrderId } PriceInUSD } } } } """) ): if result.data: new_data = pd.json_normalize(result.data['Solana']['General']) general_df = pd.concat([general_df, new_data], ignore_index=True) with st.spinner('Updating data...'): table.table(general_df) ``` ## Raydium DEX Trades: ```python elif page == "Raydium": st.subheader("Raydium Table") table = st.table(raydium_df) while True: async for result in transport.subscribe( gql(""" subscription { Solana { Raydium: DEXTrades( where: {Trade: {Dex: {ProgramAddress: {is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"}}}} ) { Trade { Dex { ProgramAddress ProtocolName } Buy { Account { Address } Amount Currency { Symbol Name } PriceInUSD } Sell { Account { Address } Amount Currency { Symbol Name } PriceInUSD } } Block { Time Height } Transaction { Signature } } } } """) ): if result.data: new_data = pd.json_normalize(result.data['Solana']['Raydium']) raydium_df = pd.concat([raydium_df, new_data], ignore_index=True) with st.spinner('Updating data...'): table.table(raydium_df) ``` ## Step 5: Clean Up and Close Connection Once the subscription ends or the user closes the dashboard, ensure to properly close the WebSocket connection to free up resources. ```python finally: await transport.close() ``` ## Step 6: Run the Streamlit App Define the main entry point for your Streamlit application: ```python def main(): st.title("Solana DEX General & Raydium Data Dashboard") asyncio.run(run_subscription()) if __name__ == "__main__": main() ``` ## The Final Result --- ## Multi-Chain Trading Data Streams (Protobuf) URL: https://docs.bitquery.io/docs/streams/protobuf/kafka-trading-topics-protobuf/ Multi-Chain Trading Data Streams (Protobuf) with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. # Multi-Chain Trading Data Streams (Protobuf) Broker setup, SASL authentication, consumer groups, and general Kafka behavior are covered in **[Bitquery Kafka Streams — Understanding Concepts](/docs/streams/kafka-streaming-concepts)**. All Kafka topics documented there deliver messages in **protobuf** format (JSON data samples for inspection: **[kafka-data-sample](https://github.com/bitquery/kafka-data-sample)**). ## Multi-chain trading topics The **`trading`** namespace defines two Kafka topics. **Both use the same credentials** as your subscription: - **`trading.prices`** — Multi-chain [Price Index Streams](/docs/trading/crypto-price-api/). See the [Crypto Price API](/docs/trading/crypto-price-api/) for usage. Message structure is defined in [`market/price_index.proto`](https://github.com/bitquery/streaming_protobuf/blob/main/market/price_index.proto). `PairUpdate`, `TokenUpdate` and `CurrencyUpdate` carry a `Liquidity` message (pool reserves and USD liquidity with a `Source`), and `PairUpdate` / `TokenUpdate` carry `RankingDetail` and, on tokens, `LeadingPool` — field numbers and semantics in [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields#kafka-tradingprices). From protobuf `v2.6.8`, `PairUpdate` also carries the liquidity pool's own price as `PoolPriceUpdate` (USD) and `PoolPriceUpdateInQuoteTokens` — see [PoolPrice fields](/docs/trading/crypto-price-api/pool-price-fields#kafka-tradingprices). - **`trading.trades`** — Real-time DEX trades aligned with the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api). Message structure is defined in [`market/trades.proto`](https://github.com/bitquery/streaming_protobuf/blob/main/market/trades.proto) in [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf). ## See also - [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts) — brokers, protobuf streams, partitioning, duplicates, retention (e.g. **Proto Streams**: messages retained **4 hours**), and limitations vs GraphQL subscriptions. - Chain-prefixed protobuf topics (**`.`**, etc.) are listed under **Complete List of Topics** on that same page. Individual chain layouts are the **Chain-specific Stream** items in this sidebar (Bitcoin, EVM, Solana, TRON). --- ## NFT Analytics Dashboard - Tutorial URL: https://docs.bitquery.io/docs/usecases/nft-analytics/ Build NFT Analytics Dashboard - Tutorial: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # NFT Analytics Dashboard - Tutorial ### Marketplace Analysis Bitquery's queries can help NFT marketplace builders analyze the performance of different NFTs on various blockchain networks. By providing real-time data on transaction volume, and other key metrics, Bitquery can help builders optimize their marketplace's offerings and improve trading conditions for users. Everything used here comes from the [NFT API](https://bitquery.io/products/nft-api) — trades, metadata, holders and floor prices across 40+ chains. ## Tutorial This is a tutorial to build a NFT Dashboard using Python code that connects to the Bitquery API and retrieves data for a particular NFT on the Ethereum network. The code then displays the data on a user-friendly interface built using Python and Streamlit. ## Required Libraries The code uses the following libraries: streamlit: A Python library for building web apps and visualizations http.client: A Python library for making HTTP requests json: A Python library for working with JSON data pandas: A Python library for data manipulation and analysis ## Step by Step Code Implementation ### Importing the Required Libraries The first step in the code is to import the required libraries using the import statement: ```python ``` ### Establishing Connection with the Bitquery API Next, the code connects to the Bitquery API using the http.client library and retrieves data on NFT transactions for a specific contract on the Ethereum network using a GraphQL query. The query is passed as a JSON payload to the request() method, along with the necessary headers and API key. ```python conn = http.client.HTTPSConnection("streaming.bitquery.io") payload = json.dumps({ "query": "{\n EVM(dataset: archive) {\n DEXTrades(\n where: {Trade: {Dex: {ProtocolFamily: {is: \"OpenSea\"}}, Buy: {Currency: {SmartContract: {is: \"0x322e2741c792c1f2666d159bcc6d3a816f98d954\"}}}}}\n ) {\n Count_NFTS_bought: sum(of: Trade_Buy_Amount)\n }\n }\n}\n", "variables": "{}" }) headers = { 'Content-Type': 'application/json', "Authorization": "Bearer your_access_token_here", } conn.request("POST", "/graphql", payload, headers) res = conn.getresponse() data = res.read() resp= json.loads( data.decode("utf-8")) count_nfts_bought = resp['data']['EVM']['DEXTrades'][0]['Count_NFTS_bought'] ``` The code retrieves the count of NFTs bought from the response data and stores it in the count_nfts_bought variable. ### Displaying the Metric The code then displays the retrieved data in a Streamlit dashboard using the streamlit library. The dashboard includes a title, a header, a metric, a table, and a line chart. ```python st.title ("NFT Dashboard") st.header("Punk Evil Rabbit NFT") st.metric("Count of Punk Evil Rabbit NFTS Bought",count_nfts_bought) ``` The title() and header() methods are used to display the title and header of the dashboard, respectively. The metric() method is used to display the count of NFTs bought as a metric. ### Adding a Table This code snippet retrieves the latest DEX trades for a specific NFT token from the Ethereum blockchain using the Bitquery DEX Trades API, and displays them in a data table using the streamlit library. ```python payload_table = json.dumps({ "query": "{\n EVM(dataset: archive, network: eth) {\n buyside: DEXTrades(\n limit: {count: 10}\n orderBy: {descending: Block_Time}\n where: {Trade: {Buy: {Currency: {SmartContract: {is: \"0x322e2741c792c1f2666d159bcc6d3a816f98d954\"}}}}}\n ) {\n Block {\n Number\n Time\n }\n Transaction {\n From\n To\n Hash\n }\n Trade {\n Buy {\n Amount\n Buyer\n Currency {\n Name\n Symbol\n SmartContract\n }\n Seller\n Price\n }\n Sell {\n Amount\n Buyer\n Currency {\n Name\n SmartContract\n Symbol\n }\n Seller\n Price\n }\n }\n }\n sellside: DEXTrades(\n limit: {count: 10}\n orderBy: {descending: Block_Time}\n where: {Trade: {Buy: {Currency: {SmartContract: {is: \"0x322e2741c792c1f2666d159bcc6d3a816f98d954\"}}}}}\n ) {\n Block {\n Number\n Time\n }\n Transaction {\n From\n To\n Hash\n }\n Trade {\n Buy {\n Amount\n Buyer\n Currency {\n Name\n Symbol\n SmartContract\n }\n Seller\n Price\n }\n Sell {\n Amount\n Buyer\n Currency {\n Name\n SmartContract\n Symbol\n }\n Seller\n Price\n }\n }\n }\n }\n}\n", "variables": "{}" }) conn.request("POST", "/graphql", payload_table, headers) res1 = conn.getresponse() data1 = res1.read() resp1= json.loads( data1.decode("utf-8")) st.subheader("Latest DEX Trades") data_table= resp1['data']['EVM']['buyside'] df = pd.json_normalize(data_table) st.dataframe(df) ``` ### Adding a Chart The chart section of the code creates a line chart using the streamlit library. The chart displays the number of NFTs bought on a daily basis on the OpenSea protocol on the Ethereum blockchain. ```python ## chart payload3 = json.dumps({ "query": "{\n EVM(dataset: archive) {\n DEXTrades(\n where: {Trade: {Dex: {ProtocolFamily: {is: \"OpenSea\"}}, Buy: {Currency: {SmartContract: {is: \"0x322e2741c792c1f2666d159bcc6d3a816f98d954\"}}}}}\n ) {\n Count_NFTS_bought: sum(of: Trade_Buy_Amount)\n Block {\n Date\n }\n }\n }\n}\n", "variables": "{}" }) conn.request("POST", "/graphql", payload3, headers) res3 = conn.getresponse() data3 = res3.read() chart_data=json.loads(data3)['data']['EVM']['DEXTrades'] df_chart = pd.json_normalize(chart_data) df_chart.columns = ['Count_NFTS_bought', 'Block_Date'] # Convert the 'Count_NFTS_bought' column to integer data type df_chart['Count_NFTS_bought'] = df_chart['Count_NFTS_bought'].astype(int) df_chart['Block_Date'] = pd.to_datetime(df_chart['Block_Date']) st.subheader('Daily Metrics') st.line_chart(df_chart,x='Block_Date',y='Count_NFTS_bought') ``` #### Here's how it looks If you want to build up query from scratch you are welcome or you can use the [premade examples](https://ide.bitquery.io/explore/All%20queries) as well. ## Setting Up Subscriptions Lastly, we also have the the [“subscribe”](https://community.bitquery.io/t/how-to-subscribe-to-real-time-data-stream-using-bitquery-api-and-python-graphql-client/1431?u=divya) feature of the dApp. These functions are important as they allow us to continuously update the dApp for our users in real-time whenever a transaction of digital collectibles occurs in the marketplace. --- ## NFT Blur MarketPlace API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/nft/nft-blur-marketplace-api/ NFT Blur MarketPlace API: track Ethereum NFT trades, ownership, and metadata with Bitquery GraphQL and streams. Covers archive history and realtime data. # NFT Blur MarketPlace API The NFT Blur Marketplace API provides a wide range of data related to the BLUR NFT Marketplace. With this API, We can access data on the latest traded NFTs, buy-sell activity of specific NFT tokens, top buyers of NFTs, specific buyer statistics for NFTs, NFT loan transactions, loan history, refinancing actions and much more. ## Stream Blur trades in real time Every query on this page has a streaming equivalent: change `query` to `subscription` and drop the ordering, since a stream is already in block order. This one pushes each Blur trade as it settles. ```graphql subscription BlurTradeStream { EVM(network: eth) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "seaport_v1.4" } } } } ) { Block { Time } Transaction { Hash } Trade { Dex { ProtocolName } Buy { Buyer Amount Currency { Name SmartContract Fungible } } Sell { Seller Amount Currency { Symbol } } } } } } ``` Blur settles through Seaport, so this filter catches Blur alongside other Seaport-routed marketplaces. `Buy.Currency.Fungible` is the field that separates the NFT leg from the payment leg. ## Latest Trades on Blur The Blur Marketplace supports the [Seaport protocol](https://opensea.io/blog/articles/introducing-seaport-protocol), which can be utilize to retrieve the most recent Blur trades - [query](https://ide.bitquery.io/Latest-10-Trades-on-Blur). ```graphql query MyQuery { EVM { DEXTrades( limit: { offset: 0, count: 10 } orderBy: { descendingByField: "Block_Time" } where: { Trade: { Dex: { ProtocolName: { is: "seaport_v1.4" } } } Transaction: { To: { is: "0x39da41747a83aeE658334415666f3EF92DD0D541" } } } ) { Trade { Dex { ProtocolName } Buy { Price Seller Buyer Currency { HasURI Name Fungible SmartContract } } Sell { Price Amount Currency { Name } Buyer Seller } } Transaction { Hash } Block { Time } } } } ``` **Parameters** - `limit` : Specifies the number of results to return and the offset from where to start. - `orderBy` : Organizes the results in descending order based on the block time. - `where` : Filters results based on specific conditions. Here, it selects trades where the DEX protocol name is "seaport_v1.4" and the transaction 'To' address is set to the Blur Marketplace contract. **Returned Data** - `Trade` : Provides details about the trade including the DEX protocol name, and the buy and sell details such as price, seller, buyer, and currency information. - `Transaction` : Contains the hash of the transaction associated with the trade. - `Block` : Shows the block time when the trade occurred. ## Most Traded NFTs on Blur Marketplace We can also identify the most traded NFT on the Blur Marketplace using this API. In the following [query](https://ide.bitquery.io/Most-traded-NFT-on-Blur-marketplace), we aggregate the data based on buyers, sellers, NFTs, and trade volume, and then sort the results based on the trade count. This highlights the most active NFTs in the marketplace. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {in: "seaport_v1.4"}}}, Transaction: {To: {is: "0x39da41747a83aeE658334415666f3EF92DD0D541"}}} orderBy: {descendingByField: "count"} limit: {count: 10} ) { tradeVol: sum(of: Trade_Buy_Amount) count buyers: count(distinct: Trade_Buy_Buyer) seller: count(distinct: Trade_Buy_Seller) nfts: count(distinct: Trade_Buy_Ids) Trade { Buy { Currency { Name ProtocolName Symbol Fungible SmartContract } } } } } } ``` **Parameters** - `where` : This filters out the trades where the DEX protocol name matches "seaport_v1.4", and the transaction is directed to the Blur Marketplace contract. - `orderBy` : This arranges the results in a descending order according to the count of trades. - `limit` : This confines the number of results to the top 10 most traded NFTs. **Returned Data** - `tradeVol` : Represents the total sum of trade buy amounts. - `count` : Represents the number of trades for each NFT. - `buyers` : Displays the count of distinct buyers involved in these trades. - `sellers` : Displays the count of distinct sellers involved in these trades. - `nfts` : Shows the count of distinct NFTs involved in the trades. - `Trade` : Includes information about the trade, specifically the currency details from the buy side of the trade. ## Total Buy-Sell of an NFT Token on Blur Here, the [query](https://ide.bitquery.io/Total-buy-sell-of-an-NFT-token-onBLUR) gather total trades, trade volume, unique buyers, and sellers for a specific NFT token on Blur Marketplace - in this case, the [Nakamigos NFT token](https://explorer.bitquery.io/ethereum/token/0xd774557b647330c91bf44cfeab205095f7e6c367). ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {in: "seaport_v1.4"}}, Buy: {Currency: {Fungible: false, SmartContract: {is: "0xd774557b647330c91bf44cfeab205095f7e6c367"}}}}, Transaction: {To: {is: "0x39da41747a83aeE658334415666f3EF92DD0D541"}}} orderBy: {descendingByField: "count"} limit: {count: 10} ) { tradeVol: sum(of: Trade_Buy_Amount) count buyer: count(distinct: Trade_Buy_Buyer) seller: count(distinct: Trade_Buy_Seller) nfts: count(distinct: Trade_Buy_Ids) Trade { Buy { Currency { Name ProtocolName Symbol Fungible SmartContract } } } } } } ``` **Parameters** - `where` : 'Trade.Buy.Currency.Fungible' filters out the trades where the currency is non-fungible. 'Trade.Buy.Currency.SmartContract' sets the smart contract address to match that of the Nakamigos NFT token. **Returned Data** - `nfts` : Shows the count of distinct Nakamigos NFT tokens involved in the trades. - `Trade.Buy.Currency` : Includes information about the Nakamigos NFT token. ## Identifying Top NFT Buyers on Blur In [this](https://ide.bitquery.io/Top-buyers-of-NFTs-onBLUR) query, we fetch the top buyers on the BLUR marketplace. We aggregate based on NFTs bought, unique transactions, and then sort them based on the number of trades ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { in: "seaport_v1.4" } } Buy: { Currency: { Fungible: false } } } Transaction: { To: { is: "0x39da41747a83aeE658334415666f3EF92DD0D541" } } } orderBy: { descendingByField: "count" } limit: { count: 10 } ) { count uniq_tx: count(distinct: Transaction_Hash) Block { first_date: Time(minimum: Block_Date) last_date: Time(maximum: Block_Date) } nfts: count(distinct: Trade_Buy_Ids) difffernt_nfts: count(distinct: Trade_Buy_Currency_SmartContract) total_money_paid: sum(of: Trade_Sell_Amount) Trade { Buy { Buyer } } } } } ``` **Parameters** - `where` : 'Trade.Buy.Currency.Fungible' filter makes sure to only consider non-fungible tokens in the trades. **Returned Data** - `uniq_tx` : Represents the number of unique transactions made by each buyer. - `Block` : Shows the first and last dates of transactions made by each buyer. - `nfts` : Provides a count of unique NFTs bought by each buyer. - `difffernt_nfts` : Displays a count of different NFTs bought by each buyer. - `total_money_paid` : The total amount of money paid by each buyer for their purchases. ## Specific Buyer stats for an NFT on Blur In [this](https://ide.bitquery.io/Specific-buyer-stats-for-an-NFT-onBLUR) query, we are getting details for a specific address on Blur NFT marketplace. We are also getting the first and last trade dates for the address. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { in: "seaport_v1.4" } } Buy: { Currency: { SmartContract: { is: "0xd774557b647330c91bf44cfeab205095f7e6c367" } } Buyer: { is: "0x9ba58eea1ea9abdea25ba83603d54f6d9a01e506" } } } Transaction: { To: { is: "0x39da41747a83aeE658334415666f3EF92DD0D541" } } } orderBy: { descendingByField: "count" } limit: { count: 10 } ) { count uniq_tx: count(distinct: Transaction_Hash) Block { first_date: Time(minimum: Block_Date) last_date: Time(maximum: Block_Date) } nfts: count(distinct: Trade_Buy_Ids) Trade { Buy { Buyer Currency { Name ProtocolName Symbol Fungible SmartContract } } } } } } ``` **Parameters** - `where` : 'Trade.Buy.Buyer' filters the trades made by a specific buyer. 'Trade.Buy.Currency.SmartContract' filters to include only the trades involving a specific NFT token. **Returned Data** - `uniq_tx` : Represents the number of unique transactions made by the buyer. - `Block` : Shows the first and last dates of trades made by the buyer. - `nfts` : Provides a count of unique NFTs bought by the buyer. ## Latest Loans taken on Blur Blur uses [Blend protocol](https://www.paradigm.xyz/2023/05/blend) for NFT loans. We're can [fetch](https://ide.bitquery.io/Latest-Loans-taken-onBlur) recent loans on the BLUR market through "LoanOfferTaken" events tied to Blur : [Blend Contract](https://explorer.bitquery.io/ethereum/smart_contract/0x29469395eaf6f95920e59f858042f0e28d98a20b/events). We're using LogHeader instead of Log → SmartContract for queries due to a [delegated proxy contract](https://medium.com/coinmonks/proxy-pattern-and-upgradeable-smart-contracts-45d68d6f15da). ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "LoanOfferTaken" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where` : 'LogHeader.Address' points to the Blur Blend Contract where the loan events are recorded. 'Log.Signature.Name' sets the event name to "LoanOfferTaken" to filter for loan-taking events. **Returned Data** - `Block.Number` : Block number where the event is recorded. - `Transaction.Hash` : Transaction hash corresponding to the loan event. - `Log.SmartContract` : Provides the address of the smart contract that emitted the event. - `Log.Signature` : Shows the name and signature of the event. - `Arguments` : Details of the arguments associated with the event, gives valuable information like loan amount, borrower address, and more. ## Latest loans for specific NFT token [This](https://ide.bitquery.io/Latest-loans-for-specific-NFTtoken) query retrieves all loans linked to the [MutantApeYachtClub](https://explorer.bitquery.io/ethereum/token/0x60e4d786628fea6478f785a6d7e704777c86a7c6) collection on the BLUR market. We filter event arguments in the smart contract and sort by block time ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "LoanOfferTaken" } } } Arguments: { includes: [ { Name: { is: "collection" } Value: { Address: { is: "0x60e4d786628fea6478f785a6d7e704777c86a7c6" } } } ] } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where` : 'LogHeader.Address' points to the Blur: Blend Contract. 'Log.Signature.Name' sets the event name to "LoanOfferTaken". 'Arguments.includes' filter specifically checks for a collection argument with an Address value corresponding to the MutantApeYachtClub NFT collection. **Returned Data** Same as previous queries, this query will return details about the block, transaction, log, and arguments. By modifying the 'Arguments.includes' filter, you can track loan activities for different NFT collections on the Blur marketplace. ## Latest Loans for a specific lender Using argument filtering, [this](https://ide.bitquery.io/Latest-Loans-for-a-specificlender) query fetches the latest loans for a specific lender address. The same method can be applied to find loans for a specific borrower address - [query](https://ide.bitquery.io/Latest-Loans-for-a-specificborrower-on-Blur-marketplace). ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "LoanOfferTaken" } } } Arguments: { includes: [ { Name: { is: "lender" } Value: { Address: { is: "0xfa0e027fcb7ce300879f3729432cd505826eaabc" } } } ] } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where` : 'LogHeader.Address' directs to the Blur: Blend Contract. 'Log.Signature.Name' sets the event name to "LoanOfferTaken". 'Arguments.includes' filter looks for a lender argument with an Address value matching the specific lender's address. **Returned Data** Similar to previous queries, this query will provide details about the block, transaction, log, and arguments. ## Loans above a specific amount on the Blur NFT marketplace If we want to track loans above a specific amount on the Blur marketplace, we can use the following [query](https://ide.bitquery.io/Loans-above-a-specific-amount-on-the-Blur-NFT-marketplace). ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "LoanOfferTaken" } } } Arguments: { includes: [ { Name: { is: "loanAmount" } Value: { BigInteger: { gt: "3000000000000000000" } } } ] } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## Loan history for specific NFT ID [This](https://ide.bitquery.io/Loan-history-for-specific-NFTID) query retrives the loan history for a specific NFT ID on the BLUR market, by matching event arguments to a particular collection address and tokenId. ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "LoanOfferTaken" } } } Arguments: { includes: [ { Name: { is: "collection" } Value: { Address: { is: "0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b" } } } { Name: { is: "tokenId" }, Value: { BigInteger: { eq: "2662" } } } ] } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where` : 'LogHeader.Address' directs to the Blur: Blend Contract. 'Log.Signature.Name' sets the event name to "LoanOfferTaken". 'Arguments.includes' filter looks for collection argument matching a specific NFT collection address and tokenId argument equating to a specific NFT ID. **Returned Data** The response includes details about the block, transaction, log, and event arguments. By changing the values in 'Arguments.includes' you can query the loan history for different NFT IDs on the Blur marketplace. ## Get loan details for specific LienId The Blur's Blend protocol utilizes LienID as a primary key to track individual loan details. [This](https://ide.bitquery.io/Get-loan-details-for-specificlienId) query fetches details for a specific LienID across different events. ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "LoanOfferTaken" } } } Arguments: { includes: [ { Name: { is: "lienId" }, Value: { BigInteger: { eq: "40501" } } } ] } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where` : 'Arguments.includes' filters for the lienId argument equating to a specific LienID. **Returned Data** The response will include details about the block, transaction, log, and event arguments. By adjusting the LienID in Arguments.includes, you can fetch loan details for various LienIDs on the Blur marketplace. ## Latest Loan Refinances on Blur Refinancing in NFTs refers to securing a new loan using an NFT as collateral to repay an existing loan. The following [query](https://ide.bitquery.io/loan-refinance-on-Blur) retrieves the latest refinance events on BLUR. ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "Refinance" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** `where` : 'LogHeader.Address' sets the address to the Blur: Blend Contract. 'Log.Signature.Name' filters for the event name "Refinance". ## All Refinance loans for specific NFT To retrieve all refinance loans for a specific NFT collection, we filter Refinance event arguments in [this](https://ide.bitquery.io/All-refinance-loans-for-specificNFT-collection) query ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "Refinance" } } } Arguments: { includes: [ { Name: { is: "collection" } Value: { Address: { is: "0xed5af388653567af2f388e6224dc7c4b3241c544" } } } ] } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ## Loan Repayments For loan repayment transactions on the BLUR market, use the [following](https://ide.bitquery.io/Loan-repayment-of-blur-marketplace) query. It filters 'Repay' events and sets the smart contract address to the Blur: Blend address ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "Repay" } } } Arguments: { includes: [ { Name: { is: "lienId" }, Value: { BigInteger: { eq: "43662" } } } ] } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where` : 'LogHeader.Address' sets the address to the Blur: Blend Contract. 'Log.Signature.Name' filters for the event name "Repay". 'Arguments.includes' Filters for the "lienId" argument to match a specific LienID. **Returned Data** The response contains details about the block, transaction, log, and arguments, allowing users to track loan repayment transactions associated with the specified LienID on the Blur marketplace. ## Auction Events The 'StartAuction' event is triggered when an NFT auction starts on the Blur : [Blend Contract](https://explorer.bitquery.io/ethereum/smart_contract/0x29469395eaf6f95920e59f858042f0e28d98a20b/events). The following [query](https://ide.bitquery.io/Auction-on-blur-marketplace) monitors these events. If you want to track auctions for a specific NFT, modify the [query](https://ide.bitquery.io/Auctions-for-specific-lienID) to filter for a specific LienID in the 'Arguments' field. ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "StartAuction" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** `where` : 'LogHeader.Address' sets the address to the Blur: Blend Contract. 'Log.Signature.Name' filters for the event name "StartAuction". ## Latest Locked NFTs Buy Trades Locked NFTs are temporarily non-transferrable and can be traded or transferred after the lock period. These NFTs are often cheaper than non-locked. The following [query](https://ide.bitquery.io/Locked-NFT-bought-on-Blur-marketplace) retrieves the latest trades of locked NFTs by filtering for the 'BuyLocked' event under the Blur : [Blend Contract](https://explorer.bitquery.io/ethereum/smart_contract/0x29469395eaf6f95920e59f858042f0e28d98a20b/events). ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "BuyLocked" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** `where` : 'LogHeader.Address' sets the address to the Blur: Blend Contract. 'Log.Signature.Name' Filters for the event name "BuyLocked". ## Get Cancelled Offers On the BLUR market, the 'OfferCancelled' event initiates when an offer is withdrawn or cancelled. The following [query](https://ide.bitquery.io/Latest-Cancelled-offers-on-Blur-NFT-marketplace) fetches recent 'OfferCancelled' events under the Blur : [Blend Contract](https://explorer.bitquery.io/ethereum/smart_contract/0x29469395eaf6f95920e59f858042f0e28d98a20b/events). . ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "OfferCancelled" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where` : 'LogHeader.Address' sets the address to the Blur : Blend Contract. `Log.Signature.Name` filters for the event name "OfferCancelled". ## Get Seize Offers When a seizure event happens, control of the NFT shifts to the lender or an enforcing third party. The [query](https://ide.bitquery.io/Latest-Seized-NFTs-on-Blur-marketplace) filters transactions for the 'seize' event on the Blur : [Blend Contract](https://explorer.bitquery.io/ethereum/smart_contract/0x29469395eaf6f95920e59f858042f0e28d98a20b/events) to track these ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } Log: { Signature: { Name: { is: "Seize" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Number } Transaction { Hash } Log { SmartContract Signature { Name Signature } } Arguments { Name Index Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` **Parameters** - `where`: 'LogHeader' filters the results where the Address matches the Blur: Blend contract address. 'Log' Further filters the results where the Name of Signature matches the "Seize" event. **Returned Data** - `Log` : Information about the event log, including the smart contract that emitted the event and the event's name and signature. - `Arguments` : Details of the arguments passed in the event, including their names, indexes, types, and values. --- ## NFT Token Transfers API: ERC-721 and ERC-1155 Transfers on Ethereum URL: https://docs.bitquery.io/docs/blockchain/Ethereum/transfers/nft-token-transfer-api/ NFT transfers on Ethereum with Bitquery GraphQL: a collection's latest transfers from history, every NFT transfer as a stream, one wallet's activity, mints. # NFT Token Transfers API: ERC-721 and ERC-1155 Transfers on Ethereum NFT transfers on Ethereum live in the same `Transfers` cube as token transfers, marked by `Currency.Fungible: false` and carrying the token `Id`, the collection contract, sender, receiver and, for ERC-1155, the amount. That means one cube answers the collection question, the wallet question and the mint question, and the same filter runs as a query over history or as a live subscription. Every example runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. The worked collection is CryptoKitties, `0x06012c8cf97bead5deae237070f9587f8e7a266d`, which still changes hands a few times a day, nine years after launch. For collection-level views such as token lists and holders see the [NFT collection API](/docs/blockchain/Ethereum/nft/nft-collection-api). ## Latest transfers of one collection The `combined` dataset reaches history, so this works for a collection whether it moved a minute ago or a year ago. Saved query [here](https://ide.bitquery.io/Cryptokitties-Token-Transfers). ```graphql { EVM(dataset: combined, network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x06012c8cf97bead5deae237070f9587f8e7a266d" } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time Number } Transfer { Id Sender Receiver Currency { Name Symbol SmartContract } } Transaction { Hash } } } } ``` ## Every NFT transfer on Ethereum, live Drop the contract and keep `Fungible: false` to stream all ERC-721 and ERC-1155 transfers as blocks are indexed. Saved stream [here](https://ide.bitquery.io/ERC721-token-transfers). ```graphql subscription { EVM(network: eth) { Transfers(where: { Transfer: { Currency: { Fungible: false } } }) { Block { Time } Transfer { Id Amount Sender Receiver Currency { Name Symbol SmartContract } } Transaction { Hash } } } } ``` Add the collection contract back into the filter to stream one collection; a quiet collection can then go hours between messages, so check it with the query above first. ## One wallet's NFT activity An `any` block matches transfers where the wallet is the sender or the receiver. The example is a large BAYC holder. ```graphql { EVM(dataset: combined, network: eth) { Transfers( where: { Transfer: { Currency: { Fungible: false } } any: [ { Transfer: { Sender: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } } { Transfer: { Receiver: { is: "0x29469395eaf6f95920e59f858042f0e28d98a20b" } } } ] } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Id Sender Receiver Currency { Name SmartContract } } Transaction { Hash } } } } ``` ## Mints A mint is a transfer from the zero address; the receiver is the minter. For CryptoKitties a mint is a kitty being born. ```graphql { EVM(dataset: combined, network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x06012c8cf97bead5deae237070f9587f8e7a266d" } } Sender: { is: "0x0000000000000000000000000000000000000000" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Id Receiver } Transaction { Hash } } } } ``` ## Fields worth knowing - `Transfer.Id` is the token id; `Transfer.Amount` is 1 for ERC-721 and the quantity for ERC-1155. - `Transfer.URI` is the metadata link when the contract exposes one; fetch it yourself for the image and attributes. - `Currency.Fungible` is the ERC-721/1155 flag; `Currency.HasURI` says whether a URI exists. - `dataset: combined` on the `EVM` root joins archive and realtime; without it a query reads the realtime window only. ## Related pages - [Ethereum NFT collection API](/docs/blockchain/Ethereum/nft/nft-collection-api) - [Ethereum NFT API](/docs/blockchain/Ethereum/nft/nft-api) - [Ethereum token transfers API](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api) - [Transfers cube](/docs/cubes/transfers-cube) --- ## NFTs Tracking Across Chains URL: https://docs.bitquery.io/docs/examples/cross-chain/cross-chain-api/ NFT balances across chains: one GraphQL query with aliases returns a wallet's NFT collections and counts on BNB Chain, Ethereum, Arbitrum and Optimism. # NFTs Tracking Across Chains Check a wallet's NFT holdings on several chains in one call. GraphQL aliases let one request query several networks at once. The query below returns the NFT collections held by `0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03` on BNB Chain, Ethereum, Arbitrum and Optimism, with the number of NFTs held in each collection. Replace it with the wallet you need. It uses the [`Balances` cube](/docs/cubes/balances-cube/), which returns the current balance per collection directly. `Balances` reports how many NFTs an address holds in a collection, not the individual token IDs. For token IDs, use the [NFT ownership API](/docs/blockchain/Ethereum/nft/nft-ownership-api/). ```graphql query MyQuery { binance: EVM(network: bsc, dataset: combined) { Balances( limit: { count: 10 } orderBy: { descending: Balance_Amount } where: { Balance: { Address: { is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03" } } Currency: { Fungible: false } } ) { Currency { Fungible Symbol SmartContract Name } Balance { Address Amount(selectWhere: { gt: "0" }) } } } eth: EVM(network: eth, dataset: combined) { Balances( limit: { count: 10 } orderBy: { descending: Balance_Amount } where: { Balance: { Address: { is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03" } } Currency: { Fungible: false } } ) { Currency { Fungible Symbol SmartContract Name } Balance { Address Amount(selectWhere: { gt: "0" }) } } } arbitrum: EVM(network: arbitrum, dataset: combined) { Balances( limit: { count: 10 } orderBy: { descending: Balance_Amount } where: { Balance: { Address: { is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03" } } Currency: { Fungible: false } } ) { Currency { Fungible Symbol SmartContract Name } Balance { Address Amount(selectWhere: { gt: "0" }) } } } optimism: EVM(network: optimism, dataset: combined) { Balances( limit: { count: 10 } orderBy: { descending: Balance_Amount } where: { Balance: { Address: { is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03" } } Currency: { Fungible: false } } ) { Currency { Fungible Symbol SmartContract Name } Balance { Address Amount(selectWhere: { gt: "0" }) } } } } ``` Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account, then swap in the wallet address you need. --- ## New Pairs and New Pools on Robinhood Chain: Real-Time Listings API URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-new-pairs-pools/ Build a DexScreener or GeckoTerminal style new pairs feed for Robinhood Chain: new liquidity pools created today, a live new pools stream, first trades of new pairs, first-hour volume by DEX and Klik.finance launches. # New Pairs and New Pools on Robinhood Chain: Real-Time Listings API This page builds a **new pairs / new pools listings feed** for Robinhood Chain, the kind of list DexScreener and GeckoTerminal show on their "new pairs" tab: every liquidity pool created today, a live stream of new liquidity pools, the first trade on a new pair, and how much each new liquidity pool traded in its first hour, grouped by DEX. For the full set of Robinhood Chain APIs start at the [Robinhood Chain API overview](/docs/blockchain/robinhood/). For trending tokens, most active liquidity pools, pair lookup and token search, see the [Robinhood Chain New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending). Every example runs on `EVM(network: robinhood)` or the `Trading` cube with `bid:robinhood`, and any query becomes a WebSocket stream by changing `query` to `subscription`. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ## Where new liquidity pools come from {#sources} A new pair on Robinhood Chain shows up as one of three events. A complete listings feed reads all three: | Event | Emitted by | Venue | | --- | --- | --- | | `Initialize` | Uniswap v4 PoolManager `0x8366a39cc670b4001a1121b8f6a443a643e40951` | Uniswap v4 liquidity pools, including the launchpads that list into v4 (Pons graduations, Klik.finance) | | `PoolCreated` | Concentrated-liquidity factories, such as the Uniswap v3 factory `0x1f7d7550b1b028f7571e69a784071f0205fd2efa` | Uniswap v3 style liquidity pools | | `PairCreated` | Constant-product factories, such as the Uniswap v2 factory `0x8bceaa40b9acdfaedf85adf4ff01f5ad6517937f` | Uniswap v2 style pairs | Bitquery parses trades on Robinhood Chain for Uniswap v2, v3 and v4, PancakeSwap v3 and Infinity, the Pons and Flap.sh bonding curves and other DEXs. `Trade.Dex.ProtocolName` on `EVM.DEXTrades` and `Pair.Market.Protocol` on `Trading.Trades` name the venue of each trade; the first-hour volume query below lists the venues active today. Uniswap v4 keeps every liquidity pool inside the PoolManager, so all v4 pairs share one pool address. Use the v4 pool id (the `id` argument of `Initialize`, `Pair.Pool.Id` on trades) or `Pair.Market.Id` in the `Trading` cube to tell v4 liquidity pools apart. `Market.Id` is unique per liquidity pool on every venue, which makes it the safe grouping key for a new pairs list. --- ## New liquidity pools created today {#new-pools-today} All liquidity pools created since 00:00 UTC today, newest first, from the three events above in one query. `Block.Date` with `since_relative: {days_ago: 0}` keeps the window on the current UTC day. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-new-liquidity-pools-created-today) ```graphql { EVM(network: robinhood) { Events( limit: {count: 50} orderBy: {descending: Block_Time} where: { Block: {Date: {since_relative: {days_ago: 0}}} any: [ { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} } {Log: {Signature: {Name: {in: ["PoolCreated", "PairCreated"]}}}} ] } ) { Block { Time Number } Log { Signature { Name } } LogHeader { Address } Transaction { Hash From To } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` How to read each row: - `Log.Signature.Name` tells you the venue type, and `LogHeader.Address` is the PoolManager or the factory that created the liquidity pool. - `Initialize` returns `id` (the v4 pool id), `currency0`, `currency1`, `fee`, `tickSpacing`, `hooks`, `sqrtPriceX96` and `tick`. A `currency0` of `0x000…000` is native ETH. - `PoolCreated` returns `token0`, `token1`, `fee`, `tickSpacing` and the new `pool` address. `PairCreated` returns `token0`, `token1` and the new `pair` address. - `Transaction.To` is the contract the creator called. For launchpad listings this is the launchpad, which is how you attribute a new pair to Klik.finance, Pons or another launch contract. The v4 `Initialize` filter is pinned to the PoolManager on purpose: every Uniswap v3 style liquidity pool also emits its own `Initialize` when it is first priced, and those rows would repeat the `PoolCreated` rows. --- ## New liquidity pools live stream {#new-pools-stream} The same filter as a WebSocket subscription. Each new Uniswap v4, v3 or v2 liquidity pool is pushed as soon as its block is indexed, with no polling. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-new-liquidity-pools-live-stream) ```graphql subscription { EVM(network: robinhood) { Events( where: { any: [ { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} } {Log: {Signature: {Name: {in: ["PoolCreated", "PairCreated"]}}}} ] } ) { Block { Time Number } Log { Signature { Name } } LogHeader { Address } Transaction { Hash From To } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` To keep only the v4 liquidity pools of one launchpad, add an `Arguments` filter on the `hooks` argument, as shown on the [New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending#new-pools) page. --- ## First trade of a new pair {#first-trade} Launchpads that list and buy in one call give you the first trade of a pair in the same transaction that creates it. The Pons `PonsV2LaunchAndBuy` router at `0xe33e9e479df8802cb0866d5d05258bec4cf62948` deploys the token, opens its bonding-curve liquidity pool and executes the creator's first buy in one transaction. Every trade whose transaction was sent to that router is therefore the first trade on a brand-new pair. This subscription streams those first trades from the `Trading` cube, with USD price, trade size and market cap already attached: [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-first-trade-new-pair-stream) ```graphql subscription { Trading { Trades( where: { Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}} TransactionHeader: {To: {is: "0xe33e9e479df8802cb0866d5d05258bec4cf62948"}} } ) { Block { Time } Pair { Token { Name Symbol Address } QuoteToken { Symbol Address } Market { Protocol Id } Pool { Address Id } } Side Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base } Supply { MarketCap } Trader { Address } TransactionHeader { Hash } } } } ``` `Trader.Address` is the creator, `AmountsInUsd.Base` is the size of the opening buy, and `Supply.MarketCap` is the market cap the pair opened at. `Pair.Market.Id` identifies the new liquidity pool; pass it to a `Trading.Trades` filter on `Pair: {Market: {Id: {is: "..."}}}` to follow every trade that comes after. For more on Pons launches, see the [Pons Launchpad API](/docs/blockchain/robinhood/pons-api). --- ## New liquidity pools by DEX with volume in the first hour {#first-hour-volume} This is the "new pairs" table: liquidity pools that made their first trade in the last hour, with the DEX, the pair, trade count, unique traders and USD volume. Rows are grouped by `Pair.Market.Id`, so each Uniswap v4 liquidity pool is its own row even though all v4 pairs share the PoolManager address. The query looks back 24 hours and keeps only the liquidity pools with no trade before the last hour (`earlier_trades` with `selectWhere: {eq: "0"}`). Every remaining liquidity pool is less than an hour old, so its `volume_usd` is its first-hour volume. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-new-liquidity-pools-first-hour-volume-by-dex) ```graphql { Trading { Trades( limit: {count: 20} orderBy: {descendingByField: "volume_usd"} where: { Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Market { Protocol Id } Token { Symbol Address } QuoteToken { Symbol } } Block { first_trade: Time(minimum: Block_Time) } earlier_trades: count(if: {Block: {Time: {till_relative: {hours_ago: 1}}}}, selectWhere: {eq: "0"}) trades: count traders: uniq(of: Trader_Address) volume_usd: sum(of: AmountsInUsd_Base) } } } ``` - `Pair.Market.Protocol` is the DEX (`uniswap_v4`, `uniswap_v3`, `pons_v2`, `flap_v5` and so on). To list one DEX only, add `Protocol: {is: "uniswap_v3"}` next to `NetworkBid`. - `first_trade` is the listing time of each liquidity pool. - Sort by `"traders"` instead of `"volume_usd"` to rank new pairs by how many wallets traded them, which is harder to inflate than USD volume. --- ## Klik.finance launchpad launches {#klik-finance} [Klik.finance](https://klik.finance/) launches a token and opens its Uniswap v4 liquidity pool in one transaction sent to the Klik.finance contract `0x16cf6788b762ee8969744586ed16fc5705140dd7`. The launch emits `ERC20TokenCreated` from that contract and `Initialize` from the PoolManager, and the token then trades as a `uniswap_v4` pair. This query lists the liquidity pools created by Klik.finance launches over the last three days, with the v4 pool id, the pair (`currency0` is native ETH) and the Klik.finance hook: [Run this query in the IDE](https://ide.bitquery.io/klik-finance-launchpad-launches-robinhood-chain) ```graphql { EVM(network: robinhood) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { Block: {Time: {since_relative: {days_ago: 3}}} Transaction: {To: {is: "0x16cf6788b762ee8969744586ed16fc5705140dd7"}} LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} } ) { Block { Time Number } Transaction { Hash From } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` `currency1` is the new token, `Transaction.From` is the wallet that launched it, and `id` is the v4 pool id: add the `0x` prefix and filter `Trading.Trades` on `Pair: {Pool: {Id: {is: "0x..."}}}` to get its trades and USD prices. For Klik.finance token mints, see the [Klik Finance section of the Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches#klik-finance). --- ## Datasets {#datasets} | Data | Cube | Window | | --- | --- | --- | | New liquidity pools (`Initialize`, `PoolCreated`, `PairCreated`) | `EVM.Events` | `realtime` holds the most recent days; add `dataset: combined` with a time filter for older listings | | First trades and first-hour volume | `Trading.Trades` | Real time plus roughly the last 30 days; no `dataset` argument | See [data coverage and retention](/docs/graphql/data-coverage-retention) for details. --- ## Video Tutorial | Most Traded Robinhood Chain Meme Coins This Week, and Who Is Really Trading Them --- ## Related pages - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API in one place - [Robinhood Chain New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending) — trending tokens, most active liquidity pools, pair lookup and token search - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) — new tokens by launchpad - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) — prices, OHLCV, market cap and top traders - [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity) — liquidity pool reserves, TVL and price impact - [WebSocket subscriptions](/docs/subscriptions/websockets/) — run any query as a stream --- ## New Pools & Trending Tokens on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-new-pools-trending/ Query new Uniswap pools, trending tokens, most active pools, pair lookups and token search on Robinhood Chain with Bitquery GraphQL and WebSocket streams. # New Pools & Trending Tokens on Robinhood Chain This page covers the four questions a token screener asks on **Robinhood Chain**: *what pools were just created*, *what is trading right now*, *what is this pair*, and *where is the token with this symbol*. Every answer is a GraphQL query you can run on your own key, page through, and convert to a WebSocket stream — no rate-limited third-party endpoint in between. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). If you have been calling a public aggregator's Robinhood endpoints and hit their limits, coverage gaps, or delays, the table below maps each one to its Bitquery equivalent. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) — prices, OHLCV, market cap, top traders - [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity) — pool reserves, TVL and price impact - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) — new tokens by launchpad - [Crypto Price API](/docs/trading/crypto-price-api/) — the `Trading` cubes in full - [WebSocket subscriptions](/docs/subscriptions/websockets/) ::: --- ## What you would call elsewhere {#endpoint-mapping} | Screener endpoint | Bitquery equivalent | Section | | --- | --- | --- | | `networks/robinhood/new_pools` | `Initialize` and `PoolCreated` events on `EVM.Events` | [New pools](#new-pools) | | `networks/robinhood/pools` | `Trading.Trades` grouped by `Pair.Pool.Address` | [Most active pools](#most-active-pools) | | `networks/robinhood/trending_pools` | `Trading.Trades` over a 24-hour bound | [Trending tokens](#trending-tokens) | | `dex/pairs/robinhood/{pool}` | `Trading.Trades` filtered on `Pair.Pool.Address`, or `Pair.Pool.Id` for Uniswap v4 | [Look up a pair](#pair-lookup) | | `dex/search?q={text}` | `Trading.Trades` filtered on `Token.Symbol` / `Token.Name` | [Search for a token](#token-search) | | Pool reserves and TVL | `EVM.DEXPoolEvents` | [Liquidity API](/docs/blockchain/robinhood/robinhood-liquidity) | Two differences are worth knowing before you port a screener across. Bitquery returns **every pool on the chain**, including the thousands minted by launchpads each day, so most feeds want a filter rather than the raw firehose. And any query here becomes a live stream by swapping `query` for `subscription`, which removes the polling loop a REST screener forces on you. --- ## New pools {#new-pools} Robinhood Chain creates pools through two paths, and a complete new-pool feed reads both. ### Uniswap v4 pools Uniswap v4 keeps every pool inside one singleton, the **PoolManager** at `0x8366a39cc670b4001a1121b8f6a443a643e40951`, which emits `Initialize` for each new pool. This is the busiest path on the chain by a wide margin, because the launchpads graduate into it. ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} Block: {Time: {since_relative: {hours_ago: 1}}} } ) { Block { Time } Transaction { Hash From } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` `Initialize` decodes into eight arguments: `id` (the v4 pool id), `currency0` and `currency1` (the pair, where `0x000…000` means native ETH), `fee`, `tickSpacing`, `hooks`, `sqrtPriceX96` and the opening `tick`. The **`hooks` argument is the useful one for filtering**. It is `0x000…000` for a plain pool, and a protocol's own address when that protocol owns the pool — so a single `Arguments` filter isolates one launchpad's graduations: ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} Arguments: {includes: { Name: {is: "hooks"} Value: {Address: {is: "0xe5e702641ea86f4ae6cc3cdaed2b886f976be044"}} }} } ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` That hook address is the [Pons](/docs/blockchain/robinhood/pons-api) meme hook, so the query returns Pons graduations only. Swap it for any other protocol's hook. ### Uniswap v3 and other factories The older factory model emits `PoolCreated` from the factory contract itself. Several factories are live on Robinhood Chain, so filter by the event name and read `LogHeader.Address` to see which factory minted each pool. ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { Log: {Signature: {Name: {is: "PoolCreated"}}} Block: {Time: {since_relative: {hours_ago: 6}}} } ) { Block { Time } LogHeader { Address } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` `PoolCreated` gives `token0`, `token1`, `fee`, `tickSpacing` and the new `pool` address. To see which factories are actually producing pools, group the same event by emitter: ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 15} orderBy: {descendingByField: "count"} where: { Log: {Signature: {Name: {is: "PoolCreated"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { LogHeader { Address } count } } } ``` The chain-wide Uniswap V3 factory `0x1f7d7550b1b028f7571e69a784071f0205fd2efa` dominates this list. It is **not** owned by any launchpad, so do not treat it as a protocol filter. ### Stream new pools Both feeds work as subscriptions. This one pushes every new v4 pool as its block is indexed: ```graphql subscription { EVM(network: robinhood) { Events( where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} } ) { Block { Time } Transaction { Hash From } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` :::caution A raw new-pool feed is mostly launchpad noise Thousands of pools are created on Robinhood Chain every day, and the overwhelming majority never attract a second trade. If you are building a watchlist rather than an archive, filter by `hooks`, or start from [trending tokens](#trending-tokens) and work backwards to the pool. ::: --- ## Trending tokens {#trending-tokens} The `Trading` cubes carry swaps with USD pricing already attached, so a trending list is one aggregation over a time bound. Rank by **trade count and unique traders** rather than USD volume: thin pools can print enormous dollar figures from a single swap. ### Most traded tokens in the last 24 hours ```graphql { Trading { Trades( limit: {count: 25} orderBy: {descendingByField: "trades"} where: { Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Token { Symbol Name Address } } trades: count traders: uniq(of: Trader_Address) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) } } } ``` `Side` is the string `"Buy"` or `"Sell"`, so the two `count(if: …)` aggregates give you buy pressure alongside the raw count. Widen or narrow the window with `hours_ago`. ### Most active pools {#most-active-pools} The same aggregation keyed on the pair answers "which pools are hot", which is what a trending-pools endpoint returns. Rows are grouped by the whole `Pair` selection, so Uniswap v4 pairs come back separately even though they share one `Pool.Address` — read `Pool.Id` to tell them apart: ```graphql { Trading { Trades( limit: {count: 25} orderBy: {descendingByField: "trades"} where: { Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Pool { Address Id } Token { Symbol Address } QuoteToken { Symbol } Market { Protocol } } trades: count traders: uniq(of: Trader_Address) } } } ``` ### Where trading happens Grouping by protocol shows how the chain's activity is split, and how many distinct pools each venue is running: ```graphql { Trading { Trades( limit: {count: 15} orderBy: {descendingByField: "trades"} where: { Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Market { Protocol ProtocolFamily } } trades: count traders: uniq(of: Trader_Address) } } } ``` Uniswap v3 and v4 carry most of the trades on the chain. The bonding-curve launchpads sit at the other end of the shape: they mint one pool per launched token, so they run far more pools than the AMMs while averaging a small fraction of the trades on each. :::caution Do not count pools with `uniq(of: Pair_Pool_Address)` No single field counts pools correctly across venues, which is why the query above does not try. Uniswap v4 keeps every pool inside one singleton contract, so **all v4 pairs report the same `Pool.Address`** and that aggregate collapses them to `1`. The reverse is true of `Pool.Id`, which only v4-style venues populate. Count pools within one protocol at a time, using `Pool.Id` for Uniswap v4 and PancakeSwap Infinity and `Pool.Address` for everything else. ::: --- ## Look up a pair {#pair-lookup} Given a pool address, return its recent trades with both sides of the pair, the venue, and price in the quote asset and in USD. This works for pools that have their own contract — Uniswap v2 and v3, PancakeSwap v3, and the bonding-curve launchpads. **Uniswap v4 needs `Pool.Id` instead**, covered right below. ```graphql { Trading { Trades( limit: {count: 25} orderBy: {descending: Block_Time} where: { Pair: { Market: {NetworkBid: {is: "bid:robinhood"}} Pool: {Address: {is: "0xbbaefcfcd7b92ed0df1a3eec22a21ba6beb0b52b"}} } } ) { Block { Time } Pair { Token { Symbol Name Address } QuoteToken { Symbol Address } Market { Protocol } Pool { Address Id } } Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base } Side Trader { Address } TransactionHeader { Hash } } } } ``` `Price` and `PriceInUsd` are plain numbers on this cube, not nested objects. For candles, market cap and supply on the same pair, see the [Trades API](/docs/blockchain/robinhood/robinhood-trades); for reserves and price impact, see the [Liquidity API](/docs/blockchain/robinhood/robinhood-liquidity). ### Uniswap v4 pairs: look up by pool id {#v4-pool-id} Uniswap v4 has no per-pool contract. Every v4 pool lives inside the PoolManager singleton, so **`Pool.Address` is `0x8366a39cc670b4001a1121b8f6a443a643e40951` on every v4 pair** and filtering on it returns the whole venue rather than one pair. The per-pool identifier is `Pool.Id`, the 32-byte v4 pool id: ```graphql { Trading { Trades( limit: {count: 25} orderBy: {descending: Block_Time} where: { Pair: { Market: {NetworkBid: {is: "bid:robinhood"}} Pool: {Id: {is: "0x7fb39eb653999feb9f0d3b1410848911383dfc681f3585229df4aa5b560bf0ba"}} } } ) { Block { Time } Pair { Token { Symbol Name Address } QuoteToken { Symbol } Market { Protocol } Pool { Id } } Price PriceInUsd Side Trader { Address } } } } ``` This is the same value the `Initialize` event carries in its `id` argument, so a pool you picked up from the [new-pool feed](#new-pools) can be handed straight to this query — add the `0x` prefix, which the event argument omits. If you only have a token address, filter on `Pair.Token.Address` instead and read `Pool.Id` off the result. ### Newly listed tokens Sorting ascending inside a recent window gives the first trades to arrive — tokens that just started trading, with the pool and venue they landed on: ```graphql { Trading { Trades( limit: {count: 25} orderBy: {ascending: Block_Time} where: { Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}} Block: {Time: {since_relative: {hours_ago: 2}}} } ) { Block { Time } Pair { Token { Symbol Name Address } QuoteToken { Symbol } Market { Protocol } Pool { Address } } } } } ``` :::note This is "first trade in the window", not "first trade ever" The `Trading` cubes hold a rolling window of roughly the last 30 days. Ascending order inside that window returns the oldest rows it still holds, so for a token older than the window you get its oldest *retained* trade. To pin a real launch time, find the mint on the [Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) or the launchpad's own guide. ::: --- ## Search for a token {#token-search} ### By symbol ```graphql { Trading { Trades( limit: {count: 25} orderBy: {descendingByField: "trades"} where: { Pair: { Market: {NetworkBid: {is: "bid:robinhood"}} Token: {Symbol: {includesCaseInsensitive: "cat"}} } Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Token { Symbol Name Address } } trades: count traders: uniq(of: Trader_Address) } } } ``` ### By name ```graphql { Trading { Trades( limit: {count: 25} orderBy: {descendingByField: "trades"} where: { Pair: { Market: {NetworkBid: {is: "bid:robinhood"}} Token: {Name: {includesCaseInsensitive: "gamestop"}} } Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Token { Symbol Name Address } } trades: count } } } ``` :::caution Symbols and names are not unique Anyone can deploy a token called `GME`. A name search on Robinhood Chain returns the tokenized stock alongside look-alikes, and ordering by trade count is what separates them — the real one is usually far ahead. Always resolve to a **contract address** before you quote a price, and never treat a symbol match as identity. ::: --- ## Datasets and windows {#datasets} | Data | Where it lives | Reach | | --- | --- | --- | | New pools (`Initialize`, `PoolCreated`) | `EVM.Events` | `realtime` holds the most recent days; add `dataset: combined` or `archive` for history | | Trending, pair lookup, search | `Trading` cubes | A rolling window of roughly the last 30 days; takes no `dataset` argument | | Pool reserves and TVL | `EVM.DEXPoolEvents` | **Realtime only** on Robinhood Chain — see the [Liquidity API](/docs/blockchain/robinhood/robinhood-liquidity) | The most common surprise is an event query that works for today and returns nothing for last month: that is the default `realtime` dataset, and `dataset: combined` fixes it. See [data coverage and retention](/docs/graphql/data-coverage-retention). --- ## FAQ {#faq} ### How do I get new pools on Robinhood Chain without a third-party API? Read `Initialize` from the Uniswap v4 PoolManager and `PoolCreated` from the v3 factories, both on `EVM.Events`. Run them as subscriptions and you have a push feed instead of a polling loop. See [New pools](#new-pools). ### Why does my new-pool feed return thousands of pools an hour? Because it is complete. Robinhood Chain launchpads mint pools continuously and most never trade again. Filter by the `hooks` argument on v4, or build your list from [trending tokens](#trending-tokens) instead. ### How do I find trending tokens or pairs? Aggregate `Trading.Trades` over a `Block.Time` bound, ranked by `count` and `uniq(of: Trader_Address)`. Rank by trade count rather than USD volume, since thin pools distort dollar figures. ### How do I look up a pair by pool address? Filter `Trading.Trades` on `Pair.Pool.Address`. That returns both sides of the pair, the venue, the price in quote and USD terms, and the trader. **Uniswap v4 is the exception**: all its pools share the PoolManager address, so filter `Pair.Pool.Id` instead. See [Look up a pair](#pair-lookup) and [Uniswap v4 pairs](#v4-pool-id). ### Can I search tokens by symbol or name? Yes, with `includesCaseInsensitive` on `Token.Symbol` or `Token.Name`. Symbols are not unique on-chain, so rank by trade count and resolve to a contract address before trusting a match. ### Does this cover pool liquidity and TVL? Not on this page. Reserves, depth and per-swap slippage live in the [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity), which uses the `DEXPools` cubes. --- ## Next steps - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) — prices, OHLCV candles, market cap and top traders - [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity) — reserves, TVL and price impact - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) — new tokens by launchpad - [Pons Launchpad API](/docs/blockchain/robinhood/pons-api) — the launchpad behind most v4 graduations - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — the full cube map - [WebSocket subscriptions](/docs/subscriptions/websockets/) — turn any query above into a stream --- ## OHLCV Candle Data Complete Guide URL: https://docs.bitquery.io/docs/usecases/ohlcv-complete-guide/ Learn how to build OHLCV candles from Bitquery DEX trade data, including intervals, aggregations, gaps, and chart-ready GraphQL examples. # Complete Guide to Building the Perfect OHLCV Data Using Bitquery APIs This page shows how to get OHLCV (Open, High, Low, Close, Volume) candlestick data, also called K-Line data, across different blockchain networks using Bitquery APIs. We’ll also explore how to filter out bot trades, outliers, and abnormally high or low prices to ensure accurate OHLC calculations. ## Recommended: pre-aggregated OHLC via the Crypto Price API (real-time + last ~30 days) This page builds candles **from raw chain-level trades** (`DEXTradeByTokens`), the right tool for **history older than ~30 days** or **custom intervals**. For anything real-time or within the last ~30 days, use the [**Crypto Price API**](/docs/trading/crypto-price-api/) instead: **true pre-aggregated OHLC down to 1-second intervals**, including the real open price that in-query aggregation cannot produce, with **USD values on every candle and MEV/outlier trades already filtered**, so none of the manual filtering below is needed. The example returns 1-minute OHLC for a token from its top-volume market; swap the token address and network, and change `Duration` for other intervals. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Token-Price-Top-Market-Rank-1). ```graphql { Trading { Pairs( where: { Token: {Address: {is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"}, Network: {is: "Solana"}} Ranking: {Position: {eq: 1}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } limit: {count: 1} orderBy: {descending: Block_Time} ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Mean } } Volume { Base Usd } Block { Time } } } } ``` The rest of this guide covers the chain-level path: building candles from raw `DEXTradeByTokens` rows for deep history and custom intervals. ## **Intervals in OHLC** Bitquery’s OHLC APIs support multiple time intervals, including minutes, hours, days, weeks, and months. You can specify the desired interval in the response field, as shown in the example below: ```graphql Block { Time(interval: {count: 1, in: minutes}) } ``` ``` Block { Time(interval: {count: 1, in: hours}) } ``` ```graphql Block { Time(interval: {count: 1, in: days}) } ``` ``` Block { Time(interval: {count: 1, in: weeks}) } ``` ``` Block { Time(interval: {count: 1, in: months}) } ``` and so on. ## **OHLC on EVM Chains** To fetch OHLC (Open, High, Low, Close) data for a specific token pair on EVM-compatible chains like Ethereum, you can use Bitquery’s `DEXTradeByTokens` API. Supported networks include: - **Ethereum** → `EVM(network: eth)` - **BNB Chain** → `EVM(network: bsc)` - **Polygon (Matic)** → `EVM(network: matic)` - **Arbitrum** → `EVM(network: arbitrum)` - **Base** → `EVM(network: base)` - **Optimism** → `EVM(network: optimism)` - **Robinhood** → `EVM(network: robinhood)` - **Arc Mainnet** → `EVM(network: arc)` ([Arc DEX trades and OHLCV guide](/docs/blockchain/arc-mainnet/arc-mainnet-trades-api/)) - **Arc Testnet** → `EVM(network: arc_testnet)` (chain-level cubes only; no `Trading` cube, USD fields are 0) For full API documentation, refer to: [Get OHLC Data for a Particular Token Pair](/docs/blockchain/Ethereum/dextrades/token-trades-apis/#get-ohlc-data-for-a-particular-token-pair). ### **Sample Query** The following GraphQL query retrieves OHLCV data for an Ethereum token pair: ```graphql query tradingViewPairs { EVM(network: eth) { DEXTradeByTokens( orderBy: { ascendingByField: "Block_Time" } where: { Trade: { Side: { Amount: { gt: "0" } Currency: { SmartContract: { is: "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } } } Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } PriceAsymmetry: { lt: 0.5 } } } ) { Block { Time(interval: { count: 5, in: minutes }) } Trade { open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) max: PriceInUSD(maximum: Trade_PriceInUSD) min: PriceInUSD(minimum: Trade_PriceInUSD) } volume: sum(of: Trade_Side_Amount) } } } ``` ## **OHLC on Non-EVM Chains** Bitquery also supports non-EVM chains, such as **Solana** and **Tron**, enabling you to retrieve OHLC data for these networks. ## **OHLC on Solana** For a detailed guide, visit: [Historical OHLC on Solana](/docs/blockchain/Solana/historical-aggregate-data/#historical-ohlc-on-solana). :::note Archive is also not complete: over a window it shares with `realtime` it returns roughly a fifth to a quarter fewer trades, so candles and volume built from it read low against the same period on `realtime` or the Trading cube. Use it for depth, and prefer the Trading cube's pre-aggregated candles for the last 30 days. On `dataset: combined` / `archive`, `PriceAsymmetry` and USD amount fields cannot be used as filters: they return an error. The query below therefore takes raw `high`/`low` extremes. See [Filter limitations on aggregate datasets](/docs/blockchain/Solana/historical-aggregate-data/#filter-limitations-on-aggregate-datasets). ::: #### **Sample Query** ```graphql { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { Block: { Time: { since_relative: { days_ago: 90 } } } Trade: { Currency: { MintAddress: { is: "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } } limit: { count: 10 } ) { Block { Timefield: Time(interval: { in: days, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## **OHLC on Tron** For details, visit: [OHLC Data on Tron](/docs/blockchain/Tron/tron-dextrades/#get-ohlc-data-of-a-token-on-tron-network). #### **Sample Query** ```graphql query tradingViewPairs { Tron { DEXTradeByTokens( orderBy: { ascendingByField: "Block_Time" } where: { Trade: { Side: { Amount: { gt: "0" } Currency: { SmartContract: { is: "TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR" } } } Currency: { SmartContract: { is: "TJ9mxWPmQSJswqMakEehFWcAntg73odiAq" } } PriceAsymmetry: { lt: 0.1 } } } ) { Block { Time(interval: { count: 5, in: minutes }) } Trade { open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) max: PriceInUSD(maximum: Trade_PriceInUSD) min: PriceInUSD(minimum: Trade_PriceInUSD) } volume: sum(of: Trade_Side_Amount) } } } ``` ## Real-time OHLC In EVM and non-EVM chains, you can also use `subscription` to get a token pair with a high or low value. [Run Stream ➤](https://ide.bitquery.io/seconds-oHLC-realtime-solana-example) Take this query below for example; ```graphql subscription LatestTrades { Solana { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } } ) { min: quantile(of: Trade_PriceInUSD, level: 0.05) max: quantile(of: Trade_PriceInUSD, level: 0.95) volume: sum(of: Trade_Side_AmountInUSD) Trade { Market { MarketAddress } Dex { ProtocolName ProtocolFamily } close: PriceInUSD Side { Type Currency { Symbol MintAddress Name } } } Block { Time(interval: { count: 1, in: seconds }) } } } } ``` This GraphQL **subscription** query is fetching real-time **OHLC (Open, High, Low, Close)** data for Solana trades by continuously monitoring and streaming the latest trades. **Calculating OHLC-Like Metrics** - **`min`** → **5th percentile** price (`quantile(of: Trade_PriceInUSD, level: 0.05)`) - What is the price of the token for lowest 5% of the trades? - **`max`** → **95th percentile** price (`quantile(of: Trade_PriceInUSD, level: 0.95)`) - What is the price of the token for top 5% of the trades? - **`close`** → The latest trade price (`PriceInUSD`). - **`volume`** → Total trade volume in USD (`sum(of: Trade_Side_AmountInUSD)`) over the interval. 4. **Streaming the Data Continuously**: - Because this is a **subscription**, every time a new trade happens on Solana for this token pair, the latest price data is sent. - The latest **closing price (`close`)** is updated dynamically as new trades occur. ### **Why This Is "Real-Time" OHLC?** - The query continuously **monitors** the latest **trades** on Solana. - Each trade updates the **latest close price (`close`)**. - The **high (`max`) and low (`min`)** prices adjust dynamically based on the last 50 trades. - It provides **near real-time OHLC-like data** without waiting for the full candle interval. ### **Limitations** - This is **not true OHLC** because: - It does not aggregate price data strictly by time intervals (e.g., every 5 min, 1h). - The **open price** (first trade of the interval) is missing. - It works based on a **rolling window of the latest trades**, not fixed time slots. ## **Filtering Abnormal Prices** When fetching trade data from Bitquery APIs, you may encounter abnormal prices. These anomalies occur due to two primary reasons: 1. **Legitimate but unusual trades** – The data is correct (can be verified via an explorer like Etherscan), but bot activity may cause extreme price variations. 2. **Incorrect trade data in Bitquery’s database** – If you suspect incorrect data, report the issue by creating a support ticket. For a complete guide, visit: [How to Filter Anomalous Prices](/docs/usecases/how-to-filter-anomaly-prices/). ### **Methods to Filter Anomalous Trades** #### **1. Using Price Asymmetry** - Measures the USD value difference between traded tokens. - To filter extreme trades, use: ```graphql { PriceAsymmetry: {lt: 0.1} } ``` (This removes trades where the price difference exceeds 10%). - Additionally, remove low-value trades: ```graphql { Trade: {AmountInUSD: {lt: "10"}} } ``` #### **2. Using Quantiles** - Quantiles divide data into percentiles, helping detect outliers. - Example: - **75th percentile (`level: 0.75`)** → 75% of values are below this. - **25th percentile (`level: 0.25`)** → 25% of values are below this. - To filter extreme values, keep trades only between the **5th and 95th percentiles**. For more details, check: [Quantile Documentation](/docs/graphql/metrics/quantile/). #### **3. Fetch All Trades and Filter Manually** - Retrieve all trade data from Bitquery. - Apply custom filters, such as: - Calculating the **5th and 95th percentiles** of trade prices. - Keeping only trades within this range. ## **Checking and Reporting Incorrect OHLC Data** If your OHLC data differs significantly from other providers, you should: - Check if **Price Asymmetry** and other filters (as discussed above) are applied. - If there’s still a **huge discrepancy**, report the issue by creating a ticket at: [Bitquery Support](https://support.bitquery.io). ### Example Scenario For example if you check the OHLC for this token `J3TqbUgHurQGNxWtT88UQPcMNVmrL875pToQZdrkpump` again WSOL, Take this query [https://ide.bitquery.io/quantile](https://ide.bitquery.io/quantile) which includes both OHLC using `maximum`, `minimum` and using `quantile` and removes small trades using `AmountinUSD >10` filter. ```graphql { Solana(dataset: archive) { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: { Block: { Time: { since_relative: { days_ago: 90 } } }, Trade: {Currency: {MintAddress: {is: "J3TqbUgHurQGNxWtT88UQPcMNVmrL875pToQZdrkpump"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}, Amount: {gt: "0.05"}}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: days, count: 1}) } volume: sum(of: Trade_Side_AmountInUSD) min1: quantile(of: Trade_PriceInUSD, level: 0.05) max1: quantile(of: Trade_PriceInUSD, level: 0.95) close1: median(of: Trade_PriceInUSD) open1: median(of: Trade_PriceInUSD) Trade { Currency { Name } high: PriceInUSD(maximum: Trade_Price) low: PriceInUSD(minimum: Trade_Price) open: PriceInUSD(minimum: Block_Slot) close: PriceInUSD(maximum: Block_Slot) Side { Currency { Name } } } count } } } ``` If you compare the results of the two, you see smoothening of spikes. **Example 1 (March 2, 2025)** - **Without quantile filtering:** - `high`: 0.00043009940205914187 (Very high) - `low`: 0.00034041182935594274 - **With quantile filtering:** - `max1`: 0.0004214320331811905 (Lower than raw high → filters extreme spike) - `min1`: 0.0003484918735921383 (Higher than raw low → removes low extremes) _Effect:_ The high (`max1`) and low (`min1`) values are adjusted to remove extreme spikes. **Example 2 (February 27, 2025)** - **Without quantile filtering:** - `close`: 0.0003147996409415908 - `high`: 0.00033683591504094873 - `low`: 0.000254437945561626 (Low outlier) - `open`: 0.00030726648293986935 - **With quantile filtering:** - `close1`: 0.0003042437473777681 - `max1`: 0.00032312784204259514 - `min1`: 0.00028326141997240487 (Higher than raw low, outlier removed) - `open1`: 0.0003042437473777681 _Effect:_ The low (`min1`) is adjusted upwards, likely removing an extreme drop. - Smoothing high price spikes (`max1` is lower than `high`) - Removing sharp downward price drops (`min1` is higher than `low`) ## **Alternative: Calculating OHLC from Trades Without Aggregating in GraphQL Query** ### Limitations of the OHLC API - Solana chain-level OHLC coverage does not span the chain's full history. See [Data coverage & retention](/docs/graphql/data-coverage-retention/) for current windows. - While you can add filters as shown above to filter only valuable trades, it is not fool-proof and might not work with all tokens especially memecoins. If you prefer not to use an aggregated GraphQL query, you can fetch raw trade data and manually compute OHLC values. Complete guide to [using trades to calculate OHLC is available here](/docs/usecases/solana-ohlc-calculator/) ## **Building TradingView Charts** To visualize OHLCV data using **TradingView Advanced Chart Library**, refer to: - [TradingView Advanced Charts Guide](/docs/usecases/tradingview-subscription-realtime/getting-started/) - [TradingView Real-Time Subscription](/docs/usecases/tradingview-subscription-realtime/getting-started/) --- ## OKX DEX API on Solana: Router Swaps, Routes, Commissions URL: https://docs.bitquery.io/docs/blockchain/Solana/okx-dex-solana-api/ OKX DEX aggregation router on Solana via Bitquery GraphQL: live swaps with the user's wallet, apps and bots using it, top tokens, route legs and commissions. # OKX DEX API on Solana: Router Swaps, Routes, Commissions OKX DEX runs a swap aggregation router on Solana, program `proVF4pMXVaYqmy4NjniPh4pqKNfMmsihgd4wdkCX3u`. It splits a trade across Solana venues and settles it in one transaction. Bitquery records each routed swap in the Solana `DEXTrades` and `DEXTradeByTokens` cubes under `ProtocolFamily: "OKX"` and `ProtocolName: "dex_solana_v3"`. In the hour to 10:00 UTC on 2026-10-26 the router carried about 15,000 trades worth $3.3 million. Two things shape every query on this page: - **The user's wallet is in `Trade.Buy.Account.Owner`.** Apps that sign for their users, such as FOMO, appear as `Transaction.Signer`, so the signer is not always the trader. - **A routed swap produces more than one trade row.** The OKX row is the user's trade; the pools along the route appear as separate rows with their own protocol names. Filter on `ProtocolFamily: "OKX"` to count each user trade once. Every example runs in the [Bitquery IDE](https://ide.bitquery.io). To stream one, change `query` to `subscription` and remove `limit` and `orderBy`. For other Solana aggregators, see the [DFlow API](/docs/blockchain/Solana/dflow-api/) and the [Jupiter API](/docs/blockchain/Solana/solana-jupiter-api/). ## Latest OKX DEX swaps on Solana [Run it in the IDE ➤](https://ide.bitquery.io/OKX-DEX-Solana-latest-swaps) ```graphql query OkxDexSolanaLatestSwaps { Solana { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolFamily: {is: "OKX"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Trade { Buy { Amount AmountInUSD Account { Owner } Currency { Symbol MintAddress } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } } Dex { ProtocolName ProgramAddress } } } } } ``` ## Apps and bots using the OKX DEX router Groups the last hour of router trades by transaction signer. Many distinct user wallets under one signer means an app that signs for its users; one wallet means a wallet or bot trading for itself. [Run it in the IDE ➤](https://ide.bitquery.io/OKX-DEX-Solana-apps-and-bots-by-signer) ```graphql query OkxDexSolanaSigners { Solana { DEXTrades( limit: {count: 20} orderBy: {descendingByField: "trades"} where: {Trade: {Dex: {ProtocolFamily: {is: "OKX"}}}, Block: {Time: {since_relative: {minutes_ago: 60}}}, Transaction: {Result: {Success: true}}} ) { Transaction { Signer } trades: count users: uniq(of: Trade_Buy_Account_Owner) volume_usd: sum(of: Trade_Buy_AmountInUSD) } } } ``` ## Most traded tokens through the OKX DEX router Ranks tokens by USD volume in the last hour, leaving out SOL and USDC. [Run it in the IDE ➤](https://ide.bitquery.io/OKX-DEX-Solana-most-traded-tokens) ```graphql query OkxDexSolanaTopTokens { Solana { DEXTradeByTokens( limit: {count: 20} orderBy: {descendingByField: "volume_usd"} where: {Trade: {Dex: {ProtocolFamily: {is: "OKX"}}, Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}}, Block: {Time: {since_relative: {minutes_ago: 60}}}, Transaction: {Result: {Success: true}}} ) { Trade { Currency { Symbol MintAddress } } trades: count volume_usd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## OKX DEX trades of one wallet Replace the address with the wallet you want. [Run it in the IDE ➤](https://ide.bitquery.io/OKX-DEX-Solana-trades-of-a-wallet) ```graphql query OkxDexSolanaWalletTrades { Solana { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolFamily: {is: "OKX"}}, Buy: {Account: {Owner: {is: "6fXBfTmEUJiKiXZ7mJp29usqzids9LADGRDzoaaxTSsA"}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Trade { Buy { Amount AmountInUSD Currency { Symbol } } Sell { Amount Currency { Symbol } } } } } } ``` ## Route legs: which venue filled each part The router logs a `SwapEvent` for every leg. The `dex` argument is a JSON enum naming the venue and instruction, for example `PumpfunammBuy2`, and `amount_in` / `amount_out` are the leg's amounts in each token's smallest unit. [Run it in the IDE ➤](https://ide.bitquery.io/OKX-DEX-Solana-route-legs) ```graphql query OkxDexSolanaRouteLegs { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "proVF4pMXVaYqmy4NjniPh4pqKNfMmsihgd4wdkCX3u"}, Method: {is: "SwapEvent"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` ## Commissions on OKX DEX swaps Apps that integrate the router can take a commission. The router logs it in `SwapWithFeesCpiEvent2` (single commission account) and `SwapWithFeeCpiEventV3` (several commission levels). This query keeps events where `commission_amount` is above zero. Each row names the source and destination mints, the token-account owners, the `commission_amount`, the `commission_account` and, where set, a platform fee and a trim amount. [Run it in the IDE ➤](https://ide.bitquery.io/OKX-DEX-Solana-commissions) ```graphql query OkxDexSolanaCommissions { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "proVF4pMXVaYqmy4NjniPh4pqKNfMmsihgd4wdkCX3u"}, Method: {is: "SwapWithFeesCpiEvent2"}, Arguments: {includes: {Name: {is: "commission_amount"}, Value: {BigInteger: {gt: "0"}}}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_Boolean_Value_Arg { bool } } } } } } } } ``` `SwapWithFeeCpiEventV3` carries multi-level commissions as JSON lists (`commission_rates`, `commission_amounts`, `commission_accounts`) with a `total_commission_amount`; in the sample on 2026-10-26 its commissions were zero. ## Pitfalls - **Count user trades on the OKX row only.** The pool rows of the same transaction repeat the trade. - **Signer is not the user for app trades.** Use `Trade.Buy.Account.Owner`. - **Instruction data covers about 12 hours.** The route-leg and commission queries read `Instructions`, which is real-time only. --- ## ONDO Tokenized Stocks API on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/ondo-stocks-api/ Query and stream Ondo Finance tokenized stocks on Robinhood Chain: catalog of ONDO stocks, holders, OHLCV, latest price, live price streams, and cross-pool arbitrage via Bitquery GraphQL. # ONDO Tokenized Stocks API on Robinhood Chain [Ondo Finance](https://ondo.finance/) issues **tokenized stocks and ETFs** as ERC-20s on Robinhood Chain (`network: robinhood`, chain ID **4663**). Each ticker is a 1:1 on-chain claim on the underlying equity (for example `NVDAon`, `AAPLon`). Bitquery indexes those tokens as ordinary ERC-20s, so you can catalog every ONDO stock, list holders, and pull prices, candles, and live streams through the same `EVM` and `Trading` cubes used for any Robinhood token. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). :::tip These examples use the Trading API Price, OHLCV, live quotes, and cross-pool prices on this page use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs). Scope Robinhood with `NetworkBid: { is: "bid:robinhood" }`. `Trading` covers **real-time plus roughly the last 30 days**. Holder rankings use `EVM.Holders` on `dataset: archive`. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades/) - [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/) - [xStocks API (Solana)](/docs/blockchain/Solana/xstocks-api/) - [Trading data overview](/docs/trading/trading-data-overview/) ::: --- ## How ONDO stocks appear on-chain ONDO tickers on Robinhood Chain use a symbol that **ends with `on`**. New supply is minted from the zero address into Ondo's issuance / custody contract. The catalog query below uses that mint pattern: | Filter | Value | Meaning | | --- | --- | --- | | `Transfer.Sender` | `0x0000000000000000000000000000000000000000` | Mint (issuance) | | `Transfer.Receiver` | `0xf2dc25b8a5231667d8cf0ecd476fb46805186572` | Ondo issuance / custody wallet | | `Currency.Symbol.endsWith` | `"on"` | ONDO ticker suffix | Copy a `SmartContract` from the catalog into the holder, OHLCV, price, and arbitrage queries. Token IDs in the Trading cubes look like `bid:robinhood:`. --- ## All ONDO tokenized stocks (address, name, symbol, minted amount) Lists every ONDO stock mint on Robinhood Chain: token name, symbol, contract address, and amount minted in that transfer. ▶️ [Run in IDE](https://ide.bitquery.io/All-tokenised-ONDO-stocks-on-Robinhood) ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: {Transfer: {Sender: {is: "0x0000000000000000000000000000000000000000"}, Receiver: {is: "0xf2dc25b8a5231667d8cf0ecd476fb46805186572"}, Currency: {Symbol: {endsWith: "on"}}}} orderBy: {descending: Block_Time} ) { Block { Time } Transaction { Hash } Transfer { Currency { Name Symbol SmartContract } Amount } } } } ``` --- ## Streaming Real time trades for Amazon ONDO stock Subscribe on `Trading.Trades` to subscribe to the latest trades for Amazon ONDO tokenized stocks on Robinhood. This stream message includes info such as trade time, trader address, trade transaction hash, trade amount and price in both base and USD evaluation, along with currency and quote currency details. The token address for Amazon ONDO tokenized stock is `0x6c0b8c7071899bf9e7fc2d6d8cc2accd23ce6135`. ▶️ [Run in IDE](https://ide.bitquery.io/real-time-trades-for-amazon-ondo-stocks) ```graphql subscription { Trading { Trades( where: { Pair: { Token: { Address: {is: "0x6c0b8c7071899bf9e7fc2d6d8cc2accd23ce6135"} NetworkBid: { is: "bid:robinhood" } } } } ) { Amounts { Base Quote } AmountsInUsd { Base } Block { Time } Price PriceInUsd Pair { Market { Address } Pool { Address } Token { Name Symbol Address } QuoteToken { Name Symbol Address } } Side Trader { Address } Supply { MarketCap } TransactionHeader{ Hash } } } } ``` To stream **one pool** instead of the blended token price, subscribe to `Trading.Pairs` and filter `Pool.Address` — same pattern as [Real-Time OHLCV for a pair](/docs/blockchain/robinhood/robinhood-trades/#real-time-ohlcv-stream-for-a-pair-on-robinhood). ## Token holders of Nvidia ONDO stock Using `EVM.Holders`, we can get top holders for Nvidia ONDO stock, with wallets ranked by balance. `Amount` is the tokenized share count. Use `dataset: combined` and add `Balance: { Amount: { gt: "0" } }` for **current** holders. The token address for `Nvidia ONDO stock` is `0x6026fd22df0ba04c1c176e1beb79cda8748ff8d7`. ▶️ [Run in IDE](https://ide.bitquery.io/token-holders-of-Nvidia-ONDO-stock) ```graphql { EVM(dataset: combined, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0x6026fd22df0ba04c1c176e1beb79cda8748ff8d7"} } Balance: { Amount: { gt: "0" } } } limit: { count: 20 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } Currency { Name Symbol SmartContract } } } } ``` --- ## OHLCV of Google ONDO stock Using `Trading.Tokens`, we can get normalized OHLC candle values without the need of data normalization from raw trades data. `Duration: { eq: 60 }` is 1-minute candles (`300` = 5 minutes, `3600` = 1 hour). For a **single pool**, use `Trading.Pairs` and add `Pool.Address`. The token address for Google ONDO tokenized stock is `0x3381a810a40cea0b7f145e341aa53a296ed4093b`. ▶️ [Run in IDE](https://ide.bitquery.io/OHLCV-of-Google-ONDO-stocks) ```graphql { Trading { Tokens( where: { Token: { Address: { is: "0x3381a810a40cea0b7f145e341aa53a296ed4093b" } NetworkBid: { is: "bid:robinhood" } } Interval: { Time: { Duration: { eq: 60 } } } Price: { IsQuotedInUsd: true } } orderBy: { descending: Interval_Time_End } ) { Token { Name Symbol Address } Interval { Time { Start Duration End } } Price { IsQuotedInUsd Ohlc { Open High Low Close } } Volume { Base Quote Usd } Block { Time } } } } ``` --- ## Latest price of Amazon ONDO stock `Trading.Tokens` returns Bitquery's **volume-weighted price across pools**. `Interval.Time.Duration: 1` is the latest 1-second bar; `limit: 1` plus `orderBy: descending Interval_Time_End` is the current snapshot. ▶️ [Run in IDE](https://ide.bitquery.io/latest-price-of-Amazon-ONDO-stock) ```graphql { Trading { Tokens( where: { Token: { Address: { is: "0x6c0b8c7071899bf9e7fc2d6d8cc2accd23ce6135" } NetworkBid: { is: "bid:robinhood" } } Interval: { Time: { Duration: { eq: 1 } } } } orderBy: { descending: Interval_Time_End } limit: { count: 1 } ) { Interval{ Time{ End } } Token { Name Symbol Address } latest_price: Price { Ohlc { Close } } Supply { MarketCap FullyDilutedValuationUsd } } } } ``` ## Tokenized stocks on other platforms - [xStocks API](/docs/blockchain/Solana/xstocks-api/): Backed's stock tokens on Solana, such as `TSLAx` and `AAPLx`. They trade in DEX pools and through RFQ quotes. - [Solana RFQ API](/docs/blockchain/Solana/solana-rfq-api/#tokenized-equities-on-rfq): Ondo also issues stock tokens on Solana. They see few trades there, most of them through RFQ quotes. - [Hyperliquid HIP-3 Stocks API](/docs/perpetuals/hyperliquid/hip3-stocks-api/): perpetual futures on the S&P 500, the Nasdaq-100 and single US stocks. They settle in USDC, and no stock token changes hands. ## Video Tutorial | Which Tokenized Stocks Actually Trade on Robinhood Chain? Volume, Trades and Traders --- ## Optimism API Documentation URL: https://docs.bitquery.io/docs/blockchain/Optimism/ Optimism data API overview: DEX trades and core chain APIs, how Bitquery differs from Optimism RPC, WebSocket and webhook support, and video tutorials. # Optimism API Documentation :::tip Building a trading app or DEX UI on Optimism? For **real-time trades and prices on Optimism** (and the last ~30 days), use the curated [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. For **historical Optimism data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: ## Overview In this section we will see how to fetch data on different tokens, transactions, and DEXs on Optimism via APIs and Streams. **[Create your account](https://account.bitquery.io/auth/signup)** to get started. If you need help getting data on Optimism, reach out to [support](https://t.me/Bloxy_info). ### What is Optimism API? Bitquery Optimism APIs help you fetch onchain data like trades, transactions, balances, etc using graphQL query. ### What are capabilities of Bitquery Optimism API? Bitquery Optimism APIs are very flexible, you can fetch trade, transaction, and balance information for a period, for a specific wallet, and join with other information. ### Difference between Optimism RPC and Bitquery Optimism API? | Optimism RPC | Bitquery Optimism API | | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | JSON-RPC endpoint exposing raw Optimism on-chain state and transactions | GraphQL endpoint over pre-indexed, parsed Optimism data (token transfers, DEX trades, logs, calls, etc.) | | No built-in history or analytics—any indexing/aggregation you build or outsource | Historical data, joins, aggregations & real-time subscriptions | | Ideal for submitting transactions | Great for real-time data and historical backtesting without running your own indexer | To access Bitquery Tron API you would require your own **[Access Token](https://account.bitquery.io/user/api_v2/access_tokens)** after signup. ### Does Bitquery support Optimism Websocket and Webhooks? Bitquery supports websocket and webhooks; you can convert most GraphQL APIs into GraphQL streams by changing the word `query` to `subscription`. You can monitor this data via a websocket. More docs and code samples are available [here](/docs/subscriptions/websockets/). ## Quick start Run this minimal GraphQL query on **[GraphQL IDE](https://ide.bitquery.io)** after signing up, to fetch the latest 5 DEX trades on Optimism: ```graphql query LatestOptimismTrades { EVM(network: optimism) { DEXTrades(limit: { count: 5 }, orderBy: { descending: Block_Time }) { Block { Time } Trade { Dex { ProtocolName } Buy { AmountInUSD Currency { Symbol } } Sell { AmountInUSD Currency { Symbol } } } Transaction { Hash } } } } ``` ## DEX APIs - [Optimism Dex Trades](./optimism-dextrades) ## Core Optimism APIs - [Balance API](./optimism-balance-api) - [NFT](./optimism-nft) - [Transfers](./optimism-transfers) ## Videos ### Video Tutorial | Get Trending Optimism Tokens Using Bitquery API ### Video Tutorial | Get Optimism DEX Trades Data Using Bitquery API ### Video Tutorial | Get Top Traders on Optimism Using Bitquery API ### Video Tutorial | Get Latest Trades on Optimism Using Bitquery Subscriptions ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Optimism Address Balance API URL: https://docs.bitquery.io/docs/blockchain/Optimism/optimism-balance-api/ Optimism Address Balance API: fetch current and historical Optimism balances with Bitquery GraphQL balance queries. Great for bots, dashboards, and alerts. # Optimism Address Balance API The **Balances** API returns current and historical token balances for an address on Optimism. To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | | -------------- | ------------------------------------------------------------------------------------------- | | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | Examples: [All Token Balances](#balance-of-an-address) · [Native ETH (Optimism)](#native-eth-optimism-balance) · [Balance on a Date](#balance-on-a-specific-date) · [Specific Token](#balance-for-a-specific-token) · [Holder Snapshot](#token-holder-snapshot) ## Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. [Run in IDE](https://ide.bitquery.io/Optimism-Balance-of-an-Address) ```graphql query { EVM(network: optimism, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xacD03D601e5bB1B275Bb94076fF46ED9D753435A" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Native ETH (Optimism) Balance Returns the native ETH balance for a wallet on Optimism (not ERC-20 tokens). Filter with `Currency: { Native: true }` instead of a token contract address. [Run in IDE](https://ide.bitquery.io/optimism-native-balances-address) ```graphql query { EVM(network: optimism, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xacD03D601e5bB1B275Bb94076fF46ED9D753435A" } } Currency: { Native: true } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` **Parameters** - `network: optimism`: Optimism mainnet. - `dataset: combined`: Merges realtime and archive data for the latest balance state. - `Balance.Address`: Wallet address to query. - `Currency.Native: true`: Native ETH on Optimism only (see [Native ETH (Optimism) Balance](#native-eth-optimism-balance)). **Returned fields** - `Currency.Symbol`, `Currency.SmartContract`: Token metadata. - `Balance.Amount`, `Balance.AmountInUSD`: Token balance and USD value (use `selectWhere` to filter non-zero amounts). ## Balance on a Specific Date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. [Run in IDE](https://ide.bitquery.io/optimism-balances-by-date) ```graphql query { EVM(network: optimism, dataset: archive) { Balances( where: { Block: { Date: { till: "2026-05-01" } } Balance: { Address: { is: "0xacD03D601e5bB1B275Bb94076fF46ED9D753435A" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Balance for a Specific Token Add a `Currency.SmartContract` filter. Always use the contract address, not the token name. Use `0x` for native ETH on Optimism, or the ERC-20 contract address for a token. [Run in IDE](https://ide.bitquery.io/optimism-balances-specific-token) ```graphql query { EVM(network: optimism, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xacD03D601e5bB1B275Bb94076fF46ED9D753435A" } } Currency: { SmartContract: { is: "0x23ee2343b892b1bb63503a4fabc840e0e2c6810f" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Token Holder Snapshot The number of unique holders, token supply, and Gini coefficient for the balance amount before a specific timestamp can be derived using the query below. These stats provide a useful holder snapshot for any given time. [Run in IDE](https://ide.bitquery.io/token-holder-snapshot-optimism)
Click to expand GraphQL query ```graphql query { EVM(network: optimism, dataset: archive) { Holders( where: { Currency: { SmartContract: { is: "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58" } } Balance: { Amount: { gt: "0" } LastChangeTime: { till: "2026-05-20T00:00:00Z" } } Holder: { Address: { not: "0x" } } } ) { Balance { LastChangeTime(maximum: Balance_LastChangeTime) } holders: uniq(of: Holder_Address) supply: sum(of: Balance_Amount) gini(of: Balance_Amount) } } } ```
## Balance History by Date Returns balance snapshots over time for an address. Use `dataset: archive`. Order by `Block_Date` descending and use `limit` to paginate. Add `Currency.SmartContract` under `Currency` to filter by a specific token. [Run in IDE](https://ide.bitquery.io/optimism-balances-history-address) ```graphql query { EVM(network: optimism, dataset: archive) { Balances( where: { Balance: { Address: { is: "0xacD03D601e5bB1B275Bb94076fF46ED9D753435A" } } Currency: {} } orderBy: { descending: Block_Date } limit: { count: 100 } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } Block { Date } } } } ``` --- ## Optimism DEX Trades API: Every Swap on Optimism, Pairs, Traders and Prices URL: https://docs.bitquery.io/docs/blockchain/Optimism/optimism-dextrades/ Optimism DEX data with Bitquery GraphQL: live swaps with trader and USD, which DEXs trade, busiest pairs, top traders, token prices and top tokens. # Optimism DEX Trades API: Every Swap on Optimism, Pairs, Traders and Prices Optimism's DEX trading runs through Velodrome, which makes the most swaps and is indexed as `velodrome_v2` and `velodrome_slipstream` (see the [Velodrome API](/docs/blockchain/Optimism/velodrome-api) and [Slipstream API](/docs/blockchain/Optimism/velodrome-slipstream-api) pages), Uniswap v3 and v4, v2-style pairs, and Balancer. Bitquery indexes all of them into the chain cubes, `DEXTrades` for one row per swap and `DEXTradeByTokens` for one row per swap per token, and into the Trading cube, which adds the trader, USD price, market cap and supply on every row for the last month or so. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. Two Optimism details shape the examples: native USDC is `0x0b2c639c533813f4aa9d7837caf62653d097ff85` and the bridged USDC.e is `0x7f5c764cbc14f9669b88837ca1490cca17c31607`, and a few swaps in thin pools carry absurd USD values, so every USD sum here caps a single trade with `Side: { AmountInUSD: { lt: "10000000" } }`. ## Live swaps with trader and USD The [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) of the Trading cube, filtered to the Optimism market. Each message is one swap with the side, the trader, both amounts in USD and the token's supply. Paste it into the [IDE](https://ide.bitquery.io) to run. ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Optimism" } } } }) { Block { Time } Side Trader { Address } Amounts { Base Quote } AmountsInUsd { Base Quote } Pair { Currency { Symbol Id } QuoteCurrency { Symbol } Market { Protocol Address } } Supply { MarketCap } } } } ``` ## Which DEXs trade on Optimism Group the last day by protocol. Saved query [here](https://ide.bitquery.io/trending-pairs-on-optimism). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "trades" } limit: { count: 20 } ) { Trade { Dex { ProtocolFamily ProtocolName } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) traders: uniq(of: Transaction_From) } } } ``` ## The busiest pairs Tokens traded against WETH, USDC or USDC.e over the last day, ranked by USD volume, with distinct buyers and sellers and the latest price. [DEXrabbit](https://dexrabbit.bitquery.io/optimism) shows the same table live. ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { Side: { AmountInUSD: { lt: "10000000" } Currency: { SmartContract: { in: [ "0x4200000000000000000000000000000000000006" "0x0b2c639c533813f4aa9d7837caf62653d097ff85" "0x7f5c764cbc14f9669b88837ca1490cca17c31607" ] } } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 30 } ) { Trade { Currency { Symbol SmartContract } Side { Currency { Symbol } } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) price: Trade { PriceInUSD(maximum: Block_Time) } } } } ``` ![Trending pairs on Optimism](/img/dexrabbit/optimism_trending_pairs.png) ## Latest swaps, live The raw `DEXTrades` stream for the chain: pool-side buy and sell with USD on both, the protocol and the transaction. Saved stream [here](https://ide.bitquery.io/Realtime-optimism-dex-trades-websocket). ```graphql subscription { EVM(network: optimism) { DEXTrades { Block { Time } Trade { Dex { ProtocolName SmartContract } Buy { Currency { Symbol } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol } Amount AmountInUSD } } Transaction { Hash From } } } } ``` ## Top traders on Optimism Rank by `Transaction.From` over the last day. Saved query [here](https://ide.bitquery.io/top-traders-on-optimism). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 50 } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) tokens: uniq(of: Trade_Currency_SmartContract) } } } ``` ![Top traders on Optimism](/img/dexrabbit/optimism_top_traders.png) ## Top traders of one pair Fix the token and the quote. The example is WETH against native USDC over the last day; the saved query used WLD/USDC, a quieter pair that needs a week. Saved query [here](https://ide.bitquery.io/top-traders-for-wld-usdc-pair). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x4200000000000000000000000000000000000006" } } Side: { AmountInUSD: { lt: "10000000" } Currency: { SmartContract: { is: "0x0b2c639c533813f4aa9d7837caf62653d097ff85" } } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 20 } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ![Top traders for a pair](/img/dexrabbit/optimism_top_pair_traders.png) ## Latest price of a token The newest `DEXTradeByTokens` row for a token carries its price in USD and the quote it traded against; the example is WBTC. For a price in a specific quote, filter the quote under `Side` as well, as in the WETH in USDC.e example. Saved queries: [WBTC in USD](https://ide.bitquery.io/Get-latest-price-of-WBTC-in-USD-on-optimism), [WETH in USDC.e](https://ide.bitquery.io/Price-of-WETH-in-terms-of-USDC-on-Optimism). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x68f180fcCe6836688e9084f035309E29Bf0A2095" } } } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Block { Time } Trade { PriceInUSD Price Side { Currency { Symbol } } Dex { ProtocolName } } } } } ``` Change `query` to `subscription` and drop `limit` and `orderBy` to stream each new price; WBTC trades often enough on Optimism for that to update every few minutes. ## Top tokens by trades Tokens ranked by number of trades over the last day, with buyers, sellers, pools and volume. Saved query [here](https://ide.bitquery.io/top-tokens-on-optimism). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "trades" } limit: { count: 50 } ) { Trade { Currency { Symbol SmartContract } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) pools: uniq(of: Trade_Dex_SmartContract) } } } ``` ![Top tokens on Optimism](/img/dexrabbit/optimism_top_tokens.png) ## Related pages - [Optimism API hub](/docs/blockchain/Optimism/) - [Uniswap v4 on Optimism](/docs/blockchain/Optimism/uniswap-v4-api) - [Velodrome API](/docs/blockchain/Optimism/velodrome-api) - [Velodrome Slipstream API](/docs/blockchain/Optimism/velodrome-slipstream-api) - [Optimism transfers API](/docs/blockchain/Optimism/optimism-transfers) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) - [DEXTrades vs DEXTradeByTokens vs Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades) --- ## Optimism NFT API: ERC-721 Transfers, Collections and Owners URL: https://docs.bitquery.io/docs/blockchain/Optimism/optimism-nft/ Query and stream ERC-721 transfers on Optimism with Bitquery GraphQL: latest transfers, one collection or token id, mints, senders and receivers. # Optimism NFT API: ERC-721 Transfers, Collections and Owners NFTs on Optimism are ERC-721 and ERC-1155 tokens, and Bitquery indexes every transfer of them in the `Transfers` cube under `EVM(network: optimism)` with `Currency.Fungible` set to `false`. Each row carries the collection contract, the token id, the sender, the receiver and the transaction, so one cube answers "what NFTs moved on Optimism just now", "who owns token 42 of this collection" and "every transfer of a collection since launch". Queries return the latest rows; changing `query` to `subscription` streams new transfers as they land. Every example runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. ## Latest NFT transfers on Optimism The most recent NFT transfers across all collections. Expect liquidity-position NFTs from DEXs such as Velodrome among them; they are ERC-721 tokens too. ```graphql { EVM(network: optimism) { Transfers( where: { Transfer: { Currency: { Fungible: false } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Currency { Name Symbol SmartContract } Id Sender Receiver } } } } ``` ## Transfers of one collection, as they happen Filter on the collection contract. The example is the Velodrome Slipstream position NFT, a collection that moves every few seconds, so the stream shows rows at once; the saved IDE subscription [here](https://ide.bitquery.io/Transfers-of-a-particular-NFT#) uses another contract. A quiet collection can go hours between transfers, so test a filter as a query first with `limit` and `orderBy` added. ```graphql subscription { EVM(network: optimism) { Transfers( where: { Transfer: { Currency: { Fungible: false SmartContract: { is: "0x416b433906b1b72fa758e166e239c43d68dc6f29" } } } } ) { Block { Hash Number } Transfer { Amount Currency { Name Symbol Native } Sender Receiver } } } } ``` ## Current owner of each token The Holders cube does not carry per-collection balances for NFTs on Optimism, so read ownership from transfers instead: the receiver of a token's latest transfer is its current owner. `limitBy` on the token id keeps one row per token, newest first. Filter `Id` to check one token. ```graphql { EVM(network: optimism) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x416b433906b1b72fa758e166e239c43d68dc6f29" } } } } orderBy: { descending: Block_Time } limitBy: { by: Transfer_Id, count: 1 } limit: { count: 20 } ) { Block { Time } Transfer { Id Receiver Sender } } } } ``` ## Useful filters - One token: `Id: { is: "42" }` inside `Transfer`. - Mints: `Sender: { is: "0x0000000000000000000000000000000000000000" }`. - One wallet: `Receiver` or `Sender` set to the address. - History: add `dataset: archive` or `combined` to the `EVM` root; without it the query reads the realtime window. ## Related pages - [Optimism API hub](/docs/blockchain/Optimism/) - [Optimism transfers API](/docs/blockchain/Optimism/optimism-transfers) - [Ethereum NFT collection API](/docs/blockchain/Ethereum/nft/nft-collection-api) - [Transfers cube](/docs/cubes/transfers-cube) --- ## Optimism Transfers API: Token and ETH Transfers, Whale Alerts, Backfills URL: https://docs.bitquery.io/docs/blockchain/Optimism/optimism-transfers/ Query and stream Optimism token and ETH transfers with Bitquery GraphQL: large USDT moves, one wallet, NFT transfers and gap-free backfills. # Optimism Transfers API: Token and ETH Transfers, Whale Alerts, Backfills Every ERC-20, ERC-721, ERC-1155 and native ETH transfer on Optimism lands in the `Transfers` cube under `EVM(network: optimism)`, with sender, receiver, amount, USD value where a price exists, the token's contract and symbol, and the transaction that carried it. The same filters run as a query for the latest rows or as a subscription for a live feed, and `dataset: combined` on the root reaches history. Every example runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. ## Large transfers of one token USDT on Optimism, transfers of 10,000 or more in the last day. Saved as a live stream [here](https://ide.bitquery.io/Whale-transfers-of-USDT-on-optimism); the query form below is the same filter with a window and a limit. ```graphql { EVM(network: optimism) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58" } } Amount: { ge: "10000" } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol Name SmartContract } } Transaction { Hash } } } } ``` For an alert, change `query` to `subscription` and drop `Block`, `limit` and `orderBy`; each qualifying transfer arrives as it is indexed. ## Transfers of one wallet Filter `Sender` or `Receiver`, or both with an `any` block, on the address. Saved stream [here](https://ide.bitquery.io/Sender-is-a-particular-address); a wallet that is idle streams nothing, so run the query form with `dataset: combined` first to see what it has done. ```graphql { EVM(network: optimism, dataset: combined) { Transfers( where: { Transfer: { Sender: { is: "0xEbe80f029b1c02862B9E8a70a7e5317C06F62Cae" } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Amount AmountInUSD Currency { Name SmartContract Native Symbol } Receiver Sender } Transaction { Hash } } } } ``` ## NFT transfers `Currency.Fungible: false` keeps ERC-721 and ERC-1155 rows only; `Id` is the token id and `URI` the metadata link. Saved stream [here](https://ide.bitquery.io/NFT-Token-Transfers-API_1); the [Optimism NFT API](/docs/blockchain/Optimism/optimism-nft) page covers collections and holders. ```graphql { EVM(network: optimism) { Transfers( where: { Transfer: { Currency: { Fungible: false } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Currency { Name Symbol SmartContract } Id Sender Receiver } } } } ``` ## Deterministic pagination for backfilling To load transfers into your own index without gaps or repeats, page in a fixed order. The composite `orderBy` over block number, transaction index, call index, log index, transfer index and type positions every transfer uniquely; move `offset` by `count` on each request. A single request can return up to 25,000 rows. This ordering runs on the realtime window; on the `archive` dataset, order by `Block_Number` and page through one block range at a time instead. Saved [here](https://ide.bitquery.io/Reliable-transfer-api). ```graphql { EVM(network: optimism) { Transfers( where: { Transfer: { Success: true } } orderBy: { ascending: [ Block_Number, Transaction_Index, Call_Index, Log_Index, Transfer_Index, Transfer_Type ] } limit: { count: 10, offset: 0 } ) { Block { Time Number } Transaction { Hash From Index } Transfer { Amount AmountInUSD Sender Receiver Index Currency { Symbol Name SmartContract Decimals Native } } Call { Index } Log { LogAfterCallIndex Index } Transfer { Type } } } } ``` Bound each pass with `Block: { Number: { ge: ..., le: ... } }` so the offset stays small per range. ## Related pages - [Optimism API hub](/docs/blockchain/Optimism/) - [Optimism NFT API](/docs/blockchain/Optimism/optimism-nft) - [Transfers cube](/docs/cubes/transfers-cube) - [Data coverage and retention](/docs/graphql/data-coverage-retention) --- ## Optimism Uniswap v4 API: Pools by PoolId, Swaps, Traders and Reserves URL: https://docs.bitquery.io/docs/blockchain/Optimism/uniswap-v4-api/ Uniswap v4 on Optimism with Bitquery GraphQL: the v4 pools of USDC by PoolId, live swaps, the ETH/USDC pool's stats, top traders and reserves. # Optimism Uniswap v4 API: Pools by PoolId, Swaps, Traders and Reserves Uniswap v4 on Optimism is small next to Base or BNB Chain: a few hundred swaps an hour, most of them in ETH/USDC, in the pool that converts between native USDC and the bridged USDC.e, and in OP/USDC. That shapes the queries on this page: windows are a day rather than an hour, and the stream examples pick pools that move. The venue itself works like v4 everywhere: one PoolManager, `0x9a13f98cb987694c9f086b1f5eb990eea8264ec3`, holds every pool; a pool is a `PoolId`, the hash of its tokens, fee, tick spacing and hook; and on raw swap rows the buyer and seller are both the PoolManager, so the trader is `Transaction.From`. Every example runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. The worked token is native USDC, `0x0b2c639c533813f4aa9d7837caf62653d097ff85`, and the worked pool is ETH/USDC, `PoolId 0x51bf4cc5b8d9f7f759e41f572fe2a25bc2aeb42432bf12544a350595e5c8bb43`. ## The v4 pools of USDC on Optimism Group `DEXTradeByTokens` by `PoolId` with USDC in `Currency`. The rows are its pools with the counter token, trade count and USD volume; the ETH pool and the USDC.e pool lead. This is where a `PoolId` for the other queries comes from. Saved query [here](https://ide.bitquery.io/get-virtual-pool-address-for-a-token-on-uniswap-v4-optimism). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } Currency: { SmartContract: { is: "0x0b2c639c533813f4aa9d7837caf62653d097ff85" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "count" } limit: { count: 20 } ) { Trade { PoolId Side { Currency { Symbol SmartContract } } } count volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Latest swaps in the ETH/USDC pool Saved query [here](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-optimism). ```graphql { EVM(network: optimism) { DEXTrades( where: { Trade: { PoolId: { is: "0x51bf4cc5b8d9f7f759e41f572fe2a25bc2aeb42432bf12544a350595e5c8bb43" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Trade { Buy { Currency { Symbol } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Live swaps across all v4 pools on Optimism The protocol filter as a subscription. Messages arrive every few seconds, which is slow enough to watch by eye. Saved stream [here](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-optimism). ```graphql subscription { EVM(network: optimism) { DEXTrades(where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v4" } } } }) { Block { Time } Trade { PoolId Buy { Currency { Symbol SmartContract } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol SmartContract } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## Daily stats of the pool Trades, distinct buyers and sellers, and USD volume by direction for the token you name. Saved query [here](https://ide.bitquery.io/trade-stats-for-a-token-pair-on-uniswap-v4-optimism). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x51bf4cc5b8d9f7f759e41f572fe2a25bc2aeb42432bf12544a350595e5c8bb43" } Currency: { SmartContract: { is: "0x0b2c639c533813f4aa9d7837caf62653d097ff85" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol } Side { Currency { Symbol } } } trades: count buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) volumeUsd: sum(of: Trade_Side_AmountInUSD) buyVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) sellVolumeUsd: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) } } } ``` ## Top traders of the pool Rank by `Transaction.From`, since the PoolManager appears as buyer and seller on every raw v4 swap. `bought` sums the token the trader received and `sold` the token it paid; `Side.Type` describes the counter-side, which is why the conditions look swapped. On Optimism a handful of bots account for most of the pool's trades. Saved queries: [top buyers](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-optimism), [top sellers](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-pool-optimism). ```graphql { EVM(network: optimism) { DEXTradeByTokens( where: { Trade: { PoolId: { is: "0x51bf4cc5b8d9f7f759e41f572fe2a25bc2aeb42432bf12544a350595e5c8bb43" } Currency: { SmartContract: { is: "0x0b2c639c533813f4aa9d7837caf62653d097ff85" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 20 } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Reserves of the pool `DEXPoolEvents` gives the reserves the PoolManager holds for the pool after each change, rebuilt from the concentrated positions around the current price and priced in USD. Filter on `PoolId`, or keep the protocol name alone to follow every v4 pool on Optimism. ```graphql { EVM(network: optimism) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0x51bf4cc5b8d9f7f759e41f572fe2a25bc2aeb42432bf12544a350595e5c8bb43" } } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } } } } ``` ## Related pages - [Optimism DEX trades API](/docs/blockchain/Optimism/optimism-dextrades) - [Optimism transfers API](/docs/blockchain/Optimism/optimism-transfers) - [Uniswap v4 on Ethereum](/docs/blockchain/Ethereum/dextrades/uniswap-v4-api) - [Uniswap v4 on Base](/docs/blockchain/Base/uniswap-v4-api) - [Uniswap v4 on Arbitrum](/docs/blockchain/Arbitrum/uniswap-v4-api) --- ## Optimize Bitquery GraphQL Queries URL: https://docs.bitquery.io/docs/graphql/optimizing-graphql-queries/ Optimize Bitquery GraphQL Queries in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # GraphQL query optimization for APIs GraphQL is an open-source query language for APIs. It allows clients to define the required data structure, and the server responds with only that data. This allows for more efficient and flexible communication between the client and server, as well as enabling better performance and easier development of APIs. GraphQL query optimization is a crucial aspect of utilizing V2 APIs to their full potential. By optimizing your queries, you can significantly reduce the amount of time and resources required to retrieve the data you need. In this section, we will see how to optimize your V2 API queries. ### Understanding Datasets Choosing the right dataset is critical for both correctness and performance. We offer three datasets with different guarantees and latency characteristics: - **realtime**: Default if omitted. Contains the most recent data (a short window that differs per chain and cube, from about 12 hours to about 30 days; see [Data coverage & retention](/docs/graphql/data-coverage-retention/)) and is optimized for low-latency reads and subscriptions. - **archive**: Full historical data from genesis - **combined**: Executes the same query against both realtime and archive and merges results. Useful when you need a continuous view that spans “now” into history, but it’s slower. Practical guidance: Examples: ```graphql # Latest trades with minimal delay EVM(dataset: realtime, network: eth) { DEXTrades(limit: { count: 100 }) { Trade { ... } } } # Historical holders snapshot EVM(dataset: archive, network: eth) { Holders(date: "2024-01-01") { uniq(of: Holder_Address) } } # One-shot view spanning history and near-real-time EVM(dataset: combined, network: bsc) { Balances(limit: { count: 1000 }) { ... } } ``` ### Understanding limits in GraphQL In V2 APIs, it's crucial to note the implicit default limit applied when a specific limit isn't explicitly defined within a query. [By default, this limit restricts the number of records returned to 10,000](/docs/start/errors/#limits). This safeguard is in place to prevent excessive resource consumption, ensuring the efficient processing of queries. However, to tailor data retrieval according to specific needs, V2 APIs provide the flexibility to set custom limits using the 'limit' parameter. This filter allows you to refine your query results, ensuring that only the necessary records are returned, reducing unnecessary point consumption risk. Let's take an example, the below query retrieves information about calls on the BNB network. For each call, it retrieves the internal call and transaction information. The number of responses is restricted to 20 by the limit field. ```graphql query CustomLimitQuery { EVM(dataset: realtime, network: bsc) { Calls(limit: { count: 20 }) { Call { LogCount InternalCalls } Transaction { Gas Hash From To Type Index } Block { Date } } } } ``` ### Understanding limitBy In addition to the 'limit' parameter, V2 APIs also offer the 'limitBy' parameter, which allows you to set limits based on specific criteria. For example, you can set a limit on the number of records returned based on a certain attribute or field. This helps to further refine your queries and reduce unnecessary resource consumption. Using the 'limitBy' parameter is particularly useful when dealing with large datasets, as it allows you to retrieve only the data that is relevant to your needs. Below is an example query that retrieves information about limitBy. For each call, it retrieves the internal call and transaction information. The number of responses is limited to 10 by the 'limit' field. ```graphql { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } } } limit: { count: 10 } limitBy: { by: Trade_Sell_Currency_SmartContract, count: 1 } ) { Trade { Dex { ProtocolName OwnerAddress ProtocolVersion Pair { SmartContract Name Symbol } } Buy { Currency { Name SmartContract } } Sell { Currency { Name SmartContract } } } } } } ``` ### Understanding Indexes In each table, certain columns are used as indexes, you can use those columns to sort in `orderby` field to improve time to response. A detailed list is available in this [Indexes](/docs/graphql/indexed-fields-reference/) page. ### Sorting Queries in GraphQL Sorting can be done by using the `order by` argument. This argument takes a list of fields to sort by, as well as the direction of the sorting (ascending or descending). For example, if you wanted to sort a list of users by their age in descending order, your GraphQL query looks like below. ```graphql query ($network: evm_network, $till: String!, $token: String!, $limit: Int) { EVM(network: $network, dataset: archive) { Holders( date: $till orderBy: { descending: Balance_Amount } limit: { count: $limit } where: { Currency: { SmartContract: { is: $token } } } ) { Holder { Address } Balance { Amount } } Blocks(limit: { count: 1 }) { ChainId } } } ``` ### Sort by Metrics Sorting by metrics in GraphQL can be achieved by using the `order by` argument along with specific metrics. This allows you to sort data based on certain criteria, such as popularity, rating, or relevance. Metric-based sorting is a powerful feature in GraphQL that allows you to sort data based on a specific metric or criteria. Let me give you some examples to help explain how this works. ```graphql { EVM(network: bsc, dataset: realtime) { Transfers( limit: { count: 10 } orderBy: { descendingByField: "received" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Transfer: { Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } } ) { Transfer { Receiver } received: sum(of: Transfer_Amount) } } } ``` In the above example, we use the `sum` metric to total the USDT each address received on BNB Chain in the last hour. We give an [alias](/docs/graphql/metrics/alias/) to the sum field (`received`) and sort the responses from highest to lowest with `descendingByField`. ### Filtering data in GraphQL queries Filtering data in GraphQL queries is done by using the `where` argument along with specific conditions. This allows you to retrieve only the data that meets certain criteria, such as a specific date range, a certain value, or a particular category. Filtering data is an important feature in GraphQL that allows you to narrow down the results of a query to only the relevant information you need. Let me give you an example to help illustrate how this works. We will look at how to use filters, with the help of the below example. ```graphql { EVM(dataset: combined, network: eth) { buyside: DEXTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } Seller: { is: "0x1111111254eeb25477b68fb85ed929f73a960582" } } } Block: { Time: { till: "2023-03-05T05:15:23Z", since: "2023-03-03T01:00:00Z" } } } ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } } Sell { Amount Buyer Currency { Name SmartContract Symbol } } } } } } ``` In the above GraphQL query, filtering is performed using the `where` argument in conjunction with conditions defined for the Trade and Block. For the `Trade` filtering, two conditions need to be satisfied. - The `Buy` property's `Currency` should have a `SmartContract` value of "0x5283d291dbcf85356a21ba090e6db59121208b44", and - The `Seller` property should be "0x1111111254eeb25477b68fb85ed929f73a960582". The `Block` filtering is based on the `Time` property. The `Time` should fall within a certain range - specifically, from "2023-03-03T01:00:00Z" to "2023-03-05T05:15:23Z". This combination of filters narrows down the results of `DEXTrades` to only include trades that meet all of the specified conditions within the given time frame. This will return only the posts that meet this criteria, and will only include their title and content fields in the response. #### Exploring Filter Types and Operators Filters play a crucial role in data retrieval systems by narrowing down search results to specific data sets. In the realm of databases, a filter acts as a condition applied to a query, fetching only the records that meet that specific condition. A variety of filter types and operators are available, allowing you to customize your search queries and obtain more accurate results. Some common filter types include: 1. Text filters: These filters enable you to search for specific text or words within a given field. 2. Numeric filters: These filters allow you to search for records based on numeric values within a specified range. Numeric filter types encompass: - Equals: represented by `is` or `=` - Not equals: represented by `NOT IN` - Greater than: represented by `gt` - Less than: represented by `lt` - Greater than or equal to: represented by `ge` - Less than or equal to: represented by `le` These operators aid in filtering data based on numeric values. 3. Date filters: These filters enable you to search for records based on specific dates or date ranges. 4. Boolean filters: These filters facilitate the search for records based on true/false values. For instance, consider the following query. Here, we utilize a string filter to narrow down the token contract to `0x23581767a106ae21c074b2276D25e5C3e136a68b` and a numeric filter with `ge` (greater than or equal to) 50, indicating a minimum balance requirement: ```graphql { EVM(dataset: archive, network: eth) { greater_than_50: Holders( date: "2023-10-23" where: { Currency: { SmartContract: { is: "0x23581767a106ae21c074b2276D25e5C3e136a68b" } }, Balance: { Amount: { ge: "50" } } } ) { uniq(of: Holder_Address) } greater_than_or_equal_to_50: Holders( date: "2023-10-23" where: { Currency: { SmartContract: { is: "0x23581767a106ae21c074b2276D25e5C3e136a68b" } }, Balance: { Amount: { gt: "50" } } } ) { uniq(of: Holder_Address) } } } ``` ### Running the same query for multiple addresses Let's say you have built a query that filters results using an address filter `{Address: {is: $token}`. To run the same query for multiple addresses, you can change the filter to `{Address: {in: ["A","B","C"]}` where `A`, `B`, `C` are all representative of addresses. --- ## Orca DEX API — Solana Liquidity Pools & Trades URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-orca-dex-api/ Orca DEX on Solana: new pools, real-time trades, token prices, OHLC, add and remove liquidity, and fee and reward collection instructions. # Orca DEX API :::tip Need real-time Orca data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Orca swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Orca data older than ~30 days**, raw per-swap detail, or call / event context. Orca is one of the venues covered by our [Solana DEX API](https://bitquery.io/products/solana-dex-api), which unifies Raydium, Orca, Meteora, Pump.fun and Jupiter trades in one schema. ::: In this section, we'll show you how to access information about Orca DEX data using Bitquery APIs. :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## Latest Pools Created On Orca To retrieve the newest pools created on Orca DEX, we will utilize the Solana instructions API/Websocket. We will specifically look for the latest instructions from Orca's Whirlpool program, identified by the program ID `whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc`.  Whenever a new pool is created on Orca, it triggers the `initializePool` instructions. The pool address can be obtained from the program addresses listed in the transaction's instructions. For instance, Index 1 and 2 represent the tokens involved in the pool, while Index 4 is for the pool's address. Note that the indexing starts from 0. You can run this query using this [link](https://ide.bitquery.io/Latest-pool-created-on-Orca---Websocket_1). ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Method: { is: "initializePool" } Address: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } } } ) { Instruction { Program { Method Arguments { Name Value { __typename ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } Accounts { Address } } Transaction { Signature } } } } ``` ## Pair Creation Time For A Specific Pair You can use the following query to get the pair creation time for a specific pair on Orca DEX on Solana. But you need to use the keyword `query`. You can run this query using [this link](https://ide.bitquery.io/pair-creation-time-for-a-specific-pair-on-Orca). ```graphql { Solana { Instructions( where: {Instruction: {Program: {Method: {in: ["initializePool", "initializePoolV2", "initializePoolWithAdaptiveFee"]}, Address: {is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"}}, Accounts: {includes: {Address: {is: "Bg8rob51iTgMBi1hmRhZV8hzaHU5zP77Pd61UpbzyzGd"}}}}, Transaction: {Result: {Success: true}}} ) { Transaction { Signature } Block { Time } } } } ``` ## Realtime Trades On Orca DEX API To access a real-time stream of trades for Solana Orca DEX, [check out this GraphQL subscription (WebSocket)](https://ide.bitquery.io/Orca-DEX-Trades-Websocket). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } } } ) { Transaction { Signature } Block { Time } Trade { Dex { ProgramAddress ProtocolName ProtocolFamily } Buy { Account { Address } Amount AmountInUSD Currency { MintAddress Symbol Name } Price PriceInUSD } Sell { Account { Address } Amount AmountInUSD Currency { MintAddress Symbol Name } Price PriceInUSD } } } } } ``` ## Latest Trades For A Specific Currency On Solana Orca DEX If you want to monitor [trades for a specific currency on Orca DEX](https://ide.bitquery.io/Orca-DEX-Trades-for-a-specific-currency-Websocket), you can use the stream provided. Input the currency's mint address; for example, in the query below, we use the WSOL token's Mint address to fetch buys of the WSOL token. By setting the limit to 1, you will receive the most recent trade, which reflects the latest price of the token. Execute this query [by following this link](https://ide.bitquery.io/Orca-DEX-Trades-for-a-specific-currency-Websocket). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } Buy: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } } ) { Transaction { Signature } Block { Time } Trade { Dex { ProgramAddress ProtocolName ProtocolFamily } Buy { Account { Address } Amount AmountInUSD Currency { MintAddress Symbol Name } Price PriceInUSD } Sell { Account { Address } Amount AmountInUSD Currency { MintAddress Symbol Name } Price PriceInUSD } } } } } ``` ## Latest Price Of A Token You can use the following query to get the latest price of a token, we have used WSOL address here in the below example. We are getting realtime price of WSOL on Orca DEX on Solana in different pools. You can run this query using [this link](https://ide.bitquery.io/Price-of-a-token-on-Orca). ```graphql subscription{ Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}, Dex: {ProgramAddress: {is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"}}}} ) { Block { Time } Trade { Amount PriceAgainstSideCurrency: Price Currency { Symbol Name MintAddress } Side { Amount Currency { Symbol Name MintAddress } } Dex { ProgramAddress ProtocolFamily ProtocolName } Market { MarketAddress } Order { LimitAmount LimitPrice OrderId } } } } } ``` ## Orca OHLC APIs If you want to get OHLC data for any specific currency pair on Orca DEX, you can use [this api](https://ide.bitquery.io/Orca-OHLC-for-specific-pair_5). Only use this API as `query` and not `subscription` websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Dex: { ProgramAddress: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } PriceAsymmetry: { lt: 0.1 } } } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Track Latest Add Liquidity Transactions On Orca DEX You can also track Add Liquidity transactions in real time on Orca DEX from Orca API using instructions. Firstly, you can use this [query](https://ide.bitquery.io/Get-all-methods-of-Orca-Program#) to get all the methods of Orca program to deduce which program method is responsible for add liquidity transactions. The method we want to filter for turns out to be `increaseLiquidity`. If you want to track latest liquidity additions in Orca pools, you can use [this Websocket api](https://ide.bitquery.io/Websocket-for-add-Liquidity-instruction-on-Solana-Orca-DEX_3). In the response, mint under 6th and 7th addresses in the Accounts array gives you the Token A and Token B respectively of the pool in which liquidity is added. ```graphql subscription { Solana { Instructions( orderBy: { descending: Block_Time } where: { Instruction: { Program: { Address: { in: [ "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" "increaseLiquidityV2" ] } Method: { is: "increaseLiquidity" } } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes InternalSeqNumber Index ExternalSeqNumber Depth CallerIndex Data CallPath BalanceUpdatesCount Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Name Method Parsed } } Transaction { Signature } } } } ``` ## Track Latest Remove Liquidity Transactions On Orca DEX You can also track Remove Liquidity transactions in real time on Orca DEX from Orca API using instructions. Firstly, you can use this [query](https://ide.bitquery.io/Get-all-methods-of-Orca-Program#) to get all the methods of Orca program to deduce which program method is responsible for remove liquidity transactions. The method we want to filter for turns out to be `decreaseLiquidity`. If you want to track latest liquidity removals in Orca pools, you can use [this Websocket api](https://ide.bitquery.io/Websocket-for-remove-Liquidity-instruction-on-Solana-Orca-DEX_1#). In the response, mint under 6th and 7th addresses in the Accounts array gives you the Token A and Token B respectively of the pool in which liquidity is removed. ```graphql subscription { Solana { Instructions( orderBy: { descending: Block_Time } where: { Instruction: { Program: { Address: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } Method: { is: "decreaseLiquidity" } } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes InternalSeqNumber Index ExternalSeqNumber Depth CallerIndex Data CallPath BalanceUpdatesCount Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Name Method Parsed } } Transaction { Signature } } } } ``` ## Track Collect Fees Instruction Calls On Orca DEX Using the query below you can get the addresses in the `Instruction Accounts[]` array for the `Collect Fees` instruction calls on Orca DEX. You can test the query [here](https://ide.bitquery.io/Websocket-for-collect-fees-instruction-on-Solana-Orca-DEX_1). ```graphql subscription { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"}, Method: {in: ["collectFees", "collectFeesV2"]}}}} ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes InternalSeqNumber Index ExternalSeqNumber Depth CallerIndex Data CallPath BalanceUpdatesCount Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Name Method Parsed } } Transaction { Signature } } } } ``` ## Track Update Fees And Rewards Instruction Calls On Orca DEX Using the query below you can get the addresses in the `Instruction Accounts[]` array for the `Update Fees and Rewards` instruction calls on Orca DEX. You can test the query [here](https://ide.bitquery.io/Websocket-for-update-fees-and-rewards-instruction-on-Solana-Orca-DEX_1). ```graphql subscription { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"}, Method: {is: "updateFeesAndRewards"}}}} ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes InternalSeqNumber Index ExternalSeqNumber Depth CallerIndex Data CallPath BalanceUpdatesCount Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Name Method Parsed } } Transaction { Signature } } } } ``` ## Track Collect Reward Instruction Calls On Orca DEX Using the query below you can get the addresses in the `Instruction Accounts[]` array for the `Collect Reward` instruction calls on Orca DEX. You can test the query [here](https://ide.bitquery.io/Websocket-for-collectReward-and-rewards-instruction-on-Solana-Orca-DEX). ```graphql subscription { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"}, Method: {in: ["collectReward", "collectRewardV2"]}}}} ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes InternalSeqNumber Index ExternalSeqNumber Depth CallerIndex Data CallPath BalanceUpdatesCount Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Name Method Parsed } } Transaction { Signature } } } } ``` ## Video Tutorial | How To Track Latest Trades, Latest Price Of A Token On Solana Orca DEX ## Video Tutorial | How To Track Latest Created Liquidity Pools, OHLC Data Of A Specific Pair On Solana Orca DEX ## Video Tutorial | How To Track Add Liquidity And Remove Liquidity Transactions On Solana Orca DEX --- ## Pair Creation Time API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/pair-creation-time/ Pair Creation Time API: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. See examples in the Bitquery IDE. # Pair Creation Time API ## Pair Creation Time for a Specific Pair Let's see how we can get pair creation time for a specific pair. We will use Events API for this. Filter for `PairCreated` event and also put one more filter, for which pair address you want the creation time. We have used `0x5c6919B79FAC1C3555675ae59A9ac2484f3972F5` pair address in our example. Open this query on our GraphQL IDE using this [link](https://ide.bitquery.io/when-a-pair-was-created-for-EVM). ```graphql query MyQuery { EVM(network: eth, dataset: combined) { Events( where: { Log: { Signature: { Name: { is: "PairCreated" } } } TransactionStatus: { Success: true } Arguments: { includes: { Value: { Address: { is: "0x5c6919B79FAC1C3555675ae59A9ac2484f3972F5" } } } } } ) { Block { Time } Transaction { Hash } } } } ``` ## Track newly created pairs on uniswap v3 You can track newly created pairs on uniswap v3. Open this query on our GraphQL IDE using this [link](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3_9). ```graphql subscription { EVM(network: eth) { Events( orderBy: { descending: Block_Number } limit: { count: 10 } where: { Log: { SmartContract: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } Signature: { Name: { is: "PoolCreated" } } } } ) { Log { Signature { Name Parsed Signature } SmartContract } Transaction { Hash } Block { Date Number } Arguments { Type Value { ... on EVM_ABI_Boolean_Value_Arg { bool } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Integer_Value_Arg { integer } } Name } } } } ``` --- ## PancakeSwap Infinity API on BNB Chain: Swaps, Pools by PoolId, Prices, Traders URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-pancakeswap-infinity-api/ PancakeSwap Infinity on BNB Chain via Bitquery GraphQL: live swaps with USD, busiest pools by PoolId, a token's price, OHLC, volume and top traders. # PancakeSwap Infinity API on BNB Chain: Swaps, Pools by PoolId, Prices, Traders PancakeSwap Infinity keeps all of its pools inside one manager contract on BNB Chain, `0xa0ffb9c1ce1fe56963b0321b32e7a0302114058b`, the same singleton design as Uniswap v4. In Bitquery's cubes that means the protocol name `pancakeswap_infinity` selects the venue, `Trade.PoolId` selects a pool, and `Dex.SmartContract` is the manager on every row. Infinity is one of the busiest venues on the chain, and stablecoin pairs such as USDT/KII are among its most traded markets. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked token is POWER, `0x9dc44ae5be187eca9e2a67e33f27a4c91cea1223`, and the worked pool is USDT/KII, `PoolId 0xf43fdb854021ddeb41e06ac1d6e5df475197038ba5d3cba147f469a56870cd1b`. Bitquery also indexes PancakeSwap v2 and v3 on BNB Chain; those are on the [PancakeSwap API](/docs/blockchain/BSC/pancake-swap-api/) page. ## Live swaps with USD on every row The Trading cube streams every Infinity swap with the trader, USD amounts and the token's market cap. Saved stream [here](https://ide.bitquery.io/Trading-API-PancakeSwap-Infinity-Trades-BSC). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Binance Smart Chain" }, Protocol: { is: "pancakeswap_infinity" } } } } ) { Block { Time } Side Trader { Address } Price PriceInUsd AmountsInUsd { Base Quote } Pair { Currency { Symbol } QuoteCurrency { Symbol } Pool { Id } } Supply { MarketCap } } } } ``` ## Latest swaps on Infinity The chain cube view: what the pool received and paid out, with USD on both sides and the PoolId. Saved query [here](https://ide.bitquery.io/pancakeswap-infinity-trades-on-bsc). ```graphql { EVM(network: bsc) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Trade { PoolId Buy { Currency { Symbol SmartContract } Amount AmountInUSD PriceInUSD } Sell { Currency { Symbol SmartContract } Amount AmountInUSD } } Transaction { From Hash } } } } ``` ## The busiest Infinity pools Group by `PoolId` over the last day. Each row is one pool with the token, the trade count and USD volume; the single-trade USD cap keeps thin-pool outliers out of the sums. ```graphql { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "pancakeswap_infinity" } } Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "trades" } limit: { count: 20 } ) { Trade { PoolId Currency { Symbol SmartContract } Side { Currency { Symbol } } } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Price of a token on Infinity The newest `DEXTradeByTokens` row for the token carries its price in the quote and in USD, plus the pool it traded in. Saved query [here](https://ide.bitquery.io/Get-Latest-Price-of-a-token-on-PancakeSwap-Infinity_1). ```graphql { EVM(network: bsc) { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { SmartContract: { is: "0x9dc44ae5be187eca9e2a67e33f27a4c91cea1223" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } } ) { Block { Time } Trade { Price PriceInUSD PoolId Currency { Symbol Name SmartContract Decimals } Side { Currency { Symbol } } } } } } ``` The same row answers the metadata question, so the saved [token metadata](https://ide.bitquery.io/get-metadata-for-bsc-pancakeswap-infnity-token) query is this one with the price fields removed. ## Hourly OHLC in USD One-hour candles for the last day. `PriceAsymmetry` below 0.1 drops trades whose two sides disagree on price, which cleans candles on thin pools. Saved query [here](https://ide.bitquery.io/OHLC-on-bsc-pancakeswap-infinity). ```graphql { EVM(network: bsc) { DEXTradeByTokens( orderBy: { descendingByField: "Block_testfield" } where: { Trade: { Currency: { SmartContract: { is: "0x9dc44ae5be187eca9e2a67e33f27a4c91cea1223" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } PriceAsymmetry: { lt: 0.1 } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 24 } ) { Block { testfield: Time(interval: { in: hours, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) } count } } } ``` ## Volume, bought and sold Totals for the token over a day. `Side.Type` describes the counter-side of each trade, so the token was bought where the side was sold. Saved query [here](https://ide.bitquery.io/trade_volume_bsc_pancakeswap_infinity). ```graphql { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x9dc44ae5be187eca9e2a67e33f27a4c91cea1223" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { trades: count volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Top traders of a token Rank by `Transaction.From`, the account that sent the swap, since the manager contract appears as buyer and seller on raw Infinity rows. Saved query [here](https://ide.bitquery.io/top-traders-of-a-token-on-pancakeswap_1). ```graphql { EVM(network: bsc) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 20 } where: { Trade: { Currency: { SmartContract: { is: "0x9dc44ae5be187eca9e2a67e33f27a4c91cea1223" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Transaction { From } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` ## Most bought and most sold tokens on Infinity One query, sorted on `bought` for the buy side; sort on `sold` for the other list. Saved queries: [top bought](https://ide.bitquery.io/top-bought-tokens-on-pancakeswap_infinity_1), [top sold](https://ide.bitquery.io/top-sold-tokens-on-pancake-infinty_1). ```graphql { EVM(network: bsc) { DEXTradeByTokens( orderBy: { descendingByField: "bought" } limit: { count: 20 } where: { Trade: { Dex: { ProtocolName: { is: "pancakeswap_infinity" } } Side: { AmountInUSD: { lt: "10000000" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol SmartContract } } bought: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Side_AmountInUSD, if: { Trade: { Side: { Type: { is: buy } } } }) trades: count } } } ``` ## Reserves of a pool `DEXPoolEvents` emits the reserves in USD after every change; filter on the `PoolId`. The [BNB Chain liquidity API](/docs/blockchain/BSC/bsc-liquidity-api) has the stream form and the other pool queries. ```graphql { EVM(network: bsc) { DEXPoolEvents( where: { PoolEvent: { Pool: { PoolId: { is: "0xf43fdb854021ddeb41e06ac1d6e5df475197038ba5d3cba147f469a56870cd1b" } } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } PoolEvent { Pool { CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } AtoBPrice } } } } ``` ## Related pages - [PancakeSwap API on BNB Chain](/docs/blockchain/BSC/pancake-swap-api/) - [Uniswap v4 on BNB Chain](/docs/blockchain/BSC/uniswap-v4-api) - [BNB Chain liquidity API](/docs/blockchain/BSC/bsc-liquidity-api) - [BNB Chain DEX trades API](/docs/blockchain/BSC/bsc-dextrades) - [Four.meme API](/docs/blockchain/BSC/four-meme-api/) --- ## Perp DEX API — Onchain Perpetual Futures Data & Streams URL: https://docs.bitquery.io/docs/perpetuals/ Perp DEX API for onchain perpetual futures: orders, trades, positions, PnL, liquidations, funding, mark price and open interest on Solana, via GraphQL and WebSocket. # Perp DEX API — Onchain Perpetual Futures Data & Streams Bitquery indexes **onchain perpetual futures DEXs** at event level and exposes the data as five GraphQL cubes. Every order placement and cancellation, every fill, every position change, every liquidation, every order-book price tick and every open-interest update is queryable over HTTP **and** streamable over WebSocket — the same query text works as a `query` (history) and as a `subscription` (live stream). | | | | ------------- | ------------------------------------------------------------------------------------- | | **Cubes** | `PerpetualOrders`, `PerpetualFills`, `PerpetualPositions`, `PerpetualPrices`, `PerpetualMarketSummaries` | | **Endpoints** | `https://streaming.bitquery.io/graphql` | | **Streaming** | `wss://streaming.bitquery.io/graphql` — see [WebSocket docs](/docs/subscriptions/websockets) | | **Kafka** | `solana.perpetual.proto` protobuf topic — see the [Solana Perpetuals Kafka Stream](/docs/streams/protobuf/chains/Solana-perpetual-protobuf) | | **Auth** | [OAuth token](/docs/authorization/how-to-generate) as `Authorization: Bearer ` | ## The five cubes | Cube | One row per… | What it answers | | -------------------------- | ------------------------------------- | ------------------------------------------------------------------------------- | | `PerpetualOrders` | order lifecycle event | Who placed, cancelled, or got rejected; limit/market/post-only/stop orders; cancel and reject reasons | | `PerpetualFills` | trade execution | Executions with price, size, fee, taker side, maker counterparty, and the position that resulted | | `PerpetualPositions` | position state change | Entry price, size before/after, realized PnL, funding settlements, liquidations | | `PerpetualPrices` | order-book price tick | Best bid, best ask, mark price, last trade — tick by tick | | `PerpetualMarketSummaries` | market state update | Open interest, spot index vs mark price, cumulative maker/taker fees | Together they cover the full trading loop: an order enters the book (`PerpetualOrders`), matches (`PerpetualFills`), moves a position (`PerpetualPositions`), and the market's price and open interest move with it (`PerpetualPrices`, `PerpetualMarketSummaries`). ## Why this data is different - **Cross-asset markets.** Onchain perp DEXs now list far more than crypto pairs: the currently indexed venue trades crypto majors and memecoins alongside **US equities, commodities like gold, silver and oil, and pre-IPO names** — all as perpetual futures, all settled onchain, all in one API. - **Order-book depth of detail.** This is not OHLC candles. You see individual post-only quotes, stop-loss placements, cancel reasons, and which fills were matched by the AMM backstop versus another trader's resting order. - **Liquidations as first-class events.** Liquidation fills and liquidated positions carry the liquidator address, liquidated size and quote value — enough to build a live liquidation feed or long-term liquidation analytics. - **PnL without reconstruction.** Position rows carry `RealizedPnl`, entry price and size transitions, so trader leaderboards don't require you to replay fills yourself. ## Supported DEXs Coverage is organized by chain, then by protocol: | Chain | Protocol | Docs | | ------ | -------------------------------------------------------------- | ----------------------------------------------------------- | | Solana | **Phoenix Perpetuals** (`phoenix_eternal`, by Ellipsis Labs) | [Phoenix Perpetuals API](/docs/perpetuals/solana/phoenix-perpetuals-api) | | Hyperliquid | **Hyperliquid core** (HyperCore, served by its own `Hyperliquid` cube) | [Hyperliquid API](/docs/perpetuals/hyperliquid) | More venues will appear here as they are enabled. To check what is indexed at any moment, group any cube by `Exchange`: ```graphql query { Solana { PerpetualFills(limit: { count: 20 }, orderBy: { descendingByField: "count" }) { count Fill { Exchange { Family Name Program Version } } } } } ``` ## Query or stream — your choice Every cube is available in both forms. A historical query: ```graphql query { Solana { PerpetualFills(limit: { count: 10 }, orderBy: { descending: Block_Time }) { Block { Time } Fill { Asset { Symbol } Side ExecutionPrice Amount { Filled Quote } } } } } ``` …becomes a live stream by changing one word and dropping the pagination arguments: ```graphql subscription { Solana { PerpetualFills { Block { Time } Fill { Asset { Symbol } Side ExecutionPrice Amount { Filled Quote } } } } } ``` ## What people build with it - **Liquidation alert bots** — stream `PerpetualPositions` filtered to `Liquidation: true` - **Trader analytics and leaderboards** — aggregate `RealizedPnl` per `Trader` - **Open-interest and fee dashboards** — snapshot `PerpetualMarketSummaries` per market - **Live tickers and charting** — stream `PerpetualPrices` best bid/ask and mark - **Market-maker monitoring** — follow order lifecycle and AMM-vs-book fill share Start with the [Phoenix Perpetuals API](/docs/perpetuals/solana/phoenix-perpetuals-api) page — it documents every cube with working queries and streams. Then jump to the [Perps Trader Cookbook](/docs/perpetuals/solana/perps-trader-cookbook) for workflow-shaped recipes: copy-trading a wallet, trader win-rate report cards, top unrealized positions, whale fills, OHLC candles, open-interest and order-flow series. --- ## Phoenix Perpetuals API — Solana Perp DEX Data & Streams URL: https://docs.bitquery.io/docs/perpetuals/solana/phoenix-perpetuals-api/ Phoenix Perpetuals API on Solana: query and stream orders, fills, positions, realized PnL, liquidations, funding, best bid/ask, mark price and open interest. # Phoenix Perpetuals API — Solana Perp DEX Data & Streams [Phoenix Perpetuals](https://www.ellipsislabs.xyz/) is the fully onchain perpetual futures exchange built by Ellipsis Labs, the team behind the Phoenix spot order book on Solana. Bitquery indexes it at event level into five cubes, each available as a GraphQL `query` and as a WebSocket `subscription`. ## Video Tutorials | | | | ------------------- | ------------------------------------------------------ | | **Exchange family** | `Phoenix` | | **Exchange name** | `phoenix_eternal` | | **Program** | `EtrnLzgbS7nMMy5fbD42kXiUzGg8XQzJ972Xtk1cjWih` | | **Quote currency** | `PhUsd` — mint `PhUsd11YkbjSaWjFncfAAmatntsjx3MgDR9B6g1ks3A`, 6 decimals | | **Markets** | Crypto majors and memecoins, US equities, commodities, pre-IPO names | | **Endpoints** | `https://streaming.bitquery.io/graphql`; streams via `wss://streaming.bitquery.io/graphql` | | **Kafka** | Same data as protobuf on the [`solana.perpetual.proto` topic](/docs/streams/protobuf/chains/Solana-perpetual-protobuf) | ## Reading the data model Every cube shares the same `Asset` block — the perpetual market being traded: - **`Asset.Id`** — the venue's numeric market id (e.g. BTC is `"1"`). Stable key; filter on it or on `Symbol`. - **`Asset.Symbol`** — the underlying: `BTC`, `SOL`, `AAPL`, `TSLA`, `GOLD`, `WTIOIL`, … - **`Asset.LotSize` / `Asset.TickSize`** — minimum size and price increments. - **`Asset.QuoteCurrency`** — always `PhUsd` on Phoenix; all prices and quote amounts are in it. - **Sizes are signed** where direction matters: negative size = short / sell side. - **`Trader` vs `Signer`** — `Trader` is the account whose position or order it is; `Signer` signed the transaction (they differ for liquidations, AMM flow, and delegated flows). - **`TraderIsAmm` / `CounterpartyIsAmm`** — Phoenix runs an AMM backstop alongside the order book. Rows flag whether each side is the AMM. To see which markets exist right now, group fills (or any cube) by asset: ```graphql query { Solana { PerpetualFills(limit: { count: 100 }, orderBy: { descendingByField: "count" }) { count Fill { Asset { Id Symbol LotSize TickSize QuoteCurrency { Symbol } } } } } } ``` ## Live prices — `PerpetualPrices` One row per order-book price tick: best bid, best ask, mark price, and the last trade price when the tick was caused by a trade. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/sol_perps_bid_ask). ```graphql query { Solana { PerpetualPrices(limit: { count: 10 }, orderBy: { descending: Block_Time }) { Block { Time } Transaction { Signature Signer } Price { Asset { Symbol QuoteCurrency { Symbol } } BestAsk BestBid LastTrade Mark SequenceNumber } } } } ``` Notes: - `LastTrade` is `0` on ticks not caused by a trade (quote updates, cancels). Filter `Price: { LastTrade: { gt: 0 } }` for trade prints only. - `SequenceNumber` is the venue's monotonic sequence — use it to order ticks within a slot. Stream the BBO for one market live: You can run this stream [in the Bitquery IDE](https://ide.bitquery.io/solana-perpetuals-mark-price-stream). ```graphql subscription { Solana { PerpetualPrices(where: { Price: { Asset: { Symbol: { is: "BTC" } } } }) { Block { Time } Price { Asset { Symbol } BestBid BestAsk Mark } } } } ``` ## Open interest & fees — `PerpetualMarketSummaries` Market-level state updates: mark price, the spot index it tracks, open interest, and fee counters. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/sol_perps_market_info). ```graphql query { Solana { PerpetualMarketSummaries( where: { MarketSummary: { Asset: { Symbol: { is: "JTO" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Transaction { Signature } MarketSummary { Asset { Id Symbol QuoteCurrency { Symbol } } Mark SpotIndex OpenInterest MakerFees TakerFees } } } } ``` You can filter by the numeric market id instead — `where: { MarketSummary: { Asset: { Id: { eq: "22" } } } }` selects the same JTO market. Notes: - `OpenInterest` is in base units of the asset (e.g. BTC for the BTC market). - **`MakerFees` and `TakerFees` are cumulative counters** since market inception, in `PhUsd`. To get fees generated over an interval, take the difference between the latest value and the value at the start of the interval — don't read a single row as a per-block fee. - `Mark` vs `SpotIndex` gives you the perp premium/discount at any moment. For a dashboard, grab the **latest snapshot of every market in one query** with `limitBy` on the asset id: You can run this query [in the Bitquery IDE](https://ide.bitquery.io/phoenix-perps-all-markets). ```graphql query { Solana { PerpetualMarketSummaries( limitBy: { by: MarketSummary_Asset_Id, count: 1 } limit: { count: 100 } orderBy: { descending: Block_Time } ) { Block { Time } MarketSummary { Asset { Id Symbol } Mark SpotIndex OpenInterest } } } } ``` Stream open-interest changes across all markets: ```graphql subscription { Solana { PerpetualMarketSummaries { Block { Time } MarketSummary { Asset { Symbol } Mark SpotIndex OpenInterest } } } } ``` ## Order lifecycle — `PerpetualOrders` You can run an order-lifecycle query [in the Bitquery IDE](https://ide.bitquery.io/sol_perps_orders). One row per order event. `Order.Type` is the **event**, and the nested `Order.Order.Type` is the **order kind**: | Field | Values seen | | -------------------- | ------------------------------------------------------------------------------------------------------------ | | `Order.Type` (event) | `OrderRequested`, `OrderPlaced`, `OrderCancelled`, `OrderRejected`, `StopLossPlaced`, `TakeProfitPlaced`, `TriggerPlaced`, `TriggerExecuted`, `TriggerCancelled`, `ConditionalExecuted`, `ConditionalCancelled` | | `Order.Order.Type` (kind) | `limit`, `market`, `post-only`, `stop-loss`, `take-profit` (empty on events where kind isn't re-stated, e.g. cancels) | | `Order.Order.CancelReason` | `UserRequested`, `Expired`, `ReduceOnlyInvalidated`, `SelfTradeCancelProvide` | | `Order.Order.RejectReason` | `TiFInvalid`, `PostOnlyCross` | A typical placement produces `OrderRequested` followed by `OrderPlaced` (which carries the assigned `Order.Order.Id`) in the same transaction. More lifecycle details, all observable in the data: - **Conditional & trigger events** (`Conditional*`, `Trigger*`) describe the stop/take-profit machinery: a `StopLossPlaced` row carries the `Price.Trigger` level and a `Order.ConditionalId` that later `TriggerExecuted` / `ConditionalCancelled` rows reference. These bookkeeping rows have an empty `Side`. - **Time-in-force**: `Order.Order.ValidUntilSlot` is a slot-based expiry for resting quotes (`0` = no expiry). Orders that hit it are cancelled with `CancelReason: "Expired"`. - **`Order.Order.ClientId`** is the trader's own hex order identifier, when supplied — useful for reconciling your execution system against the chain. ```graphql query { Solana { PerpetualOrders(limit: { count: 10 }, orderBy: { descending: Block_Time }) { Block { Time } Transaction { Signature } Order { Asset { Symbol } Type Side Trader Signer Price { Limit Trigger Mark } Amount { Size Remaining Quote } Order { Id Type ReduceOnly CancelReason RejectReason } } } } } ``` Stream every stop-loss and take-profit placement as it happens: ```graphql subscription { Solana { PerpetualOrders( where: { Order: { Type: { in: ["StopLossPlaced", "TakeProfitPlaced"] } } } ) { Block { Time } Order { Asset { Symbol } Type Side Trader Price { Trigger Mark } Amount { Size } } } } } ``` ## Trades — `PerpetualFills` You can run a live fills stream [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-live-trades-stream), or [fills for one wallet](https://ide.bitquery.io/sol_perps_filled_orders_by_signer). One row per execution. `Side` is the taker's side (`bid` = taker bought, `ask` = taker sold); `Amount.Size` is signed by direction while `Amount.Filled` is the unsigned fill quantity and `Amount.Quote` the quote value. ```graphql query { Solana { PerpetualFills(limit: { count: 10 }, orderBy: { descending: Block_Time }) { Block { Time } Transaction { Signature } Fill { Asset { Symbol QuoteCurrency { Symbol Decimals } } Side ExecutionPrice MarkPrice Amount { Filled Size Quote Fee Remaining } Trader TraderIsAmm Counterparty CounterpartyIsAmm MakerOrderId SplineId Collateral Position { EntryPrice Size } Liquidation Liquidator } } } } ``` Notes: - **AMM fills**: when `CounterpartyIsAmm` is `true`, the fill matched the AMM backstop — `MakerOrderId` is empty and `SplineId` identifies the AMM curve segment. Book fills carry the maker's `MakerOrderId` instead. The AMM currently absorbs the large majority of taker flow, so segment by this flag before drawing conclusions about book liquidity. - `Amount.Fee` is the fee charged on the fill in `PhUsd`; it is `0` on most fills and never negative in observed data. - `Position { EntryPrice, Size }` is the trader's position **after** this fill — you can follow a position's evolution from fills alone. - `Collateral` is the trader's collateral balance snapshot in `PhUsd`. - `Liquidation: true` marks forced fills, with the `Liquidator` address populated. All fills of one trader (excluding liquidations): ```graphql query { Solana { PerpetualFills( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Fill: { Liquidation: false Signer: { is: "7Kjwrohbf49adi5Gg4WM1M9h68UZSBFvLVRdw7PoeX5E" } } } ) { Block { Time } Transaction { Signature } Fill { Asset { Symbol } Side ExecutionPrice Amount { Filled Quote Fee } Position { EntryPrice Size } } } } } ``` ## Positions, PnL & liquidations — `PerpetualPositions` Runnable IDE examples: [top open positions](https://ide.bitquery.io/solana-perps-top-positions), [liquidations](https://ide.bitquery.io/solana-perps-liquidations), [realized PnL leaderboard](https://ide.bitquery.io/solana-perps-trader-pnl). One row per position state change: size transitions, realized PnL, funding settlements, and liquidations. ```graphql query { Solana { PerpetualPositions(limit: { count: 10 }, orderBy: { descending: Block_Time }) { Block { Time } Transaction { Signature Signer } Position { Asset { Symbol QuoteCurrency { Symbol } } Type Trader TraderIsAmm Position { EntryPrice Size SizeBefore } MarkPrice RealizedPnl Funding Closed Liquidation Liquidator LiquidatedQuote LiquidatedSize } } } } ``` Notes: - `Position.Type` is `PnL` for normal position accounting rows and `Liquidation` for the dedicated liquidation rows. - `SizeBefore → Size` is the transition; `Closed: true` marks a full close. - `RealizedPnl` (in `PhUsd`) is booked on closes and reductions; `Funding` is non-zero on funding settlement rows. - **Funding settlements are their own rows**: `Funding ≠ 0`, position size unchanged (`SizeBefore` = `Size`), `RealizedPnl: 0` and `MarkPrice: 0`. The sign is from the trader's perspective — positive means the position received funding, negative means it paid. Filter `Position: { Funding: { ne: 0 } }` for a funding history. - **A liquidation emits multiple rows in one transaction**: the trader's forced close (`Type: "PnL"`, `Closed: true`, negative `RealizedPnl`) plus a `Type: "Liquidation"` row carrying `LiquidatedSize` and `LiquidatedQuote`, with `Liquidator` set on each — and the liquidator's own position rows alongside. Count *events*, not rows, when measuring liquidation activity. Profitable closed trades — every close that realized more than 100 `PhUsd`: ```graphql query { Solana { PerpetualPositions( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Position: { RealizedPnl: { gt: 100 }, Closed: true } } ) { Block { Time } Transaction { Signature Signer } Position { Asset { Symbol } Trader Position { EntryPrice Size SizeBefore } MarkPrice RealizedPnl Closed } } } } ``` A realized-PnL leaderboard falls out of one aggregation — total booked PnL per trader across closed positions, AMM excluded: ```graphql query { Solana { PerpetualPositions( limit: { count: 10 } orderBy: { descendingByField: "pnl" } where: { Position: { TraderIsAmm: false, Closed: true } } ) { Position { Trader } pnl: sum(of: Position_RealizedPnl) closes: count } } } ``` Live liquidation feed: ```graphql subscription { Solana { PerpetualPositions(where: { Position: { Liquidation: true } }) { Block { Time } Transaction { Signature } Position { Asset { Symbol } Type Trader Liquidator LiquidatedSize LiquidatedQuote RealizedPnl MarkPrice } } } } ``` ## Ideas to build Worked, runnable versions of the recipes below — copy-trade feeds, trader report cards, unrealized-PnL rankings, OHLC candles, OI/basis series, order-flow pressure — live in the [Perps Trader Cookbook](/docs/perpetuals/solana/perps-trader-cookbook). - **Liquidation alerts** — the subscription above, pushed to Telegram/Discord. - **PnL leaderboard** — aggregate `RealizedPnl` by `Trader` over `PerpetualPositions`, excluding `TraderIsAmm: true`. - **OI & premium dashboard** — periodic snapshots of `PerpetualMarketSummaries` (`OpenInterest`, `Mark` vs `SpotIndex`, fee-counter diffs). - **Equity & commodity perps tracker** — filter any cube to `AAPL`, `TSLA`, `GOLD`, `WTIOIL` markets: stock and commodity price action, settled onchain, streaming in real time. - **Execution analytics** — compare `ExecutionPrice` to `MarkPrice` on fills; split volume by AMM vs order-book counterparty. --- ## Polygon (MATIC) API Documentation URL: https://docs.bitquery.io/docs/blockchain/Matic/ Polygon (MATIC) API overview: DEX trades, slippage, liquidity, transfers, balances and NFT data on Polygon, with WebSocket and webhook options and videos. # Polygon (MATIC) API Documentation Discover everything you need to build powerful Polygon (MATIC) applications—from real-time DEX trading analytics, liquidity monitoring, slippage analysis, and token holder insights to NFT tracking and transaction monitoring. This comprehensive guide provides ready-to-use GraphQL APIs, live streaming data, and step-by-step examples for tracking swaps, balances, transfers, liquidity pools, and more across the Polygon ecosystem. Whether you're building trading bots, dashboards, or DeFi analytics tools, find all the Polygon data solutions you need right here. Need help crafting a query or subscription? Message us on [support](https://t.me/Bloxy_info). ## What is the Bitquery Polygon (MATIC) API? :::tip Building a trading app or DEX UI on Polygon (MATIC)? For **real-time trades and prices on Polygon (MATIC)** (and the last ~30 days), use the curated [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. For **historical Polygon (MATIC) data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: It's a GraphQL interface over curated, indexed Polygon (MATIC) data. Write concise queries instead of building and maintaining your own indexer. ## What can you build with it? Track wallet portfolios and token holders, monitor DEX price/volume, liquidity events, pool reserves, and slippage data, analyze gas and fees, stream mempool activity, compute KPIs over blocks/transactions, and power dashboards or trading systems with real‑time data. ## How is it different from raw Polygon (MATIC) RPC? | Feature | Polygon (MATIC) RPC | Bitquery Polygon (MATIC) API | | ------------------- | -------------------------------- | -------------------------------------- | | **Data Format** | Raw JSON-RPC responses | Pre-indexed, enriched GraphQL | | **Historical Data** | No built-in history | Full historical data since genesis | | **Analytics** | Manual aggregation required | Built-in joins, aggregations, and KPIs | | **Real-time** | Basic subscription support | Rich streaming with filtering | | **Use Case** | Transaction submission, node ops | Analytics, monitoring, dashboards | | **Infrastructure** | Run your own nodes | Fully managed, auto-scaling | ## WebSockets and Webhooks Most queries can be turned into live streams by switching `query` to `subscription`, and consumed over WebSocket. See examples and code snippets [here](/docs/subscriptions/websockets/). ## DEX Trades - [Polygon (MATIC) Dex Trades](./matic-dextrades) - [Polygon (MATIC) Uniswap API](./matic-uniswap-api) Query and subscribe to on‑chain swaps, OHLCV, liquidity events, pools, and per‑wallet trading activity across major Polygon DEXes. ## Polygon (MATIC) Slippage API - [Polygon (MATIC) Slippage API](./matic-slippage-api) Get slippage and price impact data for Polygon DEX pools. Understand price impact and liquidity depth for token swaps, calculate maximum input amounts at different slippage tolerances, and monitor real-time slippage data across all DEX pools on Polygon. ## Polygon (MATIC) Liquidity API - [Polygon (MATIC) Liquidity API](./matic-liquidity-api) Monitor real-time liquidity changes, track pool reserves, and analyze liquidity depth for token pairs on Polygon DEX pools. Track when liquidity is added or removed, monitor pool health and depth, and analyze liquidity patterns across different pools. ## Transfers - [Polygon (MATIC) Transfers API](./matic-transfers) Follow ERC‑20 token flows and compute supply‑side metrics on Polygon. ## Balances - [Polygon (MATIC) Address Balance API](./matic-balance-api) — token and [native MATIC](./matic-balance-api#native-matic-balance) balances (`EVM.Balances`) Get real‑time and historical balances for addresses and tokens on Polygon. ## NFT - [Polygon (MATIC) NFT API](./matic-nft) Fetch collections, ownership, transfers, trades, and metadata on Polygon. ## Videos ### Polygon (MATIC) API | How to Get Real-time & Historical Matic (Polygon) Data ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back this chain's data goes - [Common errors and what to do](/docs/start/errors/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) - [First query in 5 minutes](/docs/start/first-query/) --- ## Polygon (MATIC) Address Balance API URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-balance-api/ Query Polygon address balances with the Bitquery Balances cube: token and native POL balances, balances on a given date, and per-token lookups. # Polygon (MATIC) Address Balance API :::tip To rank a token's holders, use the **[Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api)** (`EVM.Holders`). Balance lookups like these are productized in the [Address & Balance API](https://bitquery.io/products/address-apis) — native and token balances, labels and history on 10 core chains. ::: The **Balances** API returns current and historical token balances for an address on Polygon (MATIC). To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | | -------------- | ------------------------------------------------------------------------------------------- | | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | Examples: [All Token Balances](#balance-of-an-address) · [Native MATIC](#native-matic-balance) · [Balance on a Date](#balance-on-a-specific-date) · [Specific Token](#balance-for-a-specific-token) ## Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. [Run in IDE](https://ide.bitquery.io/matic-balances-address) ```graphql query { EVM(network: matic, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x4c569c1e541A19132AC893748E0ad54C7c989FF4" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Native MATIC Balance Returns the native MATIC balance for a wallet (not ERC-20 tokens). Filter with `Currency: { Native: true }` instead of a token contract address. [Run in IDE](https://ide.bitquery.io/matic-native-balances-address) ```graphql query { EVM(network: matic, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x4c569c1e541A19132AC893748E0ad54C7c989FF4" } } Currency: { Native: true } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` **Parameters** - `network: matic`: Polygon mainnet. - `dataset: combined`: Merges realtime and archive data for the latest balance state. - `Balance.Address`: Wallet address to query. - `Currency.Native: true`: Native MATIC only (see [Native MATIC Balance](#native-matic-balance)). **Returned fields** - `Currency.Symbol`, `Currency.SmartContract`: Token metadata. - `Balance.Amount`, `Balance.AmountInUSD`: Token balance and USD value (use `selectWhere` to filter non-zero amounts). ## Balance on a Specific Date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. [Run in IDE](https://ide.bitquery.io/matic-balances-by-date) ```graphql query { EVM(network: matic, dataset: archive) { Balances( where: { Block: { Date: { till: "2026-05-01" } } Balance: { Address: { is: "0x4c569c1e541A19132AC893748E0ad54C7c989FF4" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Balance for a Specific Token Add a `Currency.SmartContract` filter. Always use the contract address, not the token name. Use `0x` for native MATIC on Polygon, or the ERC-20 contract address for a token. [Run in IDE](https://ide.bitquery.io/matic-balances-specific-token) ```graphql query { EVM(network: matic, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x4c569c1e541A19132AC893748E0ad54C7c989FF4" } } Currency: { SmartContract: { is: "0x" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ## Token Holder Snapshot The number of unique holders, token supply, and Gini coefficient for the balance amount before a specific timestamp can be derived using the query below. These stats provide a useful holder snapshot for any given time. [Run in IDE](https://ide.bitquery.io/token-holder-snapshot-matic)
Click to expand GraphQL query ```graphql query MyQuery($network: evm_network!, $address: String!) { EVM(network: $network, dataset: archive) { Holders( where: { Currency: {SmartContract: {is: $address}}, Balance: { Amount: {gt: "0"}, LastChangeTime: {till: "2026-05-20T00:00:00Z"} }, Holder: {Address: {not: "0x"}}} ) { Balance { LastChangeTime(maximum: Balance_LastChangeTime) } holders: uniq(of: Holder_Address) supply: sum(of: Balance_Amount) gini(of: Balance_Amount) } } } ``` ```json { "network": "matic", "address": "0x99a57e6c8558bc6689f894e068733adf83c19725" } ```
## Balance History by Date Returns balance snapshots over time for an address. Use `dataset: archive`. Order by `Block_Date` descending and use `limit` to paginate. Add `Currency.SmartContract` under `Currency` to filter by a specific token. [Run in IDE](https://ide.bitquery.io/matic-balances-history) ```graphql query { EVM(network: matic, dataset: archive) { Balances( where: { Balance: { Address: { is: "0x4c569c1e541A19132AC893748E0ad54C7c989FF4" } } Currency: {} } orderBy: { descending: Block_Date } limit: { count: 100 } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } Block { Date } } } } ``` ## Wallet Balance for a Specific Token on a Date Get a wallet's balance for a specific token with `Balance.Address` and `Currency.SmartContract`. This example uses native MATIC (`SmartContract: "0x"`) with `dataset: combined`. For a balance on a calendar date, use [Balance on a Specific Date](#balance-on-a-specific-date) with `dataset: archive` and `Block.Date.till`. [Run in IDE](https://ide.bitquery.io/matic-wallet-balance-token-at-date) ```graphql query { EVM(network: matic, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x4c569c1e541A19132AC893748E0ad54C7c989FF4" } } Currency: { SmartContract: { is: "0x" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` --- ## Polygon (MATIC) DEX Trades API URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-dextrades/ Query Polygon DEX trades with Bitquery: live swap streams, OHLC candles, token prices, top traders, and full history through the archive dataset. # Polygon (MATIC) DEX Trades API :::tip Want structured trades, OHLC and USD on every row? Start with the Trading API The [**Trading API**](/docs/trading/trading-data-overview) is the fastest path to clean Polygon market data. [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns **MEV-filtered swaps with USD price, market cap and supply on every row**, across **10 chains in one API** — filter with `Pair.Market.Network: Matic`. Pre-aggregated OHLC down to one second comes from [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs), so you never have to build candles yourself. Reach for the chain-level queries on this page when you need something the Trading API deliberately does not carry: **history older than the Trading window** (via `dataset: combined` or `archive`), **raw per-swap detail**, pool internals, or **call and event context**. Both are shown below, starting with the Trading API. ::: Polygon (formerly Matic) settles DEX activity across Uniswap v2/v3, QuickSwap, Balancer, SushiSwap and the Polymarket CTF exchange. This page shows how to query and stream that activity with the Bitquery GraphQL API: live swap streams, real-time and historical token prices, OHLC candles, top tokens and traders, and full trade history through the archive dataset. :::note Token naming on Polygon Polygon's native asset was rebranded from MATIC to POL, so the wrapped native token reports as **`WPOL`** (contract `0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270` — unchanged from WMATIC). Bridged Tether reports as **`USDT0`** at `0xc2132d05d31c914a87c6611c10748aeb04b58e8f`. Filter by contract address rather than symbol wherever you can — addresses are stable across rebrands. ::: ## Live DEX swap stream (Polygon) {#crypto-trades-live-stream} [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api): one row per swap, with USD and supply. For Polygon use **`Pair.Market.Network: Matic`**. [When to use this vs chain DEX APIs](/docs/cubes/dextrades-dextradebytokens-trading-trades). Run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Polygon-with-Price-Marketcap-supply).
Click to expand GraphQL query ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Matic" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
## OHLC candles for a Polygon token {#ohlc} If you are building a chart, do not aggregate raw swaps yourself. [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) returns ready-made candles: set `Interval.Time.Duration` to the candle width in seconds (`60`, `300`, `3600`, `86400`) and filter the token by address. This example returns five-minute candles for **WPOL** over the last three hours, with volume in both base units and USD. ```graphql { Trading { Tokens( limit: { count: 36 } orderBy: { descending: Block_Time } where: { Token: { Network: { is: "Matic" } Address: { is: "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270" } } Interval: { Time: { Duration: { eq: 300 } } } Block: { Time: { since_relative: { hours_ago: 3 } } } } ) { Interval { Time { Start End Duration } } Token { Symbol Address Network } Currency { Symbol } Price { Ohlc { Open High Low Close } } Volume { Base Usd } } } } ``` Swap `Duration` for the candle size you need, and drop the `Block.Time` filter to walk further back. For pair-level candles — one specific pool rather than the token's aggregated price — use [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) with a `Market.Address` filter. ## Historical Polygon trades (archive dataset) {#historical} The realtime dataset covers a rolling recent window. For anything older, add **`dataset: archive`** (history only) or **`dataset: combined`** (history plus realtime) to the `EVM` selector. This is the main reason to use chain-level `DEXTrades` instead of the Trading API. The query below pulls Polygon swaps from a fixed historical day. Change the `since` / `till` bounds to any range you need. ```graphql { EVM(network: matic, dataset: archive) { DEXTrades( limit: { count: 25 } orderBy: { descending: Block_Time } where: { Block: { Time: { since: "2025-01-01T00:00:00Z", till: "2025-01-02T00:00:00Z" } } } ) { Block { Time Number } Transaction { Hash From } Trade { Dex { ProtocolName ProtocolFamily SmartContract } Buy { Amount Currency { Symbol SmartContract } PriceInUSD Buyer } Sell { Amount Currency { Symbol SmartContract } } } } } } ``` :::caution USD values on thin pools `PriceInUSD` is derived from the trade itself, so it can come back as `0` or wildly off for pools with almost no liquidity. If you need dependable USD, use the Trading API (which carries a vetted price per row) or filter on [`PriceAsymmetry`](/docs/graphql/metrics/priceAsymmetry/) as shown below. ::: ## Latest Polygon DEX trades {#latest-trades} This example uses the chain-specific **DEXTrades** cube via `EVM(network: matic) { DEXTrades }` (pool-side Buy/Sell; see [DEXTrades cube](/docs/cubes/dextrades)). For trader-oriented rows with reliable USD, use the [stream at the top](#crypto-trades-live-stream). Read [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) to understand when to use which cube. You can find the query [here](https://ide.bitquery.io/Realtime-matic-dex-trades-websocket) ```graphql subscription { EVM(network: matic) { DEXTrades { Block { Time } Trade { Dex { ProtocolName ProtocolFamily SmartContract } Buy { Amount Buyer Seller Currency { Decimals Fungible HasURI Name ProtocolName SmartContract Symbol } OrderId } Sell { Buyer Seller Currency { Decimals Fungible HasURI Name ProtocolName SmartContract Symbol } } } } } } ``` ## Real-time price of a token in terms of another {#realtime-price} This subscription streams the price of **WPOL** in terms of **USDC**, including the DEX, market and order details. Filtering both sides pins you to a single trading direction on a specific pair. ```graphql subscription { EVM(network: matic) { DEXTrades( where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270" } } } Buy: { Currency: { SmartContract: { is: "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359" } } } } } ) { Block { Time } Trade { Buy { Amount Buyer Seller Price_in_terms_of_sell_currency: Price Currency { Name Symbol SmartContract } OrderId } Sell { Amount Buyer Seller Price_in_terms_of_buy_currency: Price Currency { Symbol SmartContract Name } OrderId } Dex { ProtocolFamily ProtocolName SmartContract ProtocolVersion } } } } } ``` To watch one pool rather than every pool for the pair, add a `Trade: { Dex: { SmartContract: { is: "0x..." } } }` filter. ## Latest USD price of a token {#usd-price} This subscription returns the USD price of a token by filtering on the buy-side contract — here **WETH** on Polygon. Read `PriceInUSD` for the USD value. `PriceAsymmetry(selectWhere: {lt: 1})` drops trades whose two legs disagree badly on value, which is the cheapest way to filter out bot noise and broken pools. ```graphql subscription { EVM(network: matic) { DEXTrades( where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x7ceb23fd6bc0add59e62ac25578270cff1b9f619" } } } } } ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } Seller Price PriceInUSD } Sell { Amount Buyer Currency { Name SmartContract Symbol } Seller Price } PriceAsymmetry(selectWhere: { lt: 1 }) } } } } ``` ## Top tokens on Polygon by traded volume {#top-tokens} This query ranks Polygon tokens by USD volume over a relative window and returns the price now versus the start of the window, so you can compute a change percentage client-side. Two filters matter more than they look: - **`Currency: { Fungible: true }`** — without it, results are dominated by Polymarket's ERC-1155 outcome tokens, which trade in enormous quantities on Polygon, carry empty symbols, and are almost certainly not what you are ranking. See the [Polymarket API](/docs/examples/polymarket-api/) if they *are* what you want. - **`SmartContract: { notIn: $quotes }`** on the trade side and **`in: $quotes`** on the counter-side — this keeps stablecoins and wrapped majors as *quote* assets instead of letting them top their own leaderboard. Using `since_relative` rather than fixed timestamps means the query stays correct whenever it is run. ```graphql query topTokens($network: evm_network, $quotes: [String!], $min_usd: String) { EVM(network: $network) { DEXTradeByTokens( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Trade: { Currency: { Fungible: true, SmartContract: { notIn: $quotes } } Side: { Currency: { SmartContract: { in: $quotes } } } } } orderBy: { descendingByField: "usd" } limit: { count: 25 } ) { Trade { Currency { Symbol Name SmartContract } price_now: PriceInUSD(maximum: Block_Number) price_window_start: PriceInUSD(minimum: Block_Number) } usd: sum(of: Trade_Side_AmountInUSD, selectWhere: { ge: $min_usd }) trades: count buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Seller) dexes: uniq(of: Trade_Dex_OwnerAddress) } } } ``` Variables — the quote list is native USDC, bridged USDC.e, USDT0, DAI, WETH, WPOL and WBTC: ```json { "network": "matic", "quotes": [ "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359", "0x2791bca1f2de4661ed88a30c99a7a9449aa84174", "0xc2132d05d31c914a87c6611c10748aeb04b58e8f", "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063", "0x7ceb23fd6bc0add59e62ac25578270cff1b9f619", "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270", "0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6" ], "min_usd": "25000" } ``` A heatmap built on this shape of query is live at [dexrabbit.bitquery.io/matic](https://dexrabbit.bitquery.io/matic). ![Top Polygon tokens by volume on DEXrabbit](/img/dexrabbit/matic_toptokens.png) ## Top traders of a token {#top-traders} This query ranks traders of one token by volume, splitting bought and sold amounts and totalling volume in native and USD terms. `since_relative` keeps the window rolling. You can run the query [here](https://ide.bitquery.io/top-traders-of-a-token-on-matic_1) ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Currency: { SmartContract: { is: $token } } } Block: { Time: { since_relative: { days_ago: 3 } } } } ) { Trade { Buyer Dex { ProtocolFamily } } bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ```json { "network": "matic", "token": "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270" } ``` This query is available as a chart and table on [dexrabbit.bitquery.io/matic](https://dexrabbit.bitquery.io/matic). ![Top Polygon traders on DEXrabbit](/img/dexrabbit/matic_toptraders.png) --- ## More examples ### Top Traders by PnL for a Specific Pool (Last 30 Minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-polygon-pool).
Click to expand GraphQL query ```graphql { Trading { Trades( limit: { count: 10 } orderBy: { descendingByField: "PnL" } where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "0x5757371414417b8c6caad45baef941abc7d3ab32" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
## Related Polygon APIs - [Polygon (MATIC) Address Balance API](/docs/blockchain/Matic/matic-balance-api) — token and native balances - [Polygon (MATIC) Transfers API](/docs/blockchain/Matic/matic-transfers) — ERC-20 and native transfers - [Polymarket API](/docs/examples/polymarket-api/) — prediction market trades and outcome prices on Polygon - [Trading API overview](/docs/trading/trading-data-overview) — structured trades, prices and OHLC across 10 chains --- --- ## Polygon (MATIC) NFT API URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-nft/ Polygon (MATIC) NFT API: track Polygon NFT trades, ownership, and metadata with Bitquery GraphQL and streams. Keep queries fast with indexed filters. # Polygon (MATIC) NFT API In this section we'll have a look at some examples using the Matic NFT API. ## Track transfers of an NFT in Realtime This query subscribes you to the real time transfers of a specific non-fungible token (NFT) on the Matic network. You can find the query [here](https://ide.bitquery.io/Real-time-transfer-websocket-for-NFT-token-on-matic) ```graphql subscription { EVM(network: matic) { Transfers( where: { Transfer: { Currency: { Fungible: false SmartContract: { is: "0x4d544035500D7aC1B42329c70eb58E77f8249f0F" } } } } ) { Block { Hash Number } Transfer { Amount Currency { Name Symbol Native } Sender Receiver } } } } ``` --- ## Polygon (Matic) Token Market Cap API URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-token-marketcap-api/ Polygon (Matic) Token Market Cap API: stream Polygon market cap, FDV, supply, and price using Bitquery Trading GraphQL APIs. # Polygon (Matic) Token Market Cap API Use Bitquery’s **Trading** API **`Tokens`** cube to stream or query **market cap**, **fully diluted valuation (USD)**, **total supply**, **price** (OHLC and averages), and **volume** for tokens on **Polygon** (network id **`matic`** in the Trading API). Filter with **`matic:`** plus a **lowercase** contract address in **`Token.Id`** / **`Currency.Id`**. For schema details and field meanings, see the **[Tokens cube](/docs/trading/crypto-price-api/tokens)** and **[Supply fields](/docs/trading/crypto-price-api/supply-fields)**. :::note Trading API and EVM addresses On **Polygon** (**`matic`** in Trading), use **lowercase** hex in **`Id`** values (e.g. `matic:0xeb51…`, not mixed-case checksum addresses). ::: ## Related APIs - **[Ethereum Token Market Cap API](/docs/blockchain/Ethereum/token-supply/ethereum-token-marketcap-api)** — **`eth:`** ids - **[BSC Token Market Cap API](/docs/blockchain/BSC/bsc-token-marketcap-api)** — **`bsc:`** ids - **[Base Token Market Cap API](/docs/blockchain/Base/base-token-marketcap-api)** — **`base:`** ids - **[Arbitrum Token Market Cap API](/docs/blockchain/Arbitrum/arbitrum-token-marketcap-api)** — **`arbitrum:`** ids - **[Solana Token Market Cap API](/docs/blockchain/Solana/solana-token-marketcap-api)** — **`solana:`** ids - **[Crypto Price API — Tokens](/docs/trading/crypto-price-api/tokens)** — full `Tokens` cube reference --- ## How do I stream live Polygon (Matic) token market cap, price, and volume? Subscribe to **`Tokens`** where **currency id** includes **`matic`**, with **interval duration** greater than **1** (second). You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/matic-token-marketcap-stream). ```graphql subscription MyQuery { Trading { Tokens( where: { Currency: { Id: { includes: "matic" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` --- ## How do I get the latest market cap for a specific token on Polygon? Use **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, and filter **`Token.Id`** with **`includes`** (or **`includesCaseInsensitive`**) for **`matic:`** + lowercase contract. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/specific-matic-token-latest-marketcap). ```graphql query { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { includes: "matic:0xeb51d9a39ad5eef215dc0bf39a8821ff804a0f01" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` Replace the `includes` value with your token’s **`matic:`** id (lowercase hex). --- ## How do I stream Polygon tokens with market cap above $1 million? Subscribe when **`Token.Id`** matches **Polygon** (**`matic`**) and **`Supply.MarketCap`** **>** **1,000,000** (USD). You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-stream-matic-tokens-with-marketcap-above-1-million). ```graphql subscription { Trading { Tokens( where: { Token: { Id: { includesCaseInsensitive: "matic" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 1000000 } } } ) { Currency { Name Id Symbol } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` :::tip Threshold and interval Tune **`Supply.MarketCap`** and **`Interval.Time.Duration`** for your alerts or dashboards. See **[Tokens cube](/docs/trading/crypto-price-api/tokens)** for more filters. ::: --- ## How do I get top Polygon (Matic) tokens by market cap? This query ranks **Polygon** tokens by **`Supply.MarketCap`**. Set **`Token.Network`** to **Matic** (Polygon’s label in the Trading API). It uses roughly the **last 24 hours**, **1-second** intervals, at least **$1,000** **USD volume**, **`limitBy`** one row per **`Token_Id`**, and up to **50** tokens. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Polygon_1). ```graphql { Trading { Tokens( limit: { count: 50 } limitBy: { count: 1, by: Token_Id } orderBy: { descending: Supply_MarketCap } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 1000 } } Token: { Network: { is: "Matic" } } } ) { Currency { Id Name Symbol } Price { Average { Mean(maximum: Block_Time) } } Volume { Base(maximum: Block_Time) Quote(maximum: Block_Time) Usd(maximum: Block_Time) } Token { Network Symbol Address } Supply { MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) TotalSupply(maximum: Block_Time) } } } } ``` --- ## How do I get top Polygon tokens by market cap change in 1 hour? Uses a **1-hour** OHLC interval (`Duration: { eq: 3600 }`) and orders by **`change_mcap`**: **(close − open) × total supply**. **`Token.Network`** is **Matic**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/top-Polygon-tokens-by-Market-Cap-Change-1h). ```graphql { Trading { Tokens( limit: { count: 50 } orderBy: { descendingByField: "change_mcap" } where: { Interval: { Time: { Duration: { eq: 3600 } } } Token: { Network: { is: "Matic" } } } ) { Currency { Id Name Symbol } Token { Network Symbol Address } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } change_mcap: calculate( expression: "($Price_Ohlc_Close-$Price_Ohlc_Open) * Supply_TotalSupply" ) Price { Ohlc { Open Close } } } } } ``` --- ## Polygon Matic Liquidity API URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-liquidity-api/ Polygon Matic Liquidity API: read Polygon pool reserves and liquidity updates via Bitquery GraphQL DEX APIs. Great for bots, dashboards, and alerts. # Matic Liquidity API In this section we will see how to get Matic DEX pool liquidity information using Bitquery API. The liquidity API helps you monitor real-time liquidity changes, track pool reserves, and analyze liquidity depth for token pairs on Matic DEX pools. ## Understanding Liquidity and Pool Reserves Liquidity in DEX pools refers to the amount of tokens available for trading. Pool reserves (the balance of each token in the pool) determine the pool's ability to handle trades without significant price impact. Monitoring liquidity changes helps you: - Track when liquidity is added or removed from pools - Monitor pool health and depth - Identify liquidity events that may affect trading - Analyze liquidity patterns across different pools The DEXPoolEvents API provides real-time information about: - Current liquidity reserves for both tokens in the pool - Spot prices for both swap directions - Pool and token pair information - Transaction details for liquidity-changing events For a comprehensive explanation of how DEX pools work, liquidity calculations, and when pool events are emitted, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/). ## Realtime Liquidity Stream This subscription query returns real-time liquidity data for all DEX pools on Matic. You can monitor liquidity changes, pool reserves, and spot prices as trades and liquidity modifications occur across all pools. You can find the query [here](https://ide.bitquery.io/Realtime-Liquidity-Stream_5#) ```graphql subscription MyQuery { EVM(network: matic) { DEXPoolEvents { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` ## Latest Liquidity Changes of a Specific Pool This query retrieves the latest liquidity events for a specific DEX pool on Matic. Use this to check current pool reserves, spot prices, and recent liquidity changes for a particular token pair. You can find the query [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_6#) ```graphql query MyQuery { EVM(network: matic) { DEXPoolEvents( limit: { count: 10 } orderBy: { descending: Block_Time } where: { PoolEvent: { Pool: { SmartContract: { is: "0x35afbb9d4dbe49f7579ccfd659ee6854a387faa0" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` ## Realtime Liquidity Stream of a Specific Pool This subscription query monitors real-time liquidity changes for a specific DEX pool on Matic. Use this to track liquidity events, pool reserves, and spot prices for a particular pool as they occur. You can find the query [here](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_5#) ```graphql subscription MyQuery { EVM(network: matic) { DEXPoolEvents( where: { PoolEvent: { Pool: { SmartContract: { is: "0x35afbb9d4dbe49f7579ccfd659ee6854a387faa0" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` ## Latest Liquidity Changes of Pools in a Specific DEX Protocol - Uniswap V4 This subscription query monitors real-time liquidity changes for all pools in a specific DEX protocol on Matic. Here we have taken example of Uniswap V4. You can find the query [here](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4_7#) ```graphql subscription MyQuery { EVM(network: matic) { DEXPoolEvents( where: { PoolEvent: { Dex: { ProtocolName: { is: "uniswap_v4" } } } } ) { Block { Time Number } PoolEvent { AtoBPrice BtoAPrice Dex { SmartContract ProtocolName } Liquidity { AmountCurrencyA AmountCurrencyB } Pool { CurrencyA { Name SmartContract Symbol } CurrencyB { Name SmartContract Symbol } PoolId SmartContract } } Transaction { Gas Hash } } } } ``` > **Important Note:** In Uniswap V4, all pools' liquidity is stored in the PoolManager contract, so the DEX smart contract address will be the same for all pairs. Use `PoolId` to differentiate between different pools. The `PoolId` field uniquely identifies each pool within the PoolManager. ## Realtime Liquidity Data via Kafka Streams Liquidity data can also be obtained via Kafka streams for lower latency and better reliability. The Kafka topic for Matic DEX pools is: **`matic.dexpools.proto`** Kafka streams provide the same liquidity data as GraphQL subscriptions but with several advantages: - Lower latency due to shorter data pipeline - Better reliability with persistent connections - Ability to read from latest offset without gaps - Better scalability with multiple consumers For detailed information on how to connect to Kafka streams, subscribe to topics, and parse messages, refer to the [Kafka Streaming Concepts documentation](/docs/streams/kafka-streaming-concepts/). > **Note:** IDE credentials will not work with Kafka Streams. You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## Understanding the Response The `DEXPoolEvents` API response contains the following information: - **`PoolEvent`**: Pool event information - **`Liquidity`**: Current pool reserves - `AmountCurrencyA`: Current balance of CurrencyA in the pool (in raw units) - `AmountCurrencyB`: Current balance of CurrencyB in the pool (in raw units) - **`AtoBPrice`**: Current spot price for swapping CurrencyA to CurrencyB - **`BtoAPrice`**: Current spot price for swapping CurrencyB to CurrencyA - **`Pool`**: Pool information - `SmartContract`: Pool contract address - `PoolId`: Unique pool identifier - `CurrencyA`: First token in the pair (name, symbol, smart contract address) - `CurrencyB`: Second token in the pair (name, symbol, smart contract address) - **`Dex`**: DEX protocol information - `SmartContract`: DEX router/factory contract address - `ProtocolName`: Protocol name (e.g., Uniswap V2, Uniswap V3, Uniswap V4) - **`Block`**: Block information when the liquidity event occurred - `Time`: Timestamp of the block - `Number`: Block number - **`Transaction`**: Transaction information - `Hash`: Transaction hash - `Gas`: Gas used for the transaction For more details on when new pool events are emitted and how liquidity is calculated, see the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#when-is-a-new-dexpool-record-emitted-in-the-apis--streams). ## Use Cases ### Real-Time Liquidity Monitoring Use the liquidity API to monitor pool reserves in real-time: - Track when large amounts of liquidity are added or removed - Monitor pool health and detect potential liquidity issues - Alert on significant liquidity changes that may affect trading ### Liquidity Depth Analysis Analyze which pools have sufficient liquidity for your needs: - Compare liquidity reserves across different pools - Identify pools with deep liquidity for large trades - Monitor liquidity trends over time ### Trading Applications #### Pre-Trade Liquidity Checks Before executing large trades, check current pool reserves: - Verify sufficient liquidity exists for your trade size - Monitor liquidity changes that may affect execution - Identify optimal pools with best liquidity depth #### Liquidity Event Detection Track liquidity events that may create trading opportunities: - Detect when new liquidity is added to pools - Monitor liquidity removals that may signal pool abandonment - Identify pools experiencing rapid liquidity growth For more advanced use cases, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#advanced-use-cases-and-processing-patterns). --- ## Polygon Matic Slippage API URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-slippage-api/ Polygon Matic Slippage API: measure Polygon DEX price impact and slippage with Bitquery GraphQL pool metrics. Covers archive history and realtime data. # Matic Slippage API In this section we will see how to get Matic DEX pool slippage information using our API. The slippage API helps you understand price impact and liquidity depth for token swaps on Matic DEX pools. ## Understanding Slippage and Price Impact Slippage refers to the difference between the expected price of a trade and the actual execution price. When swapping tokens in a DEX pool, larger trades can move the price due to limited liquidity, resulting in slippage. The DEXPoolSlippages API provides detailed information about: - Maximum input amounts that can be swapped at different slippage tolerances - Minimum output amounts guaranteed at each slippage level - Average execution prices for different trade sizes - Price impact calculations for both swap directions (A to B and B to A) For a comprehensive explanation of how DEX pools work, liquidity calculations, and price tables, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/). ## Realtime Slippage Monitoring This subscription query returns real-time slippage data for all DEX pools on Matic. You can monitor price impact and liquidity depth as trades occur. You can find the query [here](https://ide.bitquery.io/realtime-slippage-on-matic) ```graphql subscription { EVM(network: matic) { DEXPoolSlippages { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` ## Latest Slippage for a Specific Pool This query retrieves the latest slippage data for a specific DEX pool on Matic. Use this to check current liquidity depth and price impact for a particular token pair. You can find the query [here](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Uniswap-v3) ```graphql query { EVM(network: matic) { DEXPoolSlippages( where: {Price: {Pool: {SmartContract: {is: "0x42161084d0672e1d3f26a9b53e653be2084ff19c"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Price { BtoA { Price MinAmountOut MaxAmountIn } AtoB { Price MinAmountOut MaxAmountIn } Pool { PoolId SmartContract Pair { Decimals SmartContract Name } CurrencyB { Symbol SmartContract Name Decimals } CurrencyA { Symbol SmartContract Name Decimals } } Dex { SmartContract ProtocolVersion ProtocolName ProtocolFamily } SlippageBasisPoints } Block { Time Number } } } } ``` > **Note:** This query can be converted to a subscription to monitor in real-time. Simply replace `query` with `subscription` to receive live updates whenever the pool's liquidity changes. ## Realtime Slippage Data via Kafka Streams Slippage data can also be obtained via Kafka streams for lower latency and better reliability. The Kafka topic for Matic DEX pools is: **`matic.dexpools.proto`** Kafka streams provide the same slippage data as GraphQL subscriptions but with several advantages: - Lower latency due to shorter data pipeline - Better reliability with persistent connections - Ability to read from latest offset without gaps - Better scalability with multiple consumers For detailed information on how to connect to Kafka streams, subscribe to topics, and parse messages, refer to the [Kafka Streaming Concepts documentation](/docs/streams/kafka-streaming-concepts/). > **Note:** IDE credentials will not work with Kafka Streams. You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## Understanding the Response The `DEXPoolSlippages` API response contains the following information: - **`Price`**: Price information for swaps at a specific slippage tolerance - **`AtoB`**: Price data for swapping CurrencyA to CurrencyB - `Price`: Average execution price for swaps at this slippage level - `MinAmountOut`: Minimum output amount guaranteed at this slippage level - `MaxAmountIn`: Maximum input amount that can be swapped at this slippage level - **`BtoA`**: Price data for swapping CurrencyB to CurrencyA (same structure as AtoB) - **`SlippageBasisPoints`**: Slippage tolerance in basis points (100 = 1%) - **`Pool`**: Pool information including token pair details - **`Dex`**: DEX protocol information (Uniswap V2, V3, V4, etc.) - **`Block`**: Block information when the slippage data was recorded - `Time`: Timestamp of the block - `Number`: Block number For more details on how slippage is calculated and when new pool records are emitted, see the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#when-is-a-new-dexpool-record-emitted-in-the-apis--streams). ## Use Cases ### Liquidity Depth Analysis Use the slippage API to analyze which pools can handle large trades without significant price impact. By examining `MaxAmountIn` values at different slippage levels, you can: - Identify pools with sufficient liquidity for your trade size - Determine optimal slippage tolerance settings - Estimate price impact before executing trades ### Multi-Pool Price Comparison Compare execution prices across different pools and slippage scenarios to: - Find the best pool for your specific trade size - Understand price differences between DEX protocols - Optimize trade execution strategies ### Trading Applications #### Live Execution Testing Use the slippage API to test and validate trade execution strategies in real-time: - **Pre-trade validation**: Check if your intended trade size can be executed within acceptable slippage bounds before submitting - **Execution simulation**: Calculate expected price impact and minimum output amounts for different trade sizes - **Strategy backtesting**: Monitor historical slippage data to validate trading algorithms and optimize entry/exit points - **Risk assessment**: Evaluate maximum position sizes that can be entered without exceeding your slippage tolerance #### Detecting Liquidity Shocks and Toxic Order Flow The slippage API helps identify temporary price dislocations and liquidity shocks that can be exploited or avoided: - **Flow toxicity detection**: Monitor sudden changes in `MaxAmountIn` values to detect when pools experience large outflows or inflows - **Price impact analysis**: Track how `MinAmountOut` changes relative to `MaxAmountIn` to identify when pools become less liquid - **Mean reversion opportunities**: Identify pools where large swaps have created temporary price dislocations that may revert - **Toxic order flow avoidance**: Use slippage data to avoid entering positions when liquidity is thin or when large trades are likely to move price against you For a practical implementation example of using slippage data for automated trading strategies, including flow toxicity detection and mean-reversion trading, see the [AMM Flow Toxicity Alpha Engine](https://github.com/Divyn/amm-flow-toxicity-alpha-engine) repository. This system demonstrates how to: - Detect large swaps that move price significantly (50-500 basis points) - Verify isolation from trending markets - Execute fade trades against temporary price impacts - Manage positions with dynamic stop losses and take profits based on slippage data For more advanced use cases, refer to the [DEXPools Cube documentation](/docs/cubes/evm-dexpool/#advanced-use-cases-and-processing-patterns). --- ## Polygon Matic Uniswap API URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-uniswap-api/ Polygon Uniswap API: GraphQL examples for v3 trades, top traders, hourly OHLC, 24-hour volume and top tokens, filtered to Uniswap's own factory. Most uniswap_v2 trades on Polygon are QuickSwap. # Matic Uniswap API :::tip Real-time data or the last 30 days? Use the Trading cube For real-time trades and anything from the last 30 days, use the [Trading cube](/docs/trading/trading-data-overview): [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns MEV-filtered swaps with a USD price on every row. Use the `EVM` queries on this page for raw per-swap detail or call and event context. An `EVM` query without a `dataset` argument runs on the realtime dataset, which holds only the last few days; add `dataset: combined` or `dataset: archive` for older history. ::: ## Filter by factory to exclude forks `Trade.Dex.ProtocolName` records which code a pool runs. Forks of v2 and v3 run the same code, so their trades carry the same `uniswap_v2` and `uniswap_v3` labels. In Bitquery's trade data for Polygon on 17 and 18 September 2026, about 89% of transactions labelled `uniswap_v2` went through other factories' pools, most of them QuickSwap's. For `uniswap_v3` it was about one in five. To keep only Uniswap's own pools, filter on the contract that owns them, as every example on this page now does. | Version | Filter field | Address on Polygon | | --- | --- | --- | | v2 | `Trade.Dex.OwnerAddress` | `0x9e5a52f57b3038f1b8eee45f28b3c1967e22799c` | | v3 | `Trade.Dex.OwnerAddress` | `0x1f98431c8ad98523631ae4a59f267346ea31f984` | | v4 | `Trade.Dex.SmartContract` | `0x67366782805870060151383f4bbff9dab53e5cd6` | `OwnerAddress` is the factory that deployed the pool. A v4 pool has no factory: its `OwnerAddress` is the zero address, and the PoolManager is its `SmartContract`. In the Trading cube, filter `Pair.Market.Address` to the v2 or v3 factory, or `Pair.Market.Program` to the v4 PoolManager. Addresses are from the official [deployments list](https://developers.uniswap.org/deployments). The link in each example's description opens an earlier copy saved in the Bitquery IDE, which may still filter by `ProtocolName` or use older conditions and time windows. Use the code on this page when you need Uniswap's own pools only. ## Live Uniswap v3 Trades on Polygon (Trading API, recommended) This subscription streams every Uniswap v3 trade on Polygon in real time with **USD price and USD amounts on every row**, MEV-filtered. Run it [in the IDE](https://ide.bitquery.io/Trading-API-Uniswap-v3-Trades-Matic). ```graphql subscription { Trading { Trades( where: {Pair: {Market: {Network: {is: "Matic"}, Address: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}}} ) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` ## Get Latest Trades on Uniswap v3 The query below returns the [latest DEX trades on MATIC Uniswap v3](https://ide.bitquery.io/uniswap-v3-trades-matic). ```graphql query MyQuery { EVM(dataset: realtime, network: matic) { DEXTrades( where: {Trade: {Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}}} limit: {count: 10} orderBy:{descending:Block_Time} ) { Transaction { From To } Trade { Dex { ProtocolName SmartContract } Buy { Currency { Name } Price Amount } Sell { Amount Currency { Name } Price } } Block { Time } } } } ``` ## Get Top Traders of a token on uniswap v3 This query returns the [top traders of a token](https://ide.bitquery.io/top-traders-of-a-token-on-uniswapv3-matic) on the selected network. It ranks `Transaction.From`, the account that sent each swap, since on a sale `Trade.Buyer` is the pool or a router. `Side.Type` describes the counter-side of each trade, so `bought` sums the rows where `Side.Type` is `sell`. `PriceAsymmetry: {lt: 0.1}` drops trades whose two sides disagree badly on value ([PriceAsymmetry reference](/docs/graphql/metrics/priceAsymmetry/)), which would otherwise inflate the USD totals. ```graphql query topTraders($network: evm_network, $token: String) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {SmartContract: {is: $token}}, Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}, PriceAsymmetry: {lt: 0.1}}} ) { Transaction { From } Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "network": "matic", "token": "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270" } ``` ## OHLC in USD of a Token This query retrieves [hourly open, high, low and close prices in USD](https://ide.bitquery.io/OHLCV-on-MATIC-uniswap-v3#) for one token traded on Uniswap v3. ```graphql { EVM(network: matic, dataset: realtime) { DEXTradeByTokens( orderBy: {descendingByField: "Block_testfield"} where: {Trade: {Currency: {SmartContract: {is: "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270"}}, PriceAsymmetry: {lt: 0.1}, Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}, Side: {Currency: {SmartContract: {is: "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359"}}, Type: {is: buy}}}} limit: {count: 10} ) { Block { testfield: Time(interval: {in: hours, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) open: PriceInUSD(minimum: Block_Number) close: PriceInUSD(maximum: Block_Number) } count } } } ``` ## Get trading volume, buy volume, sell volume of a token This query returns the [traded, buy and sell volume](https://ide.bitquery.io/trade_volume_matic_uniswapv3) of token `0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270` on Uniswap v3 over the last 24 hours. `PriceAsymmetry: {lt: 0.1}` drops mispriced trades, which would otherwise skew the USD sums. ```graphql query MyQuery { EVM(network: matic) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270"}}, Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}, PriceAsymmetry: {lt: 0.1}}, TransactionStatus: {Success: true}, Block: {Time: {since_relative: {hours_ago: 24}}}} ) { Trade { Currency { Name Symbol SmartContract Decimals } } traded_volume_in_usd: sum(of: Trade_Side_AmountInUSD) sell_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) buy_volume_in_usd: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) } } } ``` ## Get top bought tokens on uniswap v3 This query returns the [top bought tokens on Uniswap v3](https://ide.bitquery.io/top-bought-tokens-on-matic-uniswap-v3_4). Buys are the rows where `Side.Type`, the counter-side, is `sell`. The `PriceAsymmetry` filter keeps mispriced trades out of the totals. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "matic" } ``` ## Get top sold tokens on uniswap v3 This query returns the [top sold tokens on Uniswap v3](https://ide.bitquery.io/top-sold-tokens-on-matic-uniswap-v3). Sales are the rows where `Side.Type`, the counter-side, is `buy`. ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}, PriceAsymmetry: {lt: 0.1}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) } } } { "network": "matic" } ``` --- ## Polygon Transfers API: Token and POL Transfers, Whale Alerts, Backfills URL: https://docs.bitquery.io/docs/blockchain/Matic/matic-transfers/ Polygon transfers with Bitquery GraphQL: large USDC moves, one wallet's history and live activity, NFT transfers, a Polymarket check, gap-free backfills. # Polygon Transfers API: Token and POL Transfers, Whale Alerts, Backfills Every ERC-20, ERC-721, ERC-1155 and native POL transfer on Polygon is a row in the `Transfers` cube under `EVM(network: matic)`, with sender, receiver, amount, USD value where a price exists, the token, and the transaction. Polygon's volume has its own shape: stablecoin flows, Polymarket's conditional tokens, which are ERC-1155 and show up as NFT transfers, and bridge and distributor contracts that send tens of thousands of transfers an hour. The examples below pick from that. The same filters run as a query for the latest rows or as a subscription for a live feed, and `dataset: combined` on the root reaches history. Every example runs in the [IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. ## Large USDC transfers Native USDC on Polygon is `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359`. The query form lists transfers of 10,000 or more in the last day; change `query` to `subscription` and drop `Block`, `limit` and `orderBy` for an alert. Saved stream [here](https://ide.bitquery.io/Whale-transfers-of-USDC-on-matic). ```graphql { EVM(network: matic) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359" } } Amount: { ge: "10000" } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol } } Transaction { Hash } } } } ``` ## Transfers sent by one wallet On the `combined` dataset the query shows a wallet's history even if it has been idle for months. Saved query [here](https://ide.bitquery.io/Sender-is-a-particular-address_2). ```graphql { EVM(network: matic, dataset: combined) { Transfers( where: { Transfer: { Sender: { is: "0x1A8f43e01B78979EB4Ef7feBEC60F32c9A72f58E" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Amount AmountInUSD Currency { Symbol SmartContract Native } Receiver } Transaction { Hash } } } } ``` As a stream, pick an address that moves. The one below is a distributor contract that sends thousands of transfers an hour, so messages arrive at once; a personal wallet streams only when it transacts. ```graphql subscription { EVM(network: matic) { Transfers( where: { Transfer: { Sender: { is: "0xe111180000d2663c0091e4f400237545b87b996b" } } } ) { Block { Time } Transfer { Amount Currency { Symbol SmartContract } Receiver } Transaction { Hash } } } } ``` ## NFT transfers, including Polymarket positions `Currency.Fungible: false` keeps ERC-721 and ERC-1155 rows. On Polygon most of them are Polymarket outcome tokens, ERC-1155 positions minted and moved by the conditional tokens contract. Saved stream [here](https://ide.bitquery.io/NFT-Token-Transfers-API_3). ```graphql subscription { EVM(network: matic) { Transfers(where: { Transfer: { Currency: { Fungible: false } } }) { Block { Time } Transfer { Id Amount Sender Receiver Currency { Name SmartContract } } Transaction { Hash } } } } ``` ## Has an address ever used Polymarket Polymarket settles positions through the conditional tokens contract, `0x4d97dCd97eC945f40cF65F87097ACe5EA0476045`. One received transfer of its tokens is enough for a yes, which is cheaper than scanning prediction trades when a yes or no is all you need. Saved query [here](https://ide.bitquery.io/check-if-an-address-interacted-with-polymarket-ever). ```graphql { EVM(dataset: combined, network: matic) { Transfers( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Transfer: { Receiver: { is: "0x0c79f21ec570f5cc0d52d1bc640845faef430ad2" } Currency: { SmartContract: { is: "0x4d97dCd97eC945f40cF65F87097ACe5EA0476045" } } } } ) { Block { Time } Transfer { Id Amount } Transaction { Hash } } } } ``` ## Deterministic pagination for backfilling To load transfers into your own index without gaps or repeats, page in a fixed order: the composite `orderBy` positions every transfer uniquely, and `offset` moves by `count` on each request, up to 25,000 rows per call. This ordering runs on the realtime window; on the `archive` dataset order by `Block_Number` and page one block range at a time. Saved query [here](https://ide.bitquery.io/Reliable-transfer-api). ```graphql { EVM(network: matic) { Transfers( where: { Transfer: { Success: true } } orderBy: { ascending: [ Block_Number Transaction_Index Call_Index Log_Index Transfer_Index Transfer_Type ] } limit: { count: 100, offset: 0 } ) { Block { Number Time } Transaction { Hash Index } Transfer { Amount Sender Receiver Index Type Currency { Symbol SmartContract Native } } Call { Index } Log { Index } } } } ``` ## Related pages - [Polygon API hub](/docs/blockchain/Matic/) - [Polygon DEX trades API](/docs/blockchain/Matic/matic-dextrades) - [Polygon NFT API](/docs/blockchain/Matic/matic-nft) - [Transfers cube](/docs/cubes/transfers-cube) --- ## Polygon Uniswap V4 API URL: https://docs.bitquery.io/docs/blockchain/Matic/uniswap-v4-api/ Polygon Uniswap V4 API: query Polygon Uniswap trades, pools, and prices with Bitquery GraphQL DEX APIs. Copy GraphQL snippets for production apps. # Uniswap V4 API - Track Trader Activities, Token Trades and Market Behavior :::tip Need real-time Uniswap V4 (Polygon) data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Uniswap V4 (Polygon) swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Uniswap V4 (Polygon) data older than ~30 days**, raw per-swap detail, or call / event context. ::: Uniswap v4 introduces a major shift in protocol architecture. Instead of deploying a separate smart contract for each liquidity pool, Uniswap v4 uses a singleton PoolManager contract that manages all pools internally as structured state. Each pool in Uniswap v4 is uniquely identified by a `PoolId`, which is derived from the pool configuration (token pair, fee, tick spacing, and optional hooks), rather than a dedicated contract address. Using Bitquery's Uniswap v4 APIs, you can track: - DEX trades across all v4 pools - Trades by specific traders - Token-level trade activity - Real-time trade metrics The Uniswap v4 PoolManager contract emits all pool-related events, including pool initialization, swaps, and liquidity modifications, and serves as the single on-chain source of truth for Uniswap v4 activity on Matic. ## Real time Trades on Uniswap V4 [This](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-matic) subscription allows user to stream trades on Uniswap V4 in real time on Matic. ```graphql subscription { EVM(network: matic) { DEXTrades(where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v4"}}}}) { Block{ Time } Trade { PoolId Buy { Currency { Name Symbol SmartContract Decimals } Buyer Amount AmountInUSD Price PriceInUSD Seller } Sell { Currency { Name Symbol SmartContract Decimals } Buyer Amount AmountInUSD Price PriceInUSD Seller } } Transaction { From To Hash } } } } ``` ## Get All Pool Ids for a Currency Using [this](https://ide.bitquery.io/get-virtual-pool-address-for-a-token-on-uniswap-v4-matic) API we can get all the virtual pool addresses (`PoolId`) for a currency on Matic. ```graphql query MyQuery { EVM(network: matic) { DEXTradeByTokens( where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v4"}}, Currency: {SmartContract: {is: "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063"}}}} ) { Trade { PoolId } count } } } ``` ## Latest Trades for a Specific Currencies Pair [This](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-matic_1) API endpoint allows us to filter out the latest trades for a specific pair on Matic, using `PoolId` as a filter option. ```graphql { EVM(network: matic) { DEXTrades( orderBy: {descending: Block_Time} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v4"}}, PoolId: {is: "0x23bf8c631d30c092865d2f583f601a7080b7e3f4cb3dcbf29e622a693087a916"}}} ) { Block { Time } Trade { PoolId Buy { Currency { Name Symbol SmartContract Decimals } Amount AmountInUSD Price PriceInUSD Seller } Sell { Currency { Name Symbol SmartContract Decimals } Buyer Amount AmountInUSD Price PriceInUSD } } Transaction { From To Hash } } } } ``` ## Uniswap V4 Pair Trade Stats Using [this](https://ide.bitquery.io/trade-stats-for-a-token-pair-on-uniswap-v4-matic_1) query get pool stats (volume, bought, sold) for a specific Uniswap V4 pool on Matic. ```graphql query pairTopTraders { EVM(network: matic, dataset: realtime) { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } where: { Block:{ Time: {since_relative: {days_ago: 1}} } Trade: { Dex: { ProtocolName: {is: "uniswap_v4"} } PoolId: {is: "0x23bf8c631d30c092865d2f583f601a7080b7e3f4cb3dcbf29e622a693087a916"} } } ) { Trade { Currency{ Name Symbol SmartContract } } bought: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) sold: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Top Buyers of a Token on Uniswap V4 [This](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-matic) API returns the top buyers of a token on Uniswap V4 virtual pool on Matic, along with the amount bought in token denominations and USD. ```graphql { EVM(network: matic) { DEXTrades( orderBy: {descendingByField: "bought_in_usd"} limit: {count: 100} where: { Trade: { Dex: {ProtocolName: {is: "uniswap_v4"}}, Buy: {Currency: {SmartContract: {is: "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063"}}} PoolId: {is: "0x23bf8c631d30c092865d2f583f601a7080b7e3f4cb3dcbf29e622a693087a916"} } } ) { Trade { Sell { Currency { Name Symbol SmartContract Decimals } Buyer } } bought:sum(of: Trade_Buy_Amount) bought_in_usd:sum(of: Trade_Buy_AmountInUSD) } } } ``` ## Top Sellers of a Token on Uniswap V4 [This](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-pool-matic) API returns the top sellers of a token on Uniswap V4 virtual pool on Matic, along with the amount sold in token denominations and USD. ```graphql { EVM(network: matic) { DEXTrades( orderBy: {descendingByField: "sold_in_usd"} limit: {count: 10} where: { Trade: { Dex: {ProtocolName: {is: "uniswap_v4"}}, Sell: {Currency: {SmartContract: {is: "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063"}}} PoolId: {is: "0x23bf8c631d30c092865d2f583f601a7080b7e3f4cb3dcbf29e622a693087a916"} } } ) { Trade { Buy { Currency { Name Symbol SmartContract Decimals } Seller } } sold:sum(of: Trade_Buy_Amount) sold_in_usd:sum(of: Trade_Buy_AmountInUSD) } } } ``` --- ## Polymarket AI & Tech Markets API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-ai-tech-api/ Polymarket AI and tech markets: newly created markets, live odds, OHLC odds movement, top markets by volume, resolved markets and whale-bet alerts. # Polymarket AI & Tech Markets API Get full access to **Polymarket AI and tech prediction markets** through one API. That covers OpenAI, GPT, Anthropic, AGI, and big-tech bets, with live odds (implied probability), trades, volume, market creation and resolution, and trader activity. Bitquery runs **its own blockchain nodes** and **indexes, decodes, and parses** raw Polygon transactions into clean, structured prediction-market data. You don't have to run nodes, decode contract logs, or stitch together odds yourself. The same data is available three ways: - **Historical queries:** backfill odds, volume, and resolutions over any time range. - **Real-time GraphQL subscriptions (WebSocket):** stream new trades and odds the moment they hit the chain. - **Kafka streams:** low-latency, high-throughput feeds for production pipelines. Every query below can be run live by changing `query` to `subscription`. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. See [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/). ::: --- ## How AI & Tech Markets Are Identified AI and tech markets are matched by a keyword in `Question.Title` using `includesCaseInsensitive`. The same filter works on **PredictionManagements**, **PredictionTrades**, and **PredictionSettlements**, placed under `Prediction.Question.Title`. | Topic | Example `Question.Title` keyword | | ---------------- | -------------------------------- | | OpenAI | `"OpenAI"` | | ChatGPT / GPT | `"GPT"` | | Anthropic | `"Anthropic"` | | Claude | `"Claude"` | | Google Gemini | `"Gemini"` | | xAI / Grok | `"Grok"` | | AGI | `"AGI"` | | Big Tech | `"Apple"`, `"Nvidia"`, `"Tesla"` | > **Tip:** To match the whole AI category, use the standalone word with surrounding spaces, `" AI "`. This avoids the substring trap where a bare `"AI"` also catches unrelated words such as "Spain" or "fair". For a specific company or model, use a precise term like `"OpenAI"` or `"GPT"`. A single market is uniquely identified by its `Question.MarketId`. --- ## Latest AI Markets Created Returns the 10 most recent **Created** events for Polymarket markets whose title includes the standalone word **" AI "** (note the surrounding spaces). Swap the keyword for any term from the table above. [Run in Bitquery IDE](https://ide.bitquery.io/Latest-AI-markets-created-on-Polymarket) ```graphql query LatestAIMarketsCreated { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Created" } Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: " AI " } } } } } ) { Block { Time } Management { Description EventType Prediction { Condition { Id QuestionId Outcomes { Index Label } } Outcome { Index Label } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { Hash } } } } ``` --- ## Live Odds (Implied Probability) for an AI Market Returns the **latest trade price per outcome** for one market by `MarketId`. This is the **live implied probability** for that question. On Polymarket an outcome's `Price` ranges from 0 to 1 and equals its implied probability (e.g. `0.62` = 62%). Replace `""` with a market ID from the creation query above. Change `query` to `subscription` for a live odds feed. [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-AI-market-live-odds) ```graphql query AIMarketLiveOdds { EVM(network: matic) { PredictionTrades( limitBy: { by: Trade_Prediction_Outcome_Label, count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { MarketId: { is: "" } } } } } ) { Trade { OutcomeTrade { Price PriceInUSD } Prediction { Outcome { Index Label } OutcomeToken { Name AssetId } Question { Title MarketId ResolutionSource Image } } } } } } ``` --- ## Odds (Line) Movement: OHLC for an Outcome Returns **OHLC** (Open, High, Low, Close) in USD for one outcome of an AI market, bucketed by interval (here 5 minutes). It shows how the implied probability moved over time, and powers charts and backtests. Replace `""` and `""` (e.g. `"Yes"` or `"No"`). [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-AI-odds-movement-OHLC) ```graphql query AIOddsMovementOHLC { EVM(network: matic) { PredictionTrades( limit: { count: 100 } orderBy: { descendingByField: "Block_Interval" } where: { Trade: { Prediction: { Question: { MarketId: { is: "" } } Outcome: { Label: { is: "" } } } } } ) { Block { Interval: Time(interval: { count: 5, in: minutes }) } Trade { OutcomeTrade { Open: PriceInUSD(minimum: Block_Time) High: PriceInUSD(maximum: Trade_OutcomeTrade_PriceInUSD) Low: PriceInUSD(minimum: Trade_OutcomeTrade_PriceInUSD) Close: PriceInUSD(maximum: Block_Time) } Prediction { OutcomeToken { Name AssetId } Outcome { Id Label } } } } } } ``` --- ## Top AI Markets by Volume (Last 24 Hours) Returns AI markets (title includes the standalone word **" AI "**) ranked by USD trading volume in the last 24 hours, with buyer and seller counts. Adjust `time_ago`, `limit`, and the title keyword as needed. [Run in Bitquery IDE](https://ide.bitquery.io/Top-AI-markets-by-volume-Polymarket) ```graphql query TopAIMarketsByVolume($time_ago: Int!, $limit: Int!) { EVM(network: matic) { PredictionTrades( where: { Block: { Time: { since_relative: { hours_ago: $time_ago } } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: " AI " } } } } } limit: { count: $limit } orderBy: { descendingByField: "sumBuyAndSell" } ) { Trade { Prediction { Question { Id Image Title MarketId CreatedAt } } } buyUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { IsOutcomeBuy: true } } } ) sellUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { IsOutcomeBuy: false } } } ) sumBuyAndSell: calculate(expression: "$buyUSD + $sellUSD") trades: count buyers: count(distinct: Trade_OutcomeTrade_Buyer) sellers: count(distinct: Trade_OutcomeTrade_Seller) } } } ``` Variables: ```json { "time_ago": 24, "limit": 100 } ``` --- ## Latest Resolved AI Markets Returns the 10 most recent **Resolved** AI markets, including the winning outcome. Use this to grade results and settle positions. [Run in Bitquery IDE](https://ide.bitquery.io/Latest-resolved-AI-markets-Polymarket) ```graphql query LatestResolvedAIMarkets { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Resolved" } Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: " AI " } } } } } ) { Block { Time } Management { Description EventType Prediction { Outcome { Index Label } Question { Title MarketId ResolutionSource Image CreatedAt } } } Transaction { Hash } } } } ``` --- ## Real-Time Whale-Bet Alerts (Subscription) Streams live AI-market trades above a USD threshold (here `$5,000`). This is ideal for whale-alert bots and detecting large, conviction bets. Filter with a `Question.Title` keyword, or swap it for a single-market `MarketId`. Change `subscription` to `query` for historical results. [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-AI-whale-trades-stream) ```graphql subscription { EVM(network: matic) { PredictionTrades( where: { Trade: { OutcomeTrade: { CollateralAmountInUSD: { gt: "5000" } } Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: " AI " } } } } } ) { Block { Time } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmountInUSD Price PriceInUSD IsOutcomeBuy } Prediction { Question { Title MarketId ResolutionSource Image } Outcome { Index Label } } } Transaction { From Hash } } } } ``` --- ## Real-Time: GraphQL Subscriptions and Kafka ### GraphQL Subscriptions Any query on this page can be run as a subscription. Keep the same `where` filters and fields, and change the keyword `query` to `subscription`. You receive new events as they occur on Polygon over a WebSocket connection. ### Kafka Streams For low-latency consumption, prediction market data (including AI and tech markets) is available via Kafka: - **`matic.predictions.proto`:** Raw prediction market events (creations, resolutions, trades) - **`matic.broadcasted.predictions.proto`:** Mempool prediction market data Kafka requires separate credentials. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). For access, [contact support](https://t.me/bloxy_info) or email support@bitquery.io. --- ## Related APIs | Need | API | | ---- | --- | | **Live odds, trades, volume by sport** | [Polymarket Sports API](/docs/examples/polymarket-api/polymarket-sports-api/) | | **Commodity markets (gold, oil)** | [Polymarket Commodity API](/docs/examples/polymarket-api/polymarket-commodity-api/) | | **Bitcoin up or down odds** | [Polymarket Bitcoin API](/docs/examples/polymarket-api/bitcoin-polymarket-api/) | | **Insider & fresh-wallet detection** | [Polymarket Insider Detection API](/docs/examples/polymarket-api/polymarket-insider-detection-api/) | | **Trader realized PnL & win rate** | [Realized PnL & Win Rate for Polymarket Trader](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/) | | **Settlements & redemptions** | [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) | | **Real-time: Kafka streams** | [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) | --- ## Support - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket API - Advanced Analytics URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-advanced-analytics-api/ Polymarket analytics: USDC TVL, daily volume, hourly buy vs sell order flow, whale trade subscriptions, open interest by date and top markets by 24h volume. # Polymarket API - Advanced Analytics This guide shows **GraphQL examples** for deeper **Polymarket** metrics on **Polygon** (`network: matic`): **TVL** of Polymarket, **daily trade aggregates**, **buy vs sell pressure** for a market, **large-trade streaming**, **split/merge settlement** totals, and **top markets by volume**. All examples use `dataset: realtime`, which covers about the **last 4 days** of data. Use it together with the [Polymarket API](/docs/examples/polymarket-api/), [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/), and [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/). :::note API Key Required To run these queries outside the Bitquery IDE, you need an API access token. See [How to generate Bitquery API token](/docs/authorization/how-to-generate/). ::: :::tip Contract addresses Since the April 2026 migration, Polymarket trades on the **CTF Exchange** `0xE111180000d2663C0091e4f400237545B87B996B` and **Neg Risk CTF Exchange** `0xe2222d279d744050d28e00520010520000310F59`, and settles in **pUSD** `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` (a USDC-backed wrapper around USDC.e). Confirm addresses against the [Polymarket contracts page](https://docs.polymarket.com/resources/contracts) before production use; deployments can change over time. ::: :::note Dataset: `realtime` and retention Polymarket prediction-market data on Polygon (`PredictionTrades`, `PredictionSettlements`, and related examples on this page) use `dataset: realtime`. This dataset holds roughly the **last 4 days**, so use time filters that fall inside that window. For history from 1 September 2025, add the [Polymarket Historical Data add-on](https://bitquery.io/pricing) and switch to `dataset: archive` or `dataset: combined`. For bulk loads, use a [Data Store export](/docs/cloud/polymarket/). ::: --- ## Overview | Topic | API | What you get | | ------------------------------------ | --------------------------------- | ------------------------------------------------------------------------------------- | | **TVL Polymarket** | `TransactionBalances` | Latest **USDC.e** and **pUSD** balances for listed custody addresses | | **Daily volume & maker/taker split** | `PredictionTrades` | **Shares** (`Amount`), **USDC** collateral, split by **Buyer** vs CTF-style addresses | | **Order flow (hourly)** | `PredictionTrades` | **Buy** vs **sell** pressure using `IsOutcomeBuy`, optional **market title** filter | | **Whale trades** | `PredictionTrades` (subscription) | Trades above a **USD** threshold | | **open Interest (one day)** | `PredictionSettlements` | **Split** / **merge** USDC and **net** (liquidity-style proxy, not CLOB OI) | | **Top markets by volume** | `PredictionTrades` | Markets ranked by **buy + sell** USD over **24 hours** | --- --- ## USDC TVL: balances for Conditional Tokens and neg-risk collateral Summarize collateral held by **Conditional Tokens** and **neg-risk wrapped collateral** contracts. Traders now hold and settle in **pUSD** (`0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB`), but the collateral adapters unwrap it on the way in, so custody inside these contracts is still **USDC.e** (`0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174`). The query reads both tokens; expect USDC.e to carry almost all of the balance. Extend the `Address` list if you track additional custodians. [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-TVL) ```graphql query PolymarketCollateralTVL { EVM(dataset: realtime, network: matic) { TransactionBalances( where: { TokenBalance: { Address: { in: [ "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045" "0x3A3BD7bb9528E159577F7C2e685CC81A765002E2" ] } Currency: { SmartContract: { in: [ "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB" "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" ] } Fungible: true } } } ) { TokenBalance { Address PostBalance(maximum: Block_Time) PostBalanceInUSD(maximum: Block_Time) Currency { Symbol SmartContract Decimals } } } } } ``` --- ## Daily volume: notional shares, USDC, and buyer-address split For a **single calendar day** (UTC), aggregate: - **volume_notional_shares**: sum of outcome `Amount` (share-like notional) - **volume_usdc**: sum of `CollateralAmountInUSD` - **taker_volume_usdc_address_rule**: USDC where `Buyer` is in `$PolymarketContractAddresses` - **maker_volume_usdc_address_rule**: USDC where `Buyer` is **not** in that list Use `dataset: realtime` (see the **Dataset: realtime and retention** note at the top of this page). [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-Notional-Volume-Taker-VolumeMaker-Volume) ```graphql query PolymarketVolume( $date: String! $PolymarketContractAddresses: [String!]! ) { EVM(dataset: realtime, network: matic) { PredictionTrades( where: { TransactionStatus: { Success: true } Block: { Date: { is: $date } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Date } volume_notional_shares: sum(of: Trade_OutcomeTrade_Amount) volume_usdc: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) taker_volume_usdc_address_rule: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { Buyer: { in: $PolymarketContractAddresses } } } } ) maker_volume_usdc_address_rule: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { Buyer: { notIn: $PolymarketContractAddresses } } } } ) } } } ``` **Variables (example):** ```json { "date": "2026-09-17", "PolymarketContractAddresses": [ "0xe111180000d2663c0091e4f400237545b87b996b", "0xe2222d279d744050d28e00520010520000310f59" ] } ``` --- ## Order flow: buy vs sell pressure by hour Bucket trades by **hour** and split **collateral USD** using `IsOutcomeBuy` (see [Prediction Trades API: trade direction](/docs/examples/prediction-market/prediction-trades-api/)). ### One market (filter by exact question title) [Run in Bitquery IDE](https://ide.bitquery.io/buy-sell-pressure-of-aspecific-market) ```graphql query PolymarketOrderFlowPressureOneMarket( $hours_ago: Int! $marketTitle: String! ) { EVM(dataset: realtime, network: matic) { PredictionTrades( orderBy: { ascending: Block_Time } where: { TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: $hours_ago } } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { is: $marketTitle } } } } } ) { Block { Time(interval: { count: 1, in: hours }) } Trade { Prediction { Question { MarketId Title } } } buy_pressure_usd: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { IsOutcomeBuy: true } } } ) sell_pressure_usd: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { IsOutcomeBuy: false } } } ) } } } ``` **Variables (example):** ```json { "hours_ago": 24, "marketTitle": "US x Iran ceasefire by April 30?" } ``` --- ## Whale trades: subscription above a USD threshold Stream **successful** Polymarket trades whose **collateral** exceeds **$10,000** USD. Adjust the threshold string as needed. [Run in Bitquery IDE](https://ide.bitquery.io/polymarket-whale-trades-alert_1) ```graphql subscription PolymarketWhaleTradesAlert { EVM(dataset: realtime, network: matic) { PredictionTrades( where: { TransactionStatus: { Success: true } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } OutcomeTrade: { CollateralAmountInUSD: { gt: "10000" } } } } ) { Block { Time } Trade { OutcomeTrade { Buyer Seller CollateralAmount CollateralAmountInUSD Price PriceInUSD IsOutcomeBuy } Prediction { Question { Title MarketId } Outcome { Label } } } Transaction { Hash } } } } ``` --- ## Open Interest on Polymarket on a specific date For a **calendar day**, sum **Split** and **Merge** **collateral USD** and the **net** (`split − merge`). This describes **Open Interest** of that day. [Run in Bitquery IDE](https://ide.bitquery.io/Open-Interest-on-a-day) ```graphql query PolymarketSettlementFlowOneDay($day: String!) { EVM(dataset: realtime, network: matic) { PredictionSettlements( where: { Block: { Date: { is: $day } } Settlement: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { split_usd: sum( of: Settlement_Amounts_CollateralAmountInUSD if: { Settlement: { EventType: { is: "Split" } } } ) merge_usd: sum( of: Settlement_Amounts_CollateralAmountInUSD if: { Settlement: { EventType: { is: "Merge" } } } ) net_split_merge_usd: calculate(expression: "$split_usd - $merge_usd") } } } ``` **Variables (example):** ```json { "day": "2026-03-22" } ``` --- ## Top markets by volume: last 24 hours Rank **Polymarket** markets by **buy + sell** collateral USD, with **buy/sell** breakdown, **trade count**, **distinct buyers/sellers**, and optional **resolution** join. Uses `limitBy: Trade_Prediction_Question_Id` so each row is **one market**. [Run in Bitquery IDE](https://ide.bitquery.io/top-100-markets-by-volumein-last24-hrs_1) ```graphql query topMarketsByVolume($limit: Int!) { EVM(network: matic) { PredictionTrades( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } } limitBy: { count: 1, by: Trade_Prediction_Question_Id } limit: { count: $limit } orderBy: { descendingByField: "sumBuyAndSell" } ) { Trade { Prediction { Question { Id Image Title CreatedAt } OutcomeToken { assetId0: AssetId( if: { Trade: { Prediction: { Outcome: { Index: { eq: 0 } } } } } ) assetId1: AssetId( if: { Trade: { Prediction: { Outcome: { Index: { eq: 1 } } } } } ) } Outcome { label0: Label( if: { Trade: { Prediction: { Outcome: { Index: { eq: 0 } } } } } ) label1: Label( if: { Trade: { Prediction: { Outcome: { Index: { eq: 1 } } } } } ) } } OutcomeTrade { price0: Price( maximum: Block_Time if: { Trade: { Prediction: { Outcome: { Index: { eq: 0 } } } } } ) price1: Price( maximum: Block_Time if: { Trade: { Prediction: { Outcome: { Index: { eq: 1 } } } } } ) } } buyUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { IsOutcomeBuy: true } } } ) sellUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { OutcomeTrade: { IsOutcomeBuy: false } } } ) sumBuyAndSell: calculate(expression: "$buyUSD + $sellUSD") trades: count buyers: count(distinct: Trade_OutcomeTrade_Buyer) sellers: count(distinct: Trade_OutcomeTrade_Seller) resolved: joinPredictionManagements( join: left Management_Prediction_Question_Id: Trade_Prediction_Question_Id ) { Block { Time( maximum: Block_Time if: { Management: { EventType: { is: "Resolved" } } } ) } } } } } ``` **Variables (example):** ```json { "limit": 100 } ``` --- ## Related APIs | Need | Doc | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | Trades, prices, filters | [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/) | | Splits, merges, redemptions | [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) | | Condition ID, slug, token | [Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api/) | | Overview | [Polymarket API](/docs/examples/polymarket-api/) | | Wallet-level activity | [Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/) | | Token balances (USDC) | [Token Balance API](/docs/blockchain/Ethereum/balances/transaction-balance-tracker/token-balance-api/) | --- ## Support - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket API vs Bitquery Polymarket API (2026) URL: https://docs.bitquery.io/docs/API-Blog/polymarket-api-vs-bitquery-polymarket-api/ Official Polymarket APIs (Gamma, CLOB, Data API v2) compared with Bitquery's on-chain Polymarket API: what each does, limits, and when to use both. # Polymarket API vs Bitquery Polymarket API If you are building on Polymarket, whether a dashboard, a trading bot, a research tool, or a wallet leaderboard, you have two very different data stacks to choose from. Polymarket publishes a set of **official REST and WebSocket APIs** that serve the [polymarket.com](https://polymarket.com) application itself. Bitquery offers an **on-chain-derived GraphQL API** for the same Polymarket markets on Polygon, plus subscriptions and Kafka streams. Both give you Polymarket data. They are built for different jobs. This article walks through what each one does well, what it does not do, and when to combine them. ## TL;DR The official Polymarket APIs are the right tool when you need to **place orders**, read the **live order book**, or fetch Polymarket's own metadata (events, tags, user profiles, positions, bridge status). Those are off-chain order-book concerns. They are useful for execution and application views, but they stop where the trader's real questions begin. Bitquery's Polymarket API is the right tool for **traders and researchers**: on-chain-grounded trades, realized P&L, wallet histories, whale filtering, top-trader leaderboards, settlement flows, and cross-market analytics. An off-chain order book can tell you the current bid and your own fills; it cannot tell you **who the best traders on Polymarket are, how much every wallet has won or lost, which markets are seeing whale accumulation, or how flows move between outcomes across the protocol**. That is what on-chain trade data, exposed as GraphQL, subscriptions, and Kafka streams, is for. In most serious production stacks the two complement each other: CLOB for execution and event/market metadata, Bitquery for trader analytics, P&L, streaming, history, and anything that needs GROUP BY. ## What changed in 2026 Three changes on Polymarket's side are worth knowing before you pick a stack: - **New exchange contracts and pUSD.** In April 2026 Polymarket moved trading to new CTF Exchange contracts (`0xE111180000d2663C0091e4f400237545B87B996B` and the Neg Risk exchange `0xe2222d279d744050d28e00520010520000310F59`) and switched collateral from USDC.e to **pUSD**, a USDC-backed wrapper. Order structs and SDK package names changed with it. Bitquery queries filtered by `ProtocolName: "polymarket"` keep working; only hardcoded addresses need updating. - **Data API v2.** `data-api.polymarket.com/v2` adds cursor pagination and a shared response envelope for wallet activity, market data and trader analytics. That makes it a better per-account and per-market API than v1, but you still page through REST, so protocol-wide aggregates remain a client-side job. - **In-house indexing.** In September 2026 Polymarket said it now indexes Polygon itself (built on rindexer) with Goldsky as backup, which makes its own app and APIs faster to reflect on-chain events. For builders this mostly improves the official APIs' freshness; it does not add GraphQL aggregation, Kafka delivery, joins with other Polygon data, or warehouse exports. None of this moves the line between the two stacks. The official APIs got faster and easier to page through for execution and account views, and cross-market analytics and streaming still need an on-chain index. ## Polymarket's official API surface Polymarket splits its public surface into three REST APIs plus two WebSocket streams. The **Gamma API** at gamma-api.polymarket.com is the market-discovery layer. It indexes every event, market, tag, sports category, and series on the platform, and exposes endpoints such as /events, /markets, /public-search, /tags, /series, and /sports, along with lookups by market ID or slug. It requires no authentication, supports filtering by active/closed and tag, sorting by 24h volume, liquidity, start/end date, and returns Polymarket's canonical structure: events are top-level questions, markets are tradable binary outcomes nested inside them. Rate limits are generous for read traffic, at roughly 4,000 requests per 10 seconds overall, with per-endpoint caps such as /events at 500/10s and /markets at 300/10s. Gamma does not serve price history, on-chain balances, or order placement. The **CLOB API** at clob.polymarket.com is the trading layer. It handles order submission, order-book reads, price history (/prices-history), trade history, and user order management. Authenticated endpoints use API-key credentials derived from wallet signatures (Ethereum/Polygon private key signing with HMAC-SHA256 request signing), while order-book and price endpoints are public. Order submission is rate-limited in the order of 10 requests per second, and WebSocket connections are capped at around 5 concurrent per IP. The CLOB is also where you subscribe to the real-time market and user channels at wss://ws-subscriptions-clob.polymarket.com/ws/market and /ws/user. The **Data API** at data-api.polymarket.com (now with a **v2** at `/v2` using cursor pagination) is the user-data layer. Endpoints like GET /positions, GET /activity, and GET /trades fetch a wallet's current positions (size, average price, cash PnL, % PnL), trade history, and activity feed. Profile fields (name, pseudonym, bio, profile image) are joined inline. Polymarket also runs a public-profile endpoint on Gamma (`GET /public-profile?address=`) and a Bridge API for deposits/withdrawals. Finally, the **Real-Time Data Socket** at wss://ws-live-data.polymarket.com broadcasts activity and trades. In practice it is most useful for fills and order-book deltas; filtering by market_slug or event_slug has known gaps, and Polymarket does not currently support unsubscribing from channels mid-session. A few characteristics fall out of this design. The official APIs reflect the [polymarket.com](https://polymarket.com) application view: canonical market metadata, your own positions, and real-time fills, at high rate limits. They are tightly scoped to single-entity reads. They do not natively support aggregate queries like "top 100 wallets by Polymarket volume in the last 5 days" or "largest whale trades across every Bitcoin market", and they do not expose on-chain-level fields like transaction hash, block time, log signature, condition ID events, or split/merge settlements in a single query. Historical data depth is whatever the CLOB has persisted, which is fine for order history but less convenient for ad-hoc aggregates. ## Bitquery's Polymarket API Bitquery takes a different approach. It indexes the Polymarket contracts on Polygon directly, normalizes the events into a GraphQL schema, and exposes the same operations as REST queries, GraphQL subscriptions (WebSocket), or Kafka streams. Every Polymarket query lives under EVM(network: matic) with dataset: realtime, and filters on Marketplace.ProtocolName: "polymarket". The pages under `docs/examples/polymarket-api/` in this repo correspond to these guides: - [Polymarket API overview](/docs/examples/polymarket-api/): the entry point, covering the core PredictionTrades query, live subscriptions, whale trades, and top buyers and sellers. - [Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api/): filter markets by market_slug, condition_id, or token_id through PredictionManagements. - [Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/): recent trade counts, collateral totals, and distinct-market counts for any wallet, plus guidance on which fields belong to Polymarket's Profile, Gamma, or Bridge APIs. - [Polymarket Advanced Analytics API](/docs/examples/polymarket-api/polymarket-advanced-analytics-api/): USDC TVL in core contracts, daily volume, maker/taker splits, order flow by market, whale subscriptions, settlement flows, and top markets by volume. - [Polymarket Sports API](/docs/examples/polymarket-api/polymarket-sports-api/): cricket, sports, and esports markets filtered by ResolutionSource, description, or outcome label. - [Polymarket Commodity API](/docs/examples/polymarket-api/polymarket-commodity-api/): oil, gold, and commodity-linked prediction markets. - [Bitcoin Up or Down Polymarket API](/docs/examples/polymarket-api/bitcoin-polymarket-api/): BTC direction markets, live odds, and top winners from settlements. - [Polymarket Wallet Realized PnL](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/): PnL derived from on-chain fills. Underneath, Bitquery's primary operations are PredictionTrades (buys and sells with buyer, seller, amount, price, USD-denominated collateral, and full market metadata), PredictionManagements (creation, resolution, and other lifecycle events), and PredictionSettlements (splits, merges, redemptions). Each can be run as a query for history or as a subscription for live streaming; swapping the single keyword is the only change required. For low-latency pipelines, Bitquery also publishes Kafka topics matic.predictions.proto and matic.broadcasted.predictions.proto (mempool), which require separate credentials. Because everything is GraphQL, aggregations, limitBy, orderBy: descendingByField, and computed expressions (e.g. `calculate(expression: "$buyUSD + $sellUSD")`) are built into the query language. That is what makes queries like "top 100 Polymarket markets by volume over a window" or "all whale trades above $10k across Polymarket in real time" one query instead of a client-side batch job over the CLOB. The one caveat is retention on the live endpoint: dataset: realtime holds roughly the **last 4 days**. The [Polymarket Historical Data add-on](https://bitquery.io/pricing) opens `dataset: archive` and `combined` back to 1 September 2025. For bulk loads, a **full historical Polymarket dataset (Parquet on S3, Snowflake, BigQuery) is available as a [Data Store export](https://bitquery.io/datastore) on request** (technical details: [Polymarket exports](/docs/cloud/polymarket/)), with no need to self-persist the stream. ## Side-by-side comparison | Capability | Polymarket official APIs | Bitquery Polymarket API | | --- | --- | --- | | **Place orders** | Yes, via CLOB /order with signed requests | No (read-only) | | **Live order book (bids/asks/depth)** | Yes, via CLOB REST + WS market channel | No; trades and settlements, not the L2 book | | **Event, market, tag, series metadata** | Yes, via Gamma API, canonical | Partial: market ID, question, outcomes, condition ID, resolution source (on-chain derived) | | **User positions / PnL** | Yes, via Data API /positions | Derivable from trades + settlements; [realized PnL example](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/) | | **User activity feed** | Yes, via Data API /activity | Yes, via [Wallet API](/docs/examples/polymarket-api/polymarket-wallet-api/) | | **Price history per token** | Yes, via CLOB /prices-history | Yes, via PredictionTrades with time filter | | **On-chain fields** (tx hash, block time, log signatures, condition ID events) | Limited | Yes, native on every row | | **Aggregations** (top N markets by volume, top wallets, maker/taker split) | Client-side | Native GraphQL: sum, count(distinct:), limitBy, orderBy: descendingByField | | **Whale trade filtering across all markets** | Manual | One subscription; see the [whale trades example](/docs/examples/polymarket-api/) | | **Real-time streaming** | WebSocket (ws-subscriptions-clob, ws-live-data), cannot unsubscribe, some filter gaps | GraphQL subscriptions plus Kafka matic.predictions.proto | | **Settlement (split / merge / redeem) analytics** | Indirect | Native; see [Advanced Analytics](/docs/examples/polymarket-api/polymarket-advanced-analytics-api/) | | **Cross-market vertical APIs** (sports, commodity, BTC up/down) | Filter manually on Gamma | Dedicated guides: [Sports](/docs/examples/polymarket-api/polymarket-sports-api/), [Commodity](/docs/examples/polymarket-api/polymarket-commodity-api/), [Bitcoin Up or Down](/docs/examples/polymarket-api/bitcoin-polymarket-api/) | | **TVL / collateral (pUSD, USDC.e) custody balances** | Not exposed | Yes, via TransactionBalances on Conditional Tokens + neg-risk collateral | | **Historical depth** | Full CLOB history | realtime dataset ~last 4 days; archive from 1 September 2025 with the history add-on; full history as [Parquet exports](/docs/cloud/polymarket/) for S3, Snowflake, BigQuery | | **Auth** | API-key + HMAC-SHA256 (CLOB); none (Gamma) | Bitquery API token; Kafka requires separate creds | | **Rate limits** | 4,000/10s (Gamma), ~10 orders/sec (CLOB) | No data or rate limits on streams; Kafka for enterprise streaming and scaling to 1,000+ simultaneous users | ## When to use which Reach for the **official APIs** when you are executing orders, showing a user their own positions and PnL as Polymarket displays them, reading live order-book depth for market-making or pricing, pulling the canonical event tree (tags, series, sports categories, cover images, resolution links), or wiring into Polymarket's deposit/withdrawal bridge. These are the authoritative source for "what does [polymarket.com](https://polymarket.com) show right now for this account." Reach for **Bitquery** when you need GraphQL aggregations, server-side filtering, and on-chain fields in a single request. Typical use cases include: - Leaderboards of top buyers and sellers by USD volume over a rolling window. - Whale monitors streaming every trade above a USD threshold across all markets from a single subscription. - Volume rankings for the top 100 Polymarket markets by buy-plus-sell USD in the last 24 hours. - Category dashboards for BTC up/down, sports, or commodity markets with live odds. - Settlement flow analytics using split/merge/redeem totals as a liquidity and open-interest proxy. - Low-latency pipelines consuming matic.predictions.proto from Kafka for mempool-level insight. - Cross-wallet clustering for forensic tracing of Polymarket activity. More advanced (alpha-focused) use cases: - **Alpha signals from order flow**: net buy-pressure imbalance per market as a directional signal, with USD-weighted buy vs sell sums over rolling windows. - **Smart-money tracking**: identify historically profitable wallets via realized PnL and copy their live trades through whale subscriptions filtered on Buyer/Seller. - **Mean-reversion on odds dislocations**: detect markets where outcome price moves sharply against thin liquidity by joining trade size to pre-trade mid-price. - **Momentum from whale accumulation**: flag condition IDs where top-N wallets turn net-long above a threshold within the last hour. - **News-vs-odds divergence**: cross-reference ResolutionSource updates against live odds subscriptions to surface mispriced markets around breaking events. - **Event-driven alpha**: pre-load markets by slug or tag (elections, earnings, fights, matches) and subscribe to whale trades as the event unfolds. - **Cross-market arbitrage**: correlate implied probabilities between related Polymarket markets (e.g. winner vs margin-of-victory) and flag inconsistent pricing. - **Settlement/redemption signals**: watch PredictionSettlements for large merges or redeems as a leading indicator that informed traders are closing positions. - **Mempool front-running detection**: use matic.broadcasted.predictions.proto to spot pending whale trades before they confirm, useful for both MEV research and defensive execution. - **Cohort-based backtests**: segment wallets by realized-PnL percentile over a window, replay their trades against historical odds, and test whether following the top cohort produces alpha. - **Liquidity-migration detection**: track USDC TVL changes across Conditional Tokens and neg-risk collateral to flag when capital is rotating between market clusters. - **Sentiment indices**: roll up weighted outcome probabilities across a category (macro, geopolitics, crypto) into a single index consumable by trading models. - **Risk and exposure monitoring**: for funds or market makers, aggregate position exposure across every condition ID a wallet has touched in real time. A reasonable production architecture looks like this: - **Gamma** for canonical market catalogs. - **CLOB** for execution and order-book depth. - **Data API** for user-facing account screens. - **Bitquery** for analytics, alerting, long-running streams, and any query that needs GROUP BY. ## A practical starting set If you are new to Bitquery's Polymarket coverage, four queries exercise most of the surface area: 1. The basic recent-trades query from the [Polymarket API overview](/docs/examples/polymarket-api/), which confirms your API token and shows the shape of a PredictionTrade. 2. The volume-ranking query from the same doc, which demonstrates limitBy, orderBy: descendingByField, and the computed sumBuyAndSell expression. 3. A live whale-trade subscription: swap the query keyword for subscription and filter on `CollateralAmountInUSD: { gt: "10000" }` to push events as they happen. 4. The daily volume and maker/taker split from the [Advanced Analytics page](/docs/examples/polymarket-api/polymarket-advanced-analytics-api/), which shows how far GraphQL takes you before any client-side aggregation is required. All of these are runnable from the Bitquery IDE (linked inline from each docs page) before you ever issue an API token. ## See it live If you want a visual reference for what Bitquery's Polymarket data looks like rendered as a live dashboard, showing top markets, whale trades, odds, and volumes, the [DexRabbit Polymarket Predictions dashboard](https://dexrabbit.bitquery.io/polymarket-predictions) runs directly on these APIs. Each panel ships with a "Get API" button that exposes the exact GraphQL query behind the chart, which you can copy into your own stack. ## Which one to start with The official Polymarket APIs tell you **what Polymarket the application knows about your account and the current book**. Bitquery tells you **what actually happened on-chain across every Polymarket market, in a shape you can aggregate, stream, and replay**. Picking the right one, or more often using both, comes down to whether your next query starts with "place this order" or "across all markets…". ## Further reading Canonical Bitquery Polymarket references: - [Polymarket API, Trade, Prices & Market Data](/docs/examples/polymarket-api/) - [Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api/) for CTF Exchange, condition_id, and token_id lookups - [Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/) - [Polymarket Advanced Analytics API](/docs/examples/polymarket-api/polymarket-advanced-analytics-api/) Vertical guides: - [Polymarket Sports API](/docs/examples/polymarket-api/polymarket-sports-api/) - [Polymarket Commodity API](/docs/examples/polymarket-api/polymarket-commodity-api/) - [Bitcoin Up or Down Polymarket API](/docs/examples/polymarket-api/bitcoin-polymarket-api/) - [Polymarket Wallet Realized PnL](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/) Infrastructure and live reference: - [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) - [Polymarket historical data exports](/docs/cloud/polymarket/) - [bitquery/polymarket-api on GitHub](https://github.com/bitquery/polymarket-api) - [DexRabbit Polymarket Predictions dashboard](https://dexrabbit.bitquery.io/polymarket-predictions) --- ## Polymarket API: Trades, Prices, Wallet PnL and Live Streams URL: https://docs.bitquery.io/docs/examples/polymarket-api/ Query Polymarket on-chain data with Bitquery GraphQL: trades, outcome prices, wallet PnL, market lifecycle and oracle resolutions, with WebSocket and Kafka streams. # Polymarket API - Prediction Market Data The Bitquery Polymarket API is a read-only GraphQL API over Polymarket's on-chain activity on Polygon: every trade, outcome price, market and settlement, plus wallet activity and realized PnL across all markets at once. It covers the jobs Polymarket's own Gamma, CLOB and Data APIs are not built for: cross-market aggregation, whale and insider detection, wallet-level PnL, and full-history backfills. Query it over GraphQL or REST, subscribe over WebSocket or Kafka for live trades, or download [historical Polymarket data as Parquet](/docs/cloud/polymarket/) for everything older than the realtime window. Queries use `dataset: realtime` on the `EVM` cube (`PredictionTrades`, `PredictionSettlements` and related fields), which retains roughly the **last 4 days**. With the [Polymarket Historical Data add-on](https://bitquery.io/pricing), `dataset: archive` and `dataset: combined` go back to 1 September 2025. Filter by `condition_id`, outcome token or trade size, and select Polymarket with `ProtocolName: "polymarket"` or `Marketplace.ProtocolName`. If you are evaluating data providers, the [Polymarket API product page](https://bitquery.io/products/polymarket-api) summarizes market, trade and position coverage with plans and real-time delivery options. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::note Dataset The examples on this page use `dataset: realtime`, which keeps about the last **4 days** of Polymarket prediction trades and settlements on Polygon. For history from 1 September 2025, add the [Polymarket Historical Data add-on](https://bitquery.io/pricing) and use `dataset: archive` or `dataset: combined`. For bulk loads, or data before that date, use a [Data Store export](/docs/cloud/polymarket/). ::: --- ## Bitquery Polymarket API vs the official Polymarket API Polymarket's own APIs (Gamma, CLOB, Data API) are the right choice for **placing orders**, reading the **order book**, and looking up one market or one account at a time. Bitquery indexes Polymarket **on-chain**, straight from the exchange and Conditional Tokens contracts on Polygon, so it fits the jobs the official API is not built for: | Job | Official Polymarket API | Bitquery Polymarket API | | --- | --- | --- | | Place and manage orders, order book depth | Yes (CLOB) | No, read-only data | | Aggregate across **all markets** in one request (top markets, top traders, volume by day) | Paginate and compute yourself | One GraphQL query with `sum`, `count`, `limitBy` | | **Whale and insider detection** across every market | Manual | One subscription or query, see [insider detection](/docs/examples/polymarket-api/polymarket-insider-detection-api/) | | **Wallet PnL** and cross-market activity | Per-account endpoints | [Wallet API](/docs/examples/polymarket-api/polymarket-wallet-api/) and [realized PnL](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/) | | Join with other Polygon data (funding transfers, balances, DEX trades) | No | Same GraphQL endpoint and schema | | Delivery | REST and WebSocket | GraphQL, WebSocket subscriptions, **Kafka**, and Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore) ([details](/docs/cloud/polymarket/)) | The two work together. Trade through the official CLOB API, and run analytics, alerts and backfills on Bitquery. A longer comparison is in [Polymarket API vs Bitquery Polymarket API](/docs/API-Blog/polymarket-api-vs-bitquery-polymarket-api/). :::info Polymarket contracts and collateral (2026 migration) Polymarket moved trading to new exchange contracts in April 2026 and now settles in **pUSD** (`0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB`), a USDC-backed ERC-20 that wraps USDC.e. Current Polygon addresses: - **CTF Exchange:** `0xE111180000d2663C0091e4f400237545B87B996B` - **Neg Risk CTF Exchange:** `0xe2222d279d744050d28e00520010520000310F59` - **Conditional Tokens (CTF):** `0x4D97DCd97eC945f40cF65F87097ACe5EA0476045` (unchanged) Inside the Conditional Tokens contract, custody is still USDC.e; pUSD is what traders hold and what `CollateralToken` returns on trades. Queries that filter by `ProtocolName: "polymarket"` need no change. If you hardcode exchange or collateral addresses, use the ones above; the previous exchanges (`0x4bFb41d5…8982E`, `0xC5d563A3…0f80a`) no longer emit `OrderFilled`. ::: ## Polymarket API guides - [Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/): activity, volume and market counts by wallet - [Polymarket Wallet Realized PnL](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/): profit and loss per trader - [Polymarket Advanced Analytics API](/docs/examples/polymarket-api/polymarket-advanced-analytics-api/): TVL, daily volume, order flow, whale streams - [Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api/): look up markets by slug, condition ID or outcome token - [Polymarket Insider Detection API](/docs/examples/polymarket-api/polymarket-insider-detection-api/): fresh wallets, funding sources, pre-resolution bets - [Polymarket Sports API](/docs/examples/polymarket-api/polymarket-sports-api/), [Commodity API](/docs/examples/polymarket-api/polymarket-commodity-api/), [Bitcoin API](/docs/examples/polymarket-api/bitcoin-polymarket-api/) and [AI & Tech API](/docs/examples/polymarket-api/polymarket-ai-tech-api/): category-specific markets - [Polymarket historical data (Parquet, S3, Snowflake, BigQuery)](/docs/cloud/polymarket/): full-history backfills - [Polymarket Telegram alerts bot](/docs/usecases/polymarket-tg-alerts-bot/): tutorial - [bitquery/polymarket-api on GitHub](https://github.com/bitquery/polymarket-api): SDKs and runnable examples - [Bitquery MCP server](/docs/mcp/mcp-server/): ask Polymarket questions from Claude, ChatGPT or Cursor, no GraphQL needed ## Can I ask Polymarket questions in plain English instead of writing GraphQL? Yes. The [Bitquery MCP server](https://bitquery.io/products/bitquery-mcp-server?ref=docs-polymarket-api) puts the same on-chain Polymarket data behind tools that Claude, ChatGPT, Cursor, VS Code and Codex can call. You type a question, the agent picks the tool, and the rows come back in the chat. It reads data only. It cannot place or cancel orders. | Ask | Tool the agent calls | | --- | --- | | What are the most traded Polymarket markets in the last 24 hours? | `polymarket_top_markets` | | Find the open markets about the Fed rate decision. | `polymarket_find_markets` | | What are the current odds on this market? | `polymarket_market_odds` | | Show the latest trades in this market. | `polymarket_market_trades` | | Who traded the most volume in this market? | `polymarket_top_traders` | | What has this wallet traded, and what does it still hold? | `polymarket_trader_activity`, `polymarket_trader_positions` | | Was this market's resolution disputed? | `polymarket_market_disputes` | `polymarket_top_traders` ranks wallets by volume traded. A wallet at the top may be a market maker that is flat or losing, so do not read that list as a profit ranking. To connect from Claude Code: ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Other clients take the same URL. Steps for each are in the [MCP server install guide](/docs/mcp/mcp-server/), and plans are on the [MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-polymarket-api#pricing). ## What Polymarket data can I get with Bitquery? Bitquery provides **trades and prices** (buy/sell activity, volume, outcome prices), **positions and redemptions** (splits, merges after resolution), **market lifecycle** (creation, resolution, oracle outcomes), **market metadata** (condition ID, slug, token filters via CTF Exchange), **wallet activity** (volume and market counts by address), and **real-time streaming** (Kafka for trades and settlements). All data is on Polygon (`network: matic`) with `dataset: realtime` (about the **last 7 days**). Use the links below to find the right API. ### How do I get Polymarket trades and prices? Use the **[Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api)** to query buy/sell activity, track prices, and monitor volume across Polymarket. [→ Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api) ### How do I track positions and redemptions? Use the **[Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api)** to query splits, merges, and redemptions after market resolution. [→ Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api) ### How do I get market lifecycle data? Use the **[Prediction Market API](/docs/examples/prediction-market/prediction-market-api)** to query market creation, resolution, and complete lifecycle events. [→ Prediction Market API](/docs/examples/prediction-market/prediction-market-api) ### How do I query Polymarket CTF exchange data (condition ID, slug, token)? Use the **[Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api)** (CTF Exchange) to query market data by slug, condition ID, outcome token, or event. Combine with [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api) and [Prediction Market API](/docs/examples/prediction-market/prediction-market-api) for full lifecycle. [→ Polymarket Markets API (CTF Exchange)](/docs/examples/polymarket-api/polymarket-markets-api) ### How do I get Polymarket wallet and user activity? Use the **[Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api)** to query recent activity, volume, and market counts by wallet address. [→ Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api) ### How do I build TVL, open-interest-style metrics, maker/taker splits, and order-flow analytics? Use the **[Polymarket Advanced Analytics API](/docs/examples/polymarket-api/polymarket-advanced-analytics-api)** for GraphQL examples: USDC balances in core contracts, daily volume and maker/taker splits, order-flow by market, whale-trade subscriptions, settlement flows, and top markets by volume. [→ Polymarket Advanced Analytics API](/docs/examples/polymarket-api/polymarket-advanced-analytics-api) ### How do I stream Polymarket data in real time? Use **Kafka Streams** for low-latency Polymarket data. Subscribe to trades, settlements, and market events as they happen. Available Kafka topics: - `matic.predictions.proto`: Raw prediction market events - `matic.broadcasted.predictions.proto`: Mempool prediction market data Note: Kafka streaming requires separate credentials. [Contact support](https://t.me/bloxy_info) or email support@bitquery.io for access. [→ Kafka Streams Documentation](/docs/streams/kafka-streaming-concepts) --- ## How do I get real-time Polymarket trades using Bitquery? Use Bitquery's `PredictionTrades` GraphQL query filtered by `ProtocolName: "polymarket"` on Polygon (`network: matic`). For live streaming, use a subscription or Kafka. [Run in Bitquery IDE](https://ide.bitquery.io/prediction_trades) ```graphql query { EVM(network: matic) { PredictionTrades( limit: { count: 10 } orderBy: { descending: Transaction_Time } where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } OutcomeTrade: { IsOutcomeBuy: true } } } ) { Transaction { Hash Time } Trade { Prediction { Question { Title MarketId } Outcome { Label } CollateralToken { Symbol } } OutcomeTrade { Buyer Seller Amount CollateralAmount } } } } } ``` --- ## Query Examples ### How do I subscribe to live Polymarket trades? Use a GraphQL subscription on `PredictionTrades` filtered by `Marketplace.ProtocolName: "polymarket"` to stream trades as they happen on Polygon: ```graphql subscription PredictionTradesStream { EVM(network: matic) { PredictionTrades( where: { TransactionStatus: { Success: true } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount Price IsOutcomeBuy } Prediction { Question { Title MarketId } Outcome { Label } CollateralToken { Symbol } } } Transaction { Hash } } } } ``` ### How do I filter Polymarket trades by condition_id or asset ID? Use `PredictionManagements` with `OutcomeToken.AssetId` or `Condition.Id` in the where clause. For condition_id, market_slug, and combined filters, see the [Polymarket Markets API (CTF Exchange)](/docs/examples/polymarket-api/polymarket-markets-api/). [Run query](https://ide.bitquery.io/Filter-markets-by-asset-ID-Polymarket) ```graphql query MarketsByAssetId($assetIds: [String!]) { EVM(network: matic) { PredictionManagements( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Management: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } OutcomeToken: { AssetId: { in: $assetIds } } } } } ) { Block { Time Number } Transaction { Hash Time } Management { EventType Prediction { Condition { Id QuestionId Outcomes { Id Index Label } } Question { MarketId Title Image ResolutionSource CreatedAt } CollateralToken { Symbol Name } Outcome { Id Label } OutcomeToken { AssetId SmartContract } } } } } } ``` **Variables (example):** ```json { "assetIds": [ "19443761038809394075988687891855393102730862479306560066876868792031660494383" ] } ``` ### How do I get Polymarket markets ranked by volume? Use Bitquery's `PredictionTrades` with `limitBy: Trade_Prediction_Question_Id`, `orderBy: descendingByField: "sumBuyAndSell"`, and `sum(of: Trade_OutcomeTrade_CollateralAmountInUSD)` grouped by buy/sell to rank markets by total volume over a time window. [Run query](https://ide.bitquery.io/Top-Polymarket-Markets-by-Volume) ```graphql query questionsByVolume($time_ago: DateTime) { EVM(network: matic) { PredictionTrades( where: { TransactionStatus: {Success: true} Block: {Time: {since: $time_ago}} Trade: {Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}}} } limit: {count: 100} orderBy: {descendingByField: "sumBuyAndSell"} limitBy: {by: Trade_Prediction_Question_Id} ) { Trade { Prediction { Question { Id Image Title CreatedAt } } } buyUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: {Trade: {OutcomeTrade: {IsOutcomeBuy: true}}} ) sellUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: {Trade: {OutcomeTrade: {IsOutcomeBuy: false}}} ) sumBuyAndSell: calculate(expression: "$buyUSD + $sellUSD") } } } ``` **Variables (example):** ```json { "time_ago": "2026-02-24T07:22:21Z" } ``` ## How do I get real-time odds for all active Polymarket markets? Use a GraphQL subscription on `PredictionTrades` with `limitBy: { count: 1, by: [Trade_Prediction_Question_Id, Trade_Prediction_Outcome_Label] }` filtered by `ProtocolName: "polymarket"` to stream the latest odds for every active market. Returns live price and outcome probabilities. [Run in Bitquery IDE](https://ide.bitquery.io/How-do-I-get-real-time-odds-for-all-active-Polymarket-markets) ```graphql subscription { EVM(network: matic) { PredictionTrades( limitBy: {count: 1, by: [Trade_Prediction_Question_Id, Trade_Prediction_Outcome_Label]} where: {Trade: {Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}}}} ) { Trade { OutcomeTrade { Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol AssetId } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Label } } } } } } ``` ## How do I track high-value or whale trades on Polymarket? Use a GraphQL subscription on `PredictionTrades` filtered by `CollateralAmountInUSD: { gt: "10000" }` and `ProtocolName: "polymarket"` to monitor trades exceeding $10,000 USD in real time. Ideal for detecting whale activity and large market movements. [Run in Bitquery IDE](https://ide.bitquery.io/How-do-I-track-high-value-or-whale-trades-on-Polymarket) ```graphql subscription { EVM(network: matic) { PredictionTrades( where: { TransactionStatus: {Success: true} Trade: { Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}} OutcomeTrade: {CollateralAmountInUSD: {gt: "10000"}} } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` ## What are the largest Polymarket trades in the last 7 days? Use `PredictionTrades` with `orderBy: { descending: Trade_OutcomeTrade_CollateralAmountInUSD }` and filter by `ProtocolName: "polymarket"` to get the top 10 largest trades by USD volume. Add `Block.Time: { since: $time_ago }` for a custom time window. [Run in Bitquery IDE](https://ide.bitquery.io/What-are-the-largest-Polymarket-trades-in-the-last-7-days) ```graphql query { EVM(network: matic) { PredictionTrades( limit: {count: 10} orderBy: {descending: Trade_OutcomeTrade_CollateralAmountInUSD} where: { TransactionStatus: {Success: true} Trade: { Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}} OutcomeTrade: {CollateralAmountInUSD: {gt: "10000"}} } } ) { Block{ Time Date } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` ## How do I get top buyers and sellers on Polymarket by volume? Use `PredictionTrades` with `limitBy` and `sum(of: Trade_OutcomeTrade_CollateralAmountInUSD)` grouped by Buyer (or Seller) to rank the top 100 wallets by volume over the last 5 days. Useful for leaderboards, whale tracking, and trader analytics. [Run in Bitquery IDE](https://ide.bitquery.io/How-do-I-get-top-buyers-and-sellers-on-Polymarket-by-volume) ```graphql query { EVM(network: matic) { buyers: PredictionTrades( limit: {count: 100} orderBy: {descendingByField: "volume_usd"} where: { Block: {Time: {since_relative: {days_ago: 5}}} TransactionStatus: {Success: true} Trade: {Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}}} } ) { volume_usd: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) Trade { OutcomeTrade { Buyer } } } sellers: PredictionTrades( limit: {count: 100} orderBy: {descendingByField: "volume_usd"} where: { Block: {Time: {since_relative: {days_ago: 5}}} TransactionStatus: {Success: true} Trade: {Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}}} } ) { volume_usd: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) Trade { OutcomeTrade { Seller } } } } } ``` ## How do I count trades for a specific Polymarket trader? Use `PredictionTrades` with `any` filter on `Buyer` or `Seller` to return the total trade count for a wallet. Add `ProtocolName: "polymarket"` to restrict to Polymarket only. Replace the address with your target wallet. [Run in Bitquery IDE](https://ide.bitquery.io/How-do-I-count-trades-for-a-specific-Polymarket-trader) ```graphql query { EVM(network: matic) { PredictionTrades( where: { TransactionStatus: {Success: true} any: [ {Trade: {Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}}, OutcomeTrade: {Buyer: {is: "0xd48165a42bb4eeb5971e5e830c068eef0890af35"}}}} {Trade: {Prediction: {Marketplace: {ProtocolName: {is: "polymarket"}}}, OutcomeTrade: {Seller: {is: "0xd48165a42bb4eeb5971e5e830c068eef0890af35"}}}} ] } ) { count } } } ``` --- ## How much Polymarket volume goes through each exchange contract? Group one day of trades by exchange contract and collateral token. This shows the split between the **CTF Exchange** and the **Neg Risk CTF Exchange**, and confirms the collateral token (pUSD) your integration should expect. [Run in Bitquery IDE](https://ide.bitquery.io/polymarket-volume-by-exchange-contract-and-collateral) ```graphql query PolymarketVolumeByExchange($date: String!) { EVM(dataset: realtime, network: matic) { PredictionTrades( where: { TransactionStatus: { Success: true } Block: { Date: { is: $date } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } } limit: { count: 10 } orderBy: { descendingByField: "volume_usd" } ) { Trade { Prediction { Marketplace { SmartContract ProtocolVersion } CollateralToken { Symbol SmartContract } } } volume_usd: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) trades: count } } } ``` **Variables (example):** ```json { "date": "2026-09-17" } ``` ## Support For questions and technical support: - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket Analytics with AI: Volume, Odds History, Holders URL: https://docs.bitquery.io/docs/mcp/polymarket-analytics/ Run Polymarket analytics from a chat in Claude, ChatGPT or Cursor: rank markets by volume or by crowd, slice by subject, chart how the odds moved, and see who holds an outcome. Read-only, from on-chain data. # Polymarket Analytics with AI A dashboard gives you a fixed set of charts. This page shows the other way to do it: ask for the cut you want in plain English and get a table back. It uses six of the 14 Polymarket tools in the [Bitquery MCP server](/docs/mcp/polymarket/), in Claude, ChatGPT or Cursor. It reads data only and cannot place an order. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Every figure below came from the production server on 21 September 2026, between 15:11 and 15:15 UTC, with data 12 to 15 minutes behind the clock. ## Where is the money today? > *"Which Polymarket markets had the most volume in the last 24 hours?"* `polymarket_top_markets`, default sort. | # | Market | 24h volume | Wallets | |---|---|---:|---:| | 1 | Colts vs. Chiefs | $4,070,630 | 283 | | 2 | Will United Russia gain the most seats? | $3,815,310 | 493 | | 3 | Packers vs. Jets | $1,595,455 | 190 | | 4 | Raiders vs. Chargers | $1,486,917 | 133 | | 5 | Panthers vs. Falcons | $1,385,725 | 153 | ## Where is the crowd? > *"Now rank them by the number of wallets that traded."* Same tool, sorted by traders. | # | Market | Wallets | 24h volume | |---|---|---:|---:| | 1 | Browns vs. Buccaneers | 3,089 | $1,304,941 | | 2 | Milwaukee Brewers vs. Baltimore Orioles | 2,450 | $340,780 | | 3 | Will CD Leganés vs. Granada CF end in a draw? | 2,123 | $91,754 | | 4 | Solana Up or Down, 21 September, 8AM ET | 1,264 | $21,015 | | 5 | Will Panaitolikos Agrinio win on 20 September? | 776 | $11,171 | Not one market is on both lists. The biggest market by money had 283 wallets, about $14,384 each. The Leganés draw market had 2,123 wallets at about $43 each. Volume tells you where a few large accounts are. Wallet count is closer to the crowd, and a dashboard that shows only one of the two hides half the picture. Row 3 deserves a second look, though. It had 2,188 orders from 2,123 wallets at an average price of 0.97. One small order each on a near-certain outcome is not what a crowd of fans looks like, so check orders per wallet before you call a market popular. ## Slice by subject > *"Show the biggest politics markets over the last 7 days."* `polymarket_top_markets` takes a category (sports, crypto, politics, esports, weather, stocks, mentions, entertainment) and a title search, together or alone. | # | Market | 7-day volume | Wallets | |---|---|---:|---:| | 1 | Will United Russia (ER) gain the most seats in the next Russian parliamentary election? | $7,895,729 | 894 | | 2 | Will New People (NL) gain the most seats in the next Russian parliamentary election? | $1,391,623 | 440 | | 3 | Will United Russia (ER) win the most seats in the next Russian parliamentary election? | $827,239 | 137 | | 4 | Will AfD win the most seats in the 2026 Mecklenburg-Vorpommern elections? | $419,479 | 332 | | 5 | Will Flávio Bolsonaro win the 2026 Brazilian presidential election? | $329,878 | 191 | Read rows 1 and 3 twice. Their titles differ by one word, "gain" and "win", and they are different questions. `polymarket_market_info` returns each market's written rules: row 3 asks which party wins the most seats, and row 1 asks which party's seat count rises the most compared with before the election. Row 1 traded almost ten times as much. Every answer carries a question id. Pass that id to the next tool instead of the title, or you may chart the wrong market. ## How did the odds move? > *"Show the daily close and volume for Yes on the first market since 12 September."* `polymarket_market_price_history` with a one-day interval. Intervals run from 1 second to 1 day. | Day | Yes close | Volume on Yes | |---|---:|---:| | 12 Sep | 0.79 | $69,175 | | 13 Sep | 0.80 | $17,215 | | 14 Sep | 0.77 | $69,756 | | 15 Sep | 0.77 | $170,235 | | 16 Sep | 0.73 | $474,884 | | 17 Sep | 0.76 | $183,599 | | 18 Sep | 0.83 | $833,802 | | 19 Sep | 0.81 | $1,163,964 | | 20 Sep | 0.985 | $3,528,998 | | 21 Sep, part day | 0.999 | $786,474 | A price is dollars per share between 0 and 1, so 0.79 is a 79% chance. For eight days the close sat between 73% and 83%. On 20 September it went from 0.81 to 0.985, and that one day carried 48% of the ten days' volume. Then look at the last row: $786,474 changed hands at an average of 0.9946 when the question was all but settled. Those buyers paid 99.5 cents for a dollar. `polymarket_market_events` puts the official resolution at 12:43 UTC on 21 September, one minute after the last Yes trade. The same tool's `Vwap` column is the safer number on a thin day. A close is one fill, and on a quiet market that fill can be a few cents of dust. ## How big was it over its life? > *"What are the odds and lifetime volume on that market?"* `polymarket_market_odds` returns one row per outcome. | Outcome | Price | Lifetime volume | Lifetime trades | |---|---:|---:|---:| | Yes | 0.999 | $11,103,433 | 64,523 | | No | 0.001 | $2,026,043 | 51,476 | That is $13.1 million across 115,999 trades since the first one on 7 January 2026. Add an `at_time` and the same call gives the odds as they stood at any past moment, which is how you check what the market believed when a piece of news broke. ## Who holds what is left? > *"Who holds the most Yes shares in that market?"* `polymarket_outcome_holders`: | # | Holder | Yes shares | Share of all Yes | First acquired | |---|---|---:|---:|---| | 1 | `0x59368957...0b7b` | 140,452 | 20.9% | 21 Sep 2026 | | 2 | `0x5c14eb6a...cc49` | 89,422 | 13.3% | 29 Apr 2026 | | 3 | `0x7818687f...d185` | 45,000 | 6.7% | 12 Aug 2026 | | 4 | `0x58490840...4986` | 26,300 | 3.9% | 12 Sep 2026 | | 5 | `0x4a86dfe0...501e` | 26,047 | 3.9% | 19 Sep 2026 | 4,628 addresses still hold Yes, and five of them hold 48.8% of the 671,029 shares outstanding. The largest holder first acquired its shares on the morning of 21 September, a day when Yes never traded below 98 cents. Balances are rebuilt from every share movement, plain transfers included, so they are holdings and not a guess from the order tape. One caution the tool gives itself: a holder of record is often a proxy contract or a market maker's address, so do not read each row as one person. Run the list through `labels_for_addresses` first. Here it named one of the five, number 3, as a Polymarket deposit address. ## A prompt you can reuse > *"For Polymarket over the last 24 hours, give me two top-10 lists, by volume and by number of wallets, and mark any market on both. For the largest market, show the daily Yes close and volume for the past two weeks, the lifetime volume per outcome, and the five largest holders of Yes with their share of supply."* ## What to know before you rely on it - **Read-only.** No order placement and no order book depth. - **One market at a time below the rankings.** There is no single call for all-of-Polymarket volume per day. The rankings cover many markets; history, odds and holders take one question id. - **A few minutes behind.** Calls on this page trailed the clock by 12 to 15 minutes. A window of an hour or two can be partly unrecorded, and the first row of each answer says so. - **History starts in September 2025.** - **Categories are a best-effort sort.** They come from each market's own wording, and sports and crypto together make up about three quarters of all markets. - **Volume counts resting orders by default.** That is the right basis for market volume. Ask for taker orders if you want the aggressive side only. ## Related - [Polymarket MCP server](/docs/mcp/polymarket/): all 14 tools. - [Track Polymarket whales and top traders](/docs/mcp/polymarket-whale-tracker/): the same method pointed at wallets. - [Polymarket GraphQL API](/docs/examples/polymarket-api/) and [Polymarket Parquet exports](/docs/cloud/polymarket/): the same data in code or in a warehouse, for a dashboard that runs by itself. Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-polymarket-analytics#pricing). --- ## Polymarket Bitcoin Up or Down API & Websocket URL: https://docs.bitquery.io/docs/examples/polymarket-api/bitcoin-polymarket-api/ Polymarket Bitcoin Up or Down markets: stream trades via subscriptions and Kafka, get price odds, top traders, top winners, whale trades and wallets. # Polymarket Bitcoin Up or Down Prediction Odds API Query and stream **Polymarket Bitcoin up or down** prediction market trades and **Bitcoin price odds** via Bitquery’s GraphQL API. These markets ask whether Bitcoin will be **up** or **down** at a specific time (e.g. daily or weekly settlement). **What you can do with this API:** Build real-time dashboards, aggregate odds across markets, track top traders by volume, identify top winners from settlements, analyze market liquidity, monitor whale activity, backtest strategies, and power alerts or bots. ## How Bitcoin Up or Down markets are identified Trades are filtered by **Question.Title** containing **"Bitcoin Up or Down"**. | Filter | Use case | Where to apply | | ------------------ | ------------------------------- | ------------------------------------------- | | **Question.Title** | Bitcoin Up or Down markets only | `Trade.Prediction.Question.Title.includes` | | **ProtocolName** | Polymarket only (optional) | `Trade.Prediction.Marketplace.ProtocolName` | --- ## Real-time: Subscriptions and Kafka ### GraphQL subscriptions The **subscription** below streams live Bitcoin Up or Down trades as they occur on Polygon. Change `subscription` to `query` and add `limit` / `orderBy` for historical results. ### Kafka streams For **low-latency** consumption, prediction market data (including Bitcoin Up/Down) is available via **Kafka**: - `matic.predictions.proto`: Raw prediction market events (trades, creations, resolutions) - `matic.broadcasted.predictions.proto`: Mempool prediction market data Kafka requires **separate credentials**. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). For access, [contact support](https://t.me/bloxy_info) or email support@bitquery.io. --- ## How do I stream Bitcoin Up or Down trades in real time? Subscribe to live Polymarket trades for markets whose question title includes **"Bitcoin Up or Down"**. Includes block time, call/log signatures, full outcome trade details (buyer, seller, amount, price, USD values), and prediction metadata (question, outcomes, collateral token, marketplace). [Run in Bitquery IDE](https://ide.bitquery.io/Bitcoin-Up-or-Down-Trades-Stream) ```graphql subscription { EVM(network: matic) { PredictionTrades( where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includes: "Bitcoin Up or Down" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` ## How do I get Bitcoin price odds for all active Polymarket up/down markets? This WebSocket subscription streams real-time odds (prices) for all active "Bitcoin Up or Down" Polymarket markets. Use a GraphQL subscription on `PredictionTrades` with `limitBy: { count: 1, by: [Trade_Prediction_Question_Id, Trade_Prediction_Outcome_Label] }` to stream the latest odds (Up/Down outcome prices) for every active Bitcoin Up or Down market. Each market returns one row per outcome with `Price`, `PriceInUSD`, and market metadata. [Run in Bitquery IDE](https://ide.bitquery.io/Odds-of-all-Bitcoin-up-and-down-markets) ```graphql subscription { EVM(network: matic) { PredictionTrades( orderBy: { descending: Block_Time } limitBy: { count: 1 by: [Trade_Prediction_Question_Id, Trade_Prediction_Outcome_Label] } where: { Trade: { Prediction: { Outcome: { Label: { in: ["Up", "Down"] } } Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includes: "Bitcoin Up or Down" } } } } } ) { Trade { OutcomeTrade { Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol AssetId } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Label } } } } } } ``` ## How do I get the latest Bitcoin price odds for a specific up/down market? To track a single specific Bitcoin Up or Down market, use its unique question ID (condition ID) with the following query. This lets you fetch real-time or latest odds for just that market: Use `PredictionTrades` with `limitBy: { count: 1, by: Trade_Prediction_Outcome_Label }` and filter by `Question.Id` (condition ID) to get the latest odds for a single Bitcoin Up or Down market. Returns one row per outcome (Up/Down) with `Price` and `PriceInUSD`. Use a `query` for one-time fetch or change to `subscription` for real-time updates. Replace `Question.Id` with any market's condition ID to query odds for other Polymarket markets. [Run in Bitquery IDE](https://ide.bitquery.io/Odds-of-a-specific-Bitcoin-up-and-down-market) ```graphql { EVM(network: matic) { PredictionTrades( orderBy: { descending: Block_Time } limitBy: { count: 1, by: Trade_Prediction_Outcome_Label } where: { Trade: { Prediction: { Outcome: { Label: { in: ["Up", "Down"] } } Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Id: { is: "0xd8c16674c7242c146cd9662906af3a442ba702d08f079885287ebc194ab0c271" } Title: { includes: "Bitcoin Up or Down" } } } } } ) { Trade { OutcomeTrade { Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol AssetId } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Label } } } } } } ``` For real-time odds via WebSocket, use the same query with `subscription` instead of `query`: ```graphql subscription { EVM(network: matic) { PredictionTrades( orderBy: { descending: Block_Time } limitBy: { count: 1, by: Trade_Prediction_Outcome_Label } where: { Trade: { Prediction: { Outcome: { Label: { in: ["Up", "Down"] } } Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Id: { is: "0xd8c16674c7242c146cd9662906af3a442ba702d08f079885287ebc194ab0c271" } Title: { includes: "Bitcoin Up or Down" } } } } } ) { Trade { OutcomeTrade { Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol AssetId } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Label } } } } } } ``` Replace `Question.Id` with any market's condition ID and adjust the `Title` filter to get odds for other Polymarket prediction markets. ## How do I get top traders of Bitcoin Up or Down markets by volume? This **query** returns the top 10 **buyers** and top 10 **sellers** by traded volume in Bitcoin Up or Down markets on Polymarket over the last 24 hours. Results are aggregated by trader address and ordered by `buy_amount` (buyers) or `sell_amount` (sellers). [Run in Bitquery IDE](https://ide.bitquery.io/Top-BuyersSellers-of-Bitcoin-up-down-market) ```graphql { EVM(network: matic) { Top_buyers: PredictionTrades( where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includes: "Bitcoin Up or Down" } } } OutcomeTrade: { IsOutcomeBuy: true } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 10 } orderBy: { descendingByField: "buy_amount" } ) { Trade { OutcomeTrade { Buyer } } buy_amount: sum(of: Trade_OutcomeTrade_Amount) } Top_sellers: PredictionTrades( where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includes: "Bitcoin Up or Down" } } } OutcomeTrade: { IsOutcomeBuy: false } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 10 } orderBy: { descendingByField: "sell_amount" } ) { Trade { OutcomeTrade { Buyer } } sell_amount: sum(of: Trade_OutcomeTrade_Amount) } } } ``` ## How do I get top winners of Bitcoin Up or Down markets by redemption volume? Use `PredictionSettlements` filtered by `EventType: "Redemption"` and `Question.Title` including "Bitcoin Up or Down" to return the top 10 holders by redeemed amount over the last hour. Useful for tracking which traders won the most on settled Bitcoin Up or Down markets. [Run in Bitquery IDE](https://ide.bitquery.io/Top-Winners-of-Bitcoin-up-down-market) ```graphql query MyQuery { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descendingByField: "redeemed_amount" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Settlement: { EventType: { is: "Redemption" } Prediction: { Question: { Title: { includes: "Bitcoin Up or Down" } } } } } ) { Settlement { Holder Prediction { Question { Title } } } redeemed_amount: sum(of: Settlement_Amounts_Amount) } } } ``` ## Monitoring High-Value Trades on Polymarket Bitcoin Markets Use the following WebSocket subscription to monitor live trades greater than $5,000 USD on Polymarket Bitcoin Up or Down markets. This is ideal for detecting whale activity and large market movements in real time. ```graphql subscription { EVM(network: matic) { PredictionTrades( where: {TransactionStatus: {Success: true}, Trade: {OutcomeTrade: {CollateralAmountInUSD: {gt: "5000"}}, Prediction: {Question: {Title: {includes: "Bitcoin Up or Down"}}}}} ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` ## How do I monitor specific wallets on Bitcoin Up or Down markets in real time? Stream every Bitcoin Up or Down trade where one of a given list of wallets is the **Buyer** or the **Seller**. Pass the wallets you want to watch in the `$wallets` variable. The `any` predicate matches a trade if the wallet appears on either side. Useful for wallet-level alerting bots, copy-trading signals, and PnL tracking dashboards. [Run in Bitquery IDE](https://ide.bitquery.io/montioring-specific-wallets-in-realtime-for-Bitcoin-Up-or-Down-markets) ```graphql subscription MyQuery($wallets: [String!]) { EVM(network: matic) { PredictionTrades( where: { any: [ { Trade: { OutcomeTrade: { Buyer: { in: $wallets } } } } { Trade: { OutcomeTrade: { Seller: { in: $wallets } } } } ] Trade: { Prediction: { Question: { Title: { includesCaseInsensitive: "Bitcoin Up or Down" } } Marketplace: { ProtocolName: { is: "polymarket" } } } } TransactionStatus: { Success: true } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` **Variables:** ```json { "wallets": [ "0x87a961f161681cc1e9b3af2b6542b95ef3c4bd70", "0x0bab932893a7efc76d8e0951366ba933ba9fd3be" ] } ``` ### Same query for other Up or Down markets The same wallet-monitoring pattern works for every Polymarket Up or Down market. Only the `Question.Title` filter changes. Open any of the pre-built IDE queries below to stream trades for the chain you care about: - [Solana Up or Down, monitor specific wallets](https://ide.bitquery.io/montioring-specific-wallets-in-realtime-for-Solana-Up-or-Down-markets_1) - [Ethereum Up or Down, monitor specific wallets](https://ide.bitquery.io/monitoring-specific-wallets-trades-in-realtime-for-Ethereum-up-or-down-market) - [XRP Up or Down, monitor specific wallets](https://ide.bitquery.io/monitoring-specific-wallets-trades-in-realtime-for-XRP-up-or-down-market) Each query exposes the same `$wallets` variable, so you can drop the same wallet list into all four and run them in parallel to cover every chain at once. ## Related APIs | Need | API | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **All Polymarket trades & prices** | [Polymarket API](/docs/examples/polymarket-api/) / [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/) | | **Filter by slug, condition, token** | [Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api/) | | **Settlements & redemptions** | [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) | | **Market creation & resolution** | [Prediction Market API](/docs/examples/prediction-market/prediction-market-api/) | | **User & wallet activity** | [Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/) | | **Real-time: Kafka streams** | [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) | --- ## Support - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket Commodity API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-commodity-api/ Polymarket commodity markets for Gold and Crude Oil: new and resolved markets, outcome prices, OHLC, volumes, top redeemers, subscriptions and Kafka. # Polymarket Commodity API: Gold, Crude Oil & Commodity Markets Query **commodity-related prediction markets** on Polymarket: **Gold (GC)** (e.g. “Gold Up or Down”), **Crude Oil**, and other commodity price-direction markets. Use **PredictionManagements** for market creation and resolution events, **PredictionTrades** for prices and volume, and **PredictionSettlements** for redemptions and top redeemers. All data is on Polygon (`network: matic`). :::tip See it in action: DEXrabbit Polymarket showcase Check out our **Polymarket data showcase** on [DEXrabbit](https://dexrabbit.bitquery.io/polymarket-predictions) powered by Bitquery APIs. Explore live commodity markets: - **[Gold (GC) market example](https://dexrabbit.bitquery.io/polymarket-predictions/0x6a9b34f5f4b44a7d3dced5ac84b3300aa9ae18e163a9bb4c98b805b57bbc1abb)**: View current odds, trade statistics, volume, and top traders by PnL - **[Crude Oil market example](https://dexrabbit.bitquery.io/polymarket-predictions/0x9a1e4e09a4bb9321f9b3f4f04d4242f1c11046348f88d236eeb0ae038b336096)**: See price charts, trading activity, and market analytics Click the **"Get API"** buttons on any market page to get ready-to-use GraphQL queries for trade statistics, top traders by PnL, volume breakdowns, and more. ::: :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. See [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/). ::: --- ## How commodity markets are identified Markets are filtered by **Question.Title** using case-insensitive keywords. Use the same filters in **PredictionManagements**, **PredictionTrades**, or **PredictionSettlements** as needed. | Filter | Use case | Where to apply | |--------|----------|----------------| | **Question.Title** | Gold (GC) markets | `includesCaseInsensitive: "Gold (GC)"` | | **Question.Title** | Crude Oil markets | `includesCaseInsensitive: "crude oil"` | | **MarketId** | Specific market (prices, OHLC, volume) | `Question.MarketId` (replace with your market ID) | | **ProtocolName** | Polymarket only | `Marketplace.ProtocolName: "polymarket"` | **Network:** Polygon (`network: matic`). For full lifecycle and trade APIs, see the [Polymarket API](/docs/examples/polymarket-api/) overview and [Prediction Market API](/docs/examples/prediction-market/prediction-market-api). --- ## Latest Gold (GC) markets created Returns the 10 most recent **Created** events for Polymarket markets whose question title includes **"Gold (GC)"**, with full condition, outcomes, question, and collateral token details. [Run in Bitquery IDE](https://ide.bitquery.io/latest-created-gold-markets-on-polymarket_5) ```graphql query LatestMarketCreations { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Created" } Prediction: { Question: { Title: { includesCaseInsensitive: "Gold (GC)" } } Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Latest Crude Oil markets created Returns the 10 most recent **Created** events for Polymarket markets whose question title includes **"crude oil"**, with full prediction metadata. [Run in Bitquery IDE](https://ide.bitquery.io/latest-created-crude-oil-markets-on-polymarket) ```graphql query LatestMarketCreations { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Created" } Prediction: { Question: { Title: { includesCaseInsensitive: "crude oil" } } Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Latest resolved Gold (GC) markets Returns the 10 most recent **Resolved** events for Polymarket Gold (GC) markets, including the winning outcome and full prediction details. [Run in Bitquery IDE](https://ide.bitquery.io/latest-resolved-gold-markets_1) ```graphql query LatestMarketResolutions { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Resolved" } Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: "Gold (GC)" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Latest resolved Crude Oil markets Returns the 10 most recent **Resolved** events for Polymarket Crude Oil markets. [Run in Bitquery IDE](https://ide.bitquery.io/latest-resolved-crudeoil-markets) ```graphql query LatestMarketResolutions { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Resolved" } Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: "crude oil" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Latest price of outcomes of a Crude Oil market Returns the **latest trade price** (and price in USD) per outcome for a **single market** by `MarketId`. Replace `"1570893"` with the target Crude Oil market ID from [Polymarket](https://polymarket.com) or from the creation/resolution queries above. [Run in Bitquery IDE](https://ide.bitquery.io/latest-price-of-outcomes-of-a-crude-oil-market) ```graphql query { EVM(network: matic) { PredictionTrades( limitBy: { by: Trade_Prediction_OutcomeToken_AssetId, count: 1 } where: { TransactionStatus: { Success: true } Trade: { Prediction: { Question: { MarketId: { is: "1570893" } } } } } ) { Trade { OutcomeTrade { Price(maximum: Block_Time) PriceInUSD(maximum: Block_Time) } Prediction { OutcomeToken { Name AssetId } Outcome { Id Label } } } } } } ``` --- ## OHLC of an outcome of a Gold market Returns **OHLC** (Open, High, Low, Close) in USD for one outcome of a Gold market, bucketed by time (e.g. 1-minute intervals). Replace `MarketId` `"1606192"` and outcome `"Down"` with the desired market and outcome label (e.g. `"Up"` or `"Down"`). [Run in Bitquery IDE](https://ide.bitquery.io/OHLC-of-a-outcome-of-a-gold-market) ```graphql query { EVM(network: matic) { PredictionTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Prediction: { Question: { MarketId: { is: "1606192" } } Outcome: { Label: { is: "Down" } } } } } ) { Block { Interval: Time(interval: { count: 1, in: minutes }) } Trade { OutcomeTrade { Open: PriceInUSD(minimum: Block_Time) High: PriceInUSD(maximum: Trade_OutcomeTrade_PriceInUSD) Low: PriceInUSD(minimum: Trade_OutcomeTrade_PriceInUSD) Close: PriceInUSD(maximum: Block_Time) } Prediction { OutcomeToken { Name AssetId } Outcome { Id Label } } } } } } ``` --- ## Outcome volumes of a Gold market (last 24 hours) Returns **total volume** and **volume by outcome** (e.g. Up vs Down) for a single Gold market in the last 24 hours. Replace `MarketId` `"1650002"` with your target market ID. [Run in Bitquery IDE](https://ide.bitquery.io/outcome-volumes-of-a-gold-market-in-last-24-hours_1) ```graphql query MarketVolumeByOutcome { EVM(network: matic) { PredictionTrades( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } TransactionStatus: { Success: true } Trade: { Prediction: { Question: { MarketId: { is: "1650002" } } } } } ) { Trade { Prediction { Question { Title ResolutionSource Image MarketId Id CreatedAt } } } up_volume: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { Prediction: { Outcome: { Label: { is: "Up" } } } } } ) down_volume: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { Prediction: { Outcome: { Label: { is: "Down" } } } } } ) total_volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) } } } ``` --- ## Top 10 redeemers of a Gold market Returns the **top 10 holders** by **redeemed amount** (in USD) for a specific Gold market after resolution. Uses **PredictionSettlements** with `EventType: "Redemption"`. Replace the question title with your market’s exact **Question.Title** (e.g. from the creation/resolution queries). [Run in Bitquery IDE](https://ide.bitquery.io/top-10-traders-of-a-gold-market) ```graphql query TopRedeemersGoldMarket { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descendingByField: "redeemed_amount" } where: { Settlement: { EventType: { is: "Redemption" } Prediction: { Question: { Title: { is: "Gold (GC) Up or Down on March 18?" } } } } } ) { Settlement { Holder } redeemed_amount: sum(of: Settlement_Amounts_CollateralAmountInUSD) } } } ``` --- ## Real-time: Subscriptions and Kafka ### GraphQL subscriptions Any **query** on this page can be run as a **subscription**: use the same `where` filters and fields, and change the keyword `query` to `subscription`. You will receive new events (creations, resolutions, or trades) as they occur on Polygon over a WebSocket connection. ### Kafka streams For **low-latency** consumption, prediction market data (including commodity markets) is available via **Kafka**: - `matic.predictions.proto`: Raw prediction market events (creations, resolutions, trades) - `matic.broadcasted.predictions.proto`: Mempool prediction market data Kafka requires **separate credentials**. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). For access, [contact support](https://t.me/bloxy_info) or email support@bitquery.io. --- ## Polymarket Historical Data - Parquet, S3, Snowflake, BigQuery URL: https://docs.bitquery.io/docs/cloud/polymarket/ Polymarket historical data as Parquet: on-chain trades, prices and settlements with market question and outcome labels, ready to load into S3, Snowflake or BigQuery. # Polymarket Historical Data Bitquery provides **Polymarket historical data** as **Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), covering on-chain trades, outcome prices and settlements, already joined with the market question, outcome label and collateral token. It is built for backtesting, research, leaderboards and data lake integrations where paging through a REST API is too slow. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, DuckDB, etc**. Polymarket runs on **Polygon (Matic)**, so all Polymarket datasets live under the `matic/` prefix. ## Which Polymarket data source should I use? | Need | Use | | --- | --- | | Last ~4 days on realtime, or from 1 September 2025 with the history add-on; ad-hoc queries and aggregations | [Polymarket API](/docs/examples/polymarket-api/) (GraphQL, `dataset: realtime`) | | Live trades, whale alerts, odds as they change | [GraphQL subscriptions](/docs/examples/polymarket-api/) or [Kafka streams](/docs/streams/kafka-streaming-concepts/) | | History since September 2025, backtests, model training, warehouse joins | **Parquet exports on this page** | Polymarket moved to new CTF Exchange contracts and pUSD collateral in April 2026. Each row carries `Trade_Prediction_Marketplace_SmartContract` and `Trade_Prediction_CollateralToken_*`, so you can separate trades before and after the migration. ## Available Polymarket Topics For Polymarket, Bitquery currently provides the following datasets: - **Prediction Trades** – Outcome-token trades with market question, outcome label, price, and collateral amounts - **Prediction Settlements** – Position splits, merges and payout redemptions - **DEX Trades** – Polymarket trades in the standard EVM DEX trades schema ## Sample Polymarket Cloud Dataset You can explore schemas and validate your tooling using the **public Polymarket sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/polymarket](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/polymarket) **Sample Parquet downloads (public S3)** - **Prediction Trades** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet) - **Prediction Settlements** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/PredictionSettlements/85230000_85230049.parquet) - **DEX Trades** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/dex_trades/polymarket/83713800_83713849.parquet) ## Polymarket Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── matic/ ├── polymarket/ │ ├── prediction_trades/ │ │ ├── 84735000_84735049.parquet │ │ ├── 84735050_84735099.parquet │ │ └── ... │ └── PredictionSettlements/ │ ├── 85230000_85230049.parquet │ ├── 85230050_85230099.parquet │ └── ... └── dex_trades/ └── polymarket/ ├── 83713800_83713849.parquet ├── 83713850_83713899.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Example: ``` 84735000_84735049.parquet ``` ## Dataset Fields **Prediction Trades** records an outcome-token trade together with the market it belongs to: - `Block_Number`, `Block_Time`, `Transaction_Hash`, `Transaction_From` - `Trade_OutcomeTrade_*` – buyer, seller, order id, amount, collateral amount, price, `IsOutcomeBuy`, plus USD equivalents - `Trade_Prediction_Question_*` – market question title, id, market id, resolution source, image, creation time - `Trade_Prediction_Outcome_*` – outcome id, index, and label (for example `Down`) - `Trade_Prediction_OutcomeToken_*` / `Trade_Prediction_CollateralToken_*` – ERC-1155 outcome token and ERC-20 collateral token (for example USDC) details - `Trade_Prediction_Marketplace_*` – protocol name, family (`Gnosis_CTF`), version, and contract **Prediction Settlements** records position splits, merges and redemptions for a holder: - `Settlement_EventType` (for example `Redemption`), `Settlement_Holder`, `Settlement_OutcomeTokenIds` - `Settlement_Amounts_*` – amount and collateral amount, with USD equivalents - `Settlement_Prediction_*` – same question, outcome, token, and marketplace structure as trades **DEX Trades** uses the standard EVM DEX trades schema documented on the [EVM Data](/docs/cloud/evm/) page. ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets?network=polymarket&utm_source=docs&utm_medium=referral&utm_campaign=datastore&utm_content=cloud-polymarket) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). Datasets you can buy on the Data Store: - [Polymarket](https://bitquery.io/datastore/datasets/polymarket?utm_source=docs&utm_medium=referral&utm_campaign=datastore&utm_content=cloud-polymarket): order fills, position splits, merges and payouts, with market titles, outcomes and USD values This listing is not the full catalogue. Other topics, chains and date ranges are available on request from **sales@bitquery.io**. ## Reading Files with DuckDB You need no key or client library. Point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet') LIMIT 10; ``` ## Example: daily Polymarket volume from the sample file DuckDB can aggregate the Parquet file over HTTPS without loading it anywhere first. Swap the single file for a glob over your own bucket to run it across the full history. ```sql SELECT Trade_Prediction_Question_Title AS market, Trade_Prediction_Outcome_Label AS outcome, count(*) AS trades, sum(CAST(Trade_OutcomeTrade_CollateralAmountInUSD AS DOUBLE)) AS volume_usd, avg(CAST(Trade_OutcomeTrade_Price AS DOUBLE)) AS avg_price FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet') GROUP BY 1, 2 ORDER BY volume_usd DESC LIMIT 20; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access Data Store exports are built for **batch analytics and historical workloads**. If you require **low-latency or streaming Polymarket data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - [**GraphQL subscriptions and queries**](/docs/examples/polymarket-api/) for trades, odds, wallets and whale alerts See also [Polymarket API vs Bitquery Polymarket API](/docs/API-Blog/polymarket-api-vs-bitquery-polymarket-api/) for how this compares with Polymarket's own Data API. --- ## Polymarket Insider & Fresh-Wallet Detection API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-insider-detection-api/ Polymarket insider detection: catch large trades, check for fresh wallets, trace funding sources, find wallet clusters and score timing against outcomes. # Polymarket Insider & Fresh-Wallet Detection API Detect suspicious trading on **Polymarket** using on-chain data from Polygon. This page shows how to flag potential insiders by combining **fresh-wallet checks**, **USDC funding-source tracing**, **wallet clustering**, **large bets**, and **pre-resolution timing**. Bitquery runs **its own blockchain nodes** and **indexes, decodes, and parses** raw Polygon transactions. That gives you signals the off-chain Polymarket Gamma and Data APIs cannot provide, such as how old a wallet is, where its money came from, and which other wallets share the same funder. These on-chain signals are the foundation of every serious insider-detection and copy-trading tool. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. See [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/). ::: --- ## How Insider Detection Works on Polymarket A suspected insider leaves a specific footprint on-chain: 1. A **brand-new wallet** with little or no prior activity. 2. Funded by a **traceable USDC source**, often shared with other suspicious wallets. 3. A **large bet** in a low-volume or niche market. 4. Entered **shortly before resolution**, on the winning side. 5. **Redeems** the winnings and goes dormant. No single signal is proof. You combine them into a score and flag wallets that cross a threshold. The queries below produce each signal. ### Signal to Data Map | Signal | What you measure | Bitquery source | | ------ | ---------------- | --------------- | | **Fresh wallet** | Wallet age (first on-chain activity) vs first bet | `EVM.Transfers` (`dataset: combined`) | | **Funding source** | First USDC transfer into the wallet | `EVM.Transfers` (USDC.e) | | **Wallet cluster (Sybil)** | Other wallets funded by the same sender | `EVM.Transfers` grouped by receiver | | **Large bet in niche market** | Bet USD vs market 24h volume | `PredictionTrades` | | **Pre-resolution timing** | Hours between trade and resolution, winning side | `PredictionTrades` + `joinPredictionManagements` | | **Won and dormant** | Redemption amount, then no activity | `PredictionSettlements` + `Transfers` | :::tip Why `dataset: combined` The wallet-history queries below use `dataset: combined` so they search the **full chain history**, not just the realtime window. This matters for wallet age and funding traces, where you need the earliest activity ever recorded. ::: --- ## Step 1: Catch Large Trades in Real Time Start by streaming large Polymarket trades. Each event gives you a **buyer address** to investigate. Change `subscription` to `query` for historical results. [Run in Bitquery IDE](https://ide.bitquery.io/large-trades--on-polymarket) ```graphql subscription { EVM(network: matic) { PredictionTrades( where: { Trade: { OutcomeTrade: { CollateralAmountInUSD: { gt: "5000" } } Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time } Trade { OutcomeTrade { Buyer Seller CollateralAmountInUSD Price IsOutcomeBuy } Prediction { Question { MarketId Title } Outcome { Index Label } } } Transaction { Hash } } } } ``` --- ## Step 2: Is the Buyer a Fresh Wallet? Look up the buyer's **earliest on-chain activity**. If the wallet's first transfer is close to the time of its first big bet, it is a fresh wallet and scores high. Replace the address with the buyer from Step 1. [Run in Bitquery IDE](https://ide.bitquery.io/freshwallet-check-for-polymarket) ```graphql query FreshWalletCheck { EVM(network: matic, dataset: combined) { Transfers( where: { Transfer: { Sender: { is: "0xe8a2057abd53d285f7bea590b8f1dff1f04454c2" } } } ) { earliest: Block { Time(minimum: Block_Time) } } } } ``` A recent `earliest` time means a young wallet. You can also add `count` to the selection to get the wallet's lifetime transfer count, another freshness signal. --- ## Step 3: Trace the Funding Source Find where the wallet's money came from. The **first inbound USDC transfer** is usually the original funder, often a centralized exchange withdrawal or a parent wallet. This query uses bridged USDC.e on Polygon (`0x2791bca1f2de4661ed88a30c99a7a9449aa84174`), which is still how wallets are funded; Polymarket wraps it into **pUSD** (`0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB`) for trading, so add that contract if you also want pUSD moves between wallets. [Run in Bitquery IDE](https://ide.bitquery.io/FundingSource-for-poylmarket) ```graphql query FundingSource { EVM(network: matic, dataset: combined) { Transfers( orderBy: { ascending: Block_Time } limit: { count: 5 } where: { Transfer: { Currency: { SmartContract: { is: "0x2791bca1f2de4661ed88a30c99a7a9449aa84174" } } Receiver: { is: "0xe8a2057abd53d285f7bea590b8f1dff1f04454c2" } } } ) { Block { Time } Transfer { Sender Amount } Transaction { Hash } } } } ``` --- ## Step 4: Find the Wallet Cluster (Sybil Detection) Take the funder from Step 3 and list **every other wallet it funded**. Wallets sharing a funder are likely controlled by the same operator. A large cluster placing correlated bets is a strong signal. [Run in Bitquery IDE](https://ide.bitquery.io/SiblingWallets-for-polymarket) ```graphql query SiblingWallets { EVM(network: matic, dataset: combined) { Transfers( limitBy: { by: Transfer_Receiver, count: 1 } where: { Transfer: { Currency: { SmartContract: { is: "0x2791bca1f2de4661ed88a30c99a7a9449aa84174" } } Sender: { is: "0xe8a2057abd53d285f7bea590b8f1dff1f04454c2" } } } ) { Transfer { Receiver } received: sum(of: Transfer_Amount) } } } ``` --- ## Step 5: Timing and Outcome The final signals come from the trade itself. Check how soon before resolution the wallet entered, and whether it was on the winning side. - **Pre-resolution timing:** join the wallet's trades to the market's `Resolved` event and compute the lead time. Use the `joinPredictionManagements` pattern from the [Polymarket Sports API](/docs/examples/polymarket-api/polymarket-sports-api/). - **Won and dormant:** confirm the payout with a `Redemption` query on `PredictionSettlements`, then re-run Step 2 to check the wallet went quiet afterward. - **Realized profit and win rate:** see [Realized PnL & Win Rate for Polymarket Trader](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/). --- ## Scoring Model Combine the signals into a weighted score and flag wallets above a threshold. Tune the weights to your tolerance for false positives. ``` score = 0.30 * fresh_wallet + 0.25 * shared_funder_cluster + 0.20 * bet_pct_of_market_volume + 0.15 * entered_within_24h_of_resolution + 0.10 * won_and_went_dormant flag if score >= threshold ``` This mirrors how tools like CrowdIntel and PolyTrack work. Bitquery provides the on-chain primitives they otherwise have to reverse-engineer. --- ## Limitations Read this before acting on a flag. - These are **heuristics, not proof**. A fresh wallet or a shared funder is not evidence of wrongdoing. Exchange withdrawal addresses fund many unrelated users and create false clusters. - The "**entered before the news broke**" idea needs an off-chain news timestamp. On-chain you can only proxy it with the **resolution time** or a **sharp odds move** (see the OHLC query on the Sports API page). - Always verify the current **collateral token** and any neg-risk or Conditional Token Framework specifics in the IDE before relying on results. --- ## Related APIs | Need | API | | ---- | --- | | **Live odds, trades, volume by sport** | [Polymarket Sports API](/docs/examples/polymarket-api/polymarket-sports-api/) | | **Trader realized PnL & win rate** | [Realized PnL & Win Rate for Polymarket Trader](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/) | | **User & wallet activity** | [Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/) | | **Trades, prices, whales** | [Polymarket API](/docs/examples/polymarket-api/) | | **Settlements & redemptions** | [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) | | **Real-time: Kafka streams** | [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) | --- ## Support - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket MCP Server for Claude, ChatGPT and Cursor URL: https://docs.bitquery.io/docs/mcp/polymarket/ Give Claude, ChatGPT, Cursor or your own AI agent live Polymarket data: top markets, odds, price history, large fills, top wallets and disputed resolutions, from on-chain data. Read-only. # Polymarket MCP Server The Bitquery MCP server gives an AI client 14 tools for Polymarket data. You ask a question in Claude, ChatGPT, Cursor, VS Code or Codex, the agent picks a tool, and rows come back from Bitquery's on-chain index of Polymarket on Polygon. It reads data only. It cannot place, change or cancel an order. To trade, use Polymarket's own CLOB API; to research markets, wallets and odds, use this. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Other clients take the same URL. Steps for each are in the [MCP server install guide](/docs/mcp/mcp-server/). A 38-second demo, [Polymarket and Hyperliquid data in ChatGPT and Claude](https://www.youtube.com/watch?v=IwuIlcKsANk), shows the server answering questions like the ones below. Every figure on this page came from a call to the production server on 21 September 2026, between 09:00 and 09:10 UTC. Polymarket moves fast, so your numbers will differ. ## What can I ask? ### Which markets are people trading right now? > *"What are the five most traded Polymarket markets in the last 24 hours?"* The agent calls `polymarket_top_markets`. | # | Market | 24h volume | Orders | Wallets | |---|---|---:|---:|---:| | 1 | Colts vs. Chiefs | $4,114,943 | 9,124 | 292 | | 2 | Will United Russia (ER) gain the most seats in the next Russian parliamentary election? | $4,065,436 | 8,532 | 565 | | 3 | Will Manchester City FC win on 2026-09-20? | $1,918,415 | 5,523 | 386 | | 4 | Eagles vs. Titans | $1,800,372 | 4,075 | 188 | | 5 | Packers vs. Jets | $1,666,912 | 4,181 | 190 | The first row of every answer states the window that was ranked and how far the data trails the clock. On this call it was 14 minutes behind. A short window can therefore look quieter than it was, and the tool says so instead of reporting an empty market. ### What are the odds on a market I only know by name? > *"Find the open Polymarket markets about the Fed rate, then give me the odds on the first one."* Two calls. `polymarket_find_markets` with the text "Fed rate" returned three open markets, all created on 16 September 2026: "Another Fed rate hike in 2026?", "Fed rate cut by July 2027 meeting?" and "Fed rate cut by January 2027 meeting?". Then `polymarket_market_odds` on the first: | Outcome | Price | Implied probability | Lifetime volume | |---|---:|---:|---:| | Yes | 0.86 | 86% | $24,260 | | No | 0.15 | 15% | $8,783 | A price is dollars per share between 0 and 1, which is the market's own probability. The two sides add up to 1.01 here because the last fill on each side happened at a different minute. When one side's last trade is old, ask for the 24-hour VWAP, which the same tool returns. Search text is a plain substring. Asking for "Fed" alone also returned tennis markets for a player named Fedor. Give the agent two words when one is ambiguous. ### How did the odds move? > *"Show the daily close for Yes on the United Russia market over the last week."* `polymarket_market_price_history` with a one-day interval: | Day (UTC) | Close | Volume | |---|---:|---:| | 15 Sep | 0.77 | $170,235 | | 16 Sep | 0.73 | $474,884 | | 17 Sep | 0.76 | $183,599 | | 18 Sep | 0.83 | $833,802 | | 19 Sep | 0.81 | $1,163,964 | | 20 Sep | 0.985 | $3,528,998 | | 21 Sep (to 09:00) | 0.998 | $544,109 | Volume tripled on the day the price went from 0.81 to 0.985. Intervals run from one second to one day, and days with no trades are left out instead of being filled in. ### Who is behind the volume? > *"Who traded the most in that market, and is the top wallet a directional bettor or a market maker?"* `polymarket_top_traders` for the one market, over its whole history: | Wallet | Volume | Bought | Sold | Orders | |---|---:|---:|---:|---:| | `0xf2f6…5817` | $934,582 | $608,832 | $325,750 | 1,700 | | `0x369f…873e` | $701,366 | $421,191 | $280,175 | 498 | | `0x6575…b198` | $570,815 | $570,815 | $0 | 364 | | `0x44c1…ebc1` | $414,423 | $414,423 | $0 | 102 | | `0xc021…1fa8` | $413,220 | $297,140 | $116,080 | 511 | This list ranks by dollars traded. It says nothing about profit. The follow-up call shows why that matters: `polymarket_trader_summary` on the top wallet returns 51,391 lifetime orders across 1,237 markets and $19.55 million traded, and 48,736 of those orders (95%) were resting orders on the book. That is the footprint of a market maker. Wallets three and four are the opposite: buys only, and both placed their first order in this market within the last week (16 and 18 September). ### Where are the big fills? > *"Show the latest fills above $10,000 in that market."* `polymarket_market_trades` with a minimum size, newest four: | Time (UTC) | Wallet | Side | Price | Size | |---|---|---|---:|---:| | 08:32:02 | `0xc021…1fa8` | sell Yes | 0.998 | $49,900 | | 08:32:02 | `0xb24c…eefe` | sell Yes | 0.998 | $21,153 | | 07:51:50 | `0xb24c…eefe` | sell Yes | 0.997 | $13,757 | | 06:53:51 | `0xe25b…0f1b` | sell Yes | 0.997 | $60,782 | Read side and outcome together. Buying No is the same bet as selling Yes. Most fills on a busy market are under a dollar, so a size floor of $100 or $1,000 is what turns the tape into something readable. ### Was a resolution challenged? > *"Which Polymarket outcomes were disputed in the last day?"* The four newest rows from `polymarket_market_disputes` fell between 08:27 and 08:31 UTC, all on one tennis match (M15 Baku, Aleshchev vs Skvortcov) and its set-handicap and total-sets markets. Two wallets raised them, and all four were against answers proposed by the same address. A dispute restarts resolution; it is not a verdict, and the market often settles to the same outcome afterwards. Challenge records start on 9 March 2026. For an older market an empty answer means "not covered", and the tool's own text tells the agent to say so. ## Build a Polymarket AI agent with Claude or ChatGPT An agent that reasons about prediction markets needs current odds, fills and wallet history, and a language model has none of those by itself. This server is that data layer. Any client or framework that speaks MCP can call the same 14 tools, so a Polymarket AI agent built on Claude, ChatGPT or an open model reads the same numbers a person gets in chat. Three jobs people give such an agent: - **A morning brief.** "List the ten most traded markets in the last 24 hours, the odds on each, and any whose Yes price moved more than 10 points since yesterday." That chains `polymarket_top_markets`, `polymarket_market_odds` and `polymarket_market_price_history`. A worked version is in [Polymarket analytics with AI](/docs/mcp/polymarket-analytics/). - **A wallet watch.** Rank wallets, drop the market makers, and score the rest. The full walk-through is in [Track Polymarket whales and top traders](/docs/mcp/polymarket-whale-tracker/). - **A resolution check.** Before trusting a settled market, ask `polymarket_market_disputes` whether the answer was challenged. The agent still cannot trade through this server. Pair it with Polymarket's CLOB API if you want it to place orders, and keep a person in charge of that step. ## All 14 Polymarket tools | Tool | Use it for | |---|---| | `polymarket_find_markets` | Find markets by title text or category and get their question id | | `polymarket_market_info` | One market's detail: outcome tokens, oracle, collateral, resolution rules | | `polymarket_market_odds` | Current price and implied probability per outcome, or as of a past moment | | `polymarket_market_price_history` | OHLC, VWAP and volume per interval, 1 second to 1 day | | `polymarket_market_trades` | Individual fills, newest first, with a size floor and a per-wallet filter | | `polymarket_market_events` | Created and resolved lifecycle events | | `polymarket_market_disputes` | Challenged answers and rule changes after launch | | `polymarket_top_markets` | Markets ranked by volume, orders, wallets or fees in a window | | `polymarket_top_traders` | Wallets ranked by volume, across all markets or inside one | | `polymarket_trader_summary` | One wallet's lifetime card: first and last trade, volume, markets, maker share | | `polymarket_trader_activity` | One wallet's breakdown by market and outcome | | `polymarket_trader_positions` | What a wallet still holds | | `polymarket_outcome_holders` | Who holds an outcome token | | `polymarket_settlements` | Redemptions, splits and merges | ## What to know before you rely on it - **Read-only.** No order placement, no order book depth. Fills are settled on-chain orders. - **A few minutes behind.** Calls on this page trailed the clock by 12 to 15 minutes. Every answer reports its own lag. - **History starts in September 2025.** A wallet whose "first trade" is 1 September 2025 may have traded earlier. Dispute records start on 9 March 2026. - **No profit and loss in the rankings.** `polymarket_top_traders` is volume only. - **Collateral changed in 2026.** Older fills settle in USDC, newer ones in pUSD. The tools report which one each market used. ## MCP, GraphQL or the official API? | You want to | Use | |---|---| | Place or cancel orders, read the order book | Polymarket's CLOB API | | Ask questions in a chat or let an agent research a market | This MCP server | | Build a dashboard, alert or backfill in code | The [Bitquery Polymarket GraphQL API](/docs/examples/polymarket-api/), with WebSocket and Kafka streams | | Load full history into a warehouse | [Polymarket Data Store exports](/docs/cloud/polymarket/) | Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-polymarket#pricing). --- ## Polymarket Markets API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-markets-api/ Polymarket markets lookup: find markets by condition_id, token_id (AssetId) or market_slug, and combine filters with a time range in GraphQL queries. # Markets API Find markets on Polymarket by **market slug**, **event slug**, **condition ID**, or **token ID**. Use these parameters to narrow results to specific markets or events when building apps that combine market metadata with [trades](/docs/examples/prediction-market/prediction-trades-api/) and [settlements](/docs/examples/prediction-market/prediction-settlements-api/). **Network:** Polygon (`network: matic`). For full lifecycle and trade data, see the [Polymarket API](/docs/examples/polymarket-api/) overview and the [Prediction Market API](/docs/examples/prediction-market/prediction-market-api/). --- ## Filter parameters All parameters are optional. You can combine multiple filters; results match markets that satisfy the criteria you provide. | Parameter | Type | Description | | ---------------- | -------- | ------------------------------------------------------------------- | | **market_slug** | string[] | Filter markets by market slug(s). Can provide multiple values. | | | **condition_id** | string[] | Filter markets by condition ID(s). Can provide multiple values. | | **token_id** | string[] | Filter markets by outcome token ID(s). Can provide multiple values. | ## Find markets by condition_id Use when you have on-chain condition IDs (e.g. from Main Polymarket Contract events). Condition IDs are hex strings; you can pass one or more. Get market lifecycle events (created/resolved) for one or more condition IDs. Condition IDs are hex strings (with or without `0x`). [Run Query](https://ide.bitquery.io/Filter-markets-by-condition-ID-Polymarket) ```graphql query MarketsByConditionId($conditionIds: [String!]) { EVM(network: matic) { PredictionManagements( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Management: { Prediction: { Condition: { Id: { in: $conditionIds } } Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time Number } Transaction { Hash Time } Management { EventType Prediction { Condition { Id QuestionId Outcomes { Id Index Label } } Question { MarketId Title Image ResolutionSource CreatedAt } CollateralToken { Symbol Name } Outcome { Id Label } OutcomeToken { AssetId SmartContract } } } } } } ``` **Variables (example):** ```json { "conditionIds": [ "0x4567b275e6b667a6217f5cb4f06a797d3a1eaf1d0281fb5bc8c75e2046ae7e57" ] } ``` ## Find markets by token_id (AssetId) Use when you have outcome token IDs (e.g. from [Prediction Trades](/docs/examples/prediction-market/prediction-trades-api/) `OutcomeToken.AssetId`). Pass one or more AssetIds. [Run query](https://ide.bitquery.io/Filter-markets-by-asset-ID-Polymarket) ```graphql query MarketsByAssetId($assetIds: [String!]) { EVM(network: matic) { PredictionManagements( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Management: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } OutcomeToken: { AssetId: { in: $assetIds } } } } } ) { Block { Time Number } Transaction { Hash Time } Management { EventType Prediction { Condition { Id QuestionId Outcomes { Id Index Label } } Question { MarketId Title Image ResolutionSource CreatedAt } CollateralToken { Symbol Name } Outcome { Id Label } OutcomeToken { AssetId SmartContract } } } } } } ``` **Variables (example):** ```json { "assetIds": [ "19443761038809394075988687891855393102730862479306560066876868792031660494383" ] } ``` ## Find markets by market_slug Filter by market slug or keyword using **Question.Title** with case-insensitive match. Use the URL slug (e.g. `bitcoin-up-or-down-july-25-8pm-et`) or a keyword (e.g. `XRP`). [Run query](https://ide.bitquery.io/Find-Markets-by-market_slug-on-Polymarket) ```graphql query MarketsByMarketSlug($marketSlug: String!) { EVM(network: matic) { PredictionManagements( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Management: { Prediction: { Question: { Title: { includesCaseInsensitive: $marketSlug } } Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time Number } Transaction { Hash Time } Management { EventType Prediction { Condition { Id QuestionId Outcomes { Id Index Label } } Question { MarketId Title Image ResolutionSource CreatedAt } CollateralToken { Symbol Name } Outcome { Id Label } OutcomeToken { AssetId SmartContract } } } } } } ``` **Variables (example):** ```json { "marketSlug": "bitcoin-up-or-down-july-25-8pm-et" } ``` ### Combined filters (condition_id + time range) Combine **condition_id** with other filters such as a time window or event type in the same `where` clause. You can combine **condition_id** with other filters (e.g. time range, event type) in the same `where` clause. ```graphql query MarketsByConditionIdRecent($conditionIds: [String!]) { EVM(network: matic) { PredictionManagements( limit: { count: 20 } orderBy: { descending: Block_Time } where: { Block: { Time: { since_relative: { days_ago: 7 } } } Management: { Prediction: { Condition: { Id: { in: $conditionIds } } Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time } Management { EventType Prediction { Condition { Id } Question { MarketId Title } Outcome { Label } } } } } } ``` **Variables (example):** ```json { "conditionIds": [ "0x4567b275e6b667a6217f5cb4f06a797d3a1eaf1d0281fb5bc8c75e2046ae7e57" ] } ``` --- ## Related APIs | Need | API | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | **Trades & prices** | [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/) | | **Settlements & redemptions** | [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) | | **Market creation & resolution** | [Prediction Market API](/docs/examples/prediction-market/prediction-market-api/) / [Prediction Managements API](/docs/examples/prediction-market/prediction-managements-api/) | | **Polymarket overview** | [Polymarket API](/docs/examples/polymarket-api/) | | **User & wallet activity** | [Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/) | | **On-chain condition & tokens** | Main Polymarket Contract (on-chain) | --- ## Polymarket Sports API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-sports-api/ Polymarket sports markets: World Cup, cricket and esports markets, live odds, odds movement, volume by outcome, resolved games and top traders. # Polymarket Sports API - Live Odds, Cricket, NBA, NFL & Esports Markets Get full access to **Polymarket sports markets** through one API. That covers NBA, NFL, soccer, cricket, UFC, esports and more, with live odds (implied probability), trades, volume, market creation and resolution, and trader-level activity. Bitquery runs **its own blockchain nodes** and **indexes, decodes, and parses** raw Polygon transactions into clean, structured prediction-market data. You don't have to run nodes, decode contract logs, or stitch together odds yourself. The same data is available three ways: - **Historical queries:** backfill odds, volume, and resolutions over any time range. - **Real-time GraphQL subscriptions (WebSocket):** stream new trades and odds the moment they hit the chain. - **Kafka streams:** low-latency, high-throughput feeds for production pipelines. Every query below can be run live by changing `query` to `subscription`. See [Real-Time: GraphQL Subscriptions and Kafka](#real-time-graphql-subscriptions-and-kafka). :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. See [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/). ::: --- ## How Sports Markets Are Identified | Filter | Use case | Where to apply | | -------------------- | --------------------------------------------------------------------------- | ------------------------------------------------- | | **ResolutionSource** | Markets resolved by a specific source (e.g. `espncricinfo.com` for cricket) | `Management.Prediction.Question.ResolutionSource` | | **Description** | General sports markets (keyword in management description) | `Management.Description` | | **Outcome label** | Trades on outcomes whose label contains a term (e.g. "Esports") | `Trade.Prediction.Outcome.Label` | ### Filter by League or Team To target a specific league, tournament, or team, match a keyword in `Question.Title` with `includesCaseInsensitive` (case-insensitive). The same filter works on **PredictionManagements**, **PredictionTrades**, and **PredictionSettlements**. Just place it under `Prediction.Question.Title`. | League / Sport | Example `Question.Title` keyword | | ------------------ | ------------------------------------- | | FIFA / World Cup | `"World Cup"` | | Soccer (EPL) | `"Premier League"` | | Soccer (La Liga) | `"La Liga"` | | Soccer (Serie A) | `"Serie A"` | | Soccer (UCL) | `"Champions League"` | | NBA | `"NBA"` | | NFL | `"NFL"` | | NHL | `"NHL"` | | MLB | `"MLB"` | | UFC / MMA | `"UFC"` | | Tennis | `"Australian Open"`, `"Wimbledon"`, … | | Cricket | `"cricket"` | | Esports (Valorant) | `"Valorant"`, or `"Esports"` (label) | | A specific team | `"Lakers"`, `"Arsenal"`, … | > **Tip:** A single game is uniquely identified by its `Question.MarketId`. Use the creation queries above to discover market IDs, then plug them into the live-odds, OHLC, volume, and trader queries below. --- ### Real-Time: GraphQL Subscriptions and Kafka #### GraphQL Subscriptions Any **query** on this page can be run in **real time** as a **subscription**: keep the same `where` filters and requested fields, and change the keyword `query` to `subscription`. You receive new events (market creations or trades) as they occur on Polygon via a WebSocket connection. #### Kafka Streams For **low-latency** and high-throughput consumption, prediction market data (including sports) is also available via **Kafka**. The same lifecycle events and trades are delivered as Protocol Buffers on Polygon topics: - **`matic.predictions.proto`:** Raw prediction market events (creations, resolutions, trades) - **`matic.broadcasted.predictions.proto`:** Mempool prediction market data Kafka requires **separate credentials** (IDE tokens do not work). See the full guide and topic list: - **[Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/):** Connect, subscribe, parse messages, and configure consumers. For credentials, [contact support](https://t.me/bloxy_info) or email support@bitquery.io. ## Latest FIFA World Cup Markets Created Markets resolved via **FIFA** (`ResolutionSource` includes `fifa.com`). Returns the 10 most recent **Created** events with full condition, outcomes, question, and collateral token details. [Run in Bitquery IDE](https://ide.bitquery.io/Latest-Fifa-World-Cup-Markets-Created) ```graphql query LatestFifaMarketsCreated { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Created" } Prediction: { Question: { ResolutionSource: { includes: "fifa.com" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` ## Top FIFA World Cup Markets by Volume Markets resolved via **FIFA** (`ResolutionSource` includes `fifa.com`). Returns the top 100 cricket related polymarkets sorted by trading volume in the past 24 hours. [Run in Bitquery IDE](https://ide.bitquery.io/top-FIFA-World-Cup-markets-by-volume) ```graphql query TopFIFAMarketsByVolume($time_ago: Int!, $limit: Int!) { EVM(network: matic) { PredictionTrades( where: {Block: {Time: {since_relative: {hours_ago: $time_ago}}}, Trade: {Prediction: {Question: {ResolutionSource: {includes: "fifa.com"}}}}} limit: {count: $limit} orderBy: {descendingByField: "sumBuyAndSell"} ) { Trade { Prediction { Question { Id Image Title CreatedAt } OutcomeToken { assetId0: AssetId(if: {Trade: {Prediction: {Outcome: {Index: {eq: 0}}}}}) assetId1: AssetId(if: {Trade: {Prediction: {Outcome: {Index: {eq: 1}}}}}) } Outcome { label0: Label(if: {Trade: {Prediction: {Outcome: {Index: {eq: 0}}}}}) label1: Label(if: {Trade: {Prediction: {Outcome: {Index: {eq: 1}}}}}) } } OutcomeTrade { price0: Price( maximum: Block_Time if: {Trade: {Prediction: {Outcome: {Index: {eq: 0}}}}} ) price1: Price( maximum: Block_Time if: {Trade: {Prediction: {Outcome: {Index: {eq: 1}}}}} ) } } buyUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: {Trade: {OutcomeTrade: {IsOutcomeBuy: true}}} ) sellUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: {Trade: {OutcomeTrade: {IsOutcomeBuy: false}}} ) sumBuyAndSell: calculate(expression: "$buyUSD + $sellUSD") trades: count buyers: count(distinct: Trade_OutcomeTrade_Buyer) sellers: count(distinct: Trade_OutcomeTrade_Seller) resolved: joinPredictionManagements( join: left Management_Prediction_Question_Id: Trade_Prediction_Question_Id ) { Block { Time(maximum: Block_Time, if: {Management: {EventType: {is: "Resolved"}}}) } } } } } ``` Variables: ```json { "time_ago": 24, "limit": 100 } ``` ## Top FIFA World Cup Markets by Liquidity Returns the top 100 FIFA World Cup related polymarkets sorted by liquidity position in the past 24 hours. Here `position` is the metric used for sorting, hence it could be regarded as the liquidity position of the particular market. [Run in Bitquery IDE](https://ide.bitquery.io/Top-FIFA-World-Cup-Markets-by-Liquidity) ```graphql query TopFIFAMarketByLiquidity($time_ago: Int!, $limit: Int!) { EVM(network: matic) { PredictionSettlements( where: {Block: {Time: {since_relative: {hours_ago: $time_ago}}}, Settlement: {Prediction: {Question: {ResolutionSource: {includes: "fifa.com"}}}}} limit: {count: $limit} orderBy: {descendingByField: "position"} limitBy: {by: Settlement_Prediction_Question_Id} ) { Settlement { Prediction { Question { Image MarketId Title Id CreatedAt ResolutionSource } } } split: sum( of: Settlement_Amounts_CollateralAmountInUSD if: {Settlement: {EventType: {is: "Split"}}} ) merge: sum( of: Settlement_Amounts_CollateralAmountInUSD if: {Settlement: {EventType: {is: "Merge"}}} ) position: calculate(expression: "$split - $merge") count(if: {Settlement: {EventType: {is: "Redemption"}}}, selectWhere: {eq: "0"}) } } } ``` Variables: ```json { "time_ago": 24, "limit": 100 } ``` ## Latest Cricket Markets Created Markets resolved via **ESPN Cricinfo** (`ResolutionSource` includes `espncricinfo.com`). Returns the 10 most recent **Created** events with full condition, outcomes, question, and collateral token details. [Run in Bitquery IDE](https://ide.bitquery.io/Latest-Cricket-Markets-Created) ```graphql query LatestCricketMarketsCreated { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Created" } Prediction: { Question: { ResolutionSource: { includes: "espncricinfo.com" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` ## Top Cricket Markets by Volume Markets resolved via **ESPN Cricinfo** (`ResolutionSource` includes `espncricinfo.com`). Returns the top 100 cricket related polymarkets sorted by trading volume in the past 24 hours. [Run in Bitquery IDE](https://ide.bitquery.io/top-cricket-markets-by-volume) ```graphql query TopCricketMarketsByVolume($time_ago: Int!, $limit: Int!) { EVM(network: matic) { PredictionTrades( where: {Block: {Time: {since_relative: {hours_ago: $time_ago}}}, Trade: {Prediction: {Question: {ResolutionSource: {includes: "espncricinfo.com"}}}}} limit: {count: $limit} orderBy: {descendingByField: "sumBuyAndSell"} ) { Trade { Prediction { Question { Id Image Title CreatedAt } OutcomeToken { assetId0: AssetId(if: {Trade: {Prediction: {Outcome: {Index: {eq: 0}}}}}) assetId1: AssetId(if: {Trade: {Prediction: {Outcome: {Index: {eq: 1}}}}}) } Outcome { label0: Label(if: {Trade: {Prediction: {Outcome: {Index: {eq: 0}}}}}) label1: Label(if: {Trade: {Prediction: {Outcome: {Index: {eq: 1}}}}}) } } OutcomeTrade { price0: Price( maximum: Block_Time if: {Trade: {Prediction: {Outcome: {Index: {eq: 0}}}}} ) price1: Price( maximum: Block_Time if: {Trade: {Prediction: {Outcome: {Index: {eq: 1}}}}} ) } } buyUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: {Trade: {OutcomeTrade: {IsOutcomeBuy: true}}} ) sellUSD: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: {Trade: {OutcomeTrade: {IsOutcomeBuy: false}}} ) sumBuyAndSell: calculate(expression: "$buyUSD + $sellUSD") trades: count buyers: count(distinct: Trade_OutcomeTrade_Buyer) sellers: count(distinct: Trade_OutcomeTrade_Seller) resolved: joinPredictionManagements( join: left Management_Prediction_Question_Id: Trade_Prediction_Question_Id ) { Block { Time(maximum: Block_Time, if: {Management: {EventType: {is: "Resolved"}}}) } } } } } ``` Variables: ```json { "time_ago": 24, "limit": 100 } ``` You can checkout the above data in more intuitive form on [DexRabbit](https://dexrabbit.bitquery.io/polymarket-predictions/sports/cricket?tab=volume). ![Cricket Markets by Liquidity](/img/dexrabbit/cricket-volume.png) ## Top Cricket Markets by Liquidity Returns the top 100 cricket related polymarkets sorted by liquidity position in the past 24 hours. [Run in Bitquery IDE](https://ide.bitquery.io/Top-cricket-Markets-by-Liquidity) ```graphql query questionByLiquidity($time_ago: Int!, $limit: Int!) { EVM(network: matic) { PredictionSettlements( where: {Block: {Time: {since_relative: {hours_ago: $time_ago}}}, Settlement: {Prediction: {Question: {ResolutionSource: {includes: "espncricinfo.com"}}}}} limit: {count: $limit} orderBy: {descendingByField: "position"} limitBy: {by: Settlement_Prediction_Question_Id} ) { Settlement { Prediction { Question { Image MarketId Title Id CreatedAt ResolutionSource } } } split: sum( of: Settlement_Amounts_CollateralAmountInUSD if: {Settlement: {EventType: {is: "Split"}}} ) merge: sum( of: Settlement_Amounts_CollateralAmountInUSD if: {Settlement: {EventType: {is: "Merge"}}} ) position: calculate(expression: "$split - $merge") count(if: {Settlement: {EventType: {is: "Redemption"}}}, selectWhere: {eq: "0"}) } } } ``` Variables: ```json { "time_ago": 24, "limit": 100 } ``` You can checkout the above data in more intuitive form on [DexRabbit](https://dexrabbit.bitquery.io/polymarket-predictions/sports/cricket?tab=liquidity). ![Cricket Markets by Liquidity](/img/dexrabbit/cricket-liquidity.png) ## Latest Sports Markets Created Markets whose **management description** includes the word **"sports"**. Use this for broad sports coverage beyond a single resolution source. Returns the 10 most recent **Created** events. [Run in Bitquery IDE](https://ide.bitquery.io/Latest-Sports-Markets-Created) ```graphql query LatestSportsMarketsCreated { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Created" } Description: { includes: "sports" } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` ## Latest Esports Prediction Trades Recent **trades** where the outcome **label** includes **"Esports"**. Returns up to 50 trades ordered by block time, with buyer, seller, amounts, price, and full prediction/question metadata. [Run in Bitquery IDE](https://ide.bitquery.io/Latest-Esports-Prediction-Trades) ```graphql query LatestEsportsPredictionTrades { EVM(network: matic) { PredictionTrades( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Trade: { Prediction: { Outcome: { Label: { includes: "Esports" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` --- ## Live Odds (Implied Probability) for a Single Game Returns the **latest trade price per outcome** for one market by `MarketId`. This is the **live win probability / odds** for the game. On Polymarket an outcome's `Price` ranges from **0 to 1 and equals its implied probability** (e.g. `0.62` = **62%**). `limitBy` with `orderBy: { descending: Block_Time }` returns one most-recent row per outcome (e.g. Team A vs Team B). Replace `""` with a market ID from the creation queries above. Change `query` to `subscription` for a live odds feed. [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-live-game-odds) ```graphql query LiveGameOdds { EVM(network: matic) { PredictionTrades( limitBy: { by: Trade_Prediction_Outcome_Label, count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { MarketId: { is: "" } } } } } ) { Trade { OutcomeTrade { Price PriceInUSD } Prediction { Outcome { Index Label } OutcomeToken { Name AssetId } Question { Title MarketId ResolutionSource Image } } } } } } ``` --- ## Odds (Line) Movement: OHLC for an Outcome Returns **OHLC** (Open, High, Low, Close) in USD for one outcome of a game, bucketed by interval (here 5 minutes). It shows how the **win probability moved over time**, and powers line-movement charts and strategy backtests. Replace `""` and `""` (e.g. a team name, `"Yes"`, or `"Up"`). [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-sports-odds-movement-OHLC) ```graphql query OddsMovementOHLC { EVM(network: matic) { PredictionTrades( limit: { count: 100 } orderBy: { descendingByField: "Block_Interval" } where: { Trade: { Prediction: { Question: { MarketId: { is: "" } } Outcome: { Label: { is: "" } } } } } ) { Block { Interval: Time(interval: { count: 5, in: minutes }) } Trade { OutcomeTrade { Open: PriceInUSD(minimum: Block_Time) High: PriceInUSD(maximum: Trade_OutcomeTrade_PriceInUSD) Low: PriceInUSD(minimum: Trade_OutcomeTrade_PriceInUSD) Close: PriceInUSD(maximum: Block_Time) } Prediction { OutcomeToken { Name AssetId } Outcome { Id Label } } } } } } ``` --- ## 24-Hour Odds Change for an Outcome Returns the **opening and closing odds** (plus high/low) over the **last 24 hours** for one outcome. It is the single-window version of the OHLC query, useful for "biggest movers" leaderboards (run it per market and sort by `Close − Open`). Replace `""` and `""`. [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-sports-24h-odds-change) ```graphql query Odds24hChange { EVM(network: matic) { PredictionTrades( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Trade: { Prediction: { Question: { MarketId: { is: "" } } Outcome: { Label: { is: "" } } } } } ) { Trade { OutcomeTrade { Open: PriceInUSD(minimum: Block_Time) Close: PriceInUSD(maximum: Block_Time) High: PriceInUSD(maximum: Trade_OutcomeTrade_PriceInUSD) Low: PriceInUSD(minimum: Trade_OutcomeTrade_PriceInUSD) } Prediction { Outcome { Label } Question { Title MarketId } } } } } } ``` --- ## Volume Split by Outcome (Money on Each Side) Returns **total volume** and **volume per outcome** (e.g. Team A vs Team B) for a single game in the last 24 hours. This is an on-chain **sentiment / sharp-money** signal. Outcomes are split by `Index` (0 and 1) so it works regardless of how the labels are named. Replace `""`. [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-game-volume-by-outcome) ```graphql query GameVolumeByOutcome { EVM(network: matic) { PredictionTrades( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Trade: { Prediction: { Question: { MarketId: { is: "" } } } } } ) { Trade { Prediction { Question { Title MarketId Image ResolutionSource } Outcome { label0: Label( if: { Trade: { Prediction: { Outcome: { Index: { eq: 0 } } } } } ) label1: Label( if: { Trade: { Prediction: { Outcome: { Index: { eq: 1 } } } } } ) } } } outcome0_volume: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { Prediction: { Outcome: { Index: { eq: 0 } } } } } ) outcome1_volume: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { Prediction: { Outcome: { Index: { eq: 1 } } } } } ) total_volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) trades: count } } } ``` --- ## Latest Resolved Sports Markets (Winning Outcome) Returns the 10 most recent **Resolved** sports markets (management description includes `"sports"`), including the resolved/winning **Outcome** and full question metadata. Use this to grade results and settle bets. For a single league, swap the `Description` filter for a `Prediction.Question.Title` keyword (see the league table above). [Run in Bitquery IDE](https://ide.bitquery.io/Latest-resolved-sports-markets) ```graphql query LatestResolvedSportsMarkets { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Resolved" } Description: { includes: "sports" } } } ) { Block { Time } Management { Description EventType Prediction { Condition { Id QuestionId Outcomes { Index Label } } Outcome { Index Label } Question { Title MarketId ResolutionSource Image CreatedAt } } } Transaction { Hash } } } } ``` --- ## Top Traders on a Game (Sharp Money) Returns the top 10 **buyers** and top 10 **sellers** by USD volume on a single market, showing who is putting the most money on each side. Replace `""`. (Drop the `MarketId` filter and add a `Question.Title` league keyword to rank traders across a whole league.) [Run in Bitquery IDE](https://ide.bitquery.io/Top-traders-on-a-sports-market) ```graphql query TopTradersOnGame { EVM(network: matic) { Top_buyers: PredictionTrades( where: { Trade: { Prediction: { Question: { MarketId: { is: "" } } } OutcomeTrade: { IsOutcomeBuy: true } } } limit: { count: 10 } orderBy: { descendingByField: "buy_volume" } ) { Trade { OutcomeTrade { Buyer } } buy_volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) trades: count } Top_sellers: PredictionTrades( where: { Trade: { Prediction: { Question: { MarketId: { is: "" } } } OutcomeTrade: { IsOutcomeBuy: false } } } limit: { count: 10 } orderBy: { descendingByField: "sell_volume" } ) { Trade { OutcomeTrade { Seller } } sell_volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) trades: count } } } ``` --- ## Top Winners of a Game (by Redemption) After a game resolves, this returns the top 10 holders by **redeemed amount** (USD). These are the biggest winners. Uses `PredictionSettlements` with `EventType: "Redemption"`. Replace `""`. [Run in Bitquery IDE](https://ide.bitquery.io/Top-winners-of-a-sports-market) ```graphql query TopWinnersOnGame { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descendingByField: "redeemed_amount" } where: { Settlement: { EventType: { is: "Redemption" } Prediction: { Question: { MarketId: { is: "" } } } } } ) { Settlement { Holder Prediction { Question { Title MarketId } } } redeemed_amount: sum(of: Settlement_Amounts_CollateralAmountInUSD) } } } ``` --- ## Real-Time Whale-Bet Alerts (Subscription) Streams live sports trades **above a USD threshold** (here `$5,000`). This is ideal for whale-alert bots and detecting large line-moving bets. Filter the sport with a `Question.Title` keyword (league or team), or swap it for a single-game `MarketId`. Change `subscription` to `query` for historical results. :::tip No-code option: PolyBit Telegram bot Don't want to run your own stream? The **[PolyBit Polymarket bot](https://t.me/PolyBit_Polymarket_Bot)** is a **free Telegram bot built by the Bitquery team** that monitors whale trades and other metrics across all markets. Open a specific market directly with a deep link: ``` https://t.me/PolyBit_Polymarket_Bot?start=market_ ``` Replace `` with the market's ID, for example [`market_2453464`](https://t.me/PolyBit_Polymarket_Bot?start=market_2453464). ::: ```graphql subscription { EVM(network: matic) { PredictionTrades( where: { Trade: { OutcomeTrade: { CollateralAmountInUSD: { gt: "5000" } } Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: "" } } } } } ) { Block { Time } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD Price PriceInUSD IsOutcomeBuy } Prediction { Question { Title MarketId ResolutionSource Image } Outcome { Index Label } } } Transaction { From Hash } } } } ``` --- ## Monitor Specific Wallets on Sports Markets (Subscription) Streams every sports trade where one of a watched wallet list is the **Buyer** or **Seller**. Powers copy-trading signals, wallet alerts, and PnL dashboards. Pass the addresses in the `$wallets` variable and set the `Question.Title` filter to the league/team you care about. [Run in Bitquery IDE](https://ide.bitquery.io/Monitor-wallets-on-Polymarket-sports-markets) ```graphql subscription MonitorWallets($wallets: [String!]) { EVM(network: matic) { PredictionTrades( where: { any: [ { Trade: { OutcomeTrade: { Buyer: { in: $wallets } } } } { Trade: { OutcomeTrade: { Seller: { in: $wallets } } } } ] Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: "" } } } } } ) { Block { Time } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmountInUSD Price PriceInUSD IsOutcomeBuy } Prediction { Question { Title MarketId ResolutionSource } Outcome { Index Label } } } Transaction { From Hash } } } } ``` **Variables:** ```json { "wallets": [ "0x87a961f161681cc1e9b3af2b6542b95ef3c4bd70", "0x0bab932893a7efc76d8e0951366ba933ba9fd3be" ] } ``` --- ## Polymarket-Only Filter To restrict results to **Polymarket** only, add this to the relevant `where` clause: **PredictionManagements:** ```graphql Management: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } # ... other filters } ``` **PredictionTrades:** ```graphql Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } # ... other filters } ``` --- ## Related APIs | Need | API | | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | **Market lifecycle (creation, resolution)** | [Prediction Managements API](/docs/examples/prediction-market/prediction-managements-api/) | | **Trades, volume, prices** | [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/) | | **Filter by slug, condition ID, token** | [Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api/) | | **Polymarket overview** | [Polymarket API](/docs/examples/polymarket-api/) | | **Settlements & redemptions** | [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) | | **User & wallet activity** | [Polymarket Wallet & User Activity API](/docs/examples/polymarket-api/polymarket-wallet-api/) | | **Trader realized PnL & win rate** | [Realized PnL & Win Rate for Polymarket Trader](/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/) | | **Real-time: GraphQL subscriptions** | [GraphQL subscriptions & WebSockets](/docs/subscriptions/websockets/) | | **Real-time: Kafka streams** | [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) | --- ## Support - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket Tg Alerts Bot URL: https://docs.bitquery.io/docs/usecases/polymarket-tg-alerts-bot/ Build Polymarket Tg Alerts Bot: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # How to Build a Polymarket Whale Alerts Telegram Bot with the Bitquery API Build a production-ready **Polymarket Telegram bot** that streams realtime trades and lets users set custom alerts on trade size, share price, trader wallet, or specific market. It is all powered by the **[Bitquery Prediction Market API](/docs/examples/prediction-market/prediction-market-api/)**. By the end of this guide you'll have a multi-user Telegram bot that subscribes to every Polymarket trade on Polygon over a single GraphQL WebSocket, filters trades against per-user alert rules, and pushes Telegram notifications with links to Polymarket, PolygonScan, and the trader's profile. ## Video Walkthrough Add PolyBit on Telegram > **[Source code](https://github.com/Akshat-cs/PolyBit-Polymarket-Alerts-Telegram-Bot)** > **Stack:** Python 3.11+ · `python-telegram-bot v21` · `gql` (Bitquery GraphQL) · `httpx` > **Time to complete tutorial:** ~30 minutes > **Storage:** Flat JSON files (no database) ## What you'll learn - How to subscribe to **realtime Polymarket trades** with a Bitquery GraphQL subscription - How to query **top markets**, **search markets**, and **current outcome prices** over Bitquery's HTTP endpoint - How to match streamed trades against user-defined alert filters with a per-alert cooldown - How to ship a multi-user Telegram bot with persistent state (no DB required) - How to deploy the bot with persistent storage so user alerts survive redeploys ## Why use Bitquery for Polymarket data Polymarket runs on Polygon and uses Gnosis CTF contracts under the hood. To build any data-driven product on top of it you need to either run your own Polygon archive node, index trades from the Conditional Tokens Framework (CTF), and resolve market metadata yourself, or reach for a hosted indexer. The Bitquery Prediction Market API solves all three concerns through a single GraphQL endpoint: - **Realtime + historical in one place.** The same schema is exposed over WebSocket subscriptions and HTTP queries, you don't stitch a streaming SDK to a separate query SDK. - **Decoded trades, not logs.** `PredictionTrades` already exposes `Buyer`, `Seller`, `CollateralAmountInUSD`, `Price`, `IsOutcomeBuy`, `Outcome.Label`: no custom CTF decoding needed. - **Market metadata included.** `Question.Title`, `Question.Image`, `Question.MarketId`, `ConditionId`, `OutcomeToken.AssetId` come back on the same trade row, so a single subscription is enough to render rich notifications. - **Aggregations server-side.** `volume_usd`, `trade_count`, `unique_buyers` are computed inside the query, so "top markets last 1h" is a single round-trip, no client-side reduce. If you're building anything that needs Polymarket whale alerts, leaderboards, market analytics, dashboards, or notifications, this is the fastest path from "I have an API key" to "I'm shipping product." ## Prerequisites Before you start you'll need: 1. **Python 3.11+** installed (`python3 --version`). 2. **A Bitquery API token.** Sign up at [account.bitquery.io](https://account.bitquery.io) and generate an API v2 access token at [account.bitquery.io/user/api_v2/access_tokens](https://account.bitquery.io/user/api_v2/access_tokens). The free tier is plenty to follow this guide. 3. **A Telegram account** plus a bot token. Open Telegram, message [@BotFather](https://t.me/BotFather), send `/newbot`, follow the prompts, and copy the `123456:ABC…` token it returns. 4. **(Optional)** A Render or VPS account if you want to deploy the bot publicly. We cover Render at the end. Keep both tokens private because they grant API access on your behalf. ## Architecture overview PolyBit runs three concurrent tasks on a single asyncio event loop: ``` ┌─────────────────────────────────────────────┐ Bitquery WS ──► │ BitqueryStreamer ──► match_trade() │ (every │ ▲ │ Polymarket │ │ (Alert filters) │ trade) │ ┌───────┴───────┐ │ │ │ AlertStore │ │ │ │ UserStore │ │ Telegram <──── ─┤ TelegramSender │ (JSON files) │ │ (notifications) │ ▲ └───────┬───────┘ │ │ │ │ │ Telegram ────► ─┤ python-telegram-bot ◄───┘ │ (commands, │ Application (handlers) │ callbacks) └─────────────────────────────────────────────┘ ``` - `BitqueryStreamer` opens a single WebSocket subscription to `wss://streaming.bitquery.io/graphql` and dispatches each `TradeEvent` to registered handlers. - `match_trade()` runs the trade against every active alert and returns matches. - `TelegramSender` drains an outbound queue with per-chat throttling so Telegram's rate limits never bite. - **`AlertStore` / `UserStore`** persist users and alerts to JSON files atomically (tmp file + `os.replace`) under an `asyncio.Lock`. That's the whole system. Let's build it. ## Step 1: Project setup Clone the reference repo and install dependencies: ```bash git clone https://github.com/Akshat-cs/PolyBit-Polymarket-Alerts-Telegram-Bot.git cd PolyBit-Polymarket-Alerts-Telegram-Bot python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` `requirements.txt` is intentionally small: ``` gql[websockets]>=3.5.0 websockets>=12.0 python-dotenv>=1.0.0 httpx>=0.27.0 python-telegram-bot[ext]>=21.0 ``` Copy the env template and fill in your tokens: ```bash cp .env.example .env ``` ```bash # .env BITQUERY_TOKEN=ory_at_xxxxxxxx... TELEGRAM_BOT_TOKEN=123456:ABC... POLYBIT_LOG_LEVEL=INFO # POLYBIT_DATA_DIR=/var/data # only on a deployed instance ``` ## Step 2: Stream realtime Polymarket trades from Bitquery The core of any Polymarket alerts product is a single GraphQL subscription. We listen for every successful Polymarket trade on Polygon and request exactly the fields we need to filter, render, and link out from a notification: ```graphql subscription PolymarketTradesStream { EVM(network: matic) { PredictionTrades( where: { TransactionStatus: { Success: true } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Block { Time } Transaction { Hash From } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD Price PriceInUSD IsOutcomeBuy } Prediction { ConditionId Question { Id Title MarketId Image CreatedAt } Outcome { Label Index } OutcomeToken { AssetId } } } } } } ``` Two important field-level details for prediction markets: - `CollateralAmountInUSD` is the trade size in USDC equivalent. This is what you compare against a "min trade USD" alert filter, not the raw outcome-token `Amount`. - `IsOutcomeBuy` is the trade direction: - `true`: Seller (maker) gives USDC, Buyer (taker) gives outcome tokens. The position is being closed. - `false`: Buyer gives USDC, Seller gives outcome tokens. New exposure is being opened. PolyBit normalizes "buyer" to "whoever received outcome tokens" and surfaces both addresses in notifications. ### Connecting over WebSocket Bitquery's WebSocket endpoint expects the API token as a query parameter and the `graphql-ws` subprotocol header: ```python # polybit/bitquery.py (excerpt) from gql import gql from gql.transport.websockets import WebsocketsTransport from urllib.parse import quote BITQUERY_WS_URL = "wss://streaming.bitquery.io/graphql" def ws_url(token: str) -> str: return f"{BITQUERY_WS_URL}?token={quote(token, safe='')}" class BitqueryStreamer: def __init__(self, token: str) -> None: self._token = token self._handlers = [] def add_handler(self, fn) -> None: self._handlers.append(fn) async def run(self) -> None: transport = WebsocketsTransport( url=ws_url(self._token), headers={"Sec-WebSocket-Protocol": "graphql-ws"}, ) await transport.connect() async for result in transport.subscribe(gql(TRADES_SUBSCRIPTION)): if result.errors: continue for row in (result.data or {}).get("EVM", {}).get("PredictionTrades") or []: event = TradeEvent.from_raw(row) for handler in self._handlers: await handler(event) ``` The full implementation in `polybit/bitquery.py` adds exponential-backoff reconnection and graceful shutdown, but this is the entire happy path. One subscription, one handler chain, all Polymarket trades. ## Step 3: Query top markets over HTTP For browse/search features you don't want to filter the firehose client-side. You want server-side aggregations. Bitquery's `PredictionTrades` exposes `sum`, `count`, and `count(distinct: …)` directly inside the GraphQL query, so "top markets last 1h by volume" is one request: ```graphql query TopMarketsByVolume($hours: Int!, $limit: Int!) { EVM(network: matic) { PredictionTrades( limit: { count: $limit } orderBy: { descendingByField: "volume_usd" } where: { TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: $hours } } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } } ) { Trade { Prediction { ConditionId Question { Id Title MarketId Image } } } volume_usd: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) trade_count: count unique_buyers: count(distinct: Trade_OutcomeTrade_Buyer) } } } ``` Swap `orderBy` for `unique_buyers` or `trade_count` to get the other top-market views. That gives three leaderboards from the same query template. The HTTP client is a thin `httpx` wrapper that adds `Authorization: Bearer ` and POSTs to the same hostname: ```python # polybit/bitquery.py (excerpt) BITQUERY_HTTP_URL = "https://streaming.bitquery.io/graphql" class BitqueryHTTP: async def __aenter__(self): self._client = httpx.AsyncClient( base_url=BITQUERY_HTTP_URL, headers={"Authorization": f"Bearer {self._token}"}, timeout=30.0, ) return self async def _exec(self, query: str, variables: dict) -> dict: resp = await self._client.post( "", json={"query": query, "variables": variables}, ) resp.raise_for_status() body = resp.json() if "errors" in body: raise RuntimeError(body["errors"]) return body["data"] ``` ## Step 4: Fetch current prices and search markets Two more queries cover the rest of the browse experience: **Search markets by keyword**, same `PredictionTrades` aggregation with a title substring filter: ```graphql query SearchMarkets($q: String!, $limit: Int!, $hours: Int!) { EVM(network: matic) { PredictionTrades( limit: { count: $limit } orderBy: { descendingByField: "volume_usd" } where: { TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: $hours } } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } Question: { Title: { includesCaseInsensitive: $q } } } } } ) { ...same shape as TopMarketsByVolume } } } ``` **Current outcome prices for a single market**, uses `limitBy` to take the latest trade per outcome token: ```graphql query CurrentPricesForMarket($marketId: String!) { EVM(network: matic) { PredictionTrades( limitBy: { by: Trade_Prediction_OutcomeToken_AssetId, count: 1 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Prediction: { Question: { MarketId: { is: $marketId } } } } } ) { Block { Time } Trade { OutcomeTrade { Price(maximum: Block_Time) PriceInUSD(maximum: Block_Time) } Prediction { ConditionId Question { Id Title Image MarketId } Outcome { Label Index } OutcomeToken { AssetId } } } } } } ``` `limitBy: { by: …, count: 1 }` returns one row per `AssetId`, and `maximum: Block_Time` picks the most recent price per outcome, the same trick you'd use to render a market's current "Yes / No" prices. ## Step 5: Match streamed trades against user alerts PolyBit's alert model is a single dataclass with seven optional filters. Any field that's `None` is treated as a wildcard: ```python # polybit/store.py (excerpt) @dataclass class Alert: id: str chat_id: str market_key: str | None = None # Polymarket MarketId market_title: str | None = None outcome: str | None = None # e.g. "Yes" / "Up" min_trade_amount_usd: float | None = None max_trade_amount_usd: float | None = None min_price_usd: float | None = None max_price_usd: float | None = None trader: str | None = None # 0x... wallet last_triggered_at: float | None = None paused: bool = False ``` The matcher is straightforward: every set filter must pass, with a per-alert cooldown so a hot market can't spam the user. ```python # polybit/matcher.py (excerpt) def match_trade(event, alerts, *, cooldown_seconds=60): now = time.time() matches = [] for a in alerts: if a.paused or not a.has_any_filter(): continue if a.last_triggered_at and now - a.last_triggered_at < cooldown_seconds: continue if a.market_key and event.market_id != a.market_key: continue if a.outcome and (event.outcome_label or "").lower() != a.outcome.lower(): continue if a.min_trade_amount_usd is not None and (event.collateral_usd or 0) < a.min_trade_amount_usd: continue if a.max_trade_amount_usd is not None and (event.collateral_usd or 0) > a.max_trade_amount_usd: continue if a.min_price_usd is not None and (event.price or 0) < a.min_price_usd: continue if a.max_price_usd is not None and (event.price or 0) > a.max_price_usd: continue if a.trader and a.trader.lower() not in (event.buyer or "", event.seller or ""): continue a.last_triggered_at = now matches.append(Match(alert=a, event=event)) return matches ``` Every active alert is just an in-memory dataclass, so running this for ~hundreds of alerts per trade is trivially fast. ## Step 6: Send notifications via Telegram Wire the streamer's handler to the Telegram sender. The handler builds a notification message per match and enqueues it; the sender drains the queue with per-chat throttling so we never trip Telegram's rate limits: ```python # polybit/main.py (excerpt) async def on_trade(event): matches = match_trade(event, list(alerts.active_alerts())) if not matches: return for m in matches: text, kb, preview = fmt.fmt_trade_notification(m, canonical_url=…) await sender.enqueue(OutboundMessage( chat_id=m.alert.chat_id, text=text, reply_markup=kb, preview_url=preview, # Polymarket S3 question image )) streamer.add_handler(on_trade) ``` Notifications include inline links to: - `https://polymarket.com/event/`: resolved via Polymarket's Gamma API (`https://gamma-api.polymarket.com/markets`) using `ConditionId` from the trade row. Falls back to a slugified title. - `https://polygonscan.com/tx/`: straight from `Transaction.Hash`. - `https://polymarket.com/profile/`: for the trader who triggered the alert (when a trader filter is set). The image preview is the question's S3 image URL (`Question.Image`) directly, with no additional rendering step. ## Step 7: Persist users and alerts to JSON For multi-user state you don't need a database. Two flat JSON files, atomic writes, and an `asyncio.Lock` will hold ~hundreds of users and alerts in well under 100 KB total: ```python # polybit/store.py (excerpt) def _atomic_write_json(path, payload): tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8") os.replace(tmp, path) # atomic on POSIX + Windows class AlertStore: def __init__(self, path): self._path = path self._lock = asyncio.Lock() self._alerts: dict[str, Alert] = {} async def add(self, alert): async with self._lock: self._alerts[alert.id] = alert self._save_unlocked() ``` `UserStore` follows the same pattern. Schema: ```json // users.json { "users": [{ "chat_id": "5057295168", "username": "alice", "joined_at": "2026-05-08T09:23:45+00:00" }] } // alerts.json { "alerts": [{ "id": "0c5c9...", "chat_id": "5057295168", "market_key": "1985666", "market_title": "Will Trump visit China by May 15?", "min_trade_amount_usd": 5000, "trader": "0xae80195bd3a761fe6b39bec9dfab9b5566fc86b0", "paused": false, "created_at": "2026-05-07T18:02:11+00:00" }] } ``` `tmp + os.replace` makes a crash mid-write impossible to corrupt the file: either the rename happened (new file in place) or it didn't (old file untouched). ## Step 8: Run it ```bash python -m polybit ``` You should see: ``` INFO PolyBit starting up: 0 user(s), 0 alert(s) INFO Bitquery WS connected INFO PolyBit is running. Press Ctrl+C to stop. ``` Open your bot in Telegram, send `/start`, and try `/topmarkets`, `/search`, `/addalert`. The first trade that matches one of your alerts will arrive as a Telegram message with full context. ## Step 9: Deploy with persistent storage Because user and alert state lives in JSON files, your hosting target needs **persistent disk** rather than a free-tier ephemeral filesystem. The reference repo ships with a Render Blueprint: ```yaml # render.yaml services: - type: worker name: polybit runtime: python plan: starter buildCommand: pip install -r requirements.txt startCommand: python -m polybit envVars: - key: BITQUERY_TOKEN sync: false - key: TELEGRAM_BOT_TOKEN sync: false - key: POLYBIT_DATA_DIR value: /var/data disk: name: polybit-data mountPath: /var/data sizeGB: 1 ``` The `POLYBIT_DATA_DIR` env var redirects writes to the mounted disk, so `/var/data/users.json` and `/var/data/alerts.json` survive every redeploy. Total cost on Render: $7.25/mo (Starter Worker + 1 GB disk). For self-hosting, the same setup works under `systemd` on any VPS. Make sure the `WorkingDirectory` points at a directory that survives reboots. See [DEPLOY.md](https://github.com/Akshat-cs/PolyBit-Polymarket-Alerts-Telegram-Bot/blob/main/DEPLOY.md) in the repo for both flows. ## Inspect users and alerts at runtime The repo includes a tiny CLI for live introspection: ```bash python -m polybit.stats ``` ``` ============================================================ PolyBit · stats snapshot Data dir: /var/data ============================================================ 👥 Users: 142 Joined last 24h: 18 Joined last 7d: 64 🔔 Alerts: 287 Active: 251 Paused: 36 Bound to a market: 198 Triggered at least once: 113 🎯 Most-targeted markets (top 5): 21× Bitcoin Up or Down — May 8, 7:40AM-7:45AM ET 18× Will Trump visit China by May 15? ... ``` Useful for product checks; safe to run while the bot is live. ## What you can build next You can build other Polymarket products from the same Bitquery queries: - **Per-trader leaderboards**: aggregate `PredictionTrades` by `Buyer` over a window for top-volume wallets. - **PnL tracking**: combine `PredictionTrades` with `PredictionSettlements` to compute realized PnL per wallet. - **Market resolution alerts**: subscribe to `PredictionSettlements` to notify users when a market they hold positions in resolves. - **Whale-watch X/Twitter feeds**: same trade stream, different output channel. - **Custom dashboards**: the same aggregations power Grafana / Metabase / your own React app. All of these reuse the same GraphQL endpoint, same auth, same field shapes. ## Resources - [Bitquery Prediction Market API docs](/docs/examples/prediction-market/prediction-market-api/) - [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/) - [Prediction Managements API](/docs/examples/prediction-market/prediction-managements-api/) - [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) - [Source code](https://github.com/Akshat-cs/PolyBit-Polymarket-Alerts-Telegram-Bot) - [Live demo, @PolyBit_Polymarket_Bot](https://t.me/PolyBit_Polymarket_Bot) - [Get a Bitquery token](https://account.bitquery.io) ## Conclusion A multi-user **Polymarket Telegram alerts bot** is one GraphQL subscription, a small filter loop, and a Telegram client away. Bitquery handles the chain-level work (decoded trades, market metadata, server-side aggregations), so you can spend your time on product, not on indexing. Get a free Bitquery token at [account.bitquery.io](https://account.bitquery.io), point it at the Prediction Market API, and start shipping. --- ## Polymarket Wallet & User Activity API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-wallet-api/ Polymarket wallet activity: check whether an address ever interacted with Polymarket and list a wallet's recent trading activity. # Wallet & User Activity API Get **user- and wallet-level data** for Polymarket: recent activity, positions, trade volume, and market counts. Use Bitquery GraphQL to analyze trader behavior by wallet address, and combine with the [Polymarket API](/docs/examples/polymarket-api/) overview for trades and market data. ## Check if an address ever interacted with Polymarket (on-chain transfers) Polymarket collateral on Polygon flows through conditional tokens keyed to USDC denomination at `0x4d97DCd97eC945f40cF65F87097ACe5EA0476045`. To see whether a wallet likely has **any** Polymarket-related receipts, query for **at least one inbound transfer** of that token (`limit: { count: 1 }`). Empty results mean no indexed match. That is not a guarantee that the wallet never traded (e.g. only outbound paths), but useful for onboarding and tagging. The same pattern is documented under [Polygon (MATIC) Transfers](/docs/blockchain/Matic/matic-transfers/). **Try it:** [IDE: Polymarket interaction check](https://ide.bitquery.io/check-if-an-address-interacted-with-polymarket-ever) ```graphql query ($address: String) { EVM(dataset: combined, network: matic) { Transfers( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Transfer: { Currency: { SmartContract: { is: "0x4d97DCd97eC945f40cF65F87097ACe5EA0476045" } } Receiver: { is: $address } } } ) { Block { Time Number } Transaction { Hash } Transfer { Sender Receiver Amount } } } } ``` **Variables:** ```json { "address": "0x0c79f21ec570f5cc0d52d1bc640845faef430ad2" } ``` ## Recent user activity by wallet Get aggregate stats for a trader over the last 5 hours: total outcomes traded, collateral amounts, and number of distinct markets. [Run query in IDE](https://ide.bitquery.io/Get-recent-user-activity-on-polymarket) ```graphql query MyQuery($trader: String) { EVM(network: matic) { PredictionTrades( where: { TransactionStatus: { Success: true } any: [ { Trade: { OutcomeTrade: { Buyer: { is: $trader } } } } { Trade: { OutcomeTrade: { Seller: { is: $trader } } } } ] Block: { Time: { since_relative: { hours_ago: 5 } } } } ) { Total_Outcomes_traded: count Total_Outcome_Amount: sum(of: Trade_OutcomeTrade_Amount) Total_Collateral_Amount: sum(of: Trade_OutcomeTrade_CollateralAmount) Total_Markets: count(distinct: Trade_Prediction_Question_MarketId) } } } ``` **Variables:** ```json { "trader": "0x101f2f96db1e39a9f36a1fa067751d541fd38e1a" } ``` Replace `trader` with any Polygon wallet address (EOA or proxy wallet). --- ## What you can get by wallet | Data | Source | Notes | | ----------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------ | | **Recent activity & volume** | Bitquery (above) | GraphQL `PredictionTrades` filtered by Buyer/Seller | | **Closed positions** | Polymarket CLOB | Profile API | | **User activity timeline** | Polymarket CLOB | Profile API | | **Total value of positions** | Polymarket CLOB | Profile API | | **Trades for a user or market** | Polymarket CLOB | Profile API | | **Positions for a specific market** | Polymarket CLOB | Profile API | | **Public profile by wallet** | Polymarket Gamma API | `GET /public-profile?address=` (no auth) | | **Deposits & withdrawals** | Polymarket Bridge API | Supported assets, deposit/withdrawal addresses, transaction status | --- ## Related APIs | Need | API | | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Trades, prices, volume** | [Polymarket API](/docs/examples/polymarket-api/) · [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/) | | **Filter by market slug, condition ID, token** | [Polymarket Markets API](/docs/examples/polymarket-api/polymarket-markets-api/) | | **Settlements & redemptions** | [Prediction Settlements API](/docs/examples/prediction-market/prediction-settlements-api/) | | **Market lifecycle & resolution** | [Prediction Market API](/docs/examples/prediction-market/prediction-market-api/) | | **On-chain contracts & events** | Main Polymarket Contract (on-chain) | --- ## Support - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket Wallet Realized PnL & Win Rate (Pattern) URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-wallet-realized-pnl/ Polymarket trader PnL: get a wallet's buys and sells, aggregate them by condition ID, then calculate realized profit and loss and win rate step by step. # Realized PnL & Win Rate for Polymarket Trader You can use Bitquery `PredictionTrades` on Polygon (`network: matic`) to pull a wallet’s **outcome buys** and **outcome sells** on Polymarket over a chosen window (for example the last **24 hours**). From that response, you can aggregate by `ConditionId`, calculate `realised PnL` per condition, and derive the total **realized PnL** and **win rate** for Polymarket trading. ## How is PnL and Win Rate calculated? - **Buys** (`IsOutcomeBuy: true`): collateral spent acquiring outcome tokens (tracked as `CollateralAmountInUSD` on the trade). - **Sells** (`IsOutcomeBuy: false`): collateral received when selling outcome tokens. For each **condition** (`Trade.Prediction.ConditionId`), treat **realized PnL in the window** as: ```js Realised PnL per condition = total(sell collateral USD) − total(buy collateral USD) Realised PnL = sum(Realised PnL per condition) ``` **Win rate**: Percentage of profitable trades in the given time window. Many algorithmic traders use this metric for rating the performance of their systems instead of using PnL as a judge for success. ```js Win Rate = 100* count(profitable trade)/count(trades) ``` ## Get Buys and Sells for a Trader on Polymarket [This query](https://ide.bitquery.io/buys-and-sells-of-a-wallet-on-polymarket) below uses variables for **hours ago** and the **buyer** wallet. It returns two lists: `buys` and `sells`, each with `CollateralAmountInUSD` and `ConditionId` so you can group and calculate at your system. ```graphql query WalletTrades($hoursAgo: Int!, $buyer: String!) { EVM(dataset: realtime, network: matic) { buys: PredictionTrades( where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } OutcomeTrade: { IsOutcomeBuy: true, Buyer: { is: $buyer } } } Block: { Time: { since_relative: { hours_ago: $hoursAgo } } } } ) { Trade { OutcomeTrade { CollateralAmountInUSD } Prediction { ConditionId } } } sells: PredictionTrades( where: { Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } OutcomeTrade: { IsOutcomeBuy: false, Buyer: { is: $buyer } } } Block: { Time: { since_relative: { hours_ago: $hoursAgo } } } } ) { Trade { OutcomeTrade { CollateralAmountInUSD } Prediction { ConditionId } } } } } ``` Variables: ```json { "hoursAgo": 24, "buyer": "Wallet Address" } ``` ## Aggregate by Condition ID After you receive `buys` and `sells`, aggregate `CollateralAmountInUSD` by `ConditionId` for each list. ```text INITIALIZE empty map buyUsdByCondition INITIALIZE empty map sellUsdByCondition FOR each record IN response.buys: id = record.Trade.Prediction.ConditionId amount = record.Trade.OutcomeTrade.CollateralAmountInUSD // parse as decimal number buyUsdByCondition[id] = buyUsdByCondition[id] + amount FOR each record IN response.sells: id = record.Trade.Prediction.ConditionId amount = record.Trade.OutcomeTrade.CollateralAmountInUSD sellUsdByCondition[id] = sellUsdByCondition[id] + amount ``` ## Realised PnL calculation Use the union of all **condition IDs** that appear in either `buyUsdByCondition` or `sellUsdByCondition`, so conditions with only buys or only sells are still included. For each condition, **realised PnL in the window** is **sell collateral USD minus buy collateral USD**; **total realised PnL** is the sum of those values across all conditions. ```text INITIALIZE totalRealizedPnL = 0 INITIALIZE empty map pnlByCondition allConditionIds = union(keys(buyUsdByCondition), keys(sellUsdByCondition)) FOR each conditionId IN allConditionIds: buyTotal = buyUsdByCondition[conditionId] OR 0 sellTotal = sellUsdByCondition[conditionId] OR 0 pnlForCondition = sellTotal - buyTotal pnlByCondition[conditionId] = pnlForCondition totalRealizedPnL = totalRealizedPnL + pnlForCondition ``` **Summary** - `pnlByCondition`: `Per-ConditionId` net USD collateral flow for a given time window. - `totalRealizedPnL`: wallet-level sum of `pnlForCondition` over every condition in `allConditionIds`. ## Win rate calculation Using the same `pnlByCondition` map from the previous step, count how many conditions had **positive** PnL versus how many had **any** activity in the window, then derive **win rate**. ```text INITIALIZE trades = 0 INITIALIZE profitableTrades = 0 FOR each conditionId IN keys(pnlByCondition): trades = trades + 1 IF pnlByCondition[conditionId] > 0 THEN profitableTrades = profitableTrades + 1 END IF IF trades > 0 THEN winRatePercent = 100 * (profitableTrades / trades) ELSE winRatePercent = undefined // or 0, depending on product rules END IF ``` **Interpreting win rate** - `trades`: number of distinct `ConditionId` values with at least one matching row in `buys` or `sells` in your query result. - `profitableTrades`: subset of those where `pnlByCondition[conditionId] > 0`. - `winRatePercent`: `100 * profitableTrades / trades` when `trades > 0`. ## Related APIs | Topic | Link | | ----- | ---- | | PolyMarket APIs Intro | [Polymarket API](/docs/examples/polymarket-api/) | | Advanced Polymarket Analytics | [Advanced Polymarket Metrics](/docs/examples/polymarket-api/polymarket-advanced-analytics-api/) | | Prediction trades reference | [Prediction Trades API](/docs/examples/prediction-market/prediction-trades-api/) | | Sports Related PolyMarkets | [Polymarket Sports API](/docs/examples/polymarket-api/polymarket-sports-api/) | --- ## Polymarket Whale Tracker: Follow Top Traders with Claude URL: https://docs.bitquery.io/docs/mcp/polymarket-whale-tracker/ Track Polymarket whales and top traders from a chat: rank wallets by volume, tell market makers from bettors, read a wallet's bets, profit and open positions, and see its largest fills. Read-only. # Track Polymarket Whales and Top Traders with Claude A whale tracker answers three questions. Who is trading the most? Are they betting or just making markets? And is a given trader winning? This page walks through all three with the [Bitquery MCP server](/docs/mcp/polymarket/) in Claude, ChatGPT or Cursor, using six of its 14 Polymarket tools and the address-label tool. It reads data only. It cannot place or copy a trade. What it gives you is the research step before you decide whether anyone is worth following. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` A 38-second demo, [Polymarket and Hyperliquid data in ChatGPT and Claude](https://www.youtube.com/watch?v=IwuIlcKsANk), shows the server at work in a chat. Every figure below came from the production server on 21 September 2026, between 12:22 and 12:27 UTC, with data 13 to 16 minutes behind the clock. ## Step 1: Rank traders by what they traded > *"Who were the top Polymarket traders by volume over the last 7 days?"* The agent calls `polymarket_top_traders` with a 168-hour window. | # | Address | 7-day volume | Orders | Orders that took liquidity | Outcomes traded | |---|---|---:|---:|---:|---:| | 1 | `0x2005d16a...75ea` | $24,961,757 | 91,987 | 14.8% | 11,142 | | 2 | `0xfe787d2d...0319` | $24,249,729 | 63,289 | 7.0% | 5,989 | | 3 | `0x2c335066...0563` | $21,549,928 | 7,243 | 10.3% | 551 | | 4 | `0x821dab05...cf16` | $20,905,918 | 152,003 | 79.6% | 29,675 | | 5 | `0x2a696600...d2f7` | $18,645,208 | 144,594 | 100% | 28,702 | | 6 | `0x52685279...135d` | $16,084,516 | 31,618 | 33.3% | 4,423 | | 7 | `0x224a89db...a3d5` | $14,817,566 | 17,551 | 14.6% | 917 | | 8 | `0x63cf8544...e4d0` | $12,104,594 | 303 | 11.2% | 6 | This is a volume ranking. The tool computes no profit here and says so in its first row. The two right-hand columns already sort the list into types. Seven of them placed thousands of orders across hundreds or thousands of outcomes. Number 8 reached $12.1 million with 303 orders on six. ## Step 2: Tell a market maker from a bettor > *"Give me the lifetime summary of number 1 and number 8."* `polymarket_trader_summary` returns one row per address, covering its whole recorded history. | | Number 1 | Number 8 | |---|---:|---:| | First trade | 1 September 2025 | 16 September 2026 | | Orders | 4,606,941 | 303 | | Orders resting on the book | 92.5% | 88.8% | | Markets traded | 141,322 | 6 | | Lifetime volume | $597,996,502 | $12,104,594 | Number 1 has quoted 141,322 markets since the first day of recorded history. That is the footprint of a market maker, which quotes both sides for the spread, so its trades say little about who will win. Number 8 appeared five days before this page was written, bet on six sports results in two days and stopped. That is what people mean by a whale. ## Step 3: Read what the whale bet on > *"What did 0x63cf8544631c31e9fcea0b02141dd24d01d6e4d0 bet on this week?"* `polymarket_trader_activity` breaks its orders out by market and outcome. | Market | Bought | Spent | Average price | |---|---|---:|---:| | Lions vs. Bills | Bills | $3,329,463 | 0.70 | | Will Real Betis win on 17 September? | Yes | $2,130,921 | 0.65 | | Will AC Milan win on 16 September? | Yes | $1,975,524 | 0.45 | | Will Chelsea FC win on 18 September? | Yes | $1,070,173 | 0.38 | | Will Villarreal CF win on 17 September? | Yes | $90,000 | 0.45 | | Will Real Sociedad win on 17 September? | Yes | $36,660 | 0.33 | A price is dollars per share between 0 and 1, so 0.70 means it paid as if Bills had a 70% chance. ## Step 4: Score it > *"Show its positions, open and closed, with profit and loss."* `polymarket_trader_positions` with status set to all adds how each market resolved and, where it can, the profit. | Market | Result | Profit or loss (tool) | |---|---|---:| | Real Betis | Won, sold at 0.999 | +$1,136,626 | | Villarreal | Won, sold at 0.999 | +$109,800 | | Real Sociedad | Lost, sold at 0.04 | -$32,205 | | Chelsea | Lost, still holds 2.8 million worthless shares | -$1,070,216 | | Bills | Won | not computed | | AC Milan | Lost | not computed | On the last two rows the tool leaves profit empty and explains why: the shares left the address without a trade, so no sale price exists. It reports the share count as exact and will not guess the rest. The Bills shares left at 03:46:30 UTC on 18 September. `polymarket_settlements` shows other Bills holders being paid out through a relayer contract in that same second, which fits a payout, though no record ties this address to one. The arithmetic from here is ours, not the tool's. The four scored markets sum to +$144,005. The Bills shares, 4,726,883 of them, paid $1 each against $3,329,463 spent, a gain of $1,397,421 if they were cashed at the payout, which is our assumption. The AC Milan shares paid nothing, a loss of $1,975,524. Across six markets that is about -$434,000, before $149,358 of trading fees. So the eighth-largest trader of the week won three of six bets and still lost money. Volume made it look worth following. The positions say otherwise. ## Step 5: Watch the fills > *"Show its orders in Lions vs. Bills."* `polymarket_market_trades` with the trader filter lists each order. | Time (UTC, 17 September) | Price | Size | |---|---:|---:| | 20:28:52 | 0.71 | $698,710 | | 20:28:54 | 0.69 | $56,484 | | 20:28:54 | 0.70 | $1,989,229 | | 20:28:54 | 0.70 | $356,534 | | 20:30:04 | 0.70 | $32,106 | | 21:29:45 | 0.70 | $196,399 | $3.1 million went in across four orders inside two seconds, all of them taking liquidity from the book. Drop the trader filter and set a size floor instead, and the same tool becomes a live feed of large fills for any market. To put a name on an address, pass the list to `labels_for_addresses`. For four of the addresses above it returned a label on three: two carry a Polymarket account name and number 1 is tagged only as a Polymarket proxy wallet. Number 8 has no label. ## A prompt you can reuse > *"Rank Polymarket wallets by 7-day volume. Drop any with more than 1,000 orders or more than 100 outcomes traded. For the rest, show the lifetime summary, then open and closed positions with profit and loss, and tell me which markets they hold now."* The order and outcome cut-offs are a starting point taken from the table in step 1. Tune them to the market you follow. ## What to know before you rely on it - **Read-only.** No order placement and no copy trading. To place orders use Polymarket's own CLOB API. - **Rankings are by volume.** Profit lives in `polymarket_trader_positions`, one address at a time. - **Profit is sometimes empty.** When shares arrive or leave without a trade the tool cannot price them and says so. Its own notes put this at roughly a quarter of open positions. - **Profit is before fees.** The fee total comes back as its own column. - **One wallet is not one person.** A trader can split bets across wallets, and these tools do not link them. - **A few minutes behind.** Calls on this page trailed the clock by 13 to 16 minutes. - **History starts in September 2025.** A first trade on 1 September 2025 may be older than it looks. ## Related - [Polymarket MCP server](/docs/mcp/polymarket/): all 14 tools, with odds, price history and disputes. - [Polymarket GraphQL API](/docs/examples/polymarket-api/): the same data in code, with WebSocket and Kafka streams, for a tracker that runs by itself. - [Polymarket earnings bets that beat the odds on KPMG's clients](https://bitquery.io/investigations/polymarket-insider-trading-kpmg-clients?ref=docs-mcp-polymarket-whales): a Bitquery investigation that scored a group of wallets the same way. Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-polymarket-whales#pricing). --- ## Pons Launchpad API on Robinhood Chain: PonsLaunchFactory Launches, PonsLauncherToken Trades and Graduations URL: https://docs.bitquery.io/docs/blockchain/robinhood/pons-api/ Pons launchpad API on Robinhood Chain. Track Pons V2 launches, curve trades, graduations, the launch factory and locked liquidity with Bitquery GraphQL. # Pons Launchpad API on Robinhood Chain: PonsLaunchFactory Launches, PonsLauncherToken Trades and Graduations **[Pons](https://www.ponsfamily.com/launchpad)** (Pons Family) is a **token launchpad on Robinhood Chain**. Its **V2 launch factory** gives every token a real **bonding curve** that graduates into a **Uniswap v4 pool behind a Pons-owned hook** with **permanently locked liquidity**, and it lets a creator quote a launch in **native ETH, USDG, cbBTC, or a tokenized stock or ETF** such as TSLA, NVDA or SPY. This guide shows how to track **new Pons launches**, **bonding-curve trades**, **snipe tax**, **graduations**, the **liquidity lock**, and **post-graduation prices and liquidity** with Bitquery GraphQL APIs, using the `EVM(network: robinhood)` and `Trading` cubes. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). Pons publishes protocol and integration docs at [docs.ponsfamily.com](https://docs.ponsfamily.com/docs/v2) and states that there is no Pons API: integrators are told to index the factory and the curves themselves. That is what this page does through Bitquery, so nothing here depends on Pons infrastructure. Every query runs as written in the [Bitquery IDE](https://ide.bitquery.io). Live data and the last month of `Trading` cube history are on every paid plan; history back to the first V2 launch sits on the `archive` dataset, which paid plans add through the Robinhood archive add-on and the trial does not include (see [Historical Pons data](#historical-data)). ## Video Tutorial | Pons Launchpad API on Robinhood Chain - Track Launches, Trades & Graduations ## Video Tutorial | Build a Robinhood Chain Trading Bot: Pons Launches, Curve Trades & Graduations ## Video Tutorial | How Many Pons Coins Survive a Week? 1,923 Robinhood Chain Launches, 7 Days Later ## Contracts: PonsLaunchFactory and PonsLauncherToken {#contracts} Pons has two generations of contracts on Robinhood Chain. **`PonsLaunchFactory`** is the Pons V1 factory, and **`PonsLauncherToken`** is the ERC-20 contract it deploys for every V1 launch, so each V1 token is its own `PonsLauncherToken` contract rather than a proxy of one shared implementation. The verified source of the Pons token itself (`PONS`, `0x39dbed3a2bd333467115de45665cc57f813c4571`) is also `PonsLauncherToken`. New launches go through the V2 versions, **`PonsV2LaunchFactory`** and **`PonsV2LauncherToken`**, which add the bonding curve and graduation. All four names are the verified contract names on the [Robinhood Chain Blockscout explorer](https://robinhoodchain.blockscout.com/address/0xa5aab3f0c6eeadf30ef1d3eb997108e976351feb?tab=contract). | Contract | Address | What it emits | Queried in | | --- | --- | --- | --- | | `PonsLaunchFactory` (V1 factory) | `0xa5aab3f0c6eeadf30ef1d3eb997108e976351feb` | `TokenDeployed` and `TokenLaunched` (V1 signatures, one Uniswap V3 pool per launch), plus admin events such as `LaunchConfigAdded`, `DexConfigAdded` and `LaunchFeeUpdated` | [Pons V1 topic0 values](#pons-vs-poolstrade) | | `PonsLauncherToken` (V1 token) | one contract per V1 launch, deployed by `PonsLaunchFactory`, for example `BANKERS` `0x97133372cc4391a4f6889b4d52387649b76bc7ec` | Standard ERC-20 `Transfer` and `Approval`; its trades come from its Uniswap V3 pool | [Trading cube](#trading-data-in-the-trading-cube-crypto-price-api), [Holders and supply](#holders-and-supply) | | `PonsV2LaunchFactory` (V2 factory) | `0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e` | `TokenLaunched`, `LaunchSwept`, `PoolGraduated`, `GraduationTokensPermanentlyLocked` and the creator-fee events | [Factory events](#factory-events), [Newly launched tokens](#newly-launched-tokens), [Graduation](#graduation), [Token lifecycle](#token-lifecycle-in-one-query), [Launchpad stats](#launchpad-stats) | | `PonsV2LauncherToken` (V2 token) | one contract per V2 launch, deployed by `PonsV2LaunchFactory`, for example `DECK` `0x2861f208e71ced7beab010457bf10f0c1ccc0e2d` | Standard ERC-20 `Transfer` and `Approval`; its curve trades are the `CurveBuy` / `CurveSell` events of its own bonding curve | [Bonding-curve trades](#bonding-curve-trades), [Trading cube](#trading-data-in-the-trading-cube-crypto-price-api), [Holders and supply](#holders-and-supply) | The router, meme hook, locker and the other V2 contracts are listed in the next section. ## Pons contract addresses at a glance {#pons-contract-addresses-quick} Every Pons V2 contract, in one place. Full event lists, the quote-asset table and the caveats are in [Pons contract addresses](#contract-addresses) further down. | Contract | Address | | --- | --- | | Pons V2 launch factory (`PonsV2LaunchFactory`) | `0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e` | | Pons V2 launch locker (`PonsV2LaunchLocker`) | `0x267444d099b10fb5ed7c3cc7b7c767adca574952` | | Pons V2 meme hook (`PonsV2MemeHook`) | `0xe5e702641ea86f4ae6cc3cdaed2b886f976be044` | | Pons V2 launch router (`PonsV2LaunchAndBuy`) | `0xe33e9e479df8802cb0866d5d05258bec4cf62948` | | Pons V2 graduation executor | `0xc7819b64a1daecd7ec19856d026cb14efbd89046` | | Pons V2 launch deployer | `0x3711cea4feade896c913c68f01eda97cb06d1a42` | | Pons V2 fee escrow | `0xd3afeb2a57f70ef218aa82451c51b2fb0416ac9e` | | Pons V2 buyback vault | `0x42df2a798f82289e177311362e8f5ccc45c1219c` | | Pons V2 graduation guard | `0xf5695117b99b6f6401e67d4195bd653628176c6c` | | Pons V1 factory (superseded, no longer launching) | `0xa5aab3f0c6eeadf30ef1d3eb997108e976351feb` | | Uniswap v4 PoolManager (chain-wide, **not** Pons-only) | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | Each launched token also gets **its own bonding-curve contract**, so there is no single curve address — curve trades are matched by event signature instead. The address that receives the launch mint is that token's curve; see [Newly launched tokens](#newly-launched-tokens). :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending) — new pools, trending tokens, pair lookup and token search - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) - [Pools.trade API on Robinhood](/docs/blockchain/robinhood/pools-trade-api) - [Flap.sh API on Robinhood](/docs/blockchain/robinhood/flap-sh-api) - [Robinhood Calls API](/docs/blockchain/robinhood/robinhood-calls-api) - [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api) - [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity) - [WebSocket subscriptions](/docs/subscriptions/websockets/) ::: --- ## How a Pons V2 launch works Every launch mints a **fixed 1,000,000,000 supply** straight into its own **bonding curve contract**. Traders buy and sell against that curve — not against any DEX — until the curve has taken in its **graduation threshold** of the quote asset. At that point the curve is **swept**, and the proceeds seed a **Uniswap v4 pool** whose liquidity position is **permanently locked**. | Property | Value | | --- | --- | | Network | Robinhood Chain (`network: robinhood`, chain ID **4663**) | | Launch supply | `1000000000` (1 billion, decimal-normalized), 18 decimals | | Pre-graduation venue | **Pons bonding curve**, one contract per token | | Post-graduation venue | **Uniswap v4** (`Protocol: uniswap_v4`) | | Graduation threshold | **4.2 ETH** for native-quoted launches; a per-asset amount for ERC-20 quotes — read it from `graduationThreshold` in `TokenLaunched`, set per asset by `PairTokenEconomicsUpdated` | | Curve trade fee | **100 bps** (1%) of the quote side, set by the launch config rather than a protocol constant | | Creator tax | set per launch, capped by the factory (`maxCreatorTaxBps`) | | Launch fee | **0.0005 ETH** | | Graduated pool `fee` | `0` — **all fees are taken by the hook**, not by the pool | | Graduated pool `tickSpacing` | `200` | | Graduated pool `hooks` | `0xe5e702641ea86f4ae6cc3cdaed2b886f976be044` (**PonsV2MemeHook**) | ### The supply split The curve's shape fixes exactly how much supply reaches the pool, and it is the same for every launch regardless of quote asset: | Slice | Share of supply | Where it ends up | | --- | --- | --- | | Sold on the curve | **5/7** (≈714,285,714) | Buyers | | Swept at graduation | **2/7** (≈285,714,286) | Split below | | ↳ seeds the v4 pool | **10/49** (≈204,081,633) | Locked full-range position | | ↳ permanently locked | **4/49** (≈81,632,653) | `PonsV2LaunchLocker` | ### How Pons differs from pools.trade {#pons-vs-poolstrade} Pons and [pools.trade](/docs/blockchain/robinhood/pools-trade-api) are structurally opposite, and queries do not transfer between them: | | Pons V2 | pools.trade | | --- | --- | --- | | Pre-graduation venue | Real bonding-curve contract | Uniswap v4 pool from block one | | Graduation event | **Yes** — `LaunchSwept` + `PoolGraduated` | None | | Pool `hooks` | PonsV2MemeHook | `0x000…000` | | Pool `fee` / `tickSpacing` | `0` / `200` | `2500` / `25` or `60` | | Quote assets | ETH, USDG, cbBTC, tokenized stocks and ETFs | Mostly native ETH | | Curve trades in trade cubes | **Yes**, as `pons_v2` (`Trading`, rolling ~30-day window; EVM `DEXTrades` from 2026-08-14) | N/A — all trades are pool trades | :::caution Pons V1 is a different protocol with different event signatures `PonsLaunchFactory` at `0xa5aab3f0c6eeadf30ef1d3eb997108e976351feb` is the **V1** launchpad. It has **no bonding curve** — each token gets a Uniswap V3 pool at launch — and its events carry **different signatures and different topic0 values** from V2: ```text db51ea9ad51ab453a65a4cb7e60c3cb378c9501bb002609f8f97778fb6c4235a TokenLaunched(address,address,address,address,address,uint256,uint256,uint256,uint256,uint256) 1461370115e1c2be79cb529f8cfcbd11316e789d9c6099fc83417b0b4c48c62a TokenDeployed(address,address,address,address,uint256,uint256) ``` Every query on this page targets **V2 only**. A "Pons launches" feed built from V2 alone will not include V1 launches — add the V1 factory address and its topic0s if you need both. V1 has stopped producing launches — its factory now emits only ownership-admin events. Treat it as history — query `EVM(network: robinhood, dataset: archive)` for logs from `0xa5aab3f0c6eeadf30ef1d3eb997108e976351feb` when you need V1 launches, and re-check the realtime dataset before assuming it is dead for good. V1 pools are created by Robinhood Chain's **chain-wide Uniswap V3 pool factory**, which serves every V3 protocol on the network — a `PoolCreated` event from it is **not** on its own a Pons signal. ::: --- ## Datasets {#datasets} :::danger Omitting `dataset` gives you realtime — a rolling window, not history `EVM(network: robinhood)` with no `dataset` argument queries the **realtime** dataset, which holds only a rolling window of recent blocks. This is the single most common reason a Pons query "works" but returns nothing older than a few days, and nothing in the response says which dataset served it. If you want history, say so explicitly: | Dataset | What it covers | When to use it | | --- | --- | --- | | *(omitted)* → `realtime` | Rolling recent window | Live streams, dashboards of the last few hours | | `dataset: archive` | Full history from the chain's indexing start | Backfills, per-day counts, anything dated | | `dataset: combined` | Archive merged with the realtime tail | A continuous view from launch day to now; slower | ```graphql EVM(network: robinhood, dataset: archive) { ... } EVM(network: robinhood, dataset: combined) { ... } ``` See [Dataset options](/docs/graphql/dataset/options), [archive](/docs/graphql/dataset/archive), [realtime](/docs/graphql/dataset/realtime), [combined](/docs/graphql/dataset/combined), and [data coverage and retention](/docs/graphql/data-coverage-retention). ::: **Every query on this page runs on `archive` and `combined`** — Pons V2 history reaches back to the first V2 launch — with one exception, verified: | Construct | realtime | archive | combined | | --- | --- | --- | --- | | `Topics: {includes: […]}` filter (incl. topic0) | ✅ | ✅ | ✅ | | `Call.Input` / `Call.Output`, incl. `Input: {startsWith: […]}` | ✅ | ✅ | ✅ | | `LogHeader.Address` / `LogHeader.Data`, `Log.Signature.Name` | ✅ | ✅ | ✅ | | `Transfers`, `Holders`, `DEXTrades` | ✅ | ✅ | ✅ | | `Log.Signature.SignatureHash` / `Call.Signature.SignatureHash`, filtered or selected | ✅ | ✅ | ✅ | | **`DEXPoolEvents`, `DEXPoolSlippages`, `TransactionBalances`** | ✅ | ❌ | ❌ | The `Trading` cube is a separate root that takes no `dataset` argument; it holds a rolling window of roughly the last 30 days, so the `pons_v2` rows it serves are always the most recent month, not a fixed history. :::note `SignatureHash` works on every dataset `Log.Signature.SignatureHash` and `Call.Signature.SignatureHash` work on `realtime`, `archive` and `combined`, both as a filter and in the selection set, and a `SignatureHash` filter matches the same rows as a topic0 `Topics` filter. The queries on this page use `Topics: {includes: [{Hash: {is: ""}}]}` because it is the same filter on every dataset **and** it is the only way to match an indexed argument of an undecoded event — `Signature: {SignatureHash: …}` is an equally valid choice for topic0 alone. ::: --- ## Historical Pons data and the archive add-on {#historical-data} Three windows apply to Pons data, and your plan decides which you can reach. - **Realtime** (`EVM(network: robinhood)` with no `dataset` argument): a rolling window of recent blocks. Every plan. - **`Trading` cube**: roughly the last 30 days of curve and pool trades with USD prices. Every plan. - **`archive` and `combined`**: every launch, curve trade, graduation and lock back to the first Pons V2 launch. The free trial and paid self-service plans are real-time only, and history is a per-chain add-on, listed as the Robinhood archive on the [pricing page](https://bitquery.io/pricing) and switched on from your [account](https://account.bitquery.io/). It unlocks `DEXTrades`, `DEXTradeByTokens`, `Calls` and `Events` on Robinhood Chain, which is everything on this page except the realtime-only pool cubes; a second add-on covers historical `Transfers`, `Balances` and `Holders`. If `dataset: archive` fails or returns nothing on a paid plan, check the add-on first. How plans and add-ons are billed is on [how billing works](/docs/plans/how-billing-works/). --- ## Pons contract addresses: launch factory, router, hook, locker {#contract-addresses} Pons V2 runs from a fixed set of contracts. The launch factory `0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e` emits every `TokenLaunched`, `LaunchSwept`, and `PoolGraduated`; the launch router `0xe33e9e479df8802cb0866d5d05258bec4cf62948` wraps launch-and-first-buy into one transaction; and the meme hook `0xe5e702641ea86f4ae6cc3cdaed2b886f976be044` sits on every graduated Uniswap v4 pool and is the field that tells a Pons pool apart from any other v4 pool on the network. Each launched token also gets **its own bonding-curve contract**, so curve trades are matched by event signature rather than by a single address. | Role | Address | Notes | | --- | --- | --- | | **Launch factory** (`PonsV2LaunchFactory`) | `0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e` | Emits `TokenLaunched`, `LaunchSwept`, `PoolGraduated` | | **Launch router** (`PonsV2LaunchAndBuy`) | `0xe33e9e479df8802cb0866d5d05258bec4cf62948` | `launchAndBuy()` — creates the token and executes the creator's first buy in one transaction | | **Meme hook** (`PonsV2MemeHook`) | `0xe5e702641ea86f4ae6cc3cdaed2b886f976be044` | The v4 hook on every graduated pool; emits `PoolRegistered` and `HookFeeCollected` | | **Launch locker** (`PonsV2LaunchLocker`) | `0x267444d099b10fb5ed7c3cc7b7c767adca574952` | Holds the locked position NFT and the locked supply | | **Graduation executor** | `0xc7819b64a1daecd7ec19856d026cb14efbd89046` | Emits `GraduationDustSwept` | | **Launch deployer** | `0x3711cea4feade896c913c68f01eda97cb06d1a42` | Listed in the Pons V2 docs contracts table | | **Fee escrow** | `0xd3afeb2a57f70ef218aa82451c51b2fb0416ac9e` | Listed in the Pons V2 docs contracts table | | **Buyback vault** | `0x42df2a798f82289e177311362e8f5ccc45c1219c` | Emits `Locked` | | **Graduation guard** | `0xf5695117b99b6f6401e67d4195bd653628176c6c` | Listed in the Pons V2 docs contracts table | | **Bonding curve** | one per token | Address is the **receiver of the launch mint** — see [Newly launched tokens](#newly-launched-tokens) | | **Uniswap v4 PoolManager** | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | Shared chain singleton — **not** Pons-only | | **Pons V1 factory** | `0xa5aab3f0c6eeadf30ef1d3eb997108e976351feb` | Separate protocol, no longer launching — see the caution above | :::caution The v4 PoolManager is not a Pons filter `0x8366a39c…` is the **Uniswap v4 singleton** for all of Robinhood Chain. Every v4 trade on the network routes through it, [pools.trade](/docs/blockchain/robinhood/pools-trade-api) included. What isolates a **graduated Pons pool** is the `hooks` field being `0xe5e70264…` — see [The graduated Uniswap v4 pool](#the-graduated-uniswap-v4-pool). ::: ### Quote (pair) assets Native ETH is the default quote asset, but the factory also approves **USDG, cbBTC, and a growing set of tokenized stocks and ETFs**, each with its own graduation threshold denominated in that asset's own decimals. The set is **owner-mutable and grows in batches** — the factory emits `PairTokenApprovalUpdated` (approve or revoke) and `PairTokenEconomicsUpdated` (threshold and decimals) whenever it changes — so treat the table as a snapshot and use the query below it for the live list: | Symbol | Address | Decimals | | --- | --- | --- | | ETH (native) | `0x0000000000000000000000000000000000000000` | 18 | | USDG | `0x5fc5360d0400a0fd4f2af552add042d716f1d168` | 6 | | cbBTC | `0xcec185eb182c47d1ba1efc84e6959e18cd620be4` | 8 | | AAPL | `0xaf3d76f1834a1d425780943c99ea8a608f8a93f9` | 18 | | AMD | `0x86923f96303d656e4aa86d9d42d1e57ad2023fdc` | 18 | | AMZN | `0x12f190a9f9d7d37a250758b26824b97ce941bf54` | 18 | | BB | `0x48e39e56acdba37b09020c0b734a613c9a2f100a` | 18 | | COIN | `0x6330d8c3178a418788df01a47479c0ce7ccf450b` | 18 | | COST | `0x4ea005168d7f09a7a0ba9d1def21a479950e44c2` | 18 | | CRCL | `0xdf0992e440dd0be65bd8439b609d6d4366bf1cb5` | 18 | | DELL | `0x941ae714ec6d8130c7b75d67160ca08f1e7d11dd` | 18 | | DJT | `0x1d11f0496982706c5e14a514d4e79f2e6bde4516` | 18 | | GLD | `0xc9a981fee1f9dec688bb123ccdecc63d0debfc4e` | 18 | | GME | `0x1b0e319c6a659f002271b69db8a7df2f911c153e` | 18 | | GOOGL | `0x2e0847e8910a9732eb3fb1bb4b70a580adad4fe3` | 18 | | HIMS | `0xccee82fe024c36fa15e1005ede3e9e4787e23d09` | 18 | | LLY | `0x8005d266423c7ea827372c9c864491e5786600ea` | 18 | | META | `0xc0d6457c16cc70d6790dd43521c899c87ce02f35` | 18 | | MSFT | `0xe93237c50d904957cf27e7b1133b510c669c2e74` | 18 | | MSTR | `0xec262a75e413fafd0df80480274532c79d42da09` | 18 | | MU | `0xff080c8ce2e5feadaca0da81314ae59d232d4afd` | 18 | | NVDA | `0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec` | 18 | | PLTR | `0x894e1ec2d74ffe5aef8dc8a9e84686accb964f2a` | 18 | | QQQ | `0xd5f3879160bc7c32ebb4dc785f8a4f505888de68` | 18 | | RBLX | `0xf0c4bf4c582cb3836e98394b1d4e7b7281101be8` | 18 | | RDDT | `0x05b37fb53a299a1b874a619e1c4c404d52c36f4c` | 18 | | SKHY | `0x84cab63bc87912e71ad199ff14a0ba45de68fef8` | 18 | | SNDK | `0xb90a19ff0af67f7779aff50a882a9cff42446400` | 18 | | SPCX | `0x4a0e65a3eccec6dbe60ae065f2e7bb85fae35eea` | 18 | | SPY | `0x117cc2133c37b721f49de2a7a74833232b3b4c0c` | 18 | | TSLA | `0x322f0929c4625ed5bad873c95208d54e1c003b2d` | 18 | | TSM | `0x58ffe4a942d3885baa22d7520691f611ef09e7aa` | 18 | | TTWO | `0x5e81213613b6b86eab4c6c50d718d34359459786` | 18 | | USO | `0xa30fa36db767ad9ed3f7a60fc79526fb4d56d344` | 18 | | WYFI | `0x9e7abd3c9139d14e4c86dce0e455aab7a0c2fb3e` | 18 | The quote asset of any launch is `pairToken`, the first word of the `TokenLaunched` payload (or the `pairToken` argument once decoded). ### Read the current approved quote assets Both admin events are decoded, so the live set is one query on the factory. Keep the latest row per `pairToken`: an `approved: false` row revokes the asset, and `graduationThreshold` is in the asset's own `decimals`. ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 200} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"}} Log: {Signature: {Name: {in: ["PairTokenApprovalUpdated", "PairTokenEconomicsUpdated"]}}} } ) { Block { Time } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` This query only sees changes made from 2026-08-14 onward: earlier approval rows predate event decoding, carry no `Signature.Name`, and are not matched by the name filter at all (see the [decoding caveat](#event-reference)). The table above already folds in that initial set, so union the two. --- ## Event reference **Most Pons V2 events are now ABI-decoded.** The factory, the router, every bonding curve, and the locker's `PositionLocked` all come back with `Log.Signature.Name` populated and `Arguments` fully readable — **including the indexed arguments**, which decoding lifts out of the topics for you. Filter and read them by name: ```graphql where: { Log: { Signature: { Name: {is: "CurveBuy"} } } } ``` Three contracts are still undecoded, and for those the topic0 + `LogHeader.Data` patterns later on this page remain the only route: | Contract | Decoded? | | --- | --- | | Factory `0x7ed598bc…` | ✅ all events | | Router `0xe33e9e47…` | ✅ `Launched` | | Bonding curves (one per token) | ✅ all events (`CurveBuy`, `CurveSell`, `SnipeTaxCharged`, …) | | Locker `0x267444d0…` | ⚠️ `PositionLocked` ✅, `TokenSupplyLocked` ❌ | | **Meme hook `0xe5e70264…`** | ❌ `PoolRegistered`, `HookFeeCollected`, `PoolFeesSwept` | | **Graduation executor `0xc7819b64…`** | ❌ `GraduationDustSwept` | :::caution Decoded names only reach back to 2026-08-14 on `archive` Decoding was applied from **2026-08-14** onward and older archive rows have not been reprocessed: on `archive`/`combined`, rows before that date carry an **empty `Signature.Name` and no `Arguments`**, so a `Signature: {Name: …}` filter silently drops all earlier history — on a window that straddles that date, the name filter on `TokenLaunched` returns fewer rows than the topic0 filter, and the gap is exactly the pre-2026-08-14 launches. For anything historical, keep filtering with `Topics: {includes: [{Hash: {is: ""}}]}` (which matches decoded and undecoded rows alike) and treat `Signature.Name` / `Arguments` as fields that may be empty on old rows. If Bitquery backfills the archive later, this caveat disappears — re-run the count comparison to check. ::: ### Factory events {#factory-events} Emitter: `0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e` | Event | Indexed | topic0 (`SignatureHash`) | | --- | --- | --- | | `TokenLaunched(address,address,address,address,uint256,uint256)` | 3 | `8d4aad4953d0ca700d468f3753aa14432d1b35b43ec6409f051fb6aa43a89607` | | `LaunchSwept(address,uint256,uint256)` | 1 | `cdb72f157fd3666758a6ce201387ffb52038c7562e4fff352828da1096c4b6b4` | | `PoolGraduated(address,uint256,uint256,uint256)` | 1 | `0a44ef75df69c534f43cd6c1aa3ef8983065fe5fe79ef9e79f6494e6f258c259` | | `GraduationTokensPermanentlyLocked(address,uint256)` | 1 | `a0a18f5bf205becee8b268d7cf69addab8548ae8ef361791464cf0e0e17c1361` | | `CreatorFeeRecipientUpdated(address,address,address)` | 3 | `308c390ed1ab5873392818e036cabdf408bc8ad042fbaead3108954ff75ba980` | | `CreatorFeeRecipientChangeProposed(address,address,address,uint256,uint256)` | 3 | `7f119e44c84a715429bee60d30ad2e14afdef6c60bb1a7eaa01290ecf6d1b2e5` | | `BuybackEnabledUpdated(address,bool,address)` | 2 | `bd886f85b7731f66269f57707414d435bf8df930d3357a10becc48a69377f6d5` | | `LaunchForceSwept(address)` *(rare)* | 1 | `52c1a28345695afc7f6b7629133124dec5d61ee745affd65e4fd2a776bc05840` | | `LaunchGraduationRescued(address,address,uint256,uint256)` *(rare)* | 2 | `7017304fdd491394686dce984eac721f0be1a22228346210f16694772bde44ca` | ### Bonding curve events {#curve-events} Emitter: one contract per token — see [Newly launched tokens](#newly-launched-tokens). | Event | Indexed | topic0 (`SignatureHash`) | | --- | --- | --- | | `CurveBuy(address,address,uint256,uint256,uint256,uint256)` | 2 | `ec36bf571f136799e8dc0b0b8bea4b04d8bd3d43de838aab0d5fc21d4cbfc455` | | `CurveSell(address,address,uint256,uint256,uint256,uint256)` | 2 | `8113d738abdcb6b38357e9d53a54a7157861a09031b453651f0fe7fe151f59df` | | `SnipeTaxCharged(address,uint256)` | 1 | `3bc39a5562b28f5fe8f36cecabfbaa12bb969acf05717994709225fc412a9934` | | `SnipeTaxExempted(address)` | 1 | `e4b7e48fbd47c2f602bacadee76ad33b16542ddb4997cfc0de04c311adcfa8c7` | | `FeesSwept(uint256,uint256,uint256)` | 0 | `9f4cd7c4ed99d08a797804560c9c5d71d2cf7e101f2e3b5e7d1ca8a24c370e4f` | | `CurveBuyRefunded(address,uint256)` | 1 | `a69e8258ccc7b9bbb70ab953fc2d1062b4ee28b8ca827534097e1732e87b0262` | | `CurveCompleted(address,uint256,uint256)` | 0 | `f8d37a90738ae063b8b8058b66f5880cf3cf7ab0c5d4fa78219696591dfbfb67` | | `Initialized(address)` | 0 | `908408e307fc569b417f6cbec5d5a06f44a0a505ac0479b47d421a4b2fd6a1e6` | | `BuybackLocked(uint256,uint256)` *(rare)* | 0 | `5feba9b0d52c92ada4b9c571c2bee52390c54f2947208ab250221e6ee32f12ff` | | `AutoGraduationFailed(address,uint256)` *(rare)* | 1 | `e2cd2f31ebc05ec28640102987f4c8fc5f20e269e1b3aa82577f3f2f0e35c7c6` | ### Meme hook events {#hook-events} Emitter: `0xe5e702641ea86f4ae6cc3cdaed2b886f976be044` | Event | Indexed | topic0 (`SignatureHash`) | | --- | --- | --- | | `PoolRegistered(bytes32,address,address,address)` | 1 | `01bf263a1db1652580721573296e1a1fa70b3d4c87f61d02a69c4e1109d2d573` | | `HookFeeCollected(bytes32,address,uint256,uint256)` | 1 | `c532c43b3423e14ef72748f1c8291238829ca0af8ba9b67975ad1483485a4b4d` | | `PoolFeesSwept(bytes32,uint256,uint256,uint256,uint256)` | 1 | `2f3c43579b9064b6f28edcf41608f3815792d274a56afe024359703cb4ea9b30` | ### Router, locker, vault, executor | Event | Emitter | Indexed | topic0 (`SignatureHash`) | | --- | --- | --- | --- | | `Launched(address,address,address,address,uint256,uint256)` | router | 3 | `dcacba5e347ae7abd91cb519eb877af8fa7774e347b85dd3ddcd24a2ba8cdf37` | | `TokenSupplyLocked(address,uint256)` | locker | 1 | `af33c4aba92959b3e7ddc83ab728938262da159a6c05ca836f6c46f9bcb2c740` | | `PositionLocked(address,uint256)` | locker | 2 | `2cabb2a2973327d5863ceb4707e9441851243897e86d587ee35943599752eb54` | | `Locked(address,address,uint256,uint256)` | buyback vault | 2 | `967ad762aa9070ada8db64577288e214771e89667066ae38e8750cb8a86c5429` | | `GraduationDustSwept(address,address,uint256)` | executor | 2 | `80a5a2ff8b8c5533e5862e4e161bbcade9af6fd9d67bef56a590b062107f027f` | Every topic0 above was verified two ways: keccak-256 preimage match against the signature from the verified contract source, and live occurrence on Robinhood Chain. Rows marked *(rare)* are admin or failure paths that exist in the ABI but fire infrequently. ### Querying a decoded event by name For any decoded event, filter on `Log.Signature.Name` and read `Arguments` directly — no `LogHeader.Data` decoding, and the indexed addresses are right there: ```graphql { EVM(network: robinhood) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"}} Log: {Signature: {Name: {is: "TokenLaunched"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Block { Time Number } Transaction { Hash From } Log { Signature { Name } } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` The 24-hour window keeps the scan small; without it the request can time out. Widen the window, or add `dataset: archive` for launch history. Each row returns `token`, `curve`, `deployer`, `pairToken`, `launchConfigId` and `graduationThreshold` as named arguments — including the three indexed addresses that used to be locked away in the topics. `graduationThreshold` is a raw integer in the quote asset's own decimals: `4200000000000000000` is 4.2 ETH, `8090000000` is 8,090 USDG. This works on `realtime`, and on `archive`/`combined` for blocks from 2026-08-14 onward — see the [caution above](#event-reference). ### Querying a raw event by topic0 For the undecoded hook, executor, and locker `TokenSupplyLocked` events — and for **any** event on archive rows older than 2026-08-14 — match the topic0 with `Topics: {includes: […]}`, scope with `LogHeader.Address` where the emitter is a fixed contract, and read `LogHeader.Data`: ```graphql { EVM(network: robinhood) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"}} Topics: {includes: [{Hash: {is: "8d4aad4953d0ca700d468f3753aa14432d1b35b43ec6409f051fb6aa43a89607"}}]} } ) { Block { Time Number } Transaction { Hash From To } LogHeader { Data } } } } ``` Topic0 values work with or without the `0x` prefix. `Log: {Signature: {SignatureHash: {is: "…"}}}` is an equivalent filter and, like `Topics`, works on every dataset — see [Datasets](#datasets). :::caution Scope curve and hook events to an emitter where you can Bonding curves are one contract per token, so a topic0-only filter on `CurveBuy` is the right scope — it captures every curve on the network at once, and `LogHeader.Address` tells you which one. For fixed-emitter events, **always add `LogHeader.Address`**. A signature such as `PoolRegistered(bytes32,address,address,address)` is generic enough that unrelated contracts on the chain emit the same topic0 with a *different* indexing layout — same hash, incompatible payload. Filtering topic0 alone will mix them into your results. ::: ### Filtering by an indexed argument On decoded events, indexed arguments are ordinary named arguments — filter them with `Arguments: {includes: …}`: ```graphql Arguments: {includes: { Name: {is: "token"} Value: {Address: {is: "0x11ff6356504e85e792c385b3381f273a4b764cfe"}} }} ``` On undecoded events (the hook and executor) and on pre-2026-08-14 archive rows, the `Topics` filter is the fallback: `Topics: {includes: [{Hash: {is: "…"}}]}` matches any topic in the log, including topic0 and any indexed address padded to 32 bytes: ```graphql Topics: {includes: [{Hash: {is: "0x000000000000000000000000"}}]} ``` The `0x` prefix is optional here. `includes`, `excludes`, `startsWith`, `endsWith` and `length` are all available. `Topics` is also a perfectly good topic0 filter on every dataset, which is why the queries on this page use it throughout; `Log.Signature.SignatureHash` works equally well. See [Datasets](#datasets). ### Full signatures for client-side decoding ```text # factory — 0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e 8d4aad4953d0ca700d468f3753aa14432d1b35b43ec6409f051fb6aa43a89607 TokenLaunched(address indexed token, address indexed curve, address indexed deployer, address pairToken, uint256 launchConfigId, uint256 graduationThreshold) cdb72f157fd3666758a6ce201387ffb52038c7562e4fff352828da1096c4b6b4 LaunchSwept(address indexed token, uint256 quoteOut, uint256 tokenOut) 0a44ef75df69c534f43cd6c1aa3ef8983065fe5fe79ef9e79f6494e6f258c259 PoolGraduated(address indexed token, uint256 positionId, uint256 tokenAmount, uint256 pairTokenAmount) a0a18f5bf205becee8b268d7cf69addab8548ae8ef361791464cf0e0e17c1361 GraduationTokensPermanentlyLocked(address indexed token, uint256 amount) # bonding curve — one per token ec36bf571f136799e8dc0b0b8bea4b04d8bd3d43de838aab0d5fc21d4cbfc455 CurveBuy(address indexed buyer, address indexed recipient, uint256 quoteIn, uint256 tokensOut, uint256 fee, uint256 tax) 8113d738abdcb6b38357e9d53a54a7157861a09031b453651f0fe7fe151f59df CurveSell(address indexed seller, address indexed recipient, uint256 tokensIn, uint256 quoteOut, uint256 fee, uint256 tax) 3bc39a5562b28f5fe8f36cecabfbaa12bb969acf05717994709225fc412a9934 SnipeTaxCharged(address indexed recipient, uint256 amount) f8d37a90738ae063b8b8058b66f5880cf3cf7ab0c5d4fa78219696591dfbfb67 CurveCompleted(address recipient, uint256 quoteOut, uint256 tokenOut) # meme hook — 0xe5e702641ea86f4ae6cc3cdaed2b886f976be044 01bf263a1db1652580721573296e1a1fa70b3d4c87f61d02a69c4e1109d2d573 PoolRegistered(PoolId indexed poolId, address memecoin, address quoteToken, address creator) c532c43b3423e14ef72748f1c8291238829ca0af8ba9b67975ad1483485a4b4d HookFeeCollected(PoolId indexed poolId, address currency, uint256 feeAmount, uint256 taxAmount) # router — 0xe33e9e479df8802cb0866d5d05258bec4cf62948 dcacba5e347ae7abd91cb519eb877af8fa7774e347b85dd3ddcd24a2ba8cdf37 Launched(address indexed token, address indexed curve, address indexed deployer, address pairToken, uint256 launchConfigId, uint256 graduationThreshold) ``` --- ## Newly launched tokens The simplest launch feed is now the decoded `TokenLaunched` event itself — the [name-filtered query above](#querying-a-decoded-event-by-name) returns `token`, `curve`, `deployer`, `pairToken` and `graduationThreshold` as named arguments on every launch. Stream it as a subscription and you have a live launch tape with zero decoding. The **`Calls` cube is still worth knowing**, for two reasons: it is the only on-chain source of the launch **metadata** (name, symbol, image, socials — see [Token metadata](#token-metadata)), and its archive keeps about the last 3 months, whereas decoded event names only reach back to 2026-08-14. `Call.Output` holds the function's return data, and every Pons launch entry point returns the addresses you need: | Selector (`Call.Input` prefix) | Function | `Call.Output` | | --- | --- | --- | | `f85f8e41` | `launchAndBuy(...)` on the router | `(address token, address curve, uint256 tokensOut)` | | `f35abbcf` | `launchToken(params, launchConfigId, pairToken)` | `(address token, address curve)` | | `a72101af` | `launchToken(params, launchConfigId, pairToken, snipeTaxExemptions)` | `(address token, address curve)` | | `d6a0eef5` | `launchTokenFor(...)` — what the router calls internally | `(address token, address curve)` | `Input: {startsWith: […]}` accepts a list, and the `0x` prefix on each selector is optional. `Call: {Signature: {SignatureHash: {is: "a72101af"}}}` is an equivalent single-selector filter and also runs on `archive`. ### The complete launch feed ```graphql { EVM(network: robinhood, dataset: combined) { Calls( limit: {count: 20} orderBy: {descending: Block_Time} where: { Call: { To: {in: [ "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e", "0xe33e9e479df8802cb0866d5d05258bec4cf62948" ]} Input: {startsWith: ["0xf35abbcf", "0xa72101af", "0xf85f8e41"]} Success: true } } ) { Block { Time Number } Transaction { Hash From } Call { To Value Input Output } } } } ``` ▶️ Runnable IDE examples: [launches per day](https://ide.bitquery.io/pons-launches-per-day), [launch events for one token](https://ide.bitquery.io/pons-launch-events-by-token) `Transaction.From` is the creator. `Call.Value` is the ETH attached (launch fee plus, on `launchAndBuy`, the creator's first buy). Take the first two 32-byte words of `Call.Output` for the token and the curve: ```js const o = call.Output.replace(/^0x/, ''); const token = '0x' + o.slice(24, 64); const curve = '0x' + o.slice(88, 128); ``` :::caution Bound this query, or it times out on realtime The `Input: {startsWith: […]}` scan is the expensive part. Run unbounded against the default realtime dataset, this exact query hits the gateway timeout (`context deadline exceeded`) rather than returning slowly. Either keep `dataset: combined` (or `archive`) as above, which returns promptly and covers full history, or stay on realtime and add a time bound such as `Block: {Time: {since_relative: {hours_ago: 1}}}`. The subscription form below is unaffected — it only sees new blocks. ::: :::caution Never match `launchTokenFor` and `launchAndBuy` together `launchAndBuy` on the router calls `launchTokenFor` on the factory internally, so a filter matching both selectors returns **two rows for the same launch** — one for the router's outer call, one for the factory's inner call. Including `d6a0eef5` alongside `f85f8e41` double-counts every router launch; the three-selector filter above counts each launch once. That is why `d6a0eef5` is absent from the query. Router launches are attributed to the router call, which is also where `Transaction.From` is the real creator. If you do need `launchTokenFor` — to catch a launch routed through some other contract — add it and deduplicate on `Transaction.Hash`. ::: ### Stream new launches in real time ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { To: {in: [ "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e", "0xe33e9e479df8802cb0866d5d05258bec4cf62948" ]} Input: {startsWith: ["0xf35abbcf", "0xa72101af", "0xf85f8e41"]} Success: true } } ) { Block { Time } Transaction { Hash From } Call { To Value Input Output } } } } ``` ▶️ [Stream new Pons launches - Run in IDE](https://ide.bitquery.io/pons-new-launches-stream) ### Token metadata: name, symbol, image, description, socials {#token-metadata} Pons puts **all** launch metadata in the call arguments rather than in an event, so `Call.Input` is the only on-chain source for the description, the IPFS image and the social links. The struct is: ```solidity struct LaunchParams { string name; string symbol; string logo; // ipfs:// URI string description; Socials socials; // (twitter, telegram, discord, website, farcaster) address creatorFeeRecipient; uint16 creatorTaxBps; bool buybackEnabled; bytes32 expectedEconomics; bytes32 salt; } ``` ABI-decoding `Call.Input` from the launch feed above yields, for example: ```text token 0x6a3b0c271d335450365297cdd10a24dc8364bf63 curve 0x9314af455ff11d02b5f87317fed8ddc9d6b17bb9 name TickerYard symbol YARD logo ipfs://bafkreifqznqij7bgl7glhavtsg44ra2lf2axifmoc6r7sgwacssmlkmdzm description Route markets. Open verifiable protocol work. twitter https://x.com/TickerYardHQ creatorFeeRecipient 0x84adad3ed94495c978e834bcef1e5a7f533cf981 creatorTaxBps 100 ``` For `launchAndBuy` the outer arguments after the struct are `launchConfigId`, `pairToken`, `quoteIn`, `minTokensOut`, `recipient` and `snipeTaxExemptions[]` — `quoteIn` is the size of the creator's own first buy, which is a useful signal on its own. ### Full history: the launch mint on `archive` {#launch-mint-archive} The `Calls` feed above already runs on `combined`, and `archive` works the same way. But the **launch mint transfer** is a second, independent route to the same list, and it is often the more convenient one: it carries name, symbol and decimals directly from `Currency`, and the mint's `Receiver` **is the bonding curve**. Use it when you want token metadata without decoding calldata, or as a cross-check on the call feed. ```graphql { EVM(network: robinhood, dataset: archive) { Transfers( limit: {count: 25} orderBy: {descending: Block_Time} where: { Transfer: { Sender: {is: "0x0000000000000000000000000000000000000000"} Amount: {eq: "1000000000"} } Transaction: {To: {in: [ "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e", "0xe33e9e479df8802cb0866d5d05258bec4cf62948" ]}} } ) { Block { Time Number } Transaction { Hash From To } Transfer { Amount Receiver Currency { Name Symbol Decimals SmartContract } } } } } ``` `Transfer.Currency.SmartContract` is the token, `Transfer.Receiver` is its curve, `Transaction.From` is the creator, and `Block.Time` is the launch time. :::caution `Transaction.To` misses indirect launches This pattern only catches launches where the factory or router is the transaction target. A small share of launches route through third-party contracts or arrive inside contract-creation transactions and carry a different `Transaction.To`. The [`Calls` feed](#the-complete-launch-feed) matches on `Call.To`, so it catches those too — and it runs on `archive` as well. Treat the call feed as the source of truth, and this one as the convenient metadata-carrying view. ::: ### Most active token creators ```graphql { EVM(network: robinhood, dataset: archive) { Transfers( limit: {count: 25} orderBy: {descendingByField: "launches"} where: { Transfer: { Sender: {is: "0x0000000000000000000000000000000000000000"} Amount: {eq: "1000000000"} } Transaction: {To: {in: [ "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e", "0xe33e9e479df8802cb0866d5d05258bec4cf62948" ]}} Block: {Time: {since_relative: {days_ago: 7}}} } ) { Transaction { From } launches: count } } } ``` --- ## Bonding-curve trades **Curve trades are now indexed as trades** under their own protocol label — `Protocol: "pons_v2"`, `ProtocolFamily: "Pons"` — and the best place to read them is the **`Trading` cube (Crypto Price API)**: one row per trade with `Side`, `Trader`, and **fully populated `PriceInUsd` / `AmountsInUsd`**, plus [OHLCV candles](#ohlcv-price-candles) that work from the token's very first curve trade. `Trading` holds a rolling ~30-day window (the EVM `DEXTrades` / `DEXTradeByTokens` cubes start 2026-08-14); for anything earlier, the curve's `CurveBuy` / `CurveSell` events remain the only source. ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: { Pair: {Market: {Protocol: {is: "pons_v2"} Network: {is: "Robinhood"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Block { Time } Side Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } TransactionHeader { Hash } Pair { Token { Address Symbol } QuoteToken { Symbol } } } } } ``` The 24-hour window keeps the request inside the cube's limits; without it the request can time out. Widen it up to the cube's rolling month as needed. Add `Pair: {Token: {Address: {is: ""}}}` to scope to one token — and because the same cube also carries the token's post-graduation `uniswap_v4` trades, dropping the protocol filter gives a token's **entire curve-to-pool trade history in one query**. On `pons_v2` rows `Pair.Pool.Address` is the token's **bonding-curve contract** (it matches `curve` in `TokenLaunched`), so every curve trade hands you the curve address for free. The same trades also appear in the EVM `DEXTrades` / `DEXTradeByTokens` cubes (`ProtocolFamily: "Pons"`, curve contract as `Trade.Dex.SmartContract`), but there `PriceInUSD` / `AmountInUSD` are populated only on the realtime dataset and read `0` on `archive` and `combined` — prefer `Trading`. The event route below is still what you want for the **fee and tax parts** (`fee`, `tax`, snipe-tax attribution), which the trade cubes do not carry, and for curve trades older than the trade-cube coverage (the `Trading` cube's rolling ~30-day window, 2026-08-14 in the EVM `DEXTrades` cubes). ### Every trade on one token's curve `CurveBuy` and `CurveSell` are decoded, so filter by name and read the arguments — buyer, seller and recipient included, which used to be unreadable indexed topics. Get the curve address from the [launch feed](#newly-launched-tokens), then filter on it as the emitter. The example curve `0x639a7cd2…` belongs to DECK (token `0x2861f208…`), which launched and graduated after 2026-08-14 so every row is decoded; `dataset: combined` keeps the query working once the curve's trades leave the realtime window: ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 50} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x639a7cd26c373db065ad009c60abd623a1983c62"}} Log: {Signature: {Name: {in: ["CurveBuy", "CurveSell"]}}} } ) { Block { Time } Transaction { Hash From } LogHeader { Address } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` ▶️ Runnable IDE examples: [curve progress for one token](https://ide.bitquery.io/pons-curve-progress), [every curve buy and sell on the network](https://ide.bitquery.io/pons-curve-trades-stream) Drop the `LogHeader.Address` filter to get **every curve trade on the network** in one feed — that is the shape you want for a launch-wide tape, and `LogHeader.Address` identifies the curve on each row. ### Reading the arguments | Argument | `CurveBuy` | `CurveSell` | | --- | --- | --- | | `buyer` / `seller` | wallet that traded | wallet that traded | | `recipient` | receiver of the tokens | receiver of the quote | | `quoteIn` / `tokensIn` | quote asset spent | tokens sold | | `tokensOut` / `quoteOut` | tokens received | quote asset received | | `fee` | base fee **plus snipe tax** | base fee | | `tax` | creator tax, paid to the creator in full | creator tax | Price is `quoteIn / tokensOut` (or `quoteOut / tokensIn` on a sell). All amounts are raw integers in their asset's own decimals: 18 for the token, and the quote asset's own for the quote side (6 for USDG). The base fee rate comes from the launch's config (`curveFeeBps`) rather than a protocol constant, so derive it from the events rather than assuming 100 bps. For pre-2026-08-14 archive rows, `Arguments` comes back empty — fall back to the topic0 filter (`ec36bf57…` / `8113d738…` from the [event reference](#curve-events)) and decode `LogHeader.Data` yourself; it carries the four non-indexed words in the order above: ```js const w = i => BigInt('0x' + data.slice(i * 64, (i + 1) * 64)); const [quoteIn, tokensOut, fee, tax] = [w(0), w(1), w(2), w(3)]; ``` ### Snipe tax Pons charges a punishing, fast-decaying tax on buys inside the launch window. The curve snapshots the factory's settings when it initializes, so a launch keeps the terms it launched under: ```text snipeTaxBps(elapsed) = snipeTaxStartBps >> ((elapsed * 14) / snipeTaxSeconds) ``` with integer division, `elapsed` in seconds since the launch transaction, and zero once `elapsed >= snipeTaxSeconds`. At the factory's current settings — `snipeTaxStartBps = 9900`, `snipeTaxSeconds = 3` — that resolves to **9900 bps in the launch second, 618 bps in the next, 19 bps in the next, then zero**. Both settings are owner-mutable; read the current values with `snipeTaxStartBps()` (`0x50e25ac2`) and `snipeTaxSeconds()` (`0x6783774b`) through the `Calls` cube, taking `Call.Output`. Because `CurveBuy.fee` bundles the base fee and the snipe tax, the snipe portion is what makes an early buy's effective rate jump far above the launch's base rate. `SnipeTaxCharged` isolates it: ```graphql { EVM(network: robinhood) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { Log: {Signature: {Name: {is: "SnipeTaxCharged"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Block { Time } Transaction { Hash From } LogHeader { Address } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` The 24-hour window keeps the scan small; without it the request can time out. Widen it, or add `dataset: archive` for history. `recipient` and `amount` come back as named arguments, `LogHeader.Address` is the curve, and `Transaction.From` is the wallet that paid it — which is to say, **the sniper**. Creators can pre-declare exempt wallets at launch; those emit `SnipeTaxExempted` in the launch transaction, so the exemption list for a launch is recoverable from its own transaction hash. ### Graduation progress There is no on-chain progress event. Sum the net quote taken in by the curve — `CurveBuy.quoteIn` minus `CurveSell.quoteOut` — and compare it against the launch's `graduationThreshold` (the third word of its `TokenLaunched` payload; **4.2 ETH** for native-quoted launches). The curve's live quote balance is the same figure, so a balance read against the curve address works as a cross-check. --- ## Token lifecycle in one query Factory events are decoded and they all name the token in a `token` argument, so one `Arguments` filter returns a per-token timeline with each event's name attached. Use `dataset: combined` so the launch is still in range after it leaves the realtime window: ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 25} orderBy: {ascending: Block_Time} where: { LogHeader: {Address: {is: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"}} Arguments: {includes: { Name: {is: "token"} Value: {Address: {is: "0x2861f208e71ced7beab010457bf10f0c1ccc0e2d"}} }} } ) { Block { Time Number } Transaction { Hash From To } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` ▶️ [Launch events for one token - Run in IDE](https://ide.bitquery.io/pons-launch-events-by-token) The `Arguments` filter only matches rows that were decoded, so **a token launched before 2026-08-14 returns zero rows here** even though its events exist. For those, the topic-padding form still earns its keep — pad the token address to 32 bytes and filter it as a topic (indexed args live in the topics whether decoded or not): ```graphql Topics: {includes: [{Hash: {is: "0x0000000000000000000000002861f208e71ced7beab010457bf10f0c1ccc0e2d"}}]} ``` Add the event's topic0 as a second `includes` entry to narrow to one event type — multiple hashes are combined with **AND**. Either way you get the full arc: ```text TokenLaunched → launch LaunchSwept → threshold hit, curve drained GraduationTokensPermanentlyLocked → 4/49 of supply locked forever PoolGraduated → v4 pool created and seeded ``` :::caution This works on the factory, not on the curve The trick only works where the token address is actually one of the log's topics. Factory events index the token, so they match. The **curve's** events do not — `CreatorFeeRecipientUpdated` indexes the two recipient addresses and `SnipeTaxExempted` indexes the exempted account, so filtering a curve address by the token topic returns **zero rows**. Query curve history by the curve's own address plus the event topic0 instead. ::: --- ## Graduation Graduation is **permissionless and two-phase**. Anyone can trigger it once the threshold is crossed, and in practice keeper bots race for it, so `Transaction.To` on the sweep is usually a third-party contract rather than Pons itself: 1. **`graduate(address)`** (`0xff6d8d05`) — sweeps curve fees, halts trading, pulls the quote and remaining supply into the factory. Emits `CurveCompleted` on the curve and `LaunchSwept` on the factory. 2. **`createGraduatedPool(address)`** (`0x2f53ef2f`) — creates the v4 pool, mints and locks the full-range position, registers the hook. Emits `GraduationTokensPermanentlyLocked`, `PoolGraduated`, `Initialize` and `ModifyLiquidity` on the PoolManager, `PoolRegistered` on the hook, and `TokenSupplyLocked` + `PositionLocked` on the locker. The two phases land in **separate transactions**, seconds to minutes apart. A token in between is `Swept` — drained but not yet tradeable anywhere. ### Enumerating graduated tokens `PoolGraduated` is decoded, so `Log: {Signature: {Name: {is: "PoolGraduated"}}}` on the factory now returns the token, position id and seeded amounts as named arguments — the quickest graduation feed for recent blocks. Two reasons to still use the hook's **`PoolRegistered`** instead: it also carries `quoteToken` and `creator`, and it works across the full archive (the hook is undecoded, so it never depended on decode coverage in the first place): ```graphql { EVM(network: robinhood) { Events( limit: {count: 50} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0xe5e702641ea86f4ae6cc3cdaed2b886f976be044"}} Topics: {includes: [{Hash: {is: "01bf263a1db1652580721573296e1a1fa70b3d4c87f61d02a69c4e1109d2d573"}}]} } ) { Block { Time Number } Transaction { Hash } LogHeader { Data } } } } ``` ▶️ [Stream graduations (PoolGraduated) - Run in IDE](https://ide.bitquery.io/pons-graduations-stream) ```js const d = log.Data; const memecoin = '0x' + d.slice(24, 64); const quoteToken = '0x' + d.slice(88, 128); // 0x000…000 for native ETH const creator = '0x' + d.slice(152, 192); ``` This is the query to run first when you want a **token set** to feed into the `Trading` cube — see [Top graduated tokens](#top-graduated-pons-tokens-by-volume). Keep the `LogHeader.Address` filter on the hook; without it this topic0 also matches an unrelated contract on the chain. ### The graduated Uniswap v4 pool The PoolManager's `Initialize` **is** decoded, so the `PoolKey` reads without manual decoding. Scope it by the **`hooks` argument** — the Pons hook is what makes a pool a Pons pool: ```graphql { EVM(network: robinhood) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Block: {Time: {since_relative: {hours_ago: 24}}} Log: {Signature: {Name: {is: "Initialize"}}} Arguments: {includes: { Name: {is: "hooks"} Value: {Address: {is: "0xe5e702641ea86f4ae6cc3cdaed2b886f976be044"}} }} } ) { Block { Time } Transaction { Hash } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` The 24-hour window keeps the scan small; without it the request can time out. Widen it, or add `dataset: archive` for history. Returns `id` (the **PoolId** you need for [liquidity and slippage](#pool-liquidity-slippage-and-balance-changes)), `currency0`, `currency1`, `fee`, `tickSpacing`, `hooks`, `sqrtPriceX96` and `tick`. Every Pons pool comes back with `fee: 0`, `tickSpacing: 200` and `hooks: 0xe5e702641ea86f4ae6cc3cdaed2b886f976be044`. ### The Pons pool of one token Anyone can initialize a Uniswap v4 pool for any token, and popular Pons tokens attract extra pools with `hooks: 0x000…000` and arbitrary `fee` / `tickSpacing`. To land on the **Pons** pool of a specific token, pass two `Arguments` conditions — the list form is combined with **AND**: ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 1} where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} Arguments: {includes: [ {Name: {is: "hooks"}, Value: {Address: {is: "0xe5e702641ea86f4ae6cc3cdaed2b886f976be044"}}}, {Name: {is: "currency1"}, Value: {Address: {is: "0x2861f208e71ced7beab010457bf10f0c1ccc0e2d"}}} ]} } ) { Block { Time } Transaction { Hash To } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` The launched token is `currency1` when the quote is native ETH (`currency0` is `0x000…000`); for an ERC-20 quote the two currencies sort by address, so check both slots. :::note Filter on the hook, not on `Transaction.To` Scoping this query with `Transaction: {To: {is: ""}}` looks equivalent and is not: graduation is [permissionless](#graduation), so a keeper contract can call `createGraduatedPool` and carry its own address in `Transaction.To`, and those graduations silently drop out of a `Transaction.To` filter. The hook is on every Pons pool regardless of who triggered it. ::: :::note Why `fee` is zero Trading fees on a graduated Pons pool are charged by the **hook**, not by the pool. The pool's own LP fee is `0`, and `HookFeeCollected` on `0xe5e70264…` is where the fee and the creator tax actually show up. Reading `fee` from the `PoolKey` and calling it the trading cost will understate it to zero. ::: --- ## Locked liquidity: verifying the Pons liquidity lock {#liquidity-lock} A graduated Pons token has **two locks**, and both are visible on-chain: | Lock | What is locked | Where | Event | | --- | --- | --- | --- | | Liquidity position | The full-range Uniswap v4 position seeded with 10/49 of supply plus the graduation quote | `PonsV2LaunchLocker` `0x267444d099b10fb5ed7c3cc7b7c767adca574952` holds the position NFT | `PositionLocked(address indexed owner, uint256 indexed tokenId)` on the locker — **decoded** | | Supply | 4/49 of supply (≈81,632,653 tokens) | The same locker, as a plain token balance | `TokenSupplyLocked(address indexed token, uint256 amount)` on the locker — **undecoded**, topic0 `af33c4ab…`; `GraduationTokensPermanentlyLocked(token, amount)` on the factory is the decoded twin | Bitquery sees the effect of the locks, not the contract code: the position NFT and the 4/49 balance sit in the locker and, across every graduated token, never leave it. If you need a code-level guarantee, verify the locker source on the explorer. To verify a specific token's lock on-chain, read `PositionLocked` by the `owner` argument — which is the **launched token address**, not a wallet — and check that `tokenId` matches `positionId` in the token's `PoolGraduated`: ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 5} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x267444d099b10fb5ed7c3cc7b7c767adca574952"}} Log: {Signature: {Name: {is: "PositionLocked"}}} Arguments: {includes: { Name: {is: "owner"} Value: {Address: {is: "0x2861f208e71ced7beab010457bf10f0c1ccc0e2d"}} }} } ) { Block { Time } Transaction { Hash } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` The supply lock is a balance, so the cheapest check is the locker's holding of the token — it should read 4/49 of 1,000,000,000: ```graphql { EVM(dataset: archive, network: robinhood) { Holders( limit: {count: 1} where: { Currency: {SmartContract: {is: "0x2861f208e71ced7beab010457bf10f0c1ccc0e2d"}} Holder: {Address: {is: "0x267444d099b10fb5ed7c3cc7b7c767adca574952"}} } ) { Holder { Address } Balance { Amount } } } } ``` To stream every new lock as it happens, subscribe to `PositionLocked` on the locker without the `Arguments` filter — one row per graduation, `owner` is the token. --- ## Trading data in the Trading cube (Crypto Price API) The `Trading` cube covers a Pons token across both venues: curve trades carry `Protocol: "pons_v2"` (see [Bonding-curve trades](#bonding-curve-trades)), and once graduated the token is an ordinary Uniswap v4 market: | Field | Value | | --- | --- | | `Pair.Market.ProtocolFamily` | `Uniswap` | | `Pair.Market.Protocol` | `uniswap_v4` | | `Pair.Market.Network` | `Robinhood` | :::caution The `pons_v2` protocol label covers curve trades, not graduated pools The `Trading` cube does have a Pons label — `Protocol: "pons_v2"` — but it marks **bonding-curve trades only**. Once a token graduates, its pool trades are plain `uniswap_v4`, which on Robinhood also covers pools created elsewhere, so **graduated Pons tokens cannot be isolated by protocol filter**. Scope by token address: harvest the set from `PoolRegistered`, then filter `Trading` by `Token.Address: {in: [...]}`. A protocol filter on `pons_v2` plus a token filter together give you a token's full curve + pool trade history in one cube. On `uniswap_v4` rows `Pair.Pool.Address` is the v4 PoolManager singleton, not a per-pool address (on `pons_v2` rows it is the bonding curve). Use the `PoolId` from `Initialize` when you need to identify one pool. ::: ### Latest trades for a graduated token ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: { Pair: { Token: {Address: {is: "0x95d3bc5d467d448ac83c5b33ff90f4dcfaf4c1e4"}} Market: {Network: {is: "Robinhood"}} } } ) { Block { Time } Side Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } TransactionHeader { Hash } Pair { Token { Address Symbol Name } QuoteToken { Address Symbol } Market { Protocol ProtocolFamily Network } } } } } ``` ▶️ [Stream trades of a graduated token - Run in IDE](https://ide.bitquery.io/pons-graduated-token-trades-stream) :::note Trades are not duplicated on Pons pools Unlike [pools.trade](/docs/blockchain/robinhood/pools-trade-api#latest-trades-for-a-poolstrade-token), Pons v4 pools return **one row per swap step**. No dedup pass is needed before summing volume. One user swap can still fan out into several routed steps across different quote pairs in the same transaction, so summing every step overstates end-user volume. Graduated tokens commonly trade against both ETH and USDG. ::: ### OHLCV price candles Candles are built from every `Trading` row, so they start from the token's **first bonding-curve trade** — no need to wait for graduation, and the series runs continuously across the curve-to-pool transition: ```graphql { Trading { Tokens( limit: {count: 24} orderBy: {descending: Block_Time} where: { Token: {Address: {is: "0x95d3bc5d467d448ac83c5b33ff90f4dcfaf4c1e4"} Network: {is: "Robinhood"}} Interval: {Time: {Duration: {eq: 3600}}} } ) { Block { Time } Token { Address Symbol Name } Volume { Usd } Price { Ohlc { Open High Low Close } } } } } ``` Change `Duration` to `60`, `300`, `900` or `86400` for other candle sizes. Add `Supply { MarketCap CirculatingSupply }` for FDV. ### Top graduated Pons tokens by trade count {#top-graduated-pons-tokens-by-volume} Pass a token set harvested from [`PoolRegistered`](#enumerating-graduated-tokens): ```graphql { Trading { Tokens( limit: {count: 25} orderBy: {descendingByField: "trades"} where: { Token: { Address: {in: [ "0x95d3bc5d467d448ac83c5b33ff90f4dcfaf4c1e4", "0xddec0170ceb4426ea05f2fbd485dffa4fafa6615", "0xd928a068d2b90798373a470c9d9ba562322acdef" ]} Network: {is: "Robinhood"} } Interval: {Time: {Duration: {eq: 3600}}} Block: {Time: {since_relative: {days_ago: 1}}} } ) { Token { Address Symbol Name } vol: sum(of: Volume_Usd) trades: count } } } ``` :::note Keep per-interval metrics out of aggregations Selecting a per-row metric such as `Supply { MarketCap }` alongside `sum(of: Volume_Usd)` adds it as a grouping key, so you get one row **per interval** instead of one row per token. Time windows go in `Block: {Time: …}` — `Interval.Time.Since` is not a valid field. ::: --- ## Pool liquidity, slippage, and balance changes These three cubes are **realtime-only** on Robinhood — `archive` and `combined` both error on them, unlike the rest of this page (see [Datasets](#datasets)) — so use them for live monitoring and persist what you need. All three key off the **`PoolId`** from `Initialize`. ### Live pool liquidity (depth) ```graphql { EVM(network: robinhood) { DEXPoolEvents( limit: {count: 10} orderBy: {descending: Block_Time} where: { PoolEvent: {Pool: {PoolId: {is: "0xPOOL_ID"}}} } ) { Block { Time } Log { Signature { Name } } PoolEvent { Dex { ProtocolName ProtocolVersion } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } } } } } ``` `DEXPoolEvents` holds only the recent window, so pick a pool that has traded within it: take the `id` argument of the `Initialize` event from [The graduated Uniswap v4 pool](#the-graduated-uniswap-v4-pool) and put it in `PoolId`. `AmountCurrencyA` is the quote side (ETH in the example) and `AmountCurrencyB` the token side. The token side's USD value reads `0` for unpriced launch tokens, so value the pool from the quote side. ### Per-swap slippage ```graphql { EVM(network: robinhood) { DEXPoolSlippages( limit: {count: 10} orderBy: {descending: Block_Time} where: { Price: {Pool: {PoolId: {is: "0xPOOL_ID"}}} } ) { Block { Time } Price { Dex { ProtocolName } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } AtoB { Price MaxAmountIn MinAmountOut } SlippageBasisPoints } } } } ``` Same rule as above: `DEXPoolSlippages` is realtime-only, so use a pool with recent swaps. Streamed with `SlippageBasisPoints: {gt: 100}`, this is a ready-made toxic-fill alert. ### Per-transaction balance changes ```graphql { EVM(network: robinhood) { TransactionBalances( limit: {count: 10} orderBy: {descending: Block_Time} where: { TokenBalance: {Currency: {SmartContract: {is: "0x95d3bc5d467d448ac83c5b33ff90f4dcfaf4c1e4"}}} } ) { Block { Time } Transaction { Hash From } TokenBalance { Address PreBalance PostBalance HasPreBalance TotalSupply Currency { Symbol } } } } } ``` :::note Check `HasPreBalance` When `HasPreBalance` is `false`, `PreBalance` reads `0` meaning "unknown", not "zero". Treat the delta as reliable only when it is `true`. `TotalSupply` reads `1000000000` for every Pons launch, which is a cheap sanity check that you are looking at the right contract. ::: --- ## Holders and supply ```graphql { EVM(dataset: archive, network: robinhood) { Holders( limit: {count: 100} orderBy: {descending: Balance_Amount} where: { Currency: {SmartContract: {is: "0x95d3bc5d467d448ac83c5b33ff90f4dcfaf4c1e4"}} Balance: {Amount: {gt: "0"}} Holder: {Address: {notIn: [ "0x8366a39cc670b4001a1121b8f6a443a643e40951", "0x267444d099b10fb5ed7c3cc7b7c767adca574952", "0xe5e702641ea86f4ae6cc3cdaed2b886f976be044" ]}} } ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` :::caution Exclude three protocol addresses, not one On a graduated Pons token the top holders are all protocol contracts: - **`0x8366a39c…`** — the v4 PoolManager, which custodies the pool's liquidity - **`0x267444d0…`** — `PonsV2LaunchLocker`, holding the permanently locked 4/49 of supply - **`0xe5e70264…`** — the meme hook, holding accrued fees in the token Leave them in and the protocol itself dominates every holder count, concentration ratio and top-wallet leaderboard. The `notIn` filter above removes all three. For a token **still on its curve**, the curve contract holds all unsold supply and should be excluded the same way. ::: For circulating supply and market cap, see [Robinhood Token Supply](/docs/blockchain/robinhood/robinhood-token-supply). --- ## Launchpad stats {#launchpad-stats} Four launchpad-wide numbers, each one query on the `PonsV2LaunchFactory` events or the `Trading` cube. The event queries use `dataset: combined` with a `since_relative` window, so the counts run from 7 days ago up to the latest block, and they filter by topic0 so they read the same on every dataset. ### Pons launches per day (last 7 days) {#pons-launches-per-day} One `TokenLaunched` event per launch on the factory, counted per day, with the number of distinct wallets that launched that day: [Run this query in the IDE](https://ide.bitquery.io/pons-launchpad-launches-per-day-robinhood-chain) ```graphql { EVM(network: robinhood, dataset: combined) { Events( orderBy: {ascending: Block_Date} where: { LogHeader: {Address: {is: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"}} Topics: {includes: [{Hash: {is: "8d4aad4953d0ca700d468f3753aa14432d1b35b43ec6409f051fb6aa43a89607"}}]} Block: {Time: {since_relative: {days_ago: 7}}} } ) { Block { Date } launches: count creators: uniq(of: Transaction_From) } } } ``` ### Pons graduations per day {#pons-graduations-per-day} `PoolGraduated` fires once per token when its Uniswap v4 pool is created and seeded (see [Graduation](#graduation)), so a daily count of it is the daily graduation count: [Run this query in the IDE](https://ide.bitquery.io/pons-launchpad-graduations-per-day-robinhood-chain) ```graphql { EVM(network: robinhood, dataset: combined) { Events( orderBy: {ascending: Block_Date} where: { LogHeader: {Address: {is: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"}} Topics: {includes: [{Hash: {is: "0a44ef75df69c534f43cd6c1aa3ef8983065fe5fe79ef9e79f6494e6f258c259"}}]} Block: {Time: {since_relative: {days_ago: 7}}} } ) { Block { Date } graduations: count } } } ``` ### Top 10 Pons tokens by 24h volume {#top-pons-tokens-24h-volume} Bonding-curve trades carry `Protocol: "pons_v2"` in the `Trading` cube, so one aggregation ranks every token on its curve by USD volume over the last 24 hours: [Run this query in the IDE](https://ide.bitquery.io/pons-launchpad-top-tokens-24h-volume-robinhood-chain) ```graphql { Trading { Trades( limit: {count: 10} orderBy: {descendingByField: "volume_usd"} where: { Pair: {Market: {Protocol: {is: "pons_v2"}, Network: {is: "Robinhood"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Pair { Token { Address Symbol Name } } volume_usd: sum(of: AmountsInUsd_Quote) trades: count traders: uniq(of: Trader_Address) } } } ``` This ranks curve volume. Graduated tokens trade as `uniswap_v4`, so rank them with a token list from [`PoolRegistered`](#enumerating-graduated-tokens), as in [Top graduated Pons tokens](#top-graduated-pons-tokens-by-volume). ### Top creator wallets by launches {#top-pons-creators} `Transaction.From` on a `TokenLaunched` event is the wallet that sent the launch, including launches made through the `PonsV2LaunchAndBuy` router: [Run this query in the IDE](https://ide.bitquery.io/pons-launchpad-top-creator-wallets-robinhood-chain) ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 10} orderBy: {descendingByField: "launches"} where: { LogHeader: {Address: {is: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"}} Topics: {includes: [{Hash: {is: "8d4aad4953d0ca700d468f3753aa14432d1b35b43ec6409f051fb6aa43a89607"}}]} Block: {Time: {since_relative: {days_ago: 7}}} } ) { Transaction { From } launches: count } } } ``` --- ## Streaming Every query on this page runs as a subscription — switch `query` to `subscription` and drop `limit`/`orderBy`. Connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol (`connection_init` → `connection_ack` → `subscribe`). See [WebSocket authentication](/docs/authorization/websocket/). The three feeds worth running continuously: ```graphql # 1. Every new launch, with token + curve + full metadata subscription { EVM(network: robinhood) { Calls(where: {Call: { To: {in: ["0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e", "0xe33e9e479df8802cb0866d5d05258bec4cf62948"]} Input: {startsWith: ["0xf35abbcf", "0xa72101af", "0xf85f8e41"]} Success: true }}) { Block { Time } Transaction { Hash From } Call { To Value Input Output } } } } ``` ▶️ Runnable IDE examples: [TokenLaunched stream](https://ide.bitquery.io/pons-new-launches-stream), [launch calls with metadata](https://ide.bitquery.io/pons-launch-metadata-calls-stream) ```graphql # 2. Every bonding-curve trade on the network, fully decoded subscription { EVM(network: robinhood) { Events(where: {Log: {Signature: {Name: {in: ["CurveBuy", "CurveSell"]}}}}) { Block { Time } Transaction { Hash From } LogHeader { Address } Log { Signature { Name } } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` ▶️ Runnable IDE examples: [curve buys and sells stream](https://ide.bitquery.io/pons-curve-trades-stream), [curve trades priced in USD](https://ide.bitquery.io/pons-curve-trades-usd-stream) ```graphql # 3. Every graduation, with the token address readable in the payload subscription { EVM(network: robinhood) { Events(where: { LogHeader: {Address: {is: "0xe5e702641ea86f4ae6cc3cdaed2b886f976be044"}} Topics: {includes: [{Hash: {is: "01bf263a1db1652580721573296e1a1fa70b3d4c87f61d02a69c4e1109d2d573"}}]} }) { Block { Time } Transaction { Hash } LogHeader { Data } } } } ``` --- --- ## Next steps - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) — full trade schema for the network - [Robinhood Calls API](/docs/blockchain/robinhood/robinhood-calls-api) — more on `Call.Input` / `Call.Output` and internal calls - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) — compare launchpads side by side - [Pools.trade API](/docs/blockchain/robinhood/pools-trade-api) — the other major Robinhood Chain launchpad - [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api) — holder distribution queries - [WebSocket subscriptions](/docs/subscriptions/websockets/) — turn any query above into a live stream --- ## PoolPrice Fields: Liquidity Pool Price on Trading Pairs URL: https://docs.bitquery.io/docs/trading/crypto-price-api/pool-price-fields/ PoolPrice on the Trading Pairs cube: the liquidity pool's own price from its curve, next to the traded price. Fields, units, sources, coverage, runnable GraphQL queries and the trading.prices Kafka messages. # PoolPrice fields ## What it is `Trading.Pairs` carries two prices for each liquidity pool: - `Price` is the **traded** price: OHLC built from the swaps in the interval. - `PoolPrice` is the **pool's own** price: what the pool's curve quotes at its current liquidity, after the last swap the pool reported. `PoolPrice` is a marginal price, not an executed one. On a thin liquidity pool it sits beyond the traded close by that swap's price impact, so it legitimately differs from `Price.Ohlc.Close` on the same row. On deep liquidity pools the two agree within a percent. `PoolPrice` is on `Pairs` only. `Tokens` and `Currencies` have no pool price: a token's price is a blend of its pools, and the token row's [`LeadingPool`](/docs/trading/crypto-price-api/liquidity-fields#leadingpool-tokens-only) names the pool whose price counts most. ## How to get it Select `PoolPrice { … }` on `Trading.Pairs` next to `Price`, in queries and subscriptions. Filter on `PoolPrice.Source` to keep only rows that have a pool price. The same values are on the `trading.prices` Kafka topic as `PairUpdate.PoolPriceUpdate` (see [Kafka](#kafka-tradingprices)). ## How it is derived The price is read from the pool's state after each pool event. `PoolPrice.Source` says where: | `Source` | Read from | Where | | --- | --- | --- | | `table` | The spot of the pool's slippage table | EVM | | `event` | The post-swap state the venue's swap event reports | Solana | | `reserves` | Quote reserve divided by base reserve of a constant-product pool | Solana constant-product venues, such as pump AMM | | `""` (empty) | No pool price | Pools that report no price state | **Unit.** `PoolPrice` follows the row's unit exactly like `Price`: USD on rows where `Price.IsQuotedInUsd` is `true` (the default), quote tokens per base token when you filter `Price: {IsQuotedInUsd: false}`. **OHLC.** `Open` is the close of the previous interval. `High` and `Low` are the extremes the curve quoted after a swap inside the interval, so on a thin pool they sit beyond the traded `High` and `Low` by each swap's own impact. **Not blended.** The pool price belongs to one pool. The token's blended price stays the index; see the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). ## Fields {#fields} | Field | Type | Meaning | | --- | --- | --- | | `PoolPrice.Price` | Float | The pool's price at the end of the row's interval. Equals `PoolPrice.Ohlc.Close`. | | `PoolPrice.Ohlc { Open High Low Close }` | Float | The pool price over the row's interval. | | `PoolPrice.Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving }` | Float | Averages over the last five intervals of this length. | | `PoolPrice.Source` | String | `table`, `event` or `reserves`, above. Empty when the pool has no price. | | `PoolPrice.UpdatedAt` | DateTime | Time of the pool event the price came from. On EVM it can trail the row's block by a few seconds. On Solana it equals the block time. | ### When `PoolPrice` is empty {#absence} Not every pool reports a price. When it does not, `PoolPrice.Price`, `Ohlc`, `Average` and `UpdatedAt` are `null` and `Source` is `""`. Filter on `PoolPrice.Source` to keep only priced rows, as the examples below do. ## Examples ### Pool price candles next to traded candles The WETH/USDC Uniswap v3 liquidity pool on Ethereum, 1-minute bars for the last 30 minutes. `PoolPrice.Ohlc` and `Price.Ohlc` come back on the same row. [Run query ➤](https://ide.bitquery.io/Pool-price-vs-trade-candles) ```graphql query PoolPriceVsTradeCandles { Trading { Pairs( limit: {count: 30} orderBy: {descending: Interval_Time_Start} where: { Pool: {Address: {is: "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640"}} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 30}}} } ) { Interval { Time { Start Duration } } Token { Symbol } QuoteToken { Symbol } PoolPrice { Source UpdatedAt Ohlc { Open High Low Close } } Price { Ohlc { Open High Low Close } } } } } ``` ### Does a liquidity pool have a pool price? Returns the latest hour with a pool price. An empty list means the pool has none. Do not add a time bound here: the pool address alone is the fast path. [Run query ➤](https://ide.bitquery.io/Pair-has-pool-price) ```graphql query HasPoolPrice { Trading { Pairs( limit: {count: 1} orderBy: {descending: Interval_Time_Start} where: { Pool: {Address: {is: "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640"}} Interval: {Time: {Duration: {eq: 3600}}} PoolPrice: {Source: {not: ""}} } ) { Interval { Time { Start } } PoolPrice { Price Source UpdatedAt } } } } ``` ### Pool price in quote tokens SOL's liquidity pools on Solana, priced in quote tokens per SOL instead of USD. `Source: {is: "event"}` keeps pools whose price comes from the venue's swap event. [Run query ➤](https://ide.bitquery.io/Pool-price-in-quote-tokens) ```graphql query PoolPriceInQuoteTokens { Trading { Pairs( limit: {count: 10} orderBy: {descending: Interval_Time_Start} where: { Token: {Id: {is: "bid:solana:So11111111111111111111111111111111111111112"}} Price: {IsQuotedInUsd: false} Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 5}}} PoolPrice: {Source: {is: "event"}} } ) { Market { Protocol } Pool { Address } QuoteToken { Symbol } PoolPrice { Price Source UpdatedAt } Price { Ohlc { Close } } } } } ``` ### Stream the pool price live The same `where` works on a subscription. A pair whose pool never prices sends nothing when filtered on `Source`. [Run query ➤](https://ide.bitquery.io/Pool-price-live-stream) ```graphql subscription PoolPriceLive { Trading { Pairs( where: { Pool: {Address: {is: "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640"}} Interval: {Time: {Duration: {eq: 60}}} PoolPrice: {Source: {not: ""}} } ) { Interval { Time { Start } } PoolPrice { Price Source UpdatedAt } Price { Ohlc { Close } } } } } ``` ### Pool price of one Uniswap v4 liquidity pool Uniswap v4 and other singleton designs share one manager address across many pools. Add `Pool: {Id: {is: …}}` to select one pool. This is LSK/ETH on Ethereum, with the pool price's moving averages. [Run query ➤](https://ide.bitquery.io/Pool-price-uniswap-v4-pool) ```graphql query PoolPriceUniswapV4Pool { Trading { Pairs( limit: {count: 10} orderBy: {descending: Interval_Time_Start} where: { Pool: { Address: {is: "0x000000000004444c5dc75cb358380d2e3de08a90"} Id: {is: "0x6af632b8235f1a9d95a816f7a4090736346b763a8ab4e8327017aaae72d0d1d2"} } Interval: {Time: {Duration: {eq: 60}}} Block: {Time: {since_relative: {minutes_ago: 30}}} } ) { Interval { Time { Start } } Market { Protocol Id } Token { Symbol } QuoteToken { Symbol } PoolPrice { Price Source UpdatedAt Average { Mean SimpleMoving WeightedSimpleMoving ExponentialMoving } } Price { Ohlc { Close } } } } } ``` ## Kafka: `trading.prices` {#kafka-tradingprices} The pool price is on the `trading.prices` topic from protobuf `v2.6.8`, defined in [`market/price_index.proto`](https://github.com/bitquery/streaming_protobuf/blob/main/market/price_index.proto). It is on `PairUpdate` only, not on token, currency or trade messages. | Message | Field | Number | Unit | | --- | --- | --- | --- | | `PairUpdate` | `PoolPriceUpdate PoolPriceUpdate` | 13 | USD | | `PairUpdate` | `PoolPriceUpdate PoolPriceUpdateInQuoteTokens` | 14 | Quote tokens per base token | `PoolPriceUpdate`: | Field | Type | Number | Meaning | | --- | --- | --- | --- | | `Price` | `float` | 1 | The latest pool price, the close of the shortest interval. | | `Source` | `string` | 2 | `table`, `event` or `reserves`, as in GraphQL. | | `UpdatedAt` | `uint32` | 3 | Unix second of the pool event the price was read from. | | `PriceByTimeIntervals` | `repeated PriceByTimeInterval` | 4 | The pool price over each interval, one entry per interval of `PriceUpdate.PriceByTimeIntervals` on the same `PairUpdate`, matched by `TimeInterval`. `Ohlc` and the moving averages are set; `Amounts`, `MeanPrice` and `Ohlc.Volume` are not, because a pool price has no volume. | Differences from GraphQL: - `PoolPriceUpdate` is absent when the pool has no priced state. The USD one is also absent when the quote currency has no USD rate. Check `HasField` before reading. - `UpdatedAt` is a unix second, not a DateTime. ### Archive columns Rows of the `Trading.Pairs` cube in the parquet archive (`pairs_by_token_id`, `pairs_by_currency_id`, `pairs_by_token_address`, `pairs_by_pool_address`, `pairs_by_interval_start`) carry the same values as twelve columns: | Column | Type | Meaning | | --- | --- | --- | | `PoolPrice_Price` | Float32 | The pool's price at the end of the row's interval, in the row's unit. Equals `PoolPrice_Ohlc_Close`. | | `PoolPrice_Ohlc_Open` / `_High` / `_Low` / `_Close` | Float32 | The pool price over the row's interval. | | `PoolPrice_Average_Mean` / `_SimpleMoving` / `_WeightedSimpleMoving` / `_ExponentialMoving` | Float32 | Moving averages over the pool price of the last five intervals of this length. `PoolPrice_Average_Estimate` is always `0`. | | `PoolPrice_Source` | LowCardinality(String) | `table`, `event` or `reserves`. Empty when there is no pool price. | | `PoolPrice_UpdatedAt` | UInt32 | Unix second of the pool event the price was read from. | The unit follows the row, like the `Price_*` columns: USD when `Price_IsQuotedInUsd = 1`, quote tokens per base token otherwise. A row with no pool price has `PoolPrice_Price = 0` and an empty `PoolPrice_Source`, not NULL. ## Related - [Pairs cube](/docs/trading/crypto-price-api/pairs): every field on a `Pairs` row. - [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields): the reserve behind the price, and which pool leads a token's blend. - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm): how pool prices are blended into one token price. - [Solana Liquidity Pool Price API](/docs/blockchain/Solana/solana-pool-price): the pool price after every pool event on the Solana `DEXPools` cube. --- ## Pools.trade API — Uniswap Launchpad on Robinhood Chain URL: https://docs.bitquery.io/docs/blockchain/robinhood/pools-trade-api/ Pools.trade API: track the Uniswap launchpad on Robinhood Chain with Bitquery GraphQL. Query new token launches, Crowd Launch auctions, trades, OHLCV, and holders. # Pools.trade API — Uniswap Launchpad on Robinhood Chain **[Pools.trade](https://pools.trade/)** is the token launchpad **built by Uniswap for Robinhood Chain**, opened to the public on **5 August 2026** — its contracts had been live since **8 July 2026**, and flagship tokens like **FRONG** were minted on 30 July through the earlier entry contract. The contracts self-describe as the *Uniswap LiquidityLauncher*. This guide shows how to track **new pools.trade token launches**, **Crowd Launch auctions**, **trades**, **OHLCV prices**, and **holders** with Bitquery GraphQL APIs, using the `EVM(network: robinhood)` and `Trading` cubes. Searching for a **Pools Trade API** (the spaced spelling of pools.trade) lands you in the right place — this page covers the full data API for the launchpad. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending) — new pools, trending tokens, pair lookup and token search - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) - [Pons Launchpad API on Robinhood Chain](/docs/blockchain/robinhood/pons-api) — bonding-curve launchpad, graduations, Uniswap v4 pools - [Flap.sh API on Robinhood](/docs/blockchain/robinhood/flap-sh-api) - [Bags.fm API on Robinhood](/docs/blockchain/robinhood/bags-fm-api) - [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api) - [WebSocket subscriptions](/docs/subscriptions/websockets/) ::: --- ## How pools.trade differs from other launchpads Most launchpads (Flap.sh, Bags.fm, pump.fun-style venues) run trades through a **custom bonding-curve contract**, then emit a **graduation event** when the token migrates to a real DEX pool. **Pools.trade does not work that way.** Every launch gets a **real Uniswap v4 pool** at launch — usually created in the same transaction as the token mint, occasionally in an immediate follow-up transaction on the original entry path. There is no separate bonding-curve AMM and no migration step. | Property | Value | | --- | --- | | Network | Robinhood Chain (`network: robinhood`, chain ID **4663**) | | AMM | **Uniswap v4** (`Protocol: uniswap_v4`) | | Pool quote currency | **Native ETH** (`currency0` = `0x000…000`) | | Pool fee | `2500` (0.25%) | | Tick spacing | `25` (current path) or `60` (original path) | | Hooks | **None** (`hooks` = `0x000…000`) | | Launch supply | `1000000000` (1 billion, decimal-normalized) | The practical consequences for anyone building on this data: - **Trades are queryable from block one** in the `Trading` cube — you do not have to wait for graduation. - The "bonding curve" you see in the UI is **single-sided concentrated liquidity** in a plain v4 pool, not a separate contract. - There is **no `Graduated` / `LaunchedToDEX` event** to subscribe to for curve launches. See [Graduation](#graduation). ### The two launch modes | Mode | UI label | Mechanism | Graduation target | | --- | --- | --- | --- | | **Curve launch** | *(default)* | Token + v4 pool created instantly; price discovered by trading | **$50,000 FDV** | | **Crowd Launch** | `Crowd Launch` | A **continuous clearing auction (CCA)** runs first in its own per-token contract, then the pool opens | ≈$5,000-equivalent raise (platform-reported); auctions routinely oversubscribe far past it | Crowd Launches run in a **fixed ~4-hour window** and can be *oversubscribed*. Each auction gets its **own contract address**. See [Crowd Launch auctions](#crowd-launch-cca-auctions). --- ## Contract addresses | Role | Address | Notes | | --- | --- | --- | | **Launch entry (current)** | `0x0000ffffbe8efe702c8703ae3477ff5de3d319c0` | Live since the 5 Aug public launch | | **Launch entry (original)** | `0x00004c4ccc709ef590f7c81102c0689f0263d4e9` | Live since 8 Jul; minted FRONG, POOLS — **still active** | | **Token factory** | `0x000000e200088d55c39a11f609e5f667729ad49b` | Name, symbol, description, image | | **Launchpad (current path)** | `0x23f8209572b4a1c2ad88a42749e830791fb027f1` | `TokenLaunched` + v4 `PoolKey`; tickSpacing 25 | | **Launchpad (current path, alt)** | `0xad44d55e7f8337c3ce113fbb591486e85be104b2` | Same ABI, lower volume; tickSpacing 25 | | **Launchpad (original path)** | `0xce57498d3474dcc244dfb6710ffbe6d4441cd2b2` | Same ABI; tickSpacing 60 | | **Launchpad (original path, alt)** | `0x60d73b21cdf2ea846ab3d58699bbbb8f29d72491` | Same ABI; tickSpacing 60 | | **CCA auction factory** | `0x000000001f26a0044baa66024e7b6599c61963f8` | Emits `AuctionCreated` per Crowd Launch | | **Liquidity initializer registry** | `0x05d552391067389ee44fec3924157ed33f976000` | Emits `InitializerCreated` | | **Uniswap v4 PoolManager** | `0x8366a39cc670b4001a1121b8f6a443a643e40951` | Shared singleton — **not** pools.trade-only | | **CCA auction** | one per Crowd Launch | e.g. `0xD10dc5f79F95E953e710F1eDeBddE0baD2e8fed8` | | **USDG** | `0x5fc5360d0400a0fd4f2af552add042d716f1d168` | Secondary quote token | | **WETH** | `0x0bd7d308f8e1639fab988df18a8011f41eacad73` | Secondary quote token | :::caution There are TWO entry contracts — filter on both pools.trade ran on `0x00004c4c…` from 8 July before `0x0000ffff…` took over at the public launch, **and the original contract still processes launches**. Both emit byte-identical events (`TokenCreated`, `TokenDistributed`), so every launch filter in this guide uses `in:` with both addresses. Filtering only the new one dropped ~40% of 5 August's launches (the split varies day to day) — and misses FRONG and POOLS, the two largest tokens on the platform. ::: :::caution The v4 PoolManager is not a pools.trade filter `0x8366a39c…` is the **Uniswap v4 singleton** for all of Robinhood Chain. Every v4 trade on the network routes through it, including pools launched elsewhere. Filtering on it will **not** isolate pools.trade activity — use the token set from `TokenCreated` instead (see [Top tokens](#top-poolstrade-tokens-by-volume)). ::: --- ## Event reference **Every pools.trade event is decoded.** `Log.Signature.Name` is populated and `Arguments` returns named, typed values — including the entire Crowd Launch auction, which earlier versions of this page documented as raw. Filtering by topic0 (`SignatureHash`) still works and is still the better choice in one specific case, covered below. | Event | Emitter | Decoded? | topic0 (`SignatureHash`) | | --- | --- | --- | --- | | `TokenCreated(address)` | entry | ✅ Yes | `2e2b3f61b70d2d131b2a807371103cc98d51adcaa5e9a8f9c32658ad8426e74e` | | `Initialize` / `ModifyLiquidity` / `Swap` | v4 PoolManager | ✅ Yes | — | | `TokenDistributed` | entry | ✅ Yes | `67226bacccef969dab310a9e55dc1cf821363658e433fd330344f5cc00c79ac8` | | `TokenCreated` *(metadata overload)* | factory | ✅ Yes | `4ef8284ecf42d4cd19686572ffd87f630858c82398911e776cb831de35eddbf4` | | `TokenLaunched` | launchpad | ✅ Yes | `3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4` | | `DistributionInitialized` | launchpad | ✅ Yes | `0afd26d7f0833a451173acef122d058906aa7708ceb6f67ea7471a649d88b44b` | | `BidSubmitted` | CCA auction | ✅ Yes | `650baad5cd8ca09b8f580be220fa04ce2ba905a041f764b6a3fe2c848eb70540` | | `ClearingPriceUpdated` | CCA auction | ✅ Yes | `30adbe996d7a69a21fdebcc1f8a46270bf6c22d505a7d872c1ab4767aa707609` | | `CheckpointUpdated` | CCA auction | ✅ Yes | `f1e4b6d7d0d7c5deb6393a39862d66a2f2ecb034f3283a8a597f9bf0c36f76fa` | | `TickInitialized` | CCA auction | ✅ Yes | `7fdd20e2dbf90ff60a7d9be5ad62f1ec6d9d9cba8b36174a3839cafd059f0958` | | `NextActiveTickUpdated` | CCA auction | ✅ Yes | `b9a86892440ed5515518351623ecfc523d283b21e92f1505e533ef26137be5b0` | | `AuctionStepRecorded` | CCA auction | ✅ Yes | `6863f2b489f9186bf89231dc73aa0e9836f536b9ddb0f708f74260ed3160f297` | | `TokensReceived` | CCA auction | ✅ Yes | `468160b6769cb8abc9324bc14fe70ee0ce87f1e92087186c6ae22a964a04c572` | | `AuctionCreated` | CCA auction factory | ✅ Yes | `7ede475fad18ccf0039f2b956c4d43a8b4ed0853de4daaa8ae25299f331ae3b9` | | `InitializerCreated` | initializer registry | ✅ Yes | `6d759545eb439f07e70f45431d6339af7a4f1ffef06d43e8ddf47fdb0799708c` | Every event above returns decoded `Arguments` from the API, and every topic0 matches its signature by keccak-256 preimage. ### Reading decoded arguments Two things about the `Arguments` shape are easy to trip over. **Tuple components are flattened, and they all share the tuple's type name.** A struct argument does not arrive as one nested value — it arrives as one row per component, each carrying the *tuple's* name rather than the field's name, distinguished only by `Index`. For the factory's `TokenCreated(address,(string,string,string,bytes))`: | `Name` | `Index` | `Type` | Meaning | | --- | --- | --- | --- | | `tokenAddress` | 0 | `address` | the new token | | `UERC20Metadata` | 0 | `string` | description | | `UERC20Metadata` | 1 | `string` | external / social URL (often empty) | | `UERC20Metadata` | 2 | `string` | image URI — `ipfs://…` or `https://…` | | `UERC20Metadata` | 3 | `bytes` | extra payload (usually empty) | `TokenLaunched` behaves the same way: `poolId`, `token` and `finalPositionRecipient` are named normally, then five `PoolKey` rows follow — index 0 `currency0`, 1 `currency1`, 2 `fee`, 3 `tickSpacing`, 4 `hooks`. `InitializerCreated` flattens its nested struct into eleven `MigratorParameters` rows. **`TokenCreated` is emitted by two different contracts with two different signatures.** The entry contract emits `TokenCreated(address)` and the factory emits the metadata overload `TokenCreated(address,(string,string,string,bytes))`. Filtering on `Name: {is: "TokenCreated"}` alone matches **both**. Disambiguate with `LogHeader.Address`, or filter by the topic0, which is unique per signature. ### Filtering by topic0 Topic0 filtering remains available and is the precise way to pin one exact signature — useful for the overloaded `TokenCreated` above. Supply the hash **without** a `0x` prefix; see the dataset note below for its one limitation. ```graphql { EVM(network: robinhood) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: { Log: { Signature: { SignatureHash: {is: "67226bacccef969dab310a9e55dc1cf821363658e433fd330344f5cc00c79ac8"} } } LogHeader: {Address: {in: [ "0x0000ffffbe8efe702c8703ae3477ff5de3d319c0", "0x00004c4ccc709ef590f7c81102c0689f0263d4e9" ]}} } ) { Block { Time Number } Transaction { Hash From } LogHeader { Address Data } Log { Signature { SignatureHash } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-raw-event-by-topic0) Two things to know when reading the result: - **You no longer need `LogHeader.Data` for this event.** `TokenDistributed` now decodes to `tokenAddress`, `strategy` and `amount`, so read `Arguments` instead of hand-parsing the payload. `Data` is still returned if you want the raw bytes. - **Drop the `LogHeader.Address` filter for per-token contracts.** CCA auction events fire from a fresh contract per Crowd Launch (1,200+ live already), so filtering on the event alone is the right scope — it captures every auction at once, and `LogHeader.Address` tells you which auction each row came from. ### Full signatures Now that every event is decoded you rarely need these, but the full signatures are the quickest way to see each event's argument types and tuple layout, grouped by emitter address. ```text # entry contracts — 0x0000ffffbe8efe702c8703ae3477ff5de3d319c0 (current) # 0x00004c4ccc709ef590f7c81102c0689f0263d4e9 (original, still active) # both emit identical signatures 67226bacccef969dab310a9e55dc1cf821363658e433fd330344f5cc00c79ac8 TokenDistributed(address,address,uint256) # factory — 0x000000e200088d55c39a11f609e5f667729ad49b 4ef8284ecf42d4cd19686572ffd87f630858c82398911e776cb831de35eddbf4 TokenCreated(address,(string,string,string,bytes)) # launchpads — current path 0x23f82095…27f1 / 0xad44d55e…04b2 (tickSpacing 25) # original path 0xce57498d…d2b2 / 0x60d73b21…2491 (tickSpacing 60) 3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4 TokenLaunched(bytes32,address,address,(address,address,uint24,int24,address)) 0afd26d7f0833a451173acef122d058906aa7708ceb6f67ea7471a649d88b44b DistributionInitialized(address,address,uint256) # CCA auction factory — 0x000000001f26a0044baa66024e7b6599c61963f8 7ede475fad18ccf0039f2b956c4d43a8b4ed0853de4daaa8ae25299f331ae3b9 AuctionCreated(address,address,uint256,bytes) # liquidity initializer registry — 0x05d552391067389ee44fec3924157ed33f976000 6d759545eb439f07e70f45431d6339af7a4f1ffef06d43e8ddf47fdb0799708c InitializerCreated(address,(address,address,uint64,uint128,address,address,(uint24,int24,address),bytes,bytes)) # CCA auction — one contract per Crowd Launch 650baad5cd8ca09b8f580be220fa04ce2ba905a041f764b6a3fe2c848eb70540 BidSubmitted(uint256,address,uint256,uint128) 30adbe996d7a69a21fdebcc1f8a46270bf6c22d505a7d872c1ab4767aa707609 ClearingPriceUpdated(uint256,uint256) f1e4b6d7d0d7c5deb6393a39862d66a2f2ecb034f3283a8a597f9bf0c36f76fa CheckpointUpdated(uint256,uint256,uint24) 7fdd20e2dbf90ff60a7d9be5ad62f1ec6d9d9cba8b36174a3839cafd059f0958 TickInitialized(uint256) b9a86892440ed5515518351623ecfc523d283b21e92f1505e533ef26137be5b0 NextActiveTickUpdated(uint256) 6863f2b489f9186bf89231dc73aa0e9836f536b9ddb0f708f74260ed3160f297 AuctionStepRecorded(uint256,uint256,uint24) 468160b6769cb8abc9324bc14fe70ee0ce87f1e92087186c6ae22a964a04c572 TokensReceived(uint128) ``` :::note `SignatureHash` filters need the realtime dataset Filtering by `Log: {Signature: {SignatureHash: …}}` is served **only** by the realtime dataset. `dataset: archive` returns `no archive or API tables found for cube Event`, and `dataset: combined` returns `no data available yet to query dataset combined`. Decoding the ABIs did not change this. Filter by `Log.Signature.Name` instead when you need `archive` or `combined`; that path works on all three datasets. Be aware that **archive coverage of these events is still thin**: some events that are plentiful on realtime return little or nothing on archive. Treat realtime as the source of truth for launchpad and auction history until archive backfills. Note also that `SignatureHash` values are supplied **without** a `0x` prefix. ::: --- ## Newly launched tokens ### Latest pools.trade launches The decoded `TokenCreated` event on the two entry contracts is the cleanest launch feed — one row per launch. ```graphql { EVM(network: robinhood) { Events( limit: {count: 25} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {in: [ "0x0000ffffbe8efe702c8703ae3477ff5de3d319c0", "0x00004c4ccc709ef590f7c81102c0689f0263d4e9" ]}} Log: {Signature: {Name: {is: "TokenCreated"}}} } ) { Block { Time Number } Transaction { Hash From } LogHeader { Address } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Latest-launches) The single argument `token` is the new token's contract address. `Transaction.From` is the creator wallet, and `LogHeader.Address` tells you which entry contract handled the launch. :::note This event is intentionally thin `TokenCreated(address)` carries **only** the token address — no name, symbol, or image. Those live in the factory's separate `TokenCreated` overload; see [Token metadata](#token-metadata-name-symbol-description-image). ::: ### Stream new launches in real time Launches arrive continuously through both entry contracts, thousands per day at peak. Polling will always lag; subscribe instead. ```graphql subscription { EVM(network: robinhood) { Events( where: { LogHeader: {Address: {in: [ "0x0000ffffbe8efe702c8703ae3477ff5de3d319c0", "0x00004c4ccc709ef590f7c81102c0689f0263d4e9" ]}} Log: {Signature: {Name: {is: "TokenCreated"}}} } ) { Block { Time } Transaction { Hash From } LogHeader { Address } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Stream-new-launches) ### Stream launches with full token detail (mint transfers) The transfer-based stream returns the token's **name, symbol, decimals, and contract** in the same payload — everything a sniping bot or listings feed needs, with no follow-up metadata call. It also carries the transaction's gas economics and success flag: ```graphql subscription { EVM(network: robinhood) { Transfers( where: { Transfer: {Sender: {is: "0x0000000000000000000000000000000000000000"}} Transaction: {To: {in: [ "0x0000ffffbe8efe702c8703ae3477ff5de3d319c0", "0x00004c4ccc709ef590f7c81102c0689f0263d4e9" ]}} } ) { Block { Time Number Hash } Transaction { Hash From To Value Type GasPrice Gas Cost Index } TransactionStatus { Success } Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Decimals Fungible Native ProtocolName } Data Id Index Success Type URI } Call { From To Value Index Signature { Name Signature } } Log { SmartContract Index LogAfterCallIndex Signature { Name Signature } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Stream-launches-with-token-detail) :::caution `Transaction.To` misses indirect launches The mint-transfer pattern only catches launches where the entry contract is the transaction target. Tokens launched **through third-party routers or inside contract-creation transactions** (a measurable share — including several top-volume tokens) have a different `Transaction.To`. The [event-based pattern above](#latest-poolstrade-launches) filters on the **emitter** (`LogHeader.Address`) and catches every launch regardless of how it was routed — treat it as the source of truth and the transfer stream as the convenient enriched feed. ::: The same query works as a one-shot `query` with `limit` and `orderBy` for backfills — add `dataset: combined` there to reach past realtime retention. :::note Amounts are decimal-normalized `Transfer.Amount` is already adjusted for the token's `Decimals`, so the launch mint shows as `1000000000` — 1 billion whole tokens, not the raw on-chain integer. Add `Amount: {eq: "1000000000"}` to the filter if you want to exclude any non-launch mints. ::: ### Launches per day Grouping by `LogHeader.Address` too shows the split between the two entry contracts. `dataset: combined` merges archive history with the realtime tail — plain `archive` lags the chain head, so counts for the current day come up short. ```graphql { EVM(network: robinhood, dataset: combined) { Events( where: { LogHeader: {Address: {in: [ "0x0000ffffbe8efe702c8703ae3477ff5de3d319c0", "0x00004c4ccc709ef590f7c81102c0689f0263d4e9" ]}} Log: {Signature: {Name: {is: "TokenCreated"}}} Block: {Time: {since: "2026-07-08T00:00:00Z"}} } ) { Block { Date } launches: count } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Launches-per-day) ### Most active token creators Useful for spotting spam-bot deployers — a single wallet can mint hundreds of tokens a day. ```graphql { EVM(network: robinhood, dataset: combined) { Events( limit: {count: 25} orderBy: {descendingByField: "launches"} where: { LogHeader: {Address: {in: [ "0x0000ffffbe8efe702c8703ae3477ff5de3d319c0", "0x00004c4ccc709ef590f7c81102c0689f0263d4e9" ]}} Log: {Signature: {Name: {is: "TokenCreated"}}} Block: {Time: {since: "2026-08-05T00:00:00Z"}} } ) { Transaction { From } launches: count } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Most-active-token-creators) --- ## Token metadata (name, symbol, description, image) Metadata splits across two sources. **Name, symbol, decimals, and contract** are indexed on every transfer's `Currency` object — one query against the launch mint gives you all four for any token: ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( limit: {count: 1} where: { Transfer: { Currency: {SmartContract: {is: "0x6245e67affa44a23077f0ea7f981a8dc743a0c47"}} Sender: {is: "0x0000000000000000000000000000000000000000"} } } ) { Block { Time } Transaction { Hash From } Transfer { Amount Currency { Name Symbol Decimals SmartContract } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Token-name-symbol-decimals) `Transaction.From` on the mint is the creator wallet and `Block.Time` is the exact launch time — this works for any pools.trade token regardless of which entry contract or router launched it. The remaining fields — the **description**, the **external link**, and the **image URI** that the pools.trade UI renders — exist on-chain only in the factory's `TokenCreated(address,(string,string,string,bytes))` event. That event is now decoded, so you can read them straight out of `Arguments` with no client-side ABI work. The filter below pins the factory by address because the entry contract emits a *different* `TokenCreated` under the same name (see [Reading decoded arguments](#reading-decoded-arguments)). ```graphql { EVM(network: robinhood) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: { Log: {Signature: {Name: {is: "TokenCreated"}}} LogHeader: {Address: {is: "0x000000e200088d55c39a11f609e5f667729ad49b"}} } ) { Block { Time } Transaction { Hash } Arguments { Name Index Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Token-description-and-image) The tuple arrives flattened — `tokenAddress`, then four `UERC20Metadata` rows keyed by `Index`. A live result: ```text tokenAddress 0x228513f0b584b38415438bd661d7cfab0dbb3077 UERC20Metadata[0] string "The Stock Impaler" # description UERC20Metadata[1] string "https://stockimpaler.com/" # external link, often empty UERC20Metadata[2] string "ipfs://bafkreibersrl3o5pi3vf57d3pk5flqq5bacn…" # image UERC20Metadata[3] bytes "" # extra, usually empty ``` The image is not always IPFS — some launches point at an HTTPS CDN URL instead, so treat `UERC20Metadata[2]` as an opaque URI. --- ## The Uniswap v4 pool behind each launch ### PoolKey from `TokenLaunched` `TokenLaunched` is the richest launch event: its indexed fields are the **v4 `poolId`**, and its data payload is the full **`PoolKey`**. ```graphql { EVM(network: robinhood) { Events( limit: {count: 10} orderBy: {descending: Block_Time} where: { Log: { Signature: { SignatureHash: {is: "3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4"} } } LogHeader: {Address: {in: [ "0x23f8209572b4a1c2ad88a42749e830791fb027f1", "0xad44d55e7f8337c3ce113fbb591486e85be104b2", "0xce57498d3474dcc244dfb6710ffbe6d4441cd2b2", "0x60d73b21cdf2ea846ab3d58699bbbb8f29d72491" ]}} } ) { Block { Time } Transaction { Hash } LogHeader { Address Data } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-PoolKey-from-TokenLaunched) `LogHeader.Data` decodes as five 32-byte words: | Word | Field | Typical value | | --- | --- | --- | | 0 | `currency0` | `0x000…000` (native ETH) | | 1 | `currency1` | the launched token | | 2 | `fee` | `2500` | | 3 | `tickSpacing` | `25` (current path) / `60` (original path) | | 4 | `hooks` | `0x000…000` | :::tip All four launchpad emitters are pools.trade's own `TokenLaunched` fires from four contracts, and **all four are pools.trade infrastructure**: `0x23f82095…`/`0xad44d55e…` serve the current entry path (tickSpacing **25**), while `0xce57498d…`/`0x60d73b21…` serve the original path (tickSpacing **60** — verified: their tokens are listed live on pools.trade, and FRONG's own pool is a tickSpacing-60 pool). Constrain `LogHeader.Address` to these four; the `tickSpacing` value tells you which launch path a token used, not whether it is pools.trade. ::: ### Decoded pool creation (`Initialize`) The v4 PoolManager's `Initialize` **is** decoded, so you can read the same `PoolKey` without manual decoding — at the cost of having to scope it to a token. ```graphql { EVM(network: robinhood) { Events( limit: {count: 5} orderBy: {descending: Block_Time} where: { LogHeader: {Address: {is: "0x8366a39cc670b4001a1121b8f6a443a643e40951"}} Log: {Signature: {Name: {is: "Initialize"}}} } ) { Block { Time } Transaction { Hash } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Pool-creation-Initialize) Returns `id` (poolId), `currency0`, `currency1`, `fee`, `tickSpacing`, `hooks`, `sqrtPriceX96`, `tick`. --- ## Trading data pools.trade tokens are indexed in the `Trading` cube under the **generic Uniswap protocol family**, because they *are* ordinary Uniswap v4 pools: | Field | Value | | --- | --- | | `Pair.Market.ProtocolFamily` | `Uniswap` | | `Pair.Market.Protocol` | `uniswap_v4` | | `Pair.Market.Network` | `Robinhood` | :::caution There is no `pools.trade` protocol label Unlike Bags.fm (`ProtocolFamily: "Bags"`), pools.trade tokens **cannot be isolated by protocol filter** — `uniswap_v4` on Robinhood also covers pools created outside pools.trade. To scope a query to pools.trade, first collect the token set from `TokenCreated`, then filter `Trading` by `Token.Address: {in: [...]}`. Tokens also migrate onto other venues once liquid — the same token can show `uniswap_v3` and `pancake_swap_v3` markets with `WETH` and `USDG` quotes. ::: ### Latest trades for a pools.trade token ```graphql { Trading { Trades( limit: {count: 50} orderBy: {descending: Block_Time} where: { Pair: { Token: {Address: {is: "0x6245e67affa44a23077f0ea7f981a8dc743a0c47"}} Market: {Network: {is: "Robinhood"}} } } ) { Block { Time } Side Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Trader { Address } TransactionHeader { Hash } Pair { Token { Address Symbol Name } QuoteToken { Address Symbol } Pool { Address } Market { Protocol ProtocolFamily Network } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Latest-trades-for-a-token) :::caution Deduplicate before summing USD volume On Robinhood v4, `Trading.Trades` returns **each trade leg roughly twice**, with the two copies differing only in the last decimals of `AmountsInUsd`. Most legs appear exactly twice, so naive sums run close to **2×**. Deduplicate on `(TransactionHeader.Hash, Block.Time, Side, Amounts.Base, Pair.QuoteToken.Symbol, Trader.Address)` before aggregating. Naively summing a token's `Volume_Usd` over 24h roughly doubles the figure the pools.trade UI reports; after deduplication the two match. Note also that one user swap can fan out into **several routed legs** across ETH, WETH, and USDG pairs in the same transaction. Summing every leg overstates end-user volume even after deduplication. ::: ### OHLCV price candles ```graphql { Trading { Tokens( limit: {count: 24} orderBy: {descending: Block_Time} where: { Token: {Address: {is: "0x6245e67affa44a23077f0ea7f981a8dc743a0c47"}} Interval: {Time: {Duration: {eq: 3600}}} } ) { Block { Time } Token { Address Symbol Name Network } Volume { Usd } Price { Ohlc { Open High Low Close } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-OHLCV-price-candles) Change `Duration` to `60`, `300`, `900`, or `86400` for other candle sizes. ### Top pools.trade tokens by volume The two-step pattern: pass a token set harvested from `TokenCreated` into the `Trading` cube. ```graphql { Trading { Tokens( limit: {count: 25} orderBy: {descendingByField: "vol"} where: { Token: { Address: {in: [ "0x6245e67affa44a23077f0ea7f981a8dc743a0c47", "0x385b36ff682ab4c76e7c37a66b96aabc466471d5", "0xd3d5be6558f84e628ee091b511df92b4e461a53b" ]} Network: {is: "Robinhood"} } Interval: {Time: {Duration: {eq: 3600}}} Block: {Time: {since: "2026-08-05T06:00:00Z"}} } ) { Token { Address Symbol Name } vol: sum(of: Volume_Usd) trades: count } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Top-tokens-by-volume) :::note Keep per-interval metrics out of aggregations Selecting a per-row metric such as `Supply { MarketCap }` alongside `sum(of: Volume_Usd)` adds it as a grouping key, so you get one row **per interval** instead of one row per token. Drop it to get a clean per-token total. Time windows go in `Block: {Time: {since: …}}` — `Interval.Time.Since` is not a valid field. ::: --- ## Pool liquidity, slippage, and balance changes Three realtime cubes carry data traders usually have to compute themselves. All three are **realtime-only** on Robinhood — `dataset: archive` and `dataset: combined` both error — so use them for live monitoring and persist what you need. ### Live pool liquidity (depth) `DEXPoolEvents` snapshots the pool's reserves on every swap and liquidity event, keyed by the **v4 `PoolId`** — the same id `TokenLaunched` and `Initialize` emit at launch. This is the fastest way to read a pools.trade token's real depth (rug risk, exit capacity) without summing transfers: ```graphql { EVM(network: robinhood) { DEXPoolEvents( limit: {count: 10} orderBy: {descending: Block_Time} where: { PoolEvent: { Pool: {PoolId: {is: "0xacea8920877840033f0275c37f9b61550b5326917e948bcf8339714d96f9521a"}} } } ) { Block { Time } Log { Signature { Name } } PoolEvent { Dex { ProtocolName ProtocolVersion } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } Liquidity { AmountCurrencyA AmountCurrencyAInUSD AmountCurrencyB AmountCurrencyBInUSD } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Live-pool-liquidity) `AmountCurrencyA` / `AmountCurrencyAInUSD` is the ETH side of the pool (e.g. `141.2` ETH ≈ `$269,852` for FRONG); `AmountCurrencyB` is the token side. The token side's USD value reads `0` for unpriced meme tokens — value the pool from the ETH leg (double it for total TVL in a balanced price range). ### Per-swap slippage `DEXPoolSlippages` reports execution quality per swap — **`SlippageBasisPoints`** plus the trade's price and min-out/max-in bounds. Filter by `PoolId` the same way: ```graphql { EVM(network: robinhood) { DEXPoolSlippages( limit: {count: 10} orderBy: {descending: Block_Time} where: { Price: { Pool: {PoolId: {is: "0xacea8920877840033f0275c37f9b61550b5326917e948bcf8339714d96f9521a"}} } } ) { Block { Time } Price { Dex { ProtocolName } Pool { PoolId CurrencyA { Symbol } CurrencyB { Symbol } } AtoB { Price MaxAmountIn MinAmountOut } SlippageBasisPoints } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Per-swap-slippage) A stream of this filtered to `SlippageBasisPoints: {gt: 100}` is a ready-made "toxic fill" alert for a token's pool. ### Per-transaction balance changes `TransactionBalances` gives each address's **pre- and post-transaction balance** — position tracking without replaying transfers. For a pools.trade token: ```graphql { EVM(network: robinhood) { TransactionBalances( limit: {count: 10} orderBy: {descending: Block_Time} where: { TokenBalance: { Currency: {SmartContract: {is: "0x6245e67affa44a23077f0ea7f981a8dc743a0c47"}} } } ) { Block { Time } Transaction { Hash From } TokenBalance { Address PreBalance PostBalance BalanceChangeReasonCode HasPreBalance TotalSupply Currency { Symbol } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Per-transaction-balance-changes) :::note Check `HasPreBalance` When `HasPreBalance` is `false`, `PreBalance` reads `0` — meaning "unknown", not "zero". Treat the delta as reliable only when `HasPreBalance` is `true`. `PostBalanceInUSD` is `0` for unpriced launch tokens. ::: --- ## Crowd Launch (CCA) auctions A Crowd Launch runs a **continuous clearing auction** in its own contract for ~4 hours before the pool opens. Bidders submit into discrete **price ticks**; the clearing price ratchets up as the book fills, and the auction can end **oversubscribed**. All auction events are **raw**, so query them by topic0. Because each auction has its own contract, filtering on `SignatureHash` alone gives you **every auction on the network at once** — which is usually what you want. ### Detect new Crowd Launch auctions Every Crowd Launch deploys its auction through the **auction factory** `0x000000001f26a0044baa66024e7b6599c61963f8`, which emits `AuctionCreated(address,address,uint256,bytes)`. Stream it to learn each new auction's contract address the moment it exists — then point the bid and clearing-price queries below at that address: ```graphql subscription { EVM(network: robinhood) { Events( where: { LogHeader: {Address: {is: "0x000000001f26a0044baa66024e7b6599c61963f8"}} Log: { Signature: { SignatureHash: {is: "7ede475fad18ccf0039f2b956c4d43a8b4ed0853de4daaa8ae25299f331ae3b9"} } } } ) { Block { Time } Transaction { Hash From } LogHeader { Address Data } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Stream-new-Crowd-Launch-auctions) The launch transaction also contains the token's mint, the entry contract's `TokenCreated`, and the auction's first `TickInitialized` / `ClearingPriceUpdated` events, so one transaction hash links token, creator, and auction contract. ### Every bid across all live auctions ```graphql { EVM(network: robinhood) { Events( limit: {count: 50} orderBy: {descending: Block_Time} where: {Log: {Signature: {Name: {is: "BidSubmitted"}}}} ) { Block { Time Number } Transaction { Hash From } LogHeader { Address } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Crowd-Launch-bids) `BidSubmitted(uint256,address,uint256,uint128)` decodes to four named arguments — `id`, `owner`, `priceQ96` and `amount`. `owner` is the bidder (use it rather than `Transaction.From`, which is whatever contract or router relayed the bid), and `priceQ96` is a Q96 fixed-point price: divide by 2⁹⁶ for a human number. `LogHeader.Address` is the auction contract, which is how you tell the auctions apart — there is no filter needed to span them all. ### Clearing price updates ```graphql { EVM(network: robinhood) { Events( limit: {count: 50} orderBy: {descending: Block_Time} where: { Log: {Signature: {Name: {is: "ClearingPriceUpdated"}}} LogHeader: {Address: {is: "0xD10dc5f79F95E953e710F1eDeBddE0baD2e8fed8"}} } ) { Block { Time } Transaction { Hash } LogHeader { Address } Arguments { Name Value { ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Crowd-Launch-clearing-price) `ClearingPriceUpdated` decodes to `blockNumber` and `clearingPriceQ96`. Drop the `LogHeader.Address` filter to watch every auction at once, or swap the event name for any row in the [event reference](#event-reference) to follow tick initialization (`TickInitialized` → `priceQ96`), the moving book edge (`NextActiveTickUpdated` → `priceQ96`), or auction checkpoints (`CheckpointUpdated` → `blockNumber`, `clearingPriceQ96`, `cumulativeMps`; `AuctionStepRecorded` → `startBlock`, `endBlock`, `mps`). :::note Prices are Q96 fixed-point Clearing, floor, and tick-size prices are **Q96** values. Divide by `2**96` to get a human-readable ratio. ::: --- ## Holders and supply ```graphql { EVM(dataset: combined, network: robinhood) { Holders( limit: {count: 100} orderBy: {descending: Balance_Amount} where: { Currency: {SmartContract: {is: "0x6245e67affa44a23077f0ea7f981a8dc743a0c47"}} Balance: {Amount: {gt: "0"}} } ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` [▶ Run this query in the Bitquery IDE](https://ide.bitquery.io/Pools-trade-Token-holders-and-supply) `dataset: combined` keeps balances current to the head block — on `archive` alone the top-holder balance can lag the chain head by minutes on an actively traded token. :::caution Exclude the PoolManager from holder analytics The **top holder of every pools.trade token is the Uniswap v4 PoolManager** `0x8366a39cc670b4001a1121b8f6a443a643e40951`, because the pool's liquidity is held there. Filter it out before computing holder counts, concentration, or "top wallet" leaderboards, or the pool itself will dominate every result. ::: For circulating supply and market cap, see [Robinhood Token Supply](/docs/blockchain/robinhood/robinhood-token-supply). --- ## Graduation The pools.trade UI shows a **graduation progress** percentage and a *Near graduation* filter. It is computed off-chain as: ```text graduationProgress = fdvUsd / graduationTargetUsd * 100 ``` with a **$50,000 FDV** target for curve launches. Because the v4 pool already exists from block one, crossing 100% does **not** emit a migration event — tokens well past target still report a live-curve status. To reproduce it, take FDV from the `Trading` cube (`Supply { MarketCap }`) and compare against the $50,000 threshold, rather than looking for an on-chain graduation event. Crowd Launch auctions **do** have a discrete terminal state: the auction contract stops accepting bids at `endsAt` and the token transitions to graduated. Track that via the auction's final `CheckpointUpdated` / `ClearingPriceUpdated` events, or by watching for the first `Swap` on the token's v4 pool. --- ## Cross-checking against pools.trade's own API pools.trade exposes an **unauthenticated tRPC API** at `https://pools.trade/api/trpc/` that serves its UI. It is useful for validating numbers you derive from Bitquery (graduation progress, holder counts) and for off-chain-only fields like linked X accounts. Discovered procedures: | Procedure | Input | Returns | | --- | --- | --- | | `curve.listLaunches` | `{sortBy: "volume"}` | Curve launches: FDV, graduation %, holders, creator, X link, pool stats | | `curve.getLaunchByAddress` | `{tokenAddress}` | One launch + price series + recent trades | | `curve.listLaunchesByCreator` | `{creatorAddress}` | A creator's launches | | `curve.searchLaunches` | `{query}` | Token search | | `cca.listAuctions` | `{}` | Live + graduated Crowd Launch auctions with clearing/floor price (Q96), raise, bidders | | `cca.getAuctionByAddress` / `cca.getAuction` | `{tokenAddress}` / `{auctionId}` | One auction's full state | | `cca.getBidsHistoryPage` | `{tokenAddress}` | Paginated bids: bidder, USD amount, tx hash, status | | `cca.getTradesHistoryPage` | `{tokenAddress}` | Paginated post-graduation trades | | `prices.getOhlc` | `{chainId: 4663, address}` | OHLC candles | | `prices.getHistories` / `prices.getTokens` | token list | Price series / spot prices | Calls are GET requests with `?batch=1&input=` in tRPC batch format, e.g. `input={"0":{"tokenAddress":"0x…"}}`. :::caution Treat it as a reference, not a data source This API is undocumented, unversioned, and can change or gain authentication without notice — it exists to serve the pools.trade frontend, and heavy polling will likely get rate-limited or blocked. For production trading systems, index from the chain via the queries in this guide and use the tRPC API only to spot-check. ::: --- ## FAQ ### How do I detect a newly launched pools.trade token? Subscribe to the decoded `TokenCreated` event on **both** entry contracts — `0x0000ffff…19c0` and the still-active original `0x00004c4c…d4e9` — or use the mint-transfer stream for name/symbol/decimals in the same payload. See [Newly launched tokens](#newly-launched-tokens). ### Why can't I filter pools.trade trades by protocol? Because pools.trade tokens trade in **plain Uniswap v4 pools**, they are indexed as `ProtocolFamily: "Uniswap"` / `Protocol: "uniswap_v4"` alongside every other v4 pool on Robinhood. Scope queries by token address instead — see [Top pools.trade tokens](#top-poolstrade-tokens-by-volume). ### Why is my USD volume roughly double what pools.trade shows? `Trading.Trades` returns each leg about twice on Robinhood v4. Deduplicate before summing — see the [caution above](#latest-trades-for-a-poolstrade-token). ### How do I track Crowd Launch bids? Filter `Log.Signature.Name` on `BidSubmitted` and read `Arguments` — `id`, `owner`, `priceQ96` and `amount` all decode. Each Crowd Launch deploys its own auction contract, so filtering on the event alone spans every live auction at once, with `LogHeader.Address` identifying which one. Stay on realtime: archive currently holds no `BidSubmitted` rows. ### Where do I get a token's name, symbol, and image? The entry contract's `TokenCreated(address)` carries only the address. Use the mint-transfer query for name/symbol/decimals, and the **factory's** `TokenCreated` — now decoded — for description, external link and image; both are in [Token metadata](#token-metadata-name-symbol-description-image). ### Is there a bonding-curve contract to query? No. Unlike Flap.sh or Bags.fm, pools.trade has no separate bonding-curve AMM and no `LaunchedToDEX`-style graduation event. Trades hit a real Uniswap v4 pool from the first block. --- ## Next steps - [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) — full trade schema for the network - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) — compare launchpads side by side - [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api) — holder distribution queries - [WebSocket subscriptions](/docs/subscriptions/websockets/) — turn any query above into a live stream --- ## Predict.fun API - BSC Prediction Market Trades, Markets and Settlements URL: https://docs.bitquery.io/docs/examples/prediction-market/predict-fun-api/ Predict.fun prediction market data on BNB Smart Chain: real-time trades, trades by wallet, prices and volume per outcome, new and resolved markets, 5m/15m crypto price rounds, and split, merge and redemption settlements. # Predict.fun API [Predict.fun](https://predict.fun) is a prediction market on BNB Smart Chain. It runs the same contract design as Polymarket v1: a CTF exchange, Gnosis conditional tokens, a neg-risk adapter and a UMA-style question adapter. Bitquery decodes it into the same **PredictionTrades**, **PredictionManagements** and **PredictionSettlements** cubes used for Polymarket, so the queries below work with `EVM(network: bsc)`. **Network:** BSC (`network: bsc`). Part of the [Prediction Market API](../prediction-market-api) lifecycle (Management → Trades → Settlement). :::note Data coverage predict.fun data on BSC is available from **22 Oct 2026** in the real-time dataset. Historical (archive) data is not available yet, so `dataset: archive` returns an error for these cubes on BSC. ::: ## What is different from Polymarket - **Collateral is BSC USDT** (`0x55d398326f99059ff775485246999027b3197955`) with 18 decimals, not USDC. - **Marketplace.ProtocolName** is `predict.fun` and **ProtocolFamily** is `Gnosis_CTF`. - **Yield-bearing exchanges** keep USDT in Venus. Their trades have **ProtocolVersion** `1-yield`. Standard exchanges have `1`. - **Question.MarketId is empty.** Use **Question.Id** or **ConditionId** to identify a market. - **Short crypto markets.** predict.fun runs 5-minute and 15-minute Up/Down markets. Their titles look like `price round: BTC up or down, 5m from 2026-10-26 13:45:00Z`. ## Exchange contracts Trades come from four exchange contracts (`Trade.Prediction.Marketplace.SmartContract`): | Exchange contract | ProtocolVersion | | --- | --- | | `0x8bc070bedab741406f4b1eb65a72bee27894b689` | `1` | | `0x365fb81bd4a24d6303cd2f19c349de6894d8d58a` | `1` | | `0x6beb5a40c032afc305961162d8204cda16decfa5` | `1-yield` | | `0x8a289d458f5a134ba40015085a8f50ffb681b41d` | `1-yield` | Market creation, resolution and settlements are emitted by the conditional-token contracts, for example `0x22da1810b194ca018378464a58f6ac2b10c9d244`. ## predict.fun-only filter Add this to the `where` clause of any query to restrict results to predict.fun: ```graphql Trade: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } ``` For `PredictionManagements` use `Management: { Prediction: { Marketplace: ... } }`, and for `PredictionSettlements` use `Settlement: { Prediction: { Marketplace: ... } }`. --- ## Trades ### Real-time predict.fun trades stream Subscribe to live predict.fun trades on BSC. [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-trades-stream) ```graphql subscription PredictFunTradesStream { EVM(network: bsc) { PredictionTrades( where: { TransactionStatus: { Success: true } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Block { Time } Transaction { Hash From } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId IsOutcomeBuy } Prediction { ConditionId CollateralToken { Symbol SmartContract } OutcomeToken { SmartContract AssetId } Marketplace { SmartContract ProtocolName ProtocolVersion } Question { Title Id CreatedAt } Outcome { Label Index Id } } } } } } ``` The price of a trade is `CollateralAmount / Amount`. Use the `Price` and `PriceInUSD` fields in queries (see below). ### Latest predict.fun trades [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-latest-trades) ```graphql query LatestPredictFunTrades { EVM(network: bsc) { PredictionTrades( limit: { count: 50 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Block { Time } Transaction { Hash } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { ConditionId CollateralToken { Name Symbol SmartContract } OutcomeToken { SmartContract AssetId } Marketplace { SmartContract ProtocolName ProtocolFamily ProtocolVersion } Question { Title Id CreatedAt } Outcome { Label Index Id } } } } } } ``` ### Trades of a wallet A wallet can be the **Buyer** or the **Seller** of a trade. Use `any` to match both. Replace the address with your wallet. [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-wallet-trades) ```graphql query PredictFunWalletTrades { EVM(network: bsc) { PredictionTrades( limit: { count: 100 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } any: [ { Trade: { OutcomeTrade: { Buyer: { is: "0x8a7c3c1b1a3c0a5cdd2490130dd52623cb3eb05d" } } } } { Trade: { OutcomeTrade: { Seller: { is: "0x8a7c3c1b1a3c0a5cdd2490130dd52623cb3eb05d" } } } } ] } ) { Block { Time } Transaction { Hash } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmountInUSD Price IsOutcomeBuy } Prediction { Question { Title Id } Outcome { Label } } } } } } ``` ### Top markets by volume (last 24 hours) [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-top-markets-24h) ```graphql query PredictFunTopMarkets { EVM(network: bsc) { PredictionTrades( limit: { count: 20 } orderBy: { descendingByField: "volume" } where: { TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Trade { Prediction { ConditionId Question { Title Id } } } trades: count volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) } } } ``` ### Volume per exchange contract (last 24 hours) Shows how much volume goes through the standard and yield-bearing exchanges. [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-volume-by-exchange) ```graphql query PredictFunVolumeByExchange { EVM(network: bsc) { PredictionTrades( where: { TransactionStatus: { Success: true } Block: { Time: { since_relative: { hours_ago: 24 } } } Trade: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Trade { Prediction { Marketplace { SmartContract ProtocolVersion } } } trades: count volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) } } } ``` ### Current price of each outcome in a market Returns the latest trade per outcome token. Replace the `ConditionId` with your market. [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-outcome-prices) ```graphql query PredictFunOutcomePrices { EVM(network: bsc) { PredictionTrades( limitBy: { by: Trade_Prediction_OutcomeToken_AssetId, count: 1 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Prediction: { ConditionId: { is: "0x91b57dec0e909ea9f44d00fa5cfdd61575dfac4bc1b3d3c513aa217c5c7828dd" } } } } ) { Block { Time } Trade { OutcomeTrade { Price PriceInUSD } Prediction { Question { Title } Outcome { Label Index } OutcomeToken { AssetId } } } } } } ``` ### Volume and traders per outcome in a market [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-market-volume-per-outcome) ```graphql query PredictFunMarketVolume { EVM(network: bsc) { PredictionTrades( where: { TransactionStatus: { Success: true } Trade: { Prediction: { ConditionId: { is: "0x91b57dec0e909ea9f44d00fa5cfdd61575dfac4bc1b3d3c513aa217c5c7828dd" } } } } ) { Trade { Prediction { Outcome { Label } } } trades: count volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) buyers: uniq(of: Trade_OutcomeTrade_Buyer) } } } ``` --- ## Markets (Managements) ### Latest new markets Lists newly created markets. The `notLike` filter hides the 5m and 15m price rounds, which make up most of the new markets. [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-new-markets) ```graphql query PredictFunNewMarkets { EVM(network: bsc) { PredictionManagements( limit: { count: 20 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Management: { EventType: { is: "Created" } Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } Question: { Title: { notLike: "price round%" } } } } } ) { Block { Time } Transaction { Hash } Management { EventType Prediction { Condition { Id Oracle QuestionId Outcomes { Id Index Label } } Question { Title Id CreatedAt } CollateralToken { Symbol SmartContract } } } } } } ``` ### Latest resolved markets [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-resolved-markets) ```graphql query PredictFunResolvedMarkets { EVM(network: bsc) { PredictionManagements( limit: { count: 20 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Management: { EventType: { is: "Resolved" } Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Block { Time } Transaction { Hash } Management { EventType Prediction { Condition { Id Oracle Outcomes { Label Index } } Question { Title Id } } } } } } ``` ### 5m and 15m BTC price rounds predict.fun opens new Up/Down rounds for crypto prices every few minutes. Filter on the title to get the rounds for one asset. Change `BTC` to `ETH` or another asset. [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-btc-price-rounds) ```graphql query PredictFunBTCRounds { EVM(network: bsc) { PredictionManagements( limit: { count: 20 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Management: { EventType: { is: "Created" } Prediction: { Question: { Title: { includes: "BTC up or down" } } } } } ) { Block { Time } Management { Prediction { Condition { Id Outcomes { Label Index Id } } Question { Title Id } } } } } } ``` Some rounds show a feed id instead of an asset name in the title, for example `price round: feed 0x0003…3f38 up or down, 15m from …`. ### Market event counts (last 24 hours) [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-market-event-counts) ```graphql query PredictFunManagementCounts { EVM(network: bsc) { PredictionManagements( where: { TransactionStatus: { Success: true } Block: { Time: { since_relative: { days_ago: 1 } } } Management: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Management { EventType } count } } } ``` --- ## Settlements Settlements are **Split** (USDT into outcome tokens), **Merge** (outcome tokens back into USDT) and **Redemption** (winning tokens paid out after resolution). ### Latest settlements [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-latest-settlements) ```graphql query PredictFunSettlements { EVM(network: bsc) { PredictionSettlements( limit: { count: 20 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Settlement: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Block { Time } Transaction { Hash } Log { Signature { Name } SmartContract } Settlement { EventType Holder OutcomeTokenIds Amounts { Amount CollateralAmount CollateralAmountInUSD } Prediction { ConditionId CollateralToken { Symbol SmartContract } Question { Title Id } } } } } } ``` ### Redemptions of a wallet Shows payouts a wallet received from resolved markets. Replace the address with your wallet. [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-wallet-redemptions) ```graphql query PredictFunWalletRedemptions { EVM(network: bsc) { PredictionSettlements( limit: { count: 50 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } Settlement: { EventType: { is: "Redemption" } Holder: { is: "0xf29f1d048f138a22ba159f530ac3a7575694b69e" } Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Block { Time } Transaction { Hash } Settlement { EventType Holder Amounts { CollateralAmount CollateralAmountInUSD } Prediction { ConditionId Question { Title } } } } } } ``` ### Settlement counts by type (last 24 hours) [Run in Bitquery IDE](https://ide.bitquery.io/predict-fun-settlement-counts) ```graphql query PredictFunSettlementCounts { EVM(network: bsc) { PredictionSettlements( where: { TransactionStatus: { Success: true } Block: { Time: { since_relative: { days_ago: 1 } } } Settlement: { Prediction: { Marketplace: { ProtocolName: { is: "predict.fun" } } } } } ) { Settlement { EventType } count collateral: sum(of: Settlement_Amounts_CollateralAmountInUSD) } } } ``` ## Related - [Prediction Market API](../prediction-market-api) - [Prediction Trades API](../prediction-trades-api) - [Prediction Managements API](../prediction-managements-api) - [Prediction Settlements API](../prediction-settlements-api) - [Check if a wallet interacted with predict.fun](/docs/blockchain/BSC/bsc-transfers#check-if-an-address-ever-interacted-with-predictfun-usdt--protocol-receivers) --- ## Prediction Market API: Markets, Trades and Settlements URL: https://docs.bitquery.io/docs/examples/prediction-market/prediction-market-api/ One GraphQL API for prediction markets such as Polymarket: market creation and resolution, buy and sell trades, and split, merge and redemption settlements on Polygon. # Prediction Market API The **Prediction Market API** is a **universal** API for querying **market lifecycle events**, **trades**, and **settlements** across prediction markets (e.g. Polymarket). Use it to filter by question title, event type, outcome, collateral token, and more. Additional prediction markets will be supported soon. **Networks:** **Polygon** (`network: matic`) for Polymarket, and **BSC** (`network: bsc`) for [predict.fun](../predict-fun-api). More prediction markets coming soon. ### Lifecycle flow | Stage | Cube | Activities | | -------------- | ----------------------- | -------------------------- | | **Management** | `PredictionManagements` | Market Created / Resolved | | **Trades** | `PredictionTrades` | Buy / Sell outcome tokens | | **Settlement** | `PredictionSettlements` | Split / Merge / Redemption | Flow: **Management** (Created) → **Trades** (Buy/Sell) → **Settlement** (Split/Merge/Redemption) This is a **universal** prediction market API: the same cubes and fields work across supported chains. Use `EVM(network: matic)` for Polygon today; more chains will be added over time. For contract-level and event-based Polymarket data (e.g. OrderFilled, ConditionResolution), see the [Polymarket API](/docs/examples/polymarket-api/) docs. ## Video Tutorial | Polymarket Whale Alerts Telegram Bot (Full Python Tutorial) ## PredictionManagements **PredictionManagements** returns market lifecycle events: **Created** (new market) and **Resolved** (outcome determined). You can filter by question title, event type, and prediction metadata (e.g. image URL, resolution source). For more examples (real-time stream, creations-only and resolutions-only subscriptions, counts), see the [Prediction Market Managements API](../prediction-managements-api) doc. Each event includes: - `EventType`: `"Created"` or `"Resolved"` - **Image** — market image URL (e.g. Polymarket asset) - **ResolutionSource** — URL used to resolve the outcome (e.g. price feed or sports data URL) [Run API](https://ide.bitquery.io/Query-latest-created-resolved-prediction-markets-for-Bitcoin) ```graphql query PredictionManagements { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Transaction_Time } where: { Management: { Prediction: { Question: { Title: { includes: "Bitcoin" } } } } } ) { Transaction { Hash Time } Block { Number } Management { Description EventType Prediction { CollateralToken { Name Symbol Decimals } Condition { Id QuestionId Outcomes { Id Label } } Marketplace { ProtocolName } Question { CreatedAt Id Image MarketId ResolutionSource Title } Outcome { Id Index Label } OutcomeToken { AssetId SmartContract } } } } } } ``` ### Key fields - **Management.EventType** — `"Created"` or `"Resolved"`. - **Management.Prediction.Question** — Title, MarketId, Id, Image, ResolutionSource, CreatedAt. **Title** is useful for filtering (e.g. by keyword like "Bitcoin"). **MarketId** links to full info: `https://gamma-api.polymarket.com/markets/{MarketId}`. **ResolutionSource** can be any URL or source that indicates where the market outcome is resolved (e.g. sports scores, crypto oracles, esports). - **Management.Prediction.Condition** — Id, QuestionId, **Outcomes** (all possible outcomes; usually two: Id, Label). - **Management.Prediction.Outcome** / **OutcomeToken** — For **Resolved**: winning outcome token Id/AssetId; for **Created**: often empty. - **Management.Prediction.CollateralToken** — Name, Symbol (e.g. USDC), Decimals. - **Management.Prediction.Marketplace** — ProtocolName. ## PredictionTrades (Recent Buys) Buy/sell activity on outcome tokens: taker/maker (Buyer/Seller), amounts, and whether the trade is a buy or sell of the outcome. For more examples (real-time stream, trades by market or trader, volume by outcome, current prices), see the [Prediction Market Trades API](../prediction-trades-api) doc. ```graphql query PredictionTrades { EVM(network: matic) { PredictionTrades( limit: { count: 10 } where: { Trade: { OutcomeTrade: { IsOutcomeBuy: true } } } orderBy: { descending: Transaction_Time } ) { Transaction { Hash Time } Block { Hash } Trade { Prediction { CollateralToken { Decimals Name SmartContract Symbol } ConditionId Marketplace { ProtocolName } Outcome { Label Id Index } Question { MarketId CreatedAt Id Image Title } OutcomeToken { Decimals ProtocolName AssetId } } OutcomeTrade { Amount Buyer Seller CollateralAmount IsOutcomeBuy } } } } } ``` ### Key fields - **Trade.OutcomeTrade.IsOutcomeBuy** — `true`: Seller (maker) gives USDC (collateral), Buyer (taker) gives outcome tokens. `false`: Buyer gives USDC (collateral), Seller gives outcome tokens. - **Trade.OutcomeTrade** — Amount, Buyer, Seller, CollateralAmount. - **Trade.Prediction.Question** — MarketId (full info: `https://gamma-api.polymarket.com/markets/{MarketId}`), Title, Id, Image, CreatedAt. - **Trade.Prediction.Outcome** — Label, Id (tokenId), Index (index in Condition.Outcomes; see PredictionManagements). - **Trade.Prediction.CollateralToken** — Token used to pay for the outcome (e.g. USDC): Symbol, Name, Decimals, SmartContract. - **Trade.Prediction.OutcomeToken** — Outcome as a token: AssetId, Decimals, ProtocolName. --- ## PredictionSettlements Split, merge, and redemption of outcome tokens (minting, merging positions, redeeming after resolution). For more examples (real-time stream, whale settlements, top winners, top markets), see the [Prediction Market Settlements API](../prediction-settlements-api) doc. ```graphql query PredictionSettlements { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descending: Transaction_Time } where: { Settlement: { EventType: { in: ["Split", "Merge", "Redemption"] } Prediction: { CollateralToken: { Symbol: { not: "USDC" } } } } } ) { Transaction { Hash Time } Block { Number } Settlement { Holder Amounts { Amount CollateralAmount } EventType OutcomeTokenIds Prediction { CollateralToken { Name Symbol Decimals } ConditionId Marketplace { ProtocolName SmartContract } OutcomeToken { Decimals SmartContract } Question { CreatedAt Id Image MarketId Title ResolutionSource } } } } } } ``` ### Key fields - **Settlement.EventType** — `"Split"`, `"Merge"`, or `"Redemption"`. - **Settlement.OutcomeTokenIds** — Token IDs from Condition.Outcomes. **Split/Merge:** all possible outcome token IDs; **Redemption:** usually all possible values. - **Settlement.Amounts** — Amount, CollateralAmount. - **Settlement.Holder** — Address that receives or sends. - **Settlement.Prediction.CollateralToken** — Token used: for **Split** the sender gives this for OutcomeTokenIds; for **Merge/Redemption** they receive it. Symbol can be e.g. `"USDC"` or `"WCOL"`. - **Settlement.Prediction.Question** — MarketId, Title, Id, Image, ResolutionSource, CreatedAt. - **Settlement.Prediction.OutcomeToken** — Outcome token contract; AssetId is typically empty here. --- ## Prediction Market Managements API URL: https://docs.bitquery.io/docs/examples/prediction-market/prediction-managements-api/ Prediction market management events: real-time streams of market creations and resolutions, latest managements, and created vs resolved counts for 24 hours. # Prediction Market Managements API The **PredictionManagements** API returns **market lifecycle** events for prediction markets (e.g. Polymarket) on Polygon: **Created** (new market) and **Resolved** (outcome determined). Use it to stream live creations and resolutions, list latest events, and count Created vs Resolved over a time window. **Network:** Polygon (`network: matic`). Part of the [Prediction Market API](../prediction-market-api) lifecycle (**Management** → Trades → Settlement). ### Event types | EventType | Description | | ----------- | ----------- | | **Created** | New prediction market created; condition and possible outcomes are set. | | **Resolved** | Market resolved; the winning outcome is determined. | --- ## Key fields - **Management.EventType** — `"Created"` or `"Resolved"`. - **Management.Prediction.Question** — **Title**, **MarketId**, Id, Image, ResolutionSource, CreatedAt. Use **Title** to filter (e.g. by keyword). **MarketId** links to full info: `https://gamma-api.polymarket.com/markets/{MarketId}`. - **Management.Prediction.Condition** — Id, QuestionId, Oracle, **Outcomes** (all possible outcomes for this market: Id, Index, Label). For **Created** events, this lists every outcome the market can settle to. - **Management.Prediction.Outcome** — For **Resolved** events: the **winning** outcome (Id, Index, Label). For **Created**: often empty. - **Management.Prediction.OutcomeToken** — For **Resolved**: token details for the winning outcome (Name, Symbol, **AssetId**, SmartContract). Use this for contract address and asset ID of the winning outcome token. - **Management.Prediction.CollateralToken** — Collateral token (e.g. USDC): Name, Symbol, AssetId, SmartContract. - **Management.Prediction.Marketplace** — ProtocolName, ProtocolFamily, SmartContract. --- --- ## Real-time management stream (creations + resolutions) Subscribe to all prediction market lifecycle events (Created and Resolved) as they occur on Polygon. [Run in Bitquery IDE](https://ide.bitquery.io/Prediction-Managements-subscription-resolutions-creations) ```graphql subscription PredictionManagementsStream { EVM(network: matic) { PredictionManagements { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Latest managements (historical) Fetch the most recent creation and resolution events with full details, ordered by block time. [Run in Bitquery IDE](https://ide.bitquery.io/latest-Prediction-managements-resolutions-creations) ```graphql query LatestPredictionManagements { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Created vs Resolved count (last 24 hours) Count how many **Created** and **Resolved** events occurred in the last 24 hours. Use the **Log.Signature.Name** or **Management.EventType** in the response to distinguish them. [Run in Bitquery IDE](https://ide.bitquery.io/last-24-hr-resolution-and-ceated-count) ```graphql query CreatedResolvedCountLast24h { EVM(network: matic) { PredictionManagements( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { EventType } count } } } ``` --- ## Real-time market creations (subscription) Subscribe only to **Created** events so you can track new markets as they are created. For each creation, the full list of possible outcomes for that market is available under **Prediction.Condition.Outcomes** (Id, Index, Label for each outcome). [Run in Bitquery IDE](https://ide.bitquery.io/track-realtime-new-polymarket-creations) ```graphql subscription RealtimeMarketCreations { EVM(network: matic) { PredictionManagements(where: { Management: { EventType: { is: "Created" } } }) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Real-time market resolutions (subscription) Subscribe only to **Resolved** events. For each resolution, the **winning outcome** is given in **Prediction.Outcome** (Id, Index, Label). Token-level details for that outcome—such as **AssetId** and **SmartContract**—are in **Prediction.OutcomeToken**. [Run in Bitquery IDE](https://ide.bitquery.io/track-realtime-polymarket-resolutions) ```graphql subscription RealtimeMarketResolutions { EVM(network: matic) { PredictionManagements(where: { Management: { EventType: { is: "Resolved" } } }) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Latest market creations (query) Fetch the most recent **Created** events. For each market, all possible outcomes are listed under **Prediction.Condition.Outcomes**. [Run in Bitquery IDE](https://ide.bitquery.io/latest-polymarket-creations) ```graphql query LatestMarketCreations { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Created" } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` --- ## Latest market resolutions (query) Query that returns the 10 most recent **Resolved** events. The winning outcome is in **Prediction.Outcome**; **Prediction.OutcomeToken** holds the asset ID and contract details for that outcome. [Run in Bitquery IDE](https://ide.bitquery.io/latest-polymarket-resolutions_1) ```graphql query LatestMarketResolutions { EVM(network: matic) { PredictionManagements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Management: { EventType: { is: "Resolved" } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Management { Description EventType Prediction { CollateralToken { Name SmartContract Symbol AssetId } Condition { Id Oracle Outcomes { Id Index Label } QuestionId } Marketplace { ProtocolName ProtocolFamily SmartContract } Outcome { Id Index Label } OutcomeToken { Symbol SmartContract Name AssetId } Question { CreatedAt Id Image MarketId ResolutionSource Title } } } Transaction { From Hash } } } } ``` For trades on outcome tokens, see [Prediction Market Trades API](../prediction-trades-api). For settlements (split, merge, redemption), see [Prediction Market Settlements API](../prediction-settlements-api). --- ## Prediction Market Settlements API URL: https://docs.bitquery.io/docs/examples/prediction-market/prediction-settlements-api/ Prediction market settlements: real-time and historical redemptions, merges and splits, whale settlements, top winners, top markets and top redeemers. # Prediction Market Settlements API The **PredictionSettlements** API returns **Split**, **Merge**, and **Redemption** events for prediction markets (e.g. Polymarket) on Polygon. Use it to stream live settlements, list latest activity, count events by type, find large redemptions (whales), and rank top winners or top markets by redeemed amount. **Network:** Polygon (`network: matic`). Part of the [Prediction Market API](/docs/examples/prediction-market/prediction-market-api) lifecycle (Management → Trades → **Settlement**). ### Event types | EventType | Description | | -------------- | -------------------------------------------------------------------------- | | **Split** | Collateral converted into outcome tokens (minting). | | **Merge** | Outcome tokens converted back to collateral. | | **Redemption** | After resolution: winning outcome tokens redeemed for collateral (payout). | --- ## Key fields - **Settlement.EventType** — `"Split"`, `"Merge"`, or `"Redemption"`. - **Settlement.OutcomeTokenIds** — Token IDs from the condition. **Split/Merge:** all outcome token IDs; **Redemption:** typically all (redeemer holds winning outcome). - **Settlement.Amounts** — **Amount** (outcome token amount), **CollateralAmount**, **AmountInUSD**, **CollateralAmountInUSD**. - **Settlement.Holder** — Address that receives or sends tokens/collateral. - **Settlement.Prediction.CollateralToken** — Collateral token (e.g. USDC): Name, Symbol, AssetId, SmartContract. - **Settlement.Prediction.Question** — **Title**, MarketId, Id, Image, ResolutionSource, CreatedAt. Use **Title** to filter by market (e.g. specific question). - **Settlement.Prediction.Outcome** — Id, Index, Label (winning outcome on Redemption). - **Settlement.Prediction.Marketplace** — ProtocolName, ProtocolFamily, SmartContract. - **Settlement.Prediction.OutcomeToken** — Outcome token contract: Name, Symbol, AssetId, SmartContract. --- --- ## Real-time settlement stream Subscribe to live Split, Merge, and Redemption events as they occur on Polygon. [Run in Bitquery IDE](https://ide.bitquery.io/realtime-predicion-market-settlements-stream) ```graphql subscription PredictionSettlementsStream { EVM(network: matic) { PredictionSettlements { Block { Time } Log { Signature { Name } SmartContract } Settlement { Amounts { Amount AmountInUSD CollateralAmount CollateralAmountInUSD } EventType Holder OutcomeTokenIds Prediction { CollateralToken { Name Symbol AssetId SmartContract } ConditionId OutcomeToken { Name Symbol AssetId SmartContract } Marketplace { SmartContract ProtocolFamily ProtocolName } Question { Title MarketId ResolutionSource Image CreatedAt Id } Outcome { Id Index Label } } } Transaction { Hash } } } } ``` --- ## Latest settlements (historical) Fetch the most recent settlements with full details, ordered by block time. [Run in Bitquery IDE](https://ide.bitquery.io/latest-prediction-market-settlements_2) ```graphql query LatestPredictionSettlements { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Log { Signature { Name } SmartContract } Settlement { Amounts { Amount AmountInUSD CollateralAmount CollateralAmountInUSD } EventType Holder OutcomeTokenIds Prediction { CollateralToken { Name Symbol AssetId SmartContract } ConditionId OutcomeToken { Name Symbol AssetId SmartContract } Marketplace { SmartContract ProtocolFamily ProtocolName } Question { Title MarketId ResolutionSource Image CreatedAt Id } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` --- ## Redemption / Merge / Split count (last 1 hour) Count how many settlement events occurred in the last hour, grouped by event signature (Split, Merge, Redemption). [Run in Bitquery IDE](https://ide.bitquery.io/redemptions-merge-split-count-in-last-1-hour) ```graphql query RedemptionsMergeSplitCount { EVM(network: matic) { PredictionSettlements( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { count Log { Signature { Name } } } } } ``` --- ## Latest whale settlements (large redemptions) Find the most recent high-value redemptions (e.g. amount ≥ 10,000 USD). Useful for tracking large payouts and whale activity. [Run in Bitquery IDE](https://ide.bitquery.io/latest-whale-settlements-on-prediction-market_2) ```graphql query MyQuery { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Settlement: { EventType: { is: "Redemption" } Amounts: { CollateralAmountInUSD: { ge: "10000" } } } } ) { Block { Time } Log { Signature { Name } SmartContract } Settlement { Amounts { Amount AmountInUSD CollateralAmount CollateralAmountInUSD } EventType Holder OutcomeTokenIds Prediction { CollateralToken { Name Symbol AssetId SmartContract } ConditionId OutcomeToken { Name Symbol AssetId SmartContract } Marketplace { SmartContract ProtocolFamily ProtocolName } Question { Title MarketId ResolutionSource Image CreatedAt Id } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` --- ## Top 10 winners of a specific market question Rank holders by total redeemed amount USD for one market (filter by question title). Replace the title with your market question. [Run in Bitquery IDE](https://ide.bitquery.io/top-10-winners-of-a-market-question_1) ```graphql query MyQuery { EVM(network: matic) { PredictionSettlements( limit: {count: 10} orderBy: {descendingByField: "redeemed_amount"} where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Settlement: {EventType: {is: "Redemption"}, Prediction: {Question: {Title: {is: "Will Trump nominate Judy Shelton as the next Fed chair?"}}}}} ) { Settlement { Holder } redeemed_amount: sum(of: Settlement_Amounts_CollateralAmountInUSD selectWhere:{gt:"0"}) count } } } ``` --- ## Top 10 market questions by redeemed amount (last 1 hour) Aggregated redemptions by market question and sort by total redeemed amount. Use this to see which markets had the most payout activity recently. [Run in Bitquery IDE](https://ide.bitquery.io/top-10-market-questions-in-last-1-hour_2) ```graphql query MyQuery { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descendingByField: "redeemed_amount" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Settlement: { EventType: { is: "Redemption" } } } ) { Settlement { Prediction { Question { Title } Outcome { Label } } } count(distinct:Settlement_Holder) redeemed_amount: sum(of: Settlement_Amounts_CollateralAmountInUSD) } } } ``` --- ## Top 10 redeemers (last 1 hour) Rank addresses by total amount redeemed in the last hour across all markets. Useful for leaderboards and whale tracking. [Run in Bitquery IDE](https://ide.bitquery.io/top-10-redeemers) ```graphql query TopRedeemers { EVM(network: matic) { PredictionSettlements( limit: { count: 10 } orderBy: { descendingByField: "redeemed_amount" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Settlement: { EventType: { is: "Redemption" } } } ) { Settlement { Holder } redeemed_amount: sum(of: Settlement_Amounts_Amount) } } } ``` --- ## Use cases | Use case | Approach | | ---------------------------------- | ------------------------------------------------------------------------------------------------ | | **Live settlement feed** | Use the real-time subscription above. | | **Recent activity** | Use _Latest settlements_ with `limit` and `orderBy: { descending: Block_Time }`. | | **Volume by event type** | Use _Redemption/Merge/Split count_ with a time window. | | **Large payouts** | Use _Latest whale settlements_ with `Amounts.Amount: { ge: "..." }` and `EventType: Redemption`. | | **Winners for one market** | Use _Top 10 winners of a market question_ with `Question.Title: { is: "..." }`. | | **Hottest markets by redemptions** | Use _Top 10 market questions by redeemed amount_. | | **Top redeemers** | Use _Top 10 redeemers_ (optionally change `hours_ago` or add more filters). | For market creation and resolution events, see [PredictionManagements](/docs/examples/prediction-market/prediction-market-api#predictionmanagements). For trades, see [PredictionTrades](/docs/examples/prediction-market/prediction-market-api#predictiontrades-recent-buys). --- ## Prediction Market Trades API URL: https://docs.bitquery.io/docs/examples/prediction-market/prediction-trades-api/ Prediction market trades: real-time trade stream, latest trades, trades by market or trader, Yes/No volume, and current price per outcome. # Prediction Market Trades API The **PredictionTrades** API returns **buy/sell** activity on outcome tokens for prediction markets (e.g. Polymarket) on Polygon. Use it to stream live trades, list latest activity, filter by market or trader, compute volume per outcome, and get current prices per outcome from the latest trade. **Network:** Polygon (`network: matic`). Part of the [Prediction Market API](../prediction-market-api) lifecycle (Management → **Trades** → Settlement). ### Trade direction - **IsOutcomeBuy: true** — Seller (maker) gives USDC (collateral), Buyer (taker) gives outcome tokens. - **IsOutcomeBuy: false** — Buyer gives USDC (collateral), Seller gives outcome tokens. ## Key fields - **Trade.OutcomeTrade.IsOutcomeBuy** — `true`: Seller gives collateral (USDC), Buyer gives outcome tokens; `false`: Buyer gives collateral, Seller gives outcome tokens. - **Trade.OutcomeTrade** — **Buyer**, **Seller**, **Amount** (outcome tokens), **CollateralAmount**, **CollateralAmountInUSD**, **OrderId**, **Price**, **PriceInUSD**. - **Trade.Prediction.Question** — **Title**, **MarketId**, Id, Image, ResolutionSource, CreatedAt. Use **MarketId** to filter by market (e.g. `"1391179"`). Full info: `https://gamma-api.polymarket.com/markets/{MarketId}`. - **Trade.Prediction.Outcome** — **Label**, Id, Index. - **Trade.Prediction.CollateralToken** — Token used to pay for the outcome (e.g. USDC): Name, Symbol, SmartContract, AssetId. - **Trade.Prediction.OutcomeToken** — Outcome as a token: Name, Symbol, SmartContract, **AssetId** (use for volume/price per outcome). - **Trade.Prediction.Marketplace** — ProtocolName, ProtocolFamily, SmartContract, ProtocolVersion. --- --- ## Polymarket-only filter {#polymarket-only-filter} To restrict results to **Polymarket** only, add this to your `where` clause: ```graphql Trade: { Prediction: { Marketplace: { ProtocolName: { is: "polymarket" } } } } ``` Example: real-time stream for Polymarket only — use the [real-time trades stream](#real-time-trades-stream) query and add the filter above inside `PredictionTrades(where: { ... })`. ## Real-time trades stream Subscribe to live prediction market trades as they occur on Polygon (successful transactions only). [Run in Bitquery IDE](https://ide.bitquery.io/prediction-market-trades-subscription) ```graphql subscription PredictionTradesStream { EVM(network: matic) { PredictionTrades(where: { TransactionStatus: { Success: true } }) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` ## Latest Prediction Market trades API Fetch the most recent prediction market trades with full details, ordered by block time. [Run in Bitquery IDE](https://ide.bitquery.io/latest-prediction-market-trades) ```graphql query LatestPredictionTrades { EVM(network: matic) { PredictionTrades( limit: { count: 50 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` ## Stream Trades for a specific market Subscribe to trades for one market only by filtering on **Question.MarketId**. Replace `"1391179"` with your market ID. [Run in Bitquery IDE](https://ide.bitquery.io/subscribe-to-specific-market-trades) ```graphql subscription TradesForSpecificMarket { EVM(network: matic) { PredictionTrades( where: { TransactionStatus: { Success: true } Trade: { Prediction: { Question: { MarketId: { is: "1391179" } } } } } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` ## Trades for a specific trader Fetch all trades where the given address is either **Buyer** or **Seller**. Pass the trader address as the `$trader` variable. [Run in Bitquery IDE](https://ide.bitquery.io/Trades-for-a-specific-trader) ```graphql query TradesForTrader($trader: String) { EVM(network: matic) { PredictionTrades( limit: { count: 50 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: true } any: [ { Trade: { OutcomeTrade: { Buyer: { is: $trader } } } } { Trade: { OutcomeTrade: { Seller: { is: $trader } } } } ] } ) { Block { Time } Call { Signature { Name } } Log { Signature { Name } SmartContract } Trade { OutcomeTrade { Buyer Seller Amount CollateralAmount CollateralAmountInUSD OrderId Price PriceInUSD IsOutcomeBuy } Prediction { CollateralToken { Name Symbol SmartContract AssetId } ConditionId OutcomeToken { Name Symbol SmartContract AssetId } Marketplace { SmartContract ProtocolVersion ProtocolName ProtocolFamily } Question { Title ResolutionSource Image MarketId Id CreatedAt } Outcome { Id Index Label } } } Transaction { From Hash } } } } ``` **Variables (example):** ```json { "trader": "0x101f2f96db1e39a9f36a1fa067751d541fd38e1a" } ``` ## Total volume and Yes/No volume for a market Aggregate USD volume for a market over a time window: total volume plus volume per outcome. Many markets have **two outcomes** (e.g. Yes/No, Up/Down); this example uses a **Yes/No** market, so we split volume by outcome label "Yes" and "No". Pass the market’s outcome token **AssetId**s in `$marketAssets` (typically two: one per outcome). [Run in Bitquery IDE](https://ide.bitquery.io/total-volume-outcome-1-volume-outcome-2-volume-of-a-market) ```graphql query MarketVolumeByOutcome($marketAssets: [String!]) { EVM(network: matic) { PredictionTrades( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } TransactionStatus: { Success: true } Trade: { Prediction: { OutcomeToken: { AssetId: { in: $marketAssets } } } } } ) { Trade { Prediction { Question { Title ResolutionSource Image MarketId Id CreatedAt } } } yes_volume: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { Prediction: { Outcome: { Label: { is: "Yes" } } } } } ) no_volume: sum( of: Trade_OutcomeTrade_CollateralAmountInUSD if: { Trade: { Prediction: { Outcome: { Label: { is: "No" } } } } } ) total_volume: sum(of: Trade_OutcomeTrade_CollateralAmountInUSD) } } } ``` **Variables (example):** ```json { "marketAssets": [ "46746822541461330721074821991383617225657173789584499857683753079229786702095", "70771354585365381988139008309072205730081182435161568795508496003376222185889" ] } ``` ## Current price per outcome (latest trade) Get the latest trade price for each outcome in a market (e.g. Yes/No, Up/Down—each market defines its own outcome labels). Uses `limitBy` so you get one row per outcome (by `Trade_Prediction_OutcomeToken_AssetId`), with **Price** and **PriceInUSD** taken at the maximum block time (most recent). The response includes **Outcome.Label** so you can see which outcome each price refers to. [Run in Bitquery IDE](https://ide.bitquery.io/Current-price-inside-the-market-for-all-options-based-on-latest-trade) ```graphql query CurrentPricePerOutcome { EVM(network: matic) { PredictionTrades( limitBy: { by: Trade_Prediction_OutcomeToken_AssetId, count: 1 } where: { TransactionStatus: { Success: true } Trade: { Prediction: { Question: { MarketId: { is: "1391179" } } } } } ) { Trade { OutcomeTrade { Price(maximum: Block_Time) PriceInUSD(maximum: Block_Time) } Prediction { OutcomeToken { Name AssetId } Outcome { Id Label } } } } } } ``` For market creation and resolution, see [PredictionManagements](../prediction-market-api#predictionmanagements). For settlements (split, merge, redemption), see [Prediction Market Settlements API](../prediction-settlements-api). --- ## Price Index Algorithm URL: https://docs.bitquery.io/docs/trading/crypto-price-api/price-index-algorithm/ How the Bitquery Price Index turns DEX trades into pool, token and currency prices, what the Ranking and Verdict fields mean, and which price field to read. # Price Index Algorithm ## What it is The Price Index is the engine behind the Crypto Price API. It turns DEX trades into one price per pool, blends the pools of a token into one token price per chain, and blends a currency's tokens across chains into one currency price. This page explains the three levels well enough to read the fields they produce. It does not describe the internal rules or their thresholds. Three levels: trades make a pool price, pools blend into a token price, tokens blend into a currency price ## How to get it The index is not a separate cube. Its outputs are the price and ranking fields on the `Trading` cubes, in queries, subscriptions and on the `trading.prices` Kafka topic. | Level | Cube | One row is | | --- | --- | --- | | Pool | `Trading.Pairs` | one pool on one market, for one interval | | Token | `Trading.Tokens` | one token on one chain, all its pools blended | | Currency | `Trading.Currencies` | one asset across chains, all its tokens blended | | Group | `Trades` | `Pairs` | `Tokens` | `Currencies` | | --- | --- | --- | --- | --- | | `Ranking { Position Weight }` | yes | yes | yes | – | | `RankingDetail { Verdict StaleMultiplier }` | – | yes | yes | – | | `Liquidity { Usd Source RealShare … }` | – | yes (one pool) | yes (summed) | yes (summed) | | `LeadingPool { MarketId PoolAddress QuoteTokenId }` | – | – | yes | – | `Pairs` filtered to `Ranking: { Position: { eq: 1 } }` returns the pool that leads a token's blend. See [Getting the Most Accurate Token Price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). ## How it is derived ### Pool: from trades to a price {#how-a-pool-price-is-calculated} Trades in a pool become one pool price: drop bad prints, average by size, convert to USD - **Orientation.** One side of the pool is base, the other quote. Stablecoins and native tokens are preferred as quote, so a memecoin/WSOL pool prices the memecoin in WSOL. The rules are in [Breaking Down Price Streams in Detail](/docs/trading/crypto-price-api/in-depth). - **Bad prints are dropped.** Zero-amount trades, trades below the token's precision, and legs of a self-sandwich do not count. Trades of negligible USD value count toward volume but not price. - **The price is the pool's spot.** Each trade is priced at what the pool's curve moved to, with the pool fee excluded where the venue reports it inside the input. Chart sites show the price the trader paid, fee included, so on a pool with a 1 % fee the two differ by about 1 % in the direction of the last trade. The trader's price is still on every `Trading.Trades` row from its `Amounts`. - **Trades are averaged by size** into one pool price per block. The candle open, high, low and close come from the individual trades. - **USD** is the quote-denominated price times the quote currency's own index price. A pool whose quote has no USD price carries a price in quote tokens only. ### Token: from pools to a price {#how-token-prices-are-determined} From pools to one token price: each pool's share of liquidity is its weight, pool prices are averaged by weight Every pool where the token is base is a part of the token. Each part gets a weight, each part gets a verdict, and the token price is the average of the accepted parts' prices by weight. - **Weight** is the pool's share of the token's liquidity, discounted for staleness. Liquidity is the measured reserve where the index can read it and an estimate otherwise ([Liquidity fields](/docs/trading/crypto-price-api/liquidity-fields)). A pool that stops trading keeps its liquidity but loses weight the longer it stays quiet. This is `Ranking.Weight`; `Ranking.Position` orders the pools by it. - **Verdict** says what the blend did with the pool's price. `priced` is accepted as is. `clamped` is accepted but pulled toward the other pools. `outlier` is rejected, price and volume. `ineligible` is a pool with too little money or history: its volume counts, its price does not. `retired` is a launch curve the token has left. `no_price` is a pool with nothing to price. This is `RankingDetail.Verdict`. - **Launch curves.** While a token trades only on its bonding curve, the curve is its price. Once it graduates to a real pool, the curve is retired for that token and never votes again, so its frozen price cannot drag the blend. - **One pool.** A token with one pool has nothing to blend: that pool's price is the token's, at `Position` 1 and `Weight` 1. ### Currency: from tokens to a price {#how-currency-prices-are-determined} The same blend one level up. A non-stablecoin currency such as `bid:bitcoin` is made of its token representations across chains (WBTC, cbBTC and so on), each weighted by that token's liquidity. `Ranking` is not exposed on `Currencies`. Stablecoins skip the trade-based path: their price comes from an external spot source. At currency level they carry no `Liquidity` and no `Supply`. ## Which price to read {#which-price-to-read} | Field | What it is | Use it for | | --- | --- | --- | | `Price.Ohlc.Close` | The last accepted trade of the interval. | Candles, charts, last traded price. | | `Price.Average.Estimate` | The valuation price: smoothed over recent short intervals, so one spike moves it a little and a sustained move captures it fully. | Market cap, portfolio value. `MarketCap` is `Estimate` × supply. | | `Price.Average.Mean` | Size-weighted mean of the interval's trades. | VWAP over the bar. | | `PriceInUsd` on `Trading.Trades` | That trade's own price times the quote token's USD rate. Not the blended token price. | Per-swap accounting, PnL. | | `PoolPrice` on `Pairs` | The pool curve's marginal quote after the last swap. | Routing, slippage. See [PoolPrice fields](/docs/trading/crypto-price-api/pool-price-fields). | ## Fields {#ranking-on-trades-pairs-and-tokens} `Ranking` is exposed on `Trades`, `Pairs` and `Tokens`. | Field | Type | Meaning | | --- | --- | --- | | `Ranking.Position` | Int | 1-based priority among the parts of a blend: the pool among a token's pools, or the token among a currency's tokens. Lower is higher priority. | | `Ranking.Weight` | Float | This part's share of the blend, in `[0, 1]`. Weights across a token's pools sum to 1. | `RankingDetail { Verdict StaleMultiplier }`, `LeadingPool` and every `Liquidity` field are documented in [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields). ## Examples ### Which pools set a token's price? Filter `Pairs` on `Ranking.Position` to keep only the top contributors (positions 1, 2 and 3 here). `Weight` is normally read, not filtered. ```graphql { Trading { Pairs( where: { Ranking: { Position: { in: [1, 2, 3] } } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } limit: { count: 10 } ) { Block { Time(maximum: Block_Time) } Currency { Id } Token { Id } QuoteToken { Id } Market { Id Protocol Address } Price { Ohlc { Close } } Ranking { Position Weight } Interval { Time { Start End } } } } } ``` - `Position: 1` is the pool with the largest liquidity-weighted share, not the one with the most trades. - Add `Token: { Id: { is: "bid:solana:So11111111111111111111111111111111111111112" } }` to see one token's pools and check that their `Weight` values sum to about 1. - Add `RankingDetail { Verdict StaleMultiplier }` to see why each pool got its rank. ## Pitfalls - **Our close is not DEX Screener's close on high-fee pools.** We publish the pool's spot; chart sites publish the price the trader paid, fee included. - **`Estimate` is not the close.** It is smoothed. Use `Ohlc.Close` for the last trade and `Estimate` for valuation. - **Rejected pools still have rows.** An `outlier` or `ineligible` pool keeps its `Pairs` row and `Position`. Filter on `RankingDetail.Verdict` for the pools the price actually uses. - **Do not apply `StaleMultiplier` again.** `Weight` already includes it. - **History before 2026-10-19 is volume-weighted.** `Liquidity` fields are `0` on those rows and `Weight` follows traded volume. Do not compare weights across the cutover. - **`Volume.Quote` is not USD.** It is the sum of quote-token amounts. Use `Volume.Usd`. ## Related - [Liquidity, RankingDetail and LeadingPool fields](/docs/trading/crypto-price-api/liquidity-fields) - [Getting the Most Accurate Token Price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) - [Tokens cube](/docs/trading/crypto-price-api/tokens) - [Breaking Down Price Streams in Detail](/docs/trading/crypto-price-api/in-depth) for base and quote selection - [Crypto Price API](/docs/trading/crypto-price-api/) --- ## Private Queries in the Bitquery IDE: Who Can See a Saved Query URL: https://docs.bitquery.io/docs/ide/private/ Save a query privately in the Bitquery IDE so only your account can open it, what changes for sharing and search, and how it still runs from code. # Private Queries in the Bitquery IDE: Who Can See a Saved Query A saved query in the [Bitquery IDE](https://ide.bitquery.io) is public by default: it gets a URL under `ide.bitquery.io`, shows up in [IDE search](/docs/ide/search/), and anyone with the link can open and run it. Tick **Private** before you click **Save** and the query is visible to your account only. It still has a URL, but opening it from another account or without signing in shows nothing, and it stays out of search. Privacy applies to the saved text and its variables, not to the data: a private query runs against the same API with your token, like any other. ![IDE Query Save Private](/img/ide/query_save_private.png) ## When to save privately - Queries with client wallets, deal-specific token lists or internal addresses in the filters. - Drafts you are still shaping; publish once the example is worth finding. - Anything wired into an internal dashboard or alert whose logic you would rather not expose. Leave the box unchecked for examples you want colleagues or the community to find; public queries are how most of the examples in these docs are shared. ## Using a private query from code The IDE is a place to write and test; your application sends the query text itself. Copy the query from the IDE into your code, or export it from the IDE's code panel for your language, and call `https://streaming.bitquery.io/graphql` with your access token. Nothing about a private save changes the request; the token, not the save state, decides what your code can read. See [how to generate a token](/docs/authorization/how-to-generate/) and [how to use it](/docs/authorization/how-to-use/). ## Changing your mind Open the query, change the checkbox and save again. Making a public query private removes it from search and from other accounts; making a private one public exposes the current text, so check it for addresses first. Deleting a query removes it for everyone who had the link. ## Next steps - [Create a query](/docs/ide/query/) - [Search queries](/docs/ide/search/) - [Share a query](/docs/ide/share/) --- ## Pump.fun API (Pump Fun): Trades, Prices, OHLCV, New Launches URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/ Pump.fun API for Solana: query Pump.fun trades, new launches, prices, OHLCV, bonding curves and graduations over GraphQL, WebSocket, gRPC and Kafka. # Pump.fun API (Pump Fun): Trades, Prices, OHLCV, New Launches The Bitquery PumpFun API reads Pump.fun activity from the Solana chain: live trades, new token launches, prices and OHLCV, bonding curve progress, graduations to PumpSwap, holders and top traders, over GraphQL, WebSocket, gRPC and Kafka, filtered by the Pump.fun program address `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`. This page is its query reference. Pump.fun itself does not run a hosted data API. It publishes program documentation and IDLs for its on-chain programs on GitHub ([pump-public-docs](https://github.com/pump-fun/pump-public-docs)), and the hosts its web app calls are undocumented, so there is no supported endpoint for trades, prices, candles or new launches. Every query runs as written in the [Bitquery IDE](https://ide.bitquery.io). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. Delivery options, latency and pricing are on the [pricing and plans page](https://bitquery.io/products/pumpfun-api). :::tip Want structured trades, OHLC and market cap? Start with the Trading API The [**Trading API**](/docs/trading/trading-data-overview) is the fastest path to clean Pump.fun market data. [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns **MEV-filtered swaps with USD price, market cap and supply on every row**, across **10 chains in one API**, and [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) gives pre-aggregated OHLC down to one second, so you never build candles yourself. Worked Pump.fun examples are in [Trader-Focused Trade APIs](#trader-focused-trade-apis-with-usd-price-market-cap--supply) below. Reach for the raw chain-level queries on this page when you need what the Trading API deliberately does not carry: **history older than the Trading window**, **bonding-curve internals**, per-instruction detail, or call / event context. ::: :::info Need Pump.fun historical data as files? For backtests and research, download **[Pump.fun historical data](https://bitquery.io/datastore/datasets/pumpfun)** from the Bitquery Data Store: every bonding-curve trade, token creation, migration and per-token OHLCV as Parquet, with a free sample. Narrower Pump.fun datasets cover [token launches and creators](https://bitquery.io/datastore/datasets/pumpfun-token-registry), [7-day token outcomes](https://bitquery.io/datastore/datasets/pumpfun-token-outcomes), [early buyers](https://bitquery.io/datastore/datasets/pumpfun-early-buyers) and [dev wallet funding](https://bitquery.io/datastore/datasets/pumpfun-creator-funding). ::: For data points not covered here, ask [support](https://t.me/Bloxy_info). :::tip **Try Our PumpFun Token Sniffer** Want to screen Pump.fun mints for phishing risk? Check out our [**PumpFun Token Sniffer**](https://pumpfun-token-sniffer.vercel.app/), a proof-of-concept tool that helps identify suspicious token behavior by analyzing transfers and trades. ::: Need zero-latency Pump.fun data? [Read about our Shred Streams and contact us for a trial](/docs/streams/real-time-solana-data/). For gRPC streaming, see [Pump.fun gRPC Streams →](/docs/grpc/solana/examples/pump-fun-grpc-streams/). You may also be interested in: - [LetsBonk.fun APIs ➤](/docs/blockchain/Solana/letsbonk-api/) - [StonkFun APIs ➤](/docs/blockchain/Solana/stonkfun-api/) - [Pump.fun Creator Rewards API ➤](/docs/blockchain/Solana/Pumpfun/pump-fun-creator-rewards-api/): creator fees, unclaimed balances, fee sharing and CTO changes - [Pump.fun Holder Rewards and Cashback API ➤](/docs/blockchain/Solana/Pumpfun/pump-fun-holder-rewards-api/): holder rewards coins, payouts and cashback claims - [PumpSwap APIs ➤](/docs/blockchain/Solana/Pumpfun/pump-swap-api/) - [Moonshot APIs ➤](/docs/blockchain/Solana/Moonshot-API/) - [FourMeme APIs ➤](/docs/blockchain/BSC/four-meme-api/) - [Solana Token Price API ➤](/docs/blockchain/Solana/solana-token-price-api): latest price and OHLC for graduated Pump.fun tokens and any other SPL token - [DEXrabbit Pump.fun category](https://dexrabbit.bitquery.io/categories/pump-fun): live multi-chain DEX prices and 24h volume :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## What is the Program Address for Pump.fun on Solana? The Pump.fun program address on Solana mainnet is `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`. Use Bitquery's GraphQL API to filter DEX trades, mintn creation, and bonding curve data by this program ID. ``` 6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P ``` Use this program ID when filtering Solana instructions or supply updates for Pump.fun mints. All examples below reference this program. For bonding curve data, token creation, and migration tracking, use the queries in this guide with `Program: { Address: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } }`. Mints that complete the bonding curve graduate to PumpSwap, pump.fun's own AMM, at program address `pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA` (see the [PumpSwap API page](/docs/blockchain/Solana/Pumpfun/pump-swap-api/)). In the trade cubes the two venues appear as `Dex.ProtocolName` `pump` for the bonding curve and `pump_amm` for PumpSwap (family `Pumpswap`). Curve mints trade for hours, not months, so the examples here that need a market still alive when you read them use PUMP (`pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn`), pump.fun's own token, which trades on PumpSwap. For a token still on the curve, switch the filter to `pump` and take a live mint from [tokens traded in the last hour](#how-do-i-get-all-tokens-traded-on-pumpfun-in-the-last-1-hour). ## Token Creation & Metadata ### How do I get newly created Pump.fun tokens? Subscribe to `TokenSupplyUpdates` filtered by the Pump.fun program's `create` or `create_v2` method for metadata, supply and dev address as each mint appears. [New Pump.fun mints: run it ➤](https://ide.bitquery.io/newly-created-PF-token-dev-address-metadata_8)
Show the GraphQL ```graphql subscription { Solana { TokenSupplyUpdates( where: { Instruction: { Program: { Address: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } Method: { in: ["create", "create_v2"] } } } } ) { Block { Time } Transaction { Signer } TokenSupplyUpdate { Amount Currency { Symbol ProgramAddress PrimarySaleHappened Native Name MintAddress MetadataAddress Key IsMutable Fungible EditionNonce Decimals Wrapped VerifiedCollection Uri UpdateAuthority TokenStandard } PostBalance } } } } ```
### How do I get creation time and dev address of a Pump.fun token? [Try Pump.Fun Dev Address & Creation Time Query ➤](https://ide.bitquery.io/PumpFun-Token-creation-time--creator_2)
Show the GraphQL ```graphql query MyQuery { Solana(network: solana) { Instructions( where: { Instruction: { Accounts: { includes: { Address: { is: "token mint address" } } } Program: { Name: { is: "pump" } Method: { in: ["create", "create_v2"] } } } } ) { Block { Time } Transaction { Signer Signature } Instruction { Accounts { Address } } } } } ```
### How do I monitor Pump.fun new token launches in real time? Use Bitquery's GraphQL subscription on `Instructions` filtered by the Pump.fun program and `create`/`create_v2` methods. This returns creation events with mint address, bonding curve, metadata, creator, name, symbol, and URI. [Track launches in realtime: stream it ➤](https://ide.bitquery.io/Track-new-token-launches-on-Pump-Fun-in-realtime0_7)
Show the GraphQL ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Method: { in: ["create", "create_v2"] } Name: { is: "pump" } } } } ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } Transaction { Signature } } } } ```
### How do I get all Pump.fun tokens created by a specific address? [Everything created by an address: run it ➤](https://ide.bitquery.io/all-Pump-fun-tokens-created-by-an-address_3) :::tip Want to analyze the funding history and transaction patterns of a creator? Connect the [Bitquery MCP server](https://mcp.bitquery.io/) and ask an AI agent to trace the creator's funding in plain English ([AI Investigations](https://bitquery.io/solutions/ai-investigations)), or use our [Money Flow API](https://docs.bitquery.io/v1/docs/Examples/coinpath/money-flow-api#funding-history-of-address) to query fund movements directly. :::
Show the GraphQL ```graphql query MyQuery { Solana { TokenSupplyUpdates( where: { Transaction: { Result: { Success: true } Signer: { is: "ADD CREATOR ADDRESS HERE" } } Instruction: { Program: { Address: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } Method: { in: ["create", "create_v2"] } } } } ) { Block { Time } TokenSupplyUpdate { Amount Currency { Uri UpdateAuthority Symbol Name MintAddress MetadataAddress Fungible Decimals } PostBalance } Transaction { Signature Signer } } } } ```
### How do I get Pump.fun tokens created by a wallet from historical data? Use the **v1 Solana transfers API** to list what a wallet created on Pump.fun over a date range. Replace the `signer` value and the `date` range in the query with your target wallet and desired window. For **aggregates** (e.g. total count of mints created by a wallet), use the dedicated count query below. - **[Run query: list mints created by a wallet](https://ide.bitquery.io/Pumpfun-tokens-created-by-a-wallet-historical#)** - **[Run query: count of mints created by a wallet](https://ide.bitquery.io/Count-of-Pumpfun-tokens-created-by-a-wallet-historical#)**
Show the GraphQL ```graphql { solana { transfers( options: { limit: 100, desc: "block.height" } date: { since: "2025-02-08", till: "2025-06-08" } externalProgramId: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } transferType: { is: mint } signer: { is: "Ddu1xqgNHBRBiJrissrpLtevq2A7KAHjgiDzECoNL8HG" } ) { block { height timestamp { iso8601 } } instruction { action { name } callPath external externalAction { name type } program { name id } externalProgram { id name } } currency { name symbol address } date { date } amount receiver { address mintAccount type } transaction { signature signer } transferType } } } ```
### How do I get token metadata, dev address, and creation time for a specific Pump.fun token? Each new launch arrives with its dev address, metadata and supply. `PostBalance` carries the current supply. [New mints with dev and metadata: stream it ➤](https://ide.bitquery.io/newly-created-PF-token-dev-address-metadata_9)
Show the GraphQL ```graphql subscription { Solana { TokenSupplyUpdates( where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {in: ["create","create_v2"]}}}} ) { Block{ Time } Transaction{ Signer } TokenSupplyUpdate { Amount Currency { Symbol ProgramAddress PrimarySaleHappened Native Name MintAddress MetadataAddress Key IsMutable Fungible EditionNonce Decimals Wrapped VerifiedCollection Uri UpdateAuthority TokenStandard } PostBalance } } } } ```
## Pump.fun Mayhem Mode Tokens Below APIs are related to Pump.fun tokens which were launched within Mayhem mode. To check whether an older mint was created with Mayhem mode `true` or `false`, use this [Bitquery Solana v1 API](https://docs.bitquery.io/v1/docs/Examples/Solana/transfers#check-if-a-pump-fun-token-was-launched-in-mayhem-mode---historical-query), in v1 we have all the solana transfers data so we check for the 1 Billion token transfer to Mayhem Autonomous AI agent if theres a transfer we can say that the token was a Mayhem token. ### How do I track Mayhem mode enabled Pump.fun tokens in real time? Streams mints created with Mayhem mode enabled, as they launch. Try the API [here](https://ide.bitquery.io/Track-Mayhem-Mode-enabled-Pumpfun-Tokens-in-realtime).
Show the GraphQL ```graphql subscription MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {in: ["create", "create_v2"]}, Arguments: {includes: {Name: {is: "is_mayhem_mode"}, Value: {Boolean: true}}}}}, Transaction: {Result: {Success: true}}} ) { Instruction { Program { Method Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } Transaction { Signature } } } } ```
### How do I check Mayhem mode of a Pump.fun token? Now you can check if a pump fun token is in Mayhem mode or not, we will be checking if it was launched with the `is_mayhem_mode` as `true` or `false`. [Check Mayhem mode: run it ➤](https://ide.bitquery.io/check-mayhem-mode-of-a-pump-fun-token_1)
Show the GraphQL ```graphql query MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {in: ["create", "create_v2"]}}, Accounts: {includes: {Address: {is: "TOKEN_ADDRESS_TO_CHECK"}}}}, Transaction: {Result: {Success: true}}} ) { Instruction { Program { Method Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } Transaction { Signature } } } } ```
### How do I check if a Pump.fun token was launched in Mayhem mode? (Historical) To determine if a Pump.fun token was launched in Mayhem mode, we use the Solana v1 Transfers API. The following query checks transfers of exactly 1,000,000,000,000,000 units (which equals 1 billion tokens when adjusted for 6 decimal places). - If the resulting count is **2**, the token was launched in Mayhem mode. - If the count is **1**, the token was launched in standard mode. This method reliably identifies whether a token's initial mint followed the Mayhem mode process. [Try out the API](https://ide.bitquery.io/token-mayhem-mode-or-not_1)
Show the GraphQL ```graphql { solana { transfers( date: { since: "2025-01-01" } amount: { is: 1000000000000000 } currency: { is: "EEhQvi54Rwme2z84gG6qQmuaWjnZ6b9AMgq5aGkKpump" } ) { count } } } ```
## Token Pricing & Market Data ### How do I get the latest price of a Pump.fun token? We launched the [Price Index](/docs/trading/crypto-price-api/) in August 2025, allowing you to track price of any token trading onchain. Here's an example of tracking prices. It uses PUMP on PumpSwap; for a mint still on the bonding curve, filter `Market.Program` to `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` instead. PumpFun Token prices against SOL Stream [Latest price in USD: run it ➤](https://ide.bitquery.io/solana-token-price-using-price-api)
Show the GraphQL ```graphql { Trading { Pairs( where: { Market: { Network: { is: "Solana" } } Token: { Address: { is: "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } } Interval: { Time: { Duration: { eq: 60 } } } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Market { Address Network Program Protocol ProtocolFamily } Price { IsQuotedInUsd Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } Ohlc { Close High Low Open } } Token { Address Name Symbol } QuoteToken { Address Name Symbol } Volume { Base Usd } } } } ```
### How do I track the price of a Pump.fun token in real time? Live stream of token price updates on Pump.fun [Track price in real time: stream it ➤](https://ide.bitquery.io/Price-of-a-pump-fun-token-using-price-index-in-usd)
Show the GraphQL ```graphql subscription { Trading { Pairs( where: { Token: { Address: { is: "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } } Price: { IsQuotedInUsd: true } Market: { Network: { is: "Solana" } Program: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } } } ) { Market { Address Network Program Protocol ProtocolFamily } Price { Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } Ohlc { Close High Low Open } } Token { Address Name Symbol } QuoteToken { Address Name Symbol } Volume { Base Usd } } } } ```
### How do I get top 10 Pump.fun tokens by price change in the last 5 minutes? Returns the ten biggest price moves on Pump.fun over the last 5 minutes. Open it in the [Bitquery IDE: biggest 5-minute movers](https://ide.bitquery.io/Top-10-pump-fun-tokens-by-Price-change-in-last-5min_1).
Show the GraphQL ```graphql { Trading { Pairs( limit: {count: 10} limitBy: {count: 1, by: Token_Address} orderBy: {descendingByField: "Price_Change_5min"} where: {Interval: {Time: {Duration: {eq: 1}}}, Block: {Time: {since_relative: {minutes_ago: 5}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Solana"}, Program: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}}} ) { Market { Address Network Program Protocol ProtocolFamily } Price { Average { currentPrice: Mean(maximum: Block_Time) min5Ago: Mean( minimum: Block_Time if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} ) } } Price_Change_5min: calculate(expression: "(( $Price_Average_currentPrice - $Price_Average_min5Ago ) / $Price_Average_min5Ago) * 100") Token { Address Name Symbol } Market{ Address } QuoteToken { Address Name Symbol } } } } ```
### How do I get Pump.fun token OHLCV data historically? Use Bitquery's `DEXTradeByTokens` with `Block.Time(interval: minutes, count: 1)` to fetch open-high-low-close (OHLC) data. Filter by token mint and Pump.fun program `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`. For history, use `dataset: archive`; some fields such as `Trade_Side` are not served there. [OHLC on Pump.fun: run it ➤](https://ide.bitquery.io/OHLC-for-a-token-on-Pump-Fun0_8) :::note Trade Side Account field will not be available for aggregate queries in Archive and Combined Datasets :::
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTradeByTokens( limit: { count: 10 } orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "66VR6bjEV5DPSDhYSQyPAxNsY3dgmH6Lwgi5cyf2pump" } } Dex: { ProgramAddress: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } } } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ```
### How do I get a token's all-time high (ATH) price on Pump.fun? Use Bitquery's `DEXTradeByTokens` with `dataset: archive`, `Trade.PriceInUSD(maximum: Trade_PriceInUSD)`, and `quantile(of: Trade_PriceInUSD, level: 0.98)` to get ATH price. Market cap = ATH price × 1 billion (Pump.fun tokens have 1B supply). Pass token mint addresses in `Trade.Currency.MintAddress.in`. [ATH price and market cap in timeframe: run it ➤](https://ide.bitquery.io/ATH-Market-Cap-of-Pump-Fun-Tokens-in-a-Specific-Timeframe)
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTradeByTokens( limitBy: { by: Trade_Currency_MintAddress, count: 1 } where: { Trade: { Currency: { MintAddress: { in: [ "639g7XEn1fMf7ZpHhKWUiHywY4PpQ5QPm6VMsw8Cpump" "FXMCWau8etMkKZnyn4pi9qMM3NVfrCHFM4KKnJvNpump" ] } } Side: { Currency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" ] } } } } Block: { Time: { since: "2025-05-03T06:37:00Z" } } } ) { Trade { Currency { MintAddress Name Symbol } PriceInUSD(maximum: Trade_PriceInUSD) Side { Currency { Symbol } } } max: quantile(of: Trade_PriceInUSD, level: 0.98) ATH_Marketcap: calculate(expression: "$max * 1000000000") } } } ```
### How do I get token price change over time (delta from X minutes back)? Useful for tracking % change by comparing first/last prices [Price change over time: run it ➤](https://ide.bitquery.io/price-change-over-x-minutes)
Show the GraphQL ```graphql query PumpFunRecentTrades { Solana { DEXTradeByTokens( where: { Block: { Time: { since_relative: { minutes_ago: 60 } } } Trade: { Currency: { MintAddress: { is: "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } } Dex: { ProtocolName: { is: "pump_amm" } } } Transaction: { Result: { Success: true } } } ) { Trade { Market { MarketAddress } Currency { Symbol Name MintAddress } lastPrice: Price(maximum: Block_Slot) prePrice: Price(minimum: Block_Slot) } Price_change: calculate( expression: "(( $Trade_lastPrice - $Trade_prePrice ) / $Trade_prePrice) * 100" ) } } } ```
### How do I get a wallet's PnL on Pump.fun tokens? {#how-do-i-get-a-wallets-pnl-on-pumpfun-tokens} Bitquery does not return a single “PnL” field for Pump.fun: derive it from **historical buys and sells** for that wallet and mint. Query **`Solana.DEXTrades`** or **`DEXTradeByTokens`** with **`Dex.ProtocolName: pump`**, the token **`MintAddress`**, **`Transaction.Signer`** or buy/sell accounts, and a time window; then compute realized PnL from USD volumes (see the **[Realised PnL example on Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades/#realised-pnl-avg-buy-price-buy-volume-sell-volume)**). Use the **Crypto Price API** if you need mark-to-market for open positions. ## Trade Activity & Volume ### How do I get live trades from Pump.fun using Bitquery? Use Bitquery's `DEXTrades` GraphQL subscription filtered by `ProtocolName: "pump"` to stream live Pump.fun trades including buy/sell sides, amounts, accounts, and methods. For gRPC or Kafka, see [Pump.fun gRPC Streams](/docs/grpc/solana/examples/pump-fun-grpc-streams/). [Pump.fun real-time trades: stream it ➤](https://ide.bitquery.io/Pumpfun-DEX-Trades-stream)
Show the GraphQL ```graphql subscription MyQuery { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "pump" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Program { Method } } Trade { Dex { ProtocolFamily ProtocolName } Buy { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } Price } Sell { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } PriceInUSD Price } } Transaction { Signature } } } } ```
### How do I get the latest trades for a Pump.fun token? Retrieves recent trades with detailed price, amount, and sides [Latest trades for one mint: run it ➤](https://ide.bitquery.io/get-latest-trades-of-a-pump-fun-token_6)
Show the GraphQL ```graphql query pumpfunTokenLatestTrades($token: String) { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Trade: { Currency: { MintAddress: { is: $token } } Price: { gt: 0 } Dex: { ProtocolName: { is: "pump_amm" } } } Transaction: { Result: { Success: true } } } ) { Block { allTime: Time } Trade { Account { Address Owner } Side { Type } Price Amount Side { AmountInUSD Amount } } } } } ``` ```json { "token": "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } ```
### How do I get the volume of a Pump.fun token for the last 7 days? Use Bitquery's `DEXTradeByTokens` with `sum(of: Trade_Amount)` and a `Block.Time.since` filter (e.g. 7 days ago) to aggregate trading volume. Filter by token mint address and `ProtocolName` (`pump_amm` for PumpSwap, as in the PUMP example, or `pump` for the bonding curve). [Trading volume for one mint: run it ➤](https://ide.bitquery.io/trade-volume-7-days)
Show the GraphQL ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } } Dex: { ProtocolName: { is: "pump_amm" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { Trade { Currency { Name Symbol MintAddress } Dex { ProtocolName ProtocolFamily } } TradeVolumeRaw: sum(of: Trade_Amount) TradeVolumeUSD: sum(of: Trade_Side_AmountInUSD) } } } ```
In addition, you can get the last 7 days of trading volume using the [Crypto Price API](/docs/trading/crypto-price-api/). Example: [Last 7 days of volume: run it ➤](https://ide.bitquery.io/Last-7-days-of-volume-for-any-token_2) ```graphql { Trading { Tokens( where: { Block: { Date: { since_relative: { days_ago: 7 } } } Interval: { Time: { Duration: { eq: 3600 } } } Token: { Address: { is: "cbbtcf3aa214zXHbiAZQwf4122FBYbraNdFqgw4iMij" } } } ) { sum(of: Volume_Usd) } } } ``` ### How do I get all tokens traded on Pump.fun in the last 1 hour? To list everything traded on Pump.fun in the last hour, filter trades by the protocol and a block time inside that window. This provides a list of tokens that have had at least one trade during this window, along with associated token and market details. Each token record includes its mint address, name, symbol, and network. The sample GraphQL query below retrieves all Pump.fun tokens traded in the last hour on Solana: [Everything traded in the last hour: run it ➤](https://ide.bitquery.io/all-tokens-traded-on-Pumpfun-in-the-last-1-hour_1)
Show the GraphQL ```graphql { Trading { Pairs( limitBy: { by: Token_Address, count: 1 } where: { Market: { Program: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } Token: { Network: { is: "Solana" } } Block: { Time: { since_relative: { minutes_ago: 60 } } } Interval: { Time: { Duration: { eq: 1 } } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Market { Address Program Name } } } } ```
### How do I get tokens that reached a specific market cap on Pump.fun? To find mints that crossed a market-cap threshold, use the following example. It filters for tokens with a market cap greater than or equal to a provided value (for example, $10,000) on Solana within the last minute. Adjust the `ge` value in `MarketCap` to your chosen threshold. [Mints that reached a market cap: run it ➤](https://ide.bitquery.io/How-do-I-get-tokens-that-reached-a-specific-market-cap-on-Pumpfun)
Show the GraphQL ```graphql { Trading { Pairs( limitBy: { by: Token_Address, count: 1 } where: { Market: { Program: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } Token: { Network: { is: "Solana" } } Supply: { MarketCap: { ge: 10000 } } Block: { Time: { since_relative: { minutes_ago: 1 } } } Interval: { Time: { Duration: { eq: 1 } } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Price { Average { Mean ExponentialMoving SimpleMoving WeightedSimpleMoving } } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } Market { Address Program Name } } } } ```
### How do I get detailed trade stats (volume, buys, sells, makers, buyers, sellers)? Includes 5-minute and 1-hour metrics for deep token analytics. The windows use `since_relative` and `after_relative`, so they roll forward with no date to update; the example pair is the PUMP/USDC PumpSwap pool. [Detailed trade stats: run it ➤](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair_10)
Show the GraphQL ```graphql query PairStats($token: String!, $pair_address: String!) { Solana(dataset: realtime) { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: $token } } Market: { MarketAddress: { is: $pair_address } } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) makers_5min: count( distinct: Transaction_Signer if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) buyers: count( distinct: Transaction_Signer if: { Trade: { Side: { Type: { is: buy } } } } ) buyers_5min: count( distinct: Transaction_Signer if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) sellers: count( distinct: Transaction_Signer if: { Trade: { Side: { Type: { is: sell } } } } ) sellers_5min: count( distinct: Transaction_Signer if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) trades: count trades_5min: count(if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } }) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) buy_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) sell_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) buys_5min: count( if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) sells_5min: count( if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { after_relative: { minutes_ago: 5 } } } } ) } } } ``` ```json { "token": "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn", "pair_address": "2uF4Xh61rDwxnG9woyxsVQP7zuA6kLFpb3NvnRQeoiSd" } ```
### How do I get the first 100 buyers of a Pump.fun token? Gets the first 100 wallets that bought. DEXTrades on Solana keeps only the recent window, so pick a mint launched inside it. [First 100 buyers: run it ➤](https://ide.bitquery.io/get-first-100-buyers-of-a-token_1)
Show the GraphQL ```graphql query MyQuery { Solana { DEXTrades( where: { Trade: { Buy: { Currency: { MintAddress: { is: "token mint address" } } } } } limit: { count: 100 } orderBy: { ascending: Block_Time } ) { Trade { Buy { Amount Account { Token { Owner } } } } } } } ```
### How do I check if the first 100 buyers are still holding? Pass the owner addresses from the query above. Each row is the latest balance of one token account, picked by slot and then by transaction index, so two balance changes in the same slot are read in the right order. A balance of 0 means the wallet sold or moved everything. A wallet with no row had no balance change in the real-time window (about 12 hours); for a token launched inside that window, every buyer has a row.
Show the GraphQL ```graphql query StillHolding($token: String!, $owners: [String!]!) { Solana(dataset: realtime) { BalanceUpdates( where: { BalanceUpdate: { Account: { Owner: { in: $owners, not: "" } } Currency: { MintAddress: { is: $token, not: "" } } } Transaction: { Result: { Success: true } } } orderBy: [{ descending: Block_Slot }, { descending: Transaction_Index }] limitBy: { by: BalanceUpdate_Account_Address, count: 1 } ) { Block { Time } BalanceUpdate { Account { Owner Address } balance: PostBalance } } } } ``` ```json { "token": "token mint address", "owners": [ "ApRJBQEKfmcrViQkH94BkzRFUGWtA8uC71DXu6USdd3n", "9nG4zw1jVJFpEtSLmbGQpTnpG2TiKfLXWkkTyyRvxTt6" ] } ```
## Token Liquidity, Pools & Pairs ### How do I get all trading pairs of a Pump.fun token? Lists all markets where the token is traded, including pair addresses [All trading pairs for one mint: run it ➤](https://ide.bitquery.io/get-all-the-trading-pairs-of-a-specific-token)
Show the GraphQL ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } } } ) { count Trade { Market { MarketAddress } Dex { ProgramAddress ProtocolName ProtocolFamily } Currency { MintAddress Symbol } } } } } ```
### How do I get liquidity of Pump.fun tokens? Returns the current balance of each token vault of the pools you pass, one row per vault. A PumpSwap pool has two vaults: the token and the quote token, usually WSOL. A bonding curve priced in SOL has one, the token, because it keeps its SOL as plain SOL, which `Native: false` leaves out. Pass the `MarketAddress` values from the trading-pairs query above. Each row is the vault's latest balance, picked by slot and then by transaction index. A pool with no trade in the real-time window (about 12 hours) returns no row.
Show the GraphQL ```graphql query PoolLiquidity($pools: [String!]!) { Solana(dataset: realtime) { BalanceUpdates( where: { BalanceUpdate: { Currency: { Native: false } Account: { Owner: { in: $pools, not: "" } } } Transaction: { Result: { Success: true } } } orderBy: [{ descending: Block_Slot }, { descending: Transaction_Index }] limitBy: { by: BalanceUpdate_Account_Address, count: 1 } ) { Block { Time } BalanceUpdate { Account { Owner Address } Currency { MintAddress Symbol } Liquidity: PostBalance } } } } ``` ```json { "pools": ["pool address"] } ```
### How do I get bonding curve progress for a Pump.fun token? Use Bitquery's `DEXPools` with Pump.fun market address to get pool balances. Bonding curve progress = 100 - (((base_balance - 206900000) × 100) / 793100000). Combine with `DEXTradeByTokens` for volume and `TokenSupplyUpdates` for market cap. **Please change the timestamp in the query to recent ones; the saved query might have outdated numbers.** [Market cap, liquidity, bonding curve, volume: run it ➤](https://ide.bitquery.io/mcap-liquidity-bonding-curve-volume-supply-of-a-token-in-time-frame_1)
Show the GraphQL ```graphql query MyQuery($time_1h_ago: DateTime, $token: String, $pairAddress: String) { Solana { volume: DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: $token } } Market: { MarketAddress: { is: $pairAddress } } } Block: { Time: { since: $time_1h_ago } } Transaction: { Result: { Success: true } } } ) { VolumeInUSD: sum(of: Trade_Side_AmountInUSD) } liquidity_and_BondingCurve: DEXPools( where: { Pool: { Market: { MarketAddress: { is: $pairAddress } } } Transaction: { Result: { Success: true } } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Pool { Market { BaseCurrency { Name Symbol } QuoteCurrency { Name Symbol } } Base { Balance: PostAmount PostAmountInUSD } Quote { PostAmount PostAmountInUSD } } } marketcap_and_supply: TokenSupplyUpdates( where: { TokenSupplyUpdate: { Currency: { MintAddress: { is: $token } } } Transaction: { Result: { Success: true } } } limitBy: { by: TokenSupplyUpdate_Currency_MintAddress, count: 1 } orderBy: { descending: Block_Time } ) { TokenSupplyUpdate { MarketCap: PostBalanceInUSD Supply: PostBalance Currency { Name MintAddress Symbol } } } Price: DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: $token } } Market: { MarketAddress: { is: $pairAddress } } } } ) { Trade { Price PriceInUSD } } } } ``` ```json { "time_1h_ago": "2025-06-01T11:00:00Z", "token": "EskuW9PhydSiMTxnWbvYBLVvwWV9pKhG4yYM9SwFPump", "pairAddress": "BkivJgUrXRQtJyePt5MzJJe9Y2JXhUaFhpCJcgxkisD" } ```
### How do I get the last Pump.fun trade before a token graduates to PumpSwap AMM? Finds the final pool trade before a mint moves to PumpSwap. DEXPools keeps only the recent window, so it must have graduated inside it; drop the `Market` filter to list every recent graduation. [Last Pump.fun trade before PumpSwap: run it ➤](https://ide.bitquery.io/pump-fun-token-graduating-to-pumpswap)
Show the GraphQL ```graphql { Solana { DEXPools( where: { Pool: { Dex: { ProtocolName: { is: "pump" } } Base: { PostAmount: { eq: "206900000" } } Market: { BaseCurrency: { MintAddress: { is: "token mint address" } } } } Transaction: { Result: { Success: true } } } orderBy: { descending: Block_Time } ) { Transaction { Signer Signature } Instruction { Program { Method } } Pool { Base { ChangeAmount PostAmount } Quote { ChangeAmount ChangeAmountInUSD PostAmount PostAmountInUSD Price PriceInUSD } Dex { ProgramAddress ProtocolFamily ProtocolName } Market { BaseCurrency { Name Symbol MintAddress } MarketAddress QuoteCurrency { Name Symbol MintAddress } } } } } } ```
## Token Holder & Trader Insights ### How do I get dev's holdings of a Pump.fun token? Returns the developer's current balance of the token. Each row is the latest balance of one of the developer's token accounts, picked by slot and then by transaction index; add the rows if there is more than one. No row means the balance did not change in the real-time window (about 12 hours). The same query works for any other wallet.
Show the GraphQL ```graphql query DevHoldings($dev: String!, $token: String!) { Solana(dataset: realtime) { BalanceUpdates( where: { BalanceUpdate: { Account: { Owner: { is: $dev, not: "" } } Currency: { MintAddress: { is: $token, not: "" } } } Transaction: { Result: { Success: true } } } orderBy: [{ descending: Block_Slot }, { descending: Transaction_Index }] limitBy: { by: BalanceUpdate_Account_Address, count: 1 } ) { Block { Time } BalanceUpdate { Account { Address } balance: PostBalance } } } } ``` ```json { "dev": "8oTWME5BPpudMksqEKfn562pGobrtnEpNsG66hBBgx92", "token": "token mint address" } ```
The walkthrough below checks whether a real launch's dev sold: it finds the dev from the create instruction, lists the dev's trades on the coin, reads the dev's balance and counts the dev's other launches. ### How do I get top 10 token holders of a Pump.fun token? Returns the 10 wallets that hold the most of a token. A wallet's holding is the sum of all its balance changes for that mint, so the result equals current balances only for a token launched within the real-time window (about 12 hours). For an older token, use the V1 method on the [Solana Token Holders API](/docs/blockchain/Solana/solana-token-holders/) page. The bonding curve before graduation, and the PumpSwap pool after it, appear in the list as holders; drop those owners to see wallets only. Do not rank holders with `PostBalance(maximum: Block_Slot)`. When an account changes twice in one slot, that pick can return the older balance. At graduation a SOL-paired bonding curve goes from 206,900,000 tokens to 0 in one slot, and a wallet can sell out in several transactions in one slot. In both cases that query can return the old, nonzero balance, so the empty curve or the sold-out wallet shows up as a top holder.
Show the GraphQL ```graphql query TopHolders($token: String!) { Solana(dataset: realtime) { BalanceUpdates( limit: { count: 10 } orderBy: { descendingByField: "Holding" } where: { BalanceUpdate: { Currency: { MintAddress: { is: $token, not: "" } } } Transaction: { Result: { Success: true } } } ) { BalanceUpdate { Account { Owner } } Holding: sum(of: BalanceUpdate_Amount) } } } ``` ```json { "token": "token mint address" } ```
### How do I get top traders of a Pump.fun token? Use Bitquery's `DEXTradeByTokens` with `orderBy: descendingByField: "volumeUsd"`, `limit: 100`, and `sum(of: Trade_Side_AmountInUSD)` grouped by `Trade.Account.Owner` to rank top wallets by USD volume for a Pump.fun token. [Top traders: run it ➤](https://ide.bitquery.io/top-traders-of-a-pump-fun-token_2)
Show the GraphQL ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Currency: { MintAddress: { is: $token } } } Transaction: { Result: { Success: true } } } ) { Trade { Account { Owner } } bought: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) sold: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ```json { "token": "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn", "pool": "5Ezr4oK1vTV4m8f7g8P1Be1uwtzczhf21AztwNxWcmwM" } ```
### How do I get top Pump.fun token creators? Find wallet addresses of top creators by number of tokens launched [Top creators: run it ➤](https://ide.bitquery.io/Top-pump-fun-token-creators_2) :::tip Want to dive deeper into a creator's background? Ask an AI agent via the [Bitquery MCP server](https://mcp.bitquery.io/) to trace the source of funds for any Pump.fun creator ([AI Investigations](https://bitquery.io/solutions/ai-investigations)), or use our [Money Flow API](https://docs.bitquery.io/v1/docs/Examples/coinpath/money-flow-api#funding-history-of-address) to analyze funding history directly. :::
Show the GraphQL ```graphql query MyQuery { Solana(network: solana) { Instructions( where: { Instruction: { Program: { Name: { is: "pump" } Method: { in: ["create", "create_v2"] } } } } orderBy: { descendingByField: "tokens_count" } ) { tokens_count: count Transaction { Signer } } } } ```
## Token Security & Analysis ### How do I check if a Pump.fun token is phishy? This uses two queries to flag a possibly phishy mint, by comparing transfers against trades. It surfaces wallets that received a balance without ever buying, a common pattern in phishing and airdrop scams. #### How It Works The detection method works by: 1. **First Query**: get the first transfers to each address, giving the timestamp when each wallet first received a balance. 2. **Second Query**: Check if those addresses ever bought the token and when - pass the address list from the first query as a variable to check their purchase history. 3. **Analysis**: Compare transfer times and trade times in your code: - If an address **never bought** the token, it's suspicious. - If an address's **first buy time is later than the first transfer time**, it indicates the token was received before being purchased, which is a red flag for phishing behavior. That pattern means someone else sent them the balance, which is suspicious: devs often push supply to well-known accounts in crypto space to misguide traders. Pick a token launched within the recent window, since the Transfers cube on Solana keeps no archive and this query runs DEXTrades on realtime. Whether it is phishy is not decided here, as we are not running the timestamp comparison. Here we are just demonstrating that how you can get data from Bitquery and later run basic analysis on it. #### Query 1: Get First Transfers of a Token to Addresses This retrieves the first transfer to each address, with the timestamp when that wallet first received a balance. [Run Query](https://ide.bitquery.io/first-transfers-of-a-pump-fun-token_1#)
Show the GraphQL ```graphql query MyQuery($token: String, $bonding_curve: String) { Solana { Transfers( limit: { count: 1000 } orderBy: { ascendingByField: "Block_first_transfer" } where: { Transfer: { Receiver: { Token: { Owner: { not: $bonding_curve } } } Currency: { MintAddress: { is: $token } } } Transaction: { Result: { Success: true } } } ) { Transfer { Receiver { Token { Owner } } } Block { first_transfer: Time(minimum: Block_Time) } total_transferred_amount: sum(of: Transfer_Amount) } } } ``` ```json { "token": "token mint address", "bonding_curve": "bonding curve address" } ```
#### Query 2: Get First Buys of an Address List for a Specific Token This query checks if the addresses from Query 1 ever bought the token and when. Pass the address array from Query 1 as a variable to this query. [Run Query](https://ide.bitquery.io/get-first-buys-of-an-address-list-of-a-specific-pump-fun-token#)
Show the GraphQL ```graphql query MyQuery($token: String!, $buyersList: [String!]) { Solana { DEXTradeByTokens( orderBy: { ascendingByField: "Block_first_buy" } where: { Trade: { Account: { Token: { Owner: { in: $buyersList } } } Currency: { MintAddress: { is: $token } } Dex: { ProgramAddress: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } Side: { Type: { is: buy } } } Transaction: { Result: { Success: true } } } ) { Trade { Account { Token { Owner } } Currency { Name Symbol MintAddress } Side { Type } } Block { first_buy: Time(minimum: Block_Time) } total_bought_amount: sum(of: Trade_Amount) } } } ``` ```json { "token": "token mint address", "buyersList": [ PASS THE ADDRESS LIST YOU GOT FROM QUERY 1 HERE ] } ```
#### Implementation Notes - Extract the address list and first transfer timestamps from Query 1 - Pass the address array as a variable to Query 2 - Compare the timestamps for all addresses: - If `firstTransferTime < firstBuyTime` or `firstBuyTime` is null → **Phishy indicator** - If `firstBuyTime <= firstTransferTime` → **Normal behavior** - You can implement this logic in your application code to automatically flag suspicious tokens ### How do I check if a Pump.fun coin is bundled? A bundle is a set of purchases a coin's dev makes from several wallets at the moment of launch, sent in one Jito bundle with the launch transaction so nobody can buy in between. Bitquery's [study of 8.2 million Pump.fun launches](https://bitquery.io/investigations/pump-fun-snipers-bundles) found the dev's own wallets in the launch block of 21% of new coins. To check a coin, list every buy in its launch block, ordered by position: ```graphql { Solana { DEXTradeByTokens( orderBy: {ascending: Transaction_Index} where: { Block: {Slot: {eq: "461619096"}} Trade: {Currency: {MintAddress: {is: "4YMh1RMWNcedZ2Ffs7Yk2tVbb69bb4UYgjcEaPobpump"}}, Side: {Type: {is: buy}}} Transaction: {Result: {Success: true}} } ) { Transaction { Index Signer FeePayer } Trade { Amount Side { AmountInUSD } } } } } ``` Set the slot and the mint to the coin's launch; the slot and the launch transaction's `Index` come from its `create` or `create_v2` instruction (see [Token Creation & Metadata](#token-creation--metadata)). Read the result with three tests: - **Position.** Buys in the four transactions straight after the launch (`Index` +1 to +4) fit in the same Jito bundle. Buys further down the block are usually sniper bots. - **Fee payer.** If the dev's wallet is the `FeePayer` on another wallet's buy, that buy is the dev's. - **Coins per wallet.** Count the distinct Pump.fun coins each early buyer bought that day with `count(distinct: Trade_Currency_MintAddress)`. Sniper bots buy dozens to hundreds; bundle wallets buy a few, often the same few coins together. Position is a strong signal, not proof: confirm a bundle on a public Jito bundle explorer, since some launches do not go through Jito. The real-time data covers about the last 12 hours, so run this soon after launch; the full history is on the [Bitquery Data Store](https://bitquery.io/datastore). The walkthrough below runs all of it on a real launch: four wallets bought about 11% of the supply in the four slots after the dev, sold within 39 seconds, and bought in the launch second of nine coins that day, each from a different dev wallet. ## Token Rankings & Filters ### How do I get top Pump.fun tokens by market cap? Use **Trading API** **`Pairs`**: rank by **`Supply.MarketCap`** over the last **24 hours**, **1s** interval, **`Market.ProtocolFamily`** **Pumpfun**, **`Volume.Usd`** **> 1000**, Solana tokens, **`limitBy`** one row per **`Token_Id`**, up to **50** results. [Top mints by market cap: run it ➤](https://ide.bitquery.io/top-pump-fun-tokens-by-marketcap)
Show the GraphQL ```graphql { Trading { Pairs( limit: { count: 50 } limitBy: { count: 1, by: Token_Id } orderBy: { descending: Supply_MarketCap } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Interval: { Time: { Duration: { eq: 1 } } } Market: { ProtocolFamily: { is: "Pumpfun" } } Volume: { Usd: { gt: 1000 } } Token: { Network: { is: "Solana" } } } ) { Currency { Id Name Symbol } Price { Average { Mean(maximum: Block_Time) } } Volume { Base(maximum: Block_Time) Quote(maximum: Block_Time) Usd(maximum: Block_Time) } Token { Network Symbol Address } Supply { MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) TotalSupply(maximum: Block_Time) } } } } ```
### How do I get all Pump.fun tokens above 10K market cap? Subscribe to **Trading** **`Pairs`** when the token is on **Solana**, **`Market.ProtocolFamily`** is **Pumpfun**, **`Supply.MarketCap`** **> 10,000** (USD), and interval duration **> 1** second. [Mints above 10K market cap: stream it ➤](https://ide.bitquery.io/realtime-stream-pumpfun-tokens-with-marketcap-above-10k-marketcap#)
Show the subscription ```graphql subscription { Trading { Pairs( where: { Token: { Id: { includesCaseInsensitive: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 10000 } } Market: { ProtocolFamily: { is: "Pumpfun" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
### How do I track "King of the Hill" Pump.fun tokens (30K–35K market cap)? Tokens in the **$30K–$35K** **`Supply.MarketCap`** band on **Pumpfun** (see [Pump.fun on King of the Hill](https://x.com/pumpdotfun/status/1760103287397793933)). Subscribe to **Trading** **`Pairs`** with **`MarketCap`** between **30,000** and **35,000** USD. [“King of the Hill” mints: stream it ➤](https://ide.bitquery.io/realtime-stream-of-King-of-the-Hill-Pumpfun-tokens-30K35K-market-cap#)
Show the subscription ```graphql subscription { Trading { Pairs( where: { Token: { Id: { includesCaseInsensitive: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 30000, lt: 35000 } } Market: { ProtocolFamily: { is: "Pumpfun" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
--- ## Trader-Focused Trade APIs (with USD Price, Market Cap & Supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get All DEX Trades on PumpFun With Price, Market Cap, and Supply Stream **all PumpFun DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.ProtocolFamily: Pumpfun`** to capture every swap across Pumpfun in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/Get-All-DEX-Trades-on-Pumpfun-With-Price-Market-Cap-and-Supply).
Show the GraphQL ```graphql subscription { Trading { Trades(where: { Pair: { Market: { ProtocolFamily: { is: "Pumpfun" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } Currency { Symbol Id Name } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
### Top Traders by PnL for a Specific PumpFun Token (Last 30 Minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. The example pool is the PUMP/USDC PumpSwap pool; for a bonding curve, use the curve's market address from the [latest trades query](#how-do-i-get-the-latest-trades-for-a-pumpfun-token). You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-pumpfun-token-curve).
Show the GraphQL ```graphql { Trading { Trades( limit: { count: 10 } orderBy: { descendingByField: "PnL" } where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "2uF4Xh61rDwxnG9woyxsVQP7zuA6kLFpb3NvnRQeoiSd" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
### Get Latest Creator Fee Transfers on Pump.fun Retrieve the 10 most recent **creator fee collections** on the Pump.fun bonding curve program. Claims arrive as both **`collect_creator_fee`** and **`collect_creator_fee_v2`**, so the query filters on both, on **`Instruction.Program.Address: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"`**. Each row is a balance update showing who collected and how much. For unclaimed balances, top earners, fee sharing, sweeps and creator changes, see the [Pump.fun Creator Rewards API](/docs/blockchain/Solana/Pumpfun/pump-fun-creator-rewards-api/). You can run this query [in the Bitquery IDE](https://ide.bitquery.io/latest-creator-fees-pumpfun#).
Show the GraphQL ```graphql { Solana(network: solana) { InstructionBalanceUpdates( limit: {count: 10} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Method: {in: ["collect_creator_fee", "collect_creator_fee_v2"]}, Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}}}, Transaction: {Result: {Success: true}}} ) { Transaction { Signer Signature Result { Success ErrorMessage } Index Fee } Block { Time Hash } BalanceUpdate { Account { Address Owner Token { Owner } } Amount AmountInUSD Currency { Name MintAddress Symbol } PreBalance PostBalance } } } } ```
--- ## Does pump.fun have an official API? Not a hosted one. Pump.fun publishes program documentation and IDLs on GitHub for the bonding curve program, PumpSwap and its fee program, which is what you need to build and sign transactions. It publishes no data API: the hosts its web app calls have no reference, no published rate limits, no schema and no stability promise, so anything built on them can break without notice. The queries on this page read the same on-chain activity through Bitquery, with a documented schema, plan-based rate limits, and streaming over WebSocket, gRPC and Kafka. | | Pump.fun | Bitquery Pump.fun API | |---|---|---| | Documentation | Program docs and IDLs on GitHub; no data API reference | Schema, examples and IDE links on this page | | Trades, prices, candles, launches | Served to the pump.fun web app by undocumented hosts | GraphQL queries, WebSocket subscriptions, gRPC and Kafka streams | | History | None published | Historical datasets for trades and token creation, realtime window for pools and transfers, Parquet exports through [cloud datasets](/docs/cloud/pumpfun) | | Rate limits | Unpublished | 30, 90 or 240 requests a minute by plan, custom on Enterprise | | Access | No key or documented third-party access | Access token, seven-day free trial | ## API key, free trial and pricing Create an access token at [account.bitquery.io](https://account.bitquery.io/) and follow [how to generate a token](/docs/authorization/how-to-generate/); there is no approval step. The free trial runs for seven days and includes 1,000 API points, 100 MCP credits and two simultaneous streams. Request rate limits by plan are 30 a minute on Personal, 90 on Pro and 240 on Scale, with custom limits on Enterprise; see [rate limits](/docs/plans/rate-limits/). Points and streams are explained on [how billing works](/docs/plans/how-billing-works/), and plan prices are on the [Pump.fun API product page](https://bitquery.io/products/pumpfun-api) and the [pricing page](https://bitquery.io/pricing). ## Video Tutorials #### Pump.fun Dev Dump Checker: Did the Dev Sell? #### Pump.fun Bundle Checker: Find Dev and Bundled Wallets with an API #### Pump.Fun API | Get Live Prices, Metadata, OHLCV, Trading Pair Stats, Charts #### Video Tutorial on Getting Pump.fun Trades #### Video Tutorial | How to Get the OHLC Data & Price of a Token on Pump.fun DEX in Realtime #### Video Tutorial | How to get Top Token Holders and Trading Volume for a Pump.fun Token #### Video Tutorial | How to get Top Traders of a Token on Solana Pump.fun DEX #### Video Tutorial | How to get first 100 Buyers of a Pump.fun Token #### Video Tutorial | How to get Top Token Creators on Pump.fun #### Video Tutorial | How to get Newly Created Pump.fun Tokens, Dev Address, Creation Time, Metadata #### Video Tutorial | How to get all Pump.fun Tokens created by a Dev #### Video Tutorial | How to get Liquidity of a Pump.fun Token #### Video Tutorial | Pump.fun Mayhem Mode API #### Video Tutorial | What Does a Pump.fun Trading Bot Need? 3 Live Feeds #### Video Tutorial | Can You Get Alerts for New Pump.fun Tokens? 3 Live Subscriptions #### Video Tutorial | Where Can You Get Pump.fun Historical Data? 4 Tables as Parquet Files ### Why does my Pump.fun query return "columns not available in combined dataset"? {#why-does-my-pumpfun-query-return-columns-not-available-in-combined-dataset} Fields like `Trade.Side` are only available with `dataset: realtime`. For historical queries use `dataset: archive` (or `combined`, which adds the realtime tail) and avoid `Trade_Side`, `Trade_Side_Type`, and similar realtime-only fields. --- ## Pump.fun Creator Rewards API: Fees, Claims, Fee Sharing URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/pump-fun-creator-rewards-api/ Track Pump.fun creator rewards on Solana: fees earned per trade, unclaimed balances, claims, fee sweeps, fee-sharing payouts and creator changes over GraphQL. # Pump.fun Creator Rewards API: Fees, Claims, Fee Sharing Every Pump.fun trade pays a creator fee into the coin creator's vault. The creator claims it later, splits it with shareholders, or, on a holder rewards coin, never sees it because it goes to holders. The Bitquery Pump.fun creator rewards API reads each step from the Solana chain: the fee earned on every trade, the unclaimed vault balance, claims, sweeps, fee-sharing payouts and creator changes. Fees on the bonding curve are in the Pump.fun program (`6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`); fees after graduation are in PumpSwap (`pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA`). All queries on this page run in the [Bitquery IDE](https://ide.bitquery.io) on the real-time dataset, which keeps about 12 hours of Solana instructions. To stream any of them, change `query` to `subscription` and remove `limit` and `orderBy`. Related pages: [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) for trades, launches and prices, and [Pump.fun Holder Rewards and Cashback API](/docs/blockchain/Solana/Pumpfun/pump-fun-holder-rewards-api/) for coins that pay their fees to holders. A three-minute walkthrough, [Pump.fun Creator Rewards and Holder Rewards API](https://youtu.be/vO_giwmdlWs), runs these queries live and shows where to get the history beyond the real-time window. ## How creator rewards move | Step | Program | Instruction | Event and fields | | --- | --- | --- | --- | | Earned on each trade | Pump.fun | every buy and sell | `TradeEvent`: `mint`, `creator`, `creator_fee_basis_points`, `creator_fee`, `creator_fee_unclaimed`, `quote_mint` | | Swept into the vault | Pump.fun, PumpSwap | `sweep_creator_fee` | `SweepBondingCurveFeeEvent`, `SweepPoolFeeEvent`: `mint`, `quote_mint`, `recipient`, `amount` | | Moved from PumpSwap to the Pump.fun vault | PumpSwap | `transfer_creator_fees_to_pump`, `transfer_creator_fees_to_pump_v2` | balance updates | | Claimed by the creator | Pump.fun, PumpSwap | `collect_creator_fee`, `collect_creator_fee_v2`, `collect_coin_creator_fee` | `CollectCreatorFeeEvent`: `creator`, `creator_fee`, `quote_mint` | | Split with shareholders | Pump.fun | `distribute_creator_fees`, `distribute_creator_fees_v2` | `DistributeCreatorFeesEvent`: `mint`, `admin`, `shareholders`, `distributed`, `quote_mint` | | Creator changed | Pump.fun, PumpSwap | `migrate_bonding_curve_creator`, `admin_cto`, `admin_cto_pool` | `MigrateBondingCurveCreatorEvent`, `AdminCtoEvent`: `mint`, `old_creator`, `new_creator` | In a six-hour sample on 2026-10-26 the Pump.fun program ran about 8,800 creator fee claims (split evenly between `collect_creator_fee` and `collect_creator_fee_v2`), 21,000 creator fee sweeps, 9,000 fee-sharing distributions and 700 creator migrations. Query both the v1 and v2 instruction names; filtering on `collect_creator_fee` alone misses half the claims. Fee amounts are paid in the coin's quote mint. Most coins trade against SOL, but coins can also be paired with another pump coin such as PUMP, or with tokens such as WBTC. Event arguments carry raw integer amounts in the quote mint's smallest unit; balance updates carry decimal amounts and USD. ## Latest creator reward claims Each row is one claim: the wallet that received the fee, the amount and its USD value, and which program paid it. `BalanceUpdate.Amount` greater than zero keeps the receiving side of each transfer. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-creator-reward-claims) ```graphql query PumpfunCreatorRewardClaims { Solana { InstructionBalanceUpdates( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {in: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"]}, Method: {in: ["collect_creator_fee", "collect_creator_fee_v2", "collect_coin_creator_fee"]}}}, BalanceUpdate: {Amount: {gt: "0"}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Address Method } } BalanceUpdate { Account { Address Token { Owner } } Amount AmountInUSD Currency { Symbol MintAddress } } } } } ``` ## Top Pump.fun creators by rewards claimed Ranks receiving wallets by the creator fees they claimed in the real-time window. The `Signer` filter drops claims that pump.fun runs for holder rewards coins (see [Pitfalls](#pitfalls)). [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-top-creators-by-rewards-claimed) ```graphql query PumpfunTopCreatorsByRewardsClaimed { Solana { InstructionBalanceUpdates( limit: {count: 20} orderBy: {descendingByField: "rewards_usd"} where: {Instruction: {Program: {Address: {in: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"]}, Method: {in: ["collect_creator_fee", "collect_creator_fee_v2", "collect_coin_creator_fee"]}}}, BalanceUpdate: {Amount: {gt: "0"}}, Transaction: {Result: {Success: true}, Signer: {not: "HckQ93Xqjjo8mwt5pNPWvyCTZXQZ858rvzmm7ZRrZg9t"}}} ) { BalanceUpdate { Account { Address } } claims: count rewards: sum(of: BalanceUpdate_Amount) rewards_usd: sum(of: BalanceUpdate_AmountInUSD) } } } ``` ## Creator rewards claimed by one wallet Totals for one creator wallet: number of claims, first and last claim time, and the amount claimed in SOL and USD. Replace the address with the creator you want. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-creator-rewards-claimed-by-wallet) ```graphql query PumpfunCreatorRewardsClaimedByWallet { Solana { InstructionBalanceUpdates( where: {Instruction: {Program: {Address: {in: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"]}, Method: {in: ["collect_creator_fee", "collect_creator_fee_v2", "collect_coin_creator_fee"]}}}, BalanceUpdate: {Account: {Address: {is: "F5fu9khC4jE4M5rX6ukm3VfUMGVKRVSp5DBsJkbHx8Sm"}}, Amount: {gt: "0"}}, Transaction: {Result: {Success: true}}} ) { Block { first_claim: Time(minimum: Block_Time) last_claim: Time(maximum: Block_Time) } claims: count rewards_sol: sum(of: BalanceUpdate_Amount) rewards_usd: sum(of: BalanceUpdate_AmountInUSD) } } } ``` ## Unclaimed creator rewards for a Pump.fun coin The latest `TradeEvent` for a mint carries `creator_fee_unclaimed`: the balance of the creator's vault right after that trade. It also shows the creator fee rate and the fee that trade paid. This is the number a creator rewards calculator needs. Replace the mint with the coin you want. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-unclaimed-creator-rewards-for-a-coin) ```graphql query PumpfunUnclaimedCreatorRewards { Solana { Instructions( limit: {count: 1} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {is: "TradeEvent"}, Arguments: {includes: {Name: {is: "mint"}, Value: {Address: {is: "555vsKfrU6FweWbdgWydj1JoC4c7UKyNYeYxFCxmA6f9"}}}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` Read `creator`, `creator_fee_basis_points`, `creator_fee`, `creator_fee_unclaimed` and `quote_mint` from the arguments. Divide the amounts by the quote mint's decimals: 9 for SOL, 6 for most pump coins. ## Pump.fun coins launched with a custom creator fee `create_v2` takes a `creator_fee_bps` argument. Coins created with a value above zero set their own creator fee rate. The first account of the instruction is the new mint. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-coins-with-custom-creator-fee) ```graphql query PumpfunCoinsWithCustomCreatorFee { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {is: "create_v2"}, Arguments: {includes: {Name: {is: "creator_fee_bps"}, Value: {BigInteger: {gt: "0"}}}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { Address } Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_String_Value_Arg { string } } } } } } } } ``` ## Pump.fun fee-sharing payouts Coins with fee sharing split the creator fee among shareholders. Each `DistributeCreatorFeesEvent` lists the shareholders with their `share_bps` (10,000 = 100%) and the amount `distributed`. This query keeps distributions that paid out more than zero. The `mint` argument on each row tells you which coin paid. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-fee-sharing-payouts) ```graphql query PumpfunFeeSharingPayouts { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {is: "DistributeCreatorFeesEvent"}, Arguments: {includes: {Name: {is: "distributed"}, Value: {BigInteger: {gt: "0"}}}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` ## Pump.fun creator fee sweeps Fees kept on a bonding curve or a PumpSwap pool stay there until someone runs `sweep_creator_fee`, which anyone can call. Creators, CTO owners and fee-sharing setups sweep before they collect. The events name the mint, the recipient and the swept amount. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-creator-fee-sweeps) ```graphql query PumpfunCreatorFeeSweeps { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {in: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"]}, Method: {in: ["SweepBondingCurveFeeEvent", "SweepPoolFeeEvent"]}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Address Method Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Integer_Value_Arg { integer } } } } } } } } ``` ## Pump.fun creator changes and community takeovers A coin's `creator` can change after launch. `migrate_bonding_curve_creator` moves the creator to a fee-sharing config, and `admin_cto` / `admin_cto_pool` hand a coin to a community takeover (CTO) owner. Both events carry `old_creator` and `new_creator`; `AdminCtoEvent` also carries the old and new creator fee rate. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-creator-changes-and-cto) ```graphql query PumpfunCreatorChangesAndCto { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {in: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"]}, Method: {in: ["MigrateBondingCurveCreatorEvent", "AdminCtoEvent", "AdminCtoPoolEvent"]}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Method Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Boolean_Value_Arg { bool } } } } } } } } ``` To find who actually deployed a coin, read the signer of its `create` or `create_v2` instruction, as in [token creation and dev address](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-creation-time-and-dev-address-of-a-pumpfun-token). The `creator` on later trade events is the current fee recipient, which may no longer be the deployer. ## Pitfalls - **About 12 hours of history.** `Instructions` and `InstructionBalanceUpdates` on Solana are real-time only; `archive` and `combined` return "no API tables" for them. For lifetime creator earnings, run the claim query as a subscription or read the [Solana Kafka streams](/docs/streams/kafka-streaming-concepts/) and store the rows yourself. - **Two instruction versions.** Claims arrive as `collect_creator_fee` and `collect_creator_fee_v2`, and fee sharing as `distribute_creator_fees` and `distribute_creator_fees_v2`. Filter on both names. - **Claims pump.fun runs itself.** On holder rewards coins the creator fee goes to holders. The signer `HckQ93Xqjjo8mwt5pNPWvyCTZXQZ858rvzmm7ZRrZg9t` collects those vaults so it can pay holders. Exclude it when you rank creators, and use the [holder rewards page](/docs/blockchain/Solana/Pumpfun/pump-fun-holder-rewards-api/) for those payouts. - **The vault belongs to the creator, not the coin.** `creator_fee_unclaimed` is the creator's vault balance, so a creator with several coins sees one balance across them. - **Not always SOL.** `quote_mint` can be another pump coin, WBTC, a tokenized stock or other SPL tokens. Raw event amounts use that mint's decimals. Balance-update amounts are already in decimal form. For an SPL fee, the receiving account is a token account, so read the wallet from `BalanceUpdate.Account.Token.Owner`. - **The `creator` field is mutable.** Fee-sharing migrations and community takeovers rewrite it. Use the create instruction's signer for the original deployer. --- ## Pump.fun Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/pumpfun/ Pump.fun token creations, migrations, trades, pools and OHLCV candles as Parquet, with a free sample, the file naming and DuckDB and Python examples. # Pump.fun Data Bitquery provides **Pump.fun data** as **Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), designed for large-scale analytics, historical backfills, and data lake integrations. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, etc**. For the real-time and query-based version of this dataset (GraphQL, WebSocket, gRPC), see the [Pump.fun API product page](https://bitquery.io/products/pumpfun-api). ## Available Pump.fun Topics For Pump.fun, Bitquery currently provides the following datasets: - **Creation & Migration Events** – Pump.fun token creation and migration events - **DEX Trades** – Executed trades on Pump.fun - **DEX Pools** – Liquidity pool metadata and activity - **OHLCV** – Open/High/Low/Close/Volume candles per token ## Sample Pump.fun Cloud Dataset You can explore schemas and validate your tooling using the **public Pump.fun sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/solana](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/solana) **Sample Parquet downloads (public S3)**. The `Pumpfun_Sample/` paths are sample paths only. - **Creation & Migration Events** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/pumpfun_creation_migrations/2026-07-01.parquet) - **DEX Trades** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/dex_trades/pumpfun/390740000_390740049.parquet) - **DEX Pools** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/Pumpfun_Sample/dex_pools/415261250_415261499.parquet) - **OHLCV** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/Pumpfun_Sample/ohlcv/2ra5idczuCQhDe1U5D52G8Rms6hzHuHeTqP51fdHpump.parquet) ## Pump.fun Dataset Directory Structure The `Pumpfun_Sample/` folder below holds sample files only. ```text bitquery-blockchain-dataset/ ├── solana/ │ ├── pumpfun_creation_migrations/ │ │ ├── 2026-07-01.parquet │ │ ├── 2026-07-02.parquet │ │ └── 2026-07-03.parquet │ └── dex_trades/ │ └── pumpfun/ │ ├── 390740000_390740049.parquet │ ├── 390740050_390740099.parquet │ ├── 390740100_390740149.parquet │ └── 390740150_390740199.parquet └── Pumpfun_Sample/ ├── dex_pools/ │ ├── 415261250_415261499.parquet │ ├── 415261500_415261749.parquet │ ├── 415261750_415261999.parquet │ └── 415262000_415262249.parquet └── ohlcv/ └── .parquet ``` ### File Naming Conventions Path and naming differ per topic: - **Creation & Migration Events** – `solana/pumpfun_creation_migrations/`, partitioned by date, `.parquet`. Each file contains both creations (`create` / `create_v2`) and migrations (`migrate` / `migrate_v2`): ``` 2026-07-01.parquet ``` - **DEX Trades** – `solana/dex_trades/pumpfun/`, partitioned by slot range, `_.parquet`: ``` 390740000_390740049.parquet ``` - **DEX Pools** – `Pumpfun_Sample/dex_pools/` (sample path), partitioned by slot range, `_.parquet`: ``` 415261250_415261499.parquet ``` - **OHLCV** – `Pumpfun_Sample/ohlcv/` (sample path), one file per token, named by the token mint address, `.parquet`: ``` 2ra5idczuCQhDe1U5D52G8Rms6hzHuHeTqP51fdHpump.parquet ``` ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets?network=solana) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). Datasets you can buy on the Data Store: - [Pump.fun](https://bitquery.io/datastore/datasets/pumpfun) — bonding-curve trades, token creations, migrations, pools and OHLCV - [PumpSwap](https://bitquery.io/datastore/datasets/pumpswap) — trades on the AMM that Pump.fun tokens migrate to This listing is not the full catalogue. Other topics, chains and date ranges are available on request from **sales@bitquery.io**. ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/dex_trades/pumpfun/390740000_390740049.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/dex_trades/pumpfun/390740000_390740049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access Data Store exports are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming Pump.fun data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - [**gRPC (CoreCast)**](/docs/grpc/solana/introduction) for Solana - **GraphQL subscriptions** --- ## Pump.fun Guides: Trades, Bonding Curve, PumpSwap URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/ Start here for Pump.fun data on Solana. Pick the Bitquery page for trades, bonding curve and market cap, PumpSwap pools, migration, gRPC streams or Data Store exports. # Pump.fun Guides: Trades, Bonding Curve, PumpSwap :::tip Want structured trades, OHLC and market cap? Start with the Trading API The [**Trading API**](/docs/trading/trading-data-overview) is the fastest path to clean Pump.fun and PumpSwap market data. [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) returns **MEV-filtered swaps with USD price, market cap and supply on every row**, across **10 chains in one API**. Pre-aggregated OHLC down to one second comes from [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs), so you never build candles yourself. Reach for the chain-level Pump.fun pages below when you need what the Trading API deliberately does not carry: **history older than the Trading window**, **bonding-curve internals**, or raw per-instruction detail. ::: ### Which Pump.fun page do I need? | You want | Go to | | --- | --- | | Trades, new launches, prices, OHLCV, top traders, holders | [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) | | Market cap, FDV, circulating supply, bonding-curve progress | [Marketcap & Bonding Curve API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-Marketcap-Bonding-Curve-API/) | | Detect tokens graduating from the curve to the AMM | [Pump.fun to PumpSwap migration](/docs/blockchain/Solana/Pumpfun/pump-fun-to-pump-swap/) | | PumpSwap AMM trades, pools and liquidity | [PumpSwap API](/docs/blockchain/Solana/Pumpfun/pump-swap-api/) | | Creator fees, unclaimed rewards, fee sharing, CTO changes | [Creator Rewards API](/docs/blockchain/Solana/Pumpfun/pump-fun-creator-rewards-api/) | | Holder rewards coins, payouts to holders, cashback claims | [Holder Rewards and Cashback API](/docs/blockchain/Solana/Pumpfun/pump-fun-holder-rewards-api/) | For the product overview, delivery channels (gRPC, Kafka, WebSocket), pricing and the free trial, see the [Pump.fun API product page](https://bitquery.io/products/pumpfun-api). To get started, [sign up](https://account.bitquery.io/auth/signup?redirect_to=https%3A%2F%2Fide.bitquery.io%2F) with Bitquery and generate your [access token](https://account.bitquery.io/user/api_v2/access_tokens) by following [these steps](/docs/authorization/how-to-generate/). If you need help getting data on PumpFun, reach out to [support](https://t.me/Bloxy_info). For live DEX prices and 24h volume across graduated Pump.fun tokens, see [DEXrabbit's Pump.fun category](https://dexrabbit.bitquery.io/categories/pump-fun). ## What Pump.fun data can I get? The Bitquery PumpFun API helps you fetch on-chain data for PumpFun, including: - **Token Trades** - **Trade Prices** - **Token Creation** - **Creator Holdings** - **Token Holdings** - **Bonding Curve Progress** - **Migration to PumpSwap** - **Trades of a User** - **Trade Metrics**: volume, trades, sellers and buyers - **Token Liquidity** - **Token Price Change** - **Historical Data for Aggregated Metrics** ## How is Bitquery different from Solana RPC? The Bitquery PumpFun APIs are based on GraphQL and are highly flexible. You can fetch trades, token creation, token holdings, bonding curve progress, and migration information for a specific token or wallet over a given time period, and join the results with other on-chain data. **Solana RPC** - JSON-RPC endpoint exposing raw on-chain state & transactions - No built-in history or analytics; you build or outsource any indexing and aggregation - Ideal for submitting transactions **Bitquery Solana API** - GraphQL endpoint over pre-indexed, parsed Solana data (token transfers, DEX trades, NFTs, etc.) - Historical data, joins, aggregations & real-time subscriptions - Great for real-time data and historical backtesting without running your own indexer ## What is the difference between Solana Geyser and Bitquery Kafka streams? **Solana Geyser stream** - **Data & Protocol**: Runs as a plugin in your own Solana validator, emitting raw on-chain events (account updates, slot status changes, processed transactions, block metadata) over binary or gRPC feeds. - **Infra & Maintenance**: You must host, scale, and secure the node yourself, parse and index all raw data client-side, and deal with only basic filtering. Latency and reliability depend entirely on your setup, and there is no built-in historical querying. **Bitquery Kafka Stream** - **Data & Protocol**: Provides fully managed Kafka topics (`solana.dextrades.proto`, `solana.tokens.proto` and `solana.transactions.proto`) delivering pre-parsed, enriched Protocol-Buffers events (DEX trades, token transfers, supply/balance updates, instructions, blocks, etc.). - **Infra & Maintenance**: Enterprise-grade, auto-scaling Kafka streams with sub-second latency, schema-based filtering, instruction-level balance updates, built-in replication and failover. No node ops or custom parsing needed. Read more in [Real-time Solana data streams](/docs/streams/real-time-solana-data/) and contact sales via [Telegram](https://t.me/Bloxy_info) or [form](https://bitquery.io/forms/api) for a **Trial**. ## Does Bitquery support PumpFun WebSockets and Webhooks? Yes. Bitquery supports both WebSockets and webhooks. You can convert most of the GraphQL APIs into **GraphQL streams** by changing `query` to `subscription` and monitor the data over a WebSocket. More information and [code samples are available here](/docs/subscriptions/websockets/). ## All Pump.fun guides - [Pump Fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [Pump Swap API](/docs/blockchain/Solana/Pumpfun/pump-swap-api/) - [Marketcap Bonding Curve API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-Marketcap-Bonding-Curve-API/) - [Pump Fun to Pump Swap](/docs/blockchain/Solana/Pumpfun/pump-fun-to-pump-swap/) - [Pump.fun gRPC streams](/docs/grpc/solana/examples/pump-fun-grpc-streams/) - [Pump.fun data in Snowflake, AWS S3 and BigQuery](/docs/cloud/pumpfun/) - [Pump.fun token sniffer](/docs/usecases/pumpfun-token-sniffer/) - [Pump.fun launch pulse (MCP example)](/docs/mcp/trading/examples/pumpfun-launch-pulse/) ## Related Solana APIs - [Solana Dex Trades](/docs/blockchain/Solana/solana-dextrades) - [Solana Transactions](/docs/blockchain/Solana/solana-transactions) - [Solana Transfers](/docs/blockchain/Solana/solana-transfers) - [Solana Balance Updates](/docs/blockchain/Solana/solana-balance-updates) - [Solana Instructions](/docs/blockchain/Solana/solana-instructions) - [Solana Fees API](/docs/blockchain/Solana/solana_fees_api) - [Building an AI Trading Agent on Solana](/docs/blockchain/Solana/ai-agent-solana-data) ## Videos ### Video Tutorial | Get Live Prices, Metadata, OHLCV, Trading Pair Stats and Charts ### Video Tutorial | How to Get the OHLC Data & Price of a Token on Pump Fun DEX in Realtime ### Video Tutorial | How to Track PumpFun DEX Trades and Newly Launched Tokens in Realtime ### Video Tutorial | How to get Token Holders and Trading Volume for a PumpFun Token ### Video Tutorial | How to track the PumpFun Tokens which are about to Graduate to PumpSwap in Realtime --- ## Pump.fun Holder Rewards and Cashback API URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/pump-fun-holder-rewards-api/ Track Pump.fun holder rewards coins and cashback on Solana: new holder rewards launches, fee payouts to holders, wallet totals and cashback claims over GraphQL. # Pump.fun Holder Rewards and Cashback API A Pump.fun holder rewards coin sends its creator fee to the people holding the coin instead of to a creator wallet. Pump.fun pays those holders itself, with the `distribute_fee_to_holders` instruction, and holders do not claim anything. Cashback coins worked the other way round: the fee went back to traders, who claimed it. New cashback coins can no longer be created, but existing ones still trade and their cashback can still be claimed. The Bitquery API reads both from the Solana chain: which coins pay holder rewards, every payout and its recipients, what a wallet received, and every cashback claim. The flag is set at launch: `create_v2` takes `is_holder_reward` (and, earlier, `is_cashback_enabled`). A holder rewards coin cannot go back to a regular coin, but a regular coin can be converted through a community takeover. Trade events then report `holder_rewards_bps` and `holder_rewards`, which are zero on regular coins. All queries run in the [Bitquery IDE](https://ide.bitquery.io) on the real-time dataset, which keeps about 12 hours of Solana instructions. To stream one, change `query` to `subscription` and remove `limit` and `orderBy`. For creator fees, claims and fee sharing on regular coins, see the [Pump.fun Creator Rewards API](/docs/blockchain/Solana/Pumpfun/pump-fun-creator-rewards-api/). A three-minute walkthrough, [Pump.fun Creator Rewards and Holder Rewards API](https://youtu.be/vO_giwmdlWs), runs these queries live and shows where to get the history beyond the real-time window. | What you want | Instruction or event | Program | | --- | --- | --- | | New holder rewards coins | `create_v2` with `is_holder_reward` true | Pump.fun | | Is a coin a holder rewards coin | `TradeEvent` `holder_rewards_bps` above zero | Pump.fun | | Payout per coin | `DistributeFeeToHoldersEvent`: `mint`, `quote_mint`, `recipients`, `total` | Pump.fun | | Payout per holder wallet | balance updates of `distribute_fee_to_holders` | Pump.fun | | Cashback claims | `ClaimCashbackEvent`: `user`, `amount`, `total_claimed`, `total_cashback_earned` | Pump.fun, PumpSwap | ## New Pump.fun holder rewards coins Lists coins launched with `is_holder_reward` set to true. The first account of the instruction is the new mint; the arguments carry the name, symbol and the other launch flags such as `is_mayhem_mode`. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-new-holder-rewards-coins) ```graphql query PumpfunNewHolderRewardsCoins { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {is: "create_v2"}, Arguments: {includes: {Name: {is: "is_holder_reward"}, Value: {Boolean: true}}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { Address } Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_String_Value_Arg { string } } } } } } } } ``` ## Latest Pump.fun holder reward payouts Each `DistributeFeeToHoldersEvent` is one payout round for one coin: the `mint`, the `quote_mint` the reward is paid in, the number of `recipients` and the `total` paid, in the quote mint's smallest unit. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-holder-reward-payouts) ```graphql query PumpfunHolderRewardPayouts { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {is: "DistributeFeeToHoldersEvent"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` To follow one coin, add `Arguments: {includes: {Name: {is: "mint"}, Value: {Address: {is: ""}}}}` to the `Program` filter. ## Top Pump.fun holder rewards recipients Ranks the accounts that received the most holder rewards in the real-time window, per reward currency. For SOL rewards `Account.Address` is the wallet; for SPL rewards such as WBTC it is a token account and `Token.Owner` is the wallet. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-top-holder-rewards-recipients) ```graphql query PumpfunTopHolderRewardsRecipients { Solana { InstructionBalanceUpdates( limit: {count: 20} orderBy: {descendingByField: "received_usd"} where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {is: "distribute_fee_to_holders"}}}, BalanceUpdate: {Amount: {gt: "0"}}, Transaction: {Result: {Success: true}}} ) { BalanceUpdate { Account { Address Token { Owner } } Currency { Symbol MintAddress } } payouts: count received: sum(of: BalanceUpdate_Amount) received_usd: sum(of: BalanceUpdate_AmountInUSD) } } } ``` ## Holder rewards received by one wallet Totals per reward currency for one wallet. The `any` filter matches SOL paid to the wallet itself and SPL tokens paid to token accounts it owns. Replace the address with the wallet you want. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-holder-rewards-received-by-wallet) ```graphql query PumpfunHolderRewardsReceivedByWallet { Solana { InstructionBalanceUpdates( where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {is: "distribute_fee_to_holders"}}}, BalanceUpdate: {Amount: {gt: "0"}}, any: [{BalanceUpdate: {Account: {Address: {is: "GG5ATPW7bxGm5y4aGa2uWWZV1JvjETiM2Rabc2fT8Y7f"}}}}, {BalanceUpdate: {Account: {Token: {Owner: {is: "GG5ATPW7bxGm5y4aGa2uWWZV1JvjETiM2Rabc2fT8Y7f"}}}}}], Transaction: {Result: {Success: true}}} ) { BalanceUpdate { Currency { Symbol MintAddress } } payouts: count received: sum(of: BalanceUpdate_Amount) received_usd: sum(of: BalanceUpdate_AmountInUSD) } } } ``` ## Pump.fun cashback claims Cashback coins launched before cashback was retired still pay out when traders claim. Claims run on the Pump.fun program (`claim_cashback`, `claim_cashback_v2`) and on PumpSwap (`claim_cashback`). Each `ClaimCashbackEvent` carries the `user`, the `amount` claimed, and the user's running `total_claimed` and `total_cashback_earned`. [Run it in the IDE ➤](https://ide.bitquery.io/Pumpfun-cashback-claims) ```graphql query PumpfunCashbackClaims { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {in: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"]}, Method: {is: "ClaimCashbackEvent"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Instruction { Program { Address Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` `total_cashback_earned` minus `total_claimed` is what that user can still claim. ## Pitfalls - **About 12 hours of history.** `Instructions` and `InstructionBalanceUpdates` on Solana are real-time only. For lifetime payouts, store a subscription or read the [Solana Kafka streams](/docs/streams/kafka-streaming-concepts/). - **Pump.fun's own accounts show up.** Payouts are signed by `HckQ93Xqjjo8mwt5pNPWvyCTZXQZ858rvzmm7ZRrZg9t`, and that address also appears as a token-account owner in the recipient list. Drop it when you rank real holders. - **Rewards are not always SOL.** The reward is paid in the coin's quote mint: SOL, another pump coin, WBTC and other SPL tokens all occur. Raw event amounts use that mint's decimals. - **The creator field points at pump.fun.** On a holder rewards coin, `creator` is a pump.fun-controlled address, not the deployer. Use the signer of `create_v2` for the deployer. - **Trade events still report a creator fee.** On holder rewards coins `creator_fee` equals `holder_rewards`; the fee is computed as before and only the recipient changes. --- ## Pump.fun Marketcap & Bonding Curve API URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/Pump-Fun-Marketcap-Bonding-Curve-API/ Stream Pump.fun market cap, FDV, circulating supply and bonding curve progress on Solana with the Bitquery Trading GraphQL API. # Pump.fun Marketcap & Bonding Curve API :::tip Need real-time Pump.fun market-cap data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Pump.fun market-cap swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Pump.fun market-cap data older than ~30 days**, raw per-swap detail, or call / event context. ::: For delivery channels, pricing and the free trial, see the [Pump.fun API product page](https://bitquery.io/products/pumpfun-api). In this document, we explore examples that retrieve market cap, bonding curve progress, and whether a token has migrated to PumpSwap. The full query reference is the [Pump.fun API documentation](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/). The Moonshot API is also available — you can access its documentation [here](/docs/blockchain/Solana/Moonshot-API/). These APIs can also be delivered through different streams, including Kafka, for zero-latency requirements. Please contact us on Telegram. :::note The `Trade Side Account` field is not available for aggregate queries in the Archive and Combined datasets. ::: ## Get Latest Marketcap of a PumpFun Token Use **Trading API** **`Pairs`**: latest row per token with **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, **`Token.Id`** matching your mint (**`solana:`**), **`Market.ProtocolFamily`** **Pumpfun**, and interval duration **> 1** second. The response includes **`Supply.MarketCap`**, **FDV**, **OHLC**, **volume**, and **token** metadata. Test the query [here](https://ide.bitquery.io/specific-pumpfun-token-latest-marketcap).
Click to expand GraphQL query ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { includesCaseInsensitive: "solana:7GMB7XbtTdvnHkPjH6yEwTUB3HYf5dqC3FKyr2sueMEh" } } Interval: { Time: { Duration: { gt: 1 } } } Market: { ProtocolFamily: { is: "Pumpfun" } } } ) { Token { Name Id Address Symbol } Block { Time } Market { Program Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ```
## Get Tokens with a specific MarketCap Stream **Trading** **`Pairs`** in real time for **Solana** tokens on **Pumpfun** when **`Supply.MarketCap`** is above a threshold (example below: **> $10,000** USD). Change **`Supply.MarketCap.gt`** to tune the floor. Interval duration must be **> 1** second. Try it with this [stream link](https://ide.bitquery.io/realtime-stream-pumpfun-tokens-with-marketcap-above-10k-marketcap#).
Click to expand GraphQL subscription ```graphql subscription { Trading { Pairs( where: { Token: { Id: { includesCaseInsensitive: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 10000 } } Market: { ProtocolFamily: { is: "Pumpfun" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
You can also use **`TokenSupplyUpdates`** for supply-driven views; see the [token supply cube](/docs/blockchain/Solana/token-supply-cube/). ## Top Pump.fun tokens by market cap change in the last 1 hour **Trading** **`Pairs`** with **1-hour** OHLC (`Duration: { eq: 3600 }`), **`Market.ProtocolFamily`** **Pumpfun**, **`Token.Network`** **Solana**, ordered by **`change_mcap`**: **(close − open) × total supply**. Up to **50** rows; adjust **`limit`** as needed. Test the query [here](https://ide.bitquery.io/Top-pump-fun-tokens-by-Marketcap-change-in-last-1-hr).
Click to expand GraphQL query ```graphql { Trading { Pairs( limit: { count: 50 } orderBy: { descendingByField: "change_mcap" } where: { Market: { ProtocolFamily: { is: "Pumpfun" } } Interval: { Time: { Duration: { eq: 3600 } } } Token: { Network: { is: "Solana" } } } ) { Currency { Id Name Symbol } Token { Network Symbol Address } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } change_mcap: calculate( expression: "($Price_Ohlc_Close-$Price_Ohlc_Open) * Supply_TotalSupply" ) Price { Ohlc { Open Close } } } } } ```
## Track Pump Fun Token Migrations to PumpSwap in Realtime - Subscription Stream successful PumpSwap **`create_pool`** instructions (**`pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA`**) at **depth 1**, excluding placeholder mint **`11111111111111111111111111111111`** in instruction arguments. Migrated pair details appear under **`Instruction.Accounts`**. Run the subscription [in the Bitquery IDE](https://ide.bitquery.io/pumpfun-migration-stream_4#).
Click to expand GraphQL subscription ```graphql subscription { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Depth: { eq: 1 } Program: { Method: { is: "create_pool" } Address: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } Arguments: { includes: [{ Value: { Address: { notIn: ["11111111111111111111111111111111"] } } }] } } } } ) { Migrate_Time: Block { Time } Instruction { Program { Name Method AccountNames Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Integer_Value_Arg { integer } } } } Accounts { Address IsWritable Token { Mint Owner ProgramId } } CallerIndex Depth CallPath } Transaction { Signature Signer Fee } } } } ```
## Latest Pump Fun Token Migrations to PumpSwap - Query Same filters as the subscription, with **`limit: { count: 20 }`** and **`orderBy: { descending: Block_Slot }`** for recent migrations. Run the query [in the Bitquery IDE](https://ide.bitquery.io/pumpfun-migration-query#).
Click to expand GraphQL query ```graphql query { Solana { Instructions( limit: { count: 20 } orderBy: { descending: Block_Slot } where: { Transaction: { Result: { Success: true } } Instruction: { Depth: { eq: 1 } Program: { Method: { is: "create_pool" } Address: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } Arguments: { includes: [{ Value: { Address: { notIn: ["11111111111111111111111111111111"] } } }] } } } } ) { Migrate_Time: Block { Time } Instruction { Program { Name Method AccountNames Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Integer_Value_Arg { integer } } } } Accounts { Address IsWritable Token { Mint Owner ProgramId } } CallerIndex Depth CallPath } Transaction { Signature Signer Fee } } } } ```
## Pumpfun Token Migrations on a specific date - Historical Retrieve Pump.fun token migrations on a specific date. The API returns transfers to the PumpSwap migration receiver address for the given date. [Try the query](https://ide.bitquery.io/pumpfun-transfers-type-v1-to-pumpfun-migrations_1)
Click to expand GraphQL query ```graphql { solana { transfers( options: { limit: 500 } date: { is: "2024-10-18" } currency: { not: "SOL" } externalProgramId: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } transferType: { in: transfer } receiverAddress: { is: "39azUYFWPz3VHgKCf3VChUwbpURdCHRxjWVowf5jUJjg" } ) { block { height timestamp { iso8601 } } instruction { action { name } callPath external externalAction { name type } program { name id } externalProgram { id name } } currency { name symbol address } date { date } amount sender { address mintAccount type } receiver { address mintAccount type } transaction { signature signer } transferType } } } ```
## Check if the Pump Fun Token has migrated to PumpSwap - API To check if a Pump Fun Token has migrated to PumpSwap, we can use the below query. In this query we are checking if this token `6SmgaPU4LMd8eWhamtpTtArr7JYPKZSF8AKK2Uy5pump` has migrated to PumpSwap. You can run the query [here](https://ide.bitquery.io/check-if-a-pump-fun-token-has-migrated_1).
Click to expand GraphQL query ```graphql query ($token: String) { Solana { Instructions( where: { Instruction: { Accounts: { includes: { Address: { is: $token } } } Program: { Address: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } Logs: { includes: { includes: "Migrate" } } } Transaction: { Result: { Success: true } } } ) { Migrate_Time: Block { Time } Instruction { Program { Name Method Arguments { Name Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Address AccountNames } Accounts { Token { ProgramId Owner Mint } IsWritable Address } } Transaction { Signature } joinInstructions( join: any_inner Transaction_Index: Transaction_Index Transaction_Signature: Transaction_Signature where: { Instruction: { Program: { Address: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } Method: { is: "create_pool" } } } } ) { Instruction { Program { Name Method Arguments { Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } } Type Name } AccountNames } Accounts { Address Token { Owner Mint } } } } } } } ``` ```json { "token":"6SmgaPU4LMd8eWhamtpTtArr7JYPKZSF8AKK2Uy5pump" } ```
## Bonding Curve Progress API Below query will give you the Bonding curve progress percentage of a specific Pump Fun Token. ### Bonding Curve Progress Formula - **Formula**: BondingCurveProgress = 100 - ((leftTokens \* 100) / initialRealTokenReserves) Where: - leftTokens = realTokenReserves - reservedTokens - initialRealTokenReserves = totalSupply - reservedTokens - **Definitions**: - `initialRealTokenReserves` = `totalSupply` - `reservedTokens` - `totalSupply`: 1,000,000,000 (Pump Fun Token) - `reservedTokens`: 206,900,000 - Therefore, `initialRealTokenReserves`: 793,100,000 - `leftTokens` = `realTokenReserves` - `reservedTokens` - `realTokenReserves`: Token balance at the market address. :::note **Simplified Formula**: BondingCurveProgress = 100 - (((balance - 206900000) \* 100) / 793100000) ::: ### Additional Notes - **Balance Retrieval**: - The `balance` is the token balance at the market address. - Use this query to fetch the balance and then we use `expressions` to calculate the bonding curve progress percentage in the query itself: [Query Link](https://ide.bitquery.io/get-the-bonding-curve-progress-percentage_1).
Click to expand GraphQL query ```graphql query GetBondingCurveProgressPercentage { Solana { DEXPools( limit: { count: 1 } orderBy: { descending: Block_Slot } where: { Pool: { Market: { BaseCurrency: { MintAddress: { is: "3j3fKH9Nw9cPZsZSPvE5qNgLWnxGk6tBHM9kX3qopump" } } } Dex: { ProgramAddress: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } } } ) { Bonding_Curve_Progress_percentage: calculate( expression: "100 - ((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PriceInUSD PostAmountInUSD } Base { Balance: PostAmount } } } } } ```
## Track Pump Fun Tokens above 95% Bonding Curve Progress in realtime We can use above Bonding Curve formulae and get the Balance of the Pool needed to get to 95% and 100% Bonding Curve Progress range. And then track liquidity changes which result in `Base{PostAmount}` to fall in this range. You can run and test the saved query [here](https://ide.bitquery.io/Pump-Fun-Tokens-between-95-and-100-bonding-curve-progress_3).
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { DEXPools( where: { Pool: { Base: { PostAmount: { gt: "206900000", lt: "246555000" } } Dex: { ProgramAddress: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } Market: { QuoteCurrency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" ] } } } } Transaction: { Result: { Success: true } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { BaseCurrency { MintAddress Name Symbol } MarketAddress QuoteCurrency { MintAddress Name Symbol } } Dex { ProtocolName ProtocolFamily } Base { Balance: PostAmount } Quote { PostAmount PriceInUSD PostAmountInUSD } } } } } ```
## Top 100 About to Graduate Pump Fun Tokens We can use below query to get top 100 About to Graduate Pump Fun Tokens. You can run and test the saved query [here](https://ide.bitquery.io/Top-100-graduating-pump-fun-tokens-in-last-5-minutes_2).
Click to expand GraphQL query ```graphql { Solana { DEXPools( limitBy: { by: Pool_Market_BaseCurrency_MintAddress, count: 1 } limit: { count: 100 } orderBy: { ascending: Pool_Base_PostAmount } where: { Pool: { Base: { PostAmount: { gt: "206900000" } } Dex: { ProgramAddress: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } Market: { QuoteCurrency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" ] } } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { BaseCurrency { MintAddress Name Symbol } MarketAddress QuoteCurrency { MintAddress Name Symbol } } Dex { ProtocolName ProtocolFamily } Base { Balance: PostAmount(maximum: Block_Time) } Quote { PostAmount PriceInUSD PostAmountInUSD } } } } } ```
## Video Tutorials ### Video Tutorial | How to get Bonding Curve Progress of any Pump Fun Token ### Video Tutorial | How to track Pump Fun Token Migrations to PumpSwap in realtime ### Video Tutorial | How to get Top Pump Fun Tokens by Marketcap Value ### Video Tutorial | How to track the Pump Fun Tokens which are about to Graduate in Realtime --- ## Pump.fun Token Sniffer URL: https://docs.bitquery.io/docs/usecases/pumpfun-token-sniffer/ Build Pump.fun Token Sniffer: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Pump.fun Token Sniffer This guide demonstrates how to build a basic Pump.fun token analysis tool using Bitquery APIs. The tool displays various on-chain metrics related to Pump.fun tokens on Solana, helping users understand token distribution, holder behavior, and transfer patterns. It is built on the [Bitquery Pump.fun API](https://bitquery.io/products/pumpfun-api) — see the product page for channels, pricing and the free trial. > **⚠️ Important: Proof of Concept** > > This tool is a **proof of concept** that displays various metrics and data points about Pump.fun tokens. It does **not** make definitive claims about whether a token is a scam or legitimate. The metrics shown are for informational purposes only. You should conduct your own research and due diligence before making any investment decisions. This tool demonstrates how to use Bitquery APIs to build token analysis tools - you can extend this foundation to create more advanced analysis systems. GitHub Repository: [pumpfun-token-sniffer](https://github.com/Akshat-cs/pumpfun-token-sniffer) Solana Scam Token Checker app with a Pump.fun token address field and a table scoring recent tokens on liquidity, insider, creator-holdings and holder checks ## Overview The Pump.fun Token Sniffer is a Python-based analysis tool built with Bitquery APIs that displays various metrics about Pump.fun tokens. The tool provides: ### Token Information Metrics - **Bonding Curve Address**: Automatically detects and displays the bonding curve address - **Token Creation Details**: Creator address, creation timestamp, and transaction signature - **Token Metadata**: Name, symbol, IPFS metadata (image, website, social links, description) - **Token Status**: Mayhem mode status and graduation status (whether token has migrated to PumpSwap) ### Holder Distribution Metrics - **Top 10 Holders**: List of addresses with the largest token holdings - **Holding Percentages**: Percentage of total supply held by each top holder - **Creator Holdings**: Percentage of tokens held by the creator (if in top 10) - **Top 10 Concentration**: Total percentage of supply held by top 10 holders - **Holder Distribution Checks**: Flags if any single holder (excluding bonding curve) holds more than 5% of supply ### Holder Activity Metrics - **Pump Token Portfolio**: Number of different Pump.fun tokens each holder owns - **Trading Activity**: Number of trades executed by each holder in the last 6 hours - **Holder Engagement**: Activity level indicators based on recent trading ### Transfer and Purchase Analysis Metrics - **Transfer Statistics**: Total addresses that received token transfers - **Purchase Statistics**: Number of addresses that purchased the token - **Transfer vs Purchase Comparison**: Analysis of addresses that received transfers vs those that made purchases - **Transfer Timing Analysis**: Comparison of first transfer timestamps vs first purchase timestamps - **Transfer Amounts**: Total amounts transferred, purchased, and transferred without corresponding purchases ### Liquidity Metrics - **Pool Liquidity**: Current SOL liquidity in the bonding curve pool ### Interface Options - **Web UI**: Modern web interface for interactive analysis - **Command Line**: Terminal-based interface for quick checks ## Prerequisites 1. **Python 3.8+** installed on your system 2. **Bitquery API Token** - Get your API token [here](/docs/authorization/how-to-generate/) 3. Basic understanding of Solana blockchain and Pump.fun tokens ## Installation 1. Clone the repository: ```bash git clone https://github.com/Akshat-cs/pumpfun-token-sniffer cd pumpfun-token-sniffer ``` 2. Install the required dependencies: ```bash pip install -r requirements.txt ``` 3. Set up your API key: - Copy `.env.sample` to `.env`: ```bash cp .env.sample .env ``` - Edit `.env` and replace `your_api_key_here` with your actual Bitquery API key: ``` BITQUERY_API_KEY=BQ_your_actual_api_key_here ``` ## Project Structure The project consists of two main files: - **`check_phishy_token.py`**: Core analysis logic with GraphQL queries and detection algorithms - **`app.py`**: Flask web application that provides the UI and API endpoints ## How It Works The tool uses multiple GraphQL queries from Bitquery APIs to fetch and display various token metrics: 1. **Bonding Curve Detection**: Finds the bonding curve address by querying Pump.fun creation instructions 2. **Token Creation Data**: Retrieves creator address, creation time, and transaction details 3. **Token Metadata**: Fetches token name, symbol, and IPFS metadata 4. **First Transfers Query**: Fetches the first transfers of a token to various addresses 5. **First Buys Query**: Retrieves purchase data for addresses that received transfers 6. **Top Holders Query**: Gets top 10 holders with their current holdings 7. **Holder Activity Analytics**: Fetches pump token portfolio counts and recent trade activity for each holder 8. **Holder Distribution Analysis**: Calculates concentration metrics and distribution patterns 9. **Liquidity Query**: Gets current pool liquidity information 10. **Graduation Check**: Verifies if token has migrated to PumpSwap ### Transfer vs Purchase Analysis One of the metrics the tool displays is a comparison between token transfers and purchases: - **Addresses with transfers but no purchases**: Shows addresses that received tokens via transfer but never purchased them - **Transfer timing vs purchase timing**: Compares when addresses first received transfers vs when they first made purchases - **Transfer amounts**: Displays total amounts transferred, purchased, and the difference **Note**: This metric is displayed for informational purposes. While unusual patterns (like many addresses receiving transfers without purchases) can be noteworthy, they do not definitively indicate whether a token is legitimate or not. Many factors contribute to token distribution patterns, and this tool simply presents the data for your analysis. ### Code Walkthrough #### 1. Bonding Curve Detection The tool first identifies the bonding curve address by querying Pump.fun creation instructions: ```python def get_bonding_curve_address(token_address: str, api_key: str) -> Optional[Dict]: """ Get the bonding curve address for a Pump.fun token by querying the create instruction. The bonding curve is the 3rd account in the Instruction accounts array. """ query = """ query MyQuery($token: String) { Solana { Instructions( where: { Instruction: { Program: { Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"} Method: {in: ["create", "create_v2"]} } Accounts: {includes: {Address: {is: $token}}} } Transaction: {Result: {Success: true}} } ) { Block { Creation_time: Time } Instruction { Accounts { Address } Program { AccountNames Method Arguments { Name Type Value { ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Boolean_Value_Arg { bool } } } } } Transaction { Creation_transaction: Signature DevAddress: Signer } } } } """ ``` The bonding curve is extracted from the 3rd account (index 2) in the accounts array. This query also extracts token metadata (name, symbol, URI), creator address, creation time, and Mayhem mode status. #### 2. First Transfers Query This query fetches the first transfers of the token to addresses (excluding the bonding curve): ```python def get_first_transfers_pumpfun(token_address: str, bonding_curve: str, api_key: str) -> List[Dict]: """ Query 1: Get the first transfers of a Pump.fun token to addresses (Solana). """ query = """ query MyQuery($token: String, $bonding_curve: String) { Solana { Transfers( limit: { count: 1000 } orderBy: { ascendingByField: "Block_first_transfer" } where: { Transfer: { Receiver: { Token: { Owner: { not: $bonding_curve notIn: ["8psNvWTrdNTiVRNzAgsou9kETXNJm2SXZyaKuJraVRtf", "AkTgH1uW6J6j6QHmFNGzZuZwwXaHQsPCpHUriED28tRj"] } } } Currency: { MintAddress: { is: $token } } } Transaction: { Result: { Success: true } } } ) { Transfer { Receiver { Token { Owner } } } Block { first_transfer: Time(minimum: Block_Time) } total_transferred_amount: sum(of: Transfer_Amount) } } } """ ``` This query: - Limits results to 1,000 addresses - Excludes the bonding curve and known system addresses - Groups by receiver address - Gets the first transfer timestamp and total transferred amount #### 3. First Buys Query This query checks if the addresses that received transfers ever bought the token: ```python def get_first_buys_pumpfun(token_address: str, buyers_list: List[str], api_key: str) -> Dict[str, Dict]: """ Query 2: Get first buys of an address list for a specific Pump.fun token (Solana). """ query = """ query MyQuery($token: String!, $buyersList: [String!]) { Solana { DEXTradeByTokens( orderBy: { ascendingByField: "Block_first_buy" } where: { Trade: { Account: { Token: { Owner: { in: $buyersList } } } Currency: { MintAddress: { is: $token } } Side: { Type: { is: buy } } } Transaction: { Result: { Success: true } } } ) { Trade { Account { Token { Owner } } Currency { Name Symbol MintAddress } Side { Type } } Block { first_buy: Time(minimum: Block_Time) } total_bought_amount: sum(of: Trade_Amount) } } } """ ``` This query: - Filters for buy-side trades only - Groups by buyer address - Gets the first buy timestamp and total bought amount #### 4. Transfer vs Purchase Analysis The analysis function compares transfers and purchases to identify patterns: ```python def analyze_phishy_behavior_pumpfun(transfers: List[Dict], buy_data: Dict[str, Dict]) -> Tuple[int, List[Dict]]: """ Analyze transfers vs purchases to identify patterns for Pump.fun tokens. """ addresses_with_patterns = [] for transfer in transfers: receiver = transfer["Transfer"]["Receiver"]["Token"]["Owner"] first_transfer_time = transfer["Block"].get("first_transfer") total_transferred = transfer.get("total_transferred_amount", 0) buy_info = buy_data.get(receiver) total_bought = buy_info.get("total_amount", 0) if buy_info else 0 transferred_without_buy = float(total_transferred) - float(total_bought) if buy_info is None: # Address received transfer but never purchased addresses_with_patterns.append({ "address": receiver, "first_transfer_time": first_transfer_time, "first_buy_time": None, "total_transferred": total_transferred, "total_bought": 0, "transferred_without_buy": transferred_without_buy, "pattern": "Never bought the token" }) else: first_buy_time = buy_info.get("first_buy_time") # Compare timestamps - if transfer happened before buy, note the pattern if first_transfer_time < first_buy_time: addresses_with_patterns.append({ "address": receiver, "first_transfer_time": first_transfer_time, "first_buy_time": first_buy_time, "total_transferred": total_transferred, "total_bought": total_bought, "transferred_without_buy": transferred_without_buy, "pattern": "Transfer before buy" }) return len(addresses_with_patterns), addresses_with_patterns ``` #### 5. Top Holders Analysis The tool also fetches top 10 holders with additional analytics: ```python def get_top_holders_pumpfun(token_address: str, api_key: str) -> List[Dict]: """ Get top 10 holders of a Pump.fun token. """ query = """ query MyQuery($token: String) { Solana { BalanceUpdates( limit: {count: 10} orderBy: {descendingByField: "BalanceUpdate_Holding_maximum"} where: { BalanceUpdate: { Currency: {MintAddress: {is: $token}} } Transaction: {Result: {Success: true}} } ) { BalanceUpdate { Currency { Name MintAddress Symbol } Account { Token { Owner } } Holding: PostBalance(maximum: Block_Slot, selectWhere: {ne: "0"}) } } } } """ ``` For each holder, the tool also fetches: - **Pump token count**: Number of Pump.fun tokens held by the address - **Trade activity**: Number of trades in the last 6 hours #### 6. Web Application (Flask) The Flask app (`app.py`) provides a REST API endpoint: ```python @app.route(f'{APPLICATION_ROOT}/api/check', methods=['POST']) def check_token(): """API endpoint to analyze a token and return various metrics.""" data = request.get_json() token_address = data.get('token_address', '').strip() # Find bonding curve bonding_curve_data = get_bonding_curve_address(token_address, API_KEY) # Get transfers and analyze patterns transfers = get_first_transfers_pumpfun(token_address, bonding_curve, API_KEY) addresses = [t["Transfer"]["Receiver"]["Token"]["Owner"] for t in transfers] buy_data = get_first_buys_pumpfun(token_address, addresses, API_KEY) pattern_count, addresses_with_patterns = analyze_phishy_behavior_pumpfun(transfers, buy_data) # Get top holders with stats top_holders = get_top_holders_pumpfun(token_address, API_KEY) # ... enrich with pump token counts and trade activity return jsonify(result) ``` ### Additional Features - **Bonding Curve Detection**: Automatically finds the bonding curve address associated with the token - **Top Holders Analysis**: Shows the top 10 holders with: - Number of pump tokens each holds - Recent trading activity (last 6 hours) - Percentage of total supply - **Holder Distribution Analysis**: Displays concentration metrics showing if creator or other holders hold more than 5% of supply - **Token Metadata**: Fetches token name, symbol, and IPFS metadata (image, website, social links) - **Liquidity Information**: Gets current pool liquidity - **Graduation Check**: Verifies if token has graduated to PumpSwap (not supported) - **Summary Statistics**: Provides aggregated totals of transferred amounts, bought amounts, and amounts transferred without purchase ## Running the Tool ### Option 1: Web UI (Recommended) 1. Start the web server: ```bash python app.py ``` 2. Open your browser and navigate to `http://localhost:8080` 3. Enter a Pump.fun token address in the input field 4. Click "Check Token" to run the analysis The web UI features: - Modern web3-styled interface with dark theme - Automatic bonding curve detection - Top 10 holders table with pump token counts and trade stats - Clickable addresses linking to DEXrabbit - Copy-to-clipboard functionality for addresses - Detailed breakdown of transfer vs purchase analysis - All token metrics displayed in organized sections - Summary statistics for all metrics - Responsive design ### Option 2: Command Line Run the analysis directly from the command line: ```bash python check_phishy_token.py WZrxegwJK4vWFGC149Ajt86vbKA9tsrJxu8mJFdpump ``` Note: The bonding curve is automatically detected, so you only need to provide the token address. ## Understanding the Output The tool displays various metrics organized into different sections: ### Token Information - **Bonding Curve Address**: The bonding curve program address for this token - **Creator Address**: The wallet address that created the token - **Creation Time**: When the token was created - **Transaction Signature**: The transaction that created the token - **Token Name & Symbol**: Basic token information - **Token Metadata**: IPFS metadata including image, website, social links, and description - **Mayhem Mode**: Whether the token was created in Mayhem mode (affects total supply) - **Graduation Status**: Whether the token has migrated to PumpSwap ### Top Holders Metrics For each of the top 10 holders, the tool displays: - **Address**: The wallet address - **Holding Amount**: Number of tokens held - **Percentage of Supply**: What percentage of total supply this holder owns - **Pump Token Count**: How many different Pump.fun tokens this address holds - **Trades (Last 6h)**: Number of trades executed in the last 6 hours ### Holder Distribution Analysis - **Creator Percentage**: If creator is in top 10, shows their holding percentage - **Creator Check**: Indicates if creator holds less than 5% (or not in top 10) - **Other Holders Check**: Indicates if any other holder (excluding creator) holds more than 5% - **Top 10 Total Percentage**: Combined percentage of supply held by top 10 holders - **Top 10 Check**: Indicates if top 10 hold less than 70% of supply ### Transfer vs Purchase Analysis Metrics This section displays data comparing token transfers and purchases: - **Total Addresses with Transfers**: Count of all addresses that received the token via transfer - **Addresses with Transfers but No Purchases**: Number of addresses that received transfers but never purchased - **Addresses with Both Transfers and Purchases**: Number of addresses that both received transfers and made purchases For addresses that received transfers but didn't purchase (or received transfers before purchases), the tool shows: - **Address**: The wallet address - **First Transfer Time**: When the address first received the token - **First Buy Time**: When the address first purchased (if any) - **Total Transferred**: Total amount of tokens transferred to this address - **Total Bought**: Total amount of tokens purchased by this address - **Amount Transferred Without Buy**: Difference between transferred and bought amounts - **Pattern Type**: Description of the pattern observed (e.g., "Never bought the token" or "Transfer before buy") **Summary Totals**: - Total Amount Transferred to All Addresses - Total Amount Bought by All Addresses - Total Amount Transferred Without Purchase ### Liquidity Metrics - **Current Pool Liquidity**: Amount of SOL currently in the bonding curve pool ### Example Output The command-line output displays metrics in a structured format: ``` ============================================================ Checking Pump.fun token: WZrxegwJK4vWFGC149Ajt86vbKA9tsrJxu8mJFdpump ============================================================ Finding bonding curve address... Found bonding curve: ABC123... Found 150 addresses that received transfers Found buy records for 45 addresses ============================================================ RESULTS ============================================================ Total addresses that received transfers: 150 Addresses with transfers but no purchases: 105 Addresses with both transfers and purchases: 45 Transfer vs Purchase Analysis: Found 105 address(es) with transfers but no purchases: 1. Address: ABC123... First Transfer: 2024-01-15 10:30:00 UTC First Buy: N/A Total Transferred: 1,000,000.00 Total Bought: 0 Amount Transferred Without Buy: 1,000,000.00 Pattern: Never bought the token ------------------------------------------------------------ TRANSFER VS PURCHASE SUMMARY: ------------------------------------------------------------ Total Amount Transferred: 5,000,000.00 Total Amount Bought: 500,000.00 Total Amount Transferred Without Purchase: 4,500,000.00 ------------------------------------------------------------ ``` The web UI displays all metrics in an organized dashboard format with sections for token information, top holders, holder distribution analysis, transfer vs purchase metrics, and liquidity data. ## API Endpoints The Flask web application provides the following endpoints: ### POST `/api/check` Analyzes a Pump.fun token for phishy behavior. **Request Body:** ```json { "token_address": "WZrxegwJK4vWFGC149Ajt86vbKA9tsrJxu8mJFdpump" } ``` **Response:** ```json { "success": true, "token_address": "WZrxegwJK4vWFGC149Ajt86vbKA9tsrJxu8mJFdpump", "token_type": "pumpfun", "data": { "total_addresses": 150, "transfer_purchase_analysis": { "addresses_with_transfers_no_purchases": 105, "addresses_with_both": 45 }, "transfer_purchase_details": [ { "address": "ABC123...", "first_transfer_time": "2024-01-15T10:30:00Z", "first_buy_time": null, "total_transferred": "1000000.0", "total_bought": "0", "transferred_without_buy": 1000000.0, "pattern": "Never bought the token" } ], "top_holders": [ { "address": "XYZ789...", "holding": "50000000", "percent_holding": 5.0, "pump_tokens_count": 12, "trades_6h": 5 } ], "bonding_curve": "BondingCurveAddress...", "token_creation": { "transaction_signature": "Signature...", "creator_address": "CreatorAddress...", "creation_time": "2024-01-15T09:00:00Z" }, "token_metadata": { "name": "Token Name", "symbol": "SYMBOL", "is_mayhem_mode": false, "image": "https://ipfs.io/ipfs/...", "website": "https://example.com", "twitter": "@example" }, "holder_analysis": { "creator_percent": 2.5, "creator_check_passed": true, "other_holders_check_passed": true, "top10_percent": 45.0, "top10_check_passed": true }, "liquidity_sol": 125.5, "totals": { "total_transferred": 5000000.0, "total_bought": 500000.0, "total_without_buy": 4500000.0 } } } ``` ### GET `/api/recent-phishy` Returns a list of recently analyzed tokens from the cache (only tokens with transfer vs purchase patterns are cached). **Response:** ```json { "success": true, "tokens": [ { "token_address": "WZrxegwJK4vWFGC149Ajt86vbKA9tsrJxu8mJFdpump", "token_type": "pumpfun", "transfer_purchase_count": 105, "timestamp": "2024-01-15T12:00:00Z", "totals": { "total_transferred": 5000000.0, "total_bought": 500000.0, "total_without_buy": 4500000.0 } } ], "count": 1 } ``` ## Limitations - **Supported Tokens**: Only Pump.fun tokens on Solana are supported - **Token Age**: The tool works best with tokens created recently (bonding curve detection may fail for very old tokens) - **Graduated Tokens**: Tokens that have graduated to PumpSwap are not supported (tool will return an error) - **Address Limit**: Analyzes up to 1,000 addresses per token (limit in the GraphQL query) - **Query Time**: Queries may take 10-60+ seconds depending on data size (normal for blockchain queries) - **API Rate Limits**: Subject to Bitquery API rate limits and quota restrictions ## Use Cases This proof-of-concept tool demonstrates how to use Bitquery APIs to build token analysis tools. It can be used for: - **Token Research**: View various on-chain metrics about Pump.fun tokens in one place - **Holder Analysis**: Understand token distribution and concentration patterns - **Activity Monitoring**: See trading activity and engagement levels of top holders - **Data Aggregation**: Collect multiple data points from different Bitquery APIs - **Learning Tool**: Understand how to query and analyze Solana blockchain data using Bitquery - **Foundation for Advanced Tools**: Use this as a starting point to build more sophisticated analysis systems ## Building Advanced Tools This is a basic proof-of-concept tool that demonstrates the capabilities of Bitquery APIs. You can extend this foundation to build more advanced analysis systems by: - Adding more sophisticated analysis algorithms - Implementing machine learning models for pattern detection - Creating real-time monitoring and alerting systems - Building comprehensive risk scoring systems - Integrating with other data sources - Adding historical trend analysis - Creating comparative analysis across multiple tokens - Building portfolio tracking and management tools The Bitquery APIs provide access to comprehensive blockchain data that can power much more advanced analysis tools than this basic example. ## Important Considerations - **This tool displays metrics only**: It does not make definitive claims about token legitimacy or risk - **Metrics are informational**: All data points shown are for your analysis and research purposes - **Not investment advice**: This tool is not financial or investment advice - **Conduct your own research**: Always perform thorough due diligence before making any decisions - **Proof of concept**: This is a basic demonstration - you can build more advanced tools using the same Bitquery APIs - **Token age limitations**: The tool works best with recently created tokens (bonding curve detection may fail for very old tokens) ## Support For questions or issues: - Check the [GitHub repository](https://github.com/Akshat-cs/pumpfun-token-sniffer) for updates and issues - Contact Bitquery support via [Telegram](https://t.me/Bloxy_info) or create a ticket [here](https://support.bitquery.io/) --- ## Pump.fun gRPC Streams - Real-time DEX Trades URL: https://docs.bitquery.io/docs/grpc/solana/examples/pump-fun-grpc-streams/ Pump.fun gRPC Streams - Real-time DEX Trades for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Pump.fun gRPC Streams Real-time streaming of Pump.fun DEX trades, orders, and transactions via CoreCast gRPC API. gRPC is the lowest-latency channel of the [Bitquery Pump.fun API](https://bitquery.io/products/pumpfun-api). ## Repository 🔗 [**GitHub Repository**](https://github.com/bitquery/grpc-usecase-examples/tree/main/Solana/pumpfun-example) Clone and get started: ```bash git clone https://github.com/bitquery/grpc-usecase-examples.git ``` ## Introduction This Node.js client allows you to stream real-time trading data from Pump.fun (Solana's popular memecoin launchpad) using the CoreCast gRPC API. Monitor track buying/selling pressure, detect whale activity, and analyze trading patterns in real-time. **Key Features:** - 🚀 Real-time trade streaming from Pump.fun - 🎯 Flexible filtering by tokens, traders, and trade direction - 💰 Separate buy and sell trade monitoring - 📊 Performance metrics and statistics - 🔍 Detailed trade information including accounts and currencies - ⚡ High-performance with caching and buffering ## Quick Start ```bash # 1. Install dependencies npm install # 2. Configure your filters in config.yaml # Edit the file to set your desired token and trade filter # 3. Run the client node index.js ``` ## Stream Types The client supports multiple stream types: | Stream Type | Description | | -------------- | --------------------------------------- | | `dex_trades` | Real-time trade events (default) | | `dex_orders` | Order placement and cancellation events | | `dex_pools` | Pool liquidity change events | | `transactions` | General transaction stream | | `transfers` | Token transfer events | | `balances` | Balance update events | For Pump.fun monitoring, use **`dex_trades`** (default). ## Trade Data Structure When you stream Pump.fun trades, each message contains: ### Trade Event Structure ```javascript { Block: { Slot: 370485092 // Solana block slot number }, Transaction: { Index: 1, Signature: "5277PwHQ4PkKRExT45HV8X8XXDmQjWZzHK8dx5ru1eaA...", Status: { Success: true, ErrorMessage: null }, Header: { Fee: 5000, FeePayer: "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr", Signer: "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr", Accounts: [...] }, FeeInUsd: 0.00075 }, Trade: { InstructionIndex: 2, Dex: { ProgramAddress: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", ProtocolName: "pump_fun", ProtocolFamily: "pump_fun" }, Market: { MarketAddress: "YcQB1hGSR9hNbJ52zrCJyMvbRViQKiaLfenrgZR9BXY", BaseCurrency: { Symbol: "PUMPTOKEN", Name: "Pump Token", MintAddress: "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump", Decimals: 6 }, QuoteCurrency: { Symbol: "SOL", Name: "Wrapped SOL", MintAddress: "So11111111111111111111111111111111111111112", Decimals: 9 } }, Buy: { Amount: 100000000, // Amount of token being bought Currency: { Symbol: "PUMPTOKEN", Name: "Pump Token", MintAddress: "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump", Decimals: 6, Parsed: true }, Account: { Address: "8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m", IsSigner: true, IsWritable: true }, Order: { OrderId: null } }, Sell: { Amount: 500000000, // Amount of SOL being sold Currency: { Symbol: "SOL", Name: "Wrapped SOL", MintAddress: "So11111111111111111111111111111111111111112", Decimals: 9 }, Account: { Address: "8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m", IsSigner: true, IsWritable: true }, Order: { OrderId: null } }, Fee: 0, Royalty: 0, Instruction: { Index: 2, Depth: 0, Program: { Address: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P", Name: "pump_fun", Method: "swap", Parsed: true }, Accounts: [...], Logs: [...] } } } ``` ### Key Fields Explained | Field | Description | | -------------------------------- | ----------------------------------------------------------------- | | `Trade.Buy.Amount` | Amount of token being bought (in base units) | | `Trade.Sell.Amount` | Amount of SOL being sold (in lamports) | | `Trade.Buy.Currency.MintAddress` | Token mint address | | `Trade.Buy.Account.Address` | Buyer's wallet address | | `Trade.Dex.ProgramAddress` | Always `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` for Pump.fun | | `Trade.Market.MarketAddress` | Unique market/pool address for the token | | `Block.Slot` | Solana block slot for timing analysis | ## Configuration Options Edit `config.yaml` to configure your stream: ### Trade Filter Options ```yaml trade_filter: "alltrades" # or "buys" or "sells" ``` | Value | Description | | ----------- | ------------------------------------------------ | | `alltrades` | Show all trades (both buys and sells) | | `buys` | Show only trades where the token is being bought | | `sells` | Show only trades where the token is being sold | ### Available Filters Server-side filters (applied by CoreCast API): | Filter | Description | Example | | ---------- | -------------------------------------- | ------------------------------------------------------- | | `programs` | Filter by DEX program address | Pump.fun: `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` | | `tokens` | Filter by token mint address(es) | Your token mint address | | `pool` | Filter by specific market/pool address | Specific Pump.fun market | | `traders` | Filter by wallet address(es) | Specific trader wallets | Client-side filter (applied by this client): | Filter | Description | | -------------- | ------------------------------------------------ | | `trade_filter` | Filter by trade direction (buys/sells/alltrades) | ## Filter Examples ### 1. Monitor ALL Trades for a Specific Token Track all trading activity (both buys and sells) for a specific token on Pump.fun. ```yaml trade_filter: "alltrades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" tokens: - "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump" ``` **Use Case**: General market monitoring, volume analysis --- ### 2. Monitor Only BUYS for a Specific Token Track buying pressure - see when traders are accumulating the token. ```yaml trade_filter: "buys" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" tokens: - "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump" ``` **Use Case**: Track accumulation patterns, detect buying momentum --- ### 3. Monitor Only SELLS for a Specific Token Track selling pressure - detect when traders are dumping the token. ```yaml trade_filter: "sells" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" tokens: - "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump" ``` **Use Case**: Detect sell pressure, identify dumps, risk monitoring --- ### 4. Monitor Multiple Tokens Track trading activity across multiple Pump.fun tokens simultaneously. ```yaml trade_filter: "alltrades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" tokens: - "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump" - "H15fwzsYWQiGTQBn23sC2QuByu9zSvaXhaDwwVmkX5m9" - "AnotherTokenMintAddressHere" ``` **Use Case**: Portfolio tracking, multi-token analysis --- ### 5. Monitor ALL Pump.fun Activity Stream all trades on Pump.fun (no token filter) - useful for market-wide analysis. ```yaml trade_filter: "alltrades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # No tokens filter = all tokens ``` **Use Case**: Market-wide analytics, new token discovery, volume tracking **⚠️ Warning**: This will stream a high volume of messages. Ensure your system can handle the load. --- ### 6. Monitor Specific Trader Activity Track all trades made by a specific wallet on Pump.fun. ```yaml trade_filter: "alltrades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" traders: - "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr" ``` **Use Case**: Whale watching, copytrading, smart money tracking --- ### 7. Monitor Specific Trader's Token Buys Track when a specific wallet buys a specific token. ```yaml trade_filter: "buys" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" tokens: - "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump" traders: - "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr" ``` **Use Case**: Copy-trading specific whales, alpha signal detection --- ### 8. Monitor Multiple Traders Track activity from multiple wallets (whale watching). ```yaml trade_filter: "alltrades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" traders: - "7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr" - "8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m" - "9iJkLmNoPQrsTUVxYZaBcDeFgH1JkLmNoPQrsTUVxYZ" ``` **Use Case**: Monitor multiple known profitable traders --- ### 9. Monitor Specific Market/Pool Track all activity in a specific Pump.fun market. ```yaml trade_filter: "alltrades" filters: pool: - "YcQB1hGSR9hNbJ52zrCJyMvbRViQKiaLfenrgZR9BXY" ``` **Use Case**: Deep dive into a specific token's liquidity pool --- ### 10. Detect Large Buys (Whale Accumulation) Monitor buy trades and filter large amounts in your application logic. ```yaml trade_filter: "buys" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" tokens: - "7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump" ``` Then in your code, filter by `Trade.Buy.Amount` or `Trade.Sell.Amount` (SOL value). **Use Case**: Whale buy alerts, large transaction monitoring ## Output Example When a trade matches your filters, you'll see: ``` ================================================================================ 🟢 BUY Trade ================================================================================ Block Slot: 370485092 Timestamp: 2025-10-01T13:11:32.922Z Instruction Index: 2 📍 DEX Info: Program: 6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P Protocol: pump_fun (pump_fun) 🏪 Market Info: Address: YcQB1hGSR9hNbJ52zrCJyMvbRViQKiaLfenrgZR9BXY Base Currency: PUMPTOKEN Quote Currency: SOL 💰 Buy Side: Amount: 100000000 Currency: PUMPTOKEN (Pump Token) Mint: 7CyJ5J3tqRKKJjSWSzASuVJdD2oryAJZfyvbMVJmpump Decimals: 6 Account: 8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m Is Signer: true Is Writable: true Order ID: undefined 💸 Sell Side: Amount: 500000000 Currency: SOL (Wrapped SOL) Mint: So11111111111111111111111111111111111111112 Decimals: 9 Account: 8HqR8D9gHtN1eMJyaX7BN5PmzF5z9KgQzY4nXvFfRD8m Is Signer: true Is Writable: true Order ID: undefined 💵 Fee: 0 👑 Royalty: 0 ================================================================================ ``` --- ## Pump.fun to PumpSwap API - Token Migration Tracking URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/pump-fun-to-pump-swap/ Track Pump.fun tokens graduating to PumpSwap on Solana: detect migration events, the final bonding-curve trade, and post-migration AMM activity. # Understanding Pump.fun: From Launchpad to PumpSwap :::tip Need real-time Pump.fun & PumpSwap data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Pump.fun & PumpSwap swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Pump.fun & PumpSwap data older than ~30 days**, raw per-swap detail, or call / event context. Post-migration AMM activity is covered end-to-end by the [PumpSwap API](https://bitquery.io/products/pumpswap-api) — the product page lists swaps, pools and OHLCV coverage with plans. ::: For the productized feed of these migration events — channels, pricing, free trial — see the [Pump.fun API product page](https://bitquery.io/products/pumpfun-api). Pump.fun is a Solana-based memecoin launchpad that has reshaped how tokens are created and traded. At its core is a bonding curve model that lets anyone launch a token with a fixed supply of 1 billion tokens, of which around 800 million are made available for bonding. As traders buy into the curve, the price increases non-linearly—early buyers benefit the most. The bonding curve progress, a very useful metric for developers and traders, can be computed as: :::note **Simplified Formula**: BondingCurveProgress = 100 - (((balance - 206900000) \* 100) / 793100000) ::: where `balance` is the balance of the bonding curve for that specific token. This helps identify tokens nearing sell-out, a common signal for tokens “about to pump.” Once a token reaches full bonding (100%), it automatically migrates to PumpSwap, Pump.fun’s native AMM DEX. From there, it trades like any other Solana token—no manual listing is needed; the system handles everything. To help developers, traders, and analysts follow this journey, Bitquery offers a comprehensive real-time API suite that spans the entire lifecycle of a Pump.fun token. Let’s walk through it: ## Track New Token Creations in Real-Time Every token on Pump.fun starts with a launch event. You can track these launches in real time using a streaming API: - [Track Pump.fun Token Creations in Real-Time Using a Subscription](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-newly-created-pumpfun-tokens) This API streams metadata such as token name, symbol, mint, creator address, and timestamp the moment a new token is created. ## Follow Real-Time Market Data as Tokens Trade on Pump.fun Pump.fun tokens are actively traded as they climb the bonding curve. Traders need up-to-the-second price feeds and trade streams: - [Track Price of a Token in Real-Time](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-track-the-price-of-a-pumpfun-token-in-real-time) - [Get Real-Time Trades on Pump Fun](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-live-trades-from-pumpfun-using-bitquery) - [Get OHLC Data of a Token](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-pumpfun-token-ohlcv-data-historically) These APIs provide: - Price ticks per trade - Trade sides (buy/sell) - Volume and trader addresses - 1-minute OHLC data for charting and analysis ## Analyze Token Performance For deeper insights and analytics, developers can extract: - [Token Price Change Over Time (Delta from X Minutes Back)](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-token-price-change-over-time-delta-from-x-minutes-back) - [ATH Market Cap in a Specific Timeframe](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-a-tokens-all-time-high-ath-price-on-pumpfun) - [Get Market Cap, Price, Liquidity, Bonding Curve, and Volume](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-bonding-curve-progress-for-a-pumpfun-token) - [Get Detailed Trade Stats: Volume, Buys, Sells, Makers, Buyers, Sellers](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-detailed-trade-stats-volume-buys-sells-makers-buyers-sellers) These endpoints help answer questions like: - What’s the token’s current liquidity? - Has it reached its all-time high market cap? - How many unique wallets are buying/selling? ## Identify Hot Tokens and Dev Insights Traders constantly seek trending tokens or insider holds: - [Top Pump Fun Tokens by Market Cap](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-top-pumpfun-tokens-by-market-cap) - [Track “King of the Hill” Tokens (30K–35K Market Cap)](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-track-king-of-the-hill-pumpfun-tokens-30k35k-market-cap) - [Get Dev’s Holdings of a Token](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-devs-holdings-of-a-pumpfun-token) These tools surface: - Top-performing memecoins - Tokens nearing PumpSwap graduation (30k–35k cap) - Developer-controlled balances ## Graduation to PumpSwap and Further Trading A Pump.fun token graduates (i.e., migrates to PumpSwap) when its bonding curve is fully sold out, meaning 100% of the 800 million tradable tokens have been bought. Here’s what triggers graduation: - Total tokens sold reaches the maximum sellable limit (excluding the reserved ~200M tokens) - The market cap typically approaches $30K–$35K, depending on SOL price and trading dynamics - The Pump.fun platform then automatically creates a PumpSwap liquidity pool for the token; no manual action is needed Once graduated: - Token trading stops on Pump.fun - Trading resumes on PumpSwap as an AMM pair You can track these graduation events in real-time using Bitquery’s API: - [Track Pump Fun Token Migrations to PumpSwap](/docs/blockchain/Solana/Pumpfun/Pump-Fun-Marketcap-Bonding-Curve-API/#track-pump-fun-token-migrations-to-pumpswap-in-realtime---subscription) Post-migration, tokens trade as standard AMM pairs. Bitquery continues to offer real-time data support: - [Latest Trades for a Token on Pumpswap - Websocket](/docs/blockchain/Solana/Pumpfun/pump-swap-api/#latest-trades-for-a-token-on-pumpswap---websocket) - [Get Buy Volume, Sell Volume, Buys, Sells, Makers, Total Trade Volume, Buyers, Sellers of a Specific Token](/docs/blockchain/Solana/Pumpfun/pump-swap-api/#get-buy-volume-sell-volume-buys-sells-makers-total-trade-volume-buyers-sellers-of-a-specific-token) ## Tracking a Pump.fun Token’s Journey with Bitquery Shred Streams Bitquery’s Kafka streams offer ultra-low-latency access to blockchain data by tapping directly into Solana’s Shred-level architecture. On Solana, a shred is the smallest fragment of a block—and it’s the first unit of data propagated between validators. Bitquery’s Shred Streams capture transactions as they’re broadcast to validators, often before the block is finalized and even before timestamps are attached. This means you receive transaction data faster than any traditional block-based solution, giving you a true edge in latency-sensitive use cases such as arbitrage, sniping, and real-time analytics. **You can use this to track Pump.fun tokens as shown in [this tutorial](https://youtu.be/UlqZ8DgzNLc).** Bitquery offers three main Kafka topics for Solana: - `solana.dextrades.proto` — includes all trade and liquidity pool change data - `solana.tokens.proto` — covers token transfers, supply changes, and balance updates at both the account and instruction level - `solana.transactions.proto` — delivers detailed data for blocks, transactions, and instructions Topics, latency compared with gRPC and GraphQL, and connection setup are on the [Solana Shred Stream page](/docs/streams/solana-shred-streams/). Field-level details are in the [Solana protobuf stream reference](/docs/streams/protobuf/chains/Solana-protobuf/), and a full consumer is in the [Python Kafka tutorial](/docs/streams/protobuf/kafka-protobuf-python/). ## Conclusion Pump.fun has become the meme-fueled engine of Solana’s token economy. It has launched millions of tokens, introduced a playful but potent market dynamic, and evolved into a serious arena for real-time trading. For developers and analysts who want to build tools around this phenomenon, Bitquery offers a plug-and-play data layer that covers every phase of a Pump.fun token’s lifecycle—from minting to AMM trading. Whether you’re building dashboards, bots, trading tools, or alpha groups, these APIs let you track the entire journey without writing indexers or running infrastructure. Start querying. Stay real-time. And ride the next pump. --- ## PumpSwap API - Solana - Tokens, Trades, Live Prices URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/pump-swap-api/ Query and stream PumpSwap AMM activity on Solana: live trades, new pools, token prices and liquidity, over GraphQL, WebSocket or Kafka. # PumpSwap API :::tip Need real-time PumpSwap data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered PumpSwap swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical PumpSwap data older than ~30 days**, raw per-swap detail, or call / event context. ::: For delivery channels, pricing and the free trial, see the [PumpSwap API product page](https://bitquery.io/products/pumpswap-api). Bitquery’s **PumpSwap API** exposes the PumpSwap AMM on Solana through GraphQL: **live and historical trades**, **prices**, **OHLC**, **volume**, **pool creation**, and **Pump.fun → PumpSwap migrations**. Use **queries** for snapshots, **subscriptions** to track PumpSwap trades in real time, and **`dataset: combined`** when you need more history than **`dataset: realtime`** (~recent window). Filter trades with **`Dex.ProgramAddress: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"`**. For live DEX prices across Pump.fun tokens, see [DEXrabbit's Pump.fun category](https://dexrabbit.bitquery.io/categories/pump-fun). For other data points, reach out to [support](https://t.me/Bloxy_info). :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: - You can also explore [Pump Fun Data documentation ➤](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - Also check out [LetsBonk.fun APIs ➤](/docs/blockchain/Solana/letsbonk-api/) - Need zero-latency PumpSwap data? [Read about our Shred Streams and Contact us for a Trial](/docs/streams/real-time-solana-data/). Join us on [Telegram](https://t.me/Bloxy_info) for support and integration help. ## What is the PumpSwap program address on Solana? {#what-is-the-pumpswap-program-address-on-solana} The PumpSwap AMM program on Solana mainnet is **`pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA`**. Use this value in **`Trade.Dex.ProgramAddress`** or **`Instruction.Program.Address`** filters in Bitquery GraphQL so results are limited to PumpSwap (not other Solana DEXs). ## How do I get newly created PumpSwap pools in real time? {#get-newly-created-pools-on-pumpswap-dex-in-realtime} Subscribe to **`Instructions`** where the program method is **`create_pool`** and the program address is the PumpSwap AMM ID above. Each event reflects a new pool on PumpSwap; use account and argument fields for pair and liquidity details. [Run in Bitquery IDE — newly created PumpSwap pools (stream)](https://ide.bitquery.io/pumpSwap-new-pools-Stream)
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: {Instruction: {Program: {Method: {is: "create_pool"}, Address: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}}} ) { Instruction { Program { Address Name Method Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } AccountNames Json } Accounts { Address IsWritable Token { Mint Owner ProgramId } } Logs BalanceUpdatesCount AncestorIndexes CallPath CallerIndex Data Depth ExternalSeqNumber Index InternalSeqNumber TokenBalanceUpdatesCount } Transaction { Fee FeeInUSD Signature Signer FeePayer Result { Success ErrorMessage } } Block { Time Height } } } } ```
## How do I track Pump.fun pool migrations to PumpSwap in real time? {#track-pools-that-are-migrated-to-pumpswap} Subscribe to **`create_pool`** instructions on the PumpSwap program when they follow a Pump.fun **`migrate`** flow. **`Instruction.Accounts[]`** carries pool and token accounts; argument **`Value`** fields include liquidity added. Pair with the [Pump Fun to PumpSwap](/docs/blockchain/Solana/Pumpfun/pump-fun-to-pump-swap/) guide for full migration logic. [Run in Bitquery IDE — Pump.fun → PumpSwap migrations](https://ide.bitquery.io/pumpfun-migration-stream_2#)
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { CallerIndex: { eq: 2 } Depth: { eq: 1 } CallPath: { includes: { eq: 2 } } Program: { Method: { is: "create_pool" } Address: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } } } } ) { Instruction { Program { Address Name Method Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } AccountNames Json } Accounts { Address IsWritable Token { Mint Owner ProgramId } } Logs BalanceUpdatesCount AncestorIndexes CallPath CallerIndex Data Depth ExternalSeqNumber Index InternalSeqNumber TokenBalanceUpdatesCount } Transaction { Fee FeeInUSD Signature Signer FeePayer Result { Success ErrorMessage } } Block { Time Height } } } } ```
## How do I get the latest PumpSwap trades? {#latest-trades-on-pumpswap} Use **`DEXTrades`** with **`Solana(network: solana, dataset: realtime)`** and filter **`Trade.Dex.ProgramAddress`** to the PumpSwap AMM. This returns the most recent successful swaps on PumpSwap (snapshot query, not a live stream). For continuous updates, use the subscription in the next section. [Run in Bitquery IDE — latest PumpSwap trades](https://ide.bitquery.io/Pumpswap-latest-Trades-API)
Click to expand GraphQL query ```graphql { Solana(network: solana, dataset: realtime) { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } } } } limit: { count: 100 } orderBy: { descending: Block_Time } ) { Block { Time } Instruction { Program { Method } } Trade { Dex { ProtocolFamily ProtocolName ProgramAddress } Buy { Price PriceInUSD Amount AmountInUSD Account { Address Owner } Currency { Name Symbol MintAddress Decimals Fungible Uri } } Sell { Price PriceInUSD Amount AmountInUSD Account { Owner Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } } Transaction { Signature Signer FeePayer } } } } ```
## How do I track PumpSwap trades in real time? {#latest-trades-on-pumpswap-websocket} Use a GraphQL **`subscription`** on **`DEXTrades`** with the same PumpSwap **`ProgramAddress`** filter. Bitquery pushes each new PumpSwap trade over WebSocket as it is indexed—this is the primary way to **track PumpSwap trades in real time** for dashboards and bots. [Run in Bitquery IDE — real-time PumpSwap trades (WebSocket)](https://ide.bitquery.io/pumpswap-trades)
Click to expand GraphQL query ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } } } } ) { Trade { Dex { ProtocolName } Sell { Currency { Symbol } } Buy { Currency { Symbol } } } Transaction { Signature } Instruction { ExternalSeqNumber InternalSeqNumber } } } } ```
## How do I get OHLC data for a PumpSwap token? {#ohlc-for-pumpswap-token} Use **`DEXTradeByTokens`** with PumpSwap **`ProgramAddress`**, your token mint, and the quote side (e.g. WSOL) to aggregate **`open` / `high` / `low` / `close`** and volume per time bucket. **`Trade Side Account`** is not available on combined/archive aggregates—see the note below. [Run in Bitquery IDE — OHLC for a PumpSwap token](https://ide.bitquery.io/ohlc-for-pumpswap) :::note Note: The `Trade Side Account` field is **not available** in aggregate queries across archive or combined datasets. :::
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProgramAddress: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}, Currency: {MintAddress: {is: "6qN87akZ3Ghs3JbGmnNMYP2rCHSBDwtiXttBV4Hspump"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}, Transaction: {Result: {Success: true}}} limit: {count: 100} orderBy: {descendingByField: "Block_Timefield"} ){ Block{ Timefield: Time(interval:{count:1 in:minutes}) } Trade{ open: Price(minimum:Block_Slot) high: Price(maximum:Trade_Price) low: Price(minimum:Trade_Price) close: Price(maximum:Block_Slot) } volumeInUSD: sum(of:Trade_Side_AmountInUSD) count } } } ```
## How do I get the latest PumpSwap trades by a trader? {#latest-trades-by-a-trader} Query **`DEXTrades`** with **`Transaction.Signer`** equal to the wallet and **`Trade.Dex.ProgramAddress`** set to PumpSwap. Returns recent buys/sells and signatures for that trader on PumpSwap only. [Run in Bitquery IDE — latest trades by a trader on PumpSwap](https://ide.bitquery.io/Pumpswap-latest-Trade-for-a-trader-api_1)
Click to expand GraphQL query ```graphql { Solana { DEXTrades( orderBy: [{descending: Block_Time}, {descending: Transaction_Index}, {descending: Trade_Index}] limit: {count: 10} where: { Transaction:{ Signer:{is:"78mgMi3caj9CY5EdAW9FHhUoLcWB5suyfDF8dsQ2CNHR"} } Trade: {Dex: {ProgramAddress: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}}} ) { Block { Time } Instruction { Program { Method } } Trade { Dex { ProtocolFamily ProtocolName ProgramAddress } Buy { Price PriceInUSD Amount AmountInUSD Account { Address Owner } Currency { Name Symbol MintAddress Decimals Fungible Uri } } Sell { Price PriceInUSD Amount AmountInUSD Account { Owner Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } } Transaction { Signature Signer FeePayer } } } } ```
## How do I track a trader’s PumpSwap trades in real time? {#latest-trades-by-a-trader---get-data-in-real-time-via-a-websocket} Use a **`subscription`** on **`DEXTrades`** with the same **`Signer`** and PumpSwap **`ProgramAddress`** filters. New trades for that wallet on PumpSwap stream as they are confirmed. [Run in Bitquery IDE — real-time trades by a trader (PumpSwap)](https://ide.bitquery.io/Pumpswap-latest-Trade-for-a-trader-stream_1)
Click to expand GraphQL query ```graphql subscription { Solana { DEXTrades( where: {Transaction: {Signer: {is: "78mgMi3caj9CY5EdAW9FHhUoLcWB5suyfDF8dsQ2CNHR"}}, Trade: {Dex: {ProgramAddress: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}}} ) { Block { Time } Instruction { Program { Method } } Trade { Dex { ProtocolFamily ProtocolName ProgramAddress } Buy { Price PriceInUSD Amount AmountInUSD Account { Address Owner } Currency { Name Symbol MintAddress Decimals Fungible Uri } } Sell { Price PriceInUSD Amount AmountInUSD Account { Owner Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } } Transaction { Signature Signer FeePayer } } } } ```
## How do I get the latest trades for a token on PumpSwap? {#latest-trades-for-a-token-on-pumpswap} Use **`DEXTradeByTokens`** with PumpSwap **`ProgramAddress`** and the token **`MintAddress`**. Replace the placeholder mint with your token. Returns recent fills, price, and side for that token on PumpSwap. [Run in Bitquery IDE — latest trades for a token on PumpSwap](https://ide.bitquery.io/Solana-trade-for-a-token_2)
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Dex:{ ProgramAddress:{ is:"pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } } Currency: {MintAddress: {is: "token mint address"}}}} limit: {count: 20} orderBy: [{descending: Block_Time}, {descending: Transaction_Index}, {descending: Trade_Index}] ) { Instruction { Program { Method } } Trade { Currency { Name Symbol MintAddress } Price PriceInUSD Amount AmountInUSD Price PriceInUSD Side { Type Amount AmountInUSD Currency { Symbol Name MintAddress } } Dex { ProtocolName ProtocolFamily ProgramAddress } } Block { Time Height Slot } Transaction { Signature FeePayer Signer } } } } ```
## How do I track PumpSwap trades for a specific token in real time? {#latest-trades-for-a-token-on-pumpswap---websocket} Subscribe to **`DEXTradeByTokens`** with PumpSwap **`ProgramAddress`** and the token mint. Each update is a new trade involving that token on PumpSwap—use this to stream per-token activity without polling. [Run in Bitquery IDE — real-time trades for a token (PumpSwap)](https://ide.bitquery.io/Latest-Trades-for-a-token-on-Pumpswap)
Click to expand GraphQL query ```graphql subscription { Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProgramAddress: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}, Currency: {MintAddress: {is: "token mint address"}}}} ) { Instruction { Program { Method } } Trade { Currency { Name Symbol MintAddress } Price PriceInUSD Amount AmountInUSD Price PriceInUSD Side { Type Amount AmountInUSD Currency { Symbol Name MintAddress } } Dex { ProtocolName ProtocolFamily ProgramAddress } } Block { Time Height Slot } Transaction { Signature FeePayer Signer } } } } ```
## How do I get top traders on PumpSwap? {#top-trader-on-pumpswap} Aggregate **`DEXTradeByTokens`** by **`Transaction.Signer`** with **`limitBy`** and **`orderBy`** on trade count or volume (USD). Filter **`Dex.ProgramAddress`** to PumpSwap and optionally WSOL as the side currency to rank active wallets on the AMM. [Run in Bitquery IDE — top traders on PumpSwap](https://ide.bitquery.io/top-traders-on-pumpswap_2)
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( limitBy: {count: 1, by: Transaction_Signature} limit: {count: 10} where: {Trade: {Dex: {ProgramAddress: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}, Transaction: {Result: {Success: true}}} orderBy: {descendingByField: "total_trades"} ) { Transaction { Signer } total_trades: count total_traded_volume: sum(of: Trade_Side_AmountInUSD) } } } ```
## How do I get buy/sell volume and maker stats for a PumpSwap token? {#get-buy-volume-sell-volume-buys-sells-makers-total-trade-volume-buyers-sellers-of-a-specific-token} Use **`DEXTradeByTokens`** with **`dataset: realtime`**, token mint, **`Market.MarketAddress`**, and time variables for **5-minute** and **1-hour** windows. The query returns buyers, sellers, makers, trade counts, and USD volume splits—ideal for live token dashboards on PumpSwap pairs. [Run in Bitquery IDE — token stats (buys, sells, makers, volume)](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair0_4)
Click to expand GraphQL query ```graphql query MyQuery($token: String!, $pair_address: String!, $time_5min_ago: DateTime!, $time_1h_ago: DateTime!) { Solana(dataset: realtime) { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}},Trade: {Currency: {MintAddress: {is: $token}}, Market: {MarketAddress: {is: $pair_address}}}, Block: {Time: {since: $time_1h_ago}}} ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after: $time_5min_ago}}} ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) makers_5min: count( distinct: Transaction_Signer if: {Block: {Time: {after: $time_5min_ago}}} ) buyers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}} ) buyers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sellers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}} ) sellers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) trades: count trades_5min: count(if: {Block: {Time: {after: $time_5min_ago}}}) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {after: $time_5min_ago}}} ) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) buys: count(if: {Trade: {Side: {Type: {is: buy}}}}) buys_5min: count( if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sells: count(if: {Trade: {Side: {Type: {is: sell}}}}) sells_5min: count( if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) } } } ``` **Variables (example):** ```json { "token": "token mint address", "pair_address": "48oGgzAdYJ5nzMmNz2Jvv5qvX4HXhNgp27tmdEM5n2EF", "time_5min_ago": "2025-03-25T09:14:00Z", "time_1h_ago": "2025-03-25T08:19:00Z" } ```
## How do I track a token’s price on PumpSwap in real time? {#track-price-of-a-token-in-realtime-on-pumpswap} Subscribe to **`DEXTradeByTokens`** filtered by PumpSwap **`ProgramAddress`** and the token **`MintAddress`**. Each event includes **`Price`** and **`PriceInUSD`** for the latest leg—use it as a live price feed for that token on PumpSwap. [Run in Bitquery IDE — real-time price of a PumpSwap token](https://ide.bitquery.io/realtime-price-of-a-pumpswap-token)
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProgramAddress: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } } Currency: { MintAddress: { is: "token mint address" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Currency { MintAddress Name Symbol } Dex { ProtocolName ProtocolFamily ProgramAddress } Side { Currency { MintAddress Symbol Name } } Price PriceInUSD } Transaction { Signature } } } } ```
## How do I get the latest price of a token on PumpSwap? {#get-latest-price-of-a-token-on-pumpswap} Query **`DEXTradeByTokens`** with **`orderBy: descending Block_Time`** and **`limit`** on PumpSwap **`ProgramAddress`** plus the token mint. Returns the most recent trade-based price without keeping a subscription open. [Run in Bitquery IDE — latest price of a PumpSwap token](https://ide.bitquery.io/Price-of-a-pumpswap-token_1)
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 10 } where: { Trade: { Dex: { ProgramAddress: { is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" } } Currency: { MintAddress: { is: "token mint address" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Currency { MintAddress Name Symbol } Dex { ProtocolName ProtocolFamily ProgramAddress } Side { Currency { MintAddress Symbol Name } } Price PriceInUSD } Transaction { Signature } } } } ```
## How do I get trading volume for a PumpSwap token in a time range? {#get-the-trading-volume-of-a-specific-token-on-pumpswap-dex} Use **`DEXTradeByTokens`** with **`Block.Time`** **`since` / `till`** and **`sum(of: Trade_Side_AmountInUSD)`** (and token volume) for the window. **Use a `query` only**—aggregates such as **`sum`** are not valid on subscriptions; a WebSocket subscription would return incorrect aggregates. [Run in Bitquery IDE — trading volume of a PumpSwap token](https://ide.bitquery.io/trading-volume-of-a-token-pumpSwap)
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Dex: { ProtocolFamily: { is: "Pumpswap" } } } Block: { Time: { since: "2025-03-25T09:30:00Z", till: "2025-03-25T10:30:00Z" } } } ) { Trade { Currency { Name Symbol MintAddress } Dex { ProtocolName ProtocolFamily } } TradeVolume_USD: sum(of: Trade_Side_AmountInUSD) TradeVolume: sum(of: Trade_Amount) } } } ```
## How do I get the latest creator fee transfers on PumpSwap? {#latest-creator-fee-transfers-on-pumpswap} Query **`InstructionBalanceUpdates`** where the program method is **`collect_coin_creator_fee`** and the program address is the PumpSwap AMM ID. This returns the 10 most recent creator fee collection events with balance changes, currency details, and transaction metadata. [Run in Bitquery IDE — latest creator fee transfers on PumpSwap](https://ide.bitquery.io/latest-creator-fee-transfers-on-pumpfun-amm)
Click to expand GraphQL query ```graphql { Solana(network: solana) { InstructionBalanceUpdates( limit: {count: 10} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Method: {is: "collect_coin_creator_fee"}, Address: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}}, Transaction: {Result: {Success: true}}} ) { Transaction { Signer Signature Result { Success ErrorMessage } Index Fee } Block { Time Hash } BalanceUpdate { Account { Address Owner Token { Owner } } Amount AmountInUSD Currency { Name MintAddress Symbol } PreBalance PostBalance } } } } ```
## How do I track creator fee transfers on PumpSwap in real time? {#track-creator-fee-transfers-on-pumpswap-in-realtime} Subscribe to **`InstructionBalanceUpdates`** with the same **`collect_coin_creator_fee`** method and PumpSwap program address filter. Each event streams a new creator fee collection as it happens—use this to monitor creator revenue on PumpSwap tokens in real time. [Run in Bitquery IDE — track creator fee transfers on PumpSwap (WebSocket)](https://ide.bitquery.io/track-creator-fee-transfers-on-pumpfun-amm#)
Click to expand GraphQL query ```graphql subscription { Solana(network: solana) { InstructionBalanceUpdates( where: {Instruction: {Program: {Method: {is: "collect_coin_creator_fee"}, Address: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}}, Transaction: {Result: {Success: true}}} ) { Transaction { Signer Signature Result { Success ErrorMessage } Index Fee } Block { Time Hash } BalanceUpdate { Account { Address Owner Token { Owner } } Amount AmountInUSD Currency { Name MintAddress Symbol } PreBalance PostBalance } } } } ```
## Frequently asked questions (PumpSwap) {#frequently-asked-questions-pumpswap} ### How do I track PumpSwap trades in real time? Use a GraphQL **`subscription`** on **`DEXTrades`** (all PumpSwap trades) or **`DEXTradeByTokens`** (one token) with **`Trade.Dex.ProgramAddress: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"`**. See [How do I track PumpSwap trades in real time?](#latest-trades-on-pumpswap-websocket) and [per-token stream](#latest-trades-for-a-token-on-pumpswap---websocket). For a one-off snapshot, use a **`query`** with **`dataset: realtime`** instead. ### What is the PumpSwap program address on Solana? **`pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA`** — use it on every PumpSwap trade and pool filter. [Details above](#what-is-the-pumpswap-program-address-on-solana). ### Why do I only see recent PumpSwap data with `dataset: realtime`? **`dataset: realtime`** covers a **rolling recent window** (roughly the last several hours of activity). For **full history**, use **`dataset: combined`** (or archive where applicable) on **`Solana`**, as described in [historical aggregate data](/docs/blockchain/Solana/historical-aggregate-data/). ### Can I run PumpSwap volume or OHLC aggregates as a subscription? **No.** **`sum`**, **`count`**, and bucketed OHLC require **queries**, not **`subscription`**. Use subscriptions for **raw trades** or **per-trade prices**, and run **aggregates in your app** or via **scheduled queries**. ### Where can I get Pump.fun data before a token moves to PumpSwap? Use the [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) and [Pump Fun to PumpSwap](/docs/blockchain/Solana/Pumpfun/pump-fun-to-pump-swap/) guides. This page focuses on **PumpSwap** only after migration. ## I can only get about 12 hours of PumpSwap data with dataset: realtime — how do I get older data? {#pumpswap-realtime-vs-combined-history} **`dataset: realtime`** on Solana only covers a **rolling recent window** (on the order of **hours**). For **older PumpSwap history**, switch to **`dataset: combined`** or **`dataset: archive`** on your **`Solana { ... }`** query so archive-backed rows are included. See [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/) and the **OHLC / volume** examples later on this page. --- ## PumpSwap video tutorials {#pumpswap-video-tutorials} ### Video Tutorial | How to get Trades, Trades of a token and Trades of a trader on PumpSwap DEX in realtime ### Video Tutorial | How to get Top Traders on PumpSwap AMM --- ## Python Tutorial to use Solana Shreds from Kafka URL: https://docs.bitquery.io/docs/streams/protobuf/kafka-protobuf-python/ Python Tutorial to use Solana Shreds from Kafka with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. # Python Tutorial to use Solana Shreds from Kafka This tutorial explains how to consume **Solana** transaction protobuf messages from **Bitquery Kafka** using **Python**, and print them with **`bytes`** fields shown in **base58** (pipe-friendly **stdout**; logs on **stderr**). Background: **[Kafka streaming concepts — Protobuf streams](/docs/streams/kafka-streaming-concepts/#what-to-know-about-protobuf-streams)**. **Runnable project:** **[`bitquery/kafka-streams-examples-usecases`](https://github.com/bitquery/kafka-streams-examples-usecases)** — folder **[`python-consumer-example/`](https://github.com/bitquery/kafka-streams-examples-usecases/tree/main/python-consumer-example)** ([`consumer.py`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/python-consumer-example/consumer.py), [`settings.py`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/python-consumer-example/settings.py), [`protobuf_print.py`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/python-consumer-example/protobuf_print.py)). > **Scaling:** This sample is a single process. For high throughput, add **parallel partition consumption** and/or **worker pools** behind the poll loop, following Bitquery’s Kafka guidance in **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)**. ## Prerequisites Install dependencies from **`requirements.txt`** (pinned for compatibility with generated protobuf code): ```bash pip install -r requirements.txt ``` Typical packages (see file for exact versions): - **`confluent-kafka`** - **`bitquery-pb2-kafka-package`** (Solana **`ParsedIdlBlockMessage`** and pb2 files of all schema, can be viewed [here](https://pypi.org/project/bitquery-pb2-kafka-package/)) - **`protobuf`**, **`base58`**, **`python-dotenv`** You also need **Kafka username and password** from Bitquery for stream access. > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## 1. Setup Kafka consumer configuration Configuration is **not** embedded as a large literal in the tutorial source: it is built in **`settings.load_settings()`** from environment variables (after **`load_dotenv()`**). Conceptually, the consumer uses **non-TLS** Bitquery brokers by default: - **`bootstrap.servers`**: `rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092` (overridable) - **`security.protocol`**: `SASL_PLAINTEXT` - **`sasl.mechanisms`**: `SCRAM-SHA-512` - **`enable.auto.commit`**: `False` - **`auto.offset.reset`**: `latest` or `earliest` (from **`KAFKA_AUTO_OFFSET_RESET`**) Full key list: **[`settings.py`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/python-consumer-example/settings.py)**. ### Environment variables | Variable | Required | Notes | | ------------------------- | -------- | ---------------------------------------- | | `KAFKA_USERNAME` | Yes | | | `KAFKA_PASSWORD` | Yes | | | `KAFKA_TOPIC` | No | Default `solana.transactions.proto` | | `KAFKA_BOOTSTRAP_SERVERS` | No | Default Bitquery `rpk*` **9092** cluster | | `KAFKA_GROUP_ID` | No | If unset: `{username}-group-{uuid}` | | `KAFKA_AUTO_OFFSET_RESET` | No | `latest` or `earliest` | > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## 2. Define / use the protobuf print helper The runnable project implements traversal in **`protobuf_print.py`** (**`print_protobuf_message`**) instead of pasting a long snippet into the docs. It walks protobuf fields recursively and uses **`base58`** when **`encoding='base58'`**. > **Solana vs EVM `bytes`** > > - **Solana:** **`base58`** for typical addresses / signatures (this tutorial default). > - **EVM (Ethereum, BSC, Polygon, …):** prefer **`hex`** (often **`0x` + hex**). > > If you switch consumers to **EVM** protobuf types later, align **`print_protobuf_message(..., encoding=...)`** and any **`convert_bytes`** logic with your chain—not with Solana base58 defaults. _(Implementation detail: **`protobuf_print.py`** uses **`field.is_repeated()`** where available so it stays compatible with modern **`protobuf`** runtimes pinned in **`requirements.txt`**.)_ ## 3. Process messages from Kafka In **`consumer.py`**, **`process_payload`** parses the wire bytes: ```python block = parsed_idl_block_message_pb2.ParsedIdlBlockMessage() block.ParseFromString(raw) print_protobuf_message(block, indent=0, encoding="base58") ``` ### Adapting to another topic You can adapt the script by changing **`KAFKA_TOPIC`** **and** the **imported message class** / **`ParseFromString`** target so the **generated type matches the topic schema**. Other plumbing (Kafka config, polling) can stay parallel to this sample. ## 4. Poll and shut down cleanly The main loop (**[`consumer.py`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/python-consumer-example/consumer.py)**) **`poll`s** until **SIGINT** / **SIGTERM**, logs on **stderr**, and closes the consumer in **`finally`**. ## Clone and run (quick reference) > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ```bash git clone https://github.com/bitquery/kafka-streams-examples-usecases.git cd kafka-streams-examples-usecases/python-consumer-example python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install -r requirements.txt cp .env.example .env # edit KAFKA_USERNAME, KAFKA_PASSWORD python consumer.py ``` ## TLS (optional) Extend the **`conf`** dict from **`settings.py`** using Bitquery’s **[SASL_SSL](/docs/streams/kafka-streaming-concepts/#ssl-connection-sasl_ssl-)** snippet (brokers **9093**, PEM paths). Summary and **`curl`** for PEMs: **[examples repo `README.md`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/README.md)**. ## Troubleshooting | Issue | Action | | ---------------------------------------- | ------------------------------------------------------------------------------ | | Missing env vars | **`cp .env.example .env`** and set credentials | | **`KafkaException`** / auth | Credentials, topic enabled for account, outbound **9092** | | **`DecodeError`** | Topic schema ≠ **`ParsedIdlBlockMessage`** | | Protobuf reflection errors after upgrade | Keep **`requirements.txt`** pins aligned with **`bitquery-pb2-kafka-package`** | ## See also - **[bitquery-pb2-kafka-package (PyPI)](https://pypi.org/project/bitquery-pb2-kafka-package/)** - **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)** --- ## Query Aggregated Metrics URL: https://docs.bitquery.io/docs/graphql/capabilities/aggregated_metrics/ Query Aggregated Metrics in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Query Aggregated Metrics This is the most effective query. If you consider to query the large dataset in one query, you have to use aggregation. To use aggregation in GraphQL, you define one or several [metrics](/docs/graphql/metrics/). This type of query is useful in the following cases: 1. query data in some specific buckets or intervals. Example is a candlestick market diagram by specific time intervals 2. get statistics over a large amount of data, for example total number of transactions or transfer volume 3. query integral information about some object, for example, an address [Example](https://ide.bitquery.io/Maximum-amounts-of-ETH-transfer-by-date) of query to get maximum ethereum transfer amount by date: ```graphql query { EVM(dataset: archive network: eth) { Transfers(where: { Block: {Date: {after: "2022-02-20"}} Transfer: {Currency: {Native: true}}}) { Block { Date } Transfer { Amount(maximum: Transfer_Amount) } } } } ``` ```maximum: Transfer_Amount``` calculates maximum amount of transfer in the scope of defined dimensions, namely ```Date```. --- ## Query Fact Records: Return Raw Rows from a Bitquery Cube URL: https://docs.bitquery.io/docs/graphql/capabilities/query_fact_records/ The simplest Bitquery query returns raw rows from a cube, such as the latest transactions with cost. When it fits, how to bound it, and when to aggregate. # Query Fact Records: Return Raw Rows from a Bitquery Cube A fact record query asks a cube for rows as they are, no aggregation: name the fields you want and the cube returns matching records subject to your [filters](/docs/graphql/filters), [sorting](/docs/graphql/sorting) and [limits](/docs/graphql/limits). It is the right shape for "the last 100 transactions", "transfers of this wallet today" or "every trade of this token in the last hour". It is the wrong shape for "all transfers ever": fact tables hold billions of rows and no limit and offset walk gets you the whole set. For totals and rankings, use [aggregated metrics](/docs/graphql/capabilities/aggregated_metrics) on the same cube instead. ## Two rules that keep it fast 1. Filter tightly. An address, a token contract and a time window let the engine read a small slice; a bare cube scan does not. Time filters matter most, and on `archive` they are close to mandatory. 2. Order and limit. `orderBy` on an indexed field with a small `limit` returns the latest rows quickly. Sorting a huge unfiltered set is what times out. ## Example: the latest transactions and what they cost The 100 newest BNB Chain transactions in block order, with the cost of each. Saved query [here](https://ide.bitquery.io/Last-transactions-with-cost). ```graphql query { EVM(dataset: realtime network: bsc) { Transactions(limit: {count: 100} orderBy: [{descending: Block_Number} {descending: Transaction_Index}]) { Block { Time Number } Transaction { Hash Cost } } } } ``` Sorting by block number and then transaction index gives a stable order inside a block, which plain `Block_Time` cannot, since every transaction in a block shares the same time. ## Turning it into other shapes - **One wallet:** add `where: { Transaction: { From: { is: "0x..." } } }`. - **A window:** add `Block: { Time: { since_relative: { hours_ago: 1 } } }` inside `where`. - **A live feed:** change `query` to `subscription` and drop `limit` and `orderBy`; new rows arrive as they are indexed. - **A total:** replace the selection with `count` and `sum(of: Transaction_Cost)`; see [aggregated metrics](/docs/graphql/capabilities/aggregated_metrics). ## Related pages - [Query filters](/docs/graphql/filters) - [Query limits](/docs/graphql/limits) - [Indexed fields reference](/docs/graphql/indexed-fields-reference) - [Aggregated metrics](/docs/graphql/capabilities/aggregated_metrics) - [GraphQL query capabilities](/docs/category/capabilities) --- ## Quick Start Examples URL: https://docs.bitquery.io/docs/trading/crypto-price-api/examples/ Runnable Crypto Price API queries and streams: token prices, OHLC candles, price movers and 1-second DEX streams, each with an IDE link. # Quick Start Examples ## What it is Runnable queries and streams for the Crypto Price API, grouped by task. Each one opens in the IDE; most run as a query or, with `subscription` on top, as a live stream. ## Prices ### Most accurate price for a token (top market, rank 1) {#most-accurate-price-for-a-token} Query `Pairs` with `Ranking: { Position: { eq: 1 } }` to price a token from its top market, the pool holding the largest share of the token's liquidity, instead of a value blended across every pool. Thin, fragmented pools cannot pull the number away from where the token actually trades. Full explanation, streaming variant and caveats: [Getting the most accurate token price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). [Run query ➤](https://ide.bitquery.io/Token-price-from-top-market--rank-1_2) ```graphql { Trading { Pairs( where: { Token: { Address: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 60 } } } Price: { IsQuotedInUsd: true } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } } Ranking { Position Weight } Volume { Usd } Block { Time } } } } ``` - `Price.Ohlc.Close` is the latest price on the top market. Keep `Price: { IsQuotedInUsd: true }`: every market also publishes rows in quote-token units, so without it a WBTC/WSOL market returns WBTC in SOL. - `Ranking.Weight` is the top pool's share of the token's liquidity (after the staleness discount). Near 1 means one pool drives the price; a low value means it is fragmented, which is where this query differs most from the blended `Tokens` price. - Change `query` to `subscription` and drop `limit`/`orderBy` to stream it. ### Real-time token prices in USD on Solana 1-second OHLC and volume for every Solana market, quoted in USD. `Price: {IsQuotedInUsd: true}` puts OHLC and averages in USD; `false` gives them in the quote token. More Solana price queries are on the [Solana Token Price API](/docs/blockchain/Solana/solana-token-price-api) page. [Run Stream ➤](https://ide.bitquery.io/Real-Time-USD-price-on-solana-chain_2) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Solana"}}, Volume: {Usd: {gt: 5}}} ) { Token { Name Symbol Address } Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } } } } } ``` - `Volume: { Usd: { gt: 5 } }` is an extra guard against near-empty candles; the index already filters outliers. The same guard appears in most streams below. ### Real-time token prices in the quote token (USDC, USDT, ...) Same stream with `Price: {IsQuotedInUsd: false}`, so prices are in the pair's quote token. [Run Stream ➤](https://ide.bitquery.io/Real-Time-usd-price-on-solana-chain-in-paired-token) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: false}, Market: {Network: {is: "Solana"}}, Volume: {Usd: {gt: 5}}} ) { Token { Name Symbol Address } QuoteToken { Name Symbol Address } Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } } } } } ``` ### Real-time token prices against SOL/WSOL Restrict `QuoteToken.Address` to SOL and WSOL to get token values in Solana's native currency. [Run Stream ➤](https://ide.bitquery.io/Real-Time-usd-price-on-solana-against-WSOLSOL) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: false}, QuoteToken:{ Address:{ in:["So11111111111111111111111111111111111111112" ,"11111111111111111111111111111111" ] } }, Market: {Network: {is: "Solana"}}, Volume: {Usd: {gt: 5}}} ) { Token { Name Symbol Address } QuoteToken { Name Symbol Address } Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } } } } } ``` ### Aggregated token data (volume and price, last 24h) {#aggregated-token-data-volume--price-last-24h} One row per token with USD volume over 24h and 4h and the current and 24h-ago average price. `limitBy: { count: 1, by: Token_Id }` groups per token; conditional metrics (`Usd(if: ...)`, `Mean(..., if: ...)`) slice the window. `Tokens` is the right cube here because volume is summed across all of a token's pools; its prices are blended across those pools too, so to price one token from its top market use [Pairs with rank 1](#most-accurate-price-for-a-token). [Run query ➤](https://ide.bitquery.io/aggregated-data-for-tokens) ```graphql { Trading { Tokens( limit: {count: 100} limitBy: {count: 1, by: Token_Id} where: {Block: {Time: {since_relative: {hours_ago: 24}}}, Interval: {Time: {Duration: {eq: 60}}}} ) { Token { Id Network Symbol(maximum: Block_Time) Name(maximum: Block_Time) Address(maximum: Block_Time) } Volume { Usd H4VAgo: Usd(if: {Block: {Time: {since_relative: {hours_ago: 4}}}}) } Price { Average { currentPrice: Mean(maximum: Block_Time) H24Ago: Mean( minimum: Block_Time if: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) } } Supply { TotalSupply(maximum: Block_Time) MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) } } } } ``` - The `Duration: { eq: 60 }` filter matters: without it `Volume.Usd` sums all ten stored durations and comes out about ten times too high. - Query only: `if` does not survive conversion to a subscription. ### Find price arbitrage of a pair across chains Latest price per market for BTC/USDT, one row per venue via `limitBy` on `Market_Address`. [Run Stream ➤](https://ide.bitquery.io/Find-arbitrage-opportunity-with-same-token-across-chains_1) ```graphql query { Trading { Pairs( where: { Price: { IsQuotedInUsd: true } Currency: { Id: { is: "bid:bitcoin" } } QuoteCurrency: { Id: { is: "usdt" } } Volume: { Usd: { gt: 5 } } } limit: { count: 10 } orderBy: { descending: Block_Time } limitBy: { by: Market_Address, count: 1 } ) { Currency { Id Name Symbol } QuoteCurrency { Id Name Symbol } Market { Name NetworkBid Network Address } Price { IsQuotedInUsd Average { Mean Estimate SimpleMoving ExponentialMoving WeightedSimpleMoving } } QuoteToken { Symbol Name Id NetworkBid Network Did Address } Token { Symbol Name Id NetworkBid Network Did Address } } } } ``` - No `Duration` filter here, so rows can come from any of the ten durations; add one before comparing volumes. ## OHLC ### OHLC of a currency on multiple blockchains One Bitcoin candle per minute across every chain and every Bitcoin token (cbBTC, WBTC and others). [Run Stream ➤](https://ide.bitquery.io/OHLC-of-a-currency-on-multiple-blockchains) ```graphql { Trading { Currencies( where: { Currency: { Id: { is: "bid:bitcoin" } }, Interval: { Time: { Duration: { eq: 60 } } }, Volume: { Usd: { gt: 5 } } }, limit: { count: 1 }, orderBy: { descending: Block_Time } ) { Currency { Id Name Symbol } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd #The price is shown in USD (`IsQuotedInUsd: true` by default). Ohlc { Open # Earliest price across chains in the interval High # Highest price across chains in the interval Low # Lowest price across chains in the interval Close # Latest price across chains in the interval } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` ### OHLC stream on a chain {#ohlc-stream-on-a-chain} Live OHLC, volume and moving averages for every token on one chain. Set the chain with `Token: {Network}`; values are `Ethereum`, `Solana`, `Base`, `Optimism`, `Matic`, `Arbitrum`, `Binance Smart Chain`, `Tron`, `Robinhood`, `Arc`. Durations are listed [here](/docs/trading/crypto-price-api/#understanding-intervals). The `Tokens` cube is USD-quoted only. [Run Stream ➤](https://ide.bitquery.io/Aggregated-Price-of-all-tokens-in-real-time-on-one-chain) ```graphql subscription { Trading { Tokens( where: { Token: { Network: { is: "Solana" } } Interval: { Time: { Duration: { eq: 60 } } } Volume: { Usd: { gt: 5 } } } ) { Token { Address Id IsNative Name Network Name Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` ### OHLC of a token pair across chains 1-second ETH/USDC candles from every chain. For native tokens only the currency id is needed (`bid:eth`). `Price: {IsQuotedInUsd: false}` gives prices in USDC; switch to `true` for USD. [Run Stream ➤](https://ide.bitquery.io/Token-OHLC-Stream-1-second-Multi-Chains_1) ```graphql subscription { Trading { Pairs( where: { Price: { IsQuotedInUsd: false } Interval: { Time: { Duration: { eq: 1 } } } Currency: { Id: { is: "bid:eth" } } QuoteCurrency: { Id: { is: "usdc" } } Volume: { Usd: { gt: 5 } } } ) { Token { Id Symbol Address NetworkBid Network Name } QuoteToken { Id Symbol Address Name NetworkBid } Interval { Time { Start End Duration } } Volume { Usd Quote Base } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Open High Low Close } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ``` ## Price change and movers ### 5-minute price change API Top 10 tokens by 5-minute percentage change in USD, with at least $100k of volume in the candle. Chain-wide scans are what `Tokens` is for; once you have picked a token, price it from its top market with [Pairs + rank 1](#most-accurate-price-for-a-token). Uses [expressions](/docs/graphql/capabilities/expression/). [Run Stream ➤](https://ide.bitquery.io/5-minute-price-change-api_2) ```graphql { Trading { Tokens( limit: { count: 10 } orderBy: { descendingByField: "change" } where: { Price: { IsQuotedInUsd: true } Volume: { Usd: { gt: 100000 } } Interval: { Time: { Duration: { eq: 300 } } } } ) { Token { Address Did Id IsNative Name Network Name Symbol TokenId } Currency { Symbol Id Name } Interval { VolumeBased Time { Start End Duration } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } diff: calculate(expression: "Price_Ohlc_Close - Price_Ohlc_Open") change: calculate(expression: "round(($diff / Price_Ohlc_Open), 3) * 100") } } } ``` ### 5-minute price change stream on Solana The same ranking as a live stream on one chain. For a watchlist of specific tokens, stream their top markets instead: [Watchlist: top-market price for several tokens](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). [Run Stream ➤](https://ide.bitquery.io/5-minute-price-change-api-on-solana_6) ```graphql subscription{ Trading { Tokens( orderBy:[{descending:Block_Time} {descendingByField:"change"}] where: { Price:{IsQuotedInUsd:true} Token:{Network:{is:"Solana"}} Volume:{Usd:{gt:100000}} Interval: {Time: {Duration: {eq: 300}}}}) { Token { Address Did Id IsNative Name Network Name Symbol TokenId } Currency { Symbol Id Name } Interval { VolumeBased Time { Start End Duration } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } diff: calculate(expression:"$Price_Ohlc_Close - $Price_Ohlc_Open") change: calculate(expression:"$diff / $Price_Ohlc_Open * 100") } } } ``` ### Drawdown of an asset in the last hour Percentage drawdown `((Close - Open) / Open) * 100` over a 1-hour candle, for every token representation of a currency. Swap `Currency: {Id}` for `Token: {Address: {is: "..."}}` to target one token. This compares a currency's token representations against each other, so `Tokens` fits; to measure one token on the market where it trades, run the same expression on [Pairs with rank 1](#most-accurate-price-for-a-token). [Run query](https://ide.bitquery.io/Drawdown-of-a-token-last-hour) ```graphql { Trading { Tokens( limit: { count: 1 } orderBy: { ascendingByField: "drawdown" } where: { Volume: { Usd: { gt: 10 } } Interval: { Time: { Duration: { eq: 3600 } } } Currency: { Id: { is: "bid:bitcoin" } } } ) { Token { Address Did Id IsNative Name Network Symbol TokenId } Currency { Symbol Id Name } Interval { VolumeBased Time { Start End Duration } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } diff: calculate(expression: "Price_Ohlc_Close - Price_Ohlc_Open") drawdown: calculate(expression: "($diff / Price_Ohlc_Open) * 100") } } } ``` ### Top Solana price movers (5-minute, high volume) Solana tokens ranked by 5-minute change with a $100k volume floor, one row per token. This is a query over 300-second candles, not a volume-based interval; see [Volume-based aggregation](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api#volume-based-aggregation). [Run Stream ➤](https://ide.bitquery.io/5-minute-price-change-api-on-solana_5) ```graphql { Trading { Tokens( limit: { count: 10 } limitBy: { count: 1, by: Token_Id } orderBy: [{ descending: Block_Time }, { descendingByField: "change" }] where: { Price: { IsQuotedInUsd: true } Token: { Network: { is: "Solana" } } Volume: { Usd: { gt: 100000 } } Interval: { Time: { Duration: { eq: 300 } } } } ) { Token { Address Did Id IsNative Name Network Name Symbol TokenId } Currency { Symbol Id Name } Interval { VolumeBased Time { Start End } } Volume { Base BaseAttributedToUsd Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { Estimate ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } diff: calculate(expression: "Price_Ohlc_Close - Price_Ohlc_Open") change: calculate(expression: "round(($diff / Price_Ohlc_Open), 3) * 100") } } } ``` ### Trending tokens (multi-chain) {#trending-tokens-multi-chain} Top trending tokens across all chains in one query, ranked by trailing 1-hour USD volume. Built on 1-minute `Tokens` candles: `vol_1h` sums the hour with a $10k floor via `selectWhere`, `vol_5m` is a conditional sum for the last 5 minutes, and `priceMove` is the absolute 1h price change (%) from an [expression](/docs/graphql/capabilities/expression/). Quote and wrapped assets are excluded by symbol and market cap is capped at $100M. [Run query ➤](https://ide.bitquery.io/Trending-tokens-multi-chain) ```graphql { Trading { Tokens( limit: { count: 20 } orderBy: { descendingByField: "vol_1h" } where: { Price: { IsQuotedInUsd: true } Interval: { Time: { Duration: { eq: 60 } } } Block: { Time: { since_relative: { hours_ago: 1 } } } Supply: { MarketCap: { le: 100000000 } } Token: { Symbol: { notIn: ["WSOL", "USDC", "USDT", "WETH", "DAI", "cbBTC"] } } } ) { Token { Id Network Symbol(maximum: Block_Time) Name(maximum: Block_Time) Address(maximum: Block_Time) } vol_1h: sum(of: Volume_Usd, selectWhere: { ge: "10000" }) vol_5m: sum(of: Volume_Usd, if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } }) Price { Ohlc { open: Open(minimum: Interval_Time_Start) high: High(maximum: Price_Ohlc_High) low: Low(minimum: Price_Ohlc_Low) close: Close(maximum: Interval_Time_Start) } } priceMove: calculate(expression: "abs(($Price_Ohlc_close - $Price_Ohlc_open) / $Price_Ohlc_open) * 100") Supply { MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) } } } } ``` - Apply a price-move cut (for example 500%) client-side; a computed expression cannot be filtered server-side. - For pool depth, `Liquidity { Usd }` is on `Tokens` and `Pairs` rows (see [Liquidity fields](/docs/trading/crypto-price-api/liquidity-fields)); for raw reserves join a chain-level `DEXPools` query. - Query only: `selectWhere` and `if` do not survive conversion to a subscription. ## DEX-specific 1-second streams All eight streams share one shape: `Pairs` at `Duration: 1`, `Price: {IsQuotedInUsd: true}`, `Volume: {Usd: {gt: 5}}`, filtered to one DEX with `Market.Program` on Solana or `Market.Address` (the factory) on EVM chains. Each row is one pool's 1-second candle with volume, supply and the moving averages in `Price.Average`. Set `IsQuotedInUsd: false` to get prices in the quote token. ### PumpAMM (Solana) [Run Stream ➤](https://ide.bitquery.io/PumpAMM-tokens-1-second-price-stream-with-OHLC_1) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Solana"}, Program: {is: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` ### Heaven DEX (Solana) [Run Stream ➤](https://ide.bitquery.io/Heaven-DEX-tokens-1-second-price-stream-with-OHLC) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Solana"}, Program: {is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` ### Meteora DBC (Solana) [Run Stream ➤](https://ide.bitquery.io/Meteora-DBC-DEX-tokens-1-second-price-stream-with-OHLC) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Solana"}, Program: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` ### Raydium Launchlab (Solana) [Run Stream ➤](https://ide.bitquery.io/Raydium-Launchpad-DEX-tokens-1-second-price-stream-with-OHLC) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Solana"}, Program: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` ### Uniswap v3 (Ethereum) [Run Stream ➤](https://ide.bitquery.io/Uniswap-v3-DEX-tokens-1-second-price-stream-with-OHLC) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Ethereum"}, Address: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` ### Sushiswap (Ethereum) [Run Stream ➤](https://ide.bitquery.io/Sushiswap-DEX-tokens-1-second-price-stream-with-OHLC) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Ethereum"}, Address: {is: "0xc0aee478e3658e2610c5f7a4a2e1777ce9e4f2ac"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` - This stream returned zero rows when run as a query on 2026-10-22. If it is quiet, raise `Duration` to 60. ### PancakeSwap v3 (Ethereum) [Run Stream ➤](https://ide.bitquery.io/PancakeSwap-v3-DEX-tokens-1-second-price-stream-with-OHLC_1) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Ethereum"}, Address: {is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` - For PancakeSwap v3 on BSC, use `Network: {is: "Binance Smart Chain"}` with the same factory address as in the [OHLC guide](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api#how-do-i-stream-1-second-candles-for-pancakeswap-v3-on-bsc). ### FourMeme (BSC) [Run Stream ➤](https://ide.bitquery.io/FourMeme-DEX-tokens-1-second-price-stream-with-OHLC) ```graphql subscription { Trading { Pairs( where: {Interval: {Time: {Duration: {eq: 1}}}, Price: {IsQuotedInUsd: true}, Market: {Network: {is: "Binance Smart Chain"}, Address: {is: "0x5c952063c7fc8610ffdb798152d69f0b9550762b"}}, Volume: {Usd: {gt: 5}}} ) { Market { Protocol Program Network Name Address } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Ohlc { Close High Low Open } IsQuotedInUsd } Currency { Symbol Name Id } QuoteCurrency{ Name Symbol Id } Token{ Name Symbol Address Id NetworkBid } QuoteToken{ Name Symbol Id Address NetworkBid } } } } ``` ## Related - [Crypto Price API introduction](/docs/trading/crypto-price-api/) - [OHLC Candle (K-Line) API](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api) - [Crypto Market Cap API](/docs/trading/crypto-price-api/crypto-marketcap-api) - [Pairs](/docs/trading/crypto-price-api/pairs/), [Tokens](/docs/trading/crypto-price-api/tokens/), [Currencies](/docs/trading/crypto-price-api/currency/) - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) --- ## RWA (Real World Assets) API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/transfers/rwa-api/ RWA (Real World Assets) API: monitor Ethereum native and token transfers in real time with Bitquery GraphQL APIs. Built for traders and analytics teams. # RWA (Real World Assets) API In this section, we will explore some of the APIs that help us obtain information about Real World Assets (RWAs) on Ethereum, Arbitrum, and other EVM chains. These APIs can be executed on any EVM chain simply by changing the `network: eth` parameter to the appropriate chain and using the correct address. We have written about analyzing RWA data in the blog [here](https://bitquery.io/blog/real-world-asset-tracking-arbitrum-bitquery-apis) and how it has influenced tokenized real-estate [here](https://bitquery.io/blog/tokenized-real-estate-transforming-property-investment). ## Top Holders of an RWA You can view and execute the query for the top holders of an RWA using the following examples: - [Top holder stats for Mountain's USDM](https://ide.bitquery.io/top-holder-stats-for-Mountains-USDM) - [Top holder stats for Backed Finance’s blB01](https://ide.bitquery.io/top-holder-stats-for-Backed-Finances-blB01) ```graphql { EVM(dataset: archive, network: eth) { Holders( date: "2025-04-22" limit: { count: 10 } orderBy: { descending: Balance_Amount }, where: { Currency: { SmartContract: { is: "0x59D9356E565Ab3A36dD77763Fc0d87fEaf85508C" } } } ) { Holder { Address } Balance { UpdateCount } Balance { Amount } } } } ``` This query retrieves the top 10 holders of the specified token contract, ranked by their balance amount. ## Real-time Transfers of RWAs on Arbitrum You can monitor real-time transfers of RWAs using the stream link below: [Real-time Transfers of Xend Real World Asset Token](https://ide.bitquery.io/Subscribe-to-Latest-Xend-Real-World-Asset-token-transfers) ```graphql subscription { EVM(network: arbitrum) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x3096e7BFd0878Cc65be71f8899Bc4CFB57187Ba3" } } } } ) { Transaction { Hash } Transfer { Amount Currency { Name Symbol } Receiver Sender Type } } } } ``` This subscription continuously monitors and provides real-time updates on token transfers for the specified token contract. ## Latest Issuance of an RWA This query filters for recent `Issue` events on Ethereum and displays logs emitted by the fund’s smart contract (`0x7712c34205737192402172409a8F7ccef8aA2AEc`) and extracts structured event data. You can use the same as a `subscription` to monitor issuances in real-time. You can run the query [here](https://ide.bitquery.io/BlackRock-USD-Institutional-Digital-Liquidity-Fund-Latest-Issuance) ```graphql { EVM(dataset: realtime, network: eth) { Events( limit: {count: 20} where: {LogHeader:{Address:{is:"0x7712c34205737192402172409a8F7ccef8aA2AEc"}}, Log:{ Signature:{Name:{is:"Issue"}} }} ) { Block { Time Number Hash } Receipt { ContractAddress } Topics { Hash } TransactionStatus { Success } LogHeader { Address Index Data } Transaction { Hash From To Index } Log { EnterIndex ExitIndex Index LogAfterCallIndex Pc SmartContract Signature { Name Signature } } Arguments { Name Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { Signature { Name } } } } } ``` --- ## RadarDEX Launchpad API on Arc: Tokens, Trades and OHLCV URL: https://docs.bitquery.io/docs/blockchain/arc-mainnet/radardex-launchpad-api/ Track RadarDEX Classic and Reflection token launches on Circle Arc. Query swaps, traders, USD prices and OHLCV with Bitquery Trading APIs and streams. # RadarDEX Launchpad API on Arc: Tokens, Trades and OHLCV [RadarDEX](https://www.radardex.pro/) offers Classic and Reflection token launches on Arc, Circle's EVM chain. Its launch page describes opening a Uniswap v3 pool when a token is created. Monitor both factories to build a list of RadarDEX launches. RadarDEX's site states that it does not currently have its own token. A token name or symbol cannot prove that it belongs to the platform; match the launch contract and event. Use `EVM.Events` to find launches. All trading examples below use `Trading.Trades`, `Trading.Pairs`, or `Trading.Tokens`. :::note API access Run the saved examples in the Bitquery IDE, or create an [API access token](/docs/authorization/how-to-generate/) for `https://streaming.bitquery.io/graphql`. For streams, use `wss://streaming.bitquery.io/graphql` with [WebSocket authorization](/docs/authorization/websocket/). ::: ## Find the latest RadarDEX token launches Filter by the factory address and the `TokenLaunched` signature. The checks for transaction success and reverted calls exclude failed launches. The 24-hour filter covers only the history currently indexed. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-latest-launches) ```graphql query { EVM(network: arc) { Events( limit: {count: 20} orderBy: {descending: Block_Time} where: { Block: {Time: {since_relative: {hours_ago: 24}}} TransactionStatus: {Success: true} Call: {Success: true, Reverted: false} LogHeader: { Address: {in: ["0x4b638c1502a07a8e1a26112ee98f51a3f34bc93a", "0x2d933ce4bde6f3d99540b5d7886b383e59b2b2f8"]} Removed: false } Log: {Signature: {SignatureHash: {is: "851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {SignatureHash}} Topics {Hash} } } } ``` ## Contracts and token identity | Contract | Arc address | | --- | --- | | RadarDEX Classic | `0x4b638c1502a07a8e1a26112ee98f51a3f34bc93a` | | RadarDEX Reflection | `0x2d933ce4bde6f3d99540b5d7886b383e59b2b2f8` | The launch event signature is `851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66`. These contract/event pairs were checked against Arc data on 16 September 2026. Keep older factory addresses in your own registry when you need earlier launches. See the [RadarDEX site](https://www.radardex.pro/) and the [Arc launchpad contract list](/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/#verified-launchpad-contracts). The response's `Topics` array uses these positions: - `Topics[0].Hash`: event signature. - `Topics[1].Hash`: token address, padded on the left to 32 bytes. Take the final 40 hex characters of `Topics[1].Hash`, add `0x`, and lowercase the address. To query Trading, prefix the result with `bid:arc:`. For example, SLJ's token ID is `bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483`. These examples use two tokens whose launch events matched the RadarDEX factory: | Sample token | Contract | | --- | --- | | SLJ | `0xa6fe05d5c5beb68aae0496830199f9b36a5d4483` | | ARCG | `0x458f4cf6db2458de50ae1727fc64043af3f39ff9` | They are user-created examples. Replace their addresses with a token returned by the launch query. Save each token's factory, launch time and transaction hash in your application. :::tip Build a launchpad token list The Trading cubes do not attach a RadarDEX launchpad label to each token. Build that list from launch events, then pass the token IDs into Trading queries. For Uniswap v2/v3, `Pair.Market.Address` is the DEX factory and `Pair.Pool.Address` is the pool. For Uniswap v4, `Pair.Market.Address` can be empty and several pools share `Pair.Pool.Address`; include `Pair.Pool.Id` to select one pool. These trading fields do not identify the launchpad that created the token. ::: ## Stream new RadarDEX launches Subscribe with the same factory and signature filters. The decoded event name may be empty; the signature and raw topics still identify the launch. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-launch-stream) ```graphql subscription { EVM(network: arc) { Events( where: { TransactionStatus: {Success: true} Call: {Success: true, Reverted: false} LogHeader: { Address: {in: ["0x4b638c1502a07a8e1a26112ee98f51a3f34bc93a", "0x2d933ce4bde6f3d99540b5d7886b383e59b2b2f8"]} Removed: false } Log: {Signature: {SignatureHash: {is: "851d681a32f0efba577c4a1bd412f74b575764a6b91e499a05a48a23f3821d66"}}} } ) { Block {Number Time} Transaction {Hash From} LogHeader {Address Index} Log {Signature {SignatureHash}} Topics {Hash} } } } ``` Append new token IDs to your application's list. A Trading subscription has fixed filters: resubscribe with the updated list when a new launch arrives. Keep a time checkpoint and query recent events after reconnecting; the HTTP endpoint and WebSocket do not join these steps for you. Deduplicate launch records by transaction hash and log index. ## Recent trades for a RadarDEX token Match the token on either side of the pair. This includes trades where it is the quote asset. The `Uniswap` family filter selects the v2/v3/v4 markets observed for Arc; extend the family filter when you verify another venue. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-recent-trades) ```graphql query { Trading { Trades( limit: {count: 20} orderBy: {descending: Block_Time} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}}}} ] } ) { Block {Time} TransactionHeader {Hash Index} Trader {Address} Side Amounts {Base Quote} AmountsInUsd {Quote} PriceInUsd Pair { Token {Id Symbol} QuoteToken {Id Symbol} Market {Network Protocol} Pool {Address Id} } } } } ``` `Side` is relative to `Pair.Token`. If the selected token is `Pair.QuoteToken`, reverse Buy/Sell when describing that token's direction. `PriceInUsd` also refers to `Pair.Token` and is an indexed reference price; use the amount ratio when you need the executed price. Use `AmountsInUsd.Quote` for quoted USD turnover. Do not add base and quote USD amounts from the same row. One transaction can contain several swaps; use a distinct transaction hash count for transaction totals. ## Stream trades for a RadarDEX token The same token filters work as a Trading subscription. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-trade-stream) ```graphql subscription { Trading { Trades( where: { Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}}}} ] } ) { Block {Time} TransactionHeader {Hash Index} Trader {Address} Side Amounts {Base Quote} AmountsInUsd {Quote} PriceInUsd Pair { Token {Id Symbol} QuoteToken {Id Symbol} Market {Network Protocol} Pool {Address Id} } } } } ``` For several tokens, replace each `is` token filter with an `in` list. Keep both the base-token and quote-token branches. ## Rank a RadarDEX token watchlist by volume This sample ranks SLJ and ARCG over the last 24 hours. It includes only rows where a listed token is `Pair.Token`, so the Buy/Sell counts have a consistent meaning. Extend the list from launch events to cover more tokens. It is not a total for the whole launchpad. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-watchlist-volume) ```graphql query { Trading { Trades( limit: {count: 20} orderBy: {descendingByField: "volumeUsd"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: { Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}} Token: {Id: {in: [ "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483" "bid:arc:0x458f4cf6db2458de50ae1727fc64043af3f39ff9" ]}} } } ) { Pair {Token {Id Symbol}} trades: count transactions: count(distinct: TransactionHeader_Hash) traders: count(distinct: Trader_Address) volumeUsd: sum(of: AmountsInUsd_Quote) buys: count(if: {Side: {is: "Buy"}}) sells: count(if: {Side: {is: "Sell"}}) } } } ``` The time filter measures trading during the selected window. It does not restrict token creation time; keep launch timestamps in your own token registry if you need a new-launch cohort. :::caution Counts and volume These server aggregates count the indexed rows. The [Trading Trades field notes](/docs/trading/crypto-trades-api/trades-api/#before-you-aggregate-three-things-about-a-trades-row) describe duplicate rows that can affect exact totals. For audited figures, fetch the underlying rows and check duplicates before summing. Wallet counts refer to addresses, not people. ::: ## Most active traders for a RadarDEX token Rank wallets by quoted USD turnover across both pair orientations. This measures activity, not profit. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-top-traders) ```graphql query { Trading { Trades( limit: {count: 10} orderBy: {descendingByField: "volumeUsd"} where: { Block: {Time: {since_relative: {hours_ago: 24}}} Pair: {Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}}} any: [ {Pair: {Token: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}}}} {Pair: {QuoteToken: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}}}} ] } ) { Trader {Address} trades: count transactions: count(distinct: TransactionHeader_Hash) volumeUsd: sum(of: AmountsInUsd_Quote) } } } ``` ## Latest price from the top market Use `Trading.Pairs` with rank 1 to retrieve the token's most recent one-minute price interval from its top market. Inspect `Interval.Time.End`: a quiet token can return an old interval. Rank 1 may return no row when the top market has not traded within the requested window. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-top-market-price) ```graphql query { Trading { Pairs( limit: {count: 1} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}} Market: {NetworkBid: {is: "bid:arc"}, ProtocolFamily: {is: "Uniswap"}} Block: {Time: {since_relative: {hours_ago: 24}}} Interval: {Time: {Duration: {eq: 60}}} Ranking: {Position: {eq: 1}} Price: {IsQuotedInUsd: true} } ) { Token {Id Symbol} QuoteToken {Id Symbol} Pool {Address Id} Market {Network Protocol} Interval {Time {Start End Duration}} Price {IsQuotedInUsd Ohlc {Close}} Ranking {Position Weight} Volume {Usd} } } } ``` For broader token coverage, use the [Tokens cube](/docs/trading/crypto-price-api/tokens/). For a fixed pool's history, use the [Pairs cube](/docs/trading/crypto-price-api/pairs/) with `Pool.Address`; on Uniswap v4, also filter by its non-empty `Pool.Id`. Keep the Arc network filter. ## One-minute OHLCV candles `Trading.Tokens` combines indexed pools for the token. This query returns up to 120 rows for one-minute intervals within the last 24 hours, newest first. Resolve repeated interval rows as noted below, then plot from oldest to newest. [Run in Bitquery IDE](https://ide.bitquery.io/arc-mainnet-radardex-ohlcv-candles) ```graphql query { Trading { Tokens( limit: {count: 120} orderBy: {descending: Block_Time} where: { Token: {Id: {is: "bid:arc:0xa6fe05d5c5beb68aae0496830199f9b36a5d4483"}, NetworkBid: {is: "bid:arc"}} Block: {Time: {since_relative: {hours_ago: 24}}} Interval: {Time: {Duration: {eq: 60}}} Price: {IsQuotedInUsd: true} } ) { Token {Id Symbol} Interval {Time {Start End Duration}} Price {IsQuotedInUsd Ohlc {Open High Low Close}} Volume {Base Usd} } } } ``` `Volume.Usd` is USD volume and `Volume.Base` is token units. These candles can differ from a single pool's price. Empty intervals may be absent; treat a missing interval as missing data unless your chart has an explicit fill rule. The current interval may still change. Token symbols can arrive after price data, so the same `Token.Id` and `Interval.Time.Start` may appear more than once. Check repeated keys before plotting; do not sum repeated rows or drop conflicting values without a rule. See the [Tokens field notes](/docs/trading/crypto-price-api/tokens/#field-notes). To stream candles, change `query` to `subscription`, remove `limit`, `orderBy`, and the historical `Block.Time` filter, and keep the token and interval filters. ## Related APIs - [Tolly Launchpad API](/docs/blockchain/arc-mainnet/tolly-launchpad-api/) - [Arc Launchpads API](/docs/blockchain/arc-mainnet/arc-mainnet-launchpads-api/) - [Arc Blockchain API](/docs/blockchain/arc-mainnet/) - [Trading Trades API](/docs/trading/crypto-trades-api/trades-api/) - [Trading Tokens OHLCV API](/docs/trading/crypto-price-api/tokens/) --- ## Rate Limits, Concurrency & Backoff URL: https://docs.bitquery.io/docs/plans/rate-limits/ Bitquery API rate limits, 429 causes, recommended backoff, WebSocket concurrency caps, and gRPC stream rules. # Rate Limits, Concurrency & Backoff This page explains the limits that govern how fast you can query and stream, how to tell the different throttles apart, and how to build a client that backs off correctly. :::note Limits vary by plan The [pricing page](https://bitquery.io/pricing) is the source of truth for current per-plan limits. ::: ## Request rate limit The GraphQL API enforces a per-account **requests-per-minute** limit by plan: | Plan | Rate limit | |---|---| | Personal | 30 / min | | Pro | 90 / min | | Scale | 240 / min | | Enterprise | Custom | Exceeding it returns a `429`. Heavy analytical queries also compete for shared compute (see below), so throughput in practice depends on query cost, not just request count. ## Three different throttles — and how to tell them apart A `4xx`/`5xx` under load can come from three distinct sources. Diagnosing which one you hit determines the fix: 1. **Account rate limit** — you're sending requests faster than your plan's per-minute allowance. *Fix:* slow down / add client-side rate limiting. 2. **Shared compute pressure** — a message like `temporarily blocked due to a high number of long-running queries` means the shared query engine is busy, not that you exceeded an account limit. *Fix:* retry with backoff; make queries cheaper (narrower time windows, indexed filters). 3. **Plan entitlement block** — the request targets a chain/cube/interface not in your plan. *Fix:* this is billing, not throttling — see [How Billing Works](/docs/plans/how-billing-works/). ## Recommended client behavior - Run **heavy queries sequentially**, not in large parallel bursts. - On `429` or a shared-compute block, use **exponential backoff** (start around 5s, double, cap at ~1 min). - Keep queries cheap: narrow `Block.Time`/date ranges, and filter on [indexed fields](/docs/graphql/indexed-fields-reference/) so the engine scans less. - Prefer **one batched query** (many addresses/tokens in a single `where`) over many small ones. ## WebSocket concurrency - Each plan allows a maximum number of **concurrent subscriptions** (Personal: none; Pro: 100; Scale: 1,000; Enterprise: unlimited). - **Exceeding the cap fails silently:** the socket connects but delivers no data, rather than returning a clear error. If a subscription "connects but nothing arrives," check your running-subscription count first at [Account → Subscriptions](https://account.bitquery.io/user/api_v2/subscriptions). - **Revoking a token does not kill open sockets.** Terminate running subscriptions explicitly from the account panel. See [WebSocket subscriptions](/docs/subscriptions/websockets/). ## gRPC (Solana CoreCast) - A gRPC subscription **requires at least one filter** — an unfiltered stream is rejected. - **Multiple tokens per stream.** You can subscribe to many token/account filters in a single gRPC stream — you don't need one stream per token. ## Next steps - [How Billing Works: Points, Plans & Limits](/docs/plans/how-billing-works/) - [WebSocket subscriptions](/docs/subscriptions/websockets/) - [Common errors and what to do](/docs/start/errors/) - [Indexed fields reference](/docs/graphql/indexed-fields-reference/) --- ## Raydium CLMM API: Concentrated Liquidity Trades & Positions URL: https://docs.bitquery.io/docs/blockchain/Solana/raydium-clmm-API/ Raydium CLMM API on Solana: real-time concentrated-liquidity swaps, new pools, positions opened and closed, and liquidity added or removed at a price, via GraphQL and Kafka. Part of the Raydium DEX API. # Raydium CLMM API :::tip Need real-time Raydium CLMM data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Raydium CLMM swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Raydium CLMM data older than ~30 days**, raw per-swap detail, or call / event context. ::: Bitquery provides comprehensive real-time and historical data APIs and Streams for the Solana blockchain, enabling developers and traders to build powerful applications and execute trades based on reliable information. ## Raydium CLMM API Guide In this section we will see how to get data on Raydium CLMM trades in real-time. According to the official docs available [here](https://docs.raydium.io/products/clmm), "Concentrated Liquidity Market Maker (CLMM) pools allow liquidity providers to select a specific price range at which liquidity is active for trades within a pool. " :::note `Trade Side Account` field will not be available as aggregates in Archive and Combined Datasets ::: ## Subscribe to Realtime CLMM Trades This query subscribes to real-time trades on the Raydium CLMM (Concentrated Liquidity Market Maker) on the Solana blockchain by filtering using `{Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}}}:`. You can run the query [here](https://ide.bitquery.io/Raydium-CLMM-DEX-Trades-with-AccountNames) ```graphql subscription MyQuery { Solana { DEXTrades( where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}}}, Transaction: {Result: {Success: true}}} ) { Instruction { Program { Method AccountNames } } Trade { Buy { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } Sell { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } } Transaction { Signature } } } } ``` ## Latest Pool Creation on Raydium CLMM The below query tracks latest pool creation on raydium CLMM. The `"Program": {"AccountNames"}` includes the order in which account addresses are mentioned in `Accounts` list. This includes `poolCreator`, token vaults (`tokenVault0`, `tokenVault1`) and token mints (`tokenMint0`, `tokenMint1`). The mint addresses for the tokens being used in the pool are listed for example `tokenMint1` could be any newly deployed token and `tokenMint0` can be WSOL , indicating which tokens the CLMM pool will support. You can run the query [here](https://ide.bitquery.io/Raydium-CLMM-Pool-Creation) ```graphql { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}, Method: {is: "createPool"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Name } } } Transaction { Signature Signer } } } } ``` ## Latest Positions Closed The below query tracks latest position closes on raydium CLMM by filtering using `Method: {is: "closePosition"}`. The `personalPosition` account which is the 4th in the list of `Accounts` includes the address of account to store personal position. ```graphql { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}, Method: {is: "closePosition"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Name } } } Transaction { Signature Signer } } } } ``` ## Latest Positions Created The below query tracks latest position created on raydium CLMM by filtering using `Method: {is: "openPositionV2"}`. This is where various accounts like NFTs, tokens, and program states are updated. The parameters define liquidity and token amounts involved in the position. - **amount0Max** corresponds to **tokenVault0** and **tokenAccount0**. - **amount1Max** corresponds to **tokenVault1** and **tokenAccount1**. - **amount0Max**: The maximum amount of **Token 0** to be added to the position. - **amount1Max**: The maximum amount of **Token 1** to be added to the position. ```graphql { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}, Method: {is: "openPositionV2"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Name } } } Transaction { Signature Signer } } } } ``` ## CLMM Position Line : Adding Liquidity at a Price This API fetches Increase Liquidity V2 transactions from the Raydium CLMM on Solana. It retrieves relevant data, including liquidity amounts, token accounts, execution logs, and transaction details. The arguments and account details include - `AccountNames`: List of accounts involved ``` "nftOwner", "nftAccount", "poolState", "protocolPosition", "personalPosition", "tickArrayLower", "tickArrayUpper", "tokenAccount0", "tokenAccount1", "tokenVault0", "tokenVault1", "tokenProgram", "tokenProgram2022", "vault0Mint", "vault1Mint" ``` - `Address`: Contract address of the program - `Arguments` (Liquidity & Token Values) - `liquidity` → `{json}` - `amount0Max` → The maximum amount of Token 0 (possibly SOL) added as liquidity. - `amount1Max` → The maximum amount of Token 1 (SPL token) added as liquidity. You can run the query [here](https://ide.bitquery.io/increaseLiquidityV2-latest-raydium-clmm#) ```graphql { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}, Method: {is: "increaseLiquidityV2"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Name } Name Method Json Parsed } Logs } Transaction { Signature Signer } } } } ``` ## CLMM Position Line : Removing Liquidity at a Price This API fetches **Decrease Liquidity V2** transactions from the **Raydium CLMM** on **Solana**. It retrieves relevant data, including liquidity amounts, token accounts, execution logs, and transaction details. ### **Arguments and Account Details** - **`AccountNames`**: List of accounts involved ``` "nftOwner", "nftAccount", "personalPosition", "poolState", "protocolPosition", "tokenVault0", "tokenVault1", "tickArrayLower", "tickArrayUpper", "recipientTokenAccount0", "recipientTokenAccount1", "tokenProgram", "tokenProgram2022", "memoProgram", "vault0Mint", "vault1Mint" ``` - **`Address`**: Contract address of the program - **`Arguments` (Liquidity & Token Values)** - `liquidity` → `{json}` - `amount0Min` → The minimum amount of **Token 0** (possibly SOL) withdrawn from liquidity. - `amount1Min` → The minimum amount of **Token 1** (SPL token) withdrawn from liquidity. You can run the query **[here](https://ide.bitquery.io/decreaseLiquidityV2-latest-raydium-clmm_1#)** ```graphql { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}, Method: {is: "decreaseLiquidityV2"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Name } Name Method Json Parsed } Logs } Transaction { Signature Signer } } } } ``` ## Limit orders on Raydium CLMM Raydium CLMM pools take on-chain limit orders through four instructions: `openLimitOrder`, `decreaseLimitOrder`, `settleLimitOrder` and `closeLimitOrder`. `openLimitOrder` carries the side (`zeroForOne`), the `tickIndex` the order sits at and the `amount` in the input token's smallest unit. Settlements are signed by a Raydium keeper rather than the order's owner. The feature is new, with a handful of orders an hour on 2026-10-26. [Run it in the IDE ➤](https://ide.bitquery.io/Raydium-CLMM-limit-orders) ```graphql query ClmmLimitOrders { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}, Method: {in: ["openLimitOrder", "decreaseLimitOrder", "settleLimitOrder", "closeLimitOrder"]}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { Address } Program { Method Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` --- ## Raydium CPMM API: Constant-Product Pool Trades on Solana URL: https://docs.bitquery.io/docs/blockchain/Solana/raydium-cpmm-API/ Raydium CPMM API on Solana: real-time constant-product pool swaps, pool creation and prices via GraphQL, WebSocket and Kafka. Part of the Raydium DEX API. # Raydium CPMM API :::tip Need real-time Raydium CPMM data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Raydium CPMM swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Raydium CPMM data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section we will see how to get data on Raydium CPMM trades in real-time. You can check out our [Pump Fun docs](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/), [Raydium v4 docs](/docs/blockchain/Solana/Solana-Raydium-DEX-API/) and [Raydium LaunchPad docs](/docs/blockchain/Solana/launchpad-raydium/) too. :::note `Trade Side Account` field will not be available as aggregates in Archive and Combined Datasets ::: ## Subscribe to Realtime CPMM Trades This query subscribes to real-time trades on the Raydium CPMM on the Solana blockchain by filtering using `{Program: {Address: {is: "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"}}}:`. You can run the query [here](https://ide.bitquery.io/CPMM-trades). ```graphql subscription MyQuery { Solana { DEXTrades( where: {Instruction: {Program: {Address: {is: "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"}}}, Transaction: {Result: {Success: true}}} ) { Instruction { Program { Method } } Trade { Buy { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } Sell { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } } Transaction { Signature } } } } ``` ## Latest Pool Creation on Raydium CPMM The below query tracks latest pool creation on raydium CPMM. The `"Program": {"AccountNames"}` includes the order in which account addresses are mentioned in `Accounts` list. This includes `poolCreator`, token vaults (`tokenVault0`, `tokenVault1`) and token mints (`tokenMint0`, `tokenMint1`). The mint addresses for the tokens being used in the pool are listed for example `tokenMint1` and `tokenMint0` , indicating which tokens the CPMM will support. You can run the query [here](https://ide.bitquery.io/CPMM-pools-created_1) ```graphql { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"}, Method: {is: "initialize"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Name } } } Transaction { Signature Signer } } } } ``` --- ## Raydium DEX API - Solana Trades, Pools, OHLC URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-Raydium-DEX-API/ Query Raydium on Solana with Bitquery GraphQL: new liquidity pools over WebSocket, pair creation times, historical pairs, token prices and OHLC candles. # Raydium DEX API - Solana Trades, Pools, OHLC :::tip Need real-time Raydium data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Raydium swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Raydium data older than ~30 days**, raw per-swap detail, or call / event context. For an overview of what the [Raydium API](https://bitquery.io/products/raydium-api) covers — AMM, CLMM and CPMM trades, pools and OHLC — with plans and trial access, see the product page. ::: In this section, we will see how to get Raydium information using Bitquery APIs. This is the hub page for Raydium on Solana. It covers the AMM v4 program; each other Raydium program has its own page: - [Raydium CLMM API](/docs/blockchain/Solana/raydium-clmm-API/): concentrated-liquidity swaps, positions and liquidity changes - [Raydium CPMM API](/docs/blockchain/Solana/raydium-cpmm-API/): constant-product pool swaps and pool creation - [Raydium Launchpad API](/docs/blockchain/Solana/launchpad-raydium/): LaunchLab token launches and bonding-curve trades For gRPC streaming of Raydium DEX trades: [Solana gRPC Streams (CoreCast) →](/docs/grpc/solana/introduction/) :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## New Liquidity Pools Created on Solana Raydium DEX (Using Websocket) You can subscribe to newly created Solana Raydium liquidity pools using the GraphQL subscription (WebSocket). You can try this GraphQL subscription [using this link](https://ide.bitquery.io/Latest-Radiyum-V4-pools-created_1). In the results, you can get pool and token details using instructions. ### Pool Address You can find the pool address using the following result: Note that the array index starts from 0. Therefore, it will be the 5th entry. Instructions -> Instruction -> Accounts[4] -> Address ### Token A You can get the 1st token address using the following result: Note that the array index starts from 0. Therefore, it will be the 9th entry. Instructions -> Instruction -> Accounts[8] -> Address ### Token B You can get the 2nd token address using the following result. Instructions -> Instruction -> Accounts[9] ->. Address You can run the following query at [Bitquery IDE](https://ide.bitquery.io/Latest-Radiyum-V4-pools-created_5).
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Method: { is: "initialize2" } Address: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } } } ) { Block { Time Date } Transaction { Signature } Instruction { AncestorIndexes CallerIndex Depth Data ExternalSeqNumber InternalSeqNumber Index Accounts { Address IsWritable Token { Mint Owner ProgramId } } CallPath Logs Program { AccountNames Method Json Name Arguments { Type Name Value { __typename ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ```
## Pair Creation time for a specific pair You can use the following query to get the pair creation time for a specific pair on Raydium DEX on Solana. But you need to use keyword `query` obviously. You can run this query using [this link](https://ide.bitquery.io/Specific-pair-creation-time-on-Raydium-Solana_1).
Click to expand GraphQL query ```{ Solana { Instructions( where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Method: {is: "initializeUserWithNonce"}, Address: {is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"}}, Accounts: {includes: {Address: {is: "CSyP9JXCVuVoobWrdtBqQeq7s7VWwNAJ7FFBhLnLFUCE"}}}}} ) { Block { Time } Transaction { Signature } } } } ```
## Get the historical Created pairs on any Solana DEX This query will return information about the historical created pairs according to the selected date frame. You can find the query [here](https://ide.bitquery.io/Solana-Raydium-New-Pairs_2)
Click to expand GraphQL query ```graphql query{ Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Raydium" } } } } limit: { count: 100 }) { Block { Date(minimum: Block_Date selectWhere: { since: "2024-10-01" till: "2024-11-01" }) } Trade { Dex { ProtocolFamily } Market{ MarketAddress } Currency { Symbol MintAddress } Side { Currency { Symbol MintAddress } } } } } } ```
## Latest price of a token You can use the following query to get the latest price of a token on Raydium DEX on Solana. You can run this query using [this link](https://ide.bitquery.io/live-price-of-token-on-raydium---updated).
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"}}, Currency: {MintAddress: {is: "token mint address"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ```
## Latest Trades on Solana Raydium DEX To subscribe to the real-time trades stream for Solana Raydium DEX, [try this GraphQL subscription (WebSocket)](https://ide.bitquery.io/Updated-Real-time-trades-on-Raydium-DEX-on-Solana_1).
Click to expand GraphQL query ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Account { Address } Amount Currency { MintAddress Decimals Symbol ProgramAddress Name } PriceAgaistSellCurrency: Price } Sell { Account { Address } Amount Currency { MintAddress Decimals Symbol Name } PriceAgaistBuyCurrency: Price } } Block { Time Height } Transaction { Signature FeePayer Signer } } } } ```
## Latest Trades for a specific currency on Solana Raydium DEX Let's say you want to receive [trades only for a specific currency on Raydium DEX](https://ide.bitquery.io/Updated-Real-time-buy-and-sell-of-specific-currency-on-Raydium-DEX-on-Solana_1). You can use the following stream. Use currency's mint address; for example, in the following query, we are using Ray token's Mint address to get buy and sells of Ray token. If you limit it to 1, you will get the latest price of the token because the latest trade = the Latest Price. Run this query [using this link](https://ide.bitquery.io/Updated-Real-time-buy-and-sell-of-specific-currency-on-Raydium-DEX-on-Solana_1).
Click to expand GraphQL query ```graphql subscription { Solana { Buyside: DEXTrades( where: { Trade: { Buy: { Currency: { MintAddress: { is: "token mint address" } } } Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistSellCurrency: Price } Sell { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistBuyCurrency: Price } } Block { Time Height } Transaction { Signature FeePayer Signer } } Sellside: DEXTrades( limit: { count: 10 } where: { Trade: { Sell: { Currency: { MintAddress: { is: "token mint address" } } } Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistSellCurrency: Price } Sell { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistBuyCurrency: Price } } Block { Time Height } Transaction { Signature FeePayer Signer } } } } ```
## Raydium OHLC API If you want to get OHLC data for any specific currency pair on Raydium DEX, you can use [this api](https://ide.bitquery.io/Raydium-OHLC-for-specific-pair_5). Only use this API as `query` and not `subscription` websocket as Aggregates and Time Intervals don't work well with subscriptions.
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } PriceAsymmetry: { lt: 0.1 } } } limit: { count: 10 } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ```
## Track Latest Add Liquidity Transactions on Raydium DEX You can also track Add Liquidity transactions in real time on Raydium DEX from Raydium API using instructions. Firstly, you can use this [query](https://ide.bitquery.io/Get-all-methods-of-Raydium-V4-Program#) to get all the methods of Raydium V4 program to deduce which program method is triggered for add liquidity transactions. The method we want to filter for turns out to be `setPositionStopLoss`. If you want to track latest liquidity additions in Raydium pools, you can use [this Websocket api](https://ide.bitquery.io/Track-Add-Liquidity-Transactions-on-Solana-Raydium-DEX). In the response, mint under 7th and 8th addresses in the Accounts array gives you the Token A and Token B respectively of the pool in which liquidity is added.
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } Method: { is: "setPositionStopLoss" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Block { Time } Instruction { Accounts { Address IsWritable Token { ProgramId Owner Mint } } AncestorIndexes BalanceUpdatesCount CallPath CallerIndex Data Depth Logs InternalSeqNumber Index ExternalSeqNumber Program { Address AccountNames Method Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ```
## Track Latest Remove Liquidity Transactions on Raydium DEX You can also track Remove Liquidity transactions in real time on Raydium DEX from Raydium API using instructions. Firstly, you can use this [query](https://ide.bitquery.io/Get-all-methods-of-Raydium-V4-Program#) to get all the methods of Raydium V4 program to deduce which program method is triggered for remove liquidity transactions. The method we want to filter for turns out to be `setPositionRangeStop`. If you want to track latest liquidity removals in Raydium pools, you can use [this Websocket api](https://ide.bitquery.io/Track-Remove-Liquidity-Transactions-on-Solana-Raydium-DEX#). In the response, mint under 7th and 8th addresses in the Accounts array gives you the Token A and Token B respectively of the pool in which liquidity is removed.
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } Method: { is: "setPositionRangeStop" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Block { Time } Instruction { Accounts { Address IsWritable Token { ProgramId Owner Mint } } AncestorIndexes BalanceUpdatesCount CallPath CallerIndex Data Depth Logs InternalSeqNumber Index ExternalSeqNumber Program { Address AccountNames Method Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ```
## Track Raydium DEXTrades enabled by OpenBook Protocol You can track Raydium DEXTrades which are enabled by OpenBook Protocol in real time on Raydium DEX from Raydium API using instructions. So OpenBook is an Order Book Protocol which Raydium has integrated in its constant product amm. If you want a full explaination of this API, watch our [Youtube Video](https://www.youtube.com/watch?v=aYARyvvItHA). If you want to track latest Raydium DEXTrades enabled by OpenBook order book Protocol, you can use [this Websocket api](https://ide.bitquery.io/Raydium-dextrades-through-OpenBook-order-book#).
Click to expand GraphQL query ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Raydium" } } } Instruction: { Accounts: { includes: { Address: { is: "srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX" } } } } } ) { Trade { Buy { Account { Address } Amount AmountInUSD Currency { MintAddress Symbol } Price PriceInUSD } Market { MarketAddress } Dex { ProtocolFamily ProtocolName ProgramAddress } Sell { Account { Address } Amount AmountInUSD Currency { MintAddress Symbol } Price PriceInUSD } } Transaction { Signature } } } } ```
## Video Tutorial | How to Track Latest Trades, Latest Price of a Token on Solana Raydium DEX ## Video Tutorial | How to Track Latest Created Liquidity Pools, OHLC data of a specific pair on Solana Raydium DEX ## Video Tutorial | How to Track Add Liquidity and Remove Liquidity Transactions on Raydium DEX ## Video Tutorial | How to track Raydium DEXTrades enabled by OpenBook Protocol using Bitquery API --- ## Raydium Launchpad API: LaunchLab Token Launches & Trades URL: https://docs.bitquery.io/docs/blockchain/Solana/launchpad-raydium/ Raydium Launchpad (LaunchLab) API on Solana: new token launches, bonding-curve trades and graduations via GraphQL, WebSocket and Kafka. Part of the Raydium DEX API. # Raydium Launchpad API :::tip Need real-time Raydium Launchpad data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Raydium Launchpad swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Raydium Launchpad data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section we see how to get data on Launchpad by Raydium. This includes token creation, latest trades by trader, for a token etc. You can also check out our [Pump Fun API Docs](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) and [LetsBonk.fun API Docs](/docs/blockchain/Solana/letsbonk-api/). These APIs can be provided through different streams including Kafka for zero latency requirements. Please contact us on telegram. ## Latest Pools Created on Launchpad We will use the `PoolCreateEvent` method to filter latest pools on Launchpad. The `Argument` filed includes more information about the pool like `base_mint_param`( token details), `curve_param`( bonding curve details) and `vesting_param` ( cliff period, amount locked etc). Token address is at the 7th entry in Accounts Array. You can run the query [here](https://ide.bitquery.io/Raydium-Launchpad-pool-creations_1)
Click to expand GraphQL query ```graphql subscription { Solana(network: solana) { Instructions( where: { Instruction: { Program: { Address: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } Method: { is: "initialize_v2" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signer Signature } Instruction { Accounts { Address } Program { Name Method AccountNames Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ```
## Get all the instructions of Raydium LaunchLab Below query will get you all the instructions that the Raydium LaunchLab Program has. You can test the API [here](https://ide.bitquery.io/all-the-instructions-of-Raydium-LaunchLab).
Click to expand GraphQL query ```graphql query MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}}}} ) { Instruction { Program { Method } } count } } } ```
## Track Token Migrations to Raydium DEX and Raydium CPMM in Realtime Using above `get all instructions` api, you will figure out that there are 2 instructions `migrate_to_amm`, `migrate_to_cpswap` whose invocations migrate the Raydium LaunchLab Token to Raydium V4 AMM and Raydium CPMM Dexs respectively. Thats why we have filtered for these 2 instructions in the below API, and tracking these. Test out the API [here](https://ide.bitquery.io/Track-Token-Migrations-to-Raydium-DEX-and-Raydium-CPMM-in-realtime).
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["migrate_to_amm","migrate_to_cpswap"]}}}, Transaction: {Result: {Success: true}}} ) { Block{ Time } Instruction { Program { Method AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } } Type Name } Name } Accounts { Address IsWritable Token { ProgramId Owner Mint } } } Transaction { Signature Signer } } } } ```
## Track Raydium Launchlab, Meteora DBC, Boop.fun, LetsBonk.fun and Moonshot Token Migrations in a single subscription Use this single subscription to stream real-time token migration events across Boop.fun, Raydium Launchlab, Meteora DBC, and Moonshot. It filters by the respective program IDs and migration methods, returning block time, program details, involved accounts, and transaction signatures as events occur. Try out the [API](https://ide.bitquery.io/Raydium-Launchlab-Meteora-DBC-BoopFun-Moonshot-LetsBonkfun-token-migrations-in-realtime_2) here on IDE.
Click to expand GraphQL query ```graphql subscription{ Solana { Instructions( where: {any: [{Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {is: "initialize_v2"}}}}, {Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "graduate"}}}}, {Instruction: {Program: {Address: {is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG"}, Method: {is: "migrateFunds"}}}}, {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["migrate_meteora_damm", "migration_damm_v2"]}}}}, {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["migrate_to_amm", "migrate_to_cpswap"]}}, Accounts: {includes: {Address: {is: "FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1"}}}}}], Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Launchlab # boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4 - boop.fun # MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG - Moonshot/Moonit # dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN - Meteora DBC # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Program Address and FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1(letsbonk.fun platform config addr) is present in Accounts array then its Letsbonk.fun migration Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method Name } } Transaction { Signature Signer } } } } ```
## Market cap (Trading API) Use **Trading** **`Pairs`** with **`Market.Protocol`** **`raydium_launchpad`** for aggregated **market cap**, **FDV**, **supply**, **price**, and **volume** on Solana launchpad pairs. Replace **`solana:`** in **`Token.Id`** with your token. ### Get latest market cap for a specific Raydium Launchpad token **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, **`Token.Id`** with **`includesCaseInsensitive`**, interval duration **> 1** second, **`Market.Protocol`** **`raydium_launchpad`**. Run the query [in the Bitquery IDE](https://ide.bitquery.io/specific-raydium-launchpad-token-latest-marketcap).
Click to expand GraphQL query ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { includesCaseInsensitive: "solana:7GMB7XbtTdvnHkPjH6yEwTUB3HYf5dqC3FKyr2sueMEh" } } Interval: { Time: { Duration: { gt: 1 } } } Market: { Protocol: { is: "raydium_launchpad" } } } ) { Token { Name Id Address Symbol } Block { Time } Market { Program Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ```
### Stream Raydium Launchpad tokens with market cap above $10K Subscribe when the token is on **Solana**, **`Market.Protocol`** is **`raydium_launchpad`**, **`Supply.MarketCap`** **> 10,000** (USD), and interval duration **> 1** second. Adjust **`gt`** to change the threshold. Run the subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-stream-raydium-launchpad-tokens-with-marketcap-above-10k-marketcap#).
Click to expand GraphQL subscription ```graphql subscription { Trading { Pairs( where: { Token: { Id: { includesCaseInsensitive: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 10000 } } Market: { Protocol: { is: "raydium_launchpad" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
## Bonding Curve Progress API Below query will give you the Bonding curve progress percentage of a specific Raydium Launchlab Token. ### Bonding Curve Progress Formula - **Formula**: BondingCurveProgress = 100 - ((leftTokens \* 100) / initialRealTokenReserves) Where: - leftTokens = realTokenReserves - reservedTokens - initialRealTokenReserves = totalSupply - reservedTokens - **Definitions**: - `initialRealTokenReserves` = `totalSupply` - `reservedTokens` - `totalSupply`: 1,000,000,000 (Raydium Launchlab Token) - `reservedTokens`: 206,900,000 - Therefore, `initialRealTokenReserves`: 793,100,000 - `leftTokens` = `realTokenReserves` - `reservedTokens` - `realTokenReserves`: Token balance at the market address. :::note **Simplified Formula**: BondingCurveProgress = 100 - (((balance - 206900000) \* 100) / 793100000) ::: ### Additional Notes - **Balance Retrieval**: - The `balance` is the token balance at the market address. - Use this query to fetch the balance and then we use `expressions` to calculate the bonding curve progress percentage in the query itself: [Query Link](https://ide.bitquery.io/bonding-curve-progress-percentage-of-a-letsbonkfun-token).
Click to expand GraphQL query ```graphql query GetBondingCurveProgressPercentage { Solana { DEXPools( limit: { count: 1 } orderBy: { descending: Block_Slot } where: { Pool: { Market: { BaseCurrency: { MintAddress: { is: "CctsjizSC6pwf2T8bhdHdZTEV4PEcfXoumjeK7FBbonk" } } } Dex: { ProgramAddress: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100-((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PriceInUSD PostAmountInUSD } Base { Balance: PostAmount } } } } } ```
## Track Raydium Launchlab Tokens above 95% Bonding Curve Progress in realtime We can use above Bonding Curve formulae and get the Balance of the Pool needed to get to 95% and 100% Bonding Curve Progress range. And then track liquidity changes which result in `Base{PostAmount}` to fall in this range. You can run and test the saved query [here](https://ide.bitquery.io/LetsBonkfun-Tokens-between-95-and-100-bonding-curve-progress_2).
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { DEXPools( where: { Pool: { Base: { PostAmount: { gt: "206900000", lt: "246555000" } } Dex: { ProgramAddress: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } } Market: { QuoteCurrency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" ] } } } } Transaction: { Result: { Success: true } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { BaseCurrency { MintAddress Name Symbol } MarketAddress QuoteCurrency { MintAddress Name Symbol } } Dex { ProtocolName ProtocolFamily } Base { Balance: PostAmount } Quote { PostAmount PriceInUSD PostAmountInUSD } } } } } ```
## Top 100 About to Graduate Raydium Launchlab Tokens We can use below query to get top 100 About to Graduate Raydium Launchlab Tokens. You can run and test the saved query [here](https://ide.bitquery.io/Top-100-graduating-raydium-launchlab-tokens-in-last-5-minutes).
Click to expand GraphQL query ```graphql { Solana { DEXPools( limitBy: { by: Pool_Market_BaseCurrency_MintAddress, count: 1 } limit: { count: 100 } orderBy: { ascending: Pool_Base_PostAmount } where: { Pool: { Base: { PostAmount: { gt: "206900000" } } Dex: { ProgramAddress: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } } Market: { QuoteCurrency: { MintAddress: { in: [ "11111111111111111111111111111111" "So11111111111111111111111111111111111111112" ] } } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) { Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($Pool_Base_Balance - 206900000) * 100) / 793100000)" ) Pool { Market { BaseCurrency { MintAddress Name Symbol } MarketAddress QuoteCurrency { MintAddress Name Symbol } } Dex { ProtocolName ProtocolFamily } Base { Balance: PostAmount(maximum: Block_Time) } Quote { PostAmount PriceInUSD PostAmountInUSD } } } } } ```
## Latest Trades on Launchpad This query fetches the most recent trades on the Raydium Launchpad. You can run the query [here](https://ide.bitquery.io/Latest-Trades-on-Launchpad)
Click to expand GraphQL query ```graphql query LatestTrades { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } } } ) { Block { Time } Transaction { Signature } Trade { Market { MarketAddress } Dex { ProtocolName ProtocolFamily } AmountInUSD PriceInUSD Amount Currency { Name } Side { Type Currency { Symbol MintAddress Name } AmountInUSD Amount } } } } } ```
Similarly, you can subscribe to trades on launchpad in real-time using [subscription query](https://ide.bitquery.io/Subscribe-to-Trades-on-Launchpad). The same can be tracked using [Bitquery Kafka Streams](/docs/streams/kafka-streaming-concepts/) ## Latest Price of a Token on Launchpad This query provides the most recent price data for a specific token launched on Raydium Launchpad. You can filter by the token’s `MintAddress`, and the query will return the last recorded trade price. You can run the query [here](https://ide.bitquery.io/Latest-Price-of-a-Token-on-Launchpad)
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limit: { count: 1 } where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token mint address" } } } } ) { Block { Time } Transaction { Signature } Trade { Market { MarketAddress } Dex { ProtocolName ProtocolFamily } AmountInUSD PriceInUSD Amount Currency { Name } Side { Type Currency { Symbol MintAddress Name } AmountInUSD Amount } } } } } ```
## Latest Trades of an User on Launchpad [This](https://ide.bitquery.io/trades-by-user-on-launchpad_1) query returns the latest trades by a user on Launchpad by filtering on the basis of `Transaction_Signer`. [This](https://ide.bitquery.io/trades-by-user-on-launchpad-stream) stream of data allows to monitor the trade activities of the user on Launchpad in real time.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } } Transaction: { Signer: { is: "8KjdBwz6Q3EYUDYmqfg33em3p9GFcP48v3ghJmw2KDNe" } } } orderBy: { descending: Block_Time } limit: { count: 100 } ) { Trade { Currency { MintAddress Name Symbol } Market { MarketAddress } usd_price: PriceInUSD sol_price: Price Side { Currency { Symbol Name MintAddress } Type } } } } } ```
## Top Buyers of a Token on LaunchPad [This](https://ide.bitquery.io/top-buyers-of-a-token-on-launchpad) API endpoint returns the top 100 buyers for a token, which is `8CgTj1bVFPVFN9AgY47ZfXkMZDRwXawQ2vckp1ziqray` in this case.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token mint address" } } Side: { Type: { is: buy } } } } orderBy: { descendingByField: "buy_volume" } limit: { count: 100 } ) { Trade { Currency { MintAddress Name Symbol } } Transaction { Signer } buy_volume: sum(of: Trade_Side_AmountInUSD) } } } ```
## Top Sellers of a Token on LaunchPad Using [this](https://ide.bitquery.io/top-sellers-of-a-token-on-launchpad_1) query top 100 sellers for the token with `Mint Address` as `8CgTj1bVFPVFN9AgY47ZfXkMZDRwXawQ2vckp1ziqray` could be retrieved.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token mint address" } } Side: { Type: { is: sell } } } } orderBy: { descendingByField: "sell_volume" } limit: { count: 100 } ) { Trade { Currency { MintAddress Name Symbol } } Transaction { Signer } sell_volume: sum(of: Trade_Side_AmountInUSD) } } } ```
## OHLCV for LaunchPad Tokens [This](https://ide.bitquery.io/ohlc-for-launchpad-token) API end point returns the OHLCV vlaues for a LaunchPad token with the currency `mint address` as `72j7mBkX54KNH7djeJ2mUz5L8VoDToPbSQTd24Sdhray` when traded against WSOL.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token mint address" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } Transaction: { Result: { Success: true } } } limit: { count: 100 } orderBy: { descendingByField: "Block_Timefield" } ) { Block { Timefield: Time(interval: { count: 1, in: minutes }) } Trade { open: Price(minimum: Block_Slot) high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) close: Price(maximum: Block_Slot) } volumeInUSD: sum(of: Trade_Side_AmountInUSD) count } } } ```
## Get Liquidity Pool Address for a LaunchPad Token [This](https://ide.bitquery.io/pool-address-for-launchpad-token) query returns the pair address for the LaunchPad token with `mint address` as `72j7mBkX54KNH7djeJ2mUz5L8VoDToPbSQTd24Sdhray` on the LaunchPad exchange. The liquidity pool address is denoted by `MarketAddress`.
Click to expand GraphQL query ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolName: { is: "raydium_launchpad" } } Currency: { MintAddress: { is: "token mint address" } } } } ) { Trade { Market { MarketAddress } Currency { Name Symbol MintAddress } Side { Currency { Name Symbol MintAddress } } } count } } } ```
## Get Liquidity for a LaunchPad Token Pair Address Using [this](https://ide.bitquery.io/liquidity-for-a-launchpad-token-pair) query we can get the liquidity for a LaunchPad Token Pair, where `Base_PostBalance` is the amount of LaunchPad tokens present in the pool and `Quote_PostBalance` is the amount of WSOL present in the pool. For the purpose of filtering we are applying the condition that the `MarketAddress` is `H5875KoMLaWAovsjjXuTtHZv9otmH7EgJ2nXMovykZvp`.
Click to expand GraphQL query ```graphql { Solana { DEXPools( where: { Pool: { Market: { MarketAddress: { is: "H5875KoMLaWAovsjjXuTtHZv9otmH7EgJ2nXMovykZvp" } } } Transaction: { Result: { Success: true } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Pool { Base { PostAmount } Quote { PostAmount } Market { BaseCurrency { MintAddress Name Symbol } QuoteCurrency { MintAddress Name Symbol } } } } } } ```
[This](https://ide.bitquery.io/liquidity-for-a-launchpad-token-pair-stream) subscription could be utilised to monitor updates in liquidity pools in real time. ## Video Tutorial | How to track Raydium LaunchPad Token Migrations to Raydium V4 and Raydium CPMM Dex ## Video Tutorial | How to Track Raydium Launchpad Newly Launched Tokens in Realtime ## Video Tutorial | How to track Dex Trades of a Traders on Raydium LaunchPad in Realtime ## Video Tutorial | How to get OHLCV of a token on Raydium LaunchLab ## Video Tutorial | How to get Top Buyers and Sellers of a Raydium LaunchLab Token --- ## Real Time Indexer With Kafka Stream URL: https://docs.bitquery.io/docs/streams/real-time-indexer-with-kafka-stream/ Real Time Indexer With Kafka Stream with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. # Real-Time Blockchain Indexer: Build Reliable Indexers with Kafka Streams Instead of Archive Nodes, gRPC, or Webhook Services Building a real-time blockchain indexer is one of the most challenging infrastructure tasks in the process of tracking trades, monitoring token transfers, parsing internal calls, or building a comprehensive on-chain analytics platform. If you decide to run your own archive node, you need to plan for big SSD storage (multiple TBs), fast disks / high IOPS, and robust backup/monitoring. If not, you might be looking for need reliable, low-latency access to blockchain data at scale. We know about popular approaches like running your own archive nodes, setting up gRPC indexers with Geyser plugins (for Solana), using webhook-based services like Helius, relying on third-party RPC providers, or using graph-based indexers. **So why do we need another option?** ## The Challenge of Blockchain Indexing Blockchain indexing requires processing massive volumes of data in real-time. Whether you're building a custom indexer for transaction traces, internal transactions, or on-chain data extraction, consider these requirements: - **High Throughput**: Ethereum processes thousands of transactions per block, while Solana can handle hundreds of thousands per second - **Zero Data Loss**: Missing a single transaction can break your indexer's consistency - **Low Latency**: For trading bots, MEV applications, and real-time dashboards, every millisecond counts - **Data Completeness**: You need both raw blockchain data and enriched, decoded information—including internal transactions that don't emit events - **Reliability**: Your indexer must handle network issues, node failures, and data gaps gracefully - **Historical Backfilling**: You need to process historical blocks while maintaining live subscription to new blocks Traditional indexing approaches struggle with these requirements: ### The Archive Node Management Problem **What is an Archive Node?** An archive node requires enabling all historical state data: - `--pruning=archive`: Maintains all states in the state-trie (not just recent blocks) - `--fat-db=on`: Roughly doubles storage by storing additional information to enumerate all accounts and storage keys - `--tracing=on`: Enables transaction tracing by default for EVM traces This trades massive disk space for expensive computation—essentially a full node with a "super heavy cache" enabled. **The Infrastructure Reality** - Storage size growth is massive: Running an archive node often requires many terabytes (for Ethereum, often > 10 TB), which grows over time. - Disk performance / IOPS bottlenecks: As chain history grows, read/write performance becomes critical; archive nodes tend to be much slower unless powerful SSDs or optimized storage are used. - Synchronization time is huge / resource-intensive: Bootstrapping (full sync) can take days or weeks; replaying chain history is compute-heavy. - Maintenance overhead & cost: Archive nodes often require dedicated hardware, monitoring, careful storage planning. This makes them costly and hard to manage for small teams or projects. - Operational complexity / configuration risk: Proper config (e.g. pruning/“gcmode=archive”, snapshot management, backups, disk planning) is necessary — misconfig can lead to data loss or unusable node. **The Bottom Line** Running an archive node is not a matter of hours or days—it's a matter of **weeks** even with enterprise hardware. The infrastructure requirements are substantial: - **Storage**: Nearly 2TB of fast SSD storage (and growing) - **Time**: Weeks of continuous syncing - **Performance**: Degrades significantly as the database grows - **Maintenance**: Constant monitoring and intervention required Bitquery Kafka streams eliminate all of these challenges by providing pre-synced, maintained archive node data through a managed streaming service. ### gRPC Indexers and Webhook-Based Services Limitations Relying on gRPC indexers (like Solana's Geyser plugin approach), webhook-based services (like Helius), or third-party RPC providers introduces different problems that Bitquery Kafka streams solve: - **gRPC Complexity**: Setting up gRPC indexers requires running validators with plugins (like Geyser for Solana), which is resource-intensive and complex—Bitquery Kafka eliminates this need - **Webhook Reliability**: Webhook-based services can miss events during downtime, have delivery failures, and lack replay capabilities—Bitquery Kafka's retention solves this - **Rate Limiting**: Most providers enforce strict rate limits that can throttle your indexing speed—Bitquery Kafka has no rate limits - **Bandwidth Costs**: Many providers charge based on data transfer, making high-volume indexing expensive—Bitquery Kafka offers predictable pricing without bandwidth charges - **Reliability Issues**: RPC endpoints, gRPC streams, and webhooks can go down, rate-limit you, or provide inconsistent data—Bitquery Kafka provides enterprise-grade reliability - **Data Gaps**: If your indexer crashes or loses connection, you may miss transactions with no way to replay—Bitquery Kafka's 24-hour retention allows you to replay missed data - **Transaction Trace Limitations**: Many services don't provide full transaction traces or internal transaction data—Bitquery Kafka includes comprehensive transaction data ## Why Bitquery Kafka Streams Excel for Blockchain Indexing Bitquery's Kafka streams are designed as an alternative to running your own archive nodes, setting up gRPC indexers, using webhook-based services, or relying on RPC providers for blockchain indexing. Unlike traditional indexing approaches (self-hosted indexers, archive node-based indexing, gRPC indexers with Geyser plugins, or webhook services), Bitquery's Kafka streams provide several critical advantages: ### 1. Built-in Data Retention and Replay **Bitquery Kafka streams' retention mechanism is a game-changer for blockchain indexing.** Unlike RPC providers or WebSocket subscriptions that lose data on disconnect, Bitquery's Kafka streams retain messages for 24 hours. This means: - **No Data Loss**: If your indexer crashes or needs to restart, you can resume from where you left off - **Gap Recovery**: You can replay messages from any point within the retention window - **Testing and Debugging**: You can reprocess historical data to test your indexing logic - **Checkpoint Management**: Bitquery's Kafka consumer groups track your position, ensuring you never miss a message This retention capability is especially valuable when: - Your indexer needs maintenance or updates - You discover a bug and need to reprocess data - Network issues cause temporary disconnections - You want to test new indexing logic against recent historical data ### 2. More Data Than Raw Nodes or Archive Nodes **Bitquery's Kafka streams provide more enriched data than raw blockchain nodes or archive nodes.** Raw nodes and archive nodes give you basic transaction data, but Bitquery's streams include: - **Decoded Data**: Smart contract calls are already decoded using ABI information - **Transaction Traces**: Full transaction traces and internal transaction data without needing debug_traceBlockByNumber - **Enriched Metadata**: Token names, symbols, decimals, and USD values are included - **Protocol-Specific Parsing**: DEX trades, real-time balances, liquidity pool changes, and protocol events are pre-parsed - **Internal Transactions**: Native ETH transfers and internal calls that don't emit events are included - **Cross-Chain Consistency**: Same data structure across all supported blockchains - **Both Raw and Decoded**: Access to both raw blockchain data and enriched, structured formats This means you spend less time on block parsing, transaction trace extraction, and data processing, and more time building features. Instead of: 1. Fetching raw transaction data from archive nodes 2. Decoding function calls and parsing calldata 3. Parsing event logs 4. Extracting internal transactions that don't emit events 5. Looking up token metadata 6. Calculating USD values 7. Building historical backfilling pipelines You receive all of this pre-processed and ready to use in a unified data feed. ### 3. Zero Infrastructure Management **You don't need to manage any nodes or infrastructure.** With Bitquery's Kafka streams: - **No Archive Node Setup**: No need to sync, maintain, or upgrade archive nodes (which require significantly more resources than full nodes) - **No gRPC Indexer Configuration**: No need to set up Geyser plugins or validator-level indexing for Solana - **No Webhook Infrastructure**: No need to build webhook endpoints or handle webhook delivery failures - **No Bandwidth Management**: All data transfer happens through Bitquery Kafka, with no per-request bandwidth limits - **No Scaling Headaches**: Bitquery Kafka handles the scaling automatically - **No Maintenance Windows**: Bitquery manages uptime, redundancy, and failover This is particularly important for indexing because: - **Bandwidth Efficiency**: Traditional RPC-based indexing can consume massive bandwidth. With Bitquery Kafka, you consume data once and process it efficiently - **Cost Predictability**: Direct Kafka access pricing means no surprise bandwidth bills - **Focus on Logic**: Spend your time building indexing logic, not managing infrastructure ### 4. Enterprise-Grade Reliability **Bitquery's Kafka infrastructure is built for mission-critical blockchain indexing.** Unlike RPC providers that can go down or rate-limit you, Bitquery's Kafka streams provide: - **At-Least-Once Delivery**: Guarantees that every message is delivered at least once - **Automatic Failover**: If one broker fails, others take over seamlessly - **Consumer Groups**: Multiple consumers can share the load, with automatic rebalancing - **Partitioning**: Data is distributed across partitions for parallel processing For blockchain indexing, this means: - **No Lost Transactions**: Even if your consumer crashes, messages are retained and can be replayed - **Horizontal Scaling**: Add more consumer instances to process data faster - **Fault Tolerance**: Your indexing system can survive individual component failures ### 5. Direct Access, No Limitations **Bitquery's Kafka pricing model is designed for high-volume indexing.** - **No Bandwidth Limits**: Consume as much data as you need without worrying about rate limits - **No Request Limits**: Unlike RPC providers, there are no per-second request caps - **Predictable Pricing**: Direct Kafka access means predictable costs, not variable bandwidth charges - **High Throughput**: Process millions of transactions per day without throttling This is crucial for indexing because: - **Full Chain Coverage**: Index every transaction, not just a sample - **Real-Time Processing**: Keep up with blockchain transaction rates - **No Throttling**: Process data at your own pace without artificial limits ### 6. Both Raw and Decoded Data **Access to both raw blockchain data and enriched, decoded formats.** Bitquery provides: - **Raw Data Streams**: Access to raw blocks, transactions, and logs for custom processing - **Decoded Data Streams**: Pre-parsed transactions with decoded function calls and events - **Protocol-Specific Topics**: Separate topics for DEX trades, token transfers, and transactions - **Flexible Consumption**: Choose the level of data processing that fits your needs This flexibility allows you to: - **Start Simple**: Use decoded data for quick prototyping - **Go Deep**: Switch to raw data when you need custom parsing - **Mix and Match**: Use different topics for different parts of your indexer Build robust indexing pipelines that: - Never lose data (thanks to retention) - Can replay and reprocess (for data quality) - Handle historical backfilling while maintaining live subscription - Scale horizontally (with consumer groups) - Extract on-chain data without running archive nodes ## Getting Started with Bitquery Kafka-Based Indexing Building a real-time indexer with Bitquery's Kafka streams is straightforward: 1. **Get Kafka Access**: Contact Bitquery sales by filling the [form on the website](https://bitquery.io/forms/api) for Kafka credentials 2. **Choose Your Topics**: Select the topics that match your indexing needs. List is available [here](/docs/streams/kafka-streaming-concepts/#complete-list-of-topics) 3. **Set Up Consumers**: Create Kafka consumers with proper offset management 4. **Process Messages**: Parse protobuf messages and update your index 5. **Handle Failures**: Use Bitquery Kafka's 24-hour retention to recover from crashes ## Tutorial Tidbits: Building Real-Time Indexers with Bitquery Kafka ### Why Bitquery Kafka is Ideal for Blockchain Indexing Bitquery Kafka streams provide several advantages over archive node-based indexing, gRPC indexers, webhook-based services, or RPC-based indexing that make them perfect for building real-time blockchain indexers: **1. Data Retention for Reliability** - Bitquery Kafka streams retain messages for **24 hours**, allowing you to recover from crashes or restarts - If your indexer goes down, you can resume from the last processed offset - Unlike RPC providers, you don't need to worry about missing transactions during downtime **2. More Data Than Raw Nodes or Archive Nodes** - Bitquery's Kafka streams include **decoded smart contract calls** and **enriched metadata** - **Transaction traces and internal transactions** included without needing debug_traceBlockByNumber - Pre-parsed DEX trades, token transfers, and protocol events - Both **raw and decoded data** available in separate topics - USD values and token metadata included automatically - Native ETH transfers and internal calls that don't emit events are captured **3. Zero Infrastructure Management** - **No archive node setup required**: Bitquery manages all blockchain nodes (including archive nodes) - **No gRPC indexer configuration**: No need for Geyser plugins or validator-level indexing - **No webhook infrastructure**: No webhook endpoints or delivery handling needed - **No bandwidth limits**: Direct Kafka access means no per-request throttling - **No scaling headaches**: Kafka handles horizontal scaling automatically - Focus on your indexing logic and on-chain data extraction, not infrastructure maintenance **4. Cost-Effective for High-Volume Indexing** - **Predictable pricing**: Direct Kafka access, not variable bandwidth charges - **No rate limits**: Process millions of transactions per day without throttling - **Efficient consumption**: Consume data once and process it multiple times if needed **5. Enterprise-Grade Reliability** - **At-least-once delivery**: Guarantees no message loss - **Automatic failover**: Seamless handling of broker failures - **Consumer groups**: Share load across multiple indexer instances ### Quick Tips for Indexer Development **Handling Duplicates:** - Messages may have duplicates in Kafka topics - Implement idempotent processing: track processed transaction hashes - Use a fast lookup store to check if already processed **Recovery After Crashes:** - Bitquery Kafka's retention window (24 hours) allows you to replay recent data - Store your processing state aka message offset and partition details. - On restart, you can seek to a specific offset if needed - This is a major advantage over RPC providers, gRPC indexers, and webhook-based services, which don't offer replay capabilities **Choosing the Right Topic:** - Use `*.transactions.proto` for comprehensive transaction indexing - Use `*.dextrades.proto` for DEX-specific indexing (faster, less data) - Use `*.tokens.proto` for token transfer indexing - Use `*.broadcasted.*` topics for mempool-level data (lower latency) --- ## Real Time Solana Data URL: https://docs.bitquery.io/docs/streams/real-time-solana-data/ Real Time Solana Data with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. See examples in the Bitquery IDE. # The Need for Real-Time Data on Solana: Latency, Scale, and Fidelity at Stake > “Better be first 99 percent of the time than second 100 percent of the time.” > — Donald MacKenzie, in his book _Trading at the Speed of Light_ Solana’s ultra-fast block times have created new possibilities for real-time blockchain apps, especially in trading, payments, and gaming. Today, Solana handles around $25 billion in daily spot trading volume, surpassing even Binance, the largest centralised exchange, which does about $15 billion in daily spot volume. Solana is leading the way in building a fast, scalable trading system on the blockchain. In the future, this won’t just be for crypto—it will make it possible to trade stocks, bonds, forex, commodities, and other assets all on-chain. Building this kind of trading system requires advanced infrastructure, similar to what Nasdaq and other global exchanges use, and Low latency is an absolute necessity. To succeed, developers need reliable access to real-time, low-latency on-chain data. In this article, we’ll discuss the main ways to access ultra-low-latency data on Solana to support these applications at scale. Our focus here is on reading blockchain data; we’ll cover trade execution in a future article. Because Solana’s validators are spread around the world, not in a single location, it’s challenging to deliver real-time information efficiently. Optimizing networks to relay blockchain data quickly is essential for many applications. Let’s look at the different approaches to accessing real-time data on Solana, one by one. ## The Traditional Path: Solana Geyser Plugin Solana offers the Geyser plugin system for developers needing direct access to on-chain events: - **Update_account**: Triggered on account updates - **Update_slot_status**: Slot status changes - **Notify_transaction**: Processed transactions - **Notify_block_metadata**: Block metadata **Yellowstone Geyser Plugin** adds a gRPC API for subscribing to updates, getting blockhashes, slot numbers, and more. ### What are the challenges? While powerful, Geyser requires running your own Solana node or validator. This means ongoing infrastructure management, manual scaling, node security, and raw data parsing tasks that can slow down even the best teams. Filtering options are basic, so you may process much more data than you need, driving up costs and complexity. People are asking questions on Stack Exchange about custom filtering options in Geyser, which Bitquery provides with just too much ease. **[Ref 1:](https://solana.stackexchange.com/questions/9779/geyser-support-for-events)** ![Stack Exchange question on Geyser Filtering - 1](/img/streams/question-1-streams.png) **[Ref 2:](https://solana.stackexchange.com/questions/18663/how-to-filter-raydium-pool-with-geyser)** ![Stack Exchange question on Geyser Filtering - 2](/img/streams/question-2-streams.png) ## Bitquery: A Powerful Alternative Bitquery offers a powerful real-time streaming system with three interfaces: **GraphQL Subscriptions**, **Kafka**, and **gRPC (CoreCast)**. You can learn more about the differences and benefits of each in the [Bitquery documentation](/docs/streams/kafka-streaming-concepts/). For ultra-low-latency gRPC streams (DEX trades, transfers, transactions), see [Solana gRPC Streams (CoreCast) →](/docs/grpc/solana/introduction/). - **No Infra Needed**: You don’t need to run your own Solana node. Just use the Bitquery endpoint—no server costs, setup, or upgrades. - **Powerful Filtering**: Use GraphQL’s expressive filters to get only the data you need (by address, token, program, amount, and more). No more sifting through irrelevant noise. - **Pre-Parsed Data**: All data is already structured, labelled, and enriched (including USD values for tokens/trades). You save time and can focus on building features, not parsing raw logs. - **Supports All Major DEXs**: Instantly access DEX trades from PumpFun, Raydium, Orca, and more, with no extra parsing. - **Historical + Real-Time**: Query past data and stream new events using the same API. - **Managed Reliability**: Bitquery handles uptime, redundancy, and failover—no late-night pages for you. - **Easy Onboarding**: Get started in minutes, not weeks. ## Bitquery GraphQL Streams (with Powerful Filtering) Bitquery’s GraphQL subscriptions give you real-time access with less than 2-second latency. Queries are rich and filterable, allowing you to stream only what you need, down to addresses, programs, or amounts. You can test these queries live on the [Bitquery IDE](https://ide.bitquery.io/). ### Popular Bitquery GraphQL Streams: - **Transfers**: Real-time token transfers (fungible and NFTs), filterable by address, amount, or specific programs. - **Balance Updates**: Monitor wallet balances as they change, and see which programs trigger changes. - **DEXTrades & DEXTradeByTokens**: Full trade history, OHLCV (K-line) data, trader stats, and DEX analytics—covering all major DEXs. - **DEXPools**: Track liquidity adds, removes, and pool analytics in real time. - **Instructions**: Stream parsed Solana program instructions—great for custom app monitoring and token launches. - **Rewards**: Follow staking rewards live as they are distributed. - **TokenSupplyUpdates**: Watch minting, burning, and supply changes in real time. - **Transactions**: Get a live feed of all transactions on Solana. - **Blocks**: Stream every new block as it’s produced. ### Custom Stream Filtering Create targeted data streams for specific use cases: - [Monitor 100 specific wallet addresses](/docs/usecases/monitoring-solana-at-scale-managing-hundreds-of-addresses/) for whale tracking and large transaction alerts - Custom token streams filtering by specific programs, amounts, or trading pairs. For eg: [track newly created pump fun tokens](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-newly-created-pumpfun-tokens) - Focus processing power only on relevant data, reducing costs and complexity ## Kafka Stream by Bitquery Bitquery’s Kafka streams are a unique product that provides ultra-low latency data directly from blockchain. Here are some key features. **[Bitquery offers three main Kafka streams](/docs/streams/protobuf/chains/Solana-protobuf/)**: - `solana.dextrades.proto` — Includes all trade and liquidity pool change data. - `solana.tokens.proto` — Covers token transfers, supply changes, and balance updates at both the account and instruction level. - `solana.transactions.proto` — Delivers detailed data for blocks, transactions, and instructions. ## Feature Comparison Table | Feature | Geyser Plugin | Bitquery GraphQL Subscriptions | Bitquery Kafka Stream | | ---------------------------- | -------------------------------------- | ------------------------------------------ | ------------------------------------------- | | **Node/Infra Required** | Yes (self-managed node) | No (cloud-managed by Bitquery) | No (cloud-managed by Bitquery) | | **Setup Time** | High (node setup, sync, maintain) | Very Low (register & query) | Low (register, integrate Kafka client) | | **Data Format** | Raw, binary, or gRPC | Structured, JSON (GraphQL) | Structured, Protocol Buffers | | **Filtering** | Limited (basic filters) | Advanced (GraphQL-level filtering) | By stream/topic and schema | | **Data Coverage** | Raw on-chain data | All Onchain data parsed (DEX, pools, etc.) | All Onchain data parsed (DEX, pools, etc.) | | **Unconfirmed Transactions** | Limited | Yes | Yes (unconfirmed) | | **Historical Data** | No | Yes (queryable) | No (stream only) | | **Latency** | Low (depends on your infra) | <2s (cloud-optimized) | Sub-second, ultra-low latency | | **Scalability** | You must scale/monitor infra | Scales automatically (SaaS) | Enterprise-grade, scales automatically | | **Maintenance** | High (updates, patches, uptime) | None (managed by Bitquery) | None (managed by Bitquery) | | **Data Parsing** | Developer must parse raw data | Pre-parsed & enriched (USD values, etc.) | Pre-parsed & enriched | | **DEX/Protocol Support** | Needs custom parsing per DEX/protocol | Supported out-of-the-box | Supported out-of-the-box | | **Reliability/Failover** | Developer’s responsibility | Managed by Bitquery | Kafka’s built-in resilience + Bitquery | | **Best Use Cases** | Deep custom infra, full control needed | Fast prototyping, dashboards, bots | HFT, enterprise, large-scale real-time apps | ### Some Differentiators - Geyser provides an entry notification stream for tracking ledger entries in real time. - Bitquery Streams work directly with unconfirmed transactions and do not offer a separate entry notification stream. - Because Bitquery focuses on unconfirmed transactions, it can deliver block data before blocks are closed, often faster than other solutions. - Bitquery Streams include: Real-time instruction and log parsing, and Instruction-level balance updates (showing balance changes from each instruction). Even Geyser does not provide instruction-level balance updates natively. ## Key Advantages of Subscriptions and Kafka for Solana Applications ### Ultra-Low Latency & Real-Time Processing Kafka streams deliver sub-second latency, crucial for high-frequency trading where Solana processes $25+ billion in daily volume. Access to unconfirmed transactions provides early market signals before block finalization. Latency goes to as low as 4–5ms. ![Kafka Latency Go test results](/img/streams/kafka-latency-go-test.png) ### Enterprise Scalability Kafka's distributed architecture handles massive throughput with built-in replication and automatic failover. Scale from thousands to millions of transactions per second without infrastructure management. Read this tutorial on [how to use Bitquery’s Kafka Streams to monitor millions of Solana wallet balances](/docs/usecases/track-millions-of-solana-wallets/). Also, check out how you can [track withdrawals and deposits for 1000s of Binance exchange wallets](/docs/usecases/binance-exchange-wallet-monitoring/). ### Development Efficiency Pre-parsed, enriched data with USD values and protocol information eliminates complex parsing work. Zero node management means faster time-to-market for trading systems and DeFi applications. ## Conclusion If you’re building on Solana, Bitquery’s streaming solutions are built for developers who demand more—less setup, more speed, and richer data out of the box. With Bitquery GraphQL Subscriptions, you get clean, filtered, and pre-parsed blockchain data in minutes, while Kafka Streams give you ultra-low latency and enterprise-grade scalability for the most demanding real-time apps. Curious to see what next-gen blockchain data feels like? Try Bitquery Streams and experience the technical difference for yourself. Your next Solana project just got a whole lot easier. --- ## Real-Time Blockchain Data Streaming URL: https://docs.bitquery.io/docs/streams/ Compare Bitquery WebSocket, Kafka, and gRPC streams for latency, filtering, reliability, and crypto trading use cases. See examples in the Bitquery IDE. # Real-time Blockchain Data Streaming API | Bitquery Platform Bitquery provides powerful **real-time blockchain data streaming** capabilities through three distinct technologies, each optimized for different use cases and requirements. Whether you're building a **cryptocurrency trading bot**, **DeFi trading terminal**, **DEX pool monitoring** system, or **token sniping** application, we have the right **blockchain data streaming solution** for your needs. ## Quick Navigation | Technology | Latency | Best For | Learn More | |------------|---------|----------|------------| | **[WebSocket](#websocket-graphql-subscriptions)** | ~1 second | Beginners, Web Apps, Complex Filtering | [WebSocket Docs](/docs/subscriptions/websockets/) | | **[Kafka](#kafka-streams)** | < 500ms | Enterprise, High-Volume, Trading Bots | [Kafka Concepts](/docs/streams/kafka-streaming-concepts/) | | **[CoreCast](#corecast-grpc-streams)** | < 300ms | Solana, Ultra-Low Latency, MEV | [gRPC Docs](/docs/grpc/solana/introduction/) | ## Blockchain Data Streaming Technologies Overview ### Real-time GraphQL Subscriptions (WebSocket API) {#websocket-graphql-subscriptions} **Multichain Support** | **Live Data** | **Beginner-friendly** Our **WebSocket-based GraphQL subscriptions** provide **real-time cryptocurrency data** with very high filtering and formatting capabilities. You can filter by wallet addresses, token contracts, transaction amounts, USD values, and much more directly in your queries. Perfect for **crypto trading applications**, **DeFi dashboards**, and **blockchain analytics platforms**. - **Endpoint**: `wss://streaming.bitquery.io/graphql` - **Protocols**: `graphql-transport-ws`, `graphql-ws` - **Latency**: ~1 second (network + parsing overhead) - **Use Cases**: **Crypto trading dashboards**, **DeFi interfaces**, **real-time portfolio monitoring** > Streaming live **token trades or prices**? Subscribe to the [Trading API](/docs/trading/trading-data-overview/) cubes (`Trading.Trades`, `Trading.Tokens`, `Trading.Pairs`) rather than raw per-chain `DEXTrades` — one stream covers 10 chains with USD prices, market cap, and MEV-filtered trades built in. ### High-Performance Kafka Blockchain Streams {#kafka-streams} **Multichain Support** | **Ultra-low latency** | **High throughput** High-performance, **low-latency blockchain data streaming** for mission-critical **cryptocurrency trading systems** requiring maximum reliability and scalability. **No server-side filtering available** – you receive complete blockchain transaction data and must filter on the client side. Ideal for **MEV bots**, **arbitrage trading systems**, and **high-frequency DeFi applications** that need complete data streams. - **Endpoints**: `rpk0.bitquery.io:9092`, `rpk1.bitquery.io:9092`, `rpk2.bitquery.io:9092` - **Protocol**: Apache Kafka with SASL authentication - **Latency**: < 500ms (sub-second) - **Use Cases**: **[Cryptocurrency trading bots](/docs/streams/sniper-trade-using-bitquery-kafka-stream/)**, **real-time DeFi applications**, **MEV bot development**, **high-frequency blockchain monitoring** ### Ultra-fast gRPC Streams (CoreCast) {#corecast-grpc-streams} **Solana Blockchain** | **Sub-100ms latency** | **Smart filtering** Our newest **ultra-low latency streaming technology** provides the fastest **Solana blockchain data** with server-side filtering capabilities and efficient binary serialization. Perfect for **Solana trading bots** and **MEV applications**. Filtering is available but more limited compared to WebSocket's extensive filtering options. - **Endpoint**: `corecast.bitquery.io` - **Protocol**: gRPC with Protobuf - **Latency**: < 500ms (low latency) - **Use Cases**: **Solana trading bots**, **Solana MEV applications**, **real-time Solana DeFi protocols**, **Jupiter aggregator monitoring** ## Feature Comparison | Feature / Stream | WebSocket | Kafka | CoreCast (Smart gRPC) | |------------------|-----------|-------|----------------------| | **Latency** | ~1 second (network + parsing overhead) | < 500 ms (sub-second) | < 500ms ms (low latency) | | **Filtering** | ✅ Very high capability: addresses, tokens, pools, value thresholds, USD values, complex conditions | ❌ No filtering - complete data stream | ✅ Basic filtering: addresses, tokens, pools, thresholds (limited compared to WebSocket) | | **USD Values** | ✅ Built-in | ❌ Not available (Available in different topic) | ❌ Not available (planned) | | **Reliability** | Auto-reconnect via GraphQL, but no replay | ✅ Retention available, replay from checkpoints | Query GraphQL, no replay support | | **Retention / Replay** | ❌ No | ✅ Yes, configurable retention window | ❌ No | | **Schema / Data Format** | JSON over WebSocket | Avro/Protobuf over Kafka | Protobuf (typed contracts) | | **Delivery Guarantee** | At-most-once | ✅ At-least-once (can configure exactly-once) | At-most-once | | **Integration Complexity** | Easiest for frontends, explorers, bots | Requires infra (Kafka cluster, consumers) | Lightweight, good for backend apps and trading strategies | | **Bandwidth Efficiency** | Medium (JSON, more verbose) | High (binary encoding, batching) | Medium (Protobuf, direct streams) | | **Use Case Fit** | Dashboards, explorers, analytics needing USD values & rich filters | Mission-critical infra: indexing, ETL pipelines, guaranteed delivery | Ultra-low latency trading, real-time DeFi apps, terminals, Telegram bots | ## Choosing the Right Blockchain Data Streaming API ### Choose **Real-time GraphQL WebSocket API** if: - Building **crypto trading web applications** - Need **[advanced filtering capabilities](/docs/graphql/filters/)** with complex conditions and **real-time USD prices** - Require **[cryptocurrency price calculations](/docs/trading/crypto-price-api/)** and **DeFi token metrics** - Want fastest development and prototyping experience for **blockchain applications** - Building **crypto dashboards**, **DeFi monitoring tools**, or **blockchain analytics platforms** - Need unified interface for both **historical blockchain data** and **real-time streams** ### Choose **High-Performance Kafka Blockchain Streams** if: - **Low-latency trading** is critical for your **cryptocurrency application** - Cannot afford to lose any **blockchain transactions** (guaranteed delivery) - Need horizontal scalability and **high-throughput blockchain data processing** - Building **enterprise-grade crypto trading infrastructure** - Require **transaction replay** and **blockchain data retention** capabilities - Processing large volumes of **DeFi transaction data** with complex transformations (filtering must be done client-side) ### Choose **Ultra-fast gRPC Streams (CoreCast)** if: - Working specifically with **Solana blockchain ecosystem** - Need **ultra-low latency** (< 100ms) for **Solana trading** - Want basic server-side filtering to reduce bandwidth (more limited than WebSocket) - Building **[high-frequency Solana trading applications](/docs/blockchain/Solana/Solana-Raydium-DEX-API/)** and **MEV bots** - Developing lightweight backend services for **Solana DeFi** - Creating **[Solana trading Telegram bots](/docs/usecases/telegram-bot/)** or **terminal applications** ## Getting Started ### GraphQL Subscriptions (WebSockets) 1. **Authentication**: Use your [IDE credentials](/docs/authorization/how-to-generate/) or [OAuth tokens](/docs/authorization/websocket/) 2. **Connect**: `wss://streaming.bitquery.io/graphql` 3. **Start**: Create your first subscription in the [Bitquery IDE](https://ide.bitquery.io) using our [starter subscriptions](/docs/start/starter-subscriptions/) **Learn more**: [WebSocket Documentation](/docs/subscriptions/websockets/) | [Examples](/docs/subscriptions/examples/) ### Kafka Streams 1. **Get Access**: Contact our [sales team](https://bitquery.io/forms/api) for Kafka credentials 2. **Connect**: Use SASL authentication with provided username/password 3. **Subscribe**: Choose from topics like `eth.dextrades.proto`, `solana.transactions.proto`, etc. **Learn more**: [Kafka Concepts](/docs/streams/kafka-streaming-concepts/) | [Best Practices](/docs/streams/kafka-streaming-concepts/#best-practises) ### gRPC Streams (CoreCast) 1. **Get Token**: Generate at [API Access Tokens](https://account.bitquery.io/user/api_v2/access_tokens) 2. **Connect**: `corecast.bitquery.io` with your API token 3. **Filter**: Define filters for addresses, tokens, or value thresholds **Learn more**: [gRPC Introduction](/docs/grpc/solana/introduction/) | [Code Examples](https://github.com/bitquery/grpc-code-samples) ## Multi-chain Blockchain Data Coverage ### GraphQL Subscriptions & Kafka Support: - **[Ethereum](/docs/blockchain/Ethereum/)** & Layer 2s ([Arbitrum](/docs/blockchain/Arbitrum/), [Optimism](/docs/blockchain/Optimism/), [Base](/docs/blockchain/Base/), [Polygon](/docs/blockchain/Matic/)) - **[Binance Smart Chain (BSC)](/docs/blockchain/BSC/)** - **[Robinhood](/docs/blockchain/robinhood/)** - **[Arc Mainnet](/docs/blockchain/arc-mainnet/)** (GraphQL and WebSocket subscriptions) - **[Arc Testnet](/docs/blockchain/arc-testnet/)** - **[Solana](/docs/blockchain/Solana/)** - **[TRON](/docs/blockchain/Tron/)** - **[Hyperliquid](/docs/perpetuals/hyperliquid/)** ### gRPC Streams: - **[Solana](/docs/blockchain/Solana/)** only ## Support & Resources - **Documentation**: Comprehensive guides for each technology - **Community**: Join our [Telegram](https://t.me/Bloxy_info) for support - **Code Examples**: [GitHub repositories](https://github.com/bitquery) with sample implementations - **Interactive Tools**: Test queries in our [IDE](https://ide.bitquery.io) --- Ready to start streaming? Choose the technology that best fits your use case and dive into the detailed documentation for implementation guides, best practices, and code examples. --- ## Real-Time Wallet Balance Tracker URL: https://docs.bitquery.io/docs/usecases/real-time-balance-tracker/overview/ Plan a live wallet balance tracker with Bitquery balance streams, Node.js processing, and a simple browser UI for updates. # Overview Building a real time balance tracker can be really helpful for the investigation teams to closely monitor the activities of a wallet. In this tutorial we will learn how to build a simple real time balance tracker using Javascript and NodeJS for the logical reasoning, using Bitquery's [Balance API](/docs/blockchain/Ethereum/balances/balance-api/), while using HTML, CSS and JavaScript to make the monitoring application more intuitive. ## Real Time Balance Calculation Logic To calculate or monitor the real time balance of a wallet, we will need a GraphQL API that returns the current balance along with a stream that reports every balance change, using Bitquery's [Websocket Connection Implementation](/docs/subscriptions/examples/#implementation-exampleusing-websocket-using-javascript). This is the simplified formula we will use in this example: ``` Current Balance = Balances query result, then PostBalance from each TransactionBalances stream event ``` If during the building of project you are stuck, you can refer to the following [Github Repository](https://github.com/Kshitij0O7/real-time-balance). --- ## Realtime Database URL: https://docs.bitquery.io/docs/graphql/dataset/realtime/ Realtime Database in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. See examples in the Bitquery IDE. # Realtime Database Realtime is the default database (if you omit the attribute, then it is used). **How much data `realtime` holds depends on the cube, not on one fixed number.** It is roughly 12 hours on Solana `DEXTrades`, about 7 days on Solana `DEXTradeByTokens`, a few days on the EVM transfer and DEX cubes, and about 30 days on the `Trading` cubes. The [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/) is the source of truth per chain and per cube. There is also a limitation on the streaming side: when querying `realtime` you only receive data that is not already in the `archive` dataset. If the latest block in the archive is 2 hours old, you only receive data more recent than that block. :::caution Realtime does not error when you ask for more than it holds Querying a date range wider than the retention window returns **fewer rows, not an error** — a chart simply starts late. If a result looks short, check the retention matrix before assuming the data is missing, and switch to [`archive`](/docs/graphql/dataset/archive/) or [`combined`](/docs/graphql/dataset/combined/) for history. ::: The main cases when it is used is for: - query the latest data available with minimum delay (up to the current block) Subscriptions do not read the realtime dataset: they are served from the streams as each block's data arrives. See [What triggers a subscription update](/docs/subscriptions/trigger/). Note that the last blocks in the real time database are not finalized and may be not later recorded to the archive data. [Select Block](/docs/graphql/dataset/select-blocks/) attribute controls how you can query the trunk or branch block updates in real time database. :::tip Realtime Database features: - contains the latest data available (up to the last second); - includes all blocks, including trunk, branches. Some of these blocks can be removed when archived. Use [Select Block](/docs/graphql/dataset/select-blocks/) attribute for better control; - fast to query ::: Also Check [Archive](/docs/graphql/dataset/archive) and [Combined](/docs/graphql/dataset/combined) dataset. --- ## Realtime Liquidity Drain Detector URL: https://docs.bitquery.io/docs/usecases/realtime-liquidity-drain-detector/ Build Realtime Liquidity Drain Detector: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Realtime Liquidity Drain Detector This guide demonstrates how to build a real-time DeFi security tool that monitors DEX pools to detect liquidity drains using Bitquery's Kafka streams. The tool provides instant alerts when significant liquidity drops are detected in DEX pools, helping protect against potential liquidity drains. Realtime Liquidity Drain Detection dashboard showing 6 critical alerts across 3 pools, including a rapid-drain alert for an HLS/WETH Uniswap V3 pool with its liquidity metrics > **⚠️ Important: Proof of Concept** > > This tool is provided as a **proof of concept** for educational purposes. The detection logic may generate false positives and should be modified based on your requirements. Always verify alerts by checking on-chain transaction data before taking action. GitHub Repository: [realtime-liquidity-drain-detector](https://github.com/Akshat-cs/realtime-liquidity-drain-detector) ## Overview The Realtime Liquidity Drain Detector is a Python-based security tool that: - Monitors DEX pools in real-time using Bitquery's Kafka streams - Detects significant liquidity drops that may indicate malicious activity - Provides a web dashboard for instant alerts and monitoring - Configurable thresholds for warning and critical alerts - Supports multiple DEX protocols including Uniswap V2, V3, and V4 ## Prerequisites 1. **Python 3.8+** installed on your system 2. **Bitquery Kafka Credentials** - Contact sales via [Telegram](https://t.me/Bloxy_info) or fill out the [form](https://bitquery.io/forms/api) for Kafka access 3. **Bitquery API Token** - Get your API token [here](/docs/authorization/how-to-generate/) 4. Basic understanding of Kafka streams and Python > **Note:** IDE credentials will not work with Kafka Streams. You need separate Kafka credentials for this tool. ## Installation 1. Clone the repository: ```bash git clone https://github.com/Akshat-cs/realtime-liquidity-drain-detector cd realtime-liquidity-drain-detector ``` 2. Install the required dependencies: ```bash pip install -r requirements.txt ``` 3. Configure your credentials: - Copy `config.sample.py` to `config.py`: ```bash cp config.sample.py config.py ``` - Edit `config.py` with your Kafka credentials: ```python username = "your_kafka_username" password = "your_kafka_password" ``` ## Configuration > **Note:** The default configuration values are starting points for a proof of concept. You should **tune these parameters** based on your specific requirements and testing to minimize false positives and optimize detection accuracy for your use case. Edit thresholds in `detection_config.py` to customize alert sensitivity: ```python class DetectionConfig: # Liquidity drop percentage thresholds LIQUIDITY_DROP_WARNING = 20.0 # 20% drop = warning level alert LIQUIDITY_DROP_CRITICAL = 40.0 # 40% drop = critical level alert # Time windows BASELINE_WINDOW_HOURS = 24 # Hours of data to build baseline LOOKBACK_WINDOW_MINUTES = 30 # Minutes to check for recovery (false positive filter) RAPID_DRAIN_WINDOW_MINUTES = 5 # Window for detecting sudden drains # Max trade size decrease thresholds MAX_AMOUNT_DECREASE_WARNING = 30.0 # 30% decrease = warning MAX_AMOUNT_DECREASE_CRITICAL = 50.0 # 50% decrease = critical # Alert management ALERT_COOLDOWN_MINUTES = 10 # Minutes between alerts for same pool RECOVERY_CHECK_ENABLED = True # Check if liquidity recovers quickly (false positive filter) # False positive prevention DROP_CONFIRMATION_COUNT = 2 # Number of consecutive measurements showing drop required before alerting ENABLE_MAX_AMOUNT_DECREASE_ALERTS = False # Set to False to disable max_amount_decrease alerts # Pool size filter MIN_LIQUIDITY_TOKENS = 1000 # Minimum liquidity to monitor (filters out very small pools) # Baseline reliability MIN_MEASUREMENTS_FOR_BASELINE = 10 # Need at least 10 measurements before alerting MIN_TIME_FOR_BASELINE_MINUTES = 5 # Need at least 5 minutes of data before alerting ``` ## Running the Tool ### Start the API Server (Frontend Dashboard) The API server provides a web dashboard for viewing alerts: ```bash python api_server.py ``` Access the dashboard at: `http://localhost:5001` ### Start the Detector The detector monitors Kafka streams and sends alerts to the API server: ```bash python liquidity_drain_detector.py ``` The detector will automatically send alerts to the API server when liquidity drains are detected. ## How It Works ### 1. Real-Time Monitoring The tool connects to Bitquery's Kafka streams for Ethereum DEX pools using the topic: - **`eth.dexpools.proto`** The Kafka consumer is configured with: ```python conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092', 'group.id': f'{username}-liquidity-drain-{group_id_suffix}', 'session.timeout.ms': 30000, 'security.protocol': 'SASL_PLAINTEXT', 'ssl.endpoint.identification.algorithm': 'none', 'sasl.mechanisms': 'SCRAM-SHA-512', 'sasl.username': config.username, 'sasl.password': config.password, 'auto.offset.reset': 'latest', } ``` Kafka streams provide: - Lower latency due to shorter data pipeline - Better reliability with persistent connections - Ability to read from latest offset without gaps - Better scalability with multiple consumers For detailed information on Kafka streams, refer to the [Kafka Streaming Concepts documentation](/docs/streams/kafka-streaming-concepts/). ### 2. Data Structures The tool uses three main data structures: #### PoolState Tracks the current state of a liquidity pool: ```python @dataclass class PoolState: pool_id: str pool_address: str currency_a: str currency_b: str currency_a_symbol: str currency_b_symbol: str dex_protocol: str amount_a: float = 0.0 # Human-readable liquidity for currency A amount_b: float = 0.0 # Human-readable liquidity for currency B slippage_at_bps_a_to_b: Dict[int, Dict] # Slippage data for A->B swaps slippage_at_bps_b_to_a: Dict[int, Dict] # Slippage data for B->A swaps price_a_to_b: float = 0.0 price_b_to_a: float = 0.0 last_updated: datetime ``` #### PoolHistory Maintains historical data for baseline calculation and drain detection: ```python @dataclass class PoolHistory: pool_id: str amount_a_history: deque # Historical liquidity for currency A amount_b_history: deque # Historical liquidity for currency B max_amount_history_a_to_b_100bp: deque # Max trade size history (A->B at 100bp) max_amount_history_b_to_a_100bp: deque # Max trade size history (B->A at 100bp) baseline_amount_a: Optional[float] # Baseline liquidity for currency A baseline_amount_b: Optional[float] # Baseline liquidity for currency B baseline_max_amount_a_to_b_100bp: Optional[float] baseline_max_amount_b_to_a_100bp: Optional[float] recent_drop_measurements_a: deque # Track recent drops for confirmation recent_drop_measurements_b: deque ``` ### 3. Liquidity Drain Detection The detector processes pool events from Kafka and performs three types of checks: #### A. Liquidity Drop Detection Tracks each currency separately and detects drops from baseline: ```python def _check_liquidity_drop(self, state: PoolState, history: PoolHistory, current_amount_a: float, current_amount_b: float, current_time: datetime) -> List[DrainAlert]: # Calculate drop percentage for each currency drop_a, drop_b = history.amount_drop_percent(current_amount_a, current_amount_b) # Pre-alert confirmation: Require multiple consecutive measurements if len(history.recent_drop_measurements_a) >= DROP_CONFIRMATION_COUNT: if drop_a >= LIQUIDITY_DROP_CRITICAL: severity = 'critical' elif drop_a >= LIQUIDITY_DROP_WARNING: severity = 'warning' # Generate alert... ``` **Key Features:** - Tracks each currency (A and B) separately - Requires `DROP_CONFIRMATION_COUNT` consecutive measurements showing drop - Uses mean of last 24 hours as baseline - Checks for recovery to filter false positives #### B. Max Amount Decrease Detection Monitors when maximum trade sizes decrease significantly: ```python def _check_max_amount_decrease(self, state: PoolState, history: PoolHistory, max_amount_a_to_b: Optional[float], max_amount_b_to_a: Optional[float], current_time: datetime) -> List[DrainAlert]: # Check both swap directions decrease_a = history.max_amount_decrease_percent(max_amount_a_to_b, 'a_to_b') decrease_b = history.max_amount_decrease_percent(max_amount_b_to_a, 'b_to_a') # Use worst-case direction if worst_decrease >= 50.0: severity = 'critical' elif worst_decrease >= 30.0: severity = 'warning' ``` **Note:** This alert type is disabled by default (`ENABLE_MAX_AMOUNT_DECREASE_ALERTS = False`) as it can cause false positives. #### C. Rapid Drain Detection Detects sudden drops within a short time window: ```python def _check_rapid_drain(self, state: PoolState, history: PoolHistory, current_amount_a: float, current_amount_b: float, current_time: datetime) -> List[DrainAlert]: # Check if liquidity dropped rapidly within RAPID_DRAIN_WINDOW_MINUTES if history.is_rapid_drain(current_amount_a, current_amount_b, current_time): # Generate critical alert... ``` ### 4. Baseline Calculation The baseline is calculated using the mean of measurements from the last 24 hours: ```python def update_baseline(self, current_time: datetime): cutoff_time = current_time - timedelta(hours=BASELINE_WINDOW_HOURS) # Baseline for currency A (mean - better for gradual drain detection) recent_amount_a = [amt for ts, amt in self.amount_a_history if ts >= cutoff_time and amt > 0] if recent_amount_a: self.baseline_amount_a = sum(recent_amount_a) / len(recent_amount_a) ``` **Baseline Requirements:** - Minimum 10 measurements (`MIN_MEASUREMENTS_FOR_BASELINE`) - Minimum 5 minutes of data (`MIN_TIME_FOR_BASELINE_MINUTES`) - Uses mean (not max) for better sensitivity to gradual drains ### 5. Alert Generation When a liquidity drain is detected, the tool generates a comprehensive alert including: - **Alert Type**: `liquidity_drop`, `max_amount_decrease`, or `rapid_drain` - **Severity**: Warning or Critical - **Pool Information**: Pool ID, address, token pair, DEX protocol - **Transaction Details**: Transaction hash and timestamp - **Liquidity Metrics**: Current vs baseline liquidity for both tokens - **Slippage Data**: Max trade sizes at different slippage levels (10bp, 50bp, 100bp, 200bp, 500bp, 1000bp) - **Drop Percentages**: Detailed breakdown of liquidity drops ## Sample Alert Output ``` ================================================================================ 🚨 LIQUIDITY DRAIN ALERT - CRITICAL ================================================================================ Type: liquidity_drop Pool ID: 0x10bd2f65f40bc8b7ddb6f104c603d022cd8a0ddf_0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2_0xdd9f7920b7c77efa8d1c19e3a7c1151f985f75a6 Pool Address: 0x10bd2f65f40bc8b7ddb6f104c603d022cd8a0ddf Pair: WETH/ASTRE DEX: uniswap_v2 Transaction Hash: 0x73470ed71e7b251d0e94078559d3c9005dc14187f55b61ad9435e99feb2341ea Time: 2026-01-15 13:17:25 UTC ASTRE dropped 90.4% from baseline Current State: Currency A: WETH (0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2) - Current Liquidity: 0.000000 WETH - Baseline Liquidity: 1.300800 WETH - Drop: +100.0% Currency B: ASTRE (0xdd9f7920b7c77efa8d1c19e3a7c1151f985f75a6) - Current Liquidity: 15,357,735,936.000000 ASTRE - Baseline Liquidity: 159,272,254,854.947357 ASTRE - Drop: +90.4% A->B MaxAmountIn (all slippage levels): (10bp): Baseline: 0.000654 WETH, Drop: +100.0% (50bp): Baseline: 0.003282 WETH, Drop: +100.0% (100bp): Baseline: 0.006592 WETH, Drop: +100.0% (200bp): Baseline: 0.013285 WETH, Drop: +100.0% (500bp): Baseline: 0.034013 WETH, Drop: +100.0% (1000bp): Baseline: 0.070822 WETH, Drop: +100.0% B->A MaxAmountIn (all slippage levels): (10bp): Baseline: 80,055,434.984426 ASTRE, Drop: +90.4% (50bp): Baseline: 399,877,993.949424 ASTRE, Drop: +90.4% (100bp): Baseline: 799,081,216.317845 ASTRE, Drop: +90.4% (200bp): Baseline: 1,594,216,258.495066 ASTRE, Drop: +90.4% (500bp): Baseline: 3,958,883,536.978619 ASTRE, Drop: +90.4% (1000bp): Baseline: 7,824,577,583.154605 ASTRE, Drop: +90.4% History Stats: - Liquidity A measurements: 19 - Liquidity B measurements: 19 - MaxAmountIn measurements: 19 - Baseline window: Last 24 hours ⚠️ VALIDATION NOTES: - For Uniswap V4: Liquidity amounts are AGGREGATED across all pools - MaxAmountIn is POOL-SPECIFIC (drops reflect this specific pool's drain) - Baseline uses last 24 hours of data - Check transaction hash on Etherscan to verify on-chain events ================================================================================ ``` ## Project Structure The project consists of three main files: 1. **`liquidity_drain_detector.py`** (1052 lines): Main detector logic - Data structures (`PoolState`, `PoolHistory`, `DrainAlert`) - Detection engine (`LiquidityDrainDetector` class) - Kafka consumer integration - Alert formatting and API communication 2. **`detection_config.py`** (55 lines): Configuration class - All detection thresholds and parameters - Time windows and filtering options - Baseline requirements 3. **`api_server.py`** (345 lines): Flask API server - REST API endpoints for alerts - Frontend dashboard serving - Alert storage and filtering - Configuration management ## Code Walkthrough ### Main Execution Flow The main function sets up the Kafka consumer and processes messages: ```python def main(): # Setup logging logging.basicConfig(level=logging.INFO) # Initialize detector detector = LiquidityDrainDetector() # Configure Kafka consumer conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092', 'group.id': f'{config.username}-liquidity-drain-{group_id_suffix}', 'security.protocol': 'SASL_PLAINTEXT', 'sasl.mechanisms': 'SCRAM-SHA-512', 'sasl.username': config.username, 'sasl.password': config.password, 'auto.offset.reset': 'latest', } consumer = Consumer(conf) consumer.subscribe(['eth.dexpools.proto']) # Main processing loop while True: msg = consumer.poll(timeout=1.0) if msg is None: continue # Parse protobuf message dex_pool_block = dex_pool_block_message_pb2.DexPoolBlockMessage() dex_pool_block.ParseFromString(msg.value()) # Process each pool event for pool_event in dex_pool_block.PoolEvents: alerts = detector.process_pool_update(pool_event) # Handle alerts for alert in alerts: print(format_alert(alert, state, history)) send_alert_to_api(alert, api_url, logger) ``` ### Processing Pool Updates The `process_pool_update` method handles each pool event: ```python def process_pool_update(self, dex_pool_event) -> List[DrainAlert]: # Extract pool information pool = dex_pool_event.Pool liquidity = dex_pool_event.Liquidity price_table = dex_pool_event.PoolPriceTable # For Uniswap V4, use PoolId; for others, use composite key if protocol_name == 'uniswap_v4': pool_id = convert_bytes_to_hex(pool.PoolId).lower() else: pool_id = f"{pool_address}_{currency_a}_{currency_b}" # Update pool state with current liquidity and slippage data state.amount_a = liquidity.AmountCurrencyA # Already human-readable state.amount_b = liquidity.AmountCurrencyB # Already human-readable # Process slippage data at multiple levels (10bp, 50bp, 100bp, etc.) for price_info in price_table.AtoBPrices: bps = price_info.SlippageBasisPoints max_in = price_info.MaxAmountIn # Already human-readable state.slippage_at_bps_a_to_b[bps] = { 'max_amount_in': max_in, 'min_amount_out': price_info.MinAmountOut, 'price': price_info.Price } # Add measurement to history history.add_measurement(amount_a_human, amount_b_human, max_amount_a_to_b_100bp, max_amount_b_to_a_100bp, max_amounts_a_to_b_all, max_amounts_b_to_a_all, current_time) # Run detection checks if baseline is sufficient if history.has_sufficient_baseline(current_time): alerts.extend(self._check_liquidity_drop(...)) alerts.extend(self._check_max_amount_decrease(...)) alerts.extend(self._check_rapid_drain(...)) ``` ### API Server Endpoints The Flask API server provides several endpoints for the web dashboard: #### Get Alerts ```http GET /api/alerts?pool=&type=&severity=&limit= ``` Returns filtered list of alerts. Filters: - `pool`: Filter by pool address or pool ID (case-insensitive) - `type`: Filter by alert type (`liquidity_drop`, `max_amount_decrease`, `rapid_drain`) - `severity`: Filter by severity (`warning`, `critical`) - `limit`: Maximum number of alerts to return (default: 100) **Response:** ```json { "alerts": [...], "total": 10, "total_all": 50 } ``` #### Get Alert Statistics ```http GET /api/alerts/stats ``` Returns statistics about all alerts: ```json { "total_alerts": 50, "by_severity": {"critical": 20, "warning": 30}, "by_type": {"liquidity_drop": 45, "rapid_drain": 5}, "by_dex": {"uniswap_v2": 30, "uniswap_v3": 20}, "unique_pools": 15 } ``` #### Get Configuration ```http GET /api/config ``` Returns current detection thresholds: ```json { "liquidity_drop_warning": 20.0, "liquidity_drop_critical": 40.0, "max_amount_decrease_warning": 30.0, "max_amount_decrease_critical": 50.0, "rapid_drain_threshold": 20.0 } ``` #### Update Configuration ```http POST /api/config Content-Type: application/json { "liquidity_drop_warning": 25.0, "liquidity_drop_critical": 45.0 } ``` Updates detection thresholds (validates values are between 0-100). #### Add Alert (Internal) ```http POST /api/alerts Content-Type: application/json { "pool_id": "0x...", "severity": "critical", "alert_type": "liquidity_drop", "message": "WETH dropped 90.4% from baseline", "timestamp": "2026-01-15T13:17:25Z", "pool_info": { "pool_id": "...", "pool_address": "0x...", "currency_pair": "WETH/ASTRE", "dex": "uniswap_v2", "transaction_hash": "0x..." }, "metrics": {...} } ``` Called by the detector to add new alerts. Alerts are stored in memory (max 1000, or 24 hours retention). #### Get Pools ```http GET /api/pools ``` Returns list of unique pools that have generated alerts: ```json { "pools": [ { "pool_id": "0x...", "pool_address": "0x...", "currency_pair": "WETH/ASTRE", "dex": "uniswap_v2", "alert_count": 5 } ], "total": 15 } ``` ## Understanding the Data ### Protobuf Message Structure The tool processes `DexPoolBlockMessage` protobuf messages from Kafka, which contain: - **PoolEvents**: Array of pool update events - **Pool**: Pool information (address, PoolId, currencies, decimals) - **Liquidity**: Current reserves (AmountCurrencyA, AmountCurrencyB) - already human-readable floats - **PoolPriceTable**: Slippage and price data - **AtoBPrices**: Array of price info for A→B swaps at different slippage levels - **BtoAPrices**: Array of price info for B→A swaps at different slippage levels - Each price info contains: SlippageBasisPoints, MaxAmountIn, MinAmountOut, Price - **Dex**: DEX protocol information (ProtocolName, SmartContract) - **TransactionHeader**: Transaction hash (optional) ### Pool Identification The tool uses different pool identification strategies: - **Uniswap V4**: Uses `PoolId` (bytes converted to hex) since liquidity is aggregated in PoolManager - **Other Protocols**: Uses composite key: `{pool_address}_{currency_a}_{currency_b}` (sorted) ### Important Notes - **Uniswap V4**: Liquidity amounts are aggregated across all pools in the PoolManager contract. Use `PoolId` to differentiate between pools. MaxAmountIn is pool-specific and will show drops. - **Baseline Calculation**: Uses the mean of measurements from the last 24 hours (not max) for better sensitivity to gradual drains - **Human-Readable Values**: The protobuf schema now sends liquidity and slippage values as human-readable floats (no decimal conversion needed) - **Validation**: Always verify alerts by checking the transaction hash on Etherscan ## Use Cases ### 1. DeFi Security Monitoring Monitor DEX pools for suspicious liquidity withdrawals that may indicate: - Liquidity drain attacks - Protocol exploits - Market manipulation ### 2. Risk Management Before executing large trades: - Check current pool liquidity depth - Verify sufficient liquidity exists for your trade size - Monitor for recent liquidity drains that may affect execution ### 3. Trading Strategy Protection - Avoid entering positions when liquidity is thin - Detect when pools become less liquid - Identify pools experiencing rapid liquidity growth or decline ### 4. Portfolio Protection - Monitor pools for tokens in your portfolio - Get alerts before liquidity drains affect token prices - Track liquidity health across multiple pools ## Related Documentation - [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) - [EVM Protobuf Kafka Streams](/docs/streams/protobuf/chains/EVM-protobuf/) - [Ethereum Liquidity API](/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api) - [Ethereum Slippage API](/docs/blockchain/Ethereum/dextrades/ethereum-slippage-api) - [DEXPools Cube Documentation](/docs/cubes/evm-dexpool/) ## Important Considerations This tool is provided as a **proof of concept** and should be considered a starting point for building your own liquidity monitoring solution. The detection logic may generate false positives due to legitimate large trades, normal liquidity rebalancing, temporary market fluctuations, or legitimate protocol operations. For production use, you should modify the detection logic, tune thresholds based on your specific use case, implement additional validation rules, and integrate with your existing monitoring infrastructure. This tool is not intended for production use without significant modifications, testing, and hardening. ## Support For issues or questions: - Open an issue on [GitHub](https://github.com/Akshat-cs/realtime-liquidity-drain-detector) - Contact Bitquery support via [Telegram](https://t.me/Bloxy_info) - Check the [Bitquery Documentation](https://docs.bitquery.io/) --- ## Reconnect Automatically After Disconnect URL: https://docs.bitquery.io/docs/subscriptions/silent-disconnect-reconnect/ Reconnect Automatically After Disconnect using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Reconnect Automatically After Disconnect When using Bitquery GraphQL streams via WebSocket, you need to implement reconnect logic if you don't receive any data or a 'ka' message for, say, 10 seconds. **Bitquery's WebSocket server doesn’t allow mid-connection retries or re-inits, so once "ka" or data stops, you must fully close and re-establish the WebSocket connection** This is how it would look with below sample implemention of a silent disconnect-reconnect scenario. ![WebSocket disconnect and reconnect flow](/img/ApplicationExamples/disconnect.png) ## Best Practices When implementing WebSocket subscriptions with auto-reconnect, follow these best practices: 1. **Separate Processing and Consumption**: Keep message processing and consumption as separate, non-blocking processes. Processing incoming data should not block the WebSocket connection from receiving new messages. Use asynchronous handlers, queues, or separate threads/workers to process data independently from the WebSocket receiver. 2. **Use Standard WebSocket Libraries**: Instead of manually managing each step of the WebSocket lifecycle (connection, subscription, keep-alive, reconnection), use well-tested WebSocket libraries that handle the full subscription lifecycle automatically. Libraries like `graphql-ws`, `apollo-client`, or similar provide built-in reconnection logic, subscription management, and error handling, reducing the complexity and potential bugs in your implementation. ## Close code 1013: consuming too slowly Not every disconnect is silent. If your client falls behind the stream, the server closes the socket with an explicit reason: ``` close code 1013 — client is not consuming messages fast enough ``` `1013` is "Try Again Later" in the WebSocket spec. The query is fine and the connection was fine; the server is shedding a consumer that stopped keeping up. Reconnecting alone will not fix this, because the new connection falls behind the same way. Two changes do: 1. **Narrow the subscription.** High-volume cubes such as `Solana.Instructions` and `Solana.BalanceUpdates` carry every instruction and balance change on the chain. Add a `where` filter for the program, token or account you actually care about. The same subscription that gets dropped unfiltered runs cleanly when scoped to one token. 2. **Never process inside the read loop** (best practice 1 above). Push each message to a queue and handle it in a separate worker, so a slow parse or database write cannot stall the socket. This failure is load-dependent, so an unfiltered subscription often works in development and drops in production. See [which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/) for the cubes that require a filter and the ones that never push data at all. ## Sample Implementation in JavaScript ```js const { WebSocket } = require("ws"); let isReconnecting = false; let bitqueryConnection; let lastMessageTime = Date.now(); const INACTIVITY_TIMEOUT_MS = 5000; let inactivityInterval; const GRAPHQL_SUBSCRIPTION_ID = "1"; const subscriptionQuery = ` subscription { Tron(mempool: true) { Transfers { Transfer { Sender Receiver Amount AmountInUSD Currency { Symbol } } } } } `; function connectToBitquery() { console.log("Connecting to Bitquery..."); const wsUrl = `wss://streaming.bitquery.io/graphql?token=ory_`; bitqueryConnection = new WebSocket(wsUrl, ["graphql-ws"]); bitqueryConnection.on("open", () => { console.log( "Connected to Bitquery WebSocket", bitqueryConnection.readyState ); // Send connection_init ONLY after socket is open bitqueryConnection.send(JSON.stringify({ type: "connection_init" })); lastMessageTime = Date.now(); startInactivityTimer(); }); bitqueryConnection.on("message", (data) => { lastMessageTime = Date.now(); let response; try { response = JSON.parse(data); } catch (err) { console.error("Invalid JSON from server:", data); return; } switch (response.type) { case "connection_ack": console.log("Connection acknowledged."); // Send subscription only now (socket is open + server ack) sendSubscription(); break; case "data": console.log("Received data"); // Push to queue for async processing // setImmediate(() => processData(response.payload.data)); // console.log(response.payload.data.Tron.Transfers.Transfer) break; case "ka": console.log("Keep-alive received."); break; case "error": console.error("Error from server:", response.payload.errors); break; default: console.warn("Unknown message type:", response); } }); bitqueryConnection.on("close", () => { console.warn("WebSocket closed. Reconnecting..."); reconnect(); }); bitqueryConnection.on("error", (error) => { console.error("WebSocket error:", error.message); reconnect(); }); } function sendSubscription() { if (bitqueryConnection.readyState !== WebSocket.OPEN) { console.warn("Cannot send subscription, socket not open."); return; } const subscriptionMessage = { type: "start", id: GRAPHQL_SUBSCRIPTION_ID, payload: { query: subscriptionQuery }, }; bitqueryConnection.send(JSON.stringify(subscriptionMessage)); console.log("Subscription message sent."); } function startInactivityTimer() { clearInterval(inactivityInterval); inactivityInterval = setInterval(() => { if (Date.now() - lastMessageTime > INACTIVITY_TIMEOUT_MS) { console.warn("No message received for 5s. Closing and reconnecting..."); reconnect(); } }, 5000); } function reconnect() { if (isReconnecting) return; // Prevent multiple calls isReconnecting = true; clearInterval(inactivityInterval); if (bitqueryConnection) { try { // Send complete message to properly terminate subscription before closing if (bitqueryConnection.readyState === WebSocket.OPEN) { const completeMessage = { type: "complete", id: GRAPHQL_SUBSCRIPTION_ID, }; bitqueryConnection.send(JSON.stringify(completeMessage)); console.log("Complete message sent before reconnection."); } bitqueryConnection.close(1000, "Reconnecting due to inactivity"); } catch (e) { console.error("Error closing connection:", e.message); } } console.warn(" Reconnecting in 3 seconds..."); setTimeout(() => { isReconnecting = false; connectToBitquery(); }, 3000); // wait before retrying } connectToBitquery(); ``` Consider implementing an exponential backoff logic (e.g., retry at 3s, 6s, 12s, up to a max) to avoid sending repeated subscription requests. --- ## Relative Time Filters URL: https://docs.bitquery.io/docs/graphql/capabilities/relative-time/ Relative Time Filters in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Relative Time Filters Bitquery's GraphQL API now supports **relative time filtering**. This filtering option simplify querying time-dependent blockchain data without manually calculating or formatting exact UTC timestamps. --- ## Why Use Relative Time? Traditionally, time-based filters required exact `UTC timestamp` as shown below, which could make the development experience tedious as the user is required to add logic to update the `timestamp` again and again. ```graphql Block: { Time: { after: "2025-08-01T00:00:00" } } ``` With relative filters, you can write queries in a simpler way, improving readability and flexibility, thus imporoving the development experience. ```graphql Block: { Time: { after_relative: { hours_ago: 1 } } } ``` ## Supported Relative Time Filters The list of supported relative time filters is given below. | Operator | Description | | ----------------- | -------------------------------------- | | `after_relative` | Time **after** a given relative point | | `before_relative` | Time **before** a given relative point | | `since_relative` | Alias for `after_relative` | | `till_relative` | Alias for `before_relative` | | `is_relative` | Exact match to a relative point (rare) | ## Supported Time Units The list of supported time units are given below. | Unit | Description | |----------------|-----------------------------------------------------------------------------| | `seconds_ago` | Refers to a number of seconds before the current time | | `minutes_ago` | Refers to a number of minutes before the current time | | `hours_ago` | Refers to a number of hours before the current time | | `days_ago` | Refers to a number of days before the current time | | `weeks_ago` | Refers to a number of weeks before the current time | | `years_ago` | Refers to a number of years before the current time | ## Examples ### Last Hour Trades The following example uses the `after_relative` filter to get Solana DEX Trades for the last `1 hour`. You can checkout from the results that the oldest trades returned occurred an hour ago(UTC Time). ```graphql { Solana { DEXTrades( where: {Block: {Time: {after_relative: {hours_ago: 1}}}} orderBy: {ascending: Block_Time} ) { Trade { Buy { AmountInUSD } } Block { Time } } } } ``` ### Using Multiple Time Units Together You can use multiple time units together as shown in the example below. ```graphql { Solana { DEXTrades( where: {Block: {Time: {after_relative: {hours_ago: 1, minutes_ago: 30, seconds_ago: 30}}}} orderBy: {ascending: Block_Time} ) { Trade { Buy { AmountInUSD } } Block { Time } } } } ``` --- ## Ripple (XRP Ledger) Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/ripple/ Ripple (XRP Ledger) Data - Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Ripple (XRP Ledger) Data Bitquery provides **Ripple / XRP Ledger data** as **Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), designed for large-scale analytics, historical backfills, and data lake integrations. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, etc**. XRPL is a **ledger-object** chain rather than an account-and-contract chain. A transaction does not just move a balance — it creates, modifies, or deletes typed objects in the ledger: account roots, trust lines, DEX offers, escrows, checks, NFT offers. Most Bitquery topics mirror that structure, giving you **one row per affected ledger object per transaction**, with the transaction context attached. ## Available Ripple Topics | Topic | Grain | What it holds | | --- | --- | --- | | `transactions_tx` | one row per transaction | Transaction envelope: type, fee, sequence, result code, memos, signers | | `transfers_tx` | one row per value movement | Unified view of all value flow — payments, fees, trades, NFT trades, mints | | `payments_tx` | one row per payment | `Payment` transactions with full amount / delivered / send-max / deliver-min detail | | `balances` | one row per account per currency | Balance before and after each change, native and issued | | `account_roots_tx` | one row per account object change | Account root state: XRP balance, owner count, sequence, domain, transfer rate | | `ripple_states_tx` | one row per trust line change | Trust line (RippleState) balances between two accounts for an issued currency | | `offers_tx` | one row per DEX offer change | Order book offers: taker gets / taker pays, before and after | | `nftoken_offers_tx` | one row per NFT offer change | NFT buy and sell offers, with the NFToken and the asking price | | `escrows_tx` | one row per escrow change | Escrow creation, finish, and cancel, with conditions and time locks | | `checks_tx` | one row per check change | Checks — deferred payment authorizations | Where a topic name ends in `_tx`, rows carry the transaction that caused the change. Pick `transfers_tx` when you want a single unified stream of value movement, and the object-level topics when you need XRPL-native state such as trust lines or order books. ## Sample Ripple Cloud Dataset You can explore schemas and validate your tooling using the **public Ripple sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/ripple](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/ripple) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple//.parquet ``` **Sample Parquet downloads (public S3)** - **Transactions** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/transactions_tx/93154950_93154999.parquet) - **Transfers** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/transfers_tx/93155850_93155899.parquet) - **Payments** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/payments_tx/93154950_93154999.parquet) - **Balances** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/balances/93154950_93154999.parquet) - **Account Roots** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/account_roots_tx/93154950_93154999.parquet) - **Ripple States (trust lines)** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/ripple_states_tx/93154950_93154999.parquet) - **Offers** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/offers_tx/93154950_93154999.parquet) - **NFToken Offers** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/nftoken_offers_tx/93154950_93155149.parquet) - **Escrows** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/escrows_tx/93154950_93155149.parquet) - **Checks** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/checks_tx/93154950_93155149.parquet) ## Ripple Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── ripple/ ├── account_roots_tx/ │ ├── _.parquet │ └── ... ├── balances/ │ ├── _.parquet │ └── ... ├── checks_tx/ │ ├── _.parquet │ └── ... ├── escrows_tx/ │ ├── _.parquet │ └── ... ├── nftoken_offers_tx/ │ ├── _.parquet │ └── ... ├── offers_tx/ │ ├── _.parquet │ └── ... ├── payments_tx/ │ ├── _.parquet │ └── ... ├── ripple_states_tx/ │ ├── _.parquet │ └── ... ├── transactions_tx/ │ ├── _.parquet │ └── ... └── transfers_tx/ ├── _.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Here `block` is the XRP Ledger **ledger index**. **Range size varies by topic.** Busy topics are written in 50-ledger files, while sparse object types are batched into wider ranges so files do not become tiny. In the samples above, `transfers_tx` and `transactions_tx` cover 50 ledgers (`93154950_93154999`), while `checks_tx`, `escrows_tx`, and `nftoken_offers_tx` cover 200 (`93154950_93155149`). Discover the files under a prefix rather than assuming a fixed stride. Density varies enormously. Across the same 50 ledgers the sample files hold about 4,400 transactions, 7,000 transfers, 9,600 balance rows, and 2,600 offers — but Checks are so rare that a **200**-ledger file contains a single row. ## Common Columns Most topics share the same transaction-context columns, which makes joining across topics straightforward: | Column | Type | Description | | --- | --- | --- | | `block` | uint32 | Ledger index | | `tx_date` | date | Date partition of the ledger close time | | `tx_time` | datetime | Ledger close time (UTC) | | `tx_hash` | string | Transaction hash — the join key across every topic | | `tx_index` | uint32 | Position of the transaction within the ledger | | `tx_sender` | string | Account that submitted and signed the transaction | | `tx_type` | string | XRPL transaction type, e.g. `Payment`, `OfferCreate`, `TrustSet` | | `operation` | string | Ledger node change type — see below | | `blockchain_id` | uint32 | Bitquery network identifier | | `prev_txn_id` | string | Hash of the previous transaction that touched this ledger object | | `prev_ledger_seq` | uint32 | Ledger index of that previous change | | `flags` | uint32 | XRPL flag bitfield for the object or transaction | ### The `operation` Column On the object-level topics, `operation` is the XRPL **AffectedNodes** change type, and it tells you what happened to the ledger object: - `CreatedNode` – the object came into existence, e.g. an offer was placed or a trust line opened. "Previous" columns are zero. - `ModifiedNode` – the object already existed and changed, e.g. an offer was partially filled or a balance moved. - `DeletedNode` – the object was removed, e.g. an offer was fully consumed or cancelled, or an escrow was finished. The value columns hold the object's **final** state before removal, not zeros. A single transaction routinely produces rows across several topics. One `OfferCreate` that crosses the book can create an offer row, delete counterparty offer rows, and modify two account roots and several trust lines, all sharing one `tx_hash`. ## Correctness Notes Four things about XRPL will silently produce wrong numbers if you treat the data like an EVM chain. ### 1. Use `delivered_value`, Not `amount_value` XRPL supports **partial payments**, where the sender specifies a maximum `Amount` but the network delivers less. `amount_value` is the *requested ceiling*; `delivered_value` is what actually arrived. This is the exploit that historically drained exchanges that credited deposits from the wrong field. In the `93154950_93154999` sample, 819 of 2,247 payments are flagged partial, and 346 of them delivered strictly less than the requested amount — sometimes by a factor of 10^15. Summing the wrong column is not a rounding error: ``` -- native XRP payments only (amount_currency_token_type = '-') SUM(amount_value) = 13,000,403,476,694 XRP -- 130x the entire XRP supply SUM(delivered_value) = 482,083 XRP -- correct ``` Always aggregate `delivered_value`. The `partial` column flags affected rows (`1` = partial); when `partial = 0`, the two columns are identical in every row of the sample, so `delivered_value` is safe to use unconditionally. ### 2. Drops vs XRP — Units Differ by Topic XRPL's base unit is the **drop**, at 1,000,000 drops per XRP. The topics are not uniform: | Topic and column | Unit | Type | | --- | --- | --- | | `transactions_tx.fee` | drops | string | | `account_roots_tx.balance`, `prev_balance` | drops | string | | `balances.balance`, `prev_balance` | XRP | float64 | | `transfers_tx.amount_from`, `amount_to` | XRP | float64 | | `payments_tx.*_value` | XRP | float64 | Both drop-denominated columns are **strings**, so they must be cast before arithmetic. Verified against the sample: every one of the 4,394 transactions has `transactions_tx.fee` exactly 1,000,000× the matching `transfers_tx` fee row, and all 6,466 joinable account-root rows are exactly 1,000,000× the matching `balances` row. ```sql CAST(fee AS BIGINT) / 1000000.0 AS fee_xrp ``` ### 3. Failed Transactions Are Included `transactions_tx` contains transactions that were **applied to the ledger but did not succeed** — they still consume a fee and occupy a sequence number. In the sample, 304 of 4,394 (about 7%) failed, with result codes such as `tecPATH_PARTIAL`, `tecPATH_DRY`, `tecUNFUNDED_OFFER`, and `tecINSUF_RESERVE_OFFER`. Filter on `success = 1`, or equivalently `result = 'tesSUCCESS'`, before counting activity. ### 4. Issued Currency Codes Are Hex XRPL supports two currency code formats. Three-character codes such as `XRP`, `POZ`, or `XPM` appear as-is. Longer codes are stored as the **40-character hex** the ledger itself carries, so decode them to get a readable ticker: ```python bytes.fromhex("4D656F7752500000000000000000000000000000").rstrip(b"\x00").decode() # 'MeowRP' ``` The same applies in SQL, for example in Athena or Snowflake: ```sql SELECT rtrim(from_utf8(from_hex(currency_symbol)), chr(0)) AS symbol, sum(delivered_value) AS volume FROM ripple_payments WHERE currency_token_type = 'issued' GROUP BY 1 ORDER BY 2 DESC ``` An issued token is only unique as the pair **(currency code, issuer)** — the same ticker can be issued by many accounts, and anyone may issue one. Filter on the issuer, or use `currency_id` as a single stable key. Native XRP carries `currency_token_type = '-'` and `currency_address = '-'`. ## Topic Schemas Columns listed in [Common Columns](#common-columns) are omitted below. ### transactions_tx One row per transaction. 4,394 rows in the 50-ledger sample. | Column | Type | Description | | --- | --- | --- | | `fee` | string | Fee burned, **in drops** | | `result` | string | XRPL result code, e.g. `tesSUCCESS`, `tecPATH_DRY` | | `success` | uint8 | `1` when `result = 'tesSUCCESS'` | | `sequence` | uint32 | Sender's account sequence number | | `last_ledger_sequence` | uint32 | Last ledger the transaction was valid for | | `account_txn_id` | string | Optional chained-transaction identifier | | `source_tag` | uint32 | Sender-side routing tag | | `memos` | string | JSON array of memos, each with `data_hex`, decoded `data`, `format`, `type` | | `tx_signers` | string | JSON array of signers for multi-signed transactions | ### transfers_tx One row per value movement — the unified stream. 7,041 rows in the `93155850_93155899` sample. | Column | Type | Description | | --- | --- | --- | | `sender` | string | Account the value left; empty on mints | | `receiver` | string | Account the value arrived at; empty on fees | | `direction` | string | Transfer classification — see below | | `amount_from` | float64 | Amount debited from `sender`, **in XRP** for native | | `amount_to` | float64 | Amount credited to `receiver` | | `currency_from_*` | mixed | `id`, `symbol`, `name`, `address`, `tokenType` of the sent asset | | `currency_to_*` | mixed | Same set for the received asset | | `tx_hash_bin` | binary | Transaction hash as raw bytes — cheaper to join and filter on | | `tx_type_raw`, `transaction_type` | string | Raw and normalized transaction type | | `tx_sender_raw`, `transaction_sender` | string | Raw and normalized submitting account | One transaction produces several transfer rows. `direction` tells you what each row represents: - `payment` – a direct value transfer between two accounts, XRP or issued token - `fee` – the XRP burned to pay for the transaction. `receiver` is empty because the fee is destroyed, not paid to a validator - `trade` – a leg of a DEX order-book or AMM execution, where the sent and received currencies differ - `nft_trade` – an NFToken changing hands via `NFTokenAcceptOffer` - `mint` – an NFToken being created. `sender` is empty and `amount_from` is `0` - `other` – ledger effects that are not a completed value movement, such as `TrustSet` or `OfferCancel` bookkeeping In the sample, `fee` rows alone are half the file (3,535 of 7,041), so filter to `direction = 'payment'` for economic volume and to `direction = 'fee'` for network fee revenue. ### payments_tx One row per `Payment` transaction. 2,247 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `sender`, `receiver` | string | Payment source and destination | | `amount_value` | float64 | Requested amount — **a ceiling, not what arrived** | | `delivered_value` | float64 | Amount actually delivered — use this | | `send_max_value` | float64 | Maximum the sender was willing to spend | | `deliver_min_value` | float64 | Minimum the sender would accept delivering | | `partial` | uint8 | `1` when the partial-payment flag was set | | `amount_*`, `delivered_*`, `send_max_*`, `deliver_min_*` | mixed | Each carries its own `currency_id`, `currency_address`, `currency_name`, `currency_symbol`, `currency_token_type`, and `issuer` | | `tag` | uint32 | Destination tag — identifies the end user at an exchange | | `invoice` | string | Optional invoice identifier | ### balances One row per account per currency per change. 9,640 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `account` | string | Account whose balance changed | | `balance` | float64 | Balance after the change, **in XRP** for native | | `prev_balance` | float64 | Balance before the change | | `issuer` | string | Issuer of the currency; empty for native XRP | | `currency_*` | mixed | `id`, `address`, `name`, `symbol`, `token_type` | The per-row delta is `balance - prev_balance`. 252 rows in the sample have `balance = prev_balance`, so a change row does not guarantee a net movement. ### account_roots_tx One row per AccountRoot object change — the account's own XRP balance and settings. 6,742 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `account` | string | The account | | `balance` | string | XRP balance after the change, **in drops** | | `prev_balance` | string | XRP balance before the change, **in drops** | | `owner_count` | uint32 | Number of ledger objects the account owns, which sets its reserve | | `sequence` | uint32 | Account sequence number | | `domain` | string | Optional domain the account claims, hex encoded. Rare — 11 of 6,742 rows | | `transfer_rate` | uint32 | Fee an issuer charges on transfers of its token | Nearly all rows are `ModifiedNode`; `CreatedNode` marks account funding (16 in the sample). ### ripple_states_tx One row per RippleState (trust line) change. Trust lines hold every issued-token balance on XRPL. 1,857 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `low_account` | string | The numerically lower of the two accounts | | `high_account` | string | The numerically higher of the two accounts | | `balance` | float64 | Trust line balance after the change | | `pre_balance` | float64 | Trust line balance before the change | | `currency_*` | mixed | `id`, `address`, `name`, `symbol`, `token_type` | **The balance is signed, from the low account's perspective.** A positive balance means the low account holds the asset; a negative balance means the high account does. In the sample, 909 rows are negative, 562 positive, and 386 zero. Take the absolute value, and use the sign to decide which side holds the token — do not sum raw balances across trust lines. ### offers_tx One row per DEX offer object change. 2,572 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `account` | string | Offer owner | | `taker_gets_value` | float64 | What the taker receives, after the change | | `taker_pays_value` | float64 | What the taker pays, after the change | | `pre_taker_gets_value` | float64 | Same, before the change | | `pre_taker_pays_value` | float64 | Same, before the change | | `taker_gets_currency_*` | mixed | Currency the taker receives | | `taker_pays_currency_*` | mixed | Currency the taker pays | | `book_directory`, `book_node` | string | Order book placement | | `expiration`, `sequence` | uint32 | Offer expiry and owner sequence | Compare the `pre_*` and post columns to size a fill. On `CreatedNode` rows the `pre_*` values are zero; on `DeletedNode` rows the post columns retain the offer's final state rather than zeroing out, so a deletion is a cancel or a complete fill depending on whether the remaining value went to zero. ### nftoken_offers_tx One row per NFT offer object change. 202 rows in the 200-ledger sample. | Column | Type | Description | | --- | --- | --- | | `from_account` | string | Offer creator | | `destination_account` | string | Restricted counterparty, when the offer targets one account | | `nftoken_sell_offer` | string | Sell offer identifier, set on sell-side rows | | `nftoken_buy_offer` | string | Buy offer identifier, set on buy-side rows | | `nftoken_currency_*` | mixed | The NFToken being offered, with `token_type` of `nft` | | `nftoken_value` | float64 | NFToken quantity, normally `1` | | `currency_*` | mixed | Currency of the asking price — XRP in every sample row | | `value` | float64 | Asking price | | `book_directory`, `book_node` | string | Offer book placement | | `expiration`, `sequence` | uint32 | Offer expiry and owner sequence | Check which of `nftoken_sell_offer` / `nftoken_buy_offer` is populated to tell the two sides apart — 68 sell and 59 buy in the sample. ### escrows_tx One row per Escrow object change. 12 rows in the 200-ledger sample. | Column | Type | Description | | --- | --- | --- | | `account` | string | Escrow creator | | `destination` | string | Escrow beneficiary | | `amount` | float64 | Escrowed amount | | `condition` | string | Crypto-condition that must be fulfilled to release | | `finish_after` | uint32 | Earliest release time, **Ripple epoch seconds** | | `cancel_after` | uint32 | Time after which the escrow can be cancelled back | | `source_tag`, `destination_tag` | uint32 | Routing tags | | `currency_*` | mixed | Escrowed currency | `CreatedNode` rows are `EscrowCreate`; `DeletedNode` rows are `EscrowFinish` or `EscrowCancel` — read `tx_type` to distinguish them. **Time fields use the Ripple epoch**, which starts at 2000-01-01T00:00:00Z. Add 946,684,800 to convert to Unix time. ### checks_tx One row per Check object change. Checks are rare — the 200-ledger sample contains **one** row. | Column | Type | Description | | --- | --- | --- | | `account` | string | Check writer | | `destination` | string | Check recipient | | `send_max` | float64 | Maximum amount the check can be cashed for | | `expiration` | uint32 | Expiry, Ripple epoch seconds | | `invoice_id` | string | Optional invoice identifier | | `source_tag`, `destination_tag` | uint32 | Routing tags | | `sequence` | uint32 | Owner sequence number | | `currency_*` | mixed | Check currency | ## Joining Topics Every topic carries `tx_hash`, so it is the natural join key. To attach fee and success to value movement: ```sql SELECT p.sender, p.receiver, p.delivered_value, CAST(t.fee AS BIGINT) / 1000000.0 AS fee_xrp FROM ripple_payments p JOIN ripple_transactions t USING (tx_hash) WHERE t.success = 1 ``` Because one transaction fans out to many object rows, joining two object-level topics on `tx_hash` alone produces a cross product. Aggregate one side first, or add `block` and the object identity columns to the join. ## Reading Files in Python ```python BASE = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ripple/" RANGE = "93154950_93154999" tx = pd.read_parquet(f"{BASE}transactions_tx/{RANGE}.parquet") pay = pd.read_parquet(f"{BASE}payments_tx/{RANGE}.parquet") # fees are drops-as-string tx["fee_xrp"] = tx.fee.astype("int64") / 1_000_000 print("fees burned:", tx.fee_xrp.sum(), "XRP over", len(tx), "transactions") print("failed:", (tx.success == 0).sum()) # delivered_value, never amount_value xrp = pay[pay.amount_currency_token_type == "-"] print("XRP delivered:", xrp.delivered_value.sum()) print("if you used amount_value:", xrp.amount_value.sum()) # ~27,000,000x too high ``` ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). ## Real-Time vs Batch Data Access Data Store exports are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming Ripple data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - **GraphQL subscriptions** --- ## Robinhood Chain API: Trades, Transfers, Pons Launchpad, Live Streams (chain id 4663) URL: https://docs.bitquery.io/docs/blockchain/robinhood/ Robinhood Chain API (chain ID 4663): trades, transfers, balances, holders, liquidity, events, calls and the Pons launchpad via Bitquery GraphQL and WebSocket. # Robinhood Chain API: Trades, Transfers, Pons Launchpad, Live Streams (chain id 4663) **Robinhood Chain** (`network: robinhood`, chain ID **4663**) is Robinhood's EVM Layer 2, built with the Arbitrum Orbit stack and live on mainnet since July 2026. Gas is paid in ETH, the chain carries the **USDG** stablecoin and Robinhood's **tokenized stocks and ETFs**, and it hosts a dense cluster of meme-coin launchpads, led by **Pons**. Bitquery indexes the whole chain — blocks, transactions, internal calls, decoded events, token transfers, balances, DEX trades and pool liquidity — and serves it through one GraphQL endpoint where any query can run as a live WebSocket stream. **Chain facts:** chain ID `4663` (testnet `46630`), native gas token **ETH**, block explorer [robinhoodchain.blockscout.com](https://robinhoodchain.blockscout.com), public RPC `https://rpc.mainnet.chain.robinhood.com` (rate-limited; Robinhood's [connection docs](https://docs.robinhood.com/chain/connecting) list production RPC providers). Bitquery is the indexed data layer on top of the chain, not an RPC node. This page is the map. Use it to pick the cube that answers your question, then jump to the linked guide. The **[Pons Launchpad API](#pons)** has its own section below because it is the launchpad developers ask about most. ## Video Tutorial | Robinhood Chain APIs - Real-Time Trades, Transfers & Meme Launches :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ## Robinhood Chain at a glance {#network-facts} | Property | Value | | --- | --- | | Bitquery network name | `robinhood` in `EVM(network: robinhood)`; `bid:robinhood` in the `Trading` cubes | | Chain ID | `4663` | | Stack | EVM, Arbitrum Orbit rollup | | Gas token | ETH | | Public explorer | [robinhoodchain.blockscout.com](https://robinhoodchain.blockscout.com) — Bitquery is an indexed data API, not an explorer or an RPC node | | Public RPC | `https://rpc.mainnet.chain.robinhood.com` (rate-limited, from [Robinhood Chain docs](https://docs.robinhood.com/chain/connecting)) | | WETH | `0x0bd7d308f8e1639fab988df18a8011f41eacad73` | | USDG (Global Dollar, 6 decimals) | `0x5fc5360d0400a0fd4f2af552add042d716f1d168` | | Uniswap v4 PoolManager | `0x8366a39cc670b4001a1121b8f6a443a643e40951` — the chain-wide v4 singleton that Pons and pools.trade pools route through | | GraphQL endpoint | `https://streaming.bitquery.io/graphql` for queries and subscriptions | --- ## All Robinhood Chain API pages {#all-pages} | Page | When to use it | | --- | --- | | [DEX Trades on Robinhood Chain](/docs/blockchain/robinhood/robinhood-trades) | Live swaps, USD prices, OHLCV candles, market cap, whale trades and top traders | | [Token Transfers on Robinhood Chain](/docs/blockchain/robinhood/robinhood-transfers) | Who sent what to whom: ETH, USDG and tokenized-stock transfers, whale alerts, wallet ledgers | | [Wallet Balances on Robinhood Chain](/docs/blockchain/robinhood/robinhood-balances-api) | A wallet's full portfolio, multi-address batches and balance history as of any date | | [Token Holders on Robinhood Chain](/docs/blockchain/robinhood/robinhood-token-holders-api) | Top-holder rankings, holder counts and distribution for one token | | [Token Supply on Robinhood Chain](/docs/blockchain/robinhood/robinhood-token-supply) | Total supply of a token, a watchlist or all active tokens, as a query or stream | | [DEX Liquidity & Slippage on Robinhood Chain](/docs/blockchain/robinhood/robinhood-liquidity) | Liquidity pool reserves, TVL and price impact before you size a trade | | [New Pools & Trending Tokens on Robinhood Chain](/docs/blockchain/robinhood/robinhood-new-pools-trending) | Newly created liquidity pools, trending tokens, pair lookup and token search for a screener | | [Meme Coin Launches on Robinhood Chain](/docs/blockchain/robinhood/robinhood-meme-coin-launches) | Every new token across all launchpads in one feed, plus per-launchpad launch queries | | [Pons Launchpad API on Robinhood Chain](/docs/blockchain/robinhood/pons-api) | Pons launches, bonding-curve trades, graduations and the liquidity lock | | [Pools.trade API — Uniswap Launchpad on Robinhood Chain](/docs/blockchain/robinhood/pools-trade-api) | Uniswap's launchpad: new launches, Crowd Launch auctions, trades and holders | | [Flap.sh API on Robinhood Chain](/docs/blockchain/robinhood/flap-sh-api) | Flap.sh launches, bonding-curve buys and sells, and DEX graduations | | [trench.today API on Robinhood Chain](/docs/blockchain/robinhood/trench-today-api) | trench.today launches, curve buys and sells, and live curve reserves | | [Bags.fm API on Robinhood Chain](/docs/blockchain/robinhood/bags-fm-api) | Bags.fm trades, prices, OHLCV and bonding-curve events | | [ONDO Tokenized Stocks API on Robinhood Chain](/docs/blockchain/robinhood/ondo-stocks-api) | Ondo tokenized stocks and ETFs: catalog, holders, OHLCV and live prices | | [Lighter Perp DEX on Robinhood Chain](/docs/blockchain/robinhood/lighter-perp-dex-api) | USDG margin deposits and withdrawals and batch commits on the Lighter perp DEX | | [Smart Contract Events on Robinhood Chain](/docs/blockchain/robinhood/robinhood-events-api) | Any decoded contract event or log, as an `eth_getLogs` replacement or a live stream | | [Contract Calls & Traces on Robinhood Chain](/docs/blockchain/robinhood/robinhood-calls-api) | Method calls, internal traces, contract deployments and reverts | | [Transactions & Receipts on Robinhood Chain](/docs/blockchain/robinhood/robinhood-transactions-receipts-api) | Transactions with receipts, status, gas and fees, in place of `eth_getTransactionReceipt` | --- ## Quick start: stream every trade on Robinhood Chain {#quick-start} The `Trading` cubes carry live swaps with USD prices for Robinhood Chain and eight other chains in one schema. Paste this into the [Bitquery IDE](https://ide.bitquery.io) to watch the network trade in real time: ```graphql subscription { Trading { Trades( where: {Pair: {Market: {NetworkBid: {is: "bid:robinhood"}}}} ) { Block { Time } Trader { Address } Pair { Token { Name Symbol Address } QuoteToken { Name Symbol Address } } Amounts { Base Quote } AmountsInUsd { Base } } } } ``` Change `subscription` to `query`, add `limit: {count: 10}` and `orderBy: {descending: Block_Time}`, and the same selection set returns the latest trades instead. Prices, OHLCV candles, market cap, whale trades and top-trader leaderboards are on the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) page. :::tip Trading cubes for live data, DEXTrades for deep history `Trading.Trades` / `Tokens` / `Pairs` cover real-time plus roughly the last 30 days with USD pricing baked in. Use the chain-level `DEXTrades` cube for older history or when you need the call and event context around a swap. See the [Trading data overview](/docs/trading/trading-data-overview/). ::: --- ## Pick the right API {#pick-the-right-api} | What you want | Use this | Guide | | --- | --- | --- | | Live swaps, USD prices, OHLCV, market cap, top traders | `Trading` cubes; `DEXTrades` for older history | [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) | | New pools, trending tokens, pair lookup, token search | `Events` (`Initialize`, `PoolCreated`) and `Trading` cubes | [New Pools & Trending Tokens API](/docs/blockchain/robinhood/robinhood-new-pools-trending) | | Every new token, across all launchpads | `Transfers` (launch mints) and `Events` | [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) | | Pons launches, curve trades, graduations, liquidity lock | `Events`, `Calls`, `Trading` | [Pons Launchpad API](/docs/blockchain/robinhood/pons-api) | | Who sent what to whom, whale alerts, wallet ledgers | `Transfers` | [Robinhood Transfers API](/docs/blockchain/robinhood/robinhood-transfers) | | A wallet's portfolio and balance history | `Balances` | [Robinhood Balances API](/docs/blockchain/robinhood/robinhood-balances-api) | | Holder rankings, counts and distribution | `Holders` | [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api) | | Total supply of a token or watchlist | `TransactionBalances` | [Robinhood Token Supply API](/docs/blockchain/robinhood/robinhood-token-supply) | | Pool reserves, TVL, per-swap slippage | `DEXPools` | [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity) | | Any decoded contract event, an `eth_getLogs` replacement | `Events` | [Robinhood Events API](/docs/blockchain/robinhood/robinhood-events-api) | | Method calls, internal traces, contract deployments, reverts | `Calls` | [Robinhood Calls & Traces API](/docs/blockchain/robinhood/robinhood-calls-api) | | Transactions, receipts, status, gas and fees | `Transactions` | [Robinhood Transactions & Receipts API](/docs/blockchain/robinhood/robinhood-transactions-receipts-api) | | Swaps on Algebra pools | `DEXTrades` with `ProtocolName: "algebra"` | [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades) | | Perp margin deposits and withdrawals on Lighter | `Transfers`, `Events`, `Calls` | [Lighter Perp DEX API](/docs/blockchain/robinhood/lighter-perp-dex-api) | --- ## Pons Launchpad API on Robinhood Chain {#pons} **[Pons](https://www.ponsfamily.com/launchpad)** (Pons Family) is the bonding-curve launchpad on Robinhood Chain. Every launch mints a fixed **1 billion** supply into its own curve contract. Traders buy and sell against that curve until it takes in its graduation threshold (**4.2 ETH** for native-quoted launches; a per-asset amount for other quotes), at which point the curve is swept, the proceeds seed a **Uniswap v4 pool behind the Pons meme hook**, and the liquidity position is **permanently locked**. A creator can quote a launch in **ETH, USDG, cbBTC, or a tokenized stock or ETF** such as TSLA, NVDA or SPY. The [Pons Launchpad API guide](/docs/blockchain/robinhood/pons-api) covers the full lifecycle with runnable queries: - **New launches** — the decoded `TokenLaunched` event, a `Calls`-based launch feed with full archive history, and the on-chain token metadata (name, symbol, image, description, socials). See [Newly launched tokens](/docs/blockchain/robinhood/pons-api#newly-launched-tokens) and [Token metadata](/docs/blockchain/robinhood/pons-api#token-metadata). - **Bonding-curve trades** — `CurveBuy` and `CurveSell` events with snipe-tax fields, plus the same trades as `Protocol: pons_v2` rows in the `Trading` cube for USD prices and OHLCV. See [Bonding-curve trades](/docs/blockchain/robinhood/pons-api#bonding-curve-trades). - **Graduations** — `LaunchSwept` and `PoolGraduated`, the graduated v4 pool, and how to find the Pons pool of one token without picking up copycat pools. See [Graduation](/docs/blockchain/robinhood/pons-api#graduation). - **Locked liquidity** — verifying the lock in `PonsV2LaunchLocker`. See [Verifying the Pons liquidity lock](/docs/blockchain/robinhood/pons-api#liquidity-lock). - **Contract addresses and event reference** — every factory, curve, hook, router and locker event with its topic0. See [Contract addresses](/docs/blockchain/robinhood/pons-api#contract-addresses) and [Event reference](/docs/blockchain/robinhood/pons-api#event-reference). - **After graduation** — holders, supply, pool liquidity and slippage for graduated tokens. See [Holders and supply](/docs/blockchain/robinhood/pons-api#holders-and-supply). | Pons V2 contract | Address | | --- | --- | | Launch factory (`PonsV2LaunchFactory`) | `0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e` | | Launch router (`PonsV2LaunchAndBuy`) | `0xe33e9e479df8802cb0866d5d05258bec4cf62948` | | Meme hook (`PonsV2MemeHook`), on every graduated pool | `0xe5e702641ea86f4ae6cc3cdaed2b886f976be044` | | Launch locker (`PonsV2LaunchLocker`) | `0x267444d099b10fb5ed7c3cc7b7c767adca574952` | | Bonding curve | one contract per token — the receiver of the launch mint | Stream every new Pons launch as it happens: ```graphql subscription { EVM(network: robinhood) { Calls( where: { Call: { To: {in: [ "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e", "0xe33e9e479df8802cb0866d5d05258bec4cf62948" ]} Input: {startsWith: ["0xf35abbcf", "0xa72101af", "0xf85f8e41"]} Success: true } } ) { Block { Time } Transaction { Hash From } Call { To Value Input Output } } } } ``` `Transaction.From` is the creator, and the first two 32-byte words of `Call.Output` are the new token and its curve. The [guide](/docs/blockchain/robinhood/pons-api#newly-launched-tokens) explains the selectors, the decoding, and why `launchTokenFor` is deliberately left out of the filter. :::caution Pons and pools.trade are opposites Pons has a real bonding curve and a graduation event. [pools.trade](/docs/blockchain/robinhood/pools-trade-api) tokens trade in a Uniswap v4 pool from block one with no curve and no graduation. Queries written for one return nothing on the other — see [How Pons differs from pools.trade](/docs/blockchain/robinhood/pons-api#pons-vs-poolstrade). ::: --- ## Other launchpads on Robinhood Chain {#launchpads} Robinhood Chain launchpads are **not interchangeable**. Each has its own factory contracts, its own event signatures, and a different relationship to the DEX it trades on. Four more have dedicated guides: | Launchpad | Model | Guide | | --- | --- | --- | | **pools.trade** | Uniswap v4 pool from block one, no curve and no graduation event; Crowd Launch auctions | [Pools Trade API on Robinhood](/docs/blockchain/robinhood/pools-trade-api) | | **Flap.sh** | Bonding curve with per-token tax and progress events, graduates to a DEX; emits a decoded `TokenCreated` | [Flap.sh API on Robinhood](/docs/blockchain/robinhood/flap-sh-api) | | **trench.today** | Bonding-curve launchpad run from a single factory proxy; `TokenCreate`, `TokenPurchase`, `TokenSale` and `Sync` events expose launches, trades and live curve reserves | [trench.today API on Robinhood](/docs/blockchain/robinhood/trench-today-api) | | **Bags.fm** | Creator-fee launchpad | [Bags.fm API on Robinhood](/docs/blockchain/robinhood/bags-fm-api) | For a **cross-launchpad feed** — every new token on the network regardless of which factory minted it — use the [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches). It also carries per-launchpad launch queries for [hood.fun](/docs/blockchain/robinhood/robinhood-meme-coin-launches#hoodfun), [LaunchHood](/docs/blockchain/robinhood/robinhood-meme-coin-launches#launchhood), [Virtuals](/docs/blockchain/robinhood/robinhood-meme-coin-launches#virtuals), [Klik Finance](/docs/blockchain/robinhood/robinhood-meme-coin-launches#klik-finance), [Doppler](/docs/blockchain/robinhood/robinhood-meme-coin-launches#doppler-airlock) (the Airlock that Bankr and other front-ends launch through), [Ape.store](/docs/blockchain/robinhood/robinhood-meme-coin-launches#apestore) and [Clanker](/docs/blockchain/robinhood/robinhood-meme-coin-launches#clanker), and a query that [compares launch activity across launchpads](/docs/blockchain/robinhood/robinhood-meme-coin-launches#compare-launchpad-activity). :::tip Feed for discovery, launchpad page for depth The cross-launchpad feed answers *"what launched?"*. The per-launchpad guides answer *"what is this token doing?"* — curve trades, graduation progress, fee splits and pool state. Most production pipelines use the feed for discovery and one launchpad guide for depth. ::: --- ## Perpetual futures: Lighter on Robinhood Chain {#perps} [Lighter](https://lighter.xyz) is the perp DEX behind in-app perpetuals in Robinhood Wallet. Its ZkLighter rollup contract lives on Robinhood Chain and receives every USDG margin deposit, pays every withdrawal, and records the rollup's batch lifecycle. The [Lighter Perp DEX API](/docs/blockchain/robinhood/lighter-perp-dex-api) shows how to track deposits, withdrawals, batch commits and the contract's flow history. --- ## Real-time streams: WebSocket, Kafka and MCP {#streaming} - **WebSocket** — every query on every page above runs as a subscription: swap `query` for `subscription` and keep the same selection set. See [WebSocket subscriptions](/docs/subscriptions/websockets/) and [authorizing a WebSocket connection](/docs/authorization/websocket/). - **Kafka** — for firehose-scale workloads, Robinhood Chain is published as protobuf topics: `robinhood.transactions.proto` (transactions, calls, events), `robinhood.tokens.proto` (transfers, balances), `robinhood.dextrades.proto` (DEX trades), `robinhood.dexpools.proto` (pool liquidity) and `robinhood.raw.proto` (raw blocks). See [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/) and the [streams overview](/docs/streams/). - **MCP** — the [Bitquery MCP server](/docs/mcp/mcp-server/) exposes Robinhood Chain trades, prices and wallet history to AI agents alongside the other Trading-cube chains. --- ## Datasets and history {#datasets} Robinhood Chain queries accept a `dataset` argument that decides how far back you can reach and how fresh the tail is. - [`realtime`](/docs/graphql/dataset/realtime) — lowest latency, holds only the most recent days - [`archive`](/docs/graphql/dataset/archive) — history back to when Bitquery started indexing Robinhood Chain, higher latency - [`combined`](/docs/graphql/dataset/combined) — both, stitched - [Data coverage and retention](/docs/graphql/data-coverage-retention) — what each window actually holds Two rules of thumb. If a query works on recent data but returns nothing for older blocks, the dataset argument is almost always the reason. And a few cubes — `Transactions`, `DEXPools` and `TransactionBalances` — are realtime-only on Robinhood Chain; each guide's dataset section says what applies to it. History is sold per chain. The free trial and paid self-service plans are real-time only; paid plans add history through the Robinhood archive add-on on the [pricing page](https://bitquery.io/pricing), which unlocks `archive` and `combined` on `DEXTrades`, `DEXTradeByTokens`, `Calls` and `Events`. A second add-on covers historical `Transfers`, `Balances` and `Holders`. The Pons guide's [historical data section](/docs/blockchain/robinhood/pons-api#historical-data) walks through it. --- --- ## Robinhood Chain Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/robinhood/ Robinhood Chain DEX trades, transfers, balances, events and calls as Parquet, with column schemas and notes on USDG, tokenized equities and decimals. # Robinhood Chain Data Bitquery provides **Robinhood Chain data** as **Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), designed for large-scale analytics, historical backfills, and data lake integrations. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, etc**. Robinhood Chain is an **EVM network** (chain ID `4663`), so these exports use the **same schema as Bitquery's other EVM chains** — Ethereum, BSC, Base, Polygon. A query or loader written against `ethereum/` runs unchanged against `robinhood/`. What makes the chain distinctive is not the schema but what trades on it: **tokenized equities and RWAs** — `NVDA`, `SPY`, `SLV` — settle in the same `dex_trades` table as ordinary ERC-20s and memecoins, quoted against **USDG** rather than USDC. ## Available Robinhood Topics | Topic | Grain | What it holds | | --- | --- | --- | | `dex_trades` | one row per DEX trade | Buy and sell side with token metadata, USD amounts, pool and protocol | | `transfers` | one row per value movement | Native and ERC-20 transfers, with USD value and currency metadata | | `balances` | one row per address per currency | Balance snapshot with first and last change time, and update count | | `events` | one row per decoded log | Event logs with decoded arguments, topics, and the emitting call context | | `calls` | one row per contract call | Internal and top-level calls with decoded arguments, returns, and state changes | ## Sample Robinhood Cloud Dataset You can explore schemas and validate your tooling using the **public Robinhood sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/robinhood](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/robinhood) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood//.parquet ``` **Sample Parquet downloads (public S3)** - **DEX Trades** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood/dex_trades/56600000_56600049.parquet) - **Transfers** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood/transfers/56600000_56600049.parquet) - **Balances** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood/balances/56600000_56600049.parquet) - **Events** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood/events/56600000_56600049.parquet) - **Calls** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood/calls/56600000_56600049.parquet) All five samples cover the same 50 blocks, `56600000`–`56600049`: | Topic | Records | File size | | --- | ---: | ---: | | `calls` | 7,885 | 543 KB | | `events` | 2,211 | 283 KB | | `transfers` | 1,374 | 66 KB | | `balances` | 858 | 32 KB | | `dex_trades` | 277 | 100 KB | ## Robinhood Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── robinhood/ ├── balances/ │ ├── _.parquet │ └── ... ├── calls/ │ ├── _.parquet │ └── ... ├── dex_trades/ │ ├── _.parquet │ └── ... ├── events/ │ ├── _.parquet │ └── ... └── transfers/ ├── _.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Files hold **50 blocks** each, matching the other EVM chains — but Robinhood Chain produces roughly **10 blocks per second**, so a 50-block file is about **5 seconds** of activity, not the ten minutes the same range covers on Ethereum. The sample range spans `05:54:47` to `05:54:52` UTC. Size a backfill by time, not by file count: one hour of Robinhood Chain is roughly 720 files per topic. ## Common Columns Most topics share the same block and transaction context, which makes joining across topics straightforward: | Column | Type | Description | | --- | --- | --- | | `Block_Number` | `uint64` | Block height | | `Block_Date` | `date` | Date partition of the block | | `Block_Time` | `datetime` | Block timestamp (UTC) | | `Transaction_Hash` | `string` | Transaction hash — the join key across topics | | `Transaction_Index` | `uint64` | Position of the transaction within the block | | `TransactionStatus_Success` | `string` | `"true"` / `"false"` — a **string**, not a boolean | | `Fee_SenderFee` | `string` | Fee paid by the sender, as a decimal string | Nested structures are flattened with `_`, so `Trade { Buy { Currency { Symbol } } }` becomes `Trade_Buy_Currency_Symbol`. ## Correctness Notes Five things will silently produce wrong numbers if you treat these files casually. ### 1. Amounts Are Decimal Strings `Transfer_Amount`, `Trade_Buy_Amount`, `Trade_Sell_Amount`, `Balance_Amount`, and `Fee_SenderFee` are **strings**, preserving full token precision. Their `*InUSD` companions are floats. ```python from decimal import Decimal df["amount"] = df.Transfer_Amount.map(Decimal) # not .astype(float) ``` An 18-decimal token amount does not survive a float64 round trip. Use the string column for token quantities and the `InUSD` column for value. ### 2. Booleans Are Strings `TransactionStatus_Success`, `Transfer_Currency_Native`, `Transfer_Currency_Fungible`, `Call_Reverted`, and `Call_Success` hold `"true"` / `"false"` as text. `WHERE Call_Success` will not do what you expect — compare to the string: ```sql WHERE TransactionStatus_Success = 'true' ``` ### 3. Native ETH Is Not a `token` Transfer Robinhood Chain's native asset is ETH, carried with `Transfer_Currency_SmartContract = '0x'` and `Transfer_Currency_Native = 'true'`. It does **not** appear under `Transfer_Type = 'token'`. In the sample's 1,374 transfers: | `Transfer_Type` | Rows | What it is | | --- | ---: | --- | | `token` | 962 | ERC-20 movements | | `call` | 405 | Native ETH moved by an internal call | | `transaction` | 7 | Native ETH moved by the transaction itself | All 412 native rows are `call` or `transaction`. Filtering to `Transfer_Type = 'token'` silently drops every ETH movement on the chain. Filter currencies on the **contract address**, never the symbol — symbols are not unique. ### 4. The Quote Asset Is USDG, Not USDC Robinhood Chain settles in **USDG** (Global Dollar, `0x5fc5360d0400a0fd4f2af552add042d716f1d168`, **6 decimals**), not USDC. It is the most common side of a trade in the sample — 150 of 554 trade sides — followed by WETH (93) and native ETH (38). A pricing or volume query ported from Ethereum that hardcodes the USDC address returns **zero rows** here. ### 5. Tokenized Equities Share the ERC-20 Schema `NVDA`, `SPY`, and `SLV` are ordinary ERC-20 contracts with 18 decimals, indistinguishable from a memecoin by schema alone. **54 of the sample's 277 trades** have an equity token on one side — a fifth of all trading. | Symbol | Contract | Decimals | | --- | --- | ---: | | `NVDA` | `0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec` | 18 | | `SPY` | `0x117cc2133c37b721f49de2a7a74833232b3b4c0c` | 18 | | `SLV` | `0x411efb0e7f985935daec3d4c3ebaea0d0ad7d89f` | 18 | Maintain a contract allowlist if you need to separate RWA flow from crypto-native flow. Symbol matching is not safe: anyone can deploy a token called `NVDA`. ## DEX Venues Trades in the sample spread across six protocols, including **Pons**, which is native to Robinhood Chain: | `Trade_Dex_ProtocolName` | Family | Trades | | --- | --- | ---: | | `uniswap_v4` | Uniswap | 109 | | `uniswap_v3` | Uniswap | 106 | | `pons_v2` | Pons | 49 | | `uniswap_v2` | Uniswap | 7 | | `pancakeswap_infinity` | PancakeSwapInfinity | 5 | | `aerodrome_v1` | Aerodrome | 1 | Group on `Trade_Dex_ProtocolFamily` for venue-level aggregates and `Trade_Dex_ProtocolName` to separate versions. ## Topic Schemas Columns listed in [Common Columns](#common-columns) are omitted below. ### dex_trades One row per DEX trade. 277 rows in the sample, across 159 transactions. | Column | Type | Description | | --- | --- | --- | | `Trade_Buy_Amount`, `Trade_Sell_Amount` | string | Amounts, as decimal strings | | `Trade_Buy_AmountInUSD`, `Trade_Sell_AmountInUSD` | float64 | USD value of each side | | `Trade_Buy_Buyer`, `Trade_Buy_Seller` | string | Counterparties on the buy side | | `Trade_Sell_Buyer`, `Trade_Sell_Seller` | string | Counterparties on the sell side | | `Trade_Buy_Price`, `Trade_Buy_PriceInUSD` | float64 | Execution price, in the paired token and in USD | | `Trade_*_Currency_*` | mixed | `Symbol`, `Name`, `SmartContract`, `Decimals`, `ProtocolName`, `Fungible`, `HasURI` per side | | `Trade_Dex_SmartContract` | `string` | Router or pool manager contract | | `Trade_Dex_ProtocolName`, `_ProtocolFamily`, `_ProtocolVersion` | string | Venue identification | | `Trade_Dex_Pair_*` | mixed | Pair token metadata, where the protocol exposes one | | `Trade_Fees` | `string` | JSON array of `[Amount, AmountInUSD, [Currency…], Payer, Recipient]` | | `Trade_Index` | `uint32` | Trade position within the transaction | | `Trade_PriceAsymmetry` | `float64` | Price divergence between the two sides | | `Trade_Sender` | `string` | Address that initiated the swap | ### transfers One row per value movement, native and ERC-20. 1,374 rows in the sample, across 200 transactions. | Column | Type | Description | | --- | --- | --- | | `Transfer_Amount` | `string` | Amount, as a decimal string | | `Transfer_AmountInUSD` | `float64` | USD value | | `Transfer_Sender`, `Transfer_Receiver` | string | Counterparties | | `Transfer_Type` | `string` | `token`, `call`, or `transaction` — see note 3 above | | `Transfer_Currency_SmartContract` | `string` | Token contract; `0x` for native ETH | | `Transfer_Currency_Native` | `string` | `"true"` for native ETH | | `Transfer_Currency_Symbol`, `_Name`, `_Decimals`, `_ProtocolName` | mixed | Token metadata | | `Transfer_Currency_Fungible` | `string` | `"false"` marks NFTs | | `Transfer_Id` | `string` | Token id for non-fungible transfers | | `Transfer_Index` | `uint32` | Position within the transaction | | `Transfer_URI` | `string` | Token URI, for NFTs | ### balances Balance snapshot — levels, not deltas. 858 rows covering 427 distinct addresses in the sample. | Column | Type | Description | | --- | --- | --- | | `Balance_Address` | `string` | Account holding the balance | | `Balance_Amount` | `string` | Balance level, as a decimal string | | `Balance_FirstChangeTime`, `_LastChangeTime` | datetime | First and last change in the covered range | | `Balance_UpdateCount` | `uint64` | Number of balance changes in the range | | `Balance_RowCount` | `uint64` | Always `1` — a per-row marker | | `Currency_Name`, `_Symbol`, `_SmartContract`, `_ProtocolName` | string | Currency metadata | Only accounts whose balance changed in the range appear. Native ETH is 284 of the sample's 858 rows, ERC-20s 570, and ERC-721s 4. ### events One row per decoded log. 2,211 rows across 33 distinct decoded event names in the sample, plus 384 logs with no decoded name. | Column | Type | Description | | --- | --- | --- | | `Arguments` | `string` | JSON array of `[Index, Name, Path, Type, Value]` | | `Log_Signature_Name`, `_Signature`, `_SignatureHash` | string | Decoded event signature — `Transfer` (964), `Swap` (229), `Approval` (194) | | `Log_SmartContract` | `string` | Contract that emitted the log | | `Log_Index`, `Log_Pc` | uint32, uint64 | Log position and program counter | | `LogHeader_Address`, `_Data`, `_Index` | mixed | Raw log address, data, and index | | `Topics_Hash` | list\ | Topic hashes, **without** the `0x` prefix | | `Call_*` | mixed | The call that emitted the log — `From`, `To`, `Gas`, `Signature_Name`, `Value` | | `ChainId` | `uint64` | `4663` on every row | 384 of the sample's rows have an empty `Log_Signature_Name` — logs whose ABI Bitquery has not resolved. Their `LogHeader_Data` and `Topics_Hash` are still present, so you can decode them yourself. ### calls One row per contract call, internal calls included. 7,885 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `Call_From`, `Call_To` | string | Caller and callee | | `Call_Value`, `Call_ValueInUSD` | string, float64 | Native value attached to the call | | `Call_Signature_Name`, `_Signature`, `_SignatureHash` | string | Decoded function — `balanceOf` (2,136), `transfer` (995), `transferFrom` (394) | | `Call_Input`, `Call_Output` | string | Raw calldata and return data | | `Arguments`, `Returns` | string | JSON arrays of `[Index, Name, Path, Type, Value]` | | `StateChanges` | `string` | JSON array of `[Address, ChangeAfterCallIndex, Location, Value]` | | `Call_Gas`, `_GasUsed` | uint64 | Gas supplied and consumed | | `Call_Depth`, `_Index`, `_CallPath` | mixed | Position in the call tree | | `Call_InternalCalls`, `_LogCount` | uint32 | Children and logs produced | | `Call_Success`, `_Reverted`, `_Error` | string | Outcome — strings, not booleans | | `Call_Opcode_Name`, `_Code` | string, uint32 | Call opcode, e.g. `CALL`, `STATICCALL`, `DELEGATECALL` | | `Call_Create`, `_SelfDestruct`, `_Delegated` | string | Contract creation, destruction, and delegation flags | Read-only calls dominate: `balanceOf` alone is 27% of the sample. Filter on `Call_Signature_Name` before aggregating, or you will measure RPC-style reads rather than economic activity. ## Joining Topics Every topic except `balances` carries `Transaction_Hash`, so it is the natural join key. To attach trades to the events that produced them: ```sql SELECT t.Trade_Dex_ProtocolName, t.Trade_Buy_Currency_Symbol, t.Trade_Buy_AmountInUSD, e.Log_Signature_Name FROM robinhood_dex_trades t JOIN robinhood_events e ON t.Transaction_Hash = e.Transaction_Hash WHERE t.TransactionStatus_Success = 'true' AND e.Log_Signature_Name = 'Swap' ``` One transaction fans out to many rows in `calls`, `events`, and `transfers`, so joining two of them on `Transaction_Hash` alone produces a cross product. Aggregate one side first, or add `Block_Number` and the per-row index columns to the join. ## Reading Files in Python ```python from decimal import Decimal BASE = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood/" RANGE = "56600000_56600049" trades = pd.read_parquet(f"{BASE}dex_trades/{RANGE}.parquet") transfers = pd.read_parquet(f"{BASE}transfers/{RANGE}.parquet") # venue mix print(trades.Trade_Dex_ProtocolName.value_counts()) # tokenized equity flow, by contract not symbol EQUITIES = { "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec", # NVDA "0x117cc2133c37b721f49de2a7a74833232b3b4c0c", # SPY "0x411efb0e7f985935daec3d4c3ebaea0d0ad7d89f", # SLV } eq = trades[ trades.Trade_Buy_Currency_SmartContract.isin(EQUITIES) | trades.Trade_Sell_Currency_SmartContract.isin(EQUITIES) ] print(f"equity-side trades: {len(eq)} of {len(trades)}") # native ETH is NOT Transfer_Type == 'token' native = transfers[transfers.Transfer_Currency_Native == "true"] print("native ETH moved:", sum(native.Transfer_Amount.map(Decimal))) print("types carrying it:", native.Transfer_Type.unique()) ``` ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets?network=robinhood) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). Datasets you can buy on the Data Store: - [Pons](https://bitquery.io/datastore/datasets/pons) — every Pons launch, bonding-curve trade and graduation on Robinhood Chain, priced in USD This listing is not the full catalogue. Other topics, chains and date ranges are available on request from **sales@bitquery.io**. ## Real-Time vs Batch Data Access Data Store exports are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming Robinhood Chain data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - [**Robinhood Chain APIs**](/docs/blockchain/robinhood/) --- ## Robinhood Chain Explorer API: Look Up Any Address, Transaction, Token or Block (chain id 4663) URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-chain-explorer-api/ Build a Robinhood Chain block explorer with Bitquery GraphQL: address balance and transfers, transaction transfers and calls, token holders and trades, live blocks and transactions on chain id 4663. # Robinhood Chain Explorer API: Look Up Any Address, Transaction, Token or Block (chain id 4663) Every screen of a block explorer is one query away on [Robinhood Chain](/docs/blockchain/robinhood/) (`EVM(network: robinhood)`, chain id **4663**). This page maps the explorer screens people open most (address, transaction, token, latest blocks and latest transactions) to one tested Bitquery GraphQL query each. Use them to look things up from code, power your own explorer UI, or stream new blocks and transactions over WebSocket instead of polling an RPC node. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: **On this page:** [Address](#address-page) · [Transaction](#transaction-page) · [Token](#token-page) · [Latest blocks](#latest-blocks) · [Latest transactions](#latest-transactions) · [Build an explorer UI](#build-an-explorer-ui) | Explorer screen | Bitquery cubes | Dataset | | --- | --- | --- | | Address | `Balances` + `Transfers` | `combined` | | Transaction | `Transfers` + `Calls` | `combined` | | Token | `Holders` + `Trading.Trades` | `archive` for holders; `Trading` for trades | | Latest blocks | `Blocks` (subscription) | realtime | | Latest transactions | `Transactions` (subscription) | realtime | --- ## Address page {#address-page} An explorer address page shows the native ETH balance and the latest transfers in and out. One query returns all three: `Balances` filtered to `Currency.Native: true` for the ETH balance, and two aliased `Transfers` lists, `incoming` (address is the receiver) and `outgoing` (address is the sender). Replace the address with any wallet or contract and move the time window to the days you want. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-address-eth-balance-and-latest-transfers) ```graphql { EVM(network: robinhood, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xc2e2063b468fe3e63316c85d2af36adf9b4d5c80" } } Currency: { Native: true } } ) { Currency { Symbol Native } Balance { Amount } } incoming: Transfers( where: { Transfer: { Receiver: { is: "0xc2e2063b468fe3e63316c85d2af36adf9b4d5c80" } Success: true } Block: { Time: { since_relative: { days_ago: 7 } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } Transaction { Hash } Transfer { Sender Amount AmountInUSD Currency { Symbol SmartContract Native } } } outgoing: Transfers( where: { Transfer: { Sender: { is: "0xc2e2063b468fe3e63316c85d2af36adf9b4d5c80" } Success: true } Block: { Time: { since_relative: { days_ago: 7 } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time Number } Transaction { Hash } Transfer { Receiver Amount AmountInUSD Currency { Symbol SmartContract Native } } } } } ``` For the full token portfolio of the address, balance history and multi-address batches, see the [Robinhood Balances API](/docs/blockchain/robinhood/robinhood-balances-api/). For more transfer filters (USD thresholds, counterparties, a live wallet tracker), see the [Robinhood Transfers API](/docs/blockchain/robinhood/robinhood-transfers/). --- ## Transaction page {#transaction-page} A transaction page lists the token transfers and the internal calls of one transaction hash. Query `Transfers` and `Calls` side by side, both filtered by `Transaction.Hash`. The example is a swap transaction from 7 November 2026; the time window around its block keeps the lookup small, so set it to the day of the transaction you open. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-transaction-transfers-and-calls-by-hash) ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Transaction: { Hash: { is: "0xc21dcd9689ef5864f9754dd704f6920ea21518dc4af6c9d3ee32047ea00e5592" } } Block: { Time: { since: "2026-11-07T00:00:00Z", till: "2026-11-08T00:00:00Z" } } } limit: { count: 50 } orderBy: { ascending: Transfer_Index } ) { Block { Time Number } Transfer { Index Sender Receiver Amount AmountInUSD Success Currency { Symbol SmartContract Native } } } Calls( where: { Transaction: { Hash: { is: "0xc21dcd9689ef5864f9754dd704f6920ea21518dc4af6c9d3ee32047ea00e5592" } } Block: { Time: { since: "2026-11-07T00:00:00Z", till: "2026-11-08T00:00:00Z" } } } limit: { count: 50 } orderBy: { ascending: Call_Index } ) { Transaction { From To } Call { Index CallerIndex From To Value Success GasUsed Signature { Name } } } } } ``` `Call.CallerIndex` points at the parent call, so you can rebuild the call tree. Receipts, gas, fee fields and the decoded logs of a transaction are on the [Robinhood Transactions & Receipts API](/docs/blockchain/robinhood/robinhood-transactions-receipts-api/), and the full trace of a transaction is on the [Robinhood Calls & Traces API](/docs/blockchain/robinhood/robinhood-calls-api/#full-call-tree-of-a-transaction). --- ## Token page {#token-page} A token page shows who holds the token and its latest trades. This query does both in one request: `EVM.Holders` on `dataset: archive` for the top 10 holders, and `Trading.Trades` for the 10 newest trades with USD amounts. The example token is PONS (`0x39dbed3a2bd333467115de45665cc57f813c4571`), the token of the [Pons launchpad](/docs/blockchain/robinhood/pons-api/). [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-token-top-holders-and-latest-trades) ```graphql { EVM(network: robinhood, dataset: archive) { Holders( where: { Currency: { SmartContract: { is: "0x39dbed3a2bd333467115de45665cc57f813c4571" } } } limit: { count: 10 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount LastChangeTime } } } Trading { Trades( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Pair: { Token: { Address: { is: "0x39dbed3a2bd333467115de45665cc57f813c4571" } } Market: { NetworkBid: { is: "bid:robinhood" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Block { Time } Trader { Address } Side Amounts { Base Quote } AmountsInUsd { Base } Pair { Token { Symbol } QuoteToken { Symbol } } TransactionHeader { Hash } } } } ``` Holder counts, distribution stats and dormant holders are on the [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/). Price, OHLCV candles, market cap and top traders are on the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades/). --- ## Latest blocks {#latest-blocks} The explorer home page shows new blocks as they are produced. This subscription pushes every new Robinhood Chain block with its hash, transaction count, gas used and base fee. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-latest-blocks-stream) ```graphql subscription { EVM(network: robinhood) { Blocks { Block { Number Time Hash TxCount GasUsed GasLimit BaseFee Coinbase } } } } ``` --- ## Latest transactions {#latest-transactions} The second list on an explorer home page is the newest transactions. This subscription pushes each transaction with its sender, receiver, ETH value, gas used and status. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-latest-transactions-stream) ```graphql subscription { EVM(network: robinhood) { Transactions { Block { Number Time } Transaction { Hash From To Value } Receipt { GasUsed } TransactionStatus { Success } } } } ``` :::tip WebSocket connection Connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol. See [WebSocket authentication](/docs/authorization/websocket/). Change `subscription` to `query` and add `limit` and `orderBy: { descending: Block_Time }` to load the latest rows once before the stream starts. ::: --- ## Build an explorer UI {#build-an-explorer-ui} The five queries above are the data layer of an explorer: 1. **Home page**: open the [latest blocks](#latest-blocks) and [latest transactions](#latest-transactions) subscriptions on one WebSocket and prepend each event to its list. 2. **Search box**: route a 66-character `0x` hash to the [transaction page](#transaction-page) query and a 42-character address to the [address page](#address-page) query. If the address is a token contract, also show the [token page](#token-page). 3. **Detail pages**: fill each page from its query, and link every hash and address in the results back to the matching page. For more depth on each screen, reuse the queries on the existing guides instead of writing new ones: trades, price charts and top traders from the [Robinhood Chain DEX Trades API](/docs/blockchain/robinhood/robinhood-trades/), and holder rankings and distribution from the [Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/). --- ## Video Tutorial | Who Are the Biggest Wallets on Robinhood Chain? Top Traders and Top Holders --- --- ## Robinhood Chain: Chain ID 4663, RPC, Explorer, Bridge and Native Token URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-chain-rpc-chain-id/ Robinhood Chain network facts: chain ID 4663, public RPC URL, Blockscout explorer, Arbitrum canonical bridge and ETH gas token, from the official docs. # Robinhood Chain: Chain ID 4663, RPC, Explorer, Bridge and Native Token **Robinhood Chain** mainnet has chain ID **4663**, pays gas in **ETH**, and runs as an Arbitrum Layer-2 chain on Ethereum. This page lists the official network values (RPC URL, block explorer, bridge, testnet) in one table, then shows how to read the chain's blocks and transactions with Bitquery GraphQL without running an RPC node. For every Robinhood Chain data page (trades, transfers, balances, holders, launchpads), start at the [Robinhood Chain hub](/docs/blockchain/robinhood/). --- ## Robinhood Chain network facts {#network-facts} Every value below comes from the official Robinhood Chain documentation: [Connecting to Robinhood Chain](https://docs.robinhood.com/chain/connecting/), [Add network to your wallet](https://docs.robinhood.com/chain/add-network-to-wallet/), [Bridging](https://docs.robinhood.com/chain/bridging/), [About Robinhood Chain](https://docs.robinhood.com/chain/) and [Run a full node](https://docs.robinhood.com/chain/run-a-full-node/). | Property | Robinhood Chain (mainnet) | Robinhood Chain Testnet | | --- | --- | --- | | Network name | Robinhood Chain | Robinhood Chain Testnet | | Chain ID | `4663` | `46630` | | Native token (currency symbol) | ETH | ETH | | Public RPC URL (rate-limited) | `https://rpc.mainnet.chain.robinhood.com` | `https://rpc.testnet.chain.robinhood.com` | | Provider RPC (Alchemy, recommended) | `https://robinhood-mainnet.g.alchemy.com/v2/{API_KEY}` | `https://robinhood-testnet.g.alchemy.com/v2/{API_KEY}` | | Block explorer | [robinhoodchain.blockscout.com](https://robinhoodchain.blockscout.com/) | [explorer.testnet.chain.robinhood.com](https://explorer.testnet.chain.robinhood.com/) | | Canonical bridge | [Arbitrum canonical bridge](https://portal.arbitrum.io/bridge?destinationChain=robinhood-chain&sourceChain=ethereum) (deposit ~10 min, withdrawal ~7 days) | — | | Stack | Arbitrum Layer-2 chain built with Arbitrum Orbit (now called Arbitrum Dedicated Blockchains), running Arbitrum Nitro; Ethereum blobs for data availability | Same | | Parent chain | Ethereum | — | | Bitquery network name | `robinhood` in `EVM(network: robinhood)`; `bid:robinhood` in the `Trading` cubes | — | The official docs mark the public RPC endpoints as rate-limited and not recommended for production; for production they point to providers such as Alchemy, Chainstack, QuickNode, Blockdaemon, dRPC, Validation Cloud, GlobalStake and Pinax ([full list](https://docs.robinhood.com/chain/connecting/)). Besides the canonical bridge, the [Bridging](https://docs.robinhood.com/chain/bridging/) page lists LayerZero OFT / Stargate, Chainlink CCIP / Transporter, Relay, Across and LiFi / 0x as cross-chain routes. --- ## Query Robinhood Chain without running an RPC node {#query-without-rpc} An RPC endpoint answers one call at a time about one block, transaction or address. Bitquery indexes Robinhood Chain and serves the same blocks and transactions over one GraphQL endpoint (`https://streaming.bitquery.io/graphql`), with filters, sorting and aggregation, and any query can run as a live WebSocket subscription. To run these outside the IDE you need an API token: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/). ### Latest block (eth_blockNumber equivalent) Returns the newest Robinhood Chain block with its number, time, hash, gas used and transaction count. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-latest-block) ```graphql query { EVM(network: robinhood) { Blocks(limit: {count: 1}, orderBy: {descending: Block_Number}) { Block { Number Time Hash GasUsed GasLimit BaseFee TxCount } } } } ``` ### Stream new transactions (eth_subscribe equivalent) Pushes every new Robinhood Chain transaction over WebSocket as it lands in a block, with sender, receiver, value, gas used and status. [Run this query in the IDE](https://ide.bitquery.io/robinhood-chain-new-transactions-stream) ```graphql subscription { EVM(network: robinhood) { Transactions { Block { Number Time } Transaction { Hash From To Value } Receipt { GasUsed } TransactionStatus { Success } } } } ``` Connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol. See [WebSocket authentication](/docs/authorization/websocket/). ### More Robinhood Chain data - [Robinhood Chain DEX Trades API & Streams](/docs/blockchain/robinhood/robinhood-trades/): swaps with USD prices, OHLC and live trade streams. - [Pons Launchpad API](/docs/blockchain/robinhood/pons-api/): Pons launches, bonding-curve trades and graduations. - [Transactions & Receipts](/docs/blockchain/robinhood/robinhood-transactions-receipts-api/): block receipts, single receipts and transaction lookups that replace the JSON-RPC receipt methods. - [Transfers](/docs/blockchain/robinhood/robinhood-transfers/), [Balances](/docs/blockchain/robinhood/robinhood-balances-api/) and [Token Holders](/docs/blockchain/robinhood/robinhood-token-holders-api/): address and token lookups. - [Events](/docs/blockchain/robinhood/robinhood-events-api/) and [Calls](/docs/blockchain/robinhood/robinhood-calls-api/): decoded contract logs and internal traces. --- ## FAQ {#faq} --- ## Run Queries in Bitquery IDE URL: https://docs.bitquery.io/docs/ide/query/ Run Queries in Bitquery IDE in Bitquery docs with practical setup steps, examples, and guidance for secure API access. See examples in the Bitquery IDE. # Create Query Creating a query in IDE is very easy, on the left you can see the endpoint schema, which will help you to create a query quickly and easily. ![Create Query](/img/ide/ide_schema.png) You can go to the following entries to learn more: - [Share Query](/docs/ide/share) - [Save Query Privately](/docs/ide/private) - [Search Queries](/docs/ide/search) Each run shows the **points** it consumed, so you can gauge query cost before scaling up — see [how billing works](/docs/plans/how-billing-works/). Make sure your token targets the V2 endpoint (`streaming.bitquery.io/graphql`); see [how to generate a token](/docs/authorization/how-to-generate/). --- ## Search Queries in Bitquery IDE URL: https://docs.bitquery.io/docs/ide/search/ Search Queries in Bitquery IDE in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Search Queries You will be able to search among the queries shared by users (as well as among your own queries), to do this you must go to the top left corner, see: ![IDE Query Search](/img/ide/query_search.png) Search covers both the public queries shared by other users and your own saved queries, so it's a fast way to find a working example before writing a query from scratch. ## Next steps - [Create a query](/docs/ide/query/) - [Save a query privately](/docs/ide/private/) - [Share a query](/docs/ide/share/) --- ## Select Rows by GraphQL Metric URL: https://docs.bitquery.io/docs/graphql/metrics/selectWhere/ Select By Metric in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Keep queries fast with indexed filters. # Select By Metric A metric value can be used to filter the result with the ```selectWhere``` attribute, which defines a condition applied to the **computed metric** rather than to the input rows. It is the GraphQL equivalent of SQL's `HAVING`. This expression filters balances to positive values only: ``` sum(of: BalanceUpdate_Amount selectWhere: {gt: "0"}) ``` ## Where it applies in the pipeline `selectWhere` runs **after** aggregation and **before** ordering and limiting, so a filtered result is complete rather than a filtered page: ``` where → GROUP BY → selectWhere (HAVING) → orderBy → limitBy → limit ``` This matches ClickHouse's own clause order, and it determines what `limitBy` means: `limitBy` takes the top N per key **from the rows that already passed `selectWhere`**. A key with fewer than N survivors simply returns fewer rows — it is not padded with rows that are then filtered away. ## Operators The operator set depends on **what you attach `selectWhere` to** — there are four shapes: | Attached to | Type | Operators | | --- | --- | --- | | An aggregate metric (`sum`, `count`, `median`, …) | `Metric_filter_String` / `_Float` | `gt` `ge` `lt` `le` `eq` `ne` | | A **numeric** field-level selector | `OLAP_Float` | the same six | | A **string** field-level selector | `OLAP_String` | the full 15-operator string set — `like`, `startsWith`, `includes`, `not`, … | | A boolean leaf field | `Boolean` | a bare value: `selectWhere: true` | There is **no `between`** on any of them. Multiple clauses in one `selectWhere` are combined with AND, so express a range with `ge` and `le` together: ``` sum(of: Volume_Usd selectWhere: {ge: "10000" le: "1000000"}) ``` `in` and `notIn` are absent from the metric filters. They appear in the `OLAP_String` schema but **fail at runtime**, so use `like` / `startsWith` instead, or move set membership into the cube's own `where:` clause where `in` is supported normally. ## Literal types The literal type matches the **metric's own return type**. `sum`, `count` and `uniq` return JSON strings and therefore take string literals; every Float-returning metric takes a numeric literal. Passing the wrong one is a clean schema error, not a silent failure. String literals are compared **numerically, not lexicographically** — `"100"` is greater than `"20"`. :::note You can combine this attribute with other attributes, including conditions in ```if```. Combining `if` and `selectWhere` on the same metric gives a conditional HAVING — for example, filtering to wallets whose **buy-side** volume alone exceeds a threshold. ::: :::caution Not available on every field, and not on streams On a bare field that has no selector argument, `selectWhere` is accepted and is a **silent no-op** — it neither filters nor errors. Attach it to a metric. `selectWhere` is **not available in subscriptions**. See [what does not survive streaming](/docs/subscriptions/what-does-not-survive-streaming/). ::: --- ## Separate Development and Production Usage with Team Members URL: https://docs.bitquery.io/docs/authorization/separate-dev-production/ Split Bitquery API points between development and production by giving each environment its own team member account, with its own API tokens, on one shared plan. # Separate Development and Production Usage Bitquery reports API points **per account**, not per API key or token. All tokens created under one account add up to one usage number. To see development and production usage apart, give each environment (or each developer) its own **team member account** on your plan. Every member creates their own API tokens. Points are still paid from your one plan, but the team admin sees them split per member. ## Why not one account with two keys - Usage is counted per account, so two tokens on one account show one total. - Everyone who signs in to that account can see and use every token, including production ones. With team members, each person holds only their own tokens. Production tokens stay with the production account. ## How it works - The **team admin** owns the plan and pays for it. - **Team members** use the admin's billing period: the same points and limits. - Each member signs in with their own email and creates their own applications and tokens. - The admin sees points used by each member under **Team → Points consumption**. ![Team members page with a dev and a production member](/img/ide/team-members-dev-prod.png) ## Set it up ### 1. Invite a member per environment Sign in to [account.bitquery.io](https://account.bitquery.io/) with the account that owns the plan. Open **Team → Members** and invite a member by email, for example: - `dev@yourcompany.com` for development and testing - `prod@yourcompany.com` for your production service You can also invite each developer with their own email instead of one shared dev account. The number of members is limited by your plan. See [Develop in Team](/docs/ide/team/) for team size and pricing. ### 2. Create tokens in each member account Each member accepts the invite and signs in to [account.bitquery.io](https://account.bitquery.io/). The dashboard shows that the account uses the team admin's billing period. Then each member creates their own application and token under **Authorization → Applications**. See [How to Generate a Token](/docs/authorization/how-to-generate/). Use the dev member's token in development and the production member's token in production. ### 3. Check usage per member As team admin, open **Team → Points consumption**. For each member it shows: - Points for the last 32 days and the last 2 days - API calls for the last 32 days and the last 2 days ![Points consumption per team member](/img/ide/team-points-consumption-dev-prod.png) :::note Usage API returns the shared plan The [Usage API](/docs/authorization/usage-api/) called with a member's token returns the **team admin's** billing period, so it shows the total for the whole plan. Use **Team → Points consumption** for the per-member split. ::: ## When someone leaves Remove their member account from **Team → Members**. Tokens in the other member accounts, including production, are not affected. --- ## Setting Up App.js URL: https://docs.bitquery.io/docs/usecases/tradingview-subscription-realtime/final-step/ Build Setting Up App.js: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. See examples in the Bitquery IDE. # Setting Up `App.js` To complete the setup and run the chart, we need to call the `TVChartContainer` component inside the main `App.js` file. Here's the process: --- ### 1. `App.js` ```javascript function App() { return (
); } export default App; ``` - **App.js**: This is the entry point of your React app. It imports the `TVChartContainer` component, which encapsulates the TradingView chart logic. The component is rendered inside a `div` with the class `App`. --- ### 2. Run the Application Now that you have set up `App.js`, you can run the application using the following command: ```bash npm start ``` #### Opening the URL The sample code uses the token address from the url, so you should pass it like this for example: ``` http://localhost:3000/?base=So11111111111111111111111111111111111111112"e=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v ``` This will start the development server, and your TradingView chart with both historical and real-time OHLC data should now be visible. --- ## Setting up Google Pub-Sub URL: https://docs.bitquery.io/docs/subscriptions/google-bigquery/pub-sub/ Setting up Google Pub-Sub using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Setting up Google Pub-Sub This tutorial walks through a process of subscribing to the Bitquery Streaming API and publishing its data to a Google Cloud Pub/Sub topic. ### 1. Set Up Google Cloud Pub/Sub 1. Create a Pub/Sub Topic: - Go to the [Google Cloud Console](https://console.cloud.google.com/). - Navigate to Pub/Sub > Topics. - Create a new topic named `bitquery-data-stream`( this is an example). ![Google Pub/Sub data pipeline diagram](/img/diagrams/pubsub.png) 2. Create a Subscription: - Click on the topic and create a subscription (e.g., `test1d`). - Choose Pull or Push, depending on your architecture. 3. Service Account Configuration: - Create a service account with the role `Pub/Sub Publisher`. - Download the service account key as `key.json`. --- ### 2. Writing Code - Install Required Libraries Now we will setup the code to publish messages to the subscribers. Install the Python libraries needed for WebSocket communication and Pub/Sub interaction: ```bash pip install websockets google-cloud-pubsub ``` --- ### 3. Write the Script #### Imports and Setup Set up the necessary imports and environment variables: ```python from google.cloud import pubsub_v1 # Set Google Application Credentials os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json" ``` #### Bitquery WebSocket API Details Configure the WebSocket URL and the query to fetch Pumpfun DEX trades. To learn how to generate a token to use with the url, go [here](/docs/authorization/how-to-generate/) ```python url = "wss://streaming.bitquery.io/graphql?token=" query = """ subscription MyQuery { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "pump" } } } Transaction: { Result: { Success: true } } } ) { Trade { Dex { ProtocolFamily ProtocolName } Buy { Amount Account { Address } } Sell { Amount Account { Address } } } Transaction { Signature } } } } """ ``` #### Google Pub/Sub Configuration Set up the Pub/Sub publisher: ```python project_id = "your project id" topic_id = "bitquery-data-stream" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) ``` #### Fetch and Publish Function Handle WebSocket communication and Pub/Sub publishing: ```python async def fetch_and_publish(): async with websockets.connect(url, subprotocols=["graphql-ws"]) as websocket: # Step 1: Initialize connection await websocket.send(json.dumps({"type": "connection_init"})) # Wait for connection acknowledgment while True: response = await websocket.recv() response_data = json.loads(response) if response_data.get("type") == "connection_ack": print("Connection acknowledged.") break # Step 2: Send subscription query await websocket.send(json.dumps({"type": "start", "id": "1", "payload": {"query": query}})) # Step 3: Listen and publish messages to Pub/Sub while True: response = await websocket.recv() data = json.loads(response) # Process pumpfun data if data.get("type") == "data" and "payload" in data: trades = data['payload']['data'].get('Solana', {}).get('DEXTrades', []) for trade in trades: message = { "protocol_family": trade['Trade']['Dex']['ProtocolFamily'], "protocol_name": trade['Trade']['Dex']['ProtocolName'], "buy_amount": trade['Trade']['Buy']['Amount'], "buy_account": trade['Trade']['Buy']['Account']['Address'], "sell_amount": trade['Trade']['Sell']['Amount'], "sell_account": trade['Trade']['Sell']['Account']['Address'], "transaction_signature": trade['Transaction']['Signature'] } await publish_to_pubsub(message) ``` #### Publish to Pub/Sub Create a function to publish messages to Pub/Sub: ```python async def publish_to_pubsub(message): print(f"Publishing message: {message}") future = publisher.publish(topic_path, json.dumps(message).encode("utf-8")) future.result() # Wait for the message to be successfully published print("Message published.") ``` #### Main Function Handle errors and run the WebSocket fetch: ```python async def main(): try: await fetch_and_publish() except Exception as e: print(f"Error occurred: {e}") # Run the main function asyncio.run(main()) ``` ### 4. Part 2 - Setup Data Write to Bigquery Next, we will create a subscriber to write this data to a Bigquery Table ### 5. Architecture Overview - WebSocket Client: Fetches live data from Bitquery. - Google Pub/Sub: Acts as a message bus for downstream consumers. - Downstream Processing: Consume and process data from Pub/Sub using Bigquery, Dataflow, or other analytics tools. --- ### 6. Debugging Tips - Use `print()` statements or logging to debug errors. - Ensure your WebSocket token and Pub/Sub credentials are valid. - Test Pub/Sub message flow using the Pub/Sub console. --- ## Share Bitquery IDE Queries URL: https://docs.bitquery.io/docs/ide/share/ Share Bitquery IDE Queries in Bitquery docs with practical setup steps, examples, and guidance for secure API access. See examples in the Bitquery IDE. # Share Query In the IDE you can share your queries, this way you can allow other people to see and use your query. To do this you will have to select the `Shared to everyone` checkbox and then press the `Save` button. ![IDE Query Share](/img/ide/query_share.png) :::tip Tags are very useful to organize queries, this way it is easier to find them, try to use them! ::: --- ## Share, Manage and Export MoneyFlows - Links, Reports, Layouts URL: https://docs.bitquery.io/docs/moneyflow-lite/share-and-manage/ Share a MoneyFlow with a public link, find saved traces in the MoneyFlows list, download reports, change the date range, customise the panel layout and read the trace summary in MoneyFlow Lite. # Share and Manage MoneyFlows ## Share a MoneyFlow Click the share icon to the left of the title. The **Share** dialog explains that it creates a public link anyone can open. Only the MoneyFlow data is shared, nothing else from your account. ![Share dialog](/img/moneyflow-lite/share-dialog.jpg) 1. Check the preview. 2. Edit the **Name** if you want the shared page to carry a different title. 3. Click **Share** and copy the link. Shared MoneyFlows show a link icon in the **Shared** column of the MoneyFlows list. ## Trace summary The **i** icon in the toolbar opens a summary of the current MoneyFlow: ![MoneyFlow summary popup](/img/moneyflow-lite/moneyflow-summary.jpg) - **Addresses**: the origin address. - **Selected date range**. - **Created on** and **Last update**. - **Currencies** traced. - **Creator**: the account that created it. - **Tracing Method**, for example First-in, First-out. **New Tag** here tags the whole MoneyFlow. ## Change the date range The calendar button in the toolbar opens **Change Date Range**. Pick a new start and end and click **Create New MoneyFlow**. The app creates a separate MoneyFlow for the same address with the new range. The original is kept. ![Change date range dialog](/img/moneyflow-lite/change-date-range.jpg) ## Panel layout The layout icon at the right end of the toolbar opens the **Layout** panel. ![Layout panel](/img/moneyflow-lite/layout-panel.jpg) - **Panels**: show or hide **Moneyflow** (the chart), **Details** (the address or edge panel) and **Transactions**. - Each panel also has an expand icon for full screen and an **x** to close it. - **Save current layout** stores the arrangement. **Create new layout** saves it under a name so you can switch between layouts. ## MoneyFlows list The list icon in the top bar opens the **MoneyFlows** page, which lists every trace saved under your account. ![MoneyFlows list](/img/moneyflow-lite/moneyflows-list.jpg) | Column | Meaning | | --- | --- | | **Created on** | Creation time. Click the header to sort. | | **Address** | Origin address. | | **Date range** | Range used for the trace. | | **Name** | Title. Click it to open the MoneyFlow. | | **Tags** | Your tags, with **New Tag** to add one. | | **Shared** | A link icon when a public link exists. | ## Reports The **Reports** tab on the same page lists the reports created with **Generate report** in an address panel. Each row has the creation time, the document and its **Status**. Download the report from here once it is ready. ## Get API Every panel has a **Get API** button that opens the Coinpath® query behind it in the Bitquery IDE. See [Get API](/docs/moneyflow-lite/get-api-coinpath-query). ## Account menu The avatar in the top-right corner shows your email and offers: - **Account Settings**: opens [account.bitquery.io](https://account.bitquery.io/). - **Theme**: system, light or dark. - **Logout**. The **?** icon next to the avatar opens the Bitquery support form. --- ## Smart Contract Creation URL: https://docs.bitquery.io/docs/blockchain/Ethereum/calls/contract-creation/ Ethereum contract creation: subscribe to new smart contract deployments in real time, list creations since a date, get code, deployer and contract type. # Smart Contract Creation Smart contract creators can use these queries to track the deployment of their own smart contracts and to monitor the deployment of new smart contracts by others. ## Subscription to track new smart contract creation in real-time This subscription will return information on each new smart contract created on Ethereum. You can create a [websocket](/docs/subscriptions/websockets/) to monitor the same in real-time. ```graphql subscription { eth_creates: EVM(network: eth) { creates: Calls( where: { Call: { Create: true }}) { Block { Time } Transaction{ Hash From } Call { Input To Output } } } } ``` This subscription has information on - The block time in which the smart contract was created - The transaction hash that created the smart contract - The address of the sender of the transaction that created the smart contract - The address of the newly created smart contract - The input data for the transaction that created the smart contract - The output data from the transaction that created the smart contract ## Track new smart contract creation since a specific date This query below, will return the number of new smart contracts created on the Ethereum and Binance Smart Chain networks since a particular date. It will also return the date of each day on which new smart contracts were created. You can find the query [here](https://ide.bitquery.io/ETHBSC-SC-creates-count-over-date) ```graphql query { eth_creates: EVM(dataset: archive network: eth) { creates: Calls( where: { Block: {Date: {after: "2023-06-01"}} Call: { Create: true }}) { count Block { Date } } } bsc_creates: EVM(dataset: archive network: bsc) { creates: Calls( where: { Block: {Date: {after: "2023-06-01"}} Call: { Create: true }}) { count Block { Date } } } } ``` ## Get Code of the Token Contract This query will return the most recent transaction that created the token contract. The `Output` field of the Call object in the transaction contains the encoded bytecode of the contract. Replace `0xc923D39fA2d97fb4B660Fc66DAdB1421605975E0` with the token contract address that you want to get the code for. You can find the query [here](https://ide.bitquery.io/ByteCode-of-A-Token) ```graphql { eth_creates: EVM(dataset: archive, network: eth) { creates: Calls( where: {Call: {Create: true, To: {is: "0xc923D39fA2d97fb4B660Fc66DAdB1421605975E0"}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { Block { Time } Transaction { Hash From To } Call { Output } } } } ``` ## Creator/Deployer of a smart contract You can use calls api to get smart contract creator or deployer of a smart contract. In the following example, where we getting deployer of deployer of `0xcd80c916b1194beb48abf007d0b79a7238436d56`. Try this query [here](https://ide.bitquery.io/creator--deployer-of-an-address_1). ```graphql { EVM(dataset: combined) { Calls( where: {Call: {Create: true}, Receipt: {ContractAddress: {is: "0xcd80c916b1194beb48abf007d0b79a7238436d56"}}} ) { Transaction { Hash From To } Block { Time Number } } } } ``` ## Get Contract Type of a Contract To determine the type of a contract and its details, we can use the Transfer API. By fetching the earliest transfer to the contract, we can get relevant details that indicate the contract type. `Abi`: Provides the contract function ABI, describing its inputs and structure. For example, `"Name": "swap",` tells us the given address has a **`swap`** function. This suggests the contract is likely a **DEX (Decentralized Exchange) or token swap contract**. You can run the query [here](https://ide.bitquery.io/Get-Contract-Type-in-v2) ```graphql query MyQuery { EVM(network: eth) { Transfers( limit: {count: 1} orderBy: {ascending: Block_Time} where: {Transfer: {Receiver: {is: "0x881d40237659c251811cec9c364ef91dc08d300c"}}} ) { Call { Create Signature { SignatureType Signature Parsed Name Abi } } } } } ``` --- ## Smart Contract Events on Robinhood Chain — Logs & WebSocket Streams URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-events-api/ Stream every Robinhood smart contract event over GraphQL WebSockets — decoded logs, topics, call & receipt context. A no-node alternative to eth_getLogs. # Smart Contract Events on Robinhood Chain — Logs & WebSocket Streams Stream **every smart contract event on Robinhood** with Bitquery GraphQL — decoded arguments, raw topics, and the emitting transaction, call, and receipt joined into one record. The `EVM.Events` cube on `network: robinhood` is a drop-in **alternative to running your own node**: no RPC infrastructure, no log-decoding pipeline, no ABI management for known signatures. Part of the [Robinhood Chain API docs](/docs/blockchain/robinhood/). Open **one WebSocket that listens to everything**, or **hundreds of narrowly filtered sockets** — per contract, per event signature, per raw topic hash, even per decoded argument value. Every subscription on this page was verified live over WebSocket, and every query was executed against the production endpoint before publishing. :::note API Key Required To query or stream data outside the Bitquery IDE, you need an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: :::tip Related docs - [Robinhood Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [EVM Events schema](/docs/schema/evm/events/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) - [Robinhood Trades](/docs/blockchain/robinhood/robinhood-trades/) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) - [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity/) - [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches/) - [WebSocket authentication](/docs/authorization/websocket/) ::: **On this page:** [Why not a node](#why-stream-events-instead-of-running-a-node) · [Datasets & history](#datasets-and-history) · [Event anatomy](#what-one-event-row-contains) · [Firehose](#stream-all-events-firehose) · [By contract](#stream-events-from-one-contract) · [By signature](#stream-one-event-across-all-contracts) · [By topic0](#stream-by-raw-topic0-signature-hash) · [By argument](#watch-an-address-across-all-decoded-arguments) · [By wallet](#events-from-a-wallets-transactions) · [Historical queries](#latest-events-query) · [Use cases](#use-case-patterns) · [FAQ](#faq) --- ## Why stream events instead of running a node | | Your own node (`eth_subscribe` / `eth_getLogs`) | Bitquery Events stream | | --- | --- | --- | | Infrastructure | Run and sync a Robinhood node, manage reconnects and reorgs | One WebSocket to `streaming.bitquery.io` | | Decoding | Raw topics + data; you maintain ABIs and decoders | `Arguments` arrive **decoded and typed** for known signatures; raw `Topics` always included | | Context | Logs only — separate calls for tx, trace, receipt | Transaction, internal `Call`, and `Receipt` joined onto every event | | Filtering | Address + topics only | Address, signature name, signature hash, **decoded argument values**, tx sender, time — server-side | | Backfill | Separate `eth_getLogs` pagination logic | Same query with `dataset: archive` / `combined` | | Scale | One node, you shard consumers | One firehose socket or hundreds of filtered sockets | If you are migrating node code: your `eth_getLogs` `address` filter maps to `LogHeader.Address`, and `topics[0]` maps to `Log.Signature.SignatureHash`. --- ## Datasets and history - **`realtime`** (the default) — a rolling window of recent blocks whose depth varies; don't assume it, measure it with the probe below. - **`archive`** — deep event history with no age limit: it holds Robinhood events from 30 April 2026, its earliest rows (measured 6 November 2026); its head lags the chain by minutes. - **`combined`** — archive + realtime union; the safe choice for fixed windows (24h, 7d). Need bulk history beyond what you want to page through the API? Ask about a [Data Store export](https://bitquery.io/datastore) at sales@bitquery.io. ### Check the events window Run this against `realtime` (or `archive`) to see exactly what the dataset currently holds: ```graphql { EVM(network: robinhood) { Events { count earliest: Block { Time(minimum: Block_Time) } latest: Block { Time(maximum: Block_Time) } } } } ``` --- ## What one event row contains | Group | What it gives you | | --- | --- | | **`Log`** | Emitting context: `SmartContract`, log `Index`, and the `Signature` (`Name`, full `Signature`, `SignatureHash`, `Parsed`) | | **`Topics`** | The raw indexed topics (`Hash` array — topic0 is the event signature hash) | | **`Arguments`** | Decoded, typed argument values (`address`, `bigInteger`, `string`, `hex`, `bool`, `integer`) with names | | **`Transaction`** | Hash, `From`/`To`, value, full gas and fee fields (incl. USD) | | **`Call`** | The internal call that emitted the log: call path, signature, gas, revert/error flags | | **`Receipt`** | `GasUsed`, `CumulativeGasUsed`, deployed `ContractAddress`, receipt `Type` | | **`Block`** | `Number`, `Time`, `Nonce` | :::info LogHeader.Address vs Log.SmartContract `LogHeader.Address` is the **emitting address** — the `address` field a node would return in `eth_getLogs`. `Log.SmartContract` is the **code that produced the log**, which differs behind proxies: several major Robinhood tokens (WETH, USDG) emit through proxy addresses backed by separate implementation contracts. Filter `LogHeader.Address` to watch a deployed address; read `Log.SmartContract` to group proxies that share one implementation. ::: Hash fields (`SignatureHash`, `Topics.Hash`) are hex strings **without** a `0x` prefix. --- ## Stream all events (firehose) One socket, every event on the chain, with the full record — decoded arguments, raw topics, transaction, call, and receipt. Events arrive in per-block batches. :::warning High volume The unfiltered firehose delivers every event on a busy chain — great for exploration and building your own indexer, heavy for everything else. Use the filtered streams below in production. ::: ```graphql subscription { EVM(network: robinhood) { Events { Block { Number Time Nonce } Call { CallPath InternalCalls From To Signature { Name Parsed Signature SignatureHash SignatureType } CallerIndex Create Delegated Error Gas GasUsed Index Reverted SelfDestruct Success Value ValueInUSD } Topics { Hash } Receipt { CumulativeGasUsed ContractAddress Type GasUsed } Transaction { From To Type Cost CostInUSD Gas GasFeeCap GasFeeCapInUSD GasPriceInUSD GasPrice GasTipCapInUSD GasTipCap Hash Value ValueInUSD } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Log { Signature { Name Abi Parsed Signature SignatureHash SignatureType } SmartContract EnterIndex ExitIndex Index LogAfterCallIndex Pc } } } } ``` :::tip WebSocket connection Connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol (`connection_init` → `connection_ack` → `subscribe`). See [WebSocket authentication](/docs/authorization/websocket/). Any subscription on this page also runs as a query — add `limit` and `orderBy` and drop the `subscription` keyword. ::: :::tip Prefer Kafka for the firehose Consuming the full event feed continuously? Bitquery also delivers Robinhood data as **Kafka streams** — decoded transactions, calls, and events on the protobuf topic `robinhood.transactions.proto` — with consumer-group scaling and replay. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). ::: --- ## Stream events from one contract **Protocol monitoring:** everything a single deployed address emits — the streaming equivalent of an `eth_getLogs` address filter. Example: WETH. ```graphql subscription { EVM(network: robinhood) { Events( where: { LogHeader: { Address: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } } } ) { Block { Time } Transaction { Hash } Log { Signature { Name } SmartContract } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` ### Multiple contracts, one socket Watch a whole list of contracts with `Address.in` — one socket per protocol instead of one per contract. ```graphql subscription { EVM(network: robinhood) { Events( where: { LogHeader: { Address: { in: [ "0x0bd7d308f8e1639fab988df18a8011f41eacad73" "0x5fc5360d0400a0fd4f2af552add042d716f1d168" ] } } } ) { Block { Time } Log { Signature { Name } SmartContract } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` --- ## Stream one event across all contracts **Network-wide feeds:** filter by decoded signature name to receive one event type from **every** contract — for example, every ERC-20 `Transfer` on Robinhood in a single socket (the backbone of a token indexer). Works the same for `Swap`, `Approval`, `OwnershipTransferred`, or any launchpad event (see [Flap.sh](/docs/blockchain/robinhood/flap-sh-api/) and [Bags.fm](/docs/blockchain/robinhood/bags-fm-api/) for protocol-specific examples). ```graphql subscription { EVM(network: robinhood) { Events( where: { Log: { Signature: { Name: { is: "Transfer" } } } } ) { Block { Time } Log { SmartContract } Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` :::note Names can collide Different ABIs reuse the same event name — Robinhood carries more than one distinct `Swap` signature, for instance. A name filter catches all variants; pin one exact ABI with the [signature-hash filter](#stream-by-raw-topic0-signature-hash) below. ::: --- ## Stream by raw topic0 (signature hash) Filter on `Log.Signature.SignatureHash` — the keccak of the event signature, i.e. `topics[0]` — **without the `0x` prefix**. This pins one exact ABI variant, and it also works for **undecoded events**: rows where `Signature.Name` is empty and `Parsed` is `false` still carry their hash and raw `Topics`, so no log on the chain is out of reach. Example: the canonical ERC-20 `Transfer(address,address,uint256)` topic0. ```graphql subscription { EVM(network: robinhood) { Events( where: { Log: { Signature: { SignatureHash: { is: "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" } } } } ) { Block { Time } Log { Signature { Name SignatureHash } SmartContract } Topics { Hash } } } } ``` --- ## Watch an address across all decoded arguments **Wallet / token surveillance:** match events where **any decoded argument** equals an address — transfers in or out, approvals, swaps, or protocol events mentioning it, in one stream, regardless of event type or contract. This is a filter a raw node cannot do server-side. ```graphql subscription { EVM(network: robinhood) { Events( where: { Arguments: { includes: { Value: { Address: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } } } ) { Block { Time } Log { Signature { Name } SmartContract } Transaction { Hash } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` Add `Name: { is: "token" }` (or any argument name) inside `includes` to match a specific argument instead of any position. As a historical query, argument matching scans widely — combine it with a `Block.Time` window or a contract filter for speed. --- ## Events from a wallet's transactions Everything emitted by transactions **sent** by one address — a debugging and bot-monitoring view (which pools did my router touch, which events did my deployment emit). ```graphql subscription { EVM(network: robinhood) { Events( where: { Transaction: { From: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } ) { Block { Time } Transaction { Hash } Log { Signature { Name } SmartContract } } } } ``` Rows appear only while the wallet is actively sending transactions — swap in any sender you care about. --- ## Latest events query The query counterpart of the firehose: page through recent events, newest first. ```graphql { EVM(network: robinhood) { Events(limit: { count: 10 }, orderBy: { descending: Block_Time }) { Block { Number Time } Transaction { Hash From To } Log { Signature { Name SignatureHash } SmartContract Index } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` --- ## All events in one transaction **Forensics / debugging:** decompose a transaction into its ordered event log. A DEX swap, for example, unrolls into its `Transfer`s, pool `Sync`/`Swap` events, and any protocol hooks — with decoded arguments for each. ```graphql { EVM(network: robinhood, dataset: archive) { Events( orderBy: { ascending: Log_Index } where: { Transaction: { Hash: { is: "0xdb0f8aed6d900da3751670f311dbb8a7ae3f44022d15eff2b72a5d0863a1750f" } } } ) { Log { Index Signature { Name } SmartContract } Arguments { Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } } } } ``` --- ## Top event signatures **Discovery:** which events dominate the chain right now — grouped by signature with counts. Rows with an empty `Name` are undecoded signatures; their `SignatureHash` still identifies them. ```graphql { EVM(network: robinhood) { Events(limit: { count: 15 }, orderBy: { descendingByField: "count" }) { Log { Signature { Name SignatureHash } } count } } } ``` --- ## Most active event emitters Which contracts emit the most events over a window, and how many distinct signatures each uses — a fast map of what's hot on chain. ```graphql { EVM(network: robinhood) { Events( limit: { count: 10 } orderBy: { descendingByField: "count" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Log { SmartContract } count signatures: count(distinct: Log_Signature_SignatureHash) } } } ``` --- ## Event volume in a time window One-row stats for dashboards: total events and distinct emitting contracts. Use `dataset: combined` when the window must be complete regardless of the realtime depth. ```graphql { EVM(network: robinhood) { Events(where: { Block: { Time: { since_relative: { hours_ago: 1 } } } }) { count contracts: count(distinct: Log_SmartContract) } } } ``` --- ## Use-case patterns | Goal | Approach | | --- | --- | | Token indexer without a node | Stream `Signature.Name: "Transfer"` (or pin the [topic0 hash](#stream-by-raw-topic0-signature-hash)); backfill with the same query on `dataset: archive` | | DEX analytics | Stream `Swap` by signature hash per ABI variant; join context from `Transaction` / `Call` | | Launchpad detection | Creation events per protocol — see [Meme Coin Launches](/docs/blockchain/robinhood/robinhood-meme-coin-launches/), [Flap.sh](/docs/blockchain/robinhood/flap-sh-api/), [Bags.fm](/docs/blockchain/robinhood/bags-fm-api/) | | Pool reserve / price state | Purpose-built cubes are easier — [DEXPoolEvents](/docs/blockchain/robinhood/robinhood-liquidity/) | | Wallet / compliance watch | [Argument address filter](#watch-an-address-across-all-decoded-arguments) — one stream, every event type | | Protocol ops & alerting | [Contract filter](#stream-events-from-one-contract) on your deployments; alert on `OwnershipTransferred`, role changes, pauses | | Incident forensics | [Per-transaction event log](#all-events-in-one-transaction), plus `Call.Reverted` / `Receipt` context | | Chain discovery | [Top signatures](#top-event-signatures) and [top emitters](#most-active-event-emitters) | --- ## Tips 1. **Filter production streams.** The firehose is for exploration and full indexers; per-contract, per-signature, and per-hash sockets are cheap — open as many as you need, or multiplex several subscriptions over one WebSocket connection. 2. `LogHeader.Address` = emitting address (node-style filter); `Log.SmartContract` = the code behind it — they differ for proxy contracts. 3. Hash fields have **no `0x` prefix** — `SignatureHash` and `Topics.Hash` are bare hex. 4. Event **names collide across ABIs** (multiple `Swap` variants exist) — filter by `SignatureHash` when exact ABI identity matters. 5. Undecoded events (`Name: ""`, `Parsed: false`) are still delivered and filterable by hash — nothing on chain is invisible. 6. Realtime depth varies — measure it with the [window probe](#check-the-events-window); use `combined` for fixed windows and `archive` for full history (its head lags the chain by minutes). 7. Decoded-argument filters scan broadly as historical queries — scope them with a time window or contract filter; as subscriptions they are cheap. 8. For bulk backfills beyond API paging, ask about a [Data Store export](https://bitquery.io/datastore) at sales@bitquery.io. --- ## FAQ ### Can I listen to Robinhood contract events without running a node? Yes — that is this API's core use. A GraphQL `subscription` on `EVM(network: robinhood) { Events }` over WebSocket replaces `eth_subscribe("logs")`, with decoded arguments and joined transaction/call/receipt context that a node doesn't provide. Backfill uses the same query with `dataset: archive`. ### Should I open one WebSocket or many? Both work. One firehose socket can feed your own router, or you can open a separate narrowly-filtered subscription per contract, signature, or address — hundreds of concurrent filtered sockets are a supported pattern, and several subscriptions can also share one connection. ### Are event arguments decoded? Yes — `Arguments` returns named, typed values (`address`, `bigInteger`, `string`, `hex`, `bool`, `integer`) for known signatures. Unknown signatures still stream with raw `Topics` and their `SignatureHash`. ### How do I filter by raw topic0? Use `Log.Signature.SignatureHash` with the keccak hash of the event signature, **without** the `0x` prefix — see [the topic0 stream](#stream-by-raw-topic0-signature-hash). ### How far back does Robinhood events data go? `archive` has no age limit (its events start on 30 April 2026), and `realtime` holds a rolling recent window — measure either with the [window probe](#check-the-events-window). For bulk history, Bitquery can provide data exports on request. ### How do I get every event a specific transaction emitted? Filter `Transaction.Hash` and order by `Log_Index` — see [All events in one transaction](#all-events-in-one-transaction). ### Which cube should I use — Events, Transfers, or Calls? `Events` is the decoded-log firehose. For token movements specifically, [Transfers](/docs/blockchain/robinhood/robinhood-transfers/) is pre-modeled with USD enrichment; for pool state, use [DEXPoolEvents](/docs/blockchain/robinhood/robinhood-liquidity/). See [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/). --- ## Solana Aldrinamm API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-AldrinAmm-api/ AldrinAmm DEX on Solana: real-time trades, latest token price, OHLC candles, top traders of a token, buy and sell volume, and pair volatility. # AldrinAmm DEX API :::tip Need real-time AldrinAmm data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered AldrinAmm swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical AldrinAmm data older than ~30 days**, raw per-swap detail, or call / event context. ::: :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## AldrinAmm Trades in Real-Time This streams a message for every new Aldrin AMM trade, carrying the buy and sell sides, the block and the transaction. Open it in the [Bitquery IDE: realtime Aldrin AMM trades](https://ide.bitquery.io/Real-time-trades-on-AldrinAmm-DEX-on-Solana_4). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "AldrinAmm" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ``` ## Latest Price of a Token on AldrinAmm This returns the most recent trade for a token on Aldrin AMM, with the price in the quote token and in USD. Open it in the [Bitquery IDE: latest Aldrin AMM token price](https://ide.bitquery.io/live-price-of-token-on-aldrinAmm). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolFamily: {is: "AldrinAmm"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## AldrinAmm OHLC API If you want to get OHLC data for any specific currency pair on AldrinAmm, you can use this api. Only use [this API](https://ide.bitquery.io/AldrinAmm-OHLC-for-specific-pair) as query and not subscription websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProtocolFamily: {is: "AldrinAmm"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get the Top Traders of a specific Token on AldrinAmm DEX This ranks the wallets trading one token on Aldrin AMM, USDC in the example. Run it as a plain request rather than a WebSocket subscription, because aggregates are recomputed per message on a subscription and the totals come back wrong. Open it in the [Bitquery IDE: top traders on Aldrin AMM](https://ide.bitquery.io/top-traders-of-a-token-on-aldrinAmm_2) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProtocolFamily: {is: "AldrinAmm"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", } ``` ## Get trading volume, buy volume, sell volume of a token This reads the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`. Every Trading row carries a vetted USD price and the cube covers roughly the last 30 days in full, while the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so volume totals taken from them read low. `Side` is the trader's own side. The example follows the WSOL/USDC market on Aldrin AMM; swap the two addresses for the pair you want. Open it in the [Bitquery IDE: Aldrin AMM trade volume](https://ide.bitquery.io/trade_volume_aldrinAmm). ```graphql { Trading { Trades( where: { Pair: { Market: { ProtocolFamily: { is: "AldrinAmm" } Network: { is: "Solana" } } Token: { Address: { is: "So11111111111111111111111111111111111111112" } } QuoteToken: { Address: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ``` ## Volatility of a Pair on AldrinAmm Volatility is an important factor in trading world as it determines the fluctuation in price that implies the possibility of profit and risk of loss. Lesser volatility denotes that the pair is stable. Open the [Bitquery IDE: Aldrin AMM pair volatility](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-AldrinAmm-Dex-on-Solana_1) to read volatility for a pair over the last 24 hours. ```graphql query Volatilityon { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "AldrinAmm" } } Buy: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Sell: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Block: { Time: { after: "2025-03-18T00:00:00Z" } } } ) { volatility: standard_deviation(of: Trade_Buy_Price) } } } ``` --- ## Solana Arbitrage Dashboard Project URL: https://docs.bitquery.io/docs/usecases/solana-arbitrage-dashboard/ Build Solana Arbitrage Dashboard Project: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Solana Arbitrage Dashboard Project The following tutorial is a step by step guide to build a Dashboard that displays arbitrage opportunities for WSOL/USDC pair on Solana. This is how it will look The app has the following features: 1. It displays a table with the DEX Name, Pair exchange rate on the DEX and DEX Address once the data is fetched. 2. It handles errors during the data fetching process. 3. It has a Execute Button which doesn't implement anything yet, but any PR regarding the same is welcome. The app uses the following libraries and APIs: 1. Next: An optimized version of React for building user interfaces with server-side rendering. 2. Axios: A promise-based HTTP client for the browser and Node.js. 3. Bitquery GraphQL API: A service that provides access to blockchain data through a GraphQL interface. To use this code, you need to have the following dependencies installed in your project: 1. react 2. react-dom 3. axios 4. tailwind-css ## GraphQL query The following query will be used to fetch the required data for the project. ```graphql subscription { Solana { DEXTrades( where: { Trade: { Buy: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Sell: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } } ) { Trade { Dex { ProgramAddress ProtocolName ProtocolFamily } Buy { PriceInUSD Account { Address } } } Block { Time } } } } ``` ## Create App Create an empty next app with the ``` npx create-next-app arbitrage-dashboard ``` command, then select the recommended options and clear the defaults in page.js file. ## Data Component Add a new file named `data.js` in the app folder and follow the below steps. ### Import Statements ```js ``` ### Functional Component ```js const getData = async () => { let data = JSON.stringify({ query: 'subscription {\n Solana {\n DEXTrades(\n where: {Trade: {Buy: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Sell: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}}}\n ) {\n Trade {\n Dex {\n ProgramAddress\n ProtocolName\n ProtocolFamily\n }\n Buy {\n PriceInUSD\n Account {\n Address\n }\n }\n }\n Block {\n Time\n }\n }\n }\n}\n', variables: "{}", }); let config = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", Authorization: process.env.NEXT_PUBLIC_BITQUERY_TOKEN, }, data: data, }; let response = await axios.request(config); // console.log(JSON.stringify(response.data.data.Solana.DEXTrades)) return response.data.data.Solana.DEXTrades; }; export default getData; ``` ## Page Component All the code blocks given below will be added to the `page.js` file in the app folder. ### Import Statements ```js "use client"; ``` Note that the `"use client"` on the top is essential in order to use `useState` and `useEffect` functionalities. ### Home Component - `const Home = () => {...};`: All the code blocks below will be added in place of dots. - `export default Home;`: Export statement for Home Component. ### State Management with `useState` Hook - `const [trades, setTrades] = useState([]);`: Declares a state variable `trades` that is initially an empty array. Also defines a setter function `setTrades` to update the state value of `trades`. - `const [currentPage, setCurrentPage] = useState(0);`: Declares a state variable `currentPage` that is initially `0`. Also defines a setter function `setCurrentPage` to update the state value of `currentPage`. - `const itemsPerPage = 10;`: Sets the number of opportunities displayed on one page as `10`. ### `useEffect` Hook - `useEffect(() => {...}, []);`: Defines a `useEffect` hook that makes an HTTP POST request to the Bitquery API to retrieve data for the arbitrage opportunities on Solana chain. ### `Pagination` Methods - `const handleNextPage = () => {...};`: Defines a method `handleNextPage` to display the next `10` arbitrage opportunities. - `const handlePrevPage = () => {...};`: Defines a method `handlePrevPage` to display the previous `10` arbitrage opportunities. ### Component Render ```js return (

Arbitrage Opportunities for WSOL/USDT

{currentTrades.map((trade, index) => ( ))}
Sr. No. Timestamp DEX Name Price DEX Address
{index + 1 + currentPage * itemsPerPage} {trade.Block.Time} {trade.Trade.Dex.ProtocolFamily} {trade.Trade.Buy.PriceInUSD} {trade.Trade.Dex.ProgramAddress}
); ``` ### CSS Styling The app uses Tailwind CSS for styling which is much more effecient and easy to use. ## Video Tutorial for the Project --- ## Solana Balance Updates - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/balance/ Solana Balance Updates - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana Balance Updates gRPC Stream The `balance` gRPC Stream provides real-time balance update data for Solana accounts and token accounts. --- ## Overview Subscribe to live balance changes for accounts and token accounts. Each event includes pre/post balances, currency details, and account context. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. ## Configuration To subscribe to balance updates, configure your stream as follows: ```yaml stream: type: "balance" ``` ## Available Data The balance updates stream provides comprehensive balance change information including: - **Transaction details**: Slot, signature, status, fees (in native and USD) - **Account information**: Signers, token accounts, program IDs - **Token context**: Mint addresses, decimals, owners - **Balance changes**: Pre/post balances for accounts and token accounts - **Currency details**: Token metadata, symbols, mint addresses ## Sample Data Structure Here's an example of the data structure you'll receive: ```json { "Block": { "Slot": 370025845 }, "Transaction": { "Index": 664, "Signature": "MgetT2Zi7PtLP867x2xioiCmimwe1H4rtTiDuqwE8eqjGuK4CTs4CBiKCKyfJHh8mXmQcK4hY9aMVsngg9v1mw5", "Header": { ... "Accounts": [ ... ] } }, "BalanceUpdate": { "BalanceUpdate": { "PreBalance": 412870875328, "PostBalance": 412392356516, "AccountIndex": 4 }, "Currency": { "Name": "Wrapped Solana", ... } } } ``` ## Key Points - **Balance tracking**: Monitor pre and post balances for any account changes - **Token context**: Each balance update includes full token metadata and currency information - **Account indexing**: Balance updates reference specific account indices within transactions - **Comprehensive metadata**: Currency details include mint addresses, symbols, decimals, and program IDs ## Filtering Options The filter options are defined in the `request.proto` file. You can filter balance updates using the following filters: ```protobuf message SubscribeBalanceUpdateRequest { AddressFilter address; AddressFilter token; } ``` Available filters: - **address**: Filter by account address - **token**: Filter by token mint address (e.g., WSOL, USDC) ## Schema Reference - **Protobuf Schema**: [balance_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/block_message.proto) - **Sample Data**: [solana_balance.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_balance.json) ## Python Installation For Python development, install the protobuf package: ```bash pip install bitquery-corecast-proto ``` ## NPM Package ```bash npm install bitquery-corecast-proto ``` This package includes all necessary protobuf definitions without requiring manual downloads. --- ## Related - [CoreCast Introduction](/docs/grpc/solana/introduction/) — Topics and concepts - [Transfers gRPC](/docs/grpc/solana/topics/transfer/) — Token transfers - [Solana Balance Updates (GraphQL)](/docs/blockchain/Solana/solana-balance-updates/) — WebSocket subscriptions - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana Balance Updates Cube URL: https://docs.bitquery.io/docs/cubes/balance-updates-cube/ How the Solana BalanceUpdates cube models every balance change per account, with Type attribution, pre and post balances, and aggregation examples. # Solana Balance Updates Cube The `BalanceUpdates` cube on Solana returns every change to an account's balance, with the transaction that caused it. Use it for balance history, live balance tracking and per-account aggregates. `Solana.InstructionBalanceUpdates` gives the same changes broken down by instruction. :::note EVM and Tron For current balances and holder rankings on EVM chains and Tron, use the [Balances and Holders cubes](/docs/cubes/balances-cube). ::: ## What is a Balance Update? Any change in the balance of any account, by any means, is a balance update. On Solana that covers token transfers, fees, rewards and account changes inside a transaction. Each row carries the `Amount` of the change, the `PreBalance` and `PostBalance` of the account, and a `Type`. ## Balance updates of an account The latest balance changes of one account, newest first. ```graphql {r('b1_s1.graphql')} ``` Fields in the response: - `Account.Address`: the account whose balance changed. `Account.Owner` is the wallet that owns it (for token accounts). - `Amount` and `AmountInUSD`: the size of the change. Positive values are inflows. - `PreBalance` and `PostBalance`: the balance before and after the change. - `Type`: what kind of change it was. - `Currency`: the token; SOL has mint `11111111111111111111111111111111`. ## Stream balance updates The same query as a subscription. A new row arrives each time the account's balance changes. ```graphql {r('b1_s4.graphql')} ``` ## Aggregation in the BalanceUpdates cube Aggregates run at query time, so you can group balance changes by currency, type, time or account. ### Latest balance per token for a wallet `PostBalance(maximum: Block_Slot)` picks the post-balance of the most recent update per currency, which is the current balance. Filter on `Account.Owner` to cover all token accounts of a wallet. ```graphql {r('b1_s3.graphql')} ``` ### Net change per currency and type Sum the updates over the last 24 hours, grouped by currency and `Type`. ```graphql {r('b1_s2.graphql')} ``` ## Related - [Solana Balance & Balance Updates API](/docs/blockchain/Solana/solana-balance-updates) - [Balances and Holders cubes (EVM and Tron)](/docs/cubes/balances-cube) --- ## Solana Balances and Balance Updates API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-balance-updates/ Solana Balances and Balance Updates API: fetch current and historical Solana balances with Bitquery GraphQL balance queries. # Solana Balances and Balance Updates API In this section we will see how to monitor real-time balance changes across the Solana blockchain using our BalanceUpdates API. Note - Our [V1 APIs](https://docs.bitquery.io/v1/docs/category/examples) do support solana and you can get balances from there. However they do not have historical balance. ## 🔗 Related Solana APIs - **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** - Track transfers that cause balance changes - **[Solana Instructions API](/docs/blockchain/Solana/solana-instructions/)** - Monitor instructions that affect balances - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Track trading activities that impact balances - **[Solana Fees API](/docs/blockchain/Solana/solana_fees_api/)** - Analyze fees that reduce balances - **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** - Monitor supply changes affecting balances ## Get all the Tokens owned by an address The below query retrieves the token addresses and their balances owned by a particular account address You can access the query [here](https://ide.bitquery.io/tokens-owned-by-an-address). For tracking the transfers that cause these balance changes, see our **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)**. ```graphql query MyQuery { Solana { BalanceUpdates( where: {BalanceUpdate: {Account: {Owner: {is: "AtTjQKXo1CYTa2MuxPARtr382ZyhPU5YX4wMMpvaa1oy"}}}} orderBy: {descendingByField: "BalanceUpdate_Balance_maximum"} ) { BalanceUpdate { Balance: PostBalance(maximum: Block_Slot) Currency { Name Symbol } } } } } ``` ## Get Latest Balance Updates The query will subscribe you to real-time updates for balance changes on the Solana blockchain, providing a continuous stream of data as new transactions are processed and recorded. You can find the query [here](https://ide.bitquery.io/active-address-balance-update) The balance update does not inherently include transaction fees. Therefore, to get the actual balance after all transactions and fees, you need to subtract the total transaction fees from the balance updates. ```graphql subscription { Solana(network: solana) { BalanceUpdates( where: {BalanceUpdate: {Account: {Address: {is: "DzYV9AFEbe9eGc8GRaNvsGjnt7coYiLDY7omCS1jykJU"}}}} ) { Transaction { Signature } BalanceUpdate { Amount Currency { Name MintAddress } PostBalance PostBalanceInUSD Account { Address } Type } Block { Slot } } } } ``` ## Get Token Holdings and Holding time of an address Get the token holdings of an address and calculate the holding time using `first_buy_time` and `latest_balance_update_time`; test this query [here](https://ide.bitquery.io/token-holdings-of-an-address_2). ```graphql query MyQuery { Solana { BalanceUpdates( where: {BalanceUpdate: {Currency:{MintAddress:{is:"FSJYiGZhJ1wDPNhHbSHm49yJkzbFp7FykNB2SZFipump"}} Account: {Owner: {is: "CECN4BW4DKnbyddkd9FhWVR5dotzKhQr5p7DUPhQ55Du"}}}} ) { Block{ first_buy_time:Time(minimum:Block_Slot) latest_balance_update_time:Time(maximum: Block_Slot) } BalanceUpdate { First_Buy: PostBalance(minimum:Block_Slot) Balance: PostBalance(maximum: Block_Slot) Currency { Name Symbol MintAddress } } } } } ``` ## Get All Token Holders of a Particular Token This query returns the holders of a token, largest first. Each wallet's holding is the sum of its balance changes, which equals its current balance for a token launched within the real-time window (about 12 hours). For an older token such as USDC, use the V1 method on the [Solana Token Holders API](/docs/blockchain/Solana/solana-token-holders/) page. ```graphql query TopHolders($token: String!) { Solana(dataset: realtime) { BalanceUpdates( limit: { count: 100 } orderBy: { descendingByField: "Holding" } where: { BalanceUpdate: { Currency: { MintAddress: { is: $token, not: "" } } } Transaction: { Result: { Success: true } } } ) { BalanceUpdate { Account { Owner } } Holding: sum(of: BalanceUpdate_Amount) } } } ``` ```json { "token": "token mint address" } ``` Do not rank holders with `PostBalance(maximum: Block_Slot)`. An account can change several times in one slot, and that pick can return an older balance, such as a wallet that sold out, or a Pump.fun bonding curve emptied at graduation. ## Get Balance Updates of a Particular Wallet To focus on the balance changes of a particular Solana wallet, [this](https://ide.bitquery.io/balance-updates-of-a-wallet_4) query filters the data stream to include only those updates relevant to the specified address. This is especially useful for wallet owners or services tracking specific accounts. ```graphql subscription{ Solana { BalanceUpdates( where: {BalanceUpdate: {Account: {Address: {is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"}}}} ) { Transaction { Index FeePayer Fee Signature Result { Success ErrorMessage } } Block { Time Hash Height } BalanceUpdate { Account { Address } Amount Currency { Decimals CollectionAddress Name Key IsMutable Symbol } } } } } ``` ## Track NFT Balance Updates in Real-Time For those interested in the NFT market, this query is tailored to track balance updates involving non-fungible tokens (NFTs) on the Solana blockchain. You can find the query [here](https://ide.bitquery.io/Solana-NFT-Balance-Updates_1) ```graphql subscription { Solana { BalanceUpdates( where: {BalanceUpdate: {Currency: {Fungible: false}}} ) { Transaction { Index FeePayer Fee Signature Result { Success ErrorMessage } } Block { Time Hash Height } BalanceUpdate { Account { Address Token { Owner } } Amount Currency { Decimals CollectionAddress Name Key IsMutable Symbol } } } } } ``` ## Latest Balance of an Address on Solana The query will subscribe you to real-time updates for balance changes on the Solana blockchain for the address `675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8`, The `PostBalance` field will give you the native SOL balance in this case after the balance update. You can find the query [here](https://ide.bitquery.io/Balance-of-the-raydium-liquidity-pool-address) ```graphql subscription { Solana { BalanceUpdates( where: {BalanceUpdate: {Account: {Address: {is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"}}}} ) { BalanceUpdate { Account { Address } Amount Currency { Decimals CollectionAddress Name Key IsMutable Symbol } PreBalance PostBalance } } } } ``` ## How do I get historic SOL balance of a wallet? You can use Solana v1 Transfer API to get historical solana balances.https://docs.bitquery.io/v1/docs/Examples/Solana/transfers ## Using Pre-Made Aggregates in Solana Balance Updates When querying Solana balance updates, you can use pre-made aggregates to optimize performance. The `aggregates` flag provides three options to control the use of these aggregates: - **`aggregates: only`**: This option uses only the pre-made aggregates, which can significantly increase the speed of the response. - **`aggregates: yes`**: This option uses both pre-made aggregates and individual transaction data. - **`aggregates: no`**: This option does not use any pre-made aggregates. > When using the aggregates: only option, you need to include the Owner field in the response to ensure proper aggregation and filtering. ```graphql { Solana(aggregates: only) { BalanceUpdates( where: {BalanceUpdate: {Account: {Address: {is: "HEL1USMZKAL2odpNBj2oCjffnFGaYwmbGmyewGv1e2TU"}}}} ) { BalanceUpdate { Account { Owner } Currency { Decimals CollectionAddress Name Key IsMutable Symbol } } sum(of: BalanceUpdate_AmountInUSD) } } } ``` ## Video Tutorial on How to get Balance Updates for Wallets on Solana in Realtime ## Video Tutorial on Getting Top 100 Solana Token Holders --- ## Solana Blocks API - Slots, Height & Skipped Slots URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-blocks-api/ Query and stream Solana blocks: slot to timestamp lookup, block height vs slot, transaction counts per block, and detecting skipped slots. # Solana Blocks API The `Blocks` cube is the chain's clock. Use it to convert a slot to a timestamp, watch the chain tip, measure throughput, or detect skipped slots. ``` Block { Slot the slot this block occupies Height block height (not the same number as Slot, see below) ParentSlot the slot of the previous block Time block timestamp Date block date Hash block hash ParentHash previous block hash TxCount transactions in the block RewardsCount reward entries in the block } ``` ## Slot is not height This trips people up constantly, so it is worth stating plainly: on Solana `Slot` and `Height` are different numbers, and the gap between them grows over time. A slot is a scheduled time window for a leader to produce a block. When a leader fails to produce one, the slot is **skipped**: no block ever exists at that slot, and height does not advance. Height counts blocks that exist; slot counts opportunities that were scheduled. If you are storing "block number" for Solana, decide which one you mean. Anything time-based should key on `Slot`, since it maps to the network's schedule. Anything counting blocks should use `Height`. ## Latest blocks ```graphql query LatestSolanaBlocks { Solana { Blocks(limit: { count: 10 }, orderBy: { descending: Block_Slot }) { Block { Slot Height ParentSlot Time TxCount RewardsCount Hash } } } } ``` ## Stream the chain tip `Blocks` is one of the cleaner streams to consume: one message per block, at Solana's block cadence, with no filter required. ```graphql subscription SolanaChainTip { Solana { Blocks { Block { Slot Height Time TxCount ParentSlot } } } } ``` Useful as a heartbeat. If this stream goes quiet, the problem is your connection or the network, not your filter, which is a helpful thing to be able to distinguish when a busier subscription stops delivering. ## Detect skipped slots `Slot - ParentSlot` is 1 when no slot was skipped. Anything larger means the leader for those slots produced nothing. ```graphql subscription SkippedSlots { Solana { Blocks { Block { Slot ParentSlot Time } } } } ``` Compute the gap client-side: ```js const skipped = Number(block.Slot) - Number(block.ParentSlot) - 1; if (skipped > 0) console.log(`${skipped} slot(s) skipped before ${block.Slot}`); ``` A rising skip rate means leaders are failing to produce, which usually shows up as degraded confirmation times before it shows up anywhere else. It is a cheap network-health signal, and one you cannot get from trade or transfer data. ## Look up the timestamp for a slot ```graphql query SlotToTime { Solana { Blocks(limit: { count: 1 }, where: { Block: { Slot: { eq: "436918084" } } }) { Block { Slot Height Time TxCount } } } } ``` Replace the slot with the one you are looking up. :::note An empty result usually means retention, not a bad slot If a slot returns no rows, it is most often outside the history your plan retains rather than a slot that does not exist. Check a recent slot first to confirm the query shape, then widen. A genuinely skipped slot also returns nothing, so the two cases look identical — use `ParentSlot` on the surrounding blocks to tell them apart. ::: ## Throughput per day `TxCount` aggregates, so block and transaction throughput is one query rather than a scan over transactions. ```graphql query SolanaDailyThroughput { Solana { Blocks(limit: { count: 14 }, orderBy: { descending: Block_Date }) { Block { Date } blocks: count transactions: sum(of: Block_TxCount) rewards: sum(of: Block_RewardsCount) } } } ``` Dividing `transactions` by `blocks` gives average transactions per block, which is a better load measure than raw TPS because it is not distorted by skipped slots. ## Related - [Solana Transactions API](/docs/blockchain/Solana/solana-transactions/) - [Solana Rewards API](/docs/blockchain/Solana/solana-rewards/) - [Solana Instructions API](/docs/blockchain/Solana/solana-instructions/) - [Which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/) --- ## Solana Boop Fun API URL: https://docs.bitquery.io/docs/blockchain/Solana/Boop-Fun-API/ Boop.fun on Solana: latest token creations, buys, sells and migrations, plus one subscription for Raydium Launchlab, Meteora DBC, LetsBonk.fun and Moonshot. # Boop Fun API :::tip Need real-time Boop.fun data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Boop.fun data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this document, we will explore several examples related to Boop fun data. We also have [Raydium Launchpad APIs](/docs/blockchain/Solana/launchpad-raydium/). Additionally, you can also check out our [Moonshot APIs](/docs/blockchain/Solana/Moonshot-API/), [FourMeme APIs](/docs/blockchain/BSC/four-meme-api/). These APIs can be provided through different streams including Kafka for zero latency requirements. Please contact us on [telegram](https://t.me/Bloxy_info). :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: If you want fastest data without any latency, we can provide Kafka streams, please [fill this form](https://bitquery.io/forms/api) for it. Our Team will reach out. ## Get the latest Boop.Fun token migrations Below query can be used to track Boop.fun token migrations. In this query we are getting 10 latest Boop.fun migrations. Change the `query` keyword to `subscription` keyword then it will act as a websocket and will keep on running and give you the realtime migrations. Try the query [here](https://ide.bitquery.io/Boopfun-token-migrations) ```graphql query MyQuery { Solana { Instructions( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "graduate"}}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { IsWritable Address Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } } } } ``` ## Latest Boop.fun token buys You can track latest buy trades on Boop.Fun using the below API. Try the API [here](https://ide.bitquery.io/latest-boopfun-token-buys#). ```graphql query MyQuery { Solana { Instructions( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "buy_token"}}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { IsWritable Address Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } } } } ``` ## Latest Boop.fun token sells You can track latest sell trades on Boop.Fun using the below API. Try the API [here](https://ide.bitquery.io/latest-boopfun-token-sells#). ```graphql query MyQuery { Solana { Instructions( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "sell_token"}}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { IsWritable Address Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } } } } ``` ## Latest Boop.fun token creation You can track latest token launches on Boop.Fun using the below API. Try the API [here](https://ide.bitquery.io/latest-boopfun-token-creations#). ```graphql query MyQuery { Solana { Instructions( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "create_token"}}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { IsWritable Address Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } } } } ``` ## Track Boop.fun, Raydium Launchlab, Meteora DBC, LetsBonk.fun and Moonshot Token Migrations in a single subscription Use this single subscription to stream real-time token migration events across Boop.fun, Raydium Launchlab, Meteora DBC, and Moonshot. It filters by the respective program IDs and migration methods, returning block time, program details, involved accounts, and transaction signatures as events occur. Try out the [API](https://ide.bitquery.io/Raydium-Launchlab-Meteora-DBC-BoopFun-Moonshot-LetsBonkfun-token-migrations-in-realtime_2) here on IDE. ```graphql subscription{ Solana { Instructions( where: {any: [{Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {is: "initialize_v2"}}}}, {Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "graduate"}}}}, {Instruction: {Program: {Address: {is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG"}, Method: {is: "migrateFunds"}}}}, {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["migrate_meteora_damm", "migration_damm_v2"]}}}}, {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["migrate_to_amm", "migrate_to_cpswap"]}}, Accounts: {includes: {Address: {is: "FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1"}}}}}], Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Launchlab # boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4 - boop.fun # MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG - Moonshot/Moonit # dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN - Meteora DBC # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Program Address and FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1(letsbonk.fun platform config addr) is present in Accounts array then its Letsbonk.fun migration Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method Name } } Transaction { Signature Signer } } } } ``` --- ## Solana Builder Terms Explaination URL: https://docs.bitquery.io/docs/glossary/solana/ Solana API glossary: dataset and filter parameters plus field terms for BalanceUpdates, Blocks, DEXTrades, DEXOrders, Instructions, Rewards and Transfers. # Solana Builder Terms Explaination ### Dataset Parameters Solana API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from May 2024 up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Filter Parameters Solana API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Account`: The specific Solana account that the balance update pertains to. - `Amount`: The quantity of tokens that were added to or subtracted from the account. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WSOL, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WSOL. - `Currency`: The type of token or cryptocurrency involved in the balance update. - `PostBalance`: The account's balance after the update has been applied. - `PostBalanceInUSD`: The equivalent value of the PostBalance in US dollars at the time of the transaction. - `PreBalance`: The account's balance before the update was applied. - `PreBalanceInUSD`: The equivalent value of the PreBalance in US dollars at the time of the transaction. ### Block API Terms - `Date`: The specific date on which a block was created or recorded on the Solana blockchain. - `Hash`: A unique identifier generated from the block's data, ensuring data integrity and security. - `Height`: The position of a block in the blockchain, indicating its order relative to other blocks. - `ParentHash`: The unique identifier (hash) of the preceding block in the blockchain, linking the current block to its parent. - `ParentSlot`: The slot number of the block that precedes the current block, used to maintain the order of blocks. - `RewardsCount`: The number of rewards transactions included in a block, often related to staking or validation rewards. - `Slot`: A specific time interval in which a block is proposed and validated on the Solana network. - `Time`: The precise timestamp when the block was created, recorded in Coordinated Universal Time (UTC). - `TxCount`: The total number of transactions included within a specific block on the Solana blockchain. ### DEXOrders API DEX Orders API contains Order field in OrderEvent Field which has below attributes: - `Account`: The Solana account initiating the order. - `BuySide`: Indicates whether the order is a buy (true) or sell (false). - `LimitAmount`: The maximum quantity of the asset to be traded. - `LimitAmountInUSD`: The maximum trade amount expressed in USD. - `LimitPrice`: The price per unit of the asset specified in the order. - `LimitPriceInUSD`: The price per unit of the asset specified in USD. - `Mint`: The specific token mint address for the asset being traded. - `OrderID`: A unique identifier for the order. - `Owner`: The owner of the order, typically the Solana wallet address. - `Payer`: The Solana account responsible for paying transaction fees. ### DEXTradeByTokens API DEXTradeByTokens API gives us trades wrt a token pair. `Trade{Currency}` is first currency and details just before side are for this first currency. Whereas details such as Account, Amount, Price, PriceInUSD, etc inside side are for side currency. Side also has `type` field which tells us if its a `buy` trade or a `sell` trade. The `type` is wrt the pool and side currency. DEXTradeByTokens API contains Trade field which has below attributes: - `Account`: The unique identifier for the wallet involved in the trade. - `Amount`: The quantity of tokens traded. - `AmountInUSD`: The value of the traded tokens in US dollars. - `Currency`: The name of the token being traded. - `DEX`: This contains `ProtocolName`, `ProtocolFamily`, `ProgramAddress`. Here, Protocol or Program refers to DEX. - `Index`: The position number of the trade within a sequence. - `Market`: The address of the trading pair or market. - `Price`: The rate at which this currency is exchanged for the side currency. - `PriceInUSD`: The token's price in US dollars - `Side`: Specifies the `account` address, side `currency`, `amount`, `type` etc. ### DEXTrades API Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. - `Buy`: Details of the buy side of the trade. - `Amount`: Quantity of tokens bought. - `AmountInUSD`: Equivalent value of tokens bought in USD. - `Price`: Price at which tokens were bought. - `PriceInUSD`: Price of bought tokens in USD. - `Account` - `Address`: Address of the buyer's account. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. - `Dex`: Details of the decentralized exchange. - `ProgramAddress`: Address of the DEX program. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolName`: Name of the DEX protocol. - `Market` - `MarketAddress`: Address of the trading pair or market. - `Sell`: Details of the sell side of the trade. - `Account` - `Address`: Address of the seller's account. - `Amount`: Quantity of tokens sold. - `AmountInUSD`: Equivalent value of tokens sold in USD. - `Price`: Price at which tokens were sold. - `PriceInUSD`: Price of sold tokens in USD. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. ### Instructions API Instructions API contains Trade field which has below attributes: - `Accounts`: Details about the accounts involved, including address, writable status, token mint, owner, and program ID. - `AncestorIndexes`: Indexes of ancestor instructions in the call path. - `BalanceUpdatesCount`: The number of balance updates associated with the instruction. - `CallPath`: The sequence of calls leading to the instruction. - `CallerIndex`: Index of the calling instruction. - `Data`: Raw data of the instruction. - `Logs`: Execution logs generated by the instruction. - `InternalSeqNumber`: Internal sequence number of the instruction. - `Index`: Position number of the instruction within the transaction. - `ExternalSeqNumber`: External sequence number of the instruction. - `Depth`: Depth of the instruction in the call stack. - `TokenBalanceUpdatesCount`: Number of token balance updates triggered by the instruction. - `Program`: Information about the program, including parsed details, name, JSON, arguments, address, and account names. The Accounts addresses that we got above with `Accounts{Address}` are the addresses mapped directly to these `AccountNames`. ### Rewards API Rewards API contains Trade field which has below attributes: - `Address`: The wallet address receiving the reward. - `Amount`: The quantity of tokens rewarded. - `AmountInUSD`: The value of the rewarded tokens in US dollars. - `CommissionInUSD`: The commission earned in US dollars. - `Commission`: The commission percentage earned. - `RewardType`: The type or category of the reward. - `PostBalanceInUSD`: The wallet balance after receiving the reward in US dollars. - `PostBalance`: The wallet balance after receiving the reward in tokens. - `Index`: The position or sequence number of the reward entry. ### Transactions API Transactions API contains Trade field which has below attributes: - `Address`: The address of an account involved in the transaction. - `IsWritable`: Indicates whether the account can be modified in the transaction. - `ProgramId`: The identifier of the program associated with a token. - `Mint`: Token Program Address. - `BalanceUpdatesCount`: Number of changes in token balances during the transaction. - `Fee`: The fee paid for executing the transaction. - `FeeInUSD`: The equivalent fee amount in US dollars. - `FeePayer`: The account responsible for paying the transaction fee. - `RecentBlockhash`: The hash of the recent block involved in the transaction. - `InstructionsCount`: Number of instructions in the transaction. - `Index`: The position or sequence number of the transaction. - `Signature`: The digital signature of the transaction. - `Success`: Indicates whether the transaction was successful. - `ErrorMessage`: Details of any error encountered during the transaction. - `Signer`: The account that signed the transaction. - `TokenBalanceUpdatesCount`: Number of changes in token balances due to the transaction. ### Transfers API Transfers API contains Trade field which has below attributes: `Amount`: The quantity of tokens transferred. `AmountInUSD`: The equivalent value of the transferred tokens in US dollars. `Authority`: The wallet address that authorized the transfer. `Index`: The sequential number or position of the transfer event. `Currency`: Details about the token transferred, including its name, mint address, and metadata address, etc. `Receiver`: The recipient's wallet address and ownership details of the received tokens. `Sender`: The sender's wallet address and ownership details of the transferred tokens. ### Currency field Terms Explained Currency has many attributes. It can be a fungible token or non-fungible token(NFT). So it needs an altogether different explaination of its terms- - **CollectionAddress**: Collection address of the NFT, if the currency is an NFT. - **Decimals**: Number of decimals for the token's precision. - **EditionNonce**: Nonce used to derive the edition account address. - **Wrapped**: Indicates if the token is wrapped or not. - **VerifiedCollection**: Indicates if the token's collection is verified. - **Uri**: URI associated with the token. - **UpdateAuthority**: Authority allowed to update the token. - **TokenStandard**: Standard or protocol governing the token. - **TokenCreator**: - **Verified**: Indicates if the token creator is verified. - **Share**: Share of the token creator. - **Address**: Address of the token creator. - **Symbol**: Symbol representing the token. - **SellerFeeBasisPoints**: Basis points of the seller's fee. - **ProgramAddress**: Address of the program managing the token. - **PrimarySaleHappened**: Indicates if the primary sale has occurred. - **Native**: Indicates if the token is native to the blockchain. - **Name**: Name of the token. - **MintAddress**: Token Program Address. - **IsMutable**: Indicates if the token is mutable. - **Fungible**: Indicates if the token is fungible. --- ## Solana Builder Terms Explanation URL: https://docs.bitquery.io/docs/cubes/solana/ Solana cube terms explained: dataset and filter parameters, plus the fields of BalanceUpdates, Blocks, DEXOrders, DEXTrades, Instructions and Transfers. # Solana Builder Terms Explanation > **Before you start**: Not sure when to use Transfers vs DEX Trades vs other data primitives? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. ### Dataset Parameters Solana API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from the first (genesis) block up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Filter Parameters Solana API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Account`: The specific Solana account that the balance update pertains to. - `Amount`: The quantity of tokens that were added to or subtracted from the account. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WSOL, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WSOL. - `Currency`: The type of token or cryptocurrency involved in the balance update. - `PostBalance`: The account's balance after the update has been applied. - `PostBalanceInUSD`: The equivalent value of the PostBalance in US dollars at the time of the transaction. - `PreBalance`: The account's balance before the update was applied. - `PreBalanceInUSD`: The equivalent value of the PreBalance in US dollars at the time of the transaction. ### Block API Terms - `Date`: The specific date on which a block was created or recorded on the Solana blockchain. - `Hash`: A unique identifier generated from the block's data, ensuring data integrity and security. - `Height`: The position of a block in the blockchain, indicating its order relative to other blocks. - `ParentHash`: The unique identifier (hash) of the preceding block in the blockchain, linking the current block to its parent. - `ParentSlot`: The slot number of the block that precedes the current block, used to maintain the order of blocks. - `RewardsCount`: The number of rewards transactions included in a block, often related to staking or validation rewards. - `Slot`: A specific time interval in which a block is proposed and validated on the Solana network. - `Time`: The precise timestamp when the block was created, recorded in Coordinated Universal Time (UTC). - `TxCount`: The total number of transactions included within a specific block on the Solana blockchain. ### DEXOrders API DEX Orders API contains Order field in OrderEvent Field which has below attributes: - `Account`: The Solana account initiating the order. - `BuySide`: Indicates whether the order is a buy (true) or sell (false). - `LimitAmount`: The maximum quantity of the asset to be traded. - `LimitAmountInUSD`: The maximum trade amount expressed in USD. - `LimitPrice`: The price per unit of the asset specified in the order. - `LimitPriceInUSD`: The price per unit of the asset specified in USD. - `Mint`: The specific token mint address for the asset being traded. - `OrderID`: A unique identifier for the order. - `Owner`: The owner of the order, typically the Solana wallet address. - `Payer`: The Solana account responsible for paying transaction fees. ### DEXTradeByTokens API DEXTradeByTokens API gives us trades wrt a token pair. `Trade{Currency}` is first currency and details just before side are for this first currency. Whereas details such as Account, Amount, Price, PriceInUSD, etc inside side are for side currency. Side also has `type` field which tells us if its a `buy` trade or a `sell` trade. The `type` is wrt the pool and side currency. DEXTradeByTokens API contains Trade field which has below attributes: - `Account`: The unique identifier for the wallet involved in the trade. - `Amount`: The quantity of tokens traded. - `AmountInUSD`: The value of the traded tokens in US dollars. - `Currency`: The name of the token being traded. - `DEX`: This contains `ProtocolName`, `ProtocolFamily`, `ProgramAddress`. Here, Protocol or Program refers to DEX. - `Index`: The position number of the trade within a sequence. - `Market`: The address of the trading pair or market. - `Price`: The rate at which this currency is exchanged for the side currency. - `PriceInUSD`: The token's price in US dollars - `Side`: Specifies the `account` address, side `currency`, `amount`, `type` etc. ### DEXTrades API Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. - `Buy`: Details of the buy side of the trade. - `Amount`: Quantity of tokens bought. - `AmountInUSD`: Equivalent value of tokens bought in USD. - `Price`: Price at which tokens were bought. - `PriceInUSD`: Price of bought tokens in USD. - `Account` - `Address`: Address of the buyer's account. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. - `Dex`: Details of the decentralized exchange. - `ProgramAddress`: Address of the DEX program. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolName`: Name of the DEX protocol. - `Market` - `MarketAddress`: Address of the trading pair or market. - `Sell`: Details of the sell side of the trade. - `Account` - `Address`: Address of the seller's account. - `Amount`: Quantity of tokens sold. - `AmountInUSD`: Equivalent value of tokens sold in USD. - `Price`: Price at which tokens were sold. - `PriceInUSD`: Price of sold tokens in USD. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. ### Instructions API Instructions API contains Trade field which has below attributes: - `Accounts`: Details about the accounts involved, including address, writable status, token mint, owner, and program ID. - `AncestorIndexes`: Indexes of ancestor instructions in the call path. - `BalanceUpdatesCount`: The number of balance updates associated with the instruction. - `CallPath`: The sequence of calls leading to the instruction. - `CallerIndex`: Index of the calling instruction. - `Data`: Raw data of the instruction. - `Logs`: Execution logs generated by the instruction. - `InternalSeqNumber`: Internal sequence number of the instruction. - `Index`: Position number of the instruction within the transaction. - `ExternalSeqNumber`: External sequence number of the instruction. - `Depth`: Depth of the instruction in the call stack. - `TokenBalanceUpdatesCount`: Number of token balance updates triggered by the instruction. - `Program`: Information about the program, including parsed details, name, JSON, arguments, address, and account names. The Accounts addresses that we got above with `Accounts{Address}` are the addresses mapped directly to these `AccountNames`. ### Rewards API Rewards API contains Trade field which has below attributes: - `Address`: The wallet address receiving the reward. - `Amount`: The quantity of tokens rewarded. - `AmountInUSD`: The value of the rewarded tokens in US dollars. - `CommissionInUSD`: The commission earned in US dollars. - `Commission`: The commission percentage earned. - `RewardType`: The type or category of the reward. - `PostBalanceInUSD`: The wallet balance after receiving the reward in US dollars. - `PostBalance`: The wallet balance after receiving the reward in tokens. - `Index`: The position or sequence number of the reward entry. ### Transactions API Transactions API contains Trade field which has below attributes: - `Address`: The address of an account involved in the transaction. - `IsWritable`: Indicates whether the account can be modified in the transaction. - `ProgramId`: The identifier of the program associated with a token. - `Mint`: Token Program Address. - `BalanceUpdatesCount`: Number of changes in token balances during the transaction. - `Fee`: The fee paid for executing the transaction. - `FeeInUSD`: The equivalent fee amount in US dollars. - `FeePayer`: The account responsible for paying the transaction fee. - `RecentBlockhash`: The hash of the recent block involved in the transaction. - `InstructionsCount`: Number of instructions in the transaction. - `Index`: The position or sequence number of the transaction. - `Signature`: The digital signature of the transaction. - `Success`: Indicates whether the transaction was successful. - `ErrorMessage`: Details of any error encountered during the transaction. - `Signer`: The account that signed the transaction. - `TokenBalanceUpdatesCount`: Number of changes in token balances due to the transaction. ### Transfers API Transfers API contains Trade field which has below attributes: `Amount`: The quantity of tokens transferred. `AmountInUSD`: The equivalent value of the transferred tokens in US dollars. `Authority`: The wallet address that authorized the transfer. `Index`: The sequential number or position of the transfer event. `Currency`: Details about the token transferred, including its name, mint address, and metadata address, etc. `Receiver`: The recipient's wallet address and ownership details of the received tokens. `Sender`: The sender's wallet address and ownership details of the transferred tokens. ### Currency field Terms Explained Currency has many attributes. It can be a fungible token or non-fungible token(NFT). So it needs an altogether different explaination of its terms- - **CollectionAddress**: Collection address of the NFT, if the currency is an NFT. - **Decimals**: Number of decimals for the token's precision. - **EditionNonce**: Nonce used to derive the edition account address. - **Wrapped**: Indicates if the token is wrapped or not. - **VerifiedCollection**: Indicates if the token's collection is verified. - **Uri**: URI associated with the token. - **UpdateAuthority**: Authority allowed to update the token. - **TokenStandard**: Standard or protocol governing the token. - **TokenCreator**: - **Verified**: Indicates if the token creator is verified. - **Share**: Share of the token creator. - **Address**: Address of the token creator. - **Symbol**: Symbol representing the token. - **SellerFeeBasisPoints**: Basis points of the seller's fee. - **ProgramAddress**: Address of the program managing the token. - **PrimarySaleHappened**: Indicates if the primary sale has occurred. - **Native**: Indicates if the token is native to the blockchain. - **Name**: Name of the token. - **MintAddress**: Token Program Address. - **IsMutable**: Indicates if the token is mutable. - **Fungible**: Indicates if the token is fungible. --- ## Solana Bullx API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-bullx-api/ Build a BullX-style Solana terminal with Bitquery: live pair trades, token stats, top pairs, OHLC charts and per-token traded value. # BullX Solana API :::tip Need real-time BullX-style trader data or anything from the last ~30 days? For **real-time trader and wallet data over the last ~30 days** across **10 chains in one API**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **`Trader.Address`** as a first-class filter plus **USD price, market cap, and supply on every row**. Use this page when you need **historical BullX-style trader data older than ~30 days**, raw per-swap detail, or call / event context. ::: This section will guide you through different APIs which will tell you how to get data like realtime trades just like how BullX shows for Solana. :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## Get Trade Transactions of BullX for a particular pair in realtime This subscribes to a Solana pair and streams each trade as it confirms. Open it in the [Bitquery IDE: Solana pair trades](https://ide.bitquery.io/Get-Solana-pair-trades-data). ```graphql subscription MyQuery { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "token mint address"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProgramAddress: {is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Trade { Currency { Name Symbol } Amount PriceAgainstSideCurrency: Price PriceInUSD Side { Currency { Name Symbol } Amount Type } } Transaction { Maker: Signer Signature } } } } ``` ## Get Buy Volume, Sell Volume, Buys, Sells, Makers, Total Trade Volume, Buyers, Sellers of a specific Token of BullX This returns the headline stats for a token over the last 5 minutes and hour: value bought and sold, counts on each side, makers, and distinct buyers and sellers. Set `time_5min_ago` and `time_1h_ago` to those moments relative to now; the values below are only a shape to copy, and the example pair is Pnut against WSOL. Open it in the [Bitquery IDE: token pair stats](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair). ```graphql query MyQuery($token: String!, $side_token: String!, $pair_address: String!, $time_5min_ago: DateTime!, $time_1h_ago: DateTime!) { Solana(dataset: realtime) { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: $token}}, Side: {Currency: {MintAddress: {is: $side_token}}}, Market: {MarketAddress: {is: $pair_address}}}, Block: {Time: {since: $time_1h_ago}}} ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after: $time_5min_ago}}} ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) makers_5min: count( distinct: Transaction_Signer if: {Block: {Time: {after: $time_5min_ago}}} ) buyers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}} ) buyers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sellers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}} ) sellers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) trades: count trades_5min: count(if: {Block: {Time: {after: $time_5min_ago}}}) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {after: $time_5min_ago}}} ) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) buys: count(if: {Trade: {Side: {Type: {is: buy}}}}) buys_5min: count( if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sells: count(if: {Trade: {Side: {Type: {is: sell}}}}) sells_5min: count( if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) } } } { "token":"2qEHjDLDLbuBgRYvsxhc5D6uDWAivNFZGan56P1tpump", "side_token": "So11111111111111111111111111111111111111112", "pair_address": "4AZRPNEfCJ7iw28rJu5aUyeQhYcvdcNm8cswyL51AY9i", "time_5min_ago":"2024-11-06T15:13:00Z", "time_1h_ago": "2024-11-06T14:18:00Z" } ``` ## Get Top Pairs on Solana on BullX This ranks the ten busiest Solana pairs by trade count, returning trades, buys, sells and the value moved on each side. The window is whatever the `Block: {Time: {since: ...}}` bound sets, so move it to a recent timestamp before running it, an hour back for an hourly board. Run it as a plain request rather than a WebSocket subscription, because aggregates such as `sum` are recomputed per message on a subscription. Open it in the [Bitquery IDE: top Solana pairs](https://ide.bitquery.io/BullX--All-in-One-query_1). ``` graphql query MyQuery { Solana { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Trade: {Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}, Block: {Time: {since: "2024-08-15T04:19:00Z"}}} orderBy: {descendingByField: "total_trades"} limit: {count: 10} ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after: "2024-08-15T05:14:00Z"}}} ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct:Transaction_Signer) total_trades: count total_traded_volume: sum(of: Trade_Side_AmountInUSD) total_buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) total_sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) total_buys: count(if: {Trade: {Side: {Type: {is: buy}}}}) total_sells: count(if: {Trade: {Side: {Type: {is: sell}}}}) } } } ``` ## Get OHLC for a token pair This returns OHLC candles for a token pair, the input for a price chart. Open it in the [Bitquery IDE](https://ide.bitquery.io/Solana-OHLC-Query_5?_gl=1*1simohi*_ga*MTU0ODE3ODUxMy4xNzM5Nzg0Njcw*_ga_ZWB80TDH9J*MTc0MjQ2MjAwNi43Ny4xLjE3NDI0NjIwNDQuMC4wLjA.) ``` graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "token mint address"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get Top Traded Pairs This ranks pairs by traded value. Open it in the [Bitquery IDE](https://ide.bitquery.io/top-trading-pairs?_gl=1*131rbu4*_ga*MTU0ODE3ODUxMy4xNzM5Nzg0Njcw*_ga_ZWB80TDH9J*MTc0MjQ2MjAwNi43Ny4xLjE3NDI0NjIwNDQuMC4wLjA.). ```graphql query ($time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { Solana { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Block: {Time: {after: $time_3h_ago}}, any: [{Trade: {Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}}}, {Trade: {Currency: {MintAddress: {not: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}}, {Trade: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}, Side: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}}}}]} orderBy: {descendingByField: "usd"} limit: {count: 100} ) { Trade { Currency { Symbol Name MintAddress } Side { Currency { Symbol Name MintAddress } } price_last: PriceInUSD(maximum: Block_Slot) price_10min_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Slot) } dexes: uniq(of: Trade_Dex_ProgramAddress) amount: sum(of: Trade_Side_Amount) usd: sum(of: Trade_Side_AmountInUSD) traders: uniq(of: Trade_Account_Owner) count(selectWhere: {ge: "100"}) } } } { "time_10min_ago": "2024-09-19T12:26:17Z", "time_1h_ago": "2024-09-19T11:36:17Z", "time_3h_ago": "2024-09-19T09:36:17Z" } ``` ## Get trading volume, buy volume, sell volume of a token This sums what a token traded against WSOL across every Solana venue, split by side. It reads the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`: each row carries a vetted USD price, and the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so totals taken from them read low. The example uses PUMP; swap the base address for the mint you want. Open it in the [Bitquery IDE](https://ide.bitquery.io/trade_volume_Solana#). ```graphql { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } } Token: { Address: { is: "pumpCmXqMfrsAkQ5r49WcJnRayYRqmXz6ae8H7H9Dfn" } } QuoteToken: { Address: { is: "So11111111111111111111111111111111111111112" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) traders: count(distinct: Trader_Address) } } } ``` --- ## Solana Byreal API URL: https://docs.bitquery.io/docs/blockchain/Solana/byreal-api/ Byreal on Solana: real-time trades and prices, market cap, latest price, OHLC, top traders, and buy and sell volume for a token. # Byreal API :::tip Need real-time Byreal data or anything from the last ~30 days? Use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) for swap-level rows and [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) for **OHLC**, **volume**, and **market cap**. Both include **USD price and supply** on every row. For **historical data older than ~30 days** and **historical aggregates** (OHLC, volume, top traders), see [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/). ::: Bitquery provides real-time and historical data APIs and streams for **Byreal**, a Solana trading protocol. For **prices, OHLC, volume, market cap, and trader analytics** over the **last ~30 days**, use the [**Crypto Price API**](/docs/trading/crypto-price-api/) (`Trading.Pairs`) and [**Crypto Trades API**](/docs/trading/crypto-trades-api/trades-api) (`Trading.Trades`), filtering by **`Market.Program`** **`REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2`**. For **historical aggregates** going back to **May 2024** — OHLC candlesticks, volume, and time-bucketed analytics on **`DEXTradeByTokens`** with **`dataset: combined`** or **`dataset: archive`** — see [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/). Filter those queries by **`Trade.Dex.ProgramAddress`** **`REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2`** for Byreal-specific history. Need zero-latency Byreal data? [Read about our Shred Streams and Contact us for a Trial](/docs/streams/real-time-solana-data/). :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Byreal Trades in Real-Time — Crypto Trades API Stream new Byreal swaps via **`Trading.Trades`** with **USD price**, **market cap**, **FDV**, **supply**, **trader address**, and **transaction metadata** on every row. Filter by **`Pair.Market.Program`** **`REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2`**. For schema details, see the [**Crypto Trades API**](/docs/trading/crypto-trades-api/trades-api) and [**Supply fields**](/docs/trading/crypto-price-api/supply-fields). Run the subscription [in the Bitquery IDE](https://ide.bitquery.io/Real-time-trades-on-Byreal-DEX-on-Solana).
Click to expand GraphQL subscription ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } } } ) { Side Price PriceInUsd Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Trader { Address } TransactionHeader { Hash Fee FeePayer } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Time Timestamp } Pair { Market { Address Program Protocol ProtocolFamily Network } Token { Address Id Symbol Network } QuoteToken { Address Id Symbol Network } } } } } ```
### Stream live prices for a specific Byreal token Lock onto one token with **`Pair.Token.Id`** (e.g. **`bid:solana:`**) and the Byreal program address. Run the subscription [in the Bitquery IDE](https://ide.bitquery.io/Byreal-token-live-prices-using-trades-api).
Click to expand GraphQL subscription ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } Token: { Id: { is: "bid:solana:token Mint Address" } } } } ) { Side Price PriceInUsd Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Trader { Address } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Time } Pair { Token { Address Symbol } QuoteToken { Address Symbol } } } } } ```
## Market cap — Crypto Price API Use **`Trading.Pairs`** with **`Market.Program`** **`REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2`** for aggregated **market cap**, **FDV**, **supply**, **price**, and **volume**. Replace **`solana:`** in **`Token.Id`** with your token. See the [**Pairs cube**](/docs/trading/crypto-price-api/pairs) for full field reference. ### Get latest market cap for a specific Byreal token Run the query [in the Bitquery IDE](https://ide.bitquery.io/Sandisk---Backpack-Securities-MCAP).
Click to expand GraphQL query ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Address: { is: "token address here" } } Interval: { Time: { Duration: { gt: 1 } } } Market: { Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } } ) { Token { Name Id Address Symbol } Block { Time } Market { Program Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
### Stream Byreal tokens with market cap above $10K Subscribe when the token is on **Solana**, **`Market.Program`** is Byreal, **`Supply.MarketCap`** **> 10,000** (USD), and interval duration **> 1** second. Adjust **`gt`** to change the threshold. Run the subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-stream-byreal-tokens-with-marketcap-above-10k).
Click to expand GraphQL subscription ```graphql subscription { Trading { Pairs( where: { Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 10000 } } Market: { Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
## Latest Price of a Token on Byreal — Crypto Price API Returns the latest **OHLC close**, **average price**, and **volume** for a Byreal pair via **`Trading.Pairs`**. Replace **`token Mint Address`** with your SPL mint. Adjust **`Interval.Time.Duration`** for the candle size (e.g. `60` for 1-minute bars). Run the query [in the Bitquery IDE](https://ide.bitquery.io/latest-price-of-a-token-on-Byreal).
Click to expand GraphQL query ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Market: { Network: { is: "Solana" } Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } Token: { Address: { is: "token Mint Address" } } Interval: { Time: { Duration: { eq: 60 } } } } ) { Block { Time } Market { Address Program Protocol ProtocolFamily } Token { Address Name Symbol } QuoteToken { Address Symbol } Price { IsQuotedInUsd Average { Mean } Ohlc { Open High Low Close } } Volume { Base Quote Usd } Supply { MarketCap FullyDilutedValuationUsd TotalSupply } } } } ```
## Byreal OHLC API — Crypto Price API Fetch historical **OHLC candles** for a Byreal pair. Set **`Interval.Time.Duration`** to your bar size in seconds (`60` = 1 minute, `3600` = 1 hour). Use as a **query** for historical bars; use a **subscription** for live candle updates. Run the query [in the Bitquery IDE](https://ide.bitquery.io/Byreal-OHLC-API).
Click to expand GraphQL query ```graphql { Trading { Pairs( limit: { count: 100 } orderBy: { descending: Block_Time } where: { Market: { Network: { is: "Solana" } Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } Token: { Address: { is: "token Mint Address" } } Interval: { Time: { Duration: { eq: 60 } } } } ) { Block { Time } Interval { Time { Start End Duration } } Token { Address Symbol } QuoteToken { Address Symbol } Price { IsQuotedInUsd Ohlc { Open High Low Close } } Volume { Base Quote Usd } } } } ```
## Get the Top Traders of a specific Token on Byreal — Crypto Trades API Ranks wallets by **quoted USD volume** on Byreal for a given token. Use as a **query** only — aggregates do not work correctly over subscriptions. Run the query [in the Bitquery IDE](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Byreal-DEX).
Click to expand GraphQL query ```graphql { Trading { Trades( limit: { count: 100 } orderBy: { descendingByField: "Total_Volume" } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Pair: { Market: { Network: { is: "Solana" } Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } Token: { Id: { is: "bid:solana:token Mint Address" } } } } ) { Trades_count: count Total_Volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Quote, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) Trader { Address } } } } ```
## Get Trading Volume, Buy Volume, Sell Volume of a Token on Byreal Run the query [in the Bitquery IDE](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token-on-Byreal-DEX).
Click to expand GraphQL query ```graphql { Trading { Trades( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Pair: { Market: { Network: { is: "Solana" } Program: { is: "REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2" } } Token: { Id: { is: "bid:solana:token Mint Address" } } } } ) { Trades_count: count total_volume: sum(of: AmountsInUsd_Quote) buy_volume: sum(of: AmountsInUsd_Quote, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Quote, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) Pair { Token { Address Symbol } QuoteToken { Address Symbol } } } } } ```
## Historical data and aggregates The **Trading APIs** on this page cover **real-time streams** and roughly the **last ~30 days** of Byreal trades, prices, and OHLC. For **older Byreal history** and **historical aggregates** — OHLC candlesticks, volume buckets, and time-series analytics from **May 2024** onward — use chain-level queries on **`Solana(dataset: combined)`** or **`Solana(dataset: archive)`** with **`DEXTradeByTokens`**. Filter by **`Trade.Dex.ProgramAddress`** **`REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2`**. See the full guide with working examples: [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/). For a Byreal-specific historical OHLC starting point, try [Byreal historical OHLC — DEXTradeByTokens](https://ide.bitquery.io/Byreal-historical-OHLC-DEXTradeByTokens) in the IDE (uses **`Solana(dataset: combined)`** and **`Trade.Dex.ProgramAddress`** **`REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2`**). :::note Historical aggregate queries use **`query`** only — **`sum`**, **`count`**, and interval-based OHLC do not work reliably as **`subscription`** websockets. ::: ## Related Documentation - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) - [Crypto Price API — Pairs](/docs/trading/crypto-price-api/pairs) - [Crypto Price API — OHLC](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api) - [Traders API](/docs/trading/crypto-trades-api/traders-api) - [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/) - [Real-time Solana Data Streams](/docs/streams/real-time-solana-data/) - [API Authorization](/docs/authorization/how-to-use/) --- ## Solana Copy Trading Bot with gRPC Streams URL: https://docs.bitquery.io/docs/grpc/solana/examples/grpc-copy-trading-bot/ Solana Copy Trading Bot with gRPC Streams for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Building Solana Copy Trading Bot with gRPC Streams A comprehensive guide to building a **high-performance Solana trading bot** that leverages **gRPC streams** for real-time copy trading using [Bitquery CoreCast](/docs/grpc/solana/introduction/). ## Table of Contents - [Architecture Overview](#architecture-overview) - [Bitquery CoreCast Streams](#bitquery-corecast-integration) - [Streaming Real-Time Solana DEX Trades](#streaming-real-time-solana-dex-trades) - [Trade Execution with Jupiter API](#trade-execution-with-jupiter-api) - [Code Walkthrough](#code-walkthrough) - [Configuration & Filtering](#configuration--filtering) - [Best Practices](#best-practices) - [Output](#output) --- ## Output The final result of this project would appear as the one given below. ## Architecture Overview This **Solana trading bot** implements a streaming architecture for **copy trading**: ``` ┌─────────────────────┐ │ Solana Blockchain │ │ (DEX Trades) │ └──────────┬──────────┘ │ ▼ ┌─────────────────────────────────┐ │ Bitquery CoreCast gRPC Stream │ ← Real-time data streaming │ docs.bitquery.io/docs/grpc/ │ └──────────┬──────────────────────┘ │ ▼ ┌─────────────────────┐ │ gRPC Client │ ← @grpc/grpc-js │ (CoreCast Proto) │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Event Handler │ ← Trade filtering & strategy └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Jupiter Swap API │ ← Optimal trade execution └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Solana Transaction │ ← On-chain execution └─────────────────────┘ ``` Learn more about [Bitquery CoreCast architecture](/docs/grpc/solana/introduction/). --- ## Bitquery CoreCast Integration [Bitquery CoreCast](/docs/grpc/solana/introduction/) provides real-time blockchain data streaming via gRPC for **Solana trading bots**. ```javascript // index.js - Loading Protocol Buffers const { loadPackageDefination } = require('bitquery-corecast-proto'); const packageDefinition = loadPackageDefination(); const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); const solanaCorecast = protoDescriptor.solana_corecast; ``` Reference: [Protobuf Loading Documentation](https://www.npmjs.com/package/bitquery-corecast-proto) --- ## Streaming Real-Time Solana DEX Trades ### Initializing the gRPC Client The bot connects to Bitquery's CoreCast server using the given below code snippet: ```javascript // index.js - Client Initialization function initializeClient() { client = new solanaCorecast.CoreCast( config.server.address, // corecast.bitquery.io grpc.credentials.createSsl() ); metadata = new grpc.Metadata(); metadata.add('authorization', config.server.authorization); } ``` Refer to [this document](/docs/grpc/solana/authorization/) for any issues related to authorization. ### Creating the Stream Multiple [Solana stream topics](/docs/category/topics/) are available: ```javascript // index.js - Stream Creation function startStream() { const request = createRequest(); let stream; switch (config.stream.type) { case 'dex_trades': // Real-time DEX trades stream = client.DexTrades(request, metadata); break; case 'dex_orders': // Order book updates stream = client.DexOrders(request, metadata); break; case 'transactions': // All transactions stream = client.Transactions(request, metadata); break; // ... more stream types } } ``` ### Handling Stream Events The bot processes incoming trade messages in real-time: ```javascript // index.js - Event Handler stream.on('data', async (message) => { if (message.Trade) { // Extract trade data from protobuf message const marketAddress = toBase58(message.Trade.Market?.MarketAddress); const inputMint = toBase58(message.Trade.Buy?.Currency?.MintAddress); const outputMint = toBase58(message.Trade.Sell?.Currency?.MintAddress); const buyAmount = message.Trade.Buy?.Amount; // Apply trading strategy if (approveTrade(buyAmount)) { await executeTrades({ inputMint, outputMint, marketAddress, buyAmount }); } } }); stream.on('error', (error) => { console.error('Stream error:', error); }); stream.on('end', () => { console.log('Stream ended'); }); ``` --- ## Trade Execution with Jupiter API ### Native SOL Conversion Jupiter requires wrapped SOL (wSOL) instead of native SOL for trading. Our bot handles this conversion: ```javascript // trade.js - SOL Mint Conversion const NATIVE_SOL_MINT = '11111111111111111111111111111111'; const WRAPPED_SOL_MINT = 'So11111111111111111111111111111111111111112'; const convertedInputMint = inputMint === NATIVE_SOL_MINT ? WRAPPED_SOL_MINT : inputMint; ``` ### Fetching Swap Quotes We use Jupiter's aggregation API to find optimal swap routes: ```javascript // trade.js - Quote Fetching const jupiter = createJupiterApiClient({ basePath: 'https://quote-api.jup.ag/v6' }); const quoteReq = { inputMint: convertedInputMint, outputMint: convertedOutputMint, amount: amountInRaw, slippageBps: slippageBps.toString(), onlyDirectRoutes: false // Allow indirect routes for better liquidity }; const quote = await jupiter.quoteGet(quoteReq); ``` ### Creating and Sending Transactions Once we have a quote, we build and execute the swap transaction: ```javascript // trade.js - Transaction Execution const swapReq = { quoteResponse: quote, userPublicKey: wallet.publicKey.toString(), wrapAndUnwrapSOL: true, // Handle SOL wrapping automatically asLegacyTransaction: true }; const swapRes = await jupiter.swapPost({ swapRequest: swapReq }); // Deserialize and sign transaction const txBuf = Buffer.from(swapRes.swapTransaction, 'base64'); const tx = Transaction.from(txBuf); tx.sign([wallet]); // Send to Solana network const txSig = await connection.sendRawTransaction( tx.serialize(), { skipPreflight: true, maxRetries: 3 } ); // Wait for confirmation await connection.confirmTransaction(txSig, 'confirmed'); ``` --- ## Code Walkthrough ### Helper Functions #### Base58 Encoding Solana addresses are encoded in base58. We convert byte arrays to base58 strings: ```javascript // index.js - Base58 Conversion function toBase58(bytes) { if (!bytes || bytes.length === 0) return 'undefined'; try { return bs58.encode(bytes); } catch (error) { return 'invalid_address'; } } ``` ### Configuration Management The bot supports hot-reloading of configuration without restart: ```javascript // index.js - Config Watching fs.watch('./config.yaml', (eventType, filename) => { if (eventType === 'change') { clearTimeout(watchTimeout); watchTimeout = setTimeout(() => { reloadAndRestart(); }, 300); // Debounce rapid changes } }); ``` ### Trading Strategy Implement your **copy trading** logic in the `approveTrade()` function: ```javascript // index.js - Trade Approval Logic function approveTrade(buyAmount) { // Example: Only approve large trades if (buyAmount > 100 * 1000000000) { console.log('Approving large trade:', buyAmount); return true; } return false; } ``` **Strategy Ideas:** - Volume-based filtering - Token whitelist/blacklist - Risk management (max position size) - Cooldown periods - Multi-signal confirmation --- ## Configuration & Filtering ### Stream Configuration Configure which on-chain activity to monitor: ```yaml # config.yaml stream: type: "dex_trades" # Real-time DEX trades ``` **Available Stream Types:** - `dex_trades` - [DEX trades](/docs/grpc/solana/topics/dextrades/) - `dex_orders` - [Order book data](/docs/grpc/solana/topics/dexorder/) - `dex_pools` - [Pool liquidity events](/docs/grpc/solana/topics/dexpools/) - `transactions` - [All transactions](/docs/grpc/solana/topics/transactions/) - `transfers` - [Token transfers](/docs/grpc/solana/topics/transfer/) - `balances` - [Balance updates](/docs/grpc/solana/topics/balance/) ### Filters Use [filtering options](/docs/grpc/solana/topics/dextrades/#filtering-options) to target specific trades: ```yaml # config.yaml filters: traders: # Copy trades from specific addresses - "HV1KXxWFaSeriyFvXyx48FqG9BoFbfinB8njCJonqP7K" programs: # Filter by DEX programs - "..." pool: # Filter by liquidity pools - "..." signers: # Filter by transaction signers - "..." ``` ```javascript // index.js - Request Builder function createRequest() { const request = {}; if (config.filters.traders?.length > 0) { request.trader = { addresses: config.filters.traders }; } if (config.filters.programs?.length > 0) { request.program = { addresses: config.filters.programs }; } // ... more filter types return request; } ``` --- ## Best Practices ### 1. Error Handling Implement comprehensive error handling for network failures: ```javascript // trade.js - Error Handling try { const quote = await jupiter.quoteGet(quoteReq); } catch (error) { console.error('Jupiter API error:', error.response?.data || error.message); // Implement retry logic or fallback } ``` ### 2. Rate Limiting To avoid being rate-limited by Jupiter: ```javascript // Add delays between trades await new Promise(resolve => setTimeout(resolve, 1000)); ``` ### 3. Monitoring Log all trade executions for analysis: ```javascript console.log('✅ Copy trade executed!', { tx: txSig, inputMint, outputMint, amount: buyAmount }); ``` ### 4. Security - Keep API keys in `secrets.json` (never commit) - Use separate trading wallet - Set maximum trade amounts - Implement stop-loss mechanisms ### 5. Testing Start with small amounts: ```javascript // Reduce trade amount for testing amountInRaw: (buyAmount / 100).toString() // 1% of original ``` --- ## Additional Resources ### Bitquery Documentation - [CoreCast Introduction](/docs/grpc/solana/introduction) - [Authentication Guidelines](/docs/grpc/solana/authorization/) - [Best Practices for gRPC streams](/docs/grpc/solana/best_practices/) - [Other Solana gRPC Examples](/docs/category/examples/) - [Error Handling](/docs/grpc/solana/errors/) ### External APIs - [Jupiter Swap API](https://dev.jup.ag/docs/swap/) - [Solana Web3.js](https://solana-foundation.github.io/solana-web3.js/) - [Solana RPC](https://docs.solana.com/api/http) ### Get Started [Sign up for Bitquery CoreCast](https://account.bitquery.io/auth/signup) and start building your **Solana copy trading bot** today! --- ## Solana DEX Orders - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/dexorder/ Solana DEX Orders - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana DEX Orders gRPC Stream The `dex_orders` gRPC Stream provides real-time DEX order placement and execution data across supported Solana protocols. --- ## Overview Subscribe to live DEX order book events (place, cancel, fill) from OpenBook, Serum, and other order-book DEXs. Each event includes order details, market info, and balance updates. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. ## Configuration To subscribe to DEX orders, configure your stream as follows: ```yaml stream: type: "dex_orders" ``` ## Available Data The DEX orders stream provides comprehensive order information including: - **Transaction details**: Slot, signature, status, fees (in native and USD) - **Account information**: Signers, token accounts, program IDs - **Token context**: Mint addresses, decimals, owners, metadata - **Order specifics**: Order IDs, prices, amounts, order types, buy/sell sides - **Market data**: Market addresses, base/quote currencies, order books - **Balance updates**: Pre/post balances for accounts and token accounts ## Sample Data Structure Here's an example of the data structure you'll receive: ```json { "Block": { "Slot": 370028492 }, "Transaction": { "Index": 779, "Signature": "2eoFGRLxJFXhLGBXS4dPgSGYfjF9yGx3Tfc4EgJqrndiMqTX22SZwaH1E8E8p7333z2CWqofY8YvJgB7DN6hJv1L", ... }, "Order": { "InstructionIndex": 7, "Type": 0, "Dex": { "ProgramAddress": "opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb", "ProtocolName": "openbook_v2", "ProtocolFamily": "OpenBook" }, "Market": { "MarketAddress": "6NtxTCJuhNixA5Z2MBT4mrCuBk7qLQ69htcCNfySdu7J", "BaseCurrency": { ... }, "QuoteCurrency": { ... } }, "Order": { "OrderId": "11111111", "BuySide": true, "LimitPrice": 9223372036854775807, "LimitAmount": 92233720368547, "Account": "2qwiCSJJuDz3AX39LvgSGhPKoWeTSBAJvqzNwYNQAavj", "Owner": "2qwiCSJJuDz3AX39LvgSGhPKoWeTSBAJvqzNwYNQAavj", "Mint": "So11111111111111111111111111111111111111112" }, "Instruction": { "Index": 7, "Program": { "Address": "opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb", "Name": "openbook_v2", "Method": "placeTakeOrder" }, "Arguments": [ { "Name": "args", "Type": "PlaceTakeOrderArgs", "Json": "{\"side\":0,\"priceLots\":9223372036854775807,\"maxBaseLots\":92233720368547,\"maxQuoteLotsIncludingFees\":443279519,\"orderType\":3,\"limit\":50}" } ], "AccountNames": [ "signer", "penaltyPayer", "market", "marketAuthority", "bids", "asks", "marketBaseVault", "marketQuoteVault", "eventHeap", "userBaseAccount", "userQuoteAccount" ] }, "BalanceUpdates": [ { "PreBalance": 13595078208, "PostBalance": 13151798872, "AccountIndex": 2 } ], "TokenBalanceUpdates": [ { "PreBalance": 13593036926, "PostBalance": 13149757590, "AccountIndex": 2 }, { "PreBalance": 77176413, "PostBalance": 436576413, "AccountIndex": 3 } ] } } ``` ## Key Points - **Order tracking**: Monitor real-time order placement and execution on DEX order books - **Order book data**: Access to bids, asks, and order book state changes - **Token metadata**: Comprehensive token information including metadata and collection details - **Instruction parsing**: Detailed instruction data with arguments and account mappings - **Balance changes**: Track both native SOL and token balance updates - **Multiple protocols**: Supports various DEX protocols including OpenBook, Serum, and other order book DEXs ## Filtering Options The filter options are defined in the `request.proto` file. You can filter DEX orders using the following filters: ```protobuf message SubscribeOrdersRequest { AddressFilter program; AddressFilter pool; AddressFilter token; AddressFilter trader; } ``` Available filters: - **program**: Filter by DEX program address - **pool**: Filter by specific pool/market address - **token**: Filter by token mint address (e.g., WSOL, USDC) - **trader**: Filter by trader's wallet address ## Order Data Fields - **OrderId**: Unique identifier for the order - **BuySide**: Boolean indicating if it's a buy order (true) or sell order (false) - **LimitPrice**: The price limit for the order - **LimitAmount**: The maximum amount to be traded - **Account**: The order account address - **Owner**: The order owner address - **Payer**: The account paying for the order - **Mint**: The token mint address for the order ## Schema Reference - **Protobuf Schema**: [dex_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/dex_block_message.proto) - **Sample Data**: [solana_dex_order.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_dex_order.json) ## Python Installation For Python development, install the protobuf package: ```bash pip install bitquery-corecast-proto ``` ## NPM Package ```bash npm install bitquery-corecast-proto ``` This package includes all necessary protobuf definitions without requiring manual downloads. --- ## Related - [CoreCast Introduction](/docs/grpc/solana/introduction/) — Topics and concepts - [DEX Trades gRPC](/docs/grpc/solana/topics/dextrades/) — DEX swap stream - [Copy Trading Bot](/docs/grpc/solana/examples/grpc-copy-trading-bot/) — Uses dex_orders - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana DEX Orders API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-DEX-Orders-API/ Solana DEX orders: real-time order stream, latest orders for a token, orders above a limit price, open orders, and OpenBook DEX orders. # Solana DEX Orders API :::tip Need real-time Solana DEX orders data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Solana DEX orders swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Solana DEX orders data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section, you'll learn how to access Solana-based decentralized exchange (DEX) trading data using our DEX Orders API. ## Get Solana DEX Orders in Real-Time This query provides real-time updates on order events, including details about the DEX, market, and order specifics. You can run the query [here](https://ide.bitquery.io/Copy-of-Solana-DEX-trades-API) ```graphql subscription { Solana { DEXOrders { Instruction { Index Program { Address AccountNames Name Method } } OrderEvent { Dex { ProtocolName ProtocolFamily ProgramAddress } Index Market { MarketAddress CoinToken { Wrapped VerifiedCollection Uri UpdateAuthority TokenStandard Symbol TokenCreator { Share Address } Name Key Fungible CollectionAddress } PriceToken { Wrapped VerifiedCollection Uri TokenStandard Native Name MetadataAddress Key Fungible Decimals CollectionAddress } } Order { BuySide Account Payer OrderId Owner } Type } } } } ``` ## Latest DEX Orders of a Token To fetch the most recent orders for a specific token, filter using the token's `MintAddress`. Replace the example address in the query with the target token's address. You can run the query [here](https://ide.bitquery.io/Latest-DEXOrders-for-token-on-Solana) ```graphql { Solana(dataset: realtime) { DEXOrders( where: {OrderEvent: {Market: {BaseCurrency: {MintAddress: {is: "6kdU2J4pSxG2w1sBLqrtE8BCisQwa3t12hRdkb13JGeu"}}}}} orderBy: {descending: Block_Time} ) { OrderEvent { Dex { ProtocolName ProgramAddress } Index Market { MarketAddress QuoteCurrency { Name Symbol MintAddress } BaseCurrency { Name MintAddress } } Order { Account BuySide LimitPrice LimitAmount OrderId } } } } } ``` ## DEX Orders Above a Limit Price You can filter orders based on specific price conditions, such as all orders with a `LimitPrice` greater than a specified value. Modify the price threshold and token address as needed. You can run the query [here](https://ide.bitquery.io/LimitPrice-DEXOrders-for-token-on-Solana) ```graphql { Solana(dataset: realtime) { DEXOrders( where: {OrderEvent: {Market: {BaseCurrency: {MintAddress: {is: "6kdU2J4pSxG2w1sBLqrtE8BCisQwa3t12hRdkb13JGeu"}}}, Order: {LimitPrice: {gt: "0.068"}}}} orderBy: {descending: Block_Time} ) { OrderEvent { Dex { ProtocolName ProgramAddress } Index Market { MarketAddress QuoteCurrency { Name Symbol MintAddress } BaseCurrency { Name MintAddress } } Order { Account BuySide LimitPrice LimitAmount OrderId } } } } } ``` ## Latest Open Orders on Solana This query retrieves the latest open orders on Solana-based DEXs. Open orders are those that have been created but not yet executed or canceled. You can run the query [here](https://ide.bitquery.io/Latest-Open-DEX-Orders-Solana) ```graphql { Solana(dataset: realtime) { DEXOrders( where: {OrderEvent: {Type: {is: Open}}} orderBy: {descending: Block_Time} ) { OrderEvent { Dex { ProtocolName ProgramAddress } Index Market { MarketAddress QuoteCurrency { Name Symbol MintAddress } BaseCurrency { Name MintAddress } } Order { Account BuySide LimitPrice LimitAmount OrderId } } } } } ``` ## Latest OpenBook DEX Orders This query fetches the latest orders from the OpenBook DEX on Solana, providing comprehensive information about the DEX protocol, market, order specifics, and transaction details. OpenBook is an exchange protocol offering central limit orderbook for top Solana DeFi protocols. You can run the query [here](https://ide.bitquery.io/Latest-Openbook-DEX-Orders#) ```graphql { Solana(dataset: realtime) { DEXOrders( where: {OrderEvent: {Dex: {ProgramAddress: {is: "srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"}}}} orderBy: {descending: Block_Time} ) { OrderEvent { Dex { ProtocolName ProgramAddress } Type Order { Account BuySide LimitPrice LimitAmount OrderId } Market { MarketAddress QuoteCurrency { Name Symbol MintAddress } BaseCurrency { Name MintAddress } } Index } Transaction { Signature } Block { Time Hash } } } } ``` ## Video Tutorials --- ## Solana DEX Pools - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/dexpools/ Solana DEX Pools - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana DEX Pools gRPC Stream The `dex_pools` gRPC Stream provides real-time DEX pool liquidity and balance change data across supported Solana protocols. --- ## Overview Subscribe to live DEX pool events: liquidity adds, removes, swaps, and pool creation. Each event includes base/quote changes, market info, and balance updates. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. ## Configuration To subscribe to DEX pool events, configure your stream as follows: ```yaml stream: type: "dex_pools" ``` ## Available Data The DEX pools stream provides comprehensive pool information including: - **Transaction details**: Slot, signature, status, fees (in native and USD) - **Account information**: Signers, token accounts, program IDs - **Token context**: Mint addresses, decimals, owners, metadata - **Pool specifics**: Market addresses, base/quote currencies, liquidity changes - **Balance updates**: Pre/post balances showing pool liquidity changes and token account updates - **Instruction details**: Parsed instruction data with arguments and account names ## Sample Data Structure Here's an example of the data structure you'll receive: ```json { "Block": { "Slot": 370028492 }, "Transaction": { ... }, "PoolEvent": { "InstructionIndex": 8, "Dex": { "ProgramAddress": "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA", "ProtocolName": "pump_amm", "ProtocolFamily": "Pumpswap" }, "Market": { "MarketAddress": "DMoLXDc89o5cUUuvXiteSC3egpcKFwpcjevZrzqLU1o8", "BaseCurrency": { "Name": "Wrapped Solana", "Decimals": 9, "Symbol": "WSOL", "MintAddress": "So11111111111111111111111111111111111111112", "ProgramAddress": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }, "QuoteCurrency": { "Name": "10/1", "Decimals": 6, "Symbol": "10/1", "MintAddress": "BvtbWHDU5sNwtNitWYmNBAEu6Dfu5TWDBnTBHR7w4HZt", "ProgramAddress": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" } }, "BaseCurrency": { "ChangeAmount": 38023549, "PostAmount": 166166127607 }, "QuoteCurrency": { "ChangeAmount": -76102597, "PostAmount": 333332214494 }, "Instruction": { "Index": 8, "Program": { "Address": "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA", "Name": "pump_amm", "Method": "sell" }, "Arguments": [ { "Name": "base_amount_in", "Type": "u64", "UInt": 38023549 }, { "Name": "min_quote_amount_out", "Type": "u64", "UInt": 38103732 } ], ... }, "BalanceUpdates": [ { "PreBalance": 40062829, "PostBalance": 2039280, "AccountIndex": 1 } ], "TokenBalanceUpdates": [ { "PreBalance": 166128104058, "PostBalance": 166166127607, "AccountIndex": 3 }, { "PreBalance": 333408317091, "PostBalance": 333332214494, "AccountIndex": 4 } ] } } ``` ## Filtering Options The filter options are defined in the `request.proto` file. You can filter DEX pool events using the following filters: ```protobuf message SubscribePoolsRequest { AddressFilter program; AddressFilter pool; AddressFilter token; } ``` Available filters: - **program**: Filter by DEX program address - **pool**: Filter by specific pool/market address - **token**: Filter by token mint address (e.g., WSOL, USDC) ## Pool Event Types The DEX pools stream captures various pool-related events: - **Liquidity additions**: When liquidity is added to pools - **Liquidity removals**: When liquidity is withdrawn from pools - **Swap events**: When trades occur that affect pool balances - **Pool creation**: When new pools are created - **Pool updates**: When pool parameters are modified ## Schema Reference - **Protobuf Schema**: [dex_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/dex_block_message.proto) - **Sample Data**: [solana_pool_event.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_dex_pool.json) ## Python Installation For Python development, install the protobuf package: ```bash pip install bitquery-corecast-proto ``` ## NPM Package ```bash npm install bitquery-corecast-proto ``` This package includes all necessary protobuf definitions without requiring manual downloads. --- ## Related - [CoreCast Introduction](/docs/grpc/solana/introduction/) — Topics and concepts - [DEX Trades gRPC](/docs/grpc/solana/topics/dextrades/) — DEX swap stream - [Pump.fun gRPC Example](/docs/grpc/solana/examples/pump-fun-grpc-streams/) — Uses dex_pools - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana DEX Pools API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-DexPools-API/ Query Solana liquidity pools with Bitquery GraphQL: pool updates in real time, tokens above a liquidity threshold, per-token pools and latest reserves. # Solana DEX Pools API :::tip Which API for Solana pool data? `DEXPools` is served from the realtime dataset and covers the last few hours. For older history and one USD price per token across pools, use the [**Trading cube**](/docs/trading/trading-data-overview). For the price each pool quotes after every event, see [**Solana Liquidity Pool Price API**](/docs/blockchain/Solana/solana-pool-price). Pool and liquidity data ships with the [Solana DEX API](https://bitquery.io/products/solana-dex-api), which covers venues, plans and real-time delivery. ::: In this section we will see how to get Solana DEX Pools information using our API. ## Get all Liquidity Pools updates on Solana To get all Liquidity pools updates on solana use [this stream](https://ide.bitquery.io/solana-dex-pools-update-stream).
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools { Block { Time } Pool { Base { ChangeAmount PostAmount } Quote { ChangeAmount PostAmount } Dex { ProgramAddress ProtocolFamily } Market { BaseCurrency { MintAddress Name Symbol } QuoteCurrency { MintAddress Name Symbol } MarketAddress } } } } } ```
## Get Tokens which have liquidity over 1 Million USD You can use the below query to get the tokens which are getting traded and have liquidity over 1 million USD. Try out the query [here](https://ide.bitquery.io/Search-tokens-with-liquidity-over-1-million#).
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { DEXPools( where: {Pool: {Base: {PostAmountInUSD: {ge: "1000000"}}, Market: {QuoteCurrency: {MintAddress: {in: ["11111111111111111111111111111111", "So11111111111111111111111111111111111111112"]}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature } Pool { Base { PostAmount PostAmountInUSD } Quote{ PostAmount PostAmountInUSD } Market { MarketAddress BaseCurrency { MintAddress Name Symbol } QuoteCurrency { Name MintAddress Symbol } } Dex { ProtocolFamily ProgramAddress ProtocolName } Market { MarketAddress BaseCurrency { MintAddress Name Symbol } QuoteCurrency { Name MintAddress Symbol } } } } } } ```
## Get All Liquidity Pools info for a particular token This query will give you the information on all the liquidity pools of a particular token `EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm`. You can find the query [here](https://ide.bitquery.io/get-all-the-liquidity-pools-info-for-a-particular-token_1)
Click to expand GraphQL query ```graphql query ($token: String) { Solana { DEXPools( orderBy: {descendingByField: "Pool_Quote_PostAmountInUSD_maximum"} where: {Pool: {Market: {BaseCurrency: {MintAddress: {is: $token}}}}} ) { Pool { Market { QuoteCurrency { Symbol Name MintAddress } MarketAddress } Dex { ProtocolFamily } Base { PostAmount(maximum: Block_Slot) PostAmountInUSD(maximum: Block_Slot) } Quote { PostAmount(maximum: Block_Slot) PostAmountInUSD(maximum: Block_Slot) } } } } } ``` ```json { "token": "EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm" } ```
![image](https://github.com/user-attachments/assets/21882e2a-e769-4703-be56-15b7924b6318) Check data here on [DEXrabbit](https://dexrabbit.bitquery.io/solana/token/EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm#pools). ## Get Latest Liquidity for All Pools of a Token Use this query to get latest liquidity snapshots for all pools where a token appears either on the base side or quote side. Try the query [here](https://ide.bitquery.io/liqidity-of-all-pools-of-a-token)
Click to expand GraphQL query ```graphql query GetLatestLiquidityForPool { Solana(dataset: realtime) { DEXPools( where: { Pool: { Market: { BaseCurrency: { Name: { not: "" } } QuoteCurrency: { Name: { not: "" } } } } any: [ { Pool: { Market: { BaseCurrency: { MintAddress: { is: "F5tfztTnE4sYsMhZT5KrFpWvHmYSfJZoRjCuxKPbpump" } } } } } { Pool: { Market: { QuoteCurrency: { MintAddress: { is: "F5tfztTnE4sYsMhZT5KrFpWvHmYSfJZoRjCuxKPbpump" } } } } } ] Transaction: { Result: { Success: true } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount(maximum: Block_Slot) PostAmountInUSD(maximum: Block_Slot) } Base { PostAmount(maximum: Block_Slot) PostAmountInUSD(maximum: Block_Slot) } } } } } ```
## Latest Price of Token Based on Liquidity Each pool event carries the pool's own price in `Pool { Price { Price PriceInUSD Source } }`. To stream it for every pool of a token, use [Live pool prices of a token](/docs/blockchain/Solana/solana-pool-price#live-pool-prices-of-a-token) ([run query](https://ide.bitquery.io/Solana-pool-prices-of-token-stream)). How each venue's price is read is in [Solana Liquidity Pool Price API](/docs/blockchain/Solana/solana-pool-price#how-it-is-derived). ## Get Latest Liquidity of any Liquidity Pool This query gets you the liquidity/balance of the Quote Currency `WSOL` and Base Currency `SOLANADOG` for this particular pool address `BDQnwNhTWc3wK4hhsnsEaBBMj3sD4idGzvuidVqUw1vL`. THe liquidity value of the currencies will be in `Quote{PostAmount}` and `Base{PostAmount}`. You can find the query [here](https://ide.bitquery.io/Get-LP-Latest-liqudity-on-Solana)
Click to expand GraphQL query ```graphql query GetLatestLiquidityForPool { Solana(dataset: realtime) { DEXPools( where: { Pool: { Market: { MarketAddress: { is: "HktfL7iwGKT5QHjywQkcDnZXScoh811k7akrMZJkCcEF" } } } Transaction: { Result: { Success: true } } } orderBy: { descending: Block_Slot } limit: { count: 1 } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PostAmountInUSD } Base { PostAmount } } } } } ```
## Get Locked Liquidity of a Pool on Solana This query retrieves the locked liquidity of a pool on Solana by querying balance updates for a specific pool account owner and currency. The locked liquidity is calculated as twice the balance of WSOL in USD (since pools typically have two tokens locked). You can find the query [here](https://ide.bitquery.io/get-locked-liquidity-of-a-pool-on-Solana).
Click to expand GraphQL query ```graphql query MyQuery { Solana { BalanceUpdates( where: { BalanceUpdate: { Account: { Owner: { is: "FPY1pAp1xLq2hihs1Tm2tE2F8VQThXhLBvvZnvdfHCTb" } } Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } orderBy: { descendingByField: "BalanceUpdate_Balance_maximum" } ) { BalanceUpdate { Balance: PostBalanceInUSD(maximum: Block_Slot) Currency { Name Symbol MintAddress } } locked_liquidity: calculate(expression: "$BalanceUpdate_Balance*2") } } } ```
## Get Top Pools Based on Liquidity [This](https://ide.bitquery.io/top-10-liquidity-pools_1) query retrieves the top liquidity pools on the Solana blockchain, sorted by their total liquidity (PostAmount). The query is filtered for pools that have been active since a specific time period. The results are limited to the top 10 pools based on their liquidity.
Click to expand GraphQL query ```graphql query GetTopPoolsByDex { Solana { DEXPools( orderBy: { descending: Pool_Quote_PostAmount } where: { Block: { Time: { after: "2024-08-27T12:00:00Z" } } Transaction: { Result: { Success: true } } } limit: { count: 10 } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolName ProtocolFamily } Quote { PostAmount PostAmountInUSD } Base { PostAmount } } } } } ```
## Liquidity Add Events Tracked Using Instructions This query tracks liquidity addition events on Solana DEX pools by monitoring specific instructions. [ Run query](https://ide.bitquery.io/All-liquidity-add-instructions-track-on-Solana#)
Click to expand GraphQL query ```graphql { Solana(network: solana) { DEXPools( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Method: {in: ["add_liquidity", "addLiquidity", "increase_liquidity", "increaseLiquidity", "increase_liquidity_v2", "deposit", "depositAllTokenTypes", "join", "provide_liquidity"]}}}} ) { Pool { Market { MarketAddress BaseCurrency { Symbol Name MintAddress } QuoteCurrency { Symbol Name MintAddress } } Base { ChangeAmount ChangeAmountInUSD PostAmount PostAmountInUSD } Quote { ChangeAmount ChangeAmountInUSD PostAmount PostAmountInUSD } Dex { ProtocolName ProtocolFamily } } Block { Time } Transaction { Signature } } } } ```
## Liquidity Remove Events Tracked Using Withdraw Instruction This query tracks liquidity removal events on Solana DEX pools by monitoring withdraw instructions. [ Run query](https://ide.bitquery.io/Copy-of-Solana-DEXPools-withdraw)
Click to expand GraphQL query ```graphql { Solana(network: solana) { DEXPools( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Method: {is: "withdraw"}}}} ) { Pool { Market { MarketAddress BaseCurrency { Symbol Name MintAddress } QuoteCurrency { Symbol Name MintAddress } } Base { ChangeAmount ChangeAmountInUSD PostAmount PostAmountInUSD } Quote { ChangeAmount ChangeAmountInUSD PostAmount PostAmountInUSD } Dex { ProtocolName ProtocolFamily } } Block { Time } Transaction { Signature } } } } ```
## Liquidity Events for Raydium Pairs In this section, we will discover data streams that provides us with the real time events of liquidity addition and liquidity removal for the Raydium DEX, which has `675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8` as the Program Address. ### Liquidity addition for Raydium Pairs [This](https://ide.bitquery.io/liquidity-addition-for-Raydium_1) subscription returns the real-time liquidity addition event details for the Raydium Pairs.
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } Base: { ChangeAmount: { gt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
### Liquidity removal for Raydium Pairs [This](https://ide.bitquery.io/liquidity-removal-for-Raydium_1) subscription returns the real-time liquidity addition event details for the Raydium Pairs.
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } Base: { ChangeAmount: { lt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
## Liquidity Events for Orca Whirlpool Pairs In this section, we will discover data streams that provides us with the real time events of liquidity addition and liquidity removal for the Orca Whirlpool DEX, which has `whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc` as the Program Address. ### Liquidity addition for Orca Whirlpool Pairs [This](https://ide.bitquery.io/liquidity-addition-for-orca-whirlpool_1) subscription returns the real-time liquidity addition event details for the Orca Whirlpool Pairs.
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } Base: { ChangeAmount: { gt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
### Liquidity removal for Orca Whirlpool Pairs [This](https://ide.bitquery.io/liquidity-removal-for-orca-whirlpool_1) subscription returns the real-time liquidity addition event details for the Orca Whirlpool Pairs.
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProgramAddress: { is: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" } } Base: { ChangeAmount: { lt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
## Liquidity Events for Meteora Pairs In this section, we will discover data streams that provides us with the real time events of liquidity addition and liquidity removal for the Meteora DEX, which has `Meteora` as the Protocol Family. ### Liquidity addition for Meteora Pairs [This](https://ide.bitquery.io/liquidity-addition-for-meteora_1) subscription returns the real-time liquidity addition event details for the Meteora Pairs.
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProtocolFamily: { is: "Meteora" } } Base: { ChangeAmount: { gt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
### Liquidity removal for Meteora Pairs [This](https://ide.bitquery.io/liquidity-removal-for-meteora_1) subscription returns the real-time liquidity addition event details for the Meteora Pairs.
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools( where: { Pool: { Dex: { ProtocolFamily: { is: "Meteora" } } Base: { ChangeAmount: { lt: "0" } } } } ) { Pool { Market { MarketAddress BaseCurrency { MintAddress Symbol Name } QuoteCurrency { MintAddress Symbol Name } } Dex { ProtocolFamily ProtocolName } Quote { PostAmount PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
## How DEXPools Values Are Calculated What `PostAmount` measures, when its USD value is priced, and how to order updates that land in the same slot. Read this before feeding `DEXPools` into a simulator, bot or risk model. ### What `Base.PostAmount` and `Quote.PostAmount` represent `PostAmount` is the pool's **vault balance** of that token after the event, read from the on-chain token balances. `Base.PostAmount + Quote.PostAmount` is therefore everything the pool holds, not just the liquidity that is currently tradable. For concentrated-liquidity pools (Raydium CLMM `amm_v3`, Orca Whirlpool, Meteora DLMM) this includes liquidity in positions that are out of range. It is not the active in-range liquidity at the current tick. For constant-product pools (Raydium `raydium_amm`, `raydium_cp_swap`, PumpSwap) the vault balances are the reserves the swap formula uses. `ChangeAmount` is the signed change that event caused: positive when tokens entered the pool, negative when they left. ### How `PostAmountInUSD` is priced `PostAmountInUSD` = `PostAmount` × the token's USD price from the Bitquery [price index](/docs/trading/crypto-price-api/price-index-algorithm). The same rule fills `ChangeAmountInUSD`. The price is looked up at the block's timestamp: you get the latest index price at or before `Block.Time`, never a later one. Every row in the same block uses the same USD price for a given token. The index price is a volume-weighted blend of the token's pools over a rolling 1-hour window, with recent trades weighted more. Stablecoins take their USD price from an external spot source instead. If the index has no price for a token, its `PostAmountInUSD` is `0`. USD values carry about 7 significant digits, so use `PostAmount` when you need exact amounts. ### How fresh the USD price is The response has no field for the timestamp or source of the price used in the conversion. For actively traded tokens the index updates every few seconds. For thinly traded tokens the last index price can be minutes old, because pools stay in the 1-hour blend after they stop trading. If your system needs a strict freshness limit, take the native `PostAmount` from `DEXPools` and price it yourself with [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) or [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) at a 1-second interval. Every Trading row carries its own `Block.Time`, so you can reject prices older than your limit. ### Pool price vs `PostAmountInUSD` `PostAmountInUSD` divided by `PostAmount` will not match the pool's price. `PostAmountInUSD` uses the price index, which blends all of the token's pools. The pool's own price is `Pool.Price`, documented in [Solana Liquidity Pool Price API](/docs/blockchain/Solana/solana-pool-price). `Base.Price` / `Quote.Price` (and their `InUSD` versions) are only the ratio of the row's vault balances. They are wrong on bonding curves and concentrated pools, so use `Pool.Price` instead. ### Ordering multiple updates within one slot A busy pool can change several times in one slot. Sort by these four fields to get a deterministic order: 1. `Block.Slot` 2. `Transaction.Index`: position of the transaction in the block 3. `Instruction.Index`: position of the instruction in the transaction 4. `Instruction.InternalSeqNumber`: tie-breaker for inner instructions Sorted descending on all four, the first row is the pool's latest state. The query below returns the latest 20 updates of one pool, newest first. For only the latest state, see [Get Latest Liquidity of any Liquidity Pool](#get-latest-liquidity-of-any-liquidity-pool).
Click to expand GraphQL query ```graphql query PoolUpdatesInOrder($market: String) { Solana(dataset: realtime) { DEXPools( limit: { count: 20 } orderBy: [ { descending: Block_Slot } { descending: Transaction_Index } { descending: Instruction_Index } { descending: Instruction_InternalSeqNumber } ] where: { Pool: { Market: { MarketAddress: { is: $market } } } Transaction: { Result: { Success: true } } } ) { Block { Time Slot } Transaction { Index Signature } Instruction { Index InternalSeqNumber } Pool { Base { PostAmount PostAmountInUSD } Quote { PostAmount PostAmountInUSD } } } } } ``` ```json { "market": "DmAsjXoceoL5vTKZbYpTpXPo7MKm16FMfNMm3PJFiUha" } ```
--- ## Solana DEX Trades - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/dextrades/ Solana DEX Trades - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana DEX Trades gRPC Stream The `dex_trades` gRPC Stream provides real-time DEX trade/swap data across supported Solana protocols (Pump.fun, Raydium, Orca, Jupiter, and more). --- ## Overview Subscribe to live DEX swaps with context-aware filtering. Each event includes transaction details, token context, trade amounts, and market address. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. :::note Filters required At least one filter per subscription. See [Filtering Options](#filtering-options). ::: ## Configuration To subscribe to DEX trades, configure your stream as follows: ```yaml server: address: "corecast.bitquery.io" authorization: "" insecure: false stream: type: "dex_trades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Pump.fun example ``` --- ## Available Data The DEX trades stream provides comprehensive trade information including: - **Transaction details**: Slot, signature, status, fees (in native and USD) - **Account information**: Signers, token accounts, program IDs - **Token context**: Mint addresses, decimals, owners - **Trade specifics**: Amounts, protocols, pools - **Balance updates**: Pre/post balances for accounts and token accounts, showing pool liquidity changes ## Sample Data Structure Here's an example of the data structure you'll receive: ```json { "Block": { "Slot": 370028492 }, "Transaction": { "Index": 779, "Signature": "2eoFGRLxJFXhLGBXS4dPgSGYfjF9yGx3Tfc4EgJqrndiMqTX22SZwaH1E8E8p7333z2CWqofY8YvJgB7DN6hJv1L", "Status": { "Success": true, "ErrorMessage": "" }, "Header": { ... "Accounts": [...] } }, "Trade": { "InstructionIndex": 9, "Dex": { "ProgramAddress": "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA", "ProtocolName": "pump_amm", "ProtocolFamily": "Pumpswap" }, "Market": { "MarketAddress": "6pSvYm5Yff625pUPAWNDmhccHMqw1itAyjoV2DGpDTDJ", "BaseCurrency": { ... }, "QuoteCurrency": { ... } }, "Buy": { "Amount": 2797967683010, "Currency": { ... }, "Account": { ... } }, "Sell": { "Amount": 6645427517, "Currency": { ... }, "Account": { ... } } } } ``` ## Key Points - **No price data**: Prices are not included as they're not on-chain information. Calculate prices from token amounts and decimals. - **Token context**: Each token account includes mint address, owner, decimals, and program ID. - **Multiple protocols**: Supports various DEX protocols on Solana. ## Filtering Options The filter options are defined in the `request.proto` file. You can filter DEX trades using the following filters: ```protobuf message SubscribeTradesRequest { AddressFilter program; AddressFilter pool; AddressFilter token; AddressFilter trader; } ``` Available filters: - **program**: Filter by DEX program address - **pool**: Filter by specific pool/market address - **token**: Filter by token mint address (e.g., WSOL, USDC) - **trader**: Filter by trader's wallet address ## Schema Reference - **Protobuf Schema**: [dex_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/dex_block_message.proto) - **Sample Data**: [solana_trade.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_trade.json) ## Python Installation For Python development, install the protobuf package: ```bash pip install bitquery-corecast-proto ``` ## NPM Package ```bash npm install bitquery-corecast-proto ``` This package includes all necessary protobuf definitions without requiring manual downloads. --- ## Related - [CoreCast Introduction](/docs/grpc/solana/introduction/) — Topics and concepts - [Pump.fun gRPC Example](/docs/grpc/solana/examples/pump-fun-grpc-streams/) — Full Pump.fun app - [Copy Trading Bot](/docs/grpc/solana/examples/grpc-copy-trading-bot/) — Solana copy trading - [Solana DEX Trades (GraphQL)](/docs/blockchain/Solana/solana-dextrades) — WebSocket subscriptions - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana DEX Trades API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-dextrades/ Stream Solana DEX swaps, prices, and OHLC for Raydium, Jupiter, and more using Bitquery GraphQL queries and live streams. # Solana DEX Trades API :::tip Need real-time Solana DEX data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API** (filter with `Pair.Market.Network: Solana`). Use this page when you need **historical Solana data older than ~30 days** (with `dataset: archive`), raw per-swap detail, or call / event context. Everything on this page is part of the [Solana DEX API](https://bitquery.io/products/solana-dex-api). The product page summarizes venues, OHLCV, pools and streaming latency. :::caution Archive `DEXTradeByTokens` totals run short On `DEXTradeByTokens`, `Solana(dataset: archive)` returns fewer trades than `realtime` over a window both cover, measured at roughly a fifth to a quarter short on several busy markets, with volume short by a similar margin. `dataset: combined` adds the realtime tail on top of the same archive rows, so the shortfall applies to its archive part too. The `DEXTradeByTokens` history queries below name `archive`. When a total has to be exact for the last 30 days, read it from the [Trading API](/docs/trading/crypto-trades-api/trades-api/) instead. For per-trade history on `DEXTrades`, see [Historical DEXTrades on archive and combined](#historical-dextrades-archive-combined). See [data coverage & retention](/docs/graphql/data-coverage-retention/). ::: ::: Bitquery provides Solana DEX trade data through APIs, Streams, and Data Dumps. The GraphQL APIs and subscriptions below are examples of the real-time and historical trade data you can access across [Raydium](/docs/blockchain/Solana/Solana-Raydium-DEX-API/), [Orca](/docs/blockchain/Solana/solana-orca-dex-api/), [Phoenix](/docs/blockchain/Solana/Solana-Phoenix-api/), [Meteora](/docs/blockchain/Solana/Meteora-DAMM-v2-API/), [Jupiter](/docs/blockchain/Solana/solana-jupiter-api/), and other Solana-based DEXs. Read [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) to get a better understanding on when to use which cube. :::note RFQ and prop-AMM trades From 29 September 2026, 15:06 UTC, this cube includes Jupiter Z RFQ fills (`ProtocolName: "order_engine"`) and swaps on the prop AMMs Tessera V (`tessera_v`), HumidiFi (`humidifi`), QuantumAMM (`quantum_amm`) and Scorch (`scorch`). Earlier trades on these venues are not here. Jupiter Limit Order v2, Mayan Swift and ZeroFi still return zero rows. The [Solana RFQ API](/docs/blockchain/Solana/solana-rfq-api/) covers all of them, with ready-made queries. ::: If you have questions or need custom data, reach out to [support](https://t.me/Bloxy_info). Need zero-latency Solana DEX trade data? [Read about our Shred Streams and contact us for a trial ➤](/docs/streams/real-time-solana-data/) For gRPC streaming: [Solana gRPC Streams (CoreCast) →](/docs/grpc/solana/introduction/) ## 🔗 Related Solana APIs - **[Solana Instructions API](/docs/blockchain/Solana/solana-instructions/)** - Track real-time instructions and token creation events - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor wallet balance changes from trades - **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** - Track token transfers and movements - **[Solana Fees API](/docs/blockchain/Solana/solana_fees_api/)** - Analyze trading fees and transaction costs - **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** - Monitor token supply changes from trading activities You may also be interested in: - [PumpSwap APIs ➤](/docs/blockchain/Solana/Pumpfun/pump-swap-api/) - [Moonshot APIs ➤](/docs/blockchain/Solana/Moonshot-API/) - [FourMeme APIs ➤](/docs/blockchain/BSC/four-meme-api/) - [DEXrabbit Categories](https://dexrabbit.bitquery.io/categories): curated token groups with live multi-chain DEX prices (memes, LSTs, stablecoins, launchpads) ## How do I get trades made by a specific wallet on a DEX? Query `Solana.DEXTrades` (or `DEXTradeByTokens`) with `where` on the wallet as **`Trade.Buy.Account`**, **`Trade.Sell.Account`**, or **`Transaction.Signer`** depending on how the protocol records the user. Filter **`Transaction.Result.Success`** and the DEX program or protocol name if needed. See [latest trades by account patterns](#subscribe-to-latest-solana-trades) and [Realised PnL / trader windows](#realised-pnl-avg-buy-price-buy-volume-sell-volume) on this page for aggregated trader stats. ## How do I get historical OHLCV for a Solana token? {#how-do-i-get-historical-ohlcv-for-a-solana-token} For candles further back than the realtime window, daily history since June 2024 and a CSV export script, see [Historical Solana data and OHLCV](/docs/blockchain/Solana/historical-aggregate-data#historical-ohlc-on-solana). For **OHLC**, use the **[Crypto Price API](/docs/trading/crypto-price-api/)** first (`Trading.Tokens` / `Pairs` with **`Token.Network: solana`**) and [second-level OHLC](#solana-second-level-ohlc-k-line-api) on this page when you want **1-second-style** streams. For **historical OHLC** from on-chain DEX trades, use **`Solana(dataset: archive)`** with **`DEXTradeByTokens`**: filter **`Trade.Currency.MintAddress`** (and usually **`Trade.Side.Currency`** for the quote, e.g. WSOL/USDC), set **`Block.Time`** range, and bucket with **`Block { Time(interval: { count, in: minutes | hours | days }) }`**. Compute OHLC with **`PriceInUSD`** / **`Trade_Price`** minima and maxima or **`median`/`quantile`** as in [Solana OHLC API](#solana-ohlc-api). :::note To query or stream data via GraphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: ## Historical DEXTrades on archive and combined {#historical-dextrades-archive-combined} `Solana.DEXTrades` is available on `dataset: archive` and `dataset: combined`, so you can read per-trade rows older than the realtime window. The table is large and has no index on token or wallet columns, so these datasets come with rules that `realtime` does not have. They apply to `archive` and to the archive half of `combined`. Realtime is unaffected. Like every archive dataset, this is not included in the self-service plans. It is part of the **Solana Historical OHLCV & Token Price Data** add-on on the [pricing page](https://bitquery.io/pricing), the same add-on that unlocks `DEXTradeByTokens` history; the free trial is realtime only. ### Data range - Individual trades on `archive` are being enabled window by window. The backfill is in progress and will reach back to 2024. Run the [coverage query](https://ide.bitquery.io/Solana-DEXTrades-Archive-Coverage) below for the range the table holds right now. - Archive trails the chain by a few hours. `combined` fills that gap from realtime. - For aggregate history over the full range, `DEXTradeByTokens` on `archive` starts on 1 June 2024. See [Historical Solana data and OHLCV](/docs/blockchain/Solana/historical-aggregate-data/). ### A query must be bounded Every query needs a top-level `where` filter on `Block.Time`, `Block.Slot` or `Block.Date` that narrows the range. Without one the API returns: ``` DEXTrade from the API table dex_trades needs a filter on Block_Time or Block_Slot in the where clause ``` | Filter | Operators that count as a bound | |---|---| | `Block.Time` | `since`, `till`, `after`, `before`, `is`, `in` | | `Block.Slot` | `ge`, `gt`, `le`, `lt`, `eq`, `in` | | `Block.Date` | `since`, `till`, `after`, `before`, `is`, `in` | - Only the presence of the bound is checked. There is no maximum width. - `not` and `notIn` never count as a bound. - Put the bound at the top level of `where`. A bound inside an `any` group next to other conditions does not count. - A filter on any other column, such as a mint or a wallet, does not count. Add it next to a bound, never instead of one. ### A date filter also bounds time A `Block.Date` filter is accepted as a bound. The API adds the matching `Block.Time` range for you, because a time range reads far fewer rows than a date on this table. | `Block.Date` filter | Time range covered | |---|---| | `is: "2026-09-01"` | That day, 00:00:00 to 23:59:59 UTC | | `in: ["2026-09-01", "2026-09-02"]` | Each listed day | | `since: "2026-09-01"` | From 00:00:00 UTC on that day | | `after: "2026-09-01"` | From 00:00:00 UTC on the next day | | `till: "2026-09-01"` | Up to 23:59:59 UTC on that day | | `before: "2026-09-01"` | Up to 23:59:59 UTC on the previous day | ### Trades of a token in a time window This query returns JUP buys in a one-hour window on 1 September 2026, newest first. The `Block.Time` range is the bound, and the mint filter narrows inside it. Run it [in the IDE](https://ide.bitquery.io/Solana-Historical-Token-Trades-archive).
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTrades( limit: {count: 10} orderBy: {descending: Block_Slot} where: { Block: {Time: {since: "2026-09-01T00:00:00Z", till: "2026-09-01T01:00:00Z"}} Transaction: {Result: {Success: true}} Trade: {Buy: {Currency: {MintAddress: {is: "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"}}}} } ) { Block { Time Slot } Transaction { Signature } Trade { Dex { ProtocolName ProtocolFamily } Buy { Amount AmountInUSD PriceInUSD Currency { Symbol MintAddress } Account { Address Owner } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } } } } } } ```
### Trades of a wallet on one day This query counts the buys of one wallet on 1 September 2026 and sums their USD value. Keep the range narrow when you filter on an address column. Run it [in the IDE](https://ide.bitquery.io/Solana-Historical-Wallet-Buys-archive).
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTrades( where: { Block: {Time: {since: "2026-09-01T00:00:00Z", till: "2026-09-02T00:00:00Z"}} Trade: {Buy: {Account: {Owner: {is: "Dj8VqncBNgwQbw9cet8qSikAFcTUiqC8TkneCSRJPLwh"}}}} } ) { count volume: sum(of: Trade_Buy_AmountInUSD) } } } ```
### Every trade signed by a wallet on one day For the trade list itself, filter on `Transaction.Signer` and keep the window to a day. This query returns the trades one wallet signed on 15 September 2026, newest first, with both legs of each swap. Run it [in the IDE](https://ide.bitquery.io/Solana-Historical-Trades-by-Signer-archive).
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTrades( limit: {count: 20} orderBy: {descending: Block_Slot} where: { Block: {Time: {since: "2026-09-15T00:00:00Z", till: "2026-09-16T00:00:00Z"}} Transaction: {Signer: {is: "F7yD9Uk47rhxRwet5xh7t8rZS4wN5iE16y2o64KoiQYX"}} } ) { Block { Time } Transaction { Signature } Trade { Dex { ProtocolName } Buy { Amount AmountInUSD Currency { Symbol MintAddress } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } } } } } } ```
### Trades of a token by DEX Aggregates work inside a bound too. This query breaks JUP buys in a one-hour window down by DEX, with trade count, USD volume and distinct signers. It reads every trade in the window, so keep the window short. Run it [in the IDE](https://ide.bitquery.io/Solana-Token-Trades-by-DEX-archive).
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTrades( orderBy: {descendingByField: "trades"} where: { Block: {Time: {since: "2026-09-01T00:00:00Z", till: "2026-09-01T01:00:00Z"}} Trade: {Buy: {Currency: {MintAddress: {is: "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"}}}} } ) { Trade { Dex { ProtocolName ProtocolFamily } } trades: count volume: sum(of: Trade_Buy_AmountInUSD) traders: uniq(of: Transaction_Signer) } } } ```
### Trades in a slot range `Block.Slot` works as a bound too. This query counts the trades in 87 consecutive slots. Run it [in the IDE](https://ide.bitquery.io/Solana-DEXTrades-Slot-Range-Count-archive).
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTrades( where: {Block: {Slot: {ge: "443282200", le: "443282286"}}} ) { count } } } ```
### Aggregates that need no bound A few whole-table aggregates are answered without a bound: - The metrics must be `count`, `sum`, `minimum` or `maximum`. - They can only be taken over `Block_Date`, `Block_Time` or `Block_Slot`. - The query must have no dimensions, no `where`, and no `if` or `distinct` argument. They still read the whole table, so they are slower than a bounded query. This query returns the total trade count and the first and last trade time in the table. Run it [in the IDE](https://ide.bitquery.io/Solana-DEXTrades-Archive-Coverage).
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTrades { count first: Block { Time(minimum: Block_Time) } last: Block { Time(maximum: Block_Time) } } } } ```
### Latest trades of a token on combined `combined` reaches the current slot, so one query covers the archive and the realtime tail. Order by `Block_Slot`: this query returns the latest JUP buys in the last hour, and the same query ordered by `Block_Time` times out. Run it [in the IDE](https://ide.bitquery.io/Solana-Latest-Token-Trades-combined).
Show the GraphQL ```graphql { Solana(dataset: combined) { DEXTrades( limit: {count: 10} orderBy: {descending: Block_Slot} where: { Block: {Time: {since_relative: {hours_ago: 1}}} Trade: {Buy: {Currency: {MintAddress: {is: "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"}}}} } ) { Block { Time Slot } Transaction { Signature Signer } Trade { Dex { ProtocolName } Buy { Amount AmountInUSD PriceInUSD Currency { Symbol } } Sell { Amount Currency { Symbol } } } } } } ```
### Fields that behave differently from realtime - **USD values, fees and prices**: `AmountInUSD`, `PriceInUSD`, `FeeInUSD`, trade prices and `PriceAsymmetry` are computed from price dictionaries at query time. They are not the values stored with the trade on realtime, so small differences are normal. - **`Account.Owner`** is derived from the token account. - **Not available**: `Currency.TotalSupplyInUSD` and `Order.LimitAmountInUSD`. A query that selects them fails with `no candidate table can serve`. - **`combined` near a threshold**: a filter on a USD value or on an owner uses the stored column on the realtime half and the computed value on the archive half. Rows close to the threshold can land on different sides in the two halves. ### Query guidance - Order lists with `orderBy: {descending: Block_Slot}`, not `Block_Time`. `Block_Slot` is the first column of the table's primary key, so a limited query ordered by it stops reading once it has enough rows. Ordering by `Block_Time` reads and sorts the whole window first, and on `combined` over a recent window that times out. - Prefer `Block.Time` or `Block.Slot` ranges over dates. - Keep the range as narrow as the question allows, especially when you filter on a wallet or token address. There is no index on mint, wallet or signer columns, so every trade in the window is read; an hour reads a fraction of what a day does, and a multi-day range with an address filter can time out. - A `Block.Slot` range prunes by primary key inside each part. A `Block.Time` range only prunes whole hourly partitions. When you know the slots, bound by slot. - The general query timeout applies. A wide range with an address filter can hit it. - For the last ~30 days with USD prices and market cap on every row, the [Trading API](/docs/trading/crypto-trades-api/trades-api/) is the simpler choice. ## Live DEX swap stream (Solana) {#crypto-trades-live-stream} [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api): one row per swap, with USD and supply. Filter **`Pair.Market.Network: Solana`**. [When to use this vs chain DEX APIs](/docs/cubes/dextrades-dextradebytokens-trading-trades). Run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Solana-with-Price-Marketcap-supply). ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Solana" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ``` ## Subscribe to Latest Solana Trades {#subscribe-to-latest-solana-trades} This example uses the chain-specific **DEXTrades** cube via `Solana { DEXTrades }` (good for signer/account filters). USD can be thin on some tokens. For swap rows with stronger USD, use the [stream at the top](#crypto-trades-live-stream). Fees: [Solana Fees API](/docs/blockchain/Solana/solana_fees_api/). Open it in the [Bitquery IDE: realtime Solana trades](https://ide.bitquery.io/solana-trades-subscription_3).
Show the GraphQL ```graphql subscription { Solana { DEXTrades { Block{ Time Slot } Transaction{ Signature Index Result{ Success } } Trade { Index Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Amount Account { Address } Currency { MetadataAddress Key MintAddress IsMutable EditionNonce Decimals CollectionAddress Fungible Symbol Native Name } Price PriceInUSD Order { LimitPrice LimitAmount OrderId } } Market { MarketAddress } Sell { Account { Address } Currency { IsMutable Decimals CollectionAddress Fungible Symbol Native Name } Price PriceInUSD } } } } } ```
## Get Price of a Token Against WSOL This query retrieves the latest price of a token against Wrapped SOL (WSOL) on Solana. Specify the token pair: - MintAddress of the token to query: "CzLSujWBLFsSjncfkh59rUFqvafWcY5tzedWJSuypump" - MintAddress for WSOL: "So11111111111111111111111111111111111111112" You can run the query [here](https://ide.bitquery.io/Price-of-a-Token-Against-WSOL)
Show the GraphQL ```graphql query LatestTrades { Solana { DEXTradeByTokens( orderBy: {descending: Block_Time} limit: {count: 1} where: {Trade: {Currency: {MintAddress: {is: "CzLSujWBLFsSjncfkh59rUFqvafWcY5tzedWJSuypump"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { allTime: Time } Transaction { Signature } Trade { Market { MarketAddress } Dex { ProtocolName ProtocolFamily } AmountInUSD Price PriceInUSD Amount Side { Type Currency { Symbol MintAddress Name } AmountInUSD Amount } } } } } ```
## Get Latest Trades of a token This query will return information about the most recent trades executed for this token `CzLSujWBLFsSjncfkh59rUFqvafWcY5tzedWJSuypump` on Solana's DEX platforms. Open it in the [Bitquery IDE: latest TRUMP trades](https://ide.bitquery.io/Latest-Trades-of-Trump-COin).
Show the GraphQL ```graphql query LatestTrades($token: String, $base: String) { Solana { DEXTradeByTokens( orderBy: {descending: Block_Time} limit: {count: 50} where: {Trade: {Side: {Amount: {gt: "0"}, Currency: {MintAddress: {is: $base}}}, Currency: {MintAddress: {is: $token}}, Price: {gt: 0}}, Transaction: {Result: {Success: true}}} ) { Block { allTime: Time } Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Account { Owner } Side { Type Account { Address Owner } } Price Amount Side { Currency { Symbol MintAddress Name } AmountInUSD Amount } } } } } ``` ```json { "token": "CzLSujWBLFsSjncfkh59rUFqvafWcY5tzedWJSuypump", "base": "So11111111111111111111111111111111111111112" } ```
![image](https://github.com/user-attachments/assets/f076d3d5-b40e-4b84-b0a0-2603db456bcc) See this pair's live board on [DEXrabbit](https://dexrabbit.bitquery.io/solana/pair/59VxMU35CaHHBTndQQWDkChprM5FMw7YQi5aPE5rfSHN/So11111111111111111111111111111111111111112#pair_latest_trades). ## Calculate Price Surge of a Token While the V2 API does not support expressions yet you can get the price data between two timestamps and compute the price surge in your system. Below query gets the price of a token at the starting and ending of a period ( open and close). You can run the query [here](https://ide.bitquery.io/Price-change-of-a-token-on-Solana)
Show the GraphQL ```graphql query MyQuery { Solana(dataset: realtime) { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Trade { Dex { ProtocolName } open: Price(minimum: Block_Time) close: Price(maximum: Block_Time) } surge: calculate(expression: "($Trade_open/$Trade_close)* 100") } } } ```
## Get Buy Pressure, Sell Pressure and Net Volume of a Pair [Run Query](https://ide.bitquery.io/Copy-of-vol-change-percent-of-a-pair)
Show the GraphQL ```graphql query MyQuery { Solana(dataset: realtime) { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "2qEHjDLDLbuBgRYvsxhc5D6uDWAivNFZGan56P1tpump" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Market: { MarketAddress: { is: "4AZRPNEfCJ7iw28rJu5aUyeQhYcvdcNm8cswyL51AY9i" } } } Block: { Time: { since: "2024-11-06T14:18:00Z" } } } ) { buy_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } Block: { Time: { after: "2024-11-06T15:13:00Z" } } } ) sell_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } Block: { Time: { after: "2024-11-06T15:13:00Z" } } } ) vol_Change: calculate( expression: "(($buy_volume - $sell_volume) / $buy_volume) * 100" ) vol_Change_5min: calculate( expression: "(($buy_volume_5min - $sell_volume_5min) / $buy_volume_5min) * 100" ) } } } ```
## Price change 5min, 1hr, 6hr precentage of a specific token {#price-change-5min-1hr-6hr-precentage-of-a-specific-token} Use below query to calculate the price change percentage for a specific token in last 5 min, 1 hr, 6hr. Test the query [here](https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_2).
Show the GraphQL ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "vLieQF5eDqUuuk8RzRaqgAHkXr7bSEBZaWk9Zfibonk" } } Market: { MarketAddress: { is: "9qppy1KXRTFEeWkFaysYHD7eu9GLg5pGXdLkdL51p7EX" } } } Block: { Time: { since_relative: { hours_ago: 6 } } } } ) { Trade { Price_5min_ago: PriceInUSD( minimum: Block_Time if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) Price_1h_ago: PriceInUSD( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) Price_6h_ago: PriceInUSD(minimum: Block_Time) CurrentPrice: PriceInUSD(maximum: Block_Time) } volume_5min: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { minutes_ago: 5 } } } } ) volume_1h: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) volume_6h: sum( of: Trade_Side_AmountInUSD if: { Block: { Time: { since_relative: { hours_ago: 6 } } } } ) Price_Change_5min: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100" ) Price_Change_1h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100" ) Price_Change_6h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100" ) } } } ```
## Top 10 solana tokens by price change in last 1 hr Use the below query to get top 10 solana tokens by price change in last 1 hr. Test the query [here](https://ide.bitquery.io/Top-10-solana-tokens-by-price-change-in-last-1-hr_4)
Show the GraphQL ```graphql query MyQuery { Solana { DEXTradeByTokens( limit: {count: 10} orderBy: {descendingByField: "Price_Change_1h"} where: {Block: {Time: {since_relative: {hours_ago: 6}}}, Transaction: {Result: {Success: true}}, Trade: {Side: {Currency: {MintAddress: {in: ["So11111111111111111111111111111111111111112","EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}}}} ) { Trade { Currency { Name Symbol MintAddress } Price_5min_ago: PriceInUSD( minimum: Block_Time if: {Block: {Time: {since_relative: {minutes_ago: 5}}}} selectWhere:{ne:0} ) Price_1h_ago: PriceInUSD( minimum: Block_Time if: {Block: {Time: {since_relative: {hours_ago: 1}}}} selectWhere:{ne:0} ) Price_6h_ago: PriceInUSD(minimum: Block_Time selectWhere:{ne:0}) CurrentPrice: PriceInUSD(maximum: Block_Time) Side { Currency { Name Symbol MintAddress } } Market { MarketAddress } } Price_Change_5min: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_5min_ago) / $Trade_Price_5min_ago) * 100" ) Price_Change_1h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_1h_ago) / $Trade_Price_1h_ago) * 100" ) Price_Change_6h: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_6h_ago) / $Trade_Price_6h_ago) * 100" ) } } } ```
## Get Trade Summary of a Trade A lot of times a trade is implemented using multiple swaps. The summary of these trades are the token originally sold and the token finally purchased. To get the summary for such trades use [this](https://ide.bitquery.io/trade-summary_1) query.
Show the GraphQL ```graphql { Solana { DEXTrades( where: { Transaction: { Signer: { is: "9B4okPpQcz1MSt8cLLb7YGo2NKvgsw82pEhHqKsKW9uS" } Result: { Success: true } } } orderBy: { descending: Block_Time } ) { Trade { Buy { Amount PriceInUSD Currency { Decimals Name MintAddress Symbol } Account { Address Owner } } Dex { ProgramAddress ProtocolFamily ProtocolName } Sell { Amount Price Currency { Name Symbol MintAddress Decimals } } Index } Transaction { Signature Result { Success } } Block { Time } } } } ```
The response of the query is given below. Given multiple trades with same `Block Time`, the summary is given by the `sell currency` for the lowest Trade Index and the `buy currency` for the highest Trade Index.
Click to expand query JSON response ```json { "Block": { "Time": "2024-11-12T05:56:55Z" }, "Trade": { "Buy": { "Account": { "Address": "FJnivW3jSXVuR2P6Z6e9iRkVHEyEzppHcnUdMgsLBSgY", "Owner": "4xDsmeTWPNjgSVSS1VTfzFq3iHZhp77ffPkAmkZkdu71" }, "Amount": "7599.73089", "Currency": { "Decimals": 5, "MintAddress": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "Name": "Bonk", "Symbol": "Bonk" }, "PriceInUSD": 0.000028919810335657223 }, "Dex": { "ProgramAddress": "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo", "ProtocolFamily": "Meteora", "ProtocolName": "lb_clmm" }, "Index": 0, "Sell": { "Amount": "0.219833", "Currency": { "Decimals": 6, "MintAddress": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Name": "USD Coin", "Symbol": "USDC" }, "Price": 34570.47345030091 } }, "Transaction": { "Result": { "Success": true }, "Signature": "43aymSmr2op2aEnCiMfzkqqfpWwSofWk8EBcUWhKEUsHRrZV4KpTGW4iuxLxJyS1HKoLS7gTamzuqKiwi3e3z4Li" } }, ```
## Get the historical Created pairs on any Solana DEX This finds pairs whose **first ever** trade falls inside a date range: `Date(minimum: Block_Date)` takes each pair's earliest trade and `selectWhere` keeps only the pairs where that date lands in the window. Because "first ever" is defined against the whole history, the scan cannot be bounded by a `Block.Time` filter without changing what the query means, and against a protocol family as large as Raydium it regularly exceeds the request timeout. Narrow it to a single `Trade.Market.MarketAddress` or a smaller protocol, or run first-trade analysis over a [cloud export](/docs/cloud/solana) where a full-history scan is the normal shape of the job. Open it in the [Bitquery IDE: new Raydium pairs](https://ide.bitquery.io/Solana-Raydium-New-Pairs_2).
Show the GraphQL ```graphql query{ Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Dex: { ProtocolFamily: { is: "Raydium" } } } } limit: { count: 100 }) { Block { Date(minimum: Block_Date selectWhere: { since: "2024-10-01" till: "2024-11-01" }) } Trade { Dex { ProtocolFamily } Market{ MarketAddress } Currency { Symbol MintAddress } Side { Currency { Symbol MintAddress } } } } } } ```
## Get Buy Volume, Sell Volume, Buys, Sells, Makers, Total Trade Volume, Buyers, Sellers of a specific Token The below query gives you the essential stats for a token such as buy volume, sell volume, total buys, total sells, makers, total trade volume, buyers, sellers (in last 5 min, 1 hour) of a specific token. You can run the query [here](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair)
Show the GraphQL ```graphql query MyQuery($token: String!, $side_token: String!, $pair_address: String!, $time_5min_ago: DateTime!, $time_1h_ago: DateTime!) { Solana(dataset: realtime) { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: $token}}, Side: {Currency: {MintAddress: {is: $side_token}}}, Market: {MarketAddress: {is: $pair_address}}}, Block: {Time: {since: $time_1h_ago}}} ) { Trade { Currency { Name MintAddress Symbol } start: PriceInUSD(minimum: Block_Time) min5: PriceInUSD( minimum: Block_Time if: {Block: {Time: {after: $time_5min_ago}}} ) end: PriceInUSD(maximum: Block_Time) Dex { ProtocolName ProtocolFamily ProgramAddress } Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) makers_5min: count( distinct: Transaction_Signer if: {Block: {Time: {after: $time_5min_ago}}} ) buyers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}} ) buyers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sellers: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}} ) sellers_5min: count( distinct: Transaction_Signer if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) trades: count trades_5min: count(if: {Block: {Time: {after: $time_5min_ago}}}) traded_volume: sum(of: Trade_Side_AmountInUSD) traded_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Block: {Time: {after: $time_5min_ago}}} ) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) buy_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) sell_volume_5min: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) buys: count(if: {Trade: {Side: {Type: {is: buy}}}}) buys_5min: count( if: {Trade: {Side: {Type: {is: buy}}}, Block: {Time: {after: $time_5min_ago}}} ) sells: count(if: {Trade: {Side: {Type: {is: sell}}}}) sells_5min: count( if: {Trade: {Side: {Type: {is: sell}}}, Block: {Time: {after: $time_5min_ago}}} ) } } } { "token":"2qEHjDLDLbuBgRYvsxhc5D6uDWAivNFZGan56P1tpump", "side_token": ""So11111111111111111111111111111111111111112", "pair_address: "4AZRPNEfCJ7iw28rJu5aUyeQhYcvdcNm8cswyL51AY9i", "time_5min_ago":"2024-11-06T15:13:00Z", "time_1h_ago": "2024-11-06T14:18:00Z" } ```
## Get ATH Market Cap of Tokens {#get-ath-market-cap-of-tokens} This query returns the ATH (All-Time High) market cap, starting market cap, and related price metrics for multiple tokens. It calculates market cap using a 1 billion token supply and uses quantile to find the ATH price. You can run it [here](https://ide.bitquery.io/Marketcap-of-tokens) ```graphql query GetAthMarketCap($tokens: [String!]!) { Solana(dataset: archive) { DEXTradeByTokens( limitBy: { by: Trade_Side_Currency_MintAddress, count: 1 } where: { Trade: { Currency: { MintAddress: { in: $tokens } } } } ) { Trade { Currency { MintAddress Name Symbol } PriceInUSD(maximum: Trade_PriceInUSD) Starting_Price: PriceInUSD(minimum: Block_Slot) Side { Currency { Name Symbol MintAddress } } } max: quantile(of: Trade_PriceInUSD, level: 0.98) quantile_price_ATH_Marketcap: calculate(expression: "$max * 1000000000") Real_maximum_price_ATH_Marketcap: calculate( expression: "$Trade_PriceInUSD_maximum * 1000000000" ) Starting_Marketcap: calculate( expression: "$Trade_Starting_Price * 1000000000" ) } } } ``` ```json { "tokens": ["8SAwv8EKMKaKnupTsYjoQdgBuWxJdo3ouA178UU7pump"] } ``` ## Top 50 Trending Solana Token Pairs with all the data [This](https://ide.bitquery.io/top-50-trading-pairs-with-trades-count-volume-buys-sells-makers-marketcap-supply-and-liquidity_1) query returns the top 10 trending token pairs on Solana across all DEXs based on the number of trades happened in the last hour. Along with token pair info you will also get latest price, total traded volume, buy volume, sell volume, buys, sells, buyers, sellers, makers, marketcap, liquidity, supply.
Show the GraphQL ```graphql query ($time_1h_ago: DateTime) { Solana { DEXTradeByTokens( where: { Transaction: { Result: { Success: true } } Block: { Time: { since: $time_1h_ago } } any: [ { Trade: { Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } } { Trade: { Currency: { MintAddress: { not: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } } { Trade: { Currency: { MintAddress: { notIn: [ "So11111111111111111111111111111111111111112" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" ] } } Side: { Currency: { MintAddress: { notIn: [ "So11111111111111111111111111111111111111112" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" ] } } } } } ] } orderBy: { descendingByField: "trades_count_1h" } limit: { count: 50 } ) { Trade { Currency { Symbol Name MintAddress } Latest_Price: PriceInUSD(maximum: Block_Time) Market { MarketAddress } Side { Currency { Symbol Name MintAddress } } } makers: count(distinct: Transaction_Signer) buyers: count( distinct: Transaction_Signer if: { Trade: { Side: { Type: { is: buy } } } } ) sellers: count( distinct: Transaction_Signer if: { Trade: { Side: { Type: { is: sell } } } } ) traded_volume: sum(of: Trade_Side_AmountInUSD) buy_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) sell_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) trades_count_1h: count liquidity: joinDEXPools( join: inner Pool_Market_MarketAddress: Trade_Market_MarketAddress where: { Transaction: { Result: { Success: true } } } ) { Pool { Market { BaseCurrency { Name Symbol } QuoteCurrency { Name Symbol } } Base { Balance: PostAmount(maximum: Block_Slot) Base_Liquidity_USD: PostAmountInUSD(maximum: Block_Slot) } Quote { PostAmount(maximum: Block_Slot) Quote_Liquidity_USD: PostAmountInUSD(maximum: Block_Slot) } } } marketcap_and_supply: joinTokenSupplyUpdates( join: inner TokenSupplyUpdate_Currency_MintAddress: Trade_Currency_MintAddress where: { Transaction: { Result: { Success: true } } } ) { TokenSupplyUpdate { MarketCap: PostBalanceInUSD(maximum: Block_Slot) Supply: PostBalance(maximum: Block_Slot) Currency { Name MintAddress Symbol } } } } } } ``` ```json { "time_1h_ago": "2025-07-03T08:05:00Z" } ```
You can also checkout how such queries are used as a base to completed features such as [DEXrabbit Solana Trends](https://dexrabbit.bitquery.io/solana/token) as shown in the image below. ![Trending Pairs on DEXrabbit](/img/dexrabbit/trending_tokens_solana.png) ## Get DEX Markets for a Token This query will give you Solana DEXs on which the token `59VxMU35CaHHBTndQQWDkChprM5FMw7YQi5aPE5rfSHN` is getting traded. Open it in the [Bitquery IDE: DEX markets for a token](https://ide.bitquery.io/DEX-Markets-for-a-token).
Show the GraphQL ```graphql query ($token: String, $base: String, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "amount"} where: {Trade: {Currency: {MintAddress: {is: $token}}, Side: {Amount: {gt: "0"}, Currency: {MintAddress: {is: $base}}}}, Transaction: {Result: {Success: true}}, Block: {Time: {after: $time_3h_ago}}} ) { Trade { Dex { ProtocolFamily ProtocolName } price_last: PriceInUSD(maximum: Block_Slot) price_10min_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Slot) } amount: sum(of: Trade_Side_Amount) pairs: uniq(of: Trade_Side_Currency_MintAddress) trades: count } } } { "token": "59VxMU35CaHHBTndQQWDkChprM5FMw7YQi5aPE5rfSHN", "base": "So11111111111111111111111111111111111111112", "time_10min_ago": "2024-09-19T10:45:46Z", "time_1h_ago": "2024-09-19T09:55:46Z", "time_3h_ago": "2024-09-19T07:55:46Z" } ```
![image](https://github.com/user-attachments/assets/c7d15b15-d0b4-4fcd-9fda-c7cfc5a39732) The same pair, with its markets broken out, is on [DEXrabbit](https://dexrabbit.bitquery.io/solana/pair/59VxMU35CaHHBTndQQWDkChprM5FMw7YQi5aPE5rfSHN/So11111111111111111111111111111111111111112#pair_dex_list). ## Get Token creation date You can use the below query to get any token's creation time. Note that we are providing first trade time which in most of the cases is around creation time only. Try the query on ide [here](https://ide.bitquery.io/Token-creation-time_1)
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "94vNH3HhLv42gfkF93n9EQq9vyHPKRZ5XG6U3HmDpump"}}}} ) { Block { Time(minimum: Block_Time) } } } } ```
## Get Volume changes for trading pairs in last 2mins You can use the below stream to get the volume changes in last 2 minutes. Try the query on ide [here](https://ide.bitquery.io/volume-change-in-last-2-minutes)
Show the GraphQL ```graphql { Solana(dataset: realtime) { DEXTradeByTokens( limitBy: {by: Trade_Market_MarketAddress, count: 2} orderBy: [{descending:Trade_Market_MarketAddress} {descendingByField: "Block_Time"} ] where: {Trade: {Side: {Currency: {MintAddress: {in: ["11111111111111111111111111111111", "So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN", "EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm"]}}}}, Block: {Time: {since: "2025-07-08T09:38:52.000Z"}}, Transaction: {Result: {Success: true}}} ) { Block { Time(interval: {count: 2, in: minutes}) } Trade { Currency { MintAddress Symbol Name } Market { MarketAddress } } volume: sum(of: Trade_Side_AmountInUSD) } } } ```
## Get Solana Price in Realtime You can use the below stream to get the Solana price. Try the query on ide [here](https://ide.bitquery.io/solana-price-stream)
Show the GraphQL ```graphql subscription { Solana { DEXTrades( where: {Trade: {Sell: {Currency: {MintAddress: {in: ["So11111111111111111111111111111111111111112", "11111111111111111111111111111111"]}}}}} ) { Block { Time } Trade { Buy { Price PriceInUSD Currency { Name Symbol MintAddress } } } } } } ```
## Get Top Bought Tokens on Solana This query will give you most bought Solana Tokens on Raydium. Open it in the [Bitquery IDE: most bought Solana tokens](https://ide.bitquery.io/Top-Bought-Solana-Tokens).
Show the GraphQL ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "buy"} where: {Trade: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}, Dex: {ProtocolFamily: {is: "Raydium"}}}, Transaction: {Result: {Success: true}}} limit: {count: 100} ) { Trade { Currency { Symbol Name MintAddress } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) } } } ```
Ranked by `bought - sold`, the same ordering [DEXrabbit](https://dexrabbit.bitquery.io/solana) uses for net buying. ![image](https://github.com/user-attachments/assets/20872a56-f02a-4323-889a-605ff7947a13) See the live net-buying board on [DEXrabbit](https://dexrabbit.bitquery.io/solana). ## Get Top Sold Tokens on Solana This query will give you most sold Solana Tokens on Raydium. Open it in the [Bitquery IDE: most sold Solana tokens](https://ide.bitquery.io/Top-sold-Solana-Tokens).
Show the GraphQL ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "sell"} where: {Trade: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}, Dex: {ProtocolFamily: {is: "Raydium"}}}, Transaction: {Result: {Success: true}}} limit: {count: 100} ) { Trade { Currency { Symbol Name MintAddress } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) } } } ```
Ranked by `sold - bought`, the mirror of the section above. ![image](https://github.com/user-attachments/assets/216bfb28-d365-4a9e-b280-ae19562d7600) See the live net-selling board on [DEXrabbit](https://dexrabbit.bitquery.io/solana). ## Get Top Traded Pairs in terms of volume This query will give you top traded pairs data. Open it in the [Bitquery IDE: top trading pairs](https://ide.bitquery.io/top-trading-pairs).
Show the GraphQL ```graphql query ($time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { Solana { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}, Block: {Time: {after: $time_3h_ago}}, any: [{Trade: {Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}}}, {Trade: {Currency: {MintAddress: {not: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}}, {Trade: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}, Side: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]}}}}}]} orderBy: {descendingByField: "usd"} limit: {count: 100} ) { Trade { Currency { Symbol Name MintAddress } Side { Currency { Symbol Name MintAddress } } price_last: PriceInUSD(maximum: Block_Slot) price_10min_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: PriceInUSD( maximum: Block_Slot if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Slot) } dexes: uniq(of: Trade_Dex_ProgramAddress) amount: sum(of: Trade_Side_Amount) usd: sum(of: Trade_Side_AmountInUSD) traders: uniq(of: Trade_Account_Owner) count(selectWhere: {ge: "100"}) } } } { "time_10min_ago": "2024-09-19T12:26:17Z", "time_1h_ago": "2024-09-19T11:36:17Z", "time_3h_ago": "2024-09-19T09:36:17Z" } ```
![image](https://github.com/user-attachments/assets/4678a3a8-f4a2-476a-92ae-91e3462de2df) Browse every Solana pair on [DEXrabbit](https://dexrabbit.bitquery.io/solana/pair). ## Get Top DEXs information This query will give you top DEXs info. Open it in the [Bitquery IDE: busiest Solana DEXs](https://ide.bitquery.io/top-dexs).
Show the GraphQL ```graphql query DexMarkets { Solana { DEXTradeByTokens { Trade { Dex { ProtocolFamily } } traders: uniq(of: Trade_Account_Owner) count(if: {Trade: {Side: {Type: {is: buy}}}}) } DEXPools { Pool { Dex { ProtocolFamily } } pools: uniq(of: Pool_Market_MarketAddress) } } } ```
![image](https://github.com/user-attachments/assets/09caf85d-6930-4c24-91d1-7f40f878287e) Compare Solana DEX markets on [DEXrabbit](https://dexrabbit.bitquery.io/solana/dex_market). ## Get All Traded Pairs Info of a Token This query will give you the information on all the traded pairs of a particular token `EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm`. Open it in the [Bitquery IDE: traded pairs of a token](https://ide.bitquery.io/traded-pairs-of-a-token).
Show the GraphQL ```graphql query ($token: String, $time_10min_ago: DateTime, $time_1h_ago: DateTime, $time_3h_ago: DateTime) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "usd"} where: {Trade: {Currency: {MintAddress: {is: $token}}}, Transaction: {Result: {Success: true}}, Block: {Time: {after: $time_3h_ago}}} limit: {count: 200} ) { Trade { Currency { Symbol Name MintAddress Fungible } Side { Currency { Symbol Name MintAddress } } price_usd: PriceInUSD(maximum: Block_Slot) price_last: Price(maximum: Block_Slot) price_10min_ago: Price( maximum: Block_Slot if: {Block: {Time: {before: $time_10min_ago}}} ) price_1h_ago: Price( maximum: Block_Slot if: {Block: {Time: {before: $time_1h_ago}}} ) price_3h_ago: PriceInUSD(minimum: Block_Slot) } usd: sum(of: Trade_AmountInUSD) count } } } { "token": "EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm", "time_10min_ago": "2024-09-19T12:02:23Z", "time_1h_ago": "2024-09-19T11:12:23Z", "time_3h_ago": "2024-09-19T09:12:23Z" } ```
![image](https://github.com/user-attachments/assets/ba2381ce-422d-4120-a873-61fbc4f4124c) See this token's page on [DEXrabbit](https://dexrabbit.bitquery.io/solana/token/EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm). ## Get all DEXes To get the list of all DEXes operating within the Solana ecosystem, use the following query. Find the query [here](https://ide.bitquery.io/Solana-DEXs)
Show the GraphQL ```graphql query MyQuery { Solana { DEXTrades(limitBy: {by: Trade_Dex_ProtocolFamily, count: 1}, limit: {count: 10}) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } } } } } ```
## Latest USD Price of a Token {#latest-usd-price-of-a-token} The below query retrieves the USD price of a token on Solana by setting `MintAddress: {is: "J5FAZ6bV7CCGHcU4CTXWVG6nnKHcwD9Pn4DntY93pump"}` and `Side: {Currency: {MintAddress: {is: "11111111111111111111111111111111"}}}` . Check the field `PriceInUSD` for the USD value. You can access the query [here](https://ide.bitquery.io/Get-Latest-Price-of-SOL-in--USD-Real-time#).
Show the GraphQL ```graphql { Solana { DEXTradeByTokens( orderBy: {descending: Block_Time} where: {Trade: {Currency: {MintAddress: {is: "J5FAZ6bV7CCGHcU4CTXWVG6nnKHcwD9Pn4DntY93pump"}}, Side: {Currency: {MintAddress: {is: "11111111111111111111111111111111"}}}}} limit: {count: 1} ) { Block{ Time } Trade{ Currency{ Name Symbol MintAddress } Price PriceInUSD Side{ Currency{ Name MintAddress } } } } } } ```
## Stablecoin Peg Health (Latest Price Across All Markets) Get the **latest price of a stablecoin across all Solana DEXs/markets**. Returns one row per market with the most recent trade price. Useful for monitoring peg health and identifying which exchanges have the stablecoin trading closest to its target peg (e.g., $1.00 for USD-pegged stablecoins). Browse multi-chain stablecoin DEX prices on [DEXrabbit's Stablecoins category](https://dexrabbit.bitquery.io/categories/stablecoins). [Run in Bitquery IDE](https://ide.bitquery.io/Latest-Price-of-a-Token-on-all-exchanges_1)
Show the GraphQL ```graphql { Solana { DEXTradeByTokens( orderBy: { descending: Block_Time } limitBy: { count: 1, by: Trade_Market_MarketAddress } where: { Trade: { Currency: { MintAddress: { is: "CZzgUBvxaMLwMhVSLgqJn3npmxoTo6nzMNQPAnwtHF3s" } } } } ) { Block { Time } Transaction { Signature } Trade { Amount AmountInUSD Price PriceInUSD Currency { Name MintAddress Symbol } Market { MarketAddress } Dex { ProtocolName ProtocolFamily } Side { Type Currency { Name MintAddress Symbol } AmountInUSD Amount } } } } } ```
## Get the Token details like Update Authority, decimals, URI, is Mutable or not The below query retrieves the token details such as update authority for a particular token and also checks if a token's data is mutable or not. You can access the query [here](https://ide.bitquery.io/Solana-currency-details).
Show the GraphQL ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "AREn4LyUS4pNUGzwXcks7oefjT751G1XwYZ4GLTppump"}}}, Transaction: {Result: {Success: true}}} orderBy: {descending: Block_Time} limit: {count: 1} ) { Trade { Currency { Uri UpdateAuthority Name IsMutable } } } } } ```
The `uri` field returns the following url - [`https://ipfs.io/ipfs/QmXGGo38devA7Ghw6dT4rXfL8sREsEdv3FzkPdziE9V4oN`](https://ipfs.io/ipfs/QmXGGo38devA7Ghw6dT4rXfL8sREsEdv3FzkPdziE9V4oN). Offchain token metadata such as social urls and image could be accessed from this link. ## Top Buyers of a Token This query retrieves top buyers of the token `4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R`. Try the query [here](https://ide.bitquery.io/top-buyers-of-a-token_2).
Show the GraphQL ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "buy"} where: {Trade: {Currency: {MintAddress: {is: "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} ) { Trade { Account{ Address Token{ Owner } } Currency { Symbol Name MintAddress } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) } } } ```
## Top Sellers of a Token This query retrieves top sellers of the token `4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R`. Try the query [here](https://ide.bitquery.io/top-sellers-of-a-token_2).
Show the GraphQL ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "sell"} where: {Trade: {Currency: {MintAddress: {is: "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} ) { Trade { Account{ Address Token{ Owner } } Currency { Symbol Name MintAddress } } buy: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sell: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) } } } ```
## Trades of a wallet You can use this API to fetch trades of a specific wallet address `tRadEVu2Va7WsVHqmGSiRHspkBoDQ9Qnjp42TiJirYA`. Change the wallet address as per your needs. Try the query [here](https://ide.bitquery.io/trades-of-a-wallet_8)
Show the GraphQL ```graphql query MyQuery { Solana { DEXTradeByTokens( where: {Transaction: {Signer: {is: "tRadEVu2Va7WsVHqmGSiRHspkBoDQ9Qnjp42TiJirYA"}}} limit: {count: 10} orderBy: {descending: Block_Time} ){ Block{ Time } Trade{ Account{ Address Token{ Owner } } Currency{ MintAddress Name Symbol } Price PriceInUSD Side{ Account{ Address Token{ Owner } } Currency{ Name Symbol MintAddress } Type } } Transaction{ Signature Signer } } } } ```
## Get trading volume, buy volume, sell volume of a token This query fetches you the traded volume, buy volume and sell volume of a token `J4JbUQRaZMxdoQgY6oEHdkPttoLtZ1oKpBThic76pump`. Try out the API [here](https://ide.bitquery.io/trade_volume_Solana#).
Show the GraphQL ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( where: {Block: {Time: {since: "2025-02-10T07:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "J4JbUQRaZMxdoQgY6oEHdkPttoLtZ1oKpBThic76pump"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Trade { Currency { MintAddress Decimals } Side { Currency { Name MintAddress } } } traded_volume_USD: sum(of: Trade_Side_AmountInUSD) traded_volume: sum(of: Trade_Amount) buy_volume: sum(of:Trade_Side_AmountInUSD if:{Trade:{Side:{Type:{is:buy}}}}) sell_volume: sum(of:Trade_Side_AmountInUSD if:{Trade:{Side:{Type:{is:sell}}}}) } } } ```
## Realised PnL, avg buy price, buy volume, sell volume Get realised PnL, average buy price, buy volume, and sell volume for a token on Solana of a trader for over a time window. [Run in Bitquery IDE](https://ide.bitquery.io/Realised-Pnl-avg-buy-price-Buy-volume-Sell-Volume-Solana_2)
Show the GraphQL ```graphql { Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "4iLKj7fkZF2rSpgSD8W6UFq4fkKXkkbJMGXMz3B8pump" } } Account: { Owner: { is: "2vqBfRdhX8sHmVFo1TY1yBdFXkHMe4LgifrxvHBpXUAK" } } Dex: { ProtocolName: { notIn: ["jupiter", "dex_solana_v3"] } } } Transaction: { Result: { Success: true } } Block: { Date: { since: "2026-03-11", till: "2026-03-13" } } } ) { Trade { Currency { Name Symbol MintAddress } Account { Owner } } buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) buy_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) sell_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) buy_volume: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) sell_volume: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) RealizedPnL: calculate(expression: "$sell_volume_usd - $buy_volume_usd") trades: count avg_buy_price: calculate(expression: "$buy_volume_usd / $buy_volume") } } } ```
## Solana Second-level OHLC / K-line API {#solana-second-level-ohlc-k-line-api} For this we will use the new [Crypto Price APIs](/docs/trading/crypto-price-api/) You can get OHLC data at 1-second intervals via a subscription query, which can then be monitored via a WebSocket. Below is an example. You can read more on [quantiles here](/docs/graphql/metrics/quantile/) Test the subscription query [here](https://ide.bitquery.io/seconds-oHLC-realtime-solana-usd)
Show the GraphQL ```graphql subscription{ Trading { Tokens( where: {Currency: {Id: {is: "bid:solana"}}, Interval: {Time: {Duration: {eq: 1}}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { Token { Address Id IsNative Name Network Name Symbol TokenId } Block { Date Time Timestamp } Interval { Time { Start Duration End } } Volume { Base Quote Usd } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } } } } ```
## Solana OHLC API {#solana-ohlc-api} You can query OHLC data in for any Solana token. In the below query we are fetching OHLC information for the pair WSOL-USDC by using the smart contract addresses in the `MintAddress` filter. Only use this API as `query` and not `subscription` websocket as Aggregates and Time Intervals don't work well with subscriptions. You can run and test the [saved query here](https://ide.bitquery.io/query_ohlc_quantile___1). :::note The `Trade Side Account` field is **not available** in aggregate queries across archive or combined datasets. :::
Show the GraphQL ```graphql query TradesSolToken($ca: String!, $currencies: [String!], $dataset: dataset_arg_enum, $interval: Int) { Solana(dataset: $dataset) { DEXTradeByTokens( limit:{count:10} orderBy: {ascendingByField: "Block_Time"} where: {Trade: {Amount: {gt: "0"}, Currency: {MintAddress: {is: $ca}}, Side: {Currency: {MintAddress: {in: $currencies}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time(interval: {count: $interval, in: days}) } min: quantile(of: Trade_Price, level: 0.05) max: quantile(of: Trade_Price, level: 0.95) close: median(of: Trade_Price) open: median(of: Trade_Price) volume: sum(of: Trade_Side_Amount) Trade { Currency{ Name Symbol } Side { Currency { Name Symbol } } } } } } { "interval": 1, "dataset": "combined", "ca": "So11111111111111111111111111111111111111112", "currencies": ["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"] } ```
![image](https://github.com/user-attachments/assets/1d5c2004-b8a5-4822-bda8-9f920dbf8715) See this market's live board on [DEXrabbit](https://dexrabbit.bitquery.io/solana/pair/9Fv7n7HuA5EzjCRSvprBMx2Qhd1VL3hPEXKhTUKPm1Qh/So11111111111111111111111111111111111111112). ## Why does my per-minute OHLC query return hundreds of rows for one token? {#dextradebytokens-side-currency-grain} Three things about `DEXTradeByTokens` aggregates that are easy to miss: - **On the pre-aggregated path, price measures are grouped by side currency.** By default (`aggregates: yes`) a `DEXTradeByTokens` query on `dataset: realtime` that selects only `Block.Time(interval: …)`, price measures and `count` is served from a per-minute pre-aggregated table. On that table any `Trade { PriceInUSD(minimum: ...) }` or `PriceInUSD(maximum: ...)` selector adds `Trade.Side.Currency.MintAddress` to the grouping key even if you do not select it, because USD conversion is stored per side currency (`Trade { Price(...) }` groups by the side currency's `Decimals` instead). A minute in which WSOL traded against 797 different tokens returns 797 rows. The rows do not overlap and `count` stays additive. This table also stores `Block.Time` at minute resolution and its extremes are not the raw fill extremes. - **`aggregates: no` selects the raw trades.** `Solana(dataset: realtime, aggregates: no)` serves the same query from the raw fills: one row per token and interval across all side currencies, exact highest and lowest fill (dust trades included), `Block.Time` at second resolution, and `Block.Slot(minimum/maximum: ...)` and `uniq(...)` available. Selecting one of those raw-only fields switches to the raw path even without the flag. The raw path is not available on `dataset: combined`, and it keeps a much shorter window than the pre-aggregated table (hours to about a day, against roughly 7 days), so collect promptly. - **Use `before`, not `till`, for the end of a candle.** `till` is inclusive. On the pre-aggregated path `till: "…T02:35:00Z"` matches every trade in the 02:35 minute; on the raw path it adds the fills at second 02:35:00. `since` + `before` gives the half-open interval `[since, end)` on both. For a price series, pin the side currency to the quote currencies you care about (for WSOL: USDC and USDT; for other tokens add WSOL), because unpriced side currencies push the all-side USD extremes to absurd values. Count activity separately, across all side currencies, with a `count`-only query. One candle per token, minute and quote currency from raw trades, half-open interval:
Show the GraphQL ```graphql query SolMinuteOHLC($token: String!, $quotes: [String!]!, $since: DateTime!, $end: DateTime!) { Solana(dataset: realtime, aggregates: no) { DEXTradeByTokens( where: { Block: {Time: {since: $since, before: $end}} Transaction: {Result: {Success: true}} Trade: {Currency: {MintAddress: {is: $token}}, Side: {Currency: {MintAddress: {in: $quotes}}}} } orderBy: {ascendingByField: "Block_bucket"} limit: {count: 5000} ) { Block { bucket: Time(interval: {count: 1, in: minutes}) firstSlot: Slot(minimum: Block_Slot) lastSlot: Slot(maximum: Block_Slot) } Trade { Side { Currency { MintAddress } } open: PriceInUSD(minimum: Block_Slot) high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) close: PriceInUSD(maximum: Block_Slot) } fills: count transactions: uniq(of: Transaction_Signature) } } } { "token": "So11111111111111111111111111111111111111112", "quotes": ["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"], "since": "2026-09-10T02:34:00Z", "end": "2026-09-10T02:35:00Z" } ```
Selecting `Side { Currency }` gives one row per quote currency; fills add up across those rows, but `uniq` of transaction signatures does not, because a routed transaction can fill against both quotes. Count transactions with one `uniq` over the union filter. `count` is the number of DEX fills in which the token is one side; a routed swap with several fills counts each of them. `open` and `close` pick one fill from the first and last slot; when several fills share that slot the choice is not defined by transaction order. For a strict first and last, query the raw trades of those two slots and sort by `Block.Slot`, `Transaction.Index`, `Trade.Index` (add `Instruction.Index` and `Instruction.InternalSeqNumber` as further tie-breakers). If you want a single all-venue candle without choosing quote currencies, use the [Trading API](/docs/trading/crypto-price-api/) `Trading { Tokens }` cube (price index, about 30 days of history). ## Solana Real time prices from multiple Markets You can retrieve data from multiple Solana DEX markets using our APIs or streams. The [following query](https://ide.bitquery.io/latest-price-for-more-than-1-markets-on-solana_1) demonstrates how to do this. However, there's a caveat: since we are not specifying the buy or sell currency in the filters, the query will display both currencies on the buy side (or sell side). This happens because both currencies are traded within the pool. If you want the price of only one asset, you can define it in the filter. ere is [an example](https://ide.bitquery.io/latest-price-for-more-than-1-markets-on-solana-for-specific-currencies) from the same markets, where we specified that we need trades when the buy currency is defined.
Show the GraphQL ```graphql subscription { Solana { DEXTrades( where: {Transaction: {Result: {Success: true}}, Trade: {Market: {MarketAddress: {in: ["5qrvgpvr55Eo7c5bBcwopdiQ6TpvceiRm42yjHTbtDvc", "FpCMFDFGYotvufJ7HrFHsWEiiQCGbkLCtwHiDnh7o28Q"]}}}} ) { average(of: Trade_Buy_Price) Trade { Buy { Currency { Name Symbol MintAddress } } } } } } ```
## Using Pre-Made Aggregates in Solana DEX Trades When querying Solana DEXTradeByTokens, you can use pre-made aggregates to optimize performance. The `aggregates` flag provides three options to control the use of these aggregates: - **`aggregates: only`**: This option uses only the pre-made aggregates, which can significantly increase the speed of the response. - **`aggregates: yes`**: This option uses both pre-made aggregates and individual transaction data. - **`aggregates: no`**: This option does not use any pre-made aggregates. > When using the aggregates: only option, you need to include the mintaddress field in the response to ensure proper aggregation and filtering.
Show the GraphQL ```graphql { Solana(aggregates: only) { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "6D7NaB2xsLd7cauWu1wKk6KBsJohJmP2qZH9GEfVi5Ui"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) Currency { MintAddress } } count } } } ```
## Finding Trades that Executed the Trade a Custom Program You want to track or filter DEX trades that interacted with a specific Solana program (e.g., one you deployed or are monitoring). This query uses the [graphQL joins](/docs/graphql/capabilities/joins/) feature to join Solana DEX trades with instructions executed by a specific program address. Run this query [here](https://ide.bitquery.io/find-all-trades-interacting-with-a-program)
Show the GraphQL ```graphql { Solana { DEXTrades(limit: {count: 100}) { Trade { Dex { ProtocolName } Sell { Currency { Symbol } } Buy { Currency { Symbol } } } Transaction { Signature } Instruction { ExternalSeqNumber InternalSeqNumber } joinInstructions( join: inner Block_Slot: Block_Slot Transaction_Signature: Transaction_Signature where: { Instruction: { Program: { Address: { is: "fat2dUTkypDNDT86LtLGmzJDK11FSJ72gfUW35igk7u" } } } } ) { Instruction { Program { Address } } Transaction { Signature } } } } } ```
### How It Works - `DEXTrades`: Retrieves recent DEX trades on Solana. - `joinInstructions`: Performs an **inner join** between trades and instructions within the same **block slot** and **transaction signature**. - Filters are applied to the **Instruction.Program.Address**, targeting your custom program. - Ensures only trades where your program was involved are included. ## Aggregated Token Data (Volume & Price, Last 24h) Get up to 100 tokens with aggregated USD volume and average price over the last 24 hours, plus volume and price for 1h, 4h, and 24h via conditional metrics (Trading API; includes Solana and other chains). ▶️ [Aggregated Token Data](https://ide.bitquery.io/aggregated-data) ```graphql { Trading { Tokens( limit: { count: 100 } limitBy: { count: 1, by: Token_Id } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Token { Address Id IsNative Name Network Symbol TokenId } Volume { Usd H1VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 1 } } } }) H4VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 4 } } } }) H24VAgo: Usd(if: { Block: { Time: { since_relative: { hours_ago: 24 } } } }) } Price { Average { currentPrice: Mean(maximum: Block_Time) H1Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) H4Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 4 } } } } ) H24Ago: Mean( minimum: Block_Time if: { Block: { Time: { since_relative: { hours_ago: 24 } } } } ) } } } } } ``` ## Volume of Multiple Tokens Across Different Chains Get volume and price change data for multiple tokens trading on different chains (Solana, Ethereum, BSC, Tron) in a single query using the Trading API. Returns volume for 1h, 4h, and 24h periods, plus price change percentages for the same intervals. :::note EVM address format For **EVM chains** (Ethereum, BSC, etc.) in the Trading API, use **all lowercase addresses** in the token ID format (e.g., `bid:eth:0x...` with lowercase hex). Mixed-case addresses may not match. ::: [Run in Bitquery IDE](https://ide.bitquery.io/volume-of-a-token_1)
Show the GraphQL ```graphql query { TokenAsBase: Trading { Pairs( where: { Interval: { Time: { Duration: { eq: 1 } } } Block: { Time: { since_relative: { hours_ago: 24 } } } Price: { IsQuotedInUsd: true } Token: { Id: { in: [ "bid:solana:CZzgUBvxaMLwMhVSLgqJn3npmxoTo6nzMNQPAnwtHF3s" "bid:eth:0xfaf0cee6b20e2aaa4b80748a6af4cd89609a3d78" "bid:bsc:0xfaf0cee6b20e2aaa4b80748a6af4cd89609a3d78" "bid:tron:TXL6rJbvmjD46zeN1JssfgxvSo99qC8MRT" ] } } Market: { Protocol: { notIn: ["jupiter", "dex_solana_v3"] } } } ) { Token { Name Symbol Id } Price { Average { currentPrice: Mean(maximum: Block_Time) H1Ago: Mean( maximum: Block_Time if: { Block: { Time: { till_relative: { hours_ago: 1 } } } } ) H4Ago: Mean( maximum: Block_Time if: { Block: { Time: { till_relative: { hours_ago: 4 } } } } ) H24Ago: Mean( minimum: Block_Time if: { Block: { Time: { after_relative: { hours_ago: 24 } } } } ) } } Price_change_1h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H1Ago ) / $Price_Average_H1Ago ) * 100" ) Price_change_4h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H4Ago ) / $Price_Average_H4Ago ) * 100" ) Price_change_24h: calculate( expression: "( ( $Price_Average_currentPrice - $Price_Average_H24Ago ) / $Price_Average_H24Ago ) * 100" ) v1h: sum( of: Volume_Usd if: { Block: { Time: { since_relative: { hours_ago: 1 } } } } ) v4h: sum( of: Volume_Usd if: { Block: { Time: { since_relative: { hours_ago: 4 } } } } ) v24h: sum(of: Volume_Usd) } } } ```
--- ## Trader-Focused Trade APIs (with USD Price, Market Cap & Supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get All DEX Trades on Solana With Price, Market Cap, and Supply Stream **all Solana DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Network: Solana`** to capture every swap across **Raydium**, **Orca**, **Jupiter**, **PumpSwap**, and other Solana DEXs in a single subscription. The full runnable subscription lives in the canonical section on the Trades API page: [How Do I Get All DEX Trades on Solana With Price, Market Cap, and Supply?](/docs/trading/crypto-trades-api/trades-api/#how-do-i-get-all-dex-trades-on-solana-with-price-market-cap-and-supply), or run it directly [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Solana-with-Price-Marketcap-supply). ### Top Traders by PnL for a Specific Pool (Last 30 Minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-pair#).
Show the GraphQL ```graphql { Trading { Trades( limit: { count: 10 } orderBy: [{ descendingByField: "PnL" }] where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "2axyccPzS7Ei57c7ESEq7tBpo4HxtpfCR9gKxh5uNUpu" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
--- ## Video Tutorial on Solana DEXTrades API | How to get Decentralized Exchange Data with DEX Trades API ## Video Tutorial on Solana DEXTrades API | How to get Top Solana tokens by Price Change 5min, 1h, 6h --- ## Solana Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/solana/ Solana blocks, transactions, transfers, balance updates, DEX orders and trades, pools and rewards as Parquet, with a free sample and code examples. # Solana Data Bitquery provides **Solana blockchain data** as **Parquet exports** from the [Bitquery Data Store](https://bitquery.io/datastore), designed for large-scale analytics, historical backfills, and data lake integrations. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, etc**. ## Available Solana Topics For Solana, Bitquery currently provides the following datasets: - **Blocks** – Slot-level block metadata - **Transactions** – Full transaction-level data - **Transfers** – Native SOL and token transfers - **Balance Updates** – Account balance changes per slot - **DEX Pools** – Decentralized exchange pool metadata - **DEX Orders** – Order-level DEX activity - **DEX Trades** – Executed trades on Solana DEXs - **Rewards** – Validator and staking rewards ## Sample Solana Cloud Dataset You can explore schemas and validate your tooling using the **public Solana sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/solana](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/solana) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/balance_updates/390740000_390740049.parquet ``` ## Solana Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── solana/ ├── balance_updates/ │ ├── 390740000_390740049.parquet │ ├── 390740050_390740099.parquet │ └── ... ├── blocks/ │ ├── 390740000_390740049.parquet │ ├── 390740050_390740099.parquet │ └── ... ├── dex_orders/ │ ├── 390740000_390740049.parquet │ └── ... ├── dex_pools/ │ ├── 390740000_390740049.parquet │ └── ... ├── dex_trades/ │ ├── 390740000_390740049.parquet │ └── ... ├── rewards/ │ ├── 390740000_390740049.parquet │ └── ... ├── transactions/ │ ├── 390740000_390740049.parquet │ └── ... └── transfers/ ├── 390740000_390740049.parquet └── ... ``` ### Slot Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Example: ``` 390740000_390740049.parquet ``` ## Get Full Access [Buy on the Data Store](https://bitquery.io/datastore/datasets?network=solana) or email **sales@bitquery.io** for custom ranges. A Data Store purchase is downloaded from a Requester Pays S3 bucket or a Cloudflare R2 bucket, chosen at checkout. Custom exports can be delivered into your own S3, GCS or R2 bucket, or as a Snowflake or BigQuery share. To trial it first, [fill the API form](https://bitquery.io/forms/api). Per-protocol Solana datasets on the Data Store, each with decoded trades priced in USD: - [Pump.fun](https://bitquery.io/datastore/datasets/pumpfun) - [PumpSwap](https://bitquery.io/datastore/datasets/pumpswap) - [Raydium AMM v4](https://bitquery.io/datastore/datasets/raydium-amm-v4) - [Raydium CLMM](https://bitquery.io/datastore/datasets/raydium-clmm) - [Raydium CPMM](https://bitquery.io/datastore/datasets/raydium-cpmm) - [Raydium Launchpad](https://bitquery.io/datastore/datasets/raydium-launchpad) - [Jupiter](https://bitquery.io/datastore/datasets/jupiter) - [Orca Whirlpool](https://bitquery.io/datastore/datasets/orca-whirlpool) - [Meteora DLMM](https://bitquery.io/datastore/datasets/meteora-dlmm) - [Meteora DAMM V2](https://bitquery.io/datastore/datasets/meteora-damm-v2) - [Meteora DBC](https://bitquery.io/datastore/datasets/meteora-dbc) - [Meteora Pools](https://bitquery.io/datastore/datasets/meteora-pools) - [PancakeSwap (Solana)](https://bitquery.io/datastore/datasets/pancakeswap-solana) - [DFlow Aggregator](https://bitquery.io/datastore/datasets/dflow) - [OKX DEX](https://bitquery.io/datastore/datasets/okx-dex) - [SolFi](https://bitquery.io/datastore/datasets/solfi) - [BisonFi](https://bitquery.io/datastore/datasets/bisonfi) - [Bonkswap](https://bitquery.io/datastore/datasets/bonkswap) - [Heaven](https://bitquery.io/datastore/datasets/heaven) - [Moonshot](https://bitquery.io/datastore/datasets/moonshot) - [Boop](https://bitquery.io/datastore/datasets/boop) - [Manifest](https://bitquery.io/datastore/datasets/manifest) - [Phoenix](https://bitquery.io/datastore/datasets/phoenix) This listing is not the full catalogue. Other topics, chains and date ranges are available on request from **sales@bitquery.io**. ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/balance_updates/390740000_390740049.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/balance_updates/390740000_390740049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access Data Store exports are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming Solana data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - [**gRPC (CoreCast)**](/docs/grpc/solana/introduction) for Solana - **GraphQL subscriptions** --- ## Solana Data API - DEX Trades, Token Data, Real-Time Streams URL: https://docs.bitquery.io/docs/blockchain/Solana/ Solana data API hub: DEX trades, token data, PumpFun, Raydium and Meteora APIs, gRPC (CoreCast) and Kafka streams, WebSocket support and how it compares to RPC. # Solana Data API - DEX Trades, Token Data, Real-Time Streams :::tip Building a trading app or DEX UI on Solana? For **real-time trades and prices on Solana** (and the last ~30 days), use the curated [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. For **historical Solana data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: These are the query docs for the [Bitquery Solana API](https://bitquery.io/blockchains/solana-blockchain-api); plans, trial access and delivery options are on that page. Access data from **[Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/)**, **[Raydium DEX API](/docs/blockchain/Solana/Solana-Raydium-DEX-API)**, **[Orca API](/docs/blockchain/Solana/solana-orca-dex-api)**, **[DEXScreener API](/docs/blockchain/Solana/DEXScreener/solana_dexscreener/)**, **[Jupiter API](/docs/blockchain/Solana/solana-jupiter-api)**, **[Meteora](/docs/blockchain/Solana/Meteora-DLMM-API)**, **[GMGN](/docs/blockchain/Solana/solana-gmgn-api)**, **[Phoenix](/docs/blockchain/Solana/Solana-Phoenix-api)**, and more via GraphQL APIs and Streams. > **Before you start**: Not sure when to use Transfers vs DEX Trades vs other data primitives? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. If you need help getting data on Solana,reach out to [support](https://t.me/Bloxy_info) ## What is Solana API? Bitquery Solana APIs help you fetch onchain data by writing a graphQL query. Bitquery **V2** exposes **Solana** through GraphQL on `streaming.bitquery.io` with **`Solana { … }`** queries: **DEX trades** (Pump.fun, Raydium, Orca, Jupiter, and more), **token transfers**, **balances**, **transactions**, **NFTs**, and **aggregates** (`dataset: combined`, `realtime`, `archive`—see [datasets](/docs/graphql/dataset/combined/)). You also get **WebSocket subscriptions**, **Kafka** topics, and **Solana gRPC (CoreCast)** for low-latency streams. Start from the links below or [historical aggregate data](/docs/blockchain/Solana/historical-aggregate-data/) for OHLC-style queries. ## What are capabilities of Bitquery Solana API? Bitquery Solana APIs are very flexible, you can fetch trade, transaction, balance information for a period, for a specific wallet and join with other information. ## Difference between Solana RPC and Bitquery Solana API? **Solana RPC** - JSON-RPC endpoint exposing raw on-chain state & transactions - No built-in history or analytics—any indexing/aggregation you build or outsource - Ideal for submitting transactions **Bitquery Solana API** - GraphQL endpoint over pre-indexed, parsed Solana data (token transfers, DEX trades, NFTs, etc.) - Historical data, joins, aggregations & real-time subscriptions - Great for real-time data and historical backtesting without running your own indexer ## Difference between Solana Geyser stream and Bitquery Kafka Stream? **Solana Geyser stream** - **Data & Protocol**: Runs as a plugin in your own Solana validator, emitting raw on-chain events (account updates, slot status changes, processed transactions, block metadata) over binary or gRPC feeds. - **Infra & Maintenance**: You must host, scale, and secure the node yourself, parse and index all raw data client-side, and deal with only basic filtering—latency and reliability depend entirely on your setup; no built-in historical querying. **Bitquery Kafka Stream** - **Data & Protocol**: Provides fully managed Kafka topics—`solana.dextrades.proto`, `solana.tokens.proto`, and `solana.transactions.proto`—delivering pre-parsed, enriched Protocol-Buffers events (DEX trades, token transfers, supply/balance updates, instructions, blocks, etc.). - **Infra & Maintenance**: Enterprise-grade, auto-scaling Kafka streams with sub-second latency, schema-based filtering, instruction-level balance updates, built-in replication/failover—no node ops or custom parsing needed. Read more [here](/docs/streams/real-time-solana-data/) and contact sales via [Telegram](https://t.me/Bloxy_info) or [form](https://bitquery.io/forms/api) for a **Trial**. ## Solana gRPC Streams (CoreCast) Bitquery **[Solana gRPC Streams](/docs/grpc/solana/introduction/)** (CoreCast) provide ultra-low-latency, real-time data over gRPC with protobuf encoding. Subscribe to DEX trades, transfers, transactions, balances, and more with context-aware filtering — ideal for trading bots, copy trading, and high-frequency applications. - **[CoreCast Introduction](/docs/grpc/solana/introduction/)** — Topics, filters, and quick start - **[Pump.fun gRPC Streams](/docs/grpc/solana/examples/pump-fun-grpc-streams/)** — Real-time Pump.fun trades - **[Copy Trading Bot](/docs/grpc/solana/examples/grpc-copy-trading-bot/)** — Build a Solana copy trading bot with gRPC ## Does Bitquery support Solana Websocket and Solana Webhooks? Bitquery supports websocket and webhooks, you can convert most of the graphQL APIs into graphQL streams by changing the word `query` to `subscription`. You can monitor this data via a websocket. More and [code samples available here](/docs/subscriptions/websockets/) ## PumpFun - [DEXrabbit Pump.fun tokens](https://dexrabbit.bitquery.io/categories/pump-fun) — live DEX prices and 24h volume - [Pump Fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [Pump Swap API](/docs/blockchain/Solana/Pumpfun/pump-swap-api/) - [Marketcap Bonding Curve API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-Marketcap-Bonding-Curve-API/) - [Pump Fun to Pump Swap](/docs/blockchain/Solana/Pumpfun/pump-fun-to-pump-swap/) ## Raydium - [Raydium Launchpad](/docs/blockchain/Solana/launchpad-raydium) - [Raydium DEX API](/docs/blockchain/Solana/Solana-Raydium-DEX-API) - [Raydium CLMM API](/docs/blockchain/Solana/raydium-clmm-API) - [Raydium CPMM API](/docs/blockchain/Solana/raydium-cpmm-API) ## Meteora - [Meteora DAMM v2 API](/docs/blockchain/Solana/Meteora-DAMM-v2-API) - [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API) - [Meteora DAMM v1 API](/docs/blockchain/Solana/Meteora-DYN-API) - [Meteora Dynamic Bonding Curve API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api) ## Solana DEX APIs - [Solana Dex Trades](/docs/blockchain/Solana/solana-dextrades) - [Solana Trader API](/docs/blockchain/Solana/solana-trader-API) - [Historical Aggregate Data](/docs/blockchain/Solana/historical-aggregate-data) - [Solana Zeta](/docs/blockchain/Solana/solana-zeta) - [Solana Jupiter API](/docs/blockchain/Solana/solana-jupiter-api) - [DFlow API](/docs/blockchain/Solana/dflow-api) - [OKX DEX API (Solana)](/docs/blockchain/Solana/okx-dex-solana-api) - [Solana Launchpad Creator Fees API](/docs/blockchain/Solana/solana-launchpad-creator-fees-api) - [Solana GMGN API](/docs/blockchain/Solana/solana-gmgn-api) - [Solana BullX API](/docs/blockchain/Solana/solana-bullx-api) - [Solana Photon API](/docs/blockchain/Solana/solana-photon-api) - [Moonshot API](/docs/blockchain/Solana/Moonshot-API) - [Solana Aldrin AMM API](/docs/blockchain/Solana/Solana-AldrinAmm-api) - [Solana DEX Orders API](/docs/blockchain/Solana/Solana-DEX-Orders-API) - [Solana Dex Pools API](/docs/blockchain/Solana/Solana-DexPools-API) - [Solana Jito Bundle API](/docs/blockchain/Solana/Solana-Jito-Bundle-api) - [Solana Lifinity DEX API](/docs/blockchain/Solana/Solana-Lifinity-dex-api) - [Believe API](/docs/blockchain/Solana/Believe-API) - [Solana OpenBook API](/docs/blockchain/Solana/Solana-OpenBook-api) - [Solana Phoenix API](/docs/blockchain/Solana/Solana-Phoenix-api) - [SolFi API](/docs/blockchain/Solana/SolFi-api) - [Orbic API](/docs/blockchain/Solana/Orbic-API) - [DEX Screener (Solana)](/docs/blockchain/Solana/DEXScreener/solana_dexscreener/) PancakeSwap also runs a concentrated-liquidity AMM on Solana, program `HpNfyc2Saw7RKkQd8nEL4khUcuPhQ7WwY1B2qjx8jxFq`. Its swaps are in [Solana Dex Trades](/docs/blockchain/Solana/solana-dextrades) with `ProtocolFamily: "PancakeSwap"` and `ProtocolName: "amm_v3"`; filter on `Trade.Dex.ProgramAddress` to select it, because Raydium CLMM uses the same protocol name. ## Other Solana APIs - [Solana Balance Updates](/docs/blockchain/Solana/solana-balance-updates) - [Solana Token Price API](/docs/blockchain/Solana/solana-token-price-api) - [Token Supply Cube](/docs/blockchain/Solana/token-supply-cube) - [Solana Instructions](/docs/blockchain/Solana/solana-instructions) - [Solana Transactions](/docs/blockchain/Solana/solana-transactions) - [Solana Transaction Signers](/docs/blockchain/Solana/solana-transaction-signers) - [Solana Transfers](/docs/blockchain/Solana/solana-transfers) - [Solana Fees API](/docs/blockchain/Solana/solana_fees_api) - [Boop Fun API](/docs/blockchain/Solana/Boop-Fun-API) - [BonkSwap API](/docs/blockchain/Solana/BonkSwap-API) - [LetsBonk.fun API](/docs/blockchain/Solana/letsbonk-api) - [StonkFun API](/docs/blockchain/Solana/stonkfun-api) - [Solana Logs](/docs/blockchain/Solana/solana-logs) - [Solana NFT](/docs/blockchain/Solana/solana-nft) - [Solana Orca DEX API](/docs/blockchain/Solana/solana-orca-dex-api) - [Solana Rewards](/docs/blockchain/Solana/solana-rewards) - [Solana Search Tokens](/docs/blockchain/Solana/solana-search-tokens) - [Historical Solana Transfer Data](https://docs.bitquery.io/v1/docs/Examples/Solana/transfers) - [Building an AI Trading Agent on Solana](/docs/blockchain/Solana/ai-agent-solana-data) ## Videos ### Pump.Fun API | Get Live Prices, Metadata, OHLCV, Trading Pair Stats, Charts ### Video Tutorial on Getting Pump Fun Trades ### Video Tutorial | How to Get the OHLC Data & Price of a Token on Pump Fun DEX in Realtime ### Video Tutorial on Solana Transfers API | How to get NFT, SPL Transfers data on Solana in Realtime ### Video Tutorial | How to Track Latest Trades, Latest Price of a Token on Solana Raydium DEX ### Video Tutorial | How to Track Latest Created Liquidity Pools, OHLC data of a specific pair on Solana Raydium DEX ## More guides - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) — how far back Solana data goes - [Common errors and what to do](/docs/start/errors/) — empty results, dataset, and quota errors - [Kafka Operations Cookbook](/docs/streams/kafka-operations/) - [Plans, Points & Limits](/docs/plans/how-billing-works/) --- ## Solana Fee Anatomy - Base, Priority and Jito Tips URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-fee-anatomy/ Break a Solana transaction fee into base fee and priority fee, find what a wallet spends on fees, and understand why Jito tips are not part of the fee. # Solana fee anatomy A Solana transaction costs money in up to three ways, and only two of them appear in `Transaction.Fee`: | Component | In `Transaction.Fee`? | What it is | |---|---|---| | **Base fee** | Yes | 5,000 lamports per signature, fixed by the protocol | | **Priority fee** | Yes | compute unit price × compute units requested, set by the sender | | **Jito tip** | **No** | a normal SOL transfer to a Jito tip account | That third row is the one that causes miscounting. A Jito tip is a transfer instruction, not a fee, so it never shows up in `Fee`. Add it separately from [the Jito Bundle API](/docs/blockchain/Solana/Solana-Jito-Bundle-api/) if you want true all-in cost. ## Splitting base from priority The cube exposes the total `Fee` but not its components, so you derive the split. Base fee is 5,000 lamports per signature, so for a single-signature transaction: ``` priority_lamports = fee_lamports - 5000 ``` ```js const feeLamports = Math.round(Number(tx.Fee) * 1e9); const signatures = 1; // see the caveat below const baseFee = 5000 * signatures; const priorityFee = Math.max(0, feeLamports - baseFee); ``` :::caution Signature count is not exposed, so the split is inexact `Transactions` does not return the number of signatures, and a two-signature transaction with no priority fee costs exactly the same as a one-signature transaction paying 5,000 lamports of priority. In a sample of recent successful transactions, fees cluster hard on 5,000 and 10,000 lamports, which are one and two signatures at zero priority. Treat `fee - 5000` as an **upper bound** on the priority fee for an unknown transaction, and as exact only where you know the transaction is single-signature. ::: ## How much priority is actually being paid Quantiles answer this in one query, without pulling rows: ```graphql query SolanaFeeDistribution { Solana { Transactions(where: { Transaction: { Result: { Success: true } } }, limit: { count: 1 }) { transactions: count p25: quantile(of: Transaction_Fee, level: 0.25) median: median(of: Transaction_Fee) p75: quantile(of: Transaction_Fee, level: 0.75) p99: quantile(of: Transaction_Fee, level: 0.99) maxFee: quantile(of: Transaction_Fee, level: 0.999) } } } ``` The shape of the answer is consistent even as the numbers move: the median sits **at the base fee**, the quartiles sit at or barely above it, and the distribution only lifts in the last percentile or two. Most Solana transactions pay no meaningful priority fee at all; a small minority bidding for block position accounts for nearly all of the priority spend. This matters when you size a fee strategy. Comparing your fee against the mean puts you against a number dragged upward by a handful of bots. Compare against the median and the p99 instead, and decide which population you are competing with. ## Transactions that paid real priority Filter on `Fee` to isolate the bidders: ```graphql query HighPriorityTransactions { Solana { Transactions( where: { Transaction: { Result: { Success: true }, Fee: { gt: "0.0001" } } } orderBy: { descending: Block_Time } limit: { count: 25 } ) { Block { Time } Transaction { Signature Fee FeeInUSD FeePayer InstructionsCount } } } } ``` `0.0001` SOL is 100,000 lamports, twenty times the base fee, so anything returned is paying to be included early rather than merely to be included. ## What a wallet spends on fees Group by `FeePayer` to rank fee spend, which is a good proxy for who is running bots: ```graphql query TopFeePayers { Solana { Transactions( where: { Transaction: { Result: { Success: true } } } orderBy: { descendingByField: "totalFee" } limit: { count: 25 } ) { Transaction { FeePayer } totalFee: sum(of: Transaction_Fee) totalFeeUsd: sum(of: Transaction_FeeInUSD) transactions: count avgFee: average(of: Transaction_Fee) } } } ``` Drop the success filter and add `Transaction { Result { Success } }` to the selection to see how much of a payer's spend goes on transactions that never landed. ## Failed transactions still cost money Grouping by result is the query most worth running once: ```graphql query FeeSpentOnFailures { Solana { Transactions(limit: { count: 4 }) { Transaction { Result { Success } } transactions: count totalFee: sum(of: Transaction_Fee) avgFee: average(of: Transaction_Fee) } } } ``` Two things fall out of it, and both hold across runs: - **Failed transactions pay a higher average fee than successful ones.** That is not a paradox. Priority fees are highest exactly where competition is fiercest, and most racers lose. - **A substantial share of all fees paid on Solana is spent on transactions that fail.** If you are estimating the cost of a strategy from successful transactions alone, you are understating it, and the gap widens the more aggressively you bid. This is also the honest counterweight to any landing-rate comparison: a venue that fails often is not merely slower, it is charging you for the failures. ## Related - [Jito Bundle API](/docs/blockchain/Solana/Solana-Jito-Bundle-api/) — tips, which sit outside `Fee` - [Solana Fees API](/docs/blockchain/Solana/solana_fees_api/) — fees attached to trades and transfers - [Solana Transactions API](/docs/blockchain/Solana/solana-transactions/) - [Solana Blocks API](/docs/blockchain/Solana/solana-blocks-api/) --- ## Solana Fees API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana_fees_api/ Solana Fees API: analyze Solana transaction fees and costs with Bitquery GraphQL queries and streams. Scale further with Kafka or gRPC streams. # Solana Fees API In this document, we will explore several examples related to Solana Fees data. We also have [Pump.fun APIs](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) to track Pump Fun token swaps, [PumpSwap APIs](/docs/blockchain/Solana/Pumpfun/pump-swap-api/) if you want to track the token after it has been migrated to PumpSwap AMM. Additionally, you can also check out our [Moonshot APIs](/docs/blockchain/Solana/Moonshot-API/), [FourMeme APIs](/docs/blockchain/BSC/four-meme-api/). These APIs can be provided through different streams including Kafka for zero latency requirements. Please contact us on telegram. If you want fastest data without any latency, we can provide Kafka streams, please [fill this form](https://bitquery.io/forms/api) for it. Our Team will reach out. ## Get Trades with Transaction fees Get a list of successful DEX trades on Solana along with the transaction fee details for each trade. You can test the query [here](https://ide.bitquery.io/trades-with-transaction-fees#). ```graphql query MyQuery { Solana { DEXTradeByTokens( where: {Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Block { Time Slot } Trade { Account { Address Token { Owner } } AmountInUSD Amount PriceInUSD Price Dex { ProtocolName } Currency { MintAddress Name } Side { Account { Address Token { Owner } } Type AmountInUSD Amount Currency { Name MintAddress } } } Transaction { Signer Signature FeeInUSD Fee FeePayer } } } } ``` ## Get Transfers by an address and Transaction fees paid for the transfer Track wallet token transfers and get the fees paid for each by the address. You can test the query [here](https://ide.bitquery.io/wallet-transfers-with-transaction-fees-paid#). ```graphql query MyQuery { Solana { Transfers( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Result: {Success: true}, FeePayer: {is: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"}}} ) { Block { Time } Transfer { Currency { Name MintAddress Symbol } Sender { Address } Receiver { Address } } Transaction { Fee FeeInUSD FeePayer Signer Signature } } } } ``` ## Total transaction fees paid by an account Get the total fees (in SOL and USD) paid by a specific Solana account across all transfers. You can test the query [here](https://ide.bitquery.io/total-txn-fees-paid-by-the-Account#). ```graphql query MyQuery { Solana { Transfers( where: {Transaction: {Result: {Success: true}, FeePayer: {is: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"}}} ) { Total_fees_paid_in_USD:sum(of:Transaction_FeeInUSD) Total_fees_paid_in_SOL:sum(of:Transaction_Fee) } } } ``` ## Transaction fees paid by an account for each currency transfers Get total fees paid by a Solana account for transferring each type of token. You can test the query [here](https://ide.bitquery.io/Transaction-fees-paid-by-Account-aggregated-by-currency#). ```graphql query MyQuery { Solana { Transfers( where: {Transaction: {Result: {Success: true}, FeePayer: {is: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"}}} ) { Transfer{ Currency{ Name Symbol } } Total_fees_paid_in_USD:sum(of:Transaction_FeeInUSD) Total_fees_paid_in_SOL:sum(of:Transaction_Fee) } } } ``` ## Video Tutorial | How to get Total Fees paid by a Account on Solana ## 🔗 Related Solana APIs - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Monitor trading activities and their fees - **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** - Track transfer fees and costs - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor balance changes including fees - **[Solana Instructions API](/docs/blockchain/Solana/solana-instructions/)** - Track instruction execution fees - **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** - Monitor supply-related transaction fees --- ## Solana Heaven DEX API URL: https://docs.bitquery.io/docs/blockchain/Solana/heaven-dex-api/ Heaven DEX on Solana: track token creation, market cap, latest price, latest trades, OHLC candles, top traders and buy and sell volume for Heaven tokens. # Heaven DEX API :::tip Need real-time Heaven DEX data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Heaven DEX swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Heaven DEX data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this document, we will explore several examples related to Heaven Dex. You can also check out our [Pump Fun API Docs](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) and [FourMeme API Docs](/docs/blockchain/BSC/four-meme-api/). Need zero-latency Heaven DEX data? [Read about our Shred Streams and Contact us for a Trial](/docs/streams/real-time-solana-data/). :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: If you want fastest data without any latency, we can provide Kafka streams, please [fill this form](https://bitquery.io/forms/api) for it. Our Team will reach out. ## Track Heaven DEX Token Creation Using [this](https://ide.bitquery.io/Track-Heaven-DEX-Token-Creation_1) query, we can get the realtime created Heaven DEX tokens.
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o" } Method: { is: "create_standard_liquidity_pool" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method Name } } Transaction { Signature Signer } } } } ```
## Market cap (Trading API) Use **Trading** **`Pairs`** with **`Market.Protocol`** **`Heaven`** for aggregated **market cap**, **FDV**, **supply**, **price**, and **volume**. Replace **`solana:`** in **`Token.Id`** with your token. ### Get latest market cap for a specific Heaven DEX token **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, **`Token.Id`** with **`includesCaseInsensitive`**, interval duration **> 1** second, **`Market.Protocol`** **`Heaven`**. Run the query [in the Bitquery IDE](https://ide.bitquery.io/specific-heaven-dex-token-latest-marketcap).
Click to expand GraphQL query ```graphql { Trading { Pairs( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { includesCaseInsensitive: "solana:7GMB7XbtTdvnHkPjH6yEwTUB3HYf5dqC3FKyr2sueMEh" } } Interval: { Time: { Duration: { gt: 1 } } } Market: { Protocol: { is: "Heaven" } } } ) { Token { Name Id Address Symbol } Block { Time } Market { Program Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ```
### Stream Heaven DEX tokens with market cap above $10K Subscribe when the token is on **Solana**, **`Market.Protocol`** is **`Heaven`**, **`Supply.MarketCap`** **> 10,000** (USD), and interval duration **> 1** second. Adjust **`gt`** to change the threshold. Run the subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-heaven-tokens-with-marketcap-10k).
Click to expand GraphQL subscription ```graphql subscription { Trading { Pairs( where: { Token: { Id: { includesCaseInsensitive: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 10000 } } Market: { Protocol: { is: "Heaven" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
## Latest price of a token on Heaven DEX This returns the most recent trade for a token on the venue, with the price in the quote token and in USD. You can run this query using [this link](https://ide.bitquery.io/live-price-of-token-on-heaven-dex).
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o"}}, Currency: {MintAddress: {is: "G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ```
## Latest Trades on Solana Heaven To subscribe to the real-time trades stream for Solana Heaven DEX, [try this GraphQL subscription (WebSocket)](https://ide.bitquery.io/Real-time-trades-on-Heaven-DEX-on-Solana).
Click to expand GraphQL query ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Account { Address } Amount Currency { MintAddress Decimals Symbol ProgramAddress Name } PriceAgaistSellCurrency: Price } Sell { Account { Address } Amount Currency { MintAddress Decimals Symbol Name } PriceAgaistBuyCurrency: Price } } Block { Time Height } Transaction { Signature FeePayer Signer } } } } ```
## Latest Trades for a specific currency on Solana Heaven DEX Let's say you want to receive [trades only for a specific currency on Heaven DEX](https://ide.bitquery.io/Real-time-buy-and-sell-of-specific-currency-on-Heaven-DEX-on-Solana_3). You can use the following stream. Use currency's mint address; for example, in the following query, we are using Ray token's Mint address to get buy and sells of Ray token. If you limit it to 1, you will get the latest price of the token because the latest trade = the Latest Price. Run this query [using this link](https://ide.bitquery.io/Real-time-buy-and-sell-of-specific-currency-on-Heaven-DEX-on-Solana_2).
Click to expand GraphQL query ```graphql subscription { Solana { Buyside: DEXTrades( where: { Trade: { Buy: { Currency: { MintAddress: { is: "G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777" } } } Dex: { ProgramAddress: { is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistSellCurrency: Price } Sell { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistBuyCurrency: Price } } Block { Time Height } Transaction { Signature FeePayer Signer } } Sellside: DEXTrades( where: { Trade: { Sell: { Currency: { MintAddress: { is: "G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777" } } } Dex: { ProgramAddress: { is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistSellCurrency: Price } Sell { Account { Address } Amount Currency { Decimals Symbol MintAddress Name } PriceAgaistBuyCurrency: Price } } Block { Time Height } Transaction { Signature FeePayer Signer } } } } ```
## Heaven OHLC API If you want to get OHLC data for any specific currency pair on Heaven DEX, you can use [this api](https://ide.bitquery.io/Heaven-OHLC-for-specific-pair). Only use this API as `query` and not `subscription` websocket as Aggregates and Time Intervals don't work well with subscriptions.
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Dex: { ProgramAddress: { is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o" } } PriceAsymmetry: { lt: 0.1 } } } limit: { count: 10 } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ```
## Get the Top Traders of a specific Token on Heaven DEX This ranks the wallets trading one token on the venue. Run it as a plain request rather than a WebSocket subscription, because aggregates are recomputed per message on a subscription and the totals come back wrong. Open it in the [Bitquery IDE: top traders on Heaven](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Heaven-DEX)
Click to expand GraphQL query ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProgramAddress: {is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777" } ```
## Get trading volume, buy volume, sell volume of a Heaven DEX token This reads the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`. Every Trading row carries a vetted USD price and the cube covers roughly the last 30 days in full, while the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so volume totals taken from them read low. `Side` is the trader's own side. Tokens here are short lived, so the example uses the LIGHT/WSOL market that was trading when this page was checked; swap the base mint for the token you want. Open it in the [Bitquery IDE: trade volume](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-heaven-dex-token).
Click to expand GraphQL query ```graphql { Trading { Trades( where: { Pair: { Market: { ProtocolFamily: { is: "Heaven" }, Network: { is: "Solana" } } Token: { Address: { is: "LiGHtkg3uTa9836RaNkKLLriqTNRcMdRAhqjGWNv777" } } QuoteToken: { Address: { is: "So11111111111111111111111111111111111111112" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
## Video Tutorials ### Get Unlimited Bags FM Token Data Using Bitquery API --- ## Solana Historical Data API: OHLCV, Trades and Archive URL: https://docs.bitquery.io/docs/blockchain/Solana/historical-aggregate-data/ Solana historical data: OHLCV candles by mint or pair, aggregate trade history from June 2024, 30-day trade rows, transfers to genesis, CSV and Parquet export. # Solana Historical Data API: OHLCV, Trades and Archive Solana history on Bitquery comes in four layers, and the right one depends on how far back you need to go. Per-trade rows on `DEXTrades` are also on `archive` and `combined`, being backfilled toward 2024, with a required time or slot bound: see [Historical DEXTrades on archive and combined](/docs/blockchain/Solana/solana-dextrades/#historical-dextrades-archive-combined). Aggregate trade history (OHLCV, volume, ATH, first buyers, PnL) runs on the `DEXTradeByTokens` cube with `dataset: archive` or `combined` and starts on 1 June 2024. Per-trade rows with USD prices for the last month come from the [Trading API](/docs/trading/crypto-trades-api/trades-api/). SPL transfers back to the chain's genesis are on the [V1 endpoint](https://docs.bitquery.io/v1/docs/Examples/Solana/transfers). Bulk history for backtesting ships as Parquet exports from the [Bitquery Data Store](https://bitquery.io/datastore) (technical details: [Solana exports](/docs/cloud/solana)). Every query on this page runs as written in the [Bitquery IDE](https://ide.bitquery.io). The free trial and paid self-service plans cover real-time data only, so the `archive` and `combined` queries need the Solana Historical OHLCV & Token Price Data add-on from the [pricing page](https://bitquery.io/pricing), which covers both `DEXTradeByTokens` and `DEXTrades`. | Layer | Where | How far back | Use it for | |---|---|---|---| | Aggregate history | `Solana(dataset: archive)` or `combined`, `DEXTradeByTokens` | From 1 June 2024 | OHLCV, volume, ATH, first buyers, trader PnL | | Per-trade history | `Solana(dataset: archive)` or `combined`, `DEXTrades` | Being backfilled, will reach 2024 | Per-trade rows, wallet and token trade lookups. Needs a `Block.Time`, `Block.Slot` or `Block.Date` bound | | Recent per-trade rows | `Trading.Trades`, with built candles in `Trading.Tokens` and `Trading.Pairs` | About the last 30 days | Trade-level rows with USD prices, candles down to one second | | Realtime | `Solana(dataset: realtime)` cubes | About 7 days on `DEXTradeByTokens`, hours on the other cubes | Live filters, including the USD fields the aggregate datasets reject | | Transfers to genesis | V1 GraphQL endpoint | Full chain history | SPL transfer history | | Bulk exports | Data Store exports: Parquet on S3, GCS, Snowflake or BigQuery | Older than the API windows; other ranges on request | Backtesting and warehouses | Retention per cube is on the [data coverage and retention](/docs/graphql/data-coverage-retention) page. :::caution Archive is deep but not complete On `DEXTradeByTokens`, the `archive` dataset returns fewer trades than `realtime` over a window both cover: measured on several busy markets, archive came back roughly a fifth to a quarter short, with volume short by a similar margin. `combined` adds the realtime tail on top of the same archive rows. Use archive for depth, and read the last 30 days from the [Trading API](/docs/trading/crypto-trades-api/trades-api/) when the totals have to be exact. The examples below name `archive`; switch to `combined` when the range has to reach the current block. Expect these to be slow. An unbounded ATH or all-time OHLCV scan runs for tens of seconds against the aggregate tables, and on a busy mint such as WSOL it can exceed the gateway timeout and return a 502 instead of rows. Add a `Block: { Time: { since: ... } }` bound whenever you do not genuinely need the full range. ::: :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## Filter limitations on aggregate datasets On `Solana` with `dataset: archive` or `dataset: combined`, `DEXTradeByTokens` is served from pre-aggregated tables. **USD-denominated fields and `PriceAsymmetry` cannot be used inside `where:`.** A query that filters on them fails outright with an error such as `no table can query DEXTradeByToken` or `database schema not defined for archive cube`. It does not silently return different numbers. The same USD fields work normally as **output measures**. | Field | As a `where:` filter | As a measure / projection | |---|---|---| | `Trade.Amount`, `Trade.Side.Amount` | works | works | | `Trade.Price` | works | works | | `Trade.Currency`, `Trade.Side.Currency` | works | works | | `Trade.Account.Address` | works | works | | `Trade.Side.Type`, `Trade.Dex`, `Block.Time` | works | works | | `Trade.PriceAsymmetry` | **error** | not available | | `Trade.Side.AmountInUSD`, `Trade.AmountInUSD` | **error** | works, as `sum(of: Trade_Side_AmountInUSD)` | | `Trade.PriceInUSD` | **error** | works, as `quantile(of: Trade_PriceInUSD)` | | `Trade.Side.Account` | **error** | **error** | All of these filters work on `dataset: realtime`, which covers a rolling recent window (hours). To filter by USD amount or `PriceAsymmetry` over history, use the [Trading API](/docs/trading/crypto-trades-api/trades-api/), which carries USD price and supply on every row. ## Historical Trades for Solana **Historical trades for upto past 30 days could be retrieved via Trading API. Docs available [here](/docs/trading/crypto-trades-api/trades-api/).** The [Bitquery IDE: Solana trades over the last 30 days](https://ide.bitquery.io/historical-Solana-trades_1) example reads per-trade rows for that window through the Trading API. ```graphql query MyQuery { Trading { Trades( where: {Pair: {Market: {Network: {is: "Solana"}}}, Block: {Date: {before_relative: {days_ago: 25}, after_relative: {days_ago: 27}}}} orderBy: {ascending: Block_Date} limit: {count: 100} ) { Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Time } Pair { Market { Address Program } Pool { Address Id } QuoteToken { Name Symbol Address } Token { Name Symbol Address } } Price PriceInUsd Ranking { Position Weight } Side Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply } Trader { Address } TransactionHeader { Fee Hash } } } } ``` The example asks for a two-day slice at the far end of the window and caps the rows with `limit`. An unbounded request over the whole month can time out. ## Historical OHLCV candles for a Solana token pair {#historical-ohlc-on-solana} [This](https://ide.bitquery.io/Historical-OHLC-for-Solana-archive) query returns daily open, high, low and close prices for a pair, with volume and trade count per candle. `Trade.Currency` is the token by mint address, `Trade.Side.Currency` is the quote token, and `Time(interval: ...)` sets the candle size in seconds, minutes, hours or days. The example is USDC against WSOL, a pair that will still be trading when you run it. For one token across every pair, drop the `Side` filter. ```graphql { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } } limit: { count: 10 } ) { Block { Timefield: Time(interval: { in: days, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ### Export the candles to CSV The same query from a script, written to a CSV file. Only the Python standard library is used; set `BITQUERY_TOKEN` to your access token first. ```python TOKEN = os.environ["BITQUERY_TOKEN"] # your Bitquery access token QUERY = """ { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } } limit: { count: 365 } ) { Block { Timefield: Time(interval: { in: days, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } """ req = urllib.request.Request( "https://streaming.bitquery.io/graphql", data=json.dumps({"query": QUERY}).encode(), headers={"Content-Type": "application/json", "Authorization": f"Bearer {TOKEN}"}, ) rows = json.load(urllib.request.urlopen(req))["data"]["Solana"]["DEXTradeByTokens"] with open("usdc_wsol_daily.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["time", "open", "high", "low", "close", "volume", "trades"]) for r in rows: t = r["Trade"] w.writerow([r["Block"]["Timefield"], t["open"], t["high"], t["low"], t["close"], r["volume"], r["count"]]) print(f"wrote {len(rows)} candles") ``` Swap the mint addresses, the interval and the `limit` for other pairs and candle sizes. For whole-history exports across many tokens, [Data Store exports](https://bitquery.io/datastore) deliver the same data as Parquet. :::note Important Considerations - Each OHLC data point is calculated independently per time interval (e.g., daily). There’s no enforcement to make the `Close` of one candle match the `Open` of the next. - **Gaps are possible**: Since the data is based on actual trades, if no trades occur exactly at the start or end of a day, the nearest trades before and after those timestamps will define the open and close. For instance: - Last trade on April 14: `23:58:12` - First trade on April 15: `00:03:45` These would represent the _close_ of April 14 and _open_ of April 15 respectively, leaving a gap in between. - **Derived from block time**: All time-based grouping (daily, hourly, etc.) depends on block timestamps. - **No `PriceAsymmetry` filter on archive/combined**: this query cannot exclude asymmetric prints, so `high` and `low` take raw extremes and may include outlier trades. For cleaner candles over the last ~30 days use the [Trading API](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/), which serves USD OHLC directly. See [Filter limitations](#filter-limitations-on-aggregate-datasets). **Alternative approach**: You can get all trades and calculate OHLC locally in your own system. Complete guide [here](/docs/usecases/ohlcv-complete-guide/) ::: ## First 24 Hours Trade Volume for a Solana Token [This](https://ide.bitquery.io/first-24-hr-volume-for-a-token) query returns the trade volume for a Solana Token in the first 24 hours of its launch. We are using `13WvP5LC5ETUpFipYM2f9AQzg6QA9S5opxGp2Scpump` in this case. ```graphql query MyQuery { Solana(dataset: archive, aggregates: yes) { DEXTradeByTokens( orderBy: { ascendingByField: "Block_TimeFeild" } limit: { count: 1 } where: { Trade: { Currency: { MintAddress: { is: "13WvP5LC5ETUpFipYM2f9AQzg6QA9S5opxGp2Scpump" } } } } ) { Block { TimeFeild: Time(interval: { count: 24, in: hours }) } sum(of: Trade_Side_AmountInUSD) } } } ``` ## Top 100 traders of a token [This](https://ide.bitquery.io/top-traders-for-a-specific-token) query returns the top token traders for a specific token by USD volume over a date range. The example uses token mint `98sMhvDwXj1RQi5c5Mndm3vPe9cBqPrbLaufMXFNMh5g` paired with SOL (`So11111111111111111111111111111111111111112`) and the combined dataset for 2026-01-01 to 2026-01-02. You get trader address (Owner), buy/sell counts, buy/sell volume, total volume, and trade count per trader. ```graphql { Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "98sMhvDwXj1RQi5c5Mndm3vPe9cBqPrbLaufMXFNMh5g" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } Transaction: { Result: { Success: true } } Block: { Date: { since: "2026-01-01", till: "2026-01-02" } } } orderBy: { descendingByField: "volume" } limit: { count: 100 } ) { Trade { Currency { Name Symbol MintAddress } Account { Owner } } buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) buy_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) sell_volume: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) volume: sum(of: Trade_Side_AmountInUSD) trades: count } } } ``` ## Tokens Traded by an Account [This](https://ide.bitquery.io/tokens-traded-by-an-address) query returns the list of tokens traded by the wallet address over a period of time. The list is sorted by the amount of tokens traded, and returns token info such as mint address, name and symbol along with the total amount of tokens traded and the number of trades involving that token. ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { descendingByField: "tokens" } where: { Trade: { Account: { Owner: { is: "3CgvbiM3op4vjrrjH2zcrQUwsqh5veNVRjFCB9N6sRoD" } } } } ) { Trade { Currency { MintAddress Name Symbol } } tokens: sum(of: Trade_Amount) trades: count } } } ``` ## Change in Liquidity Over a Month [This](https://ide.bitquery.io/liquidity-change-in-recent-month) query returns the change in `liquidity` for a particular token pair over the last month. For this example the parameters listed below are used. 1. Primary Token - `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` (USDC). 2. Secondary Token - `So11111111111111111111111111111111111111112` (WSOL), 3. Pool Address - `Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE` (the USDC/WSOL Orca Whirlpool) ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } Side: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Market: { MarketAddress: { is: "Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE" } } } } orderBy: { descendingByField: "Block_Timefield" } limit: { count: 1 } ) { tokenLiquidity: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) wsolLiquidity: sum( of: Trade_Side_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) Block { Timefield: Time(interval: { in: months, count: 1 }) } Trade { Market { MarketAddress } } } } } ``` ## Get ATH (All-Time High) of a Token In this query we use the 95th percentile (`level: 0.95`) to find the highest price of a token. The 95th percentile is itself outlier-resistant, which matters here because `PriceAsymmetry` and `AmountInUSD` **cannot be used as filters** on aggregate datasets. See [Filter limitations on aggregate datasets](#filter-limitations-on-aggregate-datasets). On `dataset: realtime` you can add both filters for stricter outlier control. Read more about quantiles [here](/docs/graphql/metrics/quantile/) You can run the query [here](https://ide.bitquery.io/Price-ATH-query) ```graphql { Solana(dataset: archive) { DEXTradeByTokens( where: {Trade: {Side: {Currency: {MintAddress: {in: ["11111111111111111111111111111111", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", "So11111111111111111111111111111111111111112"]}}}, Currency: {MintAddress: {is: "2tnA2ZmwmgUZLyYLi97zbwsFBXAqpMEcHu9Cv9JW6m26"}}}} limit: {count: 1} orderBy: {descendingByField: "aATH"} ) { aATH: quantile(of: Trade_PriceInUSD, level: 0.95) } } } ``` ## Get ATH Price, ATH Date, Price Change percentage in 24h, 7d, 30d Fetches a Solana token’s ATH price, ATH date, and price change percentages over the past 24h, 7d, and 30d using Bitquery Solana APIs. Try the [query to get ATH price, ATH date, price change](https://ide.bitquery.io/ATH-with-price-delta-Solana). ```graphql query ($token: String) { Solana(dataset: archive) { DEXTradeByTokens( where: {Trade: {Side: {Currency: {MintAddress: {in: ["11111111111111111111111111111111", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", "So11111111111111111111111111111111111111112"]}}}, Currency: {MintAddress: {is: $token}}}, Transaction: {Result: {Success: true}}} limit: {count: 1} ) { Trade { Price_24h_ago: PriceInUSD( minimum: Block_Slot if: {Block: {Time: {since_relative: {hours_ago: 24}}}} ) Price_7d_ago: PriceInUSD( minimum: Block_Slot if: {Block: {Time: {since_relative: {days_ago: 7}}}} ) Price_30d_ago: PriceInUSD( minimum: Block_Slot if: {Block: {Time: {since_relative: {days_ago: 30}}}} ) CurrentPrice: PriceInUSD(maximum: Block_Slot) } change24hr: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_24h_ago) / $Trade_Price_24h_ago) * 100" ) change7d: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_7d_ago) / $Trade_Price_7d_ago) * 100" ) change30d: calculate( expression: "(($Trade_CurrentPrice - $Trade_Price_30d_ago) / $Trade_Price_30d_ago) * 100" ) aATH: quantile(of: Trade_PriceInUSD, level: 0.95) Block { Time } } } } ``` Variables: ```json { "token": "2tnA2ZmwmgUZLyYLi97zbwsFBXAqpMEcHu9Cv9JW6m26" } ``` ## Get First 100 buyers of a Token [This](https://ide.bitquery.io/first-100-buyer-of-a-token) API returns the first 100 buyers for a particular token. ```graphql { Solana(dataset: archive) { DEXTradeByTokens( orderBy: { ascending: Block_Time } limit: { count: 100 } limitBy: { count: 1, by: Trade_Account_Owner } where: { Block: { Date: { since: "2025-07-13", till: "2025-07-14" } } Trade: { Side: { Type: { is: sell } } Currency: { MintAddress: { is: "pumpeALaQHVP7mCdjmhFkAnesZj3vXMJhD4rFffYDfn" } } } } ) { Trade { Account { Owner } } } } } ``` The window is the token's launch day. Scanning from an arbitrary earlier date makes the request time out, so find the first trade date first (`Block { Time(minimum: Block_Time) }` on the same cube) and bound the window to it. ## Get ATH of Multiple Tokens You can run it [here](https://ide.bitquery.io/ATH-of-multiple-tokens-quantile-Solana) ```graphql { Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { in: ["token mint address-1", "token mint address-2"] } } } } limit: { count: 2 } orderBy: { descendingByField: "aATH" } limitBy: { by: Trade_Currency_MintAddress, count: 1 } ) { Trade { Currency { Name } } aATH: quantile(of: Trade_PriceInUSD, level: 0.99) } } } ``` ## Get ATH Market Cap of Tokens This query returns the ATH (All-Time High) market cap, starting market cap, and related price metrics for multiple tokens. It calculates market cap using a 1 billion token supply and uses quantile to find the ATH price. You can run it [here](https://ide.bitquery.io/Marketcap-of-tokens) ```graphql query GetAthMarketCap($tokens: [String!]!) { Solana(dataset: archive) { DEXTradeByTokens( limitBy: { by: Trade_Side_Currency_MintAddress, count: 1 } where: { Trade: { Currency: { MintAddress: { in: $tokens } } } } ) { Trade { Currency { MintAddress Name Symbol } PriceInUSD(maximum: Trade_PriceInUSD) Starting_Price: PriceInUSD(minimum: Block_Slot) Side { Currency { Name Symbol MintAddress } } } max: quantile(of: Trade_PriceInUSD, level: 0.98) quantile_price_ATH_Marketcap: calculate(expression: "$max * 1000000000") Real_maximum_price_ATH_Marketcap: calculate( expression: "$Trade_PriceInUSD_maximum * 1000000000" ) Starting_Marketcap: calculate( expression: "$Trade_Starting_Price * 1000000000" ) } } } ``` ```json { "tokens": ["8SAwv8EKMKaKnupTsYjoQdgBuWxJdo3ouA178UU7pump"] } ``` ## Realised PnL, avg buy price, buy volume, sell volume Get realised PnL, average buy price, buy volume, and sell volume for a token on Solana of a trader trader for over a time window. [Run in Bitquery IDE](https://ide.bitquery.io/Realised-Pnl-avg-buy-price-Buy-volume-Sell-Volume-Solana_2) ```graphql { Solana(dataset: archive) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "4iLKj7fkZF2rSpgSD8W6UFq4fkKXkkbJMGXMz3B8pump" } } Account: { Owner: { is: "2vqBfRdhX8sHmVFo1TY1yBdFXkHMe4LgifrxvHBpXUAK" } } Dex: { ProtocolName: { notIn: ["jupiter", "dex_solana_v3"] } } } Transaction: { Result: { Success: true } } Block: { Date: { since: "2026-03-11", till: "2026-03-13" } } } ) { Trade { Currency { Name Symbol MintAddress } Account { Owner } } buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) buy_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) buy_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) sell_volume_usd: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) buy_volume: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: buy } } } } ) sell_volume: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) RealizedPnL: calculate(expression: "$sell_volume_usd - $buy_volume_usd") trades: count avg_buy_price: calculate(expression: "$buy_volume_usd / $buy_volume") } } } ``` ## How far back does Bitquery's Solana historical data go on Solana? Bitquery **V2** **historical aggregates** on this page (for example **`Solana(dataset: archive)`** / **`combined`** with **`DEXTradeByTokens`**) are available from **1 June 2024** forward for the supported aggregate APIs. That is **not** full ledger genesis history. Individual trades are on **`DEXTrades`** with `archive` or `combined`, being backfilled toward 2024. For **SPL transfers and older history**, use the **[V1 Solana examples](https://docs.bitquery.io/v1/docs/Examples/Solana/transfers)**. For bulk or older history, ask about a [Data Store export](https://bitquery.io/datastore). Other chains mostly have archive history from genesis for the core cubes, but depth varies by chain and cube: see the [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/). ## What fields are available in Solana DEXTradeByTokens with dataset: combined? **`Solana(dataset: archive)`** (and **`combined`**, which adds the realtime tail) **`DEXTradeByTokens`** supports **aggregate-friendly** fields: **time / intervals**, **amounts**, **prices**, **trade counts**, **`Trade.Currency`**, **`Trade.Side.Currency`**, **`Dex`**, pool/market identifiers, and similar columns shown in the examples below. **Fine-grained per-account fields** on the trade side (e.g. **`Trade Side Account`**-style projections) are often **unsupported**: the API returns “columns not available.” **Add fields one at a time** in the IDE and rely on the live schema. See [combined vs realtime on Solana](/docs/graphql/dataset/combined#why-does-dataset-combined-return-fewer-fields-than-dataset-realtime-on-solana) and [Pump.fun combined note](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#why-does-my-pumpfun-query-return-columns-not-available-in-combined-dataset). ## CoinGecko OHLC compared with Bitquery | | CoinGecko coin OHLC endpoint | Bitquery | |---|---|---| | Scope | Coins listed on CoinGecko, by coin id (chart endpoints also accept a token address) | Any Solana mint or pair, listed or not | | Candle size | Automatic: 30 minutes for 1 to 2 days, 4 hours for 3 to 30 days, 4 days beyond; daily and hourly intervals on paid plans over fixed ranges | Any interval in seconds, minutes, hours or days | | History | The range you pass in the `days` parameter | Aggregates from 1 June 2024, per-trade rows for about 30 days, transfers to genesis on V1 | | Fields | Open, high, low, close | Open, high, low, close, volume, trade count, plus any aggregate you add (makers, buys, sells) | | Access | API key header | Access token; `archive` and `combined` aggregates need a Solana archive pack (the trial is real-time only) | ## Related pages - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades) - [Solana OHLC API and second-level candles](/docs/blockchain/Solana/solana-dextrades#solana-ohlc-api) - [Trading API: crypto price and OHLC](/docs/trading/crypto-price-api/) - [DEXScreener-style pair data for Solana](/docs/blockchain/Solana/DEXScreener/solana_dexscreener/) - [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [Solana Data Store exports](/docs/cloud/solana) - [Data coverage and retention](/docs/graphql/data-coverage-retention) ## Video Tutorial for Querying Historical Solana Data --- ## Solana Instructions API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-instructions/ Solana instructions: latest calls, new tokens on PumpFun, Raydium Launchpad, Meteora DBC and more, Metaplex metadata, buy events and token burns. # Solana Instructions API ## Overview The **Solana Instructions API** provides comprehensive access to decoded instruction data executed on the Solana blockchain. This API enables you to track real-time instructions, monitor token creation and burning events, and analyze program interactions with detailed information including signer details, transaction signatures, balance updates, and program metadata. ## 📋 Table of Contents - **[Latest Solana Instructions](#latest-solana-instructions)** - Real-time instruction monitoring - **[Latest Created Tokens on Solana](#latest-created-tokens-on-solana)** - Token creation tracking - **[Newly launched tokens (PumpFun, Raydium, Meteora, Heaven, Bags, Jupiter, Moonit)](#newly-launched-tokens-on-pumpfun-raydium-launchpad-meteora-dbc-heaven-dex-bags-jupiter-studio-moonit)** - Multi-launchpad token launches - **[Track Real-time Token Burn on Solana](#track-real-time-token-burn-on-solana)** - Token burn monitoring - **[Video Tutorials](#video-tutorials)** - Step-by-step guides ## 🔗 Related APIs - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor real-time balance changes - **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** - Track token supply and creation events - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Monitor trading activities across DEXs - **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** - Track token transfers and movements - **[Solana Fees API](/docs/blockchain/Solana/solana_fees_api/)** - Analyze transaction fees and costs --- ## Latest Solana Instructions The subscription below fetches the latest instructions executed on the Solana blockchain, including details like indices of preceding instructions, signer information, transaction signatures, balance updates, and program details. For monitoring the balance changes that result from these instructions, see our **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)**. You can run the query [here](https://ide.bitquery.io/Latest-Solana-Instructions) ```graphql subscription { Solana(network: solana) { Instructions { Transaction { Signer Signature Result { Success ErrorMessage } Index } Instruction { Logs BalanceUpdatesCount AncestorIndexes TokenBalanceUpdatesCount Program { Name Method } } Block { Time Hash } } } } ``` --- ## Latest Created Tokens on Solana The query below fetches the latest created tokens on the Solana blockchain, including details like newly created token addresses (which appear as the first entry in the Accounts array). We are querying the Solana Token Program with address `TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA` and filtering for the latest created tokens using `Method: {in: ["initializeMint", "initializeMint2", "initializeMint3"]}`. You can run the query [here](https://ide.bitquery.io/Get-newly-created-tokens-on-Solana0_3) ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" } Method: { in: ["initializeMint", "initializeMint2", "initializeMint3"] } } } Transaction: { Result: { Success: true } } } ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address } } Transaction { Signature Signer } } } } ``` ## Newly launched tokens on PumpFun, Raydium Launchpad, Meteora DBC, Heaven DEX, Bags, Jupiter studio, Moonit Subscribe to newly launched tokens across multiple Solana launchpads and DEXs in a single subscription. The query filters for successful token-creation instructions from **PumpFun** (`create` / `create_v2`), **Raydium Launchpad** (`initialize_v2`), **Meteora DBC** (`initialize_virtual_pool_with_spl_token`), **Heaven DEX** (`create_standard_liquidity_pool`), **Bags** (Meteora DBC with Bags program), **Jupiter studio** (Meteora DBC with `jups` account), and **Moonit** (`tokenMint`). [Run in Bitquery IDE](https://ide.bitquery.io/newly-launched-token-on-PumpFun-Raydium-Launchpad-Meteora-DBC-Heaven-DEX-Bags--Jupiter-studio-Moonit) ```graphql subscription { Solana { Instructions( where: { Transaction: { Result: { Success: true } } any: [ { Instruction: { Program: { Method: { in: ["create", "create_v2"] }, Address: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } } } } { Instruction: { Program: { Address: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" }, Method: { is: "initialize_v2" } } } } { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" }, Method: { is: "initialize_virtual_pool_with_spl_token" } } } } { Instruction: { Program: { Address: { is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o" }, Method: { is: "create_standard_liquidity_pool" } } } } { Instruction: { Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" }, Method: { is: "initialize_virtual_pool_with_spl_token" } }, Accounts: { includes: { Address: { is: "BAGSB9TpGrZxQbEsrEznv5jXXdwyP6AXerN8aVRiAmcv" } } } } } { Instruction: { Accounts: { includes: { Address: { endsWith: "jups" } } }, Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" }, Method: { is: "initialize_virtual_pool_with_spl_token" } } } } { Instruction: { Program: { Address: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" }, Method: { is: "tokenMint" } } } } ] } ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } Transaction { Signature } } } } ``` --- ## Get Token Metadata using Metaplex of Newly Created Tokens This query retrieves metadata for newly created tokens on Solana using the Metaplex program. The metadata is returned is the **JSON** field, which includes fields such as name, symbol, uri, and more. You can run the query [here](https://ide.bitquery.io/Get-newly-created-token-metadata-on-Solana) You can also add the keyword `subscription` and track it in real-time. ```graphql { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"}, Method: {is: "CreateMetadataAccountV3"}}}, Transaction: {Result: {Success: true}}} limit: {count: 10} orderBy: {descending: Block_Slot} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Name Method } Data } Transaction { Signature Signer } } } } ``` ## Number of Latest Created Tokens on Solana The query below fetches the count of the latest created tokens on the Solana blockchain which were created using `initializeMint` method. You can run the query [here](https://ide.bitquery.io/Count---Tokens-created-on-Solana) ```graphql query MyQuery { Solana(dataset: realtime, network: solana) { Instructions( where: {Instruction: {Program: {Address: {is: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}, Method: {is: "initializeMint"}}}} limit: {count: 10} ) { count Block { latest: Time(maximum: Block_Time) oldest: Time(minimum: Block_Time) } } } } ``` ## Get Buyevent instruction details Use the below query to get the `BuyEvent` instruction details. Test the query [here](https://ide.bitquery.io/BuyEvent). ```graphql subscription { Solana { Instructions(where: { Instruction: { Program: { Method: { is: "BuyEvent" } } } }) { Transaction { Signature } Instruction { Program { Method Name Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` --- ## Track Real-time Token Burn on Solana Receive real-time updates on token burn events on the Solana blockchain. The query below applies a filter to only include instructions where the Program Method includes `burn`, indicating that we filter instructions related specifically to token burning. You can run it [here](https://ide.bitquery.io/track-solana-token-burn-in-realtime_1) ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Method: { is: "burn" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Name Method } Logs } Transaction { Signature Signer } } } } ``` ### Latest token burns on Solana The query below fetches the latest token burn instructions on Solana by filtering for the **Token Program** (`TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`) where the method includes `burn`. The **second address in the `Accounts` list is the token address being burnt**. You can run the query [here](https://ide.bitquery.io/Latest-token-burns-on-Solana#). ```graphql { Solana(network: solana) { Instructions( where: { Instruction: { Program: { Method: { includes: "burn" } Address: { is: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" } } } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Instruction { Program { Method Name Address } Accounts { Address } Index BalanceUpdatesCount } Transaction { Signature } Block { Time Slot } } } } ``` ### Balance updates for token burn instructions The query below uses the **InstructionBalanceUpdates** API to fetch balance updates that occur when token burn instructions execute. It filters for the Token Program (`TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`) where the method includes `burn`, and returns balance deltas (Amount, PreBalance, PostBalance), currency details, and account info for each update. You can run the query [here](https://ide.bitquery.io/solana-balance-updates-executing-burn-instruction). ```graphql { Solana { InstructionBalanceUpdates( limit: { count: 20 } where: { Transaction: {} Instruction: { Program: { Method: { includesCaseInsensitive: "burn" } Address: { is: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" } } } } orderBy: { descending: Block_Time } ) { BalanceUpdate { Account { Address Owner } Amount Currency { Name Symbol MintAddress Decimals } Index AmountInUSD PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } Instruction { Program { Method Address } } Transaction { Signature FeePayer } Block { Time Height } } } } ``` ### Alternative: Token Burn Tracking via TokenSupplyUpdates API You can also track real-time token burn using the TokenSupplyUpdates API. Check out the [following example](https://ide.bitquery.io/token-burn-example-solana). For more comprehensive token supply tracking, see our **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** documentation. ```graphql { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { Amount: { lt: "0" } } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { TokenSupplyUpdate { Currency { Name Symbol MintAddress Decimals } Amount AmountInUSD PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD Account { Address Owner Token { Owner } } } Block { Time Height } Instruction { Program { Address Method } } Transaction { Signature } } } } ``` --- ## Video Tutorials ### How to Track New Liquidity Pools Created on Solana Raydium & Orca DEX ### How to Get Newly Created Tokens on Solana Blockchain in Real-time ``` ``` --- ## Solana Instructions Balance Updates API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-instruction-balance-updates/ Solana Instructions Balance Updates API: fetch current and historical Solana balances with Bitquery GraphQL balance queries. # Solana Instructions Balance Updates API This cube attaches balance changes to the instruction that caused them. That makes it the practical way to answer **"which currency moved, and how much"** for any program: the raw `Instructions` cube returns account addresses and raw integers, while this one returns `Currency` with symbol and decimals, a signed decimal `Amount`, and `AmountInUSD`. ## Latest Solana Instructions Balance Updates The query below gives you balance update associated with a instruction invocation. You can run the query [here](https://ide.bitquery.io/balance-updates) ```graphql query { Solana(dataset: realtime) { InstructionBalanceUpdates(limit: {count: 10}) { BalanceUpdate { Amount Currency { MintAddress Name } PreBalance PostBalance } } } } ``` ## Latest liquidity locks on Streamflow Using the below query, you can retrieve latest liquidity locks made using streamflow. Test the query [here](https://ide.bitquery.io/Liquidity-lock-using-instructions-balance-update) ```graphql { Solana { InstructionBalanceUpdates(limit: {count: 20} where:{ BalanceUpdate:{ Currency:{ Native:false } Amount:{gt:"0"} } Instruction:{ Program:{ Method:{is:"create"} Address:{is:"strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m"} } } } ) { BalanceUpdate { Account { Address Owner } Amount Currency { Name Symbol MintAddress Decimals } Index Amount AmountInUSD PreBalance PreBalanceInUSD PostBalance PostBalanceInUSD } Instruction { Program { Method Address } } Transaction { Signature FeePayer } Block { Time Height } } } } ``` ## Stream balance updates for one program :::caution This cube requires a filter when streaming `InstructionBalanceUpdates` carries every balance change on Solana. An unfiltered subscription is dropped by the server with `close code 1013 — client is not consuming messages fast enough`. Always scope it to a program, token or account. See [which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/). ::: Filtering by program gives you a live, currency-resolved feed of everything that program moves. The example below streams Jupiter Z RFQ fills; swap the address for the program you care about. ```graphql subscription ProgramBalanceUpdates { Solana { InstructionBalanceUpdates( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } } } BalanceUpdate: { Currency: { Native: false } } } ) { Block { Time } Transaction { Signature } BalanceUpdate { Amount AmountInUSD Currency { Symbol MintAddress Decimals } Account { Address Token { Owner } } } } } } ``` Negative `Amount` is the sender's leg, positive is the receiver's. `Account.Token.Owner` tells you which wallet each leg belongs to. :::note Native SOL legs `Currency: { Native: false }` keeps the SPL token legs and drops lamport noise. When one side of a trade is native SOL, that side disappears from the results. Remove the filter to catch it, but expect a native SOL leg to emit both a lamport movement and a WSOL token update for the same value, so do not sum them. ::: --- ## Solana Jito Bundle API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-Jito-Bundle-api/ Jito bundles on Solana: track transfers to the Jito tip payment accounts and list the methods used by the Jito Merkle Upload Authority, with transfer details. # Jito Bundle API :::tip Need real-time Jito bundle data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Jito bundle swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Jito bundle data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section, we will show you how to access information about Jito Bundles using Bitquery APIs. ## Transfers to the Tip Payment Accounts Jito foundation has Tip Payment Program that allows users to transfer tips to a set of static public keys (compared to signing the transaction with the next N leaders) and ensure that the incentives are distributed to the correct block leader, while enabling bundles to execute in upto 8 parallel threads. The subscription that provides you the transfer data of one of these addresses is [writen below](https://ide.bitquery.io/Transfers-of-Tip-Payment-Accounts-on-Solana_1#). To get the data of all addresses you can use the [this](https://ide.bitquery.io/Transfers-of-All-Tip-Payment-Accounts-on-Solana) query. ```graphql subscription { Solana { Recieved: Transfers( where: { Transfer: { Receiver: { Address: { is: "HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe" } } } } ) { Transfer { Currency { Name Symbol MintAddress } AmountInUSD Sender { Address } } Transaction { Signature } Block { Time Slot } } } } ``` ## List of methods for Jito Merkle Upload Authority Jito Merkle Upload Autjority account is the block builder that uploads the root of Merkle tree created by processing the MEV data in an offchain setting. The [below query](https://ide.bitquery.io/All-Methods-for-Jito-Bundles-on-Solana_1) returns all the methods that are accessible to this account. ```graphql { Solana { Instructions( where: { Transaction: { Signer: { is: "GZctHpWXmsZC1YHACTGGcHhYxjdRqQvTpYkb9LMvxDib" } } } ) { Instruction { Program { Address Method Name } } count } } } ``` ## More information on Transfer Method From the above query, we'll get a list of methods that the account is signing. One of those method is "Transfer". To get more info on the "Tranfer" method we can run the query given [below](https://ide.bitquery.io/Transfer-Function-Call-Event-Alert-for-Jito-Bundles-on-Solana_1). ```graphql { Solana { Instructions( limit: { count: 10 } where: { Transaction: { Signer: { is: "GZctHpWXmsZC1YHACTGGcHhYxjdRqQvTpYkb9LMvxDib" } Result: { Success: true } } Instruction: { Program: { Method: { is: "Transfer" } } } } ) { Instruction { Program { Address Method Name Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } Block { Slot Time } Transaction { Signature } } } } ``` --- ## Solana Jupiter API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-jupiter-api/ Solana Jupiter API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Includes filters and field selection tips. # Solana Jupiter API - Live Swaps, Limit Orders, DEX Aggregator Data :::tip Need real-time Jupiter data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Jupiter swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Jupiter data older than ~30 days**, raw per-swap detail, or call / event context. ::: Get ultra low latency Jupiter DEX Aggregator swaps, limit orders, routing data, and trading analytics from Jupiter API, Streams and Data Dumps. The below GraphQL APIs and Streams are examples of data points you can get with Bitquery. If you have any question on other data points reach out to [support](https://t.me/Bloxy_info) Need zero-latency Jupiter data? [Read about our Shred Streams and Contact us for a Trial](/docs/streams/real-time-solana-data/). You may also be interested in: - [Pump.fun APIs ➤](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [Raydium APIs ➤](/docs/blockchain/Solana/Solana-Raydium-DEX-API/) - [Orca APIs ➤](/docs/blockchain/Solana/solana-orca-dex-api/) - [Serum APIs ➤](/docs/blockchain/Solana/Solana-OpenBook-api/) - [Solana RFQ API ➤](/docs/blockchain/Solana/solana-rfq-api/): Jupiter Z (`order_engine`) fills, which are in DEX trade data from 29 September 2026, and Jupiter Limit Order v2, which is not :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ### Table of Contents ### 1. Jupiter Swaps & Trading Data - [Track Latest Swaps on Jupiter ➤](#track-latest-swaps-on-jupiter) - [Monitor Jupiter Swap Activity ➤](#monitor-jupiter-swap-activity) ### 2. Jupiter Limit Orders - [Track Latest Created Limit Orders ➤](#track-latest-created-limit-orders-on-jupiter) - [Monitor Cancel Limit Orders ➤](#track-latest-cancel-limit-order-transactions-on-jupiter) - [Track Cancel Expired Orders ➤](#track-latest-cancel-expired-limit-order-transactions-on-jupiter) ### 3. [Video Tutorials](#video-tutorials) ## Jupiter Swaps & Trading Data ### Track Latest Swaps on Jupiter Get real-time Jupiter aggregator swap data including tokens involved, routing paths, and account details. We monitor Jupiter's program address `JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4` for `sharedAccountsRoute` instructions to track swap activity. The query returns tokens involved in swaps, source and destination addresses, and routing information. [Jupiter Latest Swaps — Stream ➤](https://ide.bitquery.io/Tokens-involved-in-Jupiter-swap-source-address-destination-address-DEX-involved_2#)
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4" } Method: { is: "sharedAccountsRoute" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Instruction { Program { Method AccountNames Address } Accounts { Address IsWritable Token { Mint Owner ProgramId } } } } } } ```
### Monitor Jupiter Swap Activity Track comprehensive Jupiter swap data including token details, account information, and routing paths for advanced analytics.
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4" } Method: { is: "sharedAccountsRoute" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Instruction { Program { Method AccountNames Address } Accounts { Address IsWritable Token { Mint Owner ProgramId } } } } } } ```
## Jupiter Limit Orders ### Track Latest Created Limit Orders on Jupiter This stream shows each new Jupiter limit order as it is created, with its tokens and maker address. The query filters Jupiter's order program `jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu` for `initializeOrder` calls. The query returns input/output mint addresses, maker addresses, reserve addresses, and order configuration details. [Jupiter Limit Order Creation — Stream ➤](https://ide.bitquery.io/Latest-created-Limit-Order-on-Jupiter-in-realtime#)
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Method: { is: "initializeOrder" } Address: { is: "jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes BalanceUpdatesCount CallPath CallerIndex Data Depth ExternalSeqNumber InternalSeqNumber Index Logs Program { AccountNames Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } Block { Time } } } } ```
### Track Latest Cancel Limit Order Transactions on Jupiter Each cancelled order streams in with its maker and the tokens involved. The query uses the same program, `jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu`, filtered to `cancelOrder` calls. The query returns input mint addresses, maker addresses, reserve addresses, and cancellation details. [Jupiter Limit Order Cancellation — Stream ➤](https://ide.bitquery.io/Latest-Cancel-Limit-Order-Transactions-on-Jupiter-in-realtime#)
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Method: { is: "cancelOrder" } Address: { is: "jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes BalanceUpdatesCount CallPath CallerIndex Data Depth ExternalSeqNumber InternalSeqNumber Index Logs Program { AccountNames Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } Block { Time } } } } ```
### Track Latest Cancel Expired Limit Order Transactions on Jupiter Orders closed after they expired show up here, with the transaction and its accounts. This time the filter is `cancelExpiredOrder`. The query returns transaction signatures, account details, and program arguments for expired order cancellations. [Jupiter Expired Order Cancellation — Stream ➤](https://ide.bitquery.io/Latest-Cancel-Expired-Order-Transactions-on-Jupiter-in-realtime_1#)
Click to expand GraphQL query ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Method: { is: "cancelExpiredOrder" } Address: { is: "jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } AncestorIndexes BalanceUpdatesCount CallPath CallerIndex Data Depth ExternalSeqNumber InternalSeqNumber Index Logs Program { AccountNames Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } } } Block { Time } } } } ```
## Video Tutorials ### Video Tutorial | How to Track Swaps on Jupiter Aggregator on Solana in Realtime ### Video Tutorial | How to Track Jupiter Limit Order Creation and Cancellation --- ## Solana Jupiter Studio API URL: https://docs.bitquery.io/docs/blockchain/Solana/jupiter-studio-api/ Solana Jupiter Studio API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Covers archive history and realtime data. # Jupiter Studio API - Live Token Launches, Trades, OHLC, Migration Data :::tip Need real-time Jupiter Studio data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Jupiter Studio data older than ~30 days**, raw per-swap detail, or call / event context. ::: Get ultra low latency Jupiter Studio launchpad data, token trades, OHLC, migration tracking, and Meteora DBC analytics from Jupiter Studio API, Streams and Data Dumps. The examples below cover launches, trading activity, migration events and Meteora Dynamic Bonding Curve data. The below GraphQL APIs and Streams are examples of data points you can get with Bitquery. If you have any question on other data points reach out to [support](https://t.me/Bloxy_info) Need zero-latency Jupiter Studio data? [Read about our Shred Streams and Contact us for a Trial](/docs/streams/real-time-solana-data/). You may also be interested in: - [Jupiter API ➤](/docs/blockchain/Solana/solana-jupiter-api/) - [Pump.fun APIs ➤](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) - [Meteora APIs ➤](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) - [Raydium APIs ➤](/docs/blockchain/Solana/Solana-Raydium-DEX-API/) :::note Launches here are created and traded on Meteora DBC, so each one follows the lifecycle of a Meteora DBC mint. ::: :::caution Launches here are sparse Meteora DBC is busy, but most of that flow comes from other launchpads. Very few "jups" mints trade in a given week, so the realtime examples below return rows only while one is actively trading, and the per-trade price queries need a mint that traded in the last day or so. For anything older, read `dataset: archive` as the volume example does, or take the last 30 days from the [Trading cube](/docs/trading/crypto-trades-api/trades-api/). The example mints on this page are kept because they show the shape of the data; swap in a current mint before expecting live rows. ::: :::note To query or stream data via graphQL **outside the Bitquery IDE**, you need to generate an API access token. Follow the steps here to create one: [How to generate Bitquery API token ➤](/docs/authorization/how-to-generate/) ::: --- ### Table of Contents ### 1. Jupiter Studio Trading & Market Data - [Track trades in real time ➤](#track-trades-in-real-time) - [Get the latest price ➤](#get-the-latest-price) - [OHLC candles ➤](#ohlc-candles) - [Get Trading Volume & Analytics ➤](#get-trading-volume--analytics) ### 2. Launches and migration - [Track the latest launches ➤](#track-the-latest-launches-on-meteora-dbc) - [Monitor migrations ➤](#monitor-migrations) - [Check migration status ➤](#check-migration-status) ### 3. Jupiter Studio Trader Insights - [Get the top traders ➤](#get-the-top-traders) ## Jupiter Studio Trading & Market Data ### Track trades in real time This streams every fill on Meteora's Dynamic Bonding Curve as it confirms, with both sides of the trade, the accounts involved and the transaction. Launches from this platform end in "jups" and trade on the Meteora DBC program `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN`. The query returns detailed trade information including currency details, amounts, prices, and account addresses. [Stream these trades ➤](https://ide.bitquery.io/trades-of-jup-studio-tokens-on-meteora-dbc-in-realtime)
Click to expand GraphQL query ```graphql subscription { Solana { DEXTrades( where: { any: [ { Trade: { Buy: { Currency: { MintAddress: { endsWith: "jups" } } } } } { Trade: { Sell: { Currency: { MintAddress: { endsWith: "jups" } } } } } ] Trade: { Dex: { ProgramAddress: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ```
### Track the latest launches on Meteora DBC Monitor real-time Jupiter Studio token pool creations on Meteora Dynamic Bonding Curve with comprehensive launch details including token metadata, creator addresses, and pool configuration. We track Meteora DBC program address `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` for `initialize_virtual_pool_with_spl_token` instructions. The query returns token details, account information, program arguments, and transaction specifics for new Jupiter Studio token launches. [Stream new launches ➤](https://ide.bitquery.io/jup-studio-token-creations-on-meteora-DBC)
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { Instructions( where: { Instruction: { Accounts:{includes:{Address:{endsWith:"jups"}}} Program: { Address: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } Method: { is: "initialize_virtual_pool_with_spl_token" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } ```
## Launches and migration ### Monitor migrations Track real-time Jupiter Studio token migrations from Meteora Dynamic Bonding Curve to Meteora DEX with comprehensive migration details and transaction information. We monitor Meteora DBC program address `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` for migration instructions including `migrate_meteora_damm` and `migration_damm_v2`. The query returns token details, account information, and migration transaction specifics for Jupiter Studio tokens. [Stream migrations ➤](https://ide.bitquery.io/jup-studio-token-migrations-from-Meteora-DBC-to-Meteors-DEX_1)
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { Instructions( where: {Instruction: {Accounts: {includes: {Address: {endsWith: "jups"}}}, Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["migrate_meteora_damm", "migration_damm_v2"]}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } ```
### Check migration status Check if specific Jupiter Studio tokens have migrated from Meteora DBC to Meteora DEX with detailed migration history and transaction information. [Check migration status ➤](https://ide.bitquery.io/Check-if-these-jup-tokens-tokens-have-migrated-from-Meteora-DBC)
Click to expand GraphQL query ```graphql query MyQuery($tokenAddresses: [String!]) { Solana { Instructions( orderBy:{descending:Block_Time} where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["migrate_meteora_damm", "migration_damm_v2"]}}, Accounts: {includes: {Address: {in: $tokenAddresses}}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Accounts { Token { ProgramId Owner Mint } IsWritable Address } Program { Parsed Name Method Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } Type Name } Address AccountNames } } Transaction { Fee FeeInUSD FeePayer Signature } } } } { "tokenAddresses":["CEVuiDHBxUeuuwvLugKqZpRpNtv5ejaQ1wKm2qzyjups","3Po3offygJjPg4cQpvc1AVT9JsYXyUapN2EKgFUbjups"] } ```
### Get the latest price Get the most recent price data for a specific Jupiter Studio token trading on Meteora Dynamic Bonding Curve with comprehensive price information. [Run the latest-price query ➤](https://ide.bitquery.io/latest-price-of-a-jup-studio-token-on-meteora-dbc)
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}}, Currency: {MintAddress: {is: "3Po3offygJjPg4cQpvc1AVT9JsYXyUapN2EKgFUbjups"}}}} ) { Block { Time } Trade { Price PriceInUSD Currency{ Name Symbol MintAddress } } } } } ```
### OHLC candles Get comprehensive OHLC (Open, High, Low, Close) data for Jupiter Studio tokens trading on Meteora DBC with volume analysis and price movement insights. :::note Use this API as a query only, not as a subscription websocket, as aggregates and time intervals don't work well with subscriptions. ::: [Run the OHLC query ➤](https://ide.bitquery.io/Jupiter-studio-OHLC-API)
Click to expand GraphQL query ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "3Po3offygJjPg4cQpvc1AVT9JsYXyUapN2EKgFUbjups"}}, Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}, Dex: {ProgramAddress: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ```
### Get Trading Volume & Analytics This sums traded, buy and sell volume for a Jupiter Studio token on Meteora's bonding curve. It reads the `archive` dataset, because the example window predates the roughly seven days the chain-level `realtime` slice keeps. Note that Solana `archive` and `combined` return about a fifth fewer trades than `realtime` over a window both cover, so treat these totals as a floor, and read the last 30 days from the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) when they have to be exact. [Run the volume query ➤](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-jup-studio-token)
Click to expand GraphQL query ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( where: {Block: {Time: {since: "2025-07-18T09:00:00Z", till: "2025-07-19T00:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "3Po3offygJjPg4cQpvc1AVT9JsYXyUapN2EKgFUbjups"}}, Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}, Dex: {ProgramAddress: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}}}} ) { Trade { Currency { MintAddress Decimals } Side { Currency { Name MintAddress } } } traded_volume_USD: sum(of: Trade_Side_AmountInUSD) traded_volume: sum(of: Trade_Amount) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) } } } ```
## Jupiter Studio Trader Insights ### Get the top traders Get comprehensive trader analytics for Jupiter Studio tokens including top traders by volume, buy/sell activity, and USD trading volume rankings. :::note Use this API as a query only, not as a subscription websocket, because aggregates don't work with subscriptions and will return incorrect results. ::: [Run the top-traders query ➤](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-jup-studio-Token-on-Meteora-DBC)
Click to expand GraphQL query ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProgramAddress: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ```json { "token": "3Po3offygJjPg4cQpvc1AVT9JsYXyUapN2EKgFUbjups" } ```
--- ## Solana Launchpad Creator Fees API: Meteora DBC and Raydium LaunchLab URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-launchpad-creator-fees-api/ Creator and launchpad fee claims on Solana: Meteora DBC (Bags, Jupiter Studio, Believe) and Raydium LaunchLab (LetsBonk), with top earners and creator changes. # Solana Launchpad Creator Fees API: Meteora DBC and Raydium LaunchLab Most Solana launchpads other than Pump.fun run on one of two shared programs. Meteora's Dynamic Bonding Curve (DBC), `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN`, powers launchpads such as Bags, Jupiter Studio and Believe. Raydium LaunchLab, `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj`, powers LetsBonk. On both, every trade on the bonding curve pays fees that are split between the coin's creator and the launchpad (the "partner" on DBC, the "platform" on LaunchLab), and each side claims its share later. This page reads those claims from the chain: what creators claimed, what launchpads claimed, who earned the most, and when a coin's creator changed. For Pump.fun's own creator fees, see the [Pump.fun Creator Rewards API](/docs/blockchain/Solana/Pumpfun/pump-fun-creator-rewards-api/). For trades and launches on these launchpads, see [Meteora DBC](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/), [Bags](/docs/blockchain/Solana/bags-fm-api/), [Jupiter Studio](/docs/blockchain/Solana/jupiter-studio-api/), [Believe](/docs/blockchain/Solana/Believe-API/), [Raydium LaunchLab](/docs/blockchain/Solana/launchpad-raydium/) and [LetsBonk](/docs/blockchain/Solana/letsbonk-api/). All queries run in the [Bitquery IDE](https://ide.bitquery.io) on the real-time dataset, which keeps about 12 hours of Solana instructions. To stream one, change `query` to `subscription` and remove `limit` and `orderBy`. | What | Program | Instruction | Event and fields | | --- | --- | --- | --- | | Creator claims fees | Meteora DBC | `claim_creator_trading_fee`, `claim_creator_trading_fee2` | `EvtClaimCreatorTradingFee`: `pool`, `token_base_amount`, `token_quote_amount` | | Launchpad claims fees | Meteora DBC | `claim_trading_fee`, `claim_trading_fee2` | `EvtClaimTradingFee`: `pool`, `token_base_amount`, `token_quote_amount` | | Launchpad claims pool-creation fee | Meteora DBC | `claim_partner_pool_creation_fee` | `EvtPartnerClaimPoolCreationFee`: `pool`, `partner`, `creation_fee`, `fee_receiver` | | Creator changed | Meteora DBC | `transfer_pool_creator` | `EvtUpdatePoolCreator`: `pool`, `creator`, `new_creator` | | Creator claims fees | Raydium LaunchLab | `claim_creator_fee` | balance updates | | Launchpad claims fees | Raydium LaunchLab | `claim_platform_fee_from_vault` | balance updates | Event arguments carry raw amounts in each token's smallest unit: `token_base_amount` is in the launched coin, `token_quote_amount` in the quote token (SOL has 9 decimals). Balance updates carry decimal amounts and USD. ## Meteora DBC: creator fee claims [Run it in the IDE ➤](https://ide.bitquery.io/DBC-creator-trading-fee-claims) ```graphql query DbcCreatorFeeClaims { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {is: "EvtClaimCreatorTradingFee"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` ## Meteora DBC: launchpad (partner) fee claims The launchpad that owns the pool's config claims its share with `claim_trading_fee`. The signer is usually the launchpad's fee wallet. [Run it in the IDE ➤](https://ide.bitquery.io/DBC-partner-trading-fee-claims) ```graphql query DbcPartnerFeeClaims { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {is: "EvtClaimTradingFee"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` ## Meteora DBC: pool-creation fees claimed by launchpads [Run it in the IDE ➤](https://ide.bitquery.io/DBC-partner-pool-creation-fees) ```graphql query DbcPoolCreationFees { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {is: "EvtPartnerClaimPoolCreationFee"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` ## Meteora DBC: top wallets by creator fees claimed Ranks receiving accounts by creator fees claimed in the real-time window. For SOL the account is the wallet; for SPL tokens it is a token account and `Token.Owner` is the wallet. [Run it in the IDE ➤](https://ide.bitquery.io/DBC-top-creators-by-fees-claimed) ```graphql query DbcTopCreators { Solana { InstructionBalanceUpdates( limit: {count: 20} orderBy: {descendingByField: "claimed_usd"} where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["claim_creator_trading_fee", "claim_creator_trading_fee2"]}}}, BalanceUpdate: {Amount: {gt: "0"}}, Transaction: {Result: {Success: true}}} ) { BalanceUpdate { Account { Address Token { Owner } } Currency { Symbol MintAddress } } claims: count claimed: sum(of: BalanceUpdate_Amount) claimed_usd: sum(of: BalanceUpdate_AmountInUSD) } } } ``` ## Meteora DBC: creator changes `transfer_pool_creator` hands a pool's creator rights, and its future creator fees, to a new wallet. Launchpads use it too; on Bags, for example, the new creator can be a Bags address. [Run it in the IDE ➤](https://ide.bitquery.io/DBC-pool-creator-changes) ```graphql query DbcCreatorChanges { Solana { Instructions( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {is: "EvtUpdatePoolCreator"}}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` ## Raydium LaunchLab: creator fee claims Each row is the creator's wallet receiving its claimed fee. [Run it in the IDE ➤](https://ide.bitquery.io/LaunchLab-creator-fee-claims) ```graphql query LaunchLabCreatorFeeClaims { Solana { InstructionBalanceUpdates( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["claim_creator_fee"]}}}, BalanceUpdate: {Amount: {gt: "0"}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } BalanceUpdate { Account { Address Token { Owner } } Amount AmountInUSD Currency { Symbol MintAddress } } } } } ``` ## Raydium LaunchLab: launchpad (platform) fee claims The platform that launched the coin, such as LetsBonk, claims its share from the fee vault with `claim_platform_fee_from_vault`. [Run it in the IDE ➤](https://ide.bitquery.io/LaunchLab-platform-fee-claims) ```graphql query LaunchLabPlatformFeeClaims { Solana { InstructionBalanceUpdates( limit: {count: 20} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["claim_platform_fee_from_vault"]}}}, BalanceUpdate: {Amount: {gt: "0"}}, Transaction: {Result: {Success: true}}} ) { Block { Time } Transaction { Signature Signer } BalanceUpdate { Account { Address Token { Owner } } Amount AmountInUSD Currency { Symbol MintAddress } } } } } ``` ## Raydium LaunchLab: top creators by fees claimed [Run it in the IDE ➤](https://ide.bitquery.io/LaunchLab-top-creators-by-fees-claimed) ```graphql query LaunchLabTopCreators { Solana { InstructionBalanceUpdates( limit: {count: 20} orderBy: {descendingByField: "claimed_usd"} where: {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["claim_creator_fee"]}}}, BalanceUpdate: {Amount: {gt: "0"}}, Transaction: {Result: {Success: true}}} ) { BalanceUpdate { Account { Address Token { Owner } } Currency { Symbol MintAddress } } claims: count claimed: sum(of: BalanceUpdate_Amount) claimed_usd: sum(of: BalanceUpdate_AmountInUSD) } } } ``` ## Pitfalls - **About 12 hours of history.** `Instructions` and `InstructionBalanceUpdates` on Solana are real-time only. For lifetime earnings, store a subscription or read the [Solana Kafka streams](/docs/streams/kafka-streaming-concepts/). - **Two DBC instruction versions.** Claims arrive as `claim_creator_trading_fee` and `claim_creator_trading_fee2`, and `claim_trading_fee` and `claim_trading_fee2`. Query both. - **Base and quote side.** DBC fees can be paid in the launched coin (`token_base_amount`) as well as in the quote token. Add both when you total a claim. - **The creator can change.** After `transfer_pool_creator` the new wallet claims the fees, so a creator's history may sit under two wallets. --- ## Solana Lifinity DEX API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-Lifinity-dex-api/ Query Lifinity on Solana with Bitquery GraphQL: real-time trades, latest token prices, OHLC candles and the top traders of any token on the DEX. # Lifinity DEX API :::tip Need real-time Lifinity data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Lifinity swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Lifinity data older than ~30 days**, raw per-swap detail, or call / event context. Lifinity trades ship as part of the [Solana DEX API](https://bitquery.io/products/solana-dex-api), one schema across all major Solana venues. ::: :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## Lifinity Trades in Real-Time This streams a message for every new trade on the venue, carrying the buy and sell sides, the block and the transaction. You can run the query [here](https://ide.bitquery.io/Real-time-trades-on-Lifinity-DEX-on-Solana_4) ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Lifinity" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ``` ## Latest Price of a Token on Lifinity This returns the most recent trade for a token here, with the price in the quote token and in USD. Open it in the [Bitquery IDE: latest token price](https://ide.bitquery.io/live-price-of-token-on-lifinity). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolFamily: {is: "Lifinity"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Lifinity OHLC API If you want to get OHLC data for any specific currency pair on Lifinity, you can use this api. Only use [this API](https://ide.bitquery.io/Lifinity-OHLC-for-specific-pair_1) as query and not subscription websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProtocolFamily: {is: "Lifinity"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get the Top Traders of a specific Token on Lifinity DEX This ranks the wallets trading one token on the venue, USDC in the example. Run it as a plain request rather than a WebSocket subscription, because aggregates are recomputed per message on a subscription and the totals come back wrong. Open it in the [Bitquery IDE: top traders on Lifinity](https://ide.bitquery.io/top-traders-of-a-token-on-lifinity) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProtocolFamily: {is: "Lifinity"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", } ``` ## Get trading volume, buy volume, sell volume of a token This sums traded, buy and sell volume for a token on the venue. It reads the `archive` dataset because this program's trading is historical rather than current; run the latest-trade query above to see how recent the newest row is. Solana `archive` and `combined` return about a fifth fewer trades than `realtime` over a window both cover, so treat these totals as a floor. Open it in the [Bitquery IDE: trade volume](https://ide.bitquery.io/trade_volume_lifinity). ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( where: {Block: {Time: {since: "2025-03-10T07:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProtocolFamily: {is: "Lifinity"}}}} ) { Trade { Currency { MintAddress Decimals } Side { Currency { Name MintAddress } } } traded_volume_USD: sum(of: Trade_Side_AmountInUSD) traded_volume: sum(of: Trade_Amount) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) } } } ``` ## Volatility of a Pair on Lifinity Volatility is an important factor in trading world as it determines the fluctuation in price that implies the possibility of profit and risk of loss. Lesser volatility denotes that the pair is stable. Open the [Bitquery IDE: pair volatility](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-Lifinity-Dex-on-Solana) to read volatility for a pair over the last 24 hours. ```graphql query Volatility { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Lifinity" } } Buy: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Sell: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Block: { Time: { after: "2025-03-18T00:00:00Z" } } } ) { volatility: standard_deviation(of: Trade_Buy_Price) } } } ``` --- ## Solana Liquidity Pool Price API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-pool-price/ Solana liquidity pool price API: the price every Raydium, Orca, Meteora, pump.fun and PumpSwap pool quotes after each event, with fields, live queries, candles and pitfalls. # Solana Liquidity Pool Price API ## What it is Every Solana DEX pool event carries the pool's **own price after the event**. It is the price the pool quotes for the next tiny trade, read from the venue's own state. It is not the price the swap that produced the row paid; the two differ by that swap's price impact and fee. It also differs from the [Crypto Price API](/docs/trading/crypto-price-api/price-index-algorithm). That price blends recent trades across all of a token's pools. A pool price belongs to one pool and changes on every swap or liquidity change in it. ## How to get it | Delivery | Where | | --- | --- | | GraphQL | `Solana { DEXPools { Pool { Price { Price PriceInUSD Source } } } }` on `https://streaming.bitquery.io/graphql`, in queries and subscriptions. Filterable, orderable (`Pool_Price_Price`, `Pool_Price_PriceInUSD`) and aggregatable | | Kafka | `solana.dextrades.proto`, `PoolEvents[].Price` (`PoolPrice` message, field 7, `streaming_protobuf v2.6.6`). See [Solana protobuf](/docs/streams/protobuf/chains/Solana-protobuf#poolliquiditychangeevent) | Prices exist from 2026-10-23. `DEXPools` is served from the realtime dataset, so GraphQL history covers the last few hours. ## How it is derived A pool event gives a sqrt price, curve reserves or vault balances; each becomes quote per base with decimals applied, then the pool price Every venue reduces to one ratio: raw quote units per raw base unit after the event, `r`. Decimals are then applied so the price reads in whole tokens: ``` Price = r × 10^(base decimals − quote decimals) PriceInUSD = Price × USD rate of the quote token at that block ``` Base and quote are the row's `Market.BaseCurrency` and `Market.QuoteCurrency`. Where the venue stores the price the other way round, `r` is inverted. ### Concentrated pools: from the sqrt price {#concentrated-pools} Raydium CLMM, PancakeSwap CLMM, Orca Whirlpool, Meteora DAMM v2 and Meteora DBC report the pool's square-root price after the swap in their swap event, as a Q64.64 number. ``` r = (sqrtPriceX64 / 2^64)^2 token1 per token0, inverted when the base is token1 ``` The event fields are `sqrt_price_x64` on Raydium and PancakeSwap CLMM `SwapEvent`, `post_sqrt_price` on Whirlpool `Traded`, and the post-swap sqrt price on Meteora `EvtSwap` / `EvtSwap2`. `Source` is `event`. ### Bonding curves: from virtual reserves {#bonding-curves} | Venue | `r` | Event | | --- | --- | --- | | pump.fun | `virtual_sol_reserves / virtual_token_reserves` | `TradeEvent` | | Raydium Launchpad | `(virtual_quote + real_quote_after) / (virtual_base − real_base_after)` | `TradeEvent` | `Source` is `event`. ### Constant-product pools: from vault balances {#constant-product-pools} ``` r = quote vault balance / base vault balance after the event ``` PumpSwap and Raydium v4 use the vault balances on the row (`Source: reserves`). Raydium CPMM takes them from its swap event, as the balances before the swap plus the amount in and minus the amount out (`Source: event`). Its fee-collection rows fall back to the vault balances (`Source: reserves`). We checked each formula on 2026-10-26 against the raw event data of live rows on every venue above. `Price` matched to within 0.002 %. ### Rows without a price {#rows-without-a-price} - pump.fun curves in **mayhem mode**. The program does not trade them at their reported reserves, so every row of such a curve is unpriced. This was about a fifth of active curves when we checked. - pump.fun migrations, where the curve is emptied. The new PumpSwap pool's creation row has the price. - Fee claims and collections, Raydium CLMM limit-order instructions, and the liquidity changes of Whirlpool and DAMM v2. These do not move a concentrated pool's price, so keep the pool's last priced row. - Meteora DLMM, Meteora Pools (DAMM v1), and venues whose rows come only from vault balances (BisonFi, Manifest, GoonFi, Byreal, AlphaQ, Aquifer, SolFi, Bonkswap and others). ## Fields | Field | Type | Meaning | | --- | --- | --- | | `Pool.Price.Price` | Float | Quote per base in whole tokens, oriented as `Market.BaseCurrency` / `Market.QuoteCurrency` | | `Pool.Price.PriceInUSD` | Float | `Price` × the quote token's USD rate at that block. `0` when the quote has no rate | | `Pool.Price.Source` | String | `event` (read from the venue's event) or `reserves` (vault balances). Empty when the row has no price | A row without a price has `0`, `0` and `""` in GraphQL and a nil `Price` in protobuf. Treat an empty `Source` as "no price", never as a price of zero. ## Examples ### Latest price of a pool [Run query](https://ide.bitquery.io/Solana-pool-latest-price)
Click to expand GraphQL query ```graphql query SolanaPoolLatestPrice { Solana { DEXPools( limit: { count: 1 } orderBy: { descending: Block_Slot } where: { Pool: { Market: { MarketAddress: { is: "2AXXcN6oN9bBT5owwmTH53C7QHUXvhLeu718Kqt8rvY2" } } Price: { Source: { not: "" } } } } ) { Block { Slot Time } Pool { Market { MarketAddress BaseCurrency { Symbol } QuoteCurrency { Symbol } } Dex { ProtocolName ProtocolFamily } Price { Price PriceInUSD Source } Base { PostAmountInUSD } Quote { PostAmountInUSD } } } } } ```
### Live pool prices of a token Every pool where WSOL is the base, as each pool event lands. `Quote.PostAmountInUSD` shows the liquidity behind each price. [Run query](https://ide.bitquery.io/Solana-pool-prices-of-token-stream)
Click to expand GraphQL query ```graphql subscription SolanaPoolPricesOfToken { Solana { DEXPools( where: { Pool: { Market: { BaseCurrency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Price: { Source: { not: "" } } } Transaction: { Result: { Success: true } } } ) { Block { Slot Time } PoolEvent { Index } Pool { Market { MarketAddress QuoteCurrency { Symbol } } Dex { ProtocolName } Price { Price PriceInUSD Source } Quote { PostAmountInUSD } } } } } ```
### Price history of a pool over the last hour [Run query](https://ide.bitquery.io/Solana-pool-price-history-last-hour)
Click to expand GraphQL query ```graphql query SolanaPoolPriceHistory { Solana { DEXPools( orderBy: { ascending: Block_Slot } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pool: { Market: { MarketAddress: { is: "2AXXcN6oN9bBT5owwmTH53C7QHUXvhLeu718Kqt8rvY2" } } Price: { Source: { not: "" } } } } ) { Block { Slot Time } Pool { Price { Price PriceInUSD } } } } } ```
### Open, high, low and close of a pool's price `Price(minimum: Block_Slot)` is the first price in the window and `Price(maximum: Block_Slot)` the last. [Run query](https://ide.bitquery.io/Solana-pool-price-open-high-low-close)
Click to expand GraphQL query ```graphql query SolanaPoolPriceStats { Solana { DEXPools( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pool: { Market: { MarketAddress: { is: "2AXXcN6oN9bBT5owwmTH53C7QHUXvhLeu718Kqt8rvY2" } } Price: { Source: { not: "" } } } } ) { Pool { Market { MarketAddress } Price { open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) high: Price(maximum: Pool_Price_Price) low: Price(minimum: Pool_Price_Price) } } average: average(of: Pool_Price_Price) updates: count } } } ```
### Highest-priced pools with real liquidity Order by `Pool_Price_PriceInUSD` only with a liquidity floor; without one, drained pools fill the list. [Run query](https://ide.bitquery.io/Solana-highest-priced-pools-with-liquidity)
Click to expand GraphQL query ```graphql query SolanaHighestPricedPoolsWithLiquidity { Solana { DEXPools( limit: { count: 10 } limitBy: { by: Pool_Market_MarketAddress, count: 1 } orderBy: { descending: Pool_Price_PriceInUSD } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pool: { Price: { Source: { is: "event" }, PriceInUSD: { ge: 1 } } Quote: { PostAmountInUSD: { gt: "10000" } } } } ) { Block { Time } Pool { Market { MarketAddress BaseCurrency { Symbol } QuoteCurrency { Symbol } } Dex { ProtocolName } Price { Price PriceInUSD Source } Quote { PostAmountInUSD } } } } } ```
## Pitfalls - **Not the trade price.** For a swap, the pool price sits on the far side of the executed price: above it after a buy of the base, below it after a sell. On CLMM, Whirlpool, Raydium v4, CPMM, DBC, pump.fun and PancakeSwap, 94–100 % of swap rows were within 3 % of the trade when we checked. Use [DEXTradeByTokens](/docs/blockchain/Solana/solana-dextrades) for executed prices. - **PumpSwap is the vault ratio.** Some PumpSwap pools trade well away from it: boosted pools by a few percent, and we have seen gaps of 15–50 %. For what a trader pays, use DEXTradeByTokens. - **Drained pools.** A pool with dust left on one side reports prices like `1e-18` or `2e17`. A concentrated pool drained to the edge of its range can report the edge value (`2^64` or `2^-64` after decimals). Filter on `Base.PostAmountInUSD` / `Quote.PostAmountInUSD` first. - **Use it per market.** Never average prices across pools. Very large or very small prices are often genuine for tokens with huge or tiny supplies, so weigh each pool by its liquidity. - **`Pool.Base.Price` is a different number.** `Pool { Base { Price } }` and `Pool { Quote { Price } }` are the ratio of the row's vault balances. They match `Pool { Price }` only on constant-product pools. - **Check USD by mint.** Many tokens share a symbol. Compare `PriceInUSD` per `MintAddress`. - **Precision.** `Price` and `PriceInUSD` are 32-bit floats, about 7 significant digits. - **Recent history only.** For price history beyond the last few hours, use [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs). ## Related - [Solana DEX Pools API](/docs/blockchain/Solana/Solana-DexPools-API) for liquidity, reserves and pool events - [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades) for executed prices - [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) for one price per token across pools - [Solana protobuf](/docs/streams/protobuf/chains/Solana-protobuf) for the Kafka message --- ## Solana Logs API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-logs/ Solana logs: find instructions by matching log messages, filter them with like and not-like conditions, and search program logs for a keyword via GraphQL. # Solana Logs API Solana Logs API helps you filter program instruction logs using regular expressions. ## Finding Instructions with Log Matching The Solana Logs API allows you to search for specific instructions based on log content that matches exact phrases. For example, to find logs related to 'AnchorError' with a specific error code and message You can find the query [here](https://ide.bitquery.io/SlippageToleranceExceeded#) ```graphql { Solana { Instructions( limit: {count: 1} where: {Instruction: {Logs: {includes: {is: "Program log: AnchorError occurred. Error Code: SlippageToleranceExceeded. Error Number: 6001. Error Message: Slippage tolerance exceeded."}}}} ) { Instruction { Accounts { Address } Data Index Logs ExternalSeqNumber Program { Json AccountNames Method Name Arguments { Name Type } } Index } Transaction { Result { ErrorMessage } } } } } ``` ## Filtering Instructions using Not Like Filter To exclude instructions containing specific log phrases such as 'AnchorError' you can use the `notLike` filter. You can find the query [here](https://ide.bitquery.io/Not-Anchor-Error-Solana-Logs) ```graphql { Solana { Instructions( limit: {count: 1} where: {Instruction: {Logs: {includes: {notLike: "Program log: AnchorError occurred."}}}} ) { Instruction { Accounts { Address } Data Index Logs ExternalSeqNumber Program { Json AccountNames Method Name Arguments { Name Type } } Index } Transaction { Result { ErrorMessage } } } } } ``` ## Finding Instructions using Like Filter To find instructions based on logs that contain specific patterns or keywords, such as an invoke log, you can use the `like` filter. ```graphql { Solana { Instructions( limit: {count: 1} where: {Instruction: {Logs: {includes: {like: "Program Vote111111111111111111111111111111111111111 invoke [1]"}}}} ) { Instruction { Accounts { Address } Data Index Logs ExternalSeqNumber Program { Json AccountNames Method Name Arguments { Name Type } } Index } Transaction { Result { ErrorMessage } } } } } ``` ## Searching Logs using a Particular Keyword To find instructions based on logs that contain specific patterns or keywords, such as an ZETA market log, you can use the `includes` filter which searches for the presence of the keyword as a whole in the log. You can run the query [here](https://ide.bitquery.io/Solana-Zeta-Market-logs) ```graphql { Solana { Instructions( where: {Instruction: {Logs: {includes: {includes: "ZETA"}}}} limit: {count: 10} ) { Transaction { Signature } Instruction { Logs } } } } ``` --- ## Solana MCP Server for Claude, ChatGPT and Cursor URL: https://docs.bitquery.io/docs/mcp/solana/ Ask Claude, ChatGPT or Cursor about Solana in plain English: trending tokens, pump.fun launches, first buyers, token prices and where a wallet sent its SOL. Read-only, from on-chain data. # Solana MCP Server The Bitquery MCP server lets an AI client answer questions about Solana trading and money movement. You ask in Claude, ChatGPT, Cursor, VS Code or Codex, the agent picks a tool, and rows come back from Bitquery's index of Solana DEX trades and transfers. It reads data only. It cannot sign or send a transaction, and it does not hold keys. If you want an MCP that helps you write Solana programs, that is the Solana Foundation's developer MCP; this one is for market and wallet research. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Other clients take the same URL. Steps for each are in the [MCP server install guide](/docs/mcp/mcp-server/). The same server also covers other chains, [Polymarket](/docs/mcp/polymarket/) and the [Hyperliquid exchange](/docs/mcp/hyperliquid/) (perpetuals and spot markets). Every figure on this page came from a call to the production server on 21 September 2026, between 10:19 and 10:25 UTC. Solana moves fast, so your numbers will differ. ## What can I ask? ### What is trading most on Solana today? > *"What are the most traded tokens on Solana in the last 24 hours?"* The agent calls `trending_tokens` with the chain set to Solana. | # | Symbol | Token address | 24h volume | 24h price change | |---|---|---|---:|---:| | 1 | USDT | `USD2Ttdo...CdTho` | $986,660,608 | -0.68% | | 2 | SОL | `SoJh2C73...4GhTC` | $952,089,984 | -0.11% | | 3 | WSOL | `So111111...11112` | $822,212,759 | +7.09% | | 4 | USDC | `EPjFWdd5...TDt1v` | $128,175,125 | -0.01% | Rows 5 to 8 were four small tokens up between 4,618% and 11,241% on $70 million to $119 million of volume each. Wrapped SOL went from $108.00 to $115.66. Look at rows 1 and 2 again. Neither address is the real one. Tether's Solana address starts `Es9vMF`, and the "SОL" in row 2 is spelled with a Cyrillic letter. The next question shows how to catch that. ### Is that volume real? > *"Where does the token USD2Ttdovnui8b6YG3NFreErgiNJv34UwritmRCdTho trade, and how many wallets trade it?"* `token_dex_venues`, grouped by protocol: | Token | Trades | Wallets | Trading span | Reported volume | |---|---:|---:|---|---:| | "USDT" `USD2Ttdo...` | 5 | 2 | 9 minutes | $986,660,663 | | "SОL" `SoJh2C73...` | 58 | 3 | 16 hours | $952,090,033 | Both trade on one venue only, Orca Whirlpool, and the first token's nine minutes fell on 20 September. Five trades between two wallets produced a reported $987 million. The answer also lists what each token was swapped for, and the two counterfeits were swapped for each other. A handful of swaps of made-up size printed a dollar figure that nobody paid. On the second token the tool also sets `Symbol_NonAscii` to 1, its flag for look-alike letters. Two habits follow. Give the agent a token address, because a symbol is not unique on Solana. And before you trust a volume figure, ask how many wallets stood behind it. ### What launched on pump.fun in the last six hours? > *"Show new pump.fun tokens from the last 6 hours, ranked by volume."* `new_tokens` with the address pattern `%pump`, which matches pump.fun token addresses. | Token | Age | Volume | Valuation now | Fall from peak | |---|---:|---:|---:|---:| | BABYJEAN | 3.3 h | $1,855,343 | $3,483 | -99.64% | | SCRIBJEAN | 5.3 h | $1,822,028 | $2,391 | -99.70% | | JEANGREY | 1.3 h | $1,791,345 | $2,761 | -99.66% | | JEANGRINO | 4.3 h | $1,422,407 | $2,444 | -99.66% | | JeanJaks | 4.3 h | $1,249,362 | $2,664 | -98.80% | All five share a name theme, and all five had already lost at least 98.8% from their peak price. BABYJEAN peaked at a valuation of $427,193 before falling to $3,483. Valuation here is price times total supply, which the tool labels FDV. The peak and the fall come back in the same row so the agent can tell a live launch from one that is over. ### How did one of those launches go? > *"How did the BABYJEAN launch go in its first 60 seconds?"* `token_launch_stats` with a 60-second window returns one row, shown here on its side: | Measure | First 60 seconds | |---|---:| | First trade | 07:50:43 UTC | | Trades | 340 (225 buys, 115 sells) | | Wallets | 109 | | Wallets in the first block | 3 | | Wallets in the first 10 seconds | 31 | | Bought | $23,925 | | Sold | $12,646 | The same answer lists the 20 largest wallets of that minute. Two things stand out. Four wallets each made a single buy of $2,061 to $2,371 at the same instant, 1.2 seconds after the first trade. And the largest wallet of the minute, `3e1hq8LB...Cctm`, bought nothing in the window and sold $8,648 across 19 trades, starting at 14.8 seconds. ### Who got in first? > *"Who were the first buyers of BABYJEAN?"* `early_buyers`, sorted by arrival: | Wallet | Seconds after launch | Bought | Sold | Result inside the minute | |---|---:|---:|---:|---:| | `LfEcaUf7...a9Uw` | 0 | $55.33 | $57.36 | +$2.03 | | `GePaAUXD...Xjft` | 0 | $341.88 | $377.51 | +$35.63 | | `F7LqQscx...YwmE` | 0 | $289.84 | $193.43 | -$96.41, still holding | | `8N4QDR8m...kZoc` | 1 | $0.01 | $0 | -$0.01 | | `9FVZMzqS...zhcz` | 1 | $22.01 | $23.88 | +$1.87 | | `3xezief4...B69T` | 2 | $23.40 | $20.95 | -$2.45 | Arriving in the first second did not pay much here. The best of the six made $35.63. ### Where did the seller's money go? > *"Where did 3e1hq8LBpHmEQqwTp5ADrUbgWtN4coBBsN3Y3NRRCctm send its SOL?"* Two calls. `solana_address_profile` says the wallet sent 65 transfers to 7 receivers in 30 days and received 61 from 3 senders, so it is a small wallet and not an exchange. `solana_trace_next_hop`, pinned to native SOL, ranks where the money went: | Receiver | SOL | Time (UTC) | Label | |---|---:|---|---| | `3S5A2dpJ...GwqN` | 70.53 | 07:51:58 | none | | `3repxLH4...uxWQ` | 65.28 | 07:52:29 | none | | `34YJ1Xkd...XHYv` | 58.23 | 07:51:34 | none | | `iWnj1DuR...s2Ek` | 52.57 | 07:53:05 | none | | `FWZdfwbs...LeRK` | 22.06 | 07:52:42 | none | That is 268.68 SOL to five unlabeled wallets, all between 51 and 142 seconds after the token's first trade. A trace stops when a receiver carries a label such as an exchange. None did here, so the next step would be the same call on each receiver. One gap: `solana_transfers_in` returned no rows for this token on this wallet, so the transfer data does not say how the wallet got the tokens it sold. ## Tools that cover Solana Ten tools are Solana-only and carry the `solana_` prefix: | Tool | Use it for | |---|---| | `solana_address_profile` | Counts of transfers and counterparties, to size up a wallet before tracing | | `solana_address_flow_summary` | Totals in and out per token | | `solana_transfers_in` | Incoming transfers, newest or largest first, with sender labels | | `solana_transfers_out` | Outgoing transfers | | `solana_trace_next_hop` | Receivers of a wallet's funds, ranked and labeled | | `solana_flow_edges` | Wallet-to-wallet edges for a graph | | `solana_tx_transfers` | Every transfer inside one transaction | | `solana_signatures` | Every transaction an address took part in, newest first, with paging into old history | | `solana_find_instructions` | Search by program and instruction name | | `solana_transfers_raw_sql` | Your own SQL over the transfer tables | The market tools take a `blockchain` argument and work on Solana and eight other chains: | Tools | Use them for | |---|---| | `trending_tokens`, `new_tokens` | What is hot, and what just launched | | `find_tokens`, `find_token_by_address` | Turn a name or an address into a token | | `token_price`, `token_ohlcv`, `token_trade_bars`, `token_supply` | Price, candles down to 1 second, supply | | `token_dex_venues`, `pool_recent_trades`, `tx_trades` | Pools, venues and single swaps | | `token_launch_stats`, `early_buyers` | The first seconds of a launch | | `top_traders_by_token`, `profitable_traders_by_token`, `accumulating_traders_by_token` | Rank the wallets trading one token | | `trader_profile`, `trader_activity`, `trader_positions` | One wallet's trading record | | `address_labels`, `labels_for_addresses` | Exchange, bridge and scam labels | ## What to know before you rely on it - **Read-only.** No signing, no sending, no account state. For those you need a Solana RPC node. - **Check the token address.** Counterfeit tokens copy names and symbols, and one topped the volume ranking on the day this page was written. - **Dollar volume can be fake.** Ask for the number of trades and wallets before quoting a figure. - **Trade history is about 30 days.** A launch older than that is anchored at the start of the history, and the tool sets `Launch_May_Predate_History` to say so. - **Transfer tools default to 90 days.** Raise `days` to look further back. An empty answer can mean the window ended. - **Transfer amounts are in token units.** There is no dollar value on a transfer, so totals of different tokens cannot be added. - **No program logs.** Search programs with `solana_find_instructions`. Decoded events and token-holder lists are not available for Solana. ## MCP, GraphQL or an RPC node? | You want to | Use | |---|---| | Send transactions or read account state | A Solana RPC node | | Get help writing Solana programs | The Solana Foundation's developer MCP | | Ask questions in a chat, or let an agent research tokens and wallets | This MCP server | | Build a bot, dashboard or alert in code | The [Bitquery Solana API](/docs/blockchain/Solana/) and the [pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/), with WebSocket and Kafka streams | | Load full history into a warehouse | [Solana Data Store exports](/docs/cloud/solana/) | For a longer worked example, see the [pump.fun launch pulse](/docs/mcp/trading/examples/pumpfun-launch-pulse/). Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-solana#pricing). --- ## Solana Moonshot API URL: https://docs.bitquery.io/docs/blockchain/Solana/Moonshot-API/ Solana Moonshot API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Copy GraphQL snippets for production apps. # Moonit API :::tip Need real-time Moonit data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Moonit data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section we will see how to get real-time data on Moonit trades, transactions and wallet updates. Similarly you can get Pump.fun data from the [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) :::note `Trade Side Account` field will not be available as aggregates in Archive and Combined Datasets ::: ## Moonit Trades in Real-Time The below query gets real-time information whenever there's a new trade on the Moonshot including program method called , buy and sell details, details of the currencies involved, and the transaction specifics like signature. You can run the query [here](https://ide.bitquery.io/Moonshot-DEX-Trades_2) ```graphql subscription MyQuery { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Moonshot" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Program { Method } } Trade { Dex { ProtocolFamily ProtocolName } Buy { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } Sell { Amount Account { Address } Currency { Name Symbol MintAddress Decimals Fungible Uri } } } Transaction { Signature } } } } ``` ## Get newly created Moonit tokens and their Metadata Now you can track the newly created Moonit Tokens along with their metadata and supply. `PostBalance` will give you the current supply for the token. Check the query [here](https://ide.bitquery.io/Get-newly-created-Moonshot-tokens-with-metadata#) ```graphql subscription { Solana { TokenSupplyUpdates( where: { Instruction: { Program: { Address: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } Method: { is: "tokenMint" } } } } ) { TokenSupplyUpdate { Amount Currency { Symbol ProgramAddress PrimarySaleHappened Native Name MintAddress MetadataAddress Key IsMutable Fungible EditionNonce Decimals Wrapped VerifiedCollection Uri UpdateAuthority TokenStandard } PostBalance } } } } ``` ## Track New Token Creation on Moonit [Here](https://ide.bitquery.io/Track-new-token-launches-on-Moonshot-in-realtime) is the subscription to get the notification of new token creation event on Moonit. Newly Minted Token Address will be 4th address in the Accounts array. You can also see the Name, Symbol, Supply and URI of the newly minted token in the arguments. ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Method: { is: "tokenMint" } Address: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } Transaction { Signature } } } } ``` ## Get all the instructions of Moonit Below query will get you all the instructions that the Moonit Program has. You can test the API [here](https://ide.bitquery.io/instruction-invocation-count-in-last-10-hours). ```graphql query MyQuery { Solana { Instructions( where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Address: {is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG"}}}} ) { Instruction { Program { Method } } count } } } ``` ## Track Moonit Token Migrations to Raydium or Meteora in Realtime Using above `get all instructions` api, you will figure out that there is a instruction `migrate` whose invocations migrate the Moonit Token to Raydium and Meteora Dexs respectively. Thats why we have filtered for these 2 instructions in the below API, and tracking these. Test out the API [here](https://ide.bitquery.io/Track-Moonit-Token-Migrations-to-Raydium-and-Meteora-in-realtime). ```graphql subscription MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG"}, Method: {is: "migrateFunds"}}}, Transaction: {Result: {Success: true}}} ) { Block{ Time } Instruction { Program { Method AccountNames Address Arguments { Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } } Type Name } Name } Accounts { Address IsWritable Token { ProgramId Owner Mint } } } Transaction { Signature Signer } } } } ``` ## Track Moonit, LetsBonk.fun, Raydium Launchlab, Boop.fun and Meteora DBC Token Migrations in a single subscription Use this single subscription to stream real-time token migration events across Boop.fun, Raydium Launchlab, Meteora DBC, and Moonshot/Moonit. It filters by the respective program IDs and migration methods, returning block time, program details, involved accounts, and transaction signatures as events occur. Try out the [API](https://ide.bitquery.io/Raydium-Launchlab-Meteora-DBC-BoopFun-Moonshot-LetsBonkfun-token-migrations-in-realtime_2) here on IDE. ```graphql subscription{ Solana { Instructions( where: {any: [{Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {is: "initialize_v2"}}}}, {Instruction: {Program: {Address: {is: "boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4"}, Method: {is: "graduate"}}}}, {Instruction: {Program: {Address: {is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG"}, Method: {is: "migrateFunds"}}}}, {Instruction: {Program: {Address: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}, Method: {in: ["migrate_meteora_damm", "migration_damm_v2"]}}}}, {Instruction: {Program: {Address: {is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"}, Method: {in: ["migrate_to_amm", "migrate_to_cpswap"]}}, Accounts: {includes: {Address: {is: "FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1"}}}}}], Transaction: {Result: {Success: true}}} ) { Block { Time } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Launchlab # boop8hVGQGqehUK2iVEMEnMrL5RbjywRzHKBmBE7ry4 - boop.fun # MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG - Moonshot/Moonit # dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN - Meteora DBC # LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj - Program Address and FfYek5vEz23cMkWsdJwG2oa6EphsvXSHrGpdALN4g6W1(letsbonk.fun platform config addr) is present in Accounts array then its Letsbonk.fun migration Address Arguments { Name Type Value { ... on Solana_ABI_Integer_Value_Arg { integer } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Json_Value_Arg { json } } } Method Name } } Transaction { Signature Signer } } } } ``` ## Track New Token Creation on Multiple Platforms : Moonit and Pumpfun In this query we use the program addresses of Moonit and Pumpfun and creation methods to track token creation in realtime. We use the `in` filter to pass multiple addresses. You can run the query [here](https://ide.bitquery.io/new-token-launches-on-Pump-Fun--Moonshot-in-realtime) ```graphql subscription { Solana(network: solana) { Instructions( where: { Instruction: { Program: { Method: { in: ["tokenMint", "create"] } Address: { in: [ "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" ] } } } } ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Logs Program { AccountNames Address Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } Method Name } } Transaction { Signature } } } } ``` ## Get the Creator of a Moonit Token The below query fetches the details of Token Creator of a specific token `D68YAXPZdGEBre4Esg61W7HbcRJFN7rmroKzGPXDR87T`. Here you can find [saved query](https://ide.bitquery.io/Moonshot-token-creator). ```graphql query MyQuery { Solana(network: solana) { Instructions( where: { Instruction: { Accounts: { includes: { Address: { is: "token mint address" } } } Program: { Address: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } Method: { is: "tokenMint" } } } } ) { Transaction { Signer Signature } Instruction { Accounts { Address } } } } } ``` ## Top Token Creators on Moonit The below query fetches details about token creators filtering using the `MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG` program address and `tokenMint` method. The `descendingByField: "tokens_count":` Orders the results in descending order based on the count of tokens created. You can run the query [here](https://ide.bitquery.io/Top-Moonshot-token-creators) ```graphql query MyQuery { Solana(network: solana) { Instructions( where: { Instruction: { Program: { Address: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } Method: { is: "tokenMint" } } } } orderBy: { descendingByField: "tokens_count" } ) { tokens_count: count Transaction { Signer } } } } ``` ## Get OHLC Data of a Token on Moonit The below query gets OHLC data of the specified Token `A1XqfcD1vMEhUNwEKvBVRWFV48ZLDL4oheFVCPEcM3Vk` for 1 minute time interval for last 10 minutes on Moonit DEX. You can run the query [here](https://ide.bitquery.io/OHLC-for-a-token-on-Moonshot_1) Note - You can only use this API using `query` keyword, using this API as `subscription` will give wrong results because aggregation and interval don't work correctly together in `subscription`. ```graphql { Solana { DEXTradeByTokens( limit: { count: 10 } orderBy: { descendingByField: "Block_Timefield" } where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Dex: { ProgramAddress: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } } PriceAsymmetry: { lt: 0.1 } } } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Track Price of a Token in Realtime on Moonit The below query gets real-time price of the specified Token `A1XqfcD1vMEhUNwEKvBVRWFV48ZLDL4oheFVCPEcM3Vk` on the Moonit DEX. You can run the query [here](https://ide.bitquery.io/Price-of-a-Moonshot-token) ```graphql subscription MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProgramAddress: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } } Currency: { MintAddress: { is: "token mint address" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Currency { MintAddress Name Symbol } Dex { ProtocolName ProtocolFamily ProgramAddress } Side { Currency { MintAddress Symbol Name } } Price PriceInUSD } Transaction { Signature } } } } ``` ## Get the Token Holders of a specific Moonit Token The below query gets top 10 token holders of the specified Token `A1XqfcD1vMEhUNwEKvBVRWFV48ZLDL4oheFVCPEcM3Vk` on the Moonit DEX. Keep in mind you can use this API only as a query and not a subscription websocket because aggregates don't work with subscription and you will end up getting wrong results. You can run the query [here](https://ide.bitquery.io/Top-10-holders-for-a-Moonshot-token) ```graphql query MyQuery { Solana { BalanceUpdates( limit: { count: 10 } orderBy: { descendingByField: "TotalHolding" } where: { BalanceUpdate: { Currency: { MintAddress: { is: "token mint address" } } } } ) { BalanceUpdate { Currency { Name MintAddress Symbol } Account { Address Token { Owner } } } TotalHolding: sum(of: BalanceUpdate_Amount, selectWhere: { gt: "0" }) } } } ``` ## Get the Trading Volume of a specific Token on Moonit DEX The below query gets the Trading volume of the specified Token `A1XqfcD1vMEhUNwEKvBVRWFV48ZLDL4oheFVCPEcM3Vk` on the Moonit DEX in the past 1 hour. You will have to change the time in this `Block: {Time: {since: "2024-08-13T08:05:00Z"}}` when you try the query yourself. Keep in mind you can use this API only as a query and not a subscription websocket because aggregates don't work with subscription and you will end up getting wrong results. You can run the query [here](https://ide.bitquery.io/trading-volume-of-a-token-Moonshot_1) ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Dex: { ProgramAddress: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } } } Block: { Time: { since: "2024-08-13T08:05:00Z" } } Transaction: { Result: { Success: true } } } ) { Trade { Currency { Name Symbol MintAddress } Dex { ProtocolName ProtocolFamily } Side { Currency { Name Symbol MintAddress } } } TradeVolume: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Get the Top Traders of a specific Token on Moonit DEX The below query gets the Top Traders of the specified Token `A1XqfcD1vMEhUNwEKvBVRWFV48ZLDL4oheFVCPEcM3Vk` which was launched on Moonit. Keep in mind you can use this API only as a query and not a subscription websocket because aggregates don't work with subscription and you will end up getting wrong results. You can run the query [here](https://ide.bitquery.io/Top-traders-with-their-bought-sold-and-total-volume_3) ```graphql query TopTraders { Solana { DEXTradeByTokens( orderBy: { descendingByField: "volume" } limit: { count: 5 } where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Dex: { ProgramAddress: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } } } Transaction: { Result: { Success: true } } } ) { Trade { Dex { ProtocolName ProtocolFamily ProgramAddress } Currency { Symbol Name MintAddress } Account { Address } } bought: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: sell } } } } ) sold: sum( of: Trade_Side_AmountInUSD if: { Trade: { Side: { Type: { is: buy } } } } ) volume: sum(of: Trade_Side_AmountInUSD) } } } ``` ## All tokens created by an address To get all Moonit tokens created by address use [this query](https://ide.bitquery.io/Moonshot-tokens-created-by-a-specific-address). ```graphql query MyQuery { Solana(network: solana) { Instructions( where: { Transaction: { Signer: { is: "BGfwxRRcAps1WrJQQRsgWHzvLWVBpRRnfbUxUNGGQ1xV" } } Instruction: { Program: { Address: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } Method: { is: "tokenMint" } } } } ) { Transaction { Signer Signature } Instruction { Accounts { Address } } } } } ``` ## Moonit Token first and last price To check the first and last price to calculate the price change in the last X minutes, use [this query](https://ide.bitquery.io/Moonshot-coins-with-price--mc-with-limit-and-delta-from-10-min-back-simple). In this query, the `from` time should be when you need the price change. For example, if you want a price change for the last 10 minutes, then `from` should be 10 minutes before now. ```graphql query MoonshotRecentTrades($from: DateTime) { Solana { DEXTradeByTokens( limit: {count: 100} orderBy: {descendingByField: "Trade_lastPrice_maximum"} where: {Block: {Time: {since: $from}}, Trade: {Currency: {Native: false}, Dex: {ProgramAddress: {is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Market { MarketAddress } Currency { Symbol Name MintAddress } lastPrice: Price(maximum: Block_Slot) prePrice: Price(minimum: Block_Slot) } } } } { "from": "2024-08-13T09:10:00Z" } ``` ## Get Pools details for Moonit token To get pool details (Market address) for Moonit token use [this query](https://ide.bitquery.io/Market-info-on-Moonshot-by-tokens). ```graphql query ($tokens: [String!]) { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProgramAddress: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } } Currency: { MintAddress: { in: $tokens } } } } ) { count Trade { Market { MarketAddress } Currency { MintAddress Symbol } } } } } ``` ```json { "tokens": [ "token mint address" ] } ``` ## OHLC price in SOL and USD and Volume To get OHLC price in SOL and USD and to get volume use [following query](https://ide.bitquery.io/ohlc-in-sol-with-usd-price_4). ```graphql { Solana { DEXTradeByTokens( orderBy: { ascendingByField: "Block_Time" } where: { Trade: { Currency: { MintAddress: { is: "token mint address" } } Dex: { ProgramAddress: { is: "MoonCVVNZFSYkqNXP6bxHLPL6QQJiMagDL3qcqUQTrG" } } PriceAsymmetry: { lt: 0.1 } } Transaction: { Result: { Success: true } } } ) { Block { Time(interval: { count: 5, in: minutes }) } Trade { Dex { ProtocolName ProtocolFamily } Currency { Symbol Name MintAddress } open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) min: Price(maximum: Trade_Price) max: Price(minimum: Trade_Price) closeUsd: PriceInUSD(maximum: Trade_PriceInUSD) } volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` --- ## Solana NFT API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-nft/ Solana NFT API: track Solana NFT trades, ownership, and metadata with Bitquery GraphQL and streams. Covers archive history and realtime data. # Solana NFT API In this section we'll have a look at some examples using the Solana NFT API. ## Track Latest NFT Trades The subscription query provided below fetches the most recent NFT trades on the Solana blockchain. You can find the query [here](https://ide.bitquery.io/Latest-Solana-NFT-Trades). In this query you will also get failed transactions. To get only successful transactions, set `Transaction: {Result: {Success: true}}` ```graphql subscription { Solana { DEXTradeByTokens(where: {Trade: {Currency: {Fungible: false}}}) { Trade { Dex { ProtocolName ProtocolFamily } Currency { Symbol } Amount Side { Currency { Symbol } Amount } } } } } ``` ## Track all NFT balance updates across the Solana Ecosystem The subscription query provided below fetches the real time nft balance updates of addressses across Solana Ecosystem. This query also gives us NFT balance of the wallets using `PreBalance` and `PostBalance`. You can find the query [here](https://ide.bitquery.io/real-time-nft-balance-updates-across-solana-ecosystem) ```graphql subscription { Solana { BalanceUpdates( where: {BalanceUpdate: {Currency: {Fungible: false}}} ) { BalanceUpdate { Currency { Name MintAddress TokenCreator { Address Share } } Account { Address } PreBalance PostBalance } } } } ``` ## Get Most Traded NFTs Recently The subscription query provided fetches the most-traded NFTs in the last few hours. For Solana, only realtime information is available, so the aggregate might not be accurate beyond a few hours. You can find the query [here](https://ide.bitquery.io/NFT-currencies-on-Solana-by-DEXes_1) ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "amt"} where: {Trade: {Currency: {Fungible: false}}} ) { amt: sum(of: Trade_Amount) Trade { Dex { ProtocolName ProtocolFamily } Currency { Symbol MintAddress } } count } } } ``` ## Video Tutorial on How to Get NFT Trades, NFT Balance Updates and Top Traded NFTs Data on Solana --- ## Solana Openbook API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-OpenBook-api/ Query OpenBook v2 on Solana with Bitquery GraphQL: real-time trades, pair price averages, and every instruction including placeOrder and placeTakeOrder. # OpenBook DEX API :::tip Need real-time OpenBook data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered OpenBook swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical OpenBook data older than ~30 days**, raw per-swap detail, or call / event context. OpenBook markets are covered by the [Solana DEX API](https://bitquery.io/products/solana-dex-api) alongside Raydium, Orca and Jupiter. ::: :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## OpenBook Trades in Real-Time This streams a message for every new trade on the order book, carrying both sides of the fill, the venue that matched it and the block time. Open it in the [Bitquery IDE: realtime order-book trades](https://ide.bitquery.io/Real-time-trades-on-OpenBook-DEX-on-Solana_1). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "OpenBook" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ``` ## Price Average of Pair on OpenBook Open the [Bitquery IDE: average price over 24 hours](https://ide.bitquery.io/Average-Price-for-24-hours-of-a-token-on-OpenBook-DEX-on-Solana_1) to read the average price of a pair on a chosen day. ```graphql query PriceAverage { Solana { DEXTrades( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Dex: { ProtocolFamily: { is: "OpenBook" } } Sell: { Currency: { Symbol: { is: "USDC" } } } Buy: { Currency: { Symbol: { is: "WSOL" } } } } Block: { Time: { after: "2024-06-03T00:00:00Z" before: "2024-06-04T00:00:00Z" } } } ) { tokenPrice: average(of: Trade_Buy_Price) } } } ``` ## Get All Instructions of OpenBook v2 The Solana instructions API returns every instruction the v2 program executed. Open it in the [Bitquery IDE: OpenBook v2 instructions](https://ide.bitquery.io/Instructions-of-OpenBookV2-Program). ```graphql query MyQuery { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Program { Method } } count } } } ``` ## Listen to placeOrder, placeTakeOrder Instructions of OpenBook v2 This subscription follows transactions that place orders on v2, through the Solana instructions API. There is also a [video walkthrough on YouTube](https://www.youtube.com/watch?v=B-3w1t-tnwE). Open it in the [Bitquery IDE: placeOrder and placeTakeOrder instructions](https://ide.bitquery.io/listen-to-placeOrder-placeTakeOrder-instruction-on-OpenBook-V2). ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb" } Method: { in: ["placeOrder", "placeTakeOrder"] } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Method Name Parsed Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } } } } } } ``` ## Listen to consumeEvents Instructions of OpenBook v2 This subscription follows `consumeEvents` transactions on v2. That instruction settles trade events and cancellations, updating the book so every filled order is accounted for. The same [video walkthrough](https://www.youtube.com/watch?v=B-3w1t-tnwE) covers it. Open it in the [Bitquery IDE: consumeEvents instruction](https://ide.bitquery.io/consumeEvents-instruction-on-OpenBook-V2_3). ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb" } Method: { is: "consumeEvents" } } } Transaction: { Result: { Success: true } } } ) { Transaction { Signature } Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Method Name Parsed Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } ... on Solana_ABI_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Address_Value_Arg { address } ... on Solana_ABI_String_Value_Arg { string } ... on Solana_ABI_Integer_Value_Arg { integer } } } } } } } } ``` ## Latest Price of a Token on OpenBook This returns the most recent trade for a token on the order book, with the price in the quote token and in USD. Open it in the [Bitquery IDE: latest token price](https://ide.bitquery.io/live-price-of-token-on-openbook). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolFamily: {is: "OpenBook"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Block { Time } Trade { Currency { MintAddress } Side { Currency { MintAddress } } Price PriceInUSD } } } } ``` ## OpenBook OHLC API If you want to get OHLC data for any specific currency pair on OpenBook, you can use this api. Only use [this API](https://ide.bitquery.io/OpenBook-OHLC-for-specific-pair) as query and not subscription websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Dex: {ProtocolFamily: {is: "OpenBook"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get the Top Traders of a specific Token on OpenBook DEX This ranks the wallets trading one token on the venue, USDC in the example. Run it as a plain request rather than a WebSocket subscription, because aggregates are recomputed per message on a subscription and the totals come back wrong. Open it in the [Bitquery IDE: top traders on OpenBook](https://ide.bitquery.io/top-traders-of-a-token-on-openbook) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProtocolFamily: {is: "OpenBook"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", } ``` ## Get trading volume, buy volume, sell volume of a token This reads the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`. Every Trading row carries a vetted USD price and the cube covers roughly the last 30 days in full, while the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so volume totals taken from them read low. `Side` is the trader's own side. Markets here are quoted in USDC, so the example sums every USDC-quoted market on the venue, matching what the previous chain-level version measured. Filter `Token` as well to narrow it to one pair. Open it in the [Bitquery IDE: trade volume](https://ide.bitquery.io/trade_volume_openbook). ```graphql { Trading { Trades( where: { Pair: { Market: { ProtocolFamily: { is: "OpenBook" }, Network: { is: "Solana" } } QuoteToken: { Address: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ``` ## Volatility of a Pair on OpenBook Volatility is an important factor in trading world as it determines the fluctuation in price that implies the possibility of profit and risk of loss. Lesser volatility denotes that the pair is stable. Open the [Bitquery IDE: token volatility](https://ide.bitquery.io/Volatility-of-USDC-on-OpenBook-Dex-on-Solana) to read volatility for a token over the last 24 hours. ```graphql query Volatility { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "OpenBook" } } Sell: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Block: { Time: { after: "2025-03-18T00:00:00Z" } } } ) { volatility: standard_deviation(of: Trade_Buy_Price) } } } ``` ## Video Tutorial | How to Listen to OpenBook v2 Instruction Calls in Realtime - Bitquery API --- ## Solana Orbic API URL: https://docs.bitquery.io/docs/blockchain/Solana/Orbic-API/ Orbic DEX on Solana: stream real-time trades, get the latest price and a live price feed, OHLC candles, top traders and buy and sell volume of a token. # Orbic API :::tip Need real-time Orbic data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Orbic swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Orbic data older than ~30 days**, raw per-swap detail, or call / event context. ::: ## Orbic Trades in Real-Time This streams a message for every new trade on the venue, carrying the buy and sell sides, the block and the transaction. You can run the query [here](https://ide.bitquery.io/Real-time-trades-on-orbic-DEX-on-Solana#) ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "obriQD1zbpyLz95G5n7nJe6a4DPjpFwa5XYPoNm113y" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ``` ## Latest Price of a Token on Orbic This returns the most recent trade for a mint, with the price in the quote currency and in USD. Open it in the [Bitquery IDE: latest price](https://ide.bitquery.io/latest-price-of-a-token-on-Orbic#). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "obriQD1zbpyLz95G5n7nJe6a4DPjpFwa5XYPoNm113y"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Realtime Price feed of a Token on Orbic The same filter as a subscription pushes a message on every new trade, giving a live price feed instead of a single reading. Open it in the [Bitquery IDE: realtime price feed](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-Orbic#). ```graphql subscription{ Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProgramAddress: {is: "obriQD1zbpyLz95G5n7nJe6a4DPjpFwa5XYPoNm113y"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Orbic OHLC API If you want to get OHLC data for any specific currency pair on Orbic, you can use this api. Only use [this API](https://ide.bitquery.io/Orbic-OHLC-API#) as query and not subscription websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProgramAddress: {is: "obriQD1zbpyLz95G5n7nJe6a4DPjpFwa5XYPoNm113y"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get the Top Traders of a specific Token on Orbic DEX This ranks the wallets trading one mint on the venue, USDC in the example. Run it as a plain request rather than a WebSocket subscription, because aggregates are recomputed per message on a subscription and the totals come back wrong. Open it in the [Bitquery IDE: top traders on Orbic](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Orbic-DEX#) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProgramAddress: {is: "obriQD1zbpyLz95G5n7nJe6a4DPjpFwa5XYPoNm113y"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } ``` ## Get trading volume, buy volume, sell volume of a token This sums traded, buy and sell volume for a mint on the venue. It reads the `archive` dataset because this program's trading is historical rather than current; run the latest-trade query above to see how recent the newest row is. Note that Solana `archive` and `combined` return about a fifth fewer trades than `realtime` over a window both cover, so treat these totals as a floor. Open it in the [Bitquery IDE: trade volume](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token_5#). ```graphql query MyQuery { Solana(dataset: archive) { DEXTradeByTokens( where: {Block: {Time: {since: "2025-03-10T07:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProgramAddress: {is: "obriQD1zbpyLz95G5n7nJe6a4DPjpFwa5XYPoNm113y"}}}} ) { Trade { Currency { MintAddress Decimals } Side { Currency { Name MintAddress } } } traded_volume_USD: sum(of: Trade_Side_AmountInUSD) traded_volume: sum(of: Trade_Amount) buy_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}} ) sell_volume: sum( of: Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}} ) } } } ``` --- ## Solana Perpetuals Kafka Stream — solana.perpetual.proto URL: https://docs.bitquery.io/docs/streams/protobuf/chains/Solana-perpetual-protobuf/ Solana perpetual futures over Kafka: orders, fills, positions, PnL, liquidations, prices and open interest as protobuf on the solana.perpetual.proto topic. # Solana Perpetuals Kafka Stream The `solana.perpetual.proto` topic carries the same perpetual-futures data as the [Perp DEX API](/docs/perpetuals/) — orders, fills, positions, prices and market summaries — as **protobuf messages over Kafka**, one message per Solana block. Use it when you want the lowest-latency delivery, replay from the consumer group's offset, and you are comfortable running a Kafka consumer instead of a GraphQL WebSocket. | | | | ---------- | -------------------------------------------------------------------------------- | | **Topic** | `solana.perpetual.proto` | | **Message**| `PerpetualBlockMessage` — [schema on GitHub](https://github.com/bitquery/streaming_protobuf/blob/main/solana/perpetual_block_message.proto) | | **Brokers**| `rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092` | | **Auth** | SASL_PLAINTEXT / SCRAM-SHA-512 (TLS optional on `9093`) — [connection guide](/docs/streams/kafka-streaming-concepts/) | | **Access** | Kafka stream credentials from the [API request form](https://bitquery.io/forms/api) — not IDE API keys | | **Venue** | Phoenix Perpetuals (`phoenix_eternal`) — see the [Phoenix Perpetuals API](/docs/perpetuals/solana/phoenix-perpetuals-api) for market semantics | ## Message anatomy Every block produces one `PerpetualBlockMessage`: ``` PerpetualBlockMessage ├── Header BlockHeader — Slot, Timestamp, … └── Transactions[] ParsedPerpetualTransaction ├── Index, Signature, Status, Header ├── Orders[] order lifecycle events ├── Fills[] executions ├── Positions[] PnL, funding, liquidations ├── Prices[] best bid/ask, mark └── MarketSummaries[] open interest, spot index, fee totals ``` The five lists map one-to-one onto the GraphQL cubes, so everything documented on the [Phoenix Perpetuals API](/docs/perpetuals/solana/phoenix-perpetuals-api) page — order lifecycle enums, cancel reasons, the multi-row liquidation pattern, cumulative fee counters — applies here unchanged: | Kafka list | GraphQL cube | | ----------------- | -------------------------- | | `Orders` | `PerpetualOrders` | | `Fills` | `PerpetualFills` | | `Positions` | `PerpetualPositions` | | `Prices` | `PerpetualPrices` | | `MarketSummaries` | `PerpetualMarketSummaries` | Blocks with no perpetual activity still produce a message with an empty `Transactions` list — a convenient liveness signal for your consumer. ## Reading the schema correctly These rules come from the schema itself and from consuming the live topic: - **Everything is already in human units.** Sizes are in asset units, prices and amounts in the quote currency. The venue's internal lot/tick arithmetic is resolved before publishing, so no decimal scaling is needed on your side. - **`bytes` fields are raw 32-byte Solana keys** (`Signer`, `Trader`, `Liquidator`, `Program`, `Oracle`, mint addresses). Base58-encode them for display. An **empty** `bytes` field means the chain named no account — it is never the all-zero address. - **proto3 drops zero values from the wire — and SOL's asset id is literally `0`.** An absent `Asset.Id` means SOL, not "unknown". Join and group on `Asset.Symbol`, which is always present, and never treat `Id == 0` as a missing-value sentinel. - **A perpetual asset has no mint.** GOLD, NVDA or WTIOIL perps have no token on Solana; `Id` + `Symbol` are the market's whole identity. The only real mint in the message is the quote currency's (`PhUsd` on Phoenix — the venue's canonical quote token, backed 1:1 by USDC). - **`EventIndex` is one counter across all five lists** within a transaction. Use it to place a fill against the order that caused it and the mark of the same moment. There is no per-event timestamp — time and slot live on `BlockHeader`. - **`MakerOrderId` XOR `SplineId`** — exactly one is ever set on a fill. A book fill names the maker's order (joins back to its placement and cancellation); an AMM fill (`CounterpartyIsAmm: true`) names the spline instead. - **`Collateral` is the account's cross-margin collateral, not this position's margin.** One collateral balance covers every market the trader is in, so dividing one position's notional by it is not leverage. Real leverage is the sum of `|Size × MarkPrice|` across all the trader's markets divided by `Collateral`. - **`Liquidation` is flagged on every event of the liquidated trader** in that transaction — the PnL row that realizes the loss, the forced order, the fill — not only on the row typed `"Liquidation"`. Without the flag a forced close is indistinguishable from a voluntary one. - **`MarkPrice` is denormalized** from the same transaction's price events: always present on fills, present on roughly 60% of PnL events. When it is `0`, as-of join the `Prices` stream on `(Asset, Slot)`. - **`Amount.Fee` can be negative — that is a maker rebate.** - **`Prices` rows are a side effect of trading.** The oracle's timer-based republication is not part of this stream, so a market that does not trade produces no price rows; `SequenceNumber` is per-asset and sparse. Use it for ordering and dedup, not as a completeness check. - **`Trader` vs `Signer`**: `Trader` is the position-owning account (a PDA on Phoenix), `Signer` is the wallet that signed. An expiry crank cancelling other people's orders carries neither — join those cancels to their placement by `Order.Id`. - **Conditional orders** (stop-loss / take-profit) are addressed by `(Trader, Asset.Id, ConditionalId)`, not by book order id. Their `Order.Type` is empty on `Conditional*` end events — recover the kind by joining back to the placement. ## Quickstart consumer (Python) Compile the schema (or use the published packages: [`bitquery-pb2-kafka-package`](https://pypi.org/project/bitquery-pb2-kafka-package/) for Python, [`bitquery-protobuf-schema`](https://www.npmjs.com/package/bitquery-protobuf-schema) for JS, [`streaming_protobuf/v2`](https://pkg.go.dev/github.com/bitquery/streaming_protobuf/v2) for Go): ```bash git clone https://github.com/bitquery/streaming_protobuf.git pip install confluent-kafka protobuf grpcio-tools base58 python -m grpc_tools.protoc -I streaming_protobuf --python_out=. \ streaming_protobuf/solana/perpetual_block_message.proto \ streaming_protobuf/solana/block_message.proto ``` Then consume: ```python from confluent_kafka import Consumer from solana import perpetual_block_message_pb2 as perp conf = { "bootstrap.servers": "rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092", "security.protocol": "SASL_PLAINTEXT", "sasl.mechanism": "SCRAM-SHA-512", "sasl.username": os.environ["KAFKA_USERNAME"], "sasl.password": os.environ["KAFKA_PASSWORD"], "group.id": os.environ["KAFKA_USERNAME"] + "-perp-1", "auto.offset.reset": "latest", "enable.auto.commit": False, } consumer = Consumer(conf) consumer.subscribe(["solana.perpetual.proto"]) while True: msg = consumer.poll(1.0) if msg is None or msg.error(): continue block = perp.PerpetualBlockMessage() block.ParseFromString(msg.value()) for tx in block.Transactions: for f in tx.Fills: print( block.Header.Slot, f.Asset.Symbol, f.Side, f.Amount.Size, "@", f.ExecutionPrice, "liq" if f.Liquidation else "", base58.b58encode(f.Trader).decode(), ) ``` Prefix your `group.id` with your Kafka username. Full consumer patterns — TLS, rebalancing, at-least-once processing — are in the [examples repository](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/README.md) and the language guides: [Python](/docs/streams/protobuf/kafka-protobuf-python), [JavaScript](/docs/streams/protobuf/kafka-protobuf-js), [Go](/docs/streams/protobuf/kafka-protobuf-go). ## Kafka or GraphQL subscription? | Need | Use | | ------------------------------------------------ | ------------------------------------------------------------------- | | Lowest latency, full firehose, offset replay | This Kafka topic | | Server-side filtering (one market, one trader) | [GraphQL subscriptions](/docs/perpetuals/solana/phoenix-perpetuals-api) — filter in `where` | | Historical queries and aggregations | [GraphQL queries](/docs/perpetuals/) over the same cubes | Kafka delivers everything and you filter client-side; the GraphQL layer filters server-side but adds the API layer's processing. The underlying events are identical. --- ## Solana Perps Trader Cookbook — Copy Trading, PnL & Signals URL: https://docs.bitquery.io/docs/perpetuals/solana/perps-trader-cookbook/ Ready-to-run Solana perps queries: copy-trade a wallet, rank traders by PnL and win rate, unrealized positions, whale fills, OHLC, open interest, order flow. # Solana Perps Trader Cookbook Ready-to-run recipes for the questions traders, copy-traders and strategy builders actually ask, built on the [Perp DEX cubes](/docs/perpetuals/). Every query here was validated against the live endpoint; swap the example wallet/market for your own. Field semantics live on the [Phoenix Perpetuals API](/docs/perpetuals/solana/phoenix-perpetuals-api) page. Two rules apply to almost every recipe: - **`TraderIsAmm: false`** — the venue's AMM backstop trades every market; leave it in and it tops every leaderboard. - **Latest-state snapshots** use `limitBy` + `orderBy: {descending: Block_Time}` — the newest row per key *is* the current state. Don't pre-filter `Closed: false` or `Size: {ne: 0}`: that skips past closing rows and resurrects stale positions. Take the latest row, then drop flats (`Size == 0`) client-side. ## Copy trading ### Follow a trader's every fill, live You can run the wallet-fills version [in the Bitquery IDE](https://ide.bitquery.io/sol_perps_filled_orders_by_signer). Stream each execution of a wallet you follow — the signal feed a copy-trading bot subscribes to, including the position each fill produced: ```graphql subscription { Solana { PerpetualFills( where: { Fill: { Trader: { is: "DUGirckBgoaW3zoEPhTVVo68pZpXrTKuJrsLBLWcZQo2" } Liquidation: false } } ) { Block { Time } Fill { Asset { Symbol } Side ExecutionPrice Amount { Filled Quote } Position { Size EntryPrice } } } } } ``` `Position { Size, EntryPrice }` after each fill tells you their resulting exposure — you see reduces and flips, not just entries. Note that `Trader` is the venue's position account (a PDA), which you learn from any of their fills or positions. ### A trader's current open book Latest state per market for one wallet — what they hold right now: ```graphql query { Solana { PerpetualPositions( limitBy: { by: Position_Asset_Id, count: 1 } orderBy: { descending: Block_Time } limit: { count: 100 } where: { Position: { Trader: { is: "DUGirckBgoaW3zoEPhTVVo68pZpXrTKuJrsLBLWcZQo2" } } } ) { Block { Time } Position { Asset { Symbol } Position { EntryPrice Size } MarkPrice } } } } ``` Rows with `Size: 0` are markets they've fully closed — drop them and the rest is the live book, with entry prices. ### Who is worth copying — the report card You can run this query [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-trader-pnl). Realized PnL, close count, win rate and liquidation count per trader, in one aggregation: ```graphql query { Solana { PerpetualPositions( limit: { count: 20 } orderBy: { descendingByField: "realized" } where: { Position: { TraderIsAmm: false, Closed: true } } ) { Position { Trader } realized: sum(of: Position_RealizedPnl) closes: count wins: count(if: { Position: { RealizedPnl: { gt: 0 } } }) losses: count(if: { Position: { RealizedPnl: { lt: 0 } } }) liquidated: count(if: { Position: { Liquidation: true } }) } } } ``` Win rate is `wins / closes`; a high `realized` with `liquidated > 0` tells you how they treat risk. Add a `Block: { Time: { since: … } }` filter to score a recent window instead of all time. ## Positions & PnL ### Top unrealized positions and traders You can run this query [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-top-positions). Unrealized PnL is `(mark − entry) × size` over each trader's latest open position. One request returns both the position snapshot and fresh marks: ```graphql query { Solana { openPositions: PerpetualPositions( limitBy: { by: [Position_Trader, Position_Asset_Id], count: 1 } orderBy: { descending: Block_Time } limit: { count: 3000 } where: { Position: { TraderIsAmm: false } } ) { Block { Time } Position { Trader Asset { Id Symbol } Position { EntryPrice Size } MarkPrice } } marks: PerpetualPrices( limitBy: { by: Price_Asset_Id, count: 1 } orderBy: { descending: Block_Time } limit: { count: 200 } ) { Price { Asset { Id Symbol } Mark } } } } ``` Then a few lines client-side: ```python marks = {m["Price"]["Asset"]["Id"]: m["Price"]["Mark"] for m in d["marks"]} open_pos = [] for r in d["openPositions"]: p = r["Position"]; size = p["Position"]["Size"] if size == 0: continue # flat = closed mark = marks.get(p["Asset"]["Id"]) or p["MarkPrice"] upnl = (mark - p["Position"]["EntryPrice"]) * size # signed Size handles shorts open_pos.append((p["Trader"], p["Asset"]["Symbol"], size, upnl)) top_positions = sorted(open_pos, key=lambda x: x[3], reverse=True) ``` Sum per `Trader` for a whale-exposure leaderboard. Prefer the `marks` alias over the position row's own `MarkPrice` — the latter is denormalized and can be `0`. ### Funding a trader has paid or received Funding settlements are their own rows — `Funding` non-zero, size unchanged: ```graphql query { Solana { PerpetualPositions( limit: { count: 100 } orderBy: { descending: Block_Time } where: { Position: { Trader: { is: "DUGirckBgoaW3zoEPhTVVo68pZpXrTKuJrsLBLWcZQo2" } Funding: { ne: 0 } } } ) { Block { Time } Position { Asset { Symbol } Funding } } } } ``` Positive = received, negative = paid. Replace the field list with `total: sum(of: Position_Funding)` for the net carry cost of holding their positions. ## Market signals ### Whale fills You can run the query version [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-whale-trades). Every fill above a notional threshold — as history or a live tape: ```graphql subscription { Solana { PerpetualFills(where: { Fill: { Amount: { Quote: { gt: 5000 } } } }) { Block { Time } Fill { Asset { Symbol } Side ExecutionPrice Amount { Filled Quote } Trader Liquidation } } } } ``` As a `query`, add `orderBy: { descending: Block_Time }` and a `limit` for the recent whale prints. ### OHLC candles from the mark price You can run this query [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-ohlc-candles). Strategy builders and backtesters: bucket `PerpetualPrices` into intervals and take argMin/argMax aggregates — ```graphql query { Solana { PerpetualPrices( where: { Price: { Asset: { Symbol: { is: "BTC" } } } } orderBy: { ascendingByField: "Block_Time" } limit: { count: 96 } ) { Block { Time(interval: { in: minutes, count: 15 }) } Price { open: Mark(minimum: Block_Time) high: Mark(maximum: Price_Mark) low: Mark(minimum: Price_Mark) close: Mark(maximum: Block_Time) } } } } ``` `Mark(minimum: Block_Time)` reads "the Mark at the earliest time in the bucket" — open; `Mark(maximum: Price_Mark)` is the bucket's high. Price rows are emitted on trading activity, so an interval with no trades produces no candle (no zero-filled bars). ### Open interest, basis and fee revenue over time You can run this query [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-open-interest). One query per market gives an OI series, the perp-vs-spot basis, and — because `TakerFees`/`MakerFees` are cumulative counters — per-bucket fee revenue as end-minus-start: ```graphql query { Solana { PerpetualMarketSummaries( where: { MarketSummary: { Asset: { Symbol: { is: "SOL" } } } } orderBy: { ascendingByField: "Block_Time" } limit: { count: 168 } ) { Block { Time(interval: { in: hours, count: 1 }) } MarketSummary { oi: OpenInterest(maximum: Block_Time) mark: Mark(maximum: Block_Time) spot: SpotIndex(maximum: Block_Time) takerFeesEnd: TakerFees(maximum: Block_Time) takerFeesStart: TakerFees(minimum: Block_Time) } } } } ``` Basis = `mark − spot`; hourly taker fees = `takerFeesEnd − takerFeesStart`. Rising OI with a widening basis is the classic crowded-longs signal. ### Order-flow pressure — taker buys vs sells You can run this query [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-taker-buy-sell-pressure). Conditional sums split taker volume by side per bucket: ```graphql query { Solana { PerpetualFills( where: { Fill: { Asset: { Symbol: { is: "SOL" } } } } orderBy: { ascendingByField: "Block_Time" } limit: { count: 168 } ) { Block { Time(interval: { in: hours, count: 1 }) } buyVol: sum(of: Fill_Amount_Quote, if: { Fill: { Side: { is: "bid" } } }) sellVol: sum(of: Fill_Amount_Quote, if: { Fill: { Side: { is: "ask" } } }) trades: count } } } ``` `(buyVol − sellVol) / (buyVol + sellVol)` is a ready order-flow-imbalance series. ## Risk ### Biggest liquidations You can run this query [in the Bitquery IDE](https://ide.bitquery.io/solana-perps-liquidations). Rank forced closes by what they took: ```graphql query { Solana { PerpetualPositions( limit: { count: 20 } orderBy: { descendingByField: "lost" } where: { Position: { Type: { is: "Liquidation" } } } ) { Position { Trader Asset { Symbol } } lost: sum(of: Position_LiquidatedQuote) events: count } } } ``` For the live feed version and the multi-row anatomy of a liquidation, see the [liquidation section](/docs/perpetuals/solana/phoenix-perpetuals-api#positions-pnl--liquidations--perpetualpositions) of the Phoenix page. --- Every `query` above becomes a live stream by switching to `subscription` and removing `limit`/`orderBy`/`limitBy` — except the snapshot and interval recipes, which are inherently query-shaped. Run them over Kafka instead with the [`solana.perpetual.proto` topic](/docs/streams/protobuf/chains/Solana-perpetual-protobuf) when you need the full firehose. --- ## Solana Phoenix API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-Phoenix-api/ Query the Phoenix order book on Solana with Bitquery GraphQL: real-time trades, latest and streaming token prices, and OHLC candles for any pair. # Phoenix DEX API :::info Looking for Phoenix **Perpetuals**? This page covers the Phoenix **spot** order book. For perpetual futures (orders, fills, positions, realized PnL, liquidations, funding, mark price and open interest), see the [**Phoenix Perpetuals API**](/docs/perpetuals/solana/phoenix-perpetuals-api), also available as a [Kafka protobuf stream](/docs/streams/protobuf/chains/Solana-perpetual-protobuf). Phoenix order-book data is available as a product. See the [Phoenix Trades API](https://bitquery.io/products/phoenix-trades) page for coverage and plans. ::: :::tip Need real-time Phoenix data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Phoenix swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Phoenix data older than ~30 days**, raw per-swap detail, or call / event context. ::: ## Phoenix Trades in Real-Time This streams a message for every new trade on the venue, carrying the buy and sell sides, the block and the transaction. Open it in the [Bitquery IDE: realtime order-book trades](https://ide.bitquery.io/Real-time-trades-on-Phoenix-DEX-on-Solana_1). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Phoenix" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ``` ## Latest Price of a Token on Phoenix This returns the most recent trade for a token here, with the price in the quote token and in USD. Open it in the [Bitquery IDE: latest token price](https://ide.bitquery.io/latest-price-of-token-on-phoenix). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolFamily: {is: "Phoenix"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Realtime Price feed of a Token on Phoenix The same filter as a subscription pushes a message on every new trade, giving a live price feed instead of a single reading. Open it in the [Bitquery IDE: realtime price feed](https://ide.bitquery.io/realtime-price-of-token-on-phoenix). ```graphql subscription{ Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProtocolFamily: {is: "Phoenix"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Phoenix OHLC API For OHLC candles on a pair here, use [this endpoint](https://ide.bitquery.io/Phoenix-OHLC-for-specific-pair_1) as query and not subscription websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProtocolFamily: {is: "Phoenix"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get the Top Traders of a specific Token on Phoenix DEX This ranks the wallets trading one token on the order book, USDC in the example. Run it as a plain request rather than a WebSocket subscription, because aggregates are recomputed per message on a subscription and the totals come back wrong. Open it in the [Bitquery IDE: top traders on Phoenix](https://ide.bitquery.io/top-traders-of-a-token-on-phoenix) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProtocolFamily: {is: "Phoenix"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } ``` ## Get trading volume, buy volume, sell volume of a token This reads the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`. Every Trading row carries a vetted USD price and the cube covers roughly the last 30 days in full, while the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so volume totals taken from them read low. `Side` is the trader's own side. The example follows the WSOL/USDC market; swap the two addresses for the pair you want. Open it in the [Bitquery IDE: Phoenix trade volume](https://ide.bitquery.io/trade_volume_phoenix). ```graphql { Trading { Trades( where: { Pair: { Market: { ProtocolFamily: { is: "Phoenix" }, Network: { is: "Solana" } } Token: { Address: { is: "So11111111111111111111111111111111111111112" } } QuoteToken: { Address: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ``` ## Volatility of a Pair on Phoenix Volatility is an important factor in trading world as it determines the fluctuation in price that implies the possibility of profit and risk of loss. Lesser volatility denotes that the pair is stable. Open the [Bitquery IDE: pair volatility](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-phoenix-Dex-on-Solana_1) to read volatility for a pair over the last 24 hours. ```graphql query VolatilityonPhoenix { Solana(dataset: realtime) { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Phoenix" } } Buy: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Sell: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Block: { Time: { after: "2025-06-06T01:00:00Z" before: "2025-06-06T02:00:00Z" } } } ) { volatility: standard_deviation(of: Trade_Buy_Price) } } } ``` --- ## Solana Photon API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-photon-api/ Track Photon-routed Solana trades with Bitquery GraphQL: latest trades by pair, trader-level rows with USD price, market cap and supply, plus live streams. # Photon Solana API :::tip Need real-time Photon-style trader data or anything from the last ~30 days? For **real-time trader and wallet data over the last ~30 days** across **10 chains in one API**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **`Trader.Address`** as a first-class filter plus **USD price, market cap, and supply on every row**. Use this page when you need **historical Photon-style trader data older than ~30 days**, raw per-swap detail, or call / event context. The queries below run on the same data that powers Photon-style terminals — the [Solana DEX API](https://bitquery.io/products/solana-dex-api) page covers venues, latency and plans. ::: Photon is a routing aggregator on Solana that finds the best execution paths across multiple DEXs. To identify trades that were routed through Photon, we use their program address `BSfD6SHZigAfDWSjzD5Q41jw8LmKwtmjskPH9XW1mrRW` in our queries. This program address appears in the instruction data when Photon routes a trade, allowing us to filter and analyze only the trades that went through their routing system. By joining DEX trade data with instruction data containing this program address, we can accurately track Photon's routing activity and provide insights into their trade execution patterns. :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## Latest Trades Routed via Photon This query retrieves the latest 100 trades that were routed through Photon on Solana. The query uses a `joinInstructions` function to filter trades that specifically involved Photon's routing program (address: `BSfD6SHZigAfDWSjzD5Q41jw8LmKwtmjskPH9XW1mrRW`). For more information about using joins in Bitquery APIs, see our [graphQL joins documentation](/docs/graphql/capabilities/joins/). [Run Query](https://ide.bitquery.io/Trades-Executed-on-Photon) ```graphql { Solana { DEXTrades(limit: {count: 100}, orderBy: {descending: Block_Time}) { Trade { Dex { ProtocolName } Sell { Currency { Symbol } Amount AmountInUSD Account { Address } Price PriceInUSD } Buy { Currency { Symbol } Amount AmountInUSD Account { Address } Price PriceInUSD } } Transaction { Signature } Instruction { ExternalSeqNumber InternalSeqNumber } joinInstructions( join: inner Block_Slot: Block_Slot Transaction_Signature: Transaction_Signature where: {Instruction: {Program: {Address: {is: "BSfD6SHZigAfDWSjzD5Q41jw8LmKwtmjskPH9XW1mrRW"}}}} ) { Instruction { Program { Address } } Transaction { Signature } } } } } ``` ## Get Trade Transactions Of Photon For A Particular Pair The query will get latest trades for a Solana pair executed via Photon You can find the query [here](https://ide.bitquery.io/Trades-of-a-Pair-Executed-on-Photon) ```graphql { Solana { DEXTrades( limit: {count: 100} orderBy: {descending: Block_Time} where: {Trade: {Market:{MarketAddress:{is:"FsKeY7bWnGL3ucTVfWWWJZyGCqr1VGXbKVZWteUHPYzX"}}}} ) { Trade { Dex { ProtocolName } Sell { Currency { Symbol } Amount AmountInUSD Account { Address } Price PriceInUSD } Buy { Currency { Symbol } Amount AmountInUSD Account { Address } Price PriceInUSD } Market { MarketAddress } } Transaction { Signature } Instruction { ExternalSeqNumber InternalSeqNumber } joinInstructions( join: inner Block_Slot: Block_Slot Transaction_Signature: Transaction_Signature where: {Instruction: {Program: {Address: {is: "BSfD6SHZigAfDWSjzD5Q41jw8LmKwtmjskPH9XW1mrRW"}}}} ) { Instruction { Program { Address } } Transaction { Signature } } } } } ``` --- ## Trader-Focused Trade APIs (with USD Price, Market Cap & Supply) The queries below use the **[Trades cube](/docs/trading/crypto-trades-api/trades-api/)** (`Trading { Trades }`) which is trader-focused and provides reliable USD prices including for all tokens. See [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades) for when to use which. ### Get All DEX Trades on Solana With Price, Market Cap, and Supply Stream **all Solana DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Network: Solana`** to capture every swap across **Raydium**, **Orca**, **Jupiter**, **PumpSwap**, and other Solana DEXs in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/All-trades-on-Solana-with-Price-Marketcap-supply).
Click to expand GraphQL query ```graphql subscription { Trading { Trades(where: { Pair: { Market: { Network: { is: "Solana" } } } }) { Side Supply { MaxSupply TotalSupply FullyDilutedValuationUsd CirculatingSupply MarketCap } Trader { Address } TransactionHeader { Fee FeePayer Sender To Hash Index } Amounts { Base Quote } AmountsInUsd { Base Quote } Block { Date Time Timestamp } Pair { Currency { Id Name Symbol } Market { Address Program Network } QuoteCurrency { Id Name Symbol } Token { Address Id IsNative Symbol TokenId Network } QuoteToken { Address Id IsNative Symbol TokenId Network } } Price PriceInUsd } } } ```
### Top Traders by PnL for a Specific Pool (Last 30 Minutes) Rank traders by **`PnL`** on one pool: filter **`Pair.Market.Address`**, last **30 minutes**, **`limit: 10`**, and **`orderBy`** **`PnL`** descending. Useful for **leaderboards**, **smart-money screens**, and **pool-specific trader analytics**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-pair#).
Click to expand GraphQL query ```graphql { Trading { Trades( limit: { count: 10 } orderBy: [{ descendingByField: "PnL" }] where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "2axyccPzS7Ei57c7ESEq7tBpo4HxtpfCR9gKxh5uNUpu" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) Amount_Bought_native: sum(of: Amounts_Base, if: { Side: { is: "Buy" } }) Amount_Sold_native: sum(of: Amounts_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ```
--- ## Video Tutorial | Photon API Tutorial: Track DEXTrades on Solana (2026) --- ## Solana RFQ API - Jupiter Z & Intent Settlement URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-rfq-api/ Query and stream Solana RFQ trades: Jupiter Z order_engine fills, quote expiry, maker spreads and tokenized-equity prices, over API and WebSocket. # Solana RFQ API In an RFQ (Request For Quote) trade there is no pool. The taker asks market makers for a price off chain, a maker signs a firm quote, and the only thing that reaches the chain is a settlement instruction that moves both sides of the trade at once. :::info Jupiter Z and the large prop AMMs are in DEX trade data from 29 September 2026 From 15:06 UTC that day, `DEXTrades`, `DEXTradeByTokens` and the `Trading` cube include Jupiter Z fills and swaps on Tessera V, HumidiFi, QuantumAMM and Scorch. Trades on these venues from before that time are not in the trade tables. Jupiter Limit Order v2, Mayan Swift, ZeroFi and 1inch Fusion still produce no trade rows. ::: For volume and prices, start with [RFQ trades in DEX trade data](#rfq-trades-in-dex-trade-data). The rest of the page works at instruction level, for the detail the trade tables leave out: quote expiry, who paid gas, the raw accounts, and the venues that are still not in trade data. Those sections use the [Solana Instructions cube](/docs/blockchain/Solana/solana-instructions), the [Transfers cube](/docs/blockchain/Solana/solana-transfers) and [Instruction Balance Updates](/docs/blockchain/Solana/solana-instruction-balance-updates). --- ## Quickstart Endpoint, auth header, and a request you can paste into a terminal right now. ```bash curl -X POST https://streaming.bitquery.io/graphql \ -H 'Content-Type: application/json' \ -H "Authorization: Bearer $BITQUERY_TOKEN" \ -d '{"query":"{ Solana { Instructions(limit: {count: 3} orderBy: {descending: Block_Time} where: {Transaction: {Result: {Success: true}} Instruction: {Program: {Address: {is: \"61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH\"} Method: {is: \"fill\"}}}}) { Block { Time } Transaction { Signature } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } }"}' ``` For streams, the same document works over WebSocket at `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-ws` subprotocol. See [generating a token](/docs/authorization/how-to-generate) and [WebSocket authorization](/docs/authorization/websocket). :::info Query window Historical depth depends on your plan, so a query with an old `since` date can come back empty even when the filter is correct. Test without a date filter first. ::: --- ## Which protocols exist Two families. Both price off chain, but only the first settles through a named RFQ instruction. ### Family 1: true RFQ and intent settlement | Protocol | Program ID | IDL / instruction | What it is | In DEX trade data | |---|---|---|---|---| | Jupiter Z (JupiterZ) | `61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH` | `order_engine` → `fill` | Same-chain RFQ. The maker signs and pays gas, the taker pays nothing. | Yes | | Jupiter Z (2nd deployment) | `2En5Y11SEAGLNmEezTuRUCwTyzyNReHaMbSnS5gjGsL1` | `order_engine` → `fill` | Same IDL and same maker set, but the taker or a relayer pays gas. | Yes | | Jupiter RFQ v2 | `fd3nMFYTQjX1yr5ER8u7tPdHJB7qt8RpDpNtLQX2Br5` | `rfq_v2` → `fill_exact_in` | Newer Jupiter RFQ program. Very little traffic so far. | No | | Jupiter Limit Order v2 | `j1o2qRpjcyUwEvwtcfhEQefh773ZgjxcVRry7LDqg5X` | `limit_order_2` → `fill_order` | Resting maker orders filled by a keeper. | No | | Mayan Swift | `mayan34VedncxdK2XobtvWFDXQASUTBXhUVzt2kKgny` | `swift` → `init_order` / `fulfill` / `settle` | Cross-chain intent auction with competing drivers (solvers). | No | | 1inch Fusion | `HNarfxC3kYMMhFkxUFeYb8wHVdPzY5t9pupqW5fL2meM` | `fusion_swap` → `fill` | Dutch-auction intents. Deployed, but barely used on Solana. | No | ### Family 2: proprietary market-maker AMMs These have RFQ economics (one professional maker quotes, aggregators route to it) with AMM plumbing (a `swap` instruction against program-owned inventory). Several publish quote updates directly on chain, covered in [the quote tape](#the-on-chain-quote-tape). | Venue | Program ID | Indexed as DEX trades? | |---|---|---| | SolFi v2 | `SV2EYYJyRz2YhfXwXnhNAevDEui5Q6yrfyo13WtupPF` | Yes | | GoonFi v2 | `goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE` | Yes | | BisonFi | `BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi` | Yes | | AlphaQ | `ALPHAQmeA7bjrVuccPsYPiCvsi428SNwte66Srvs4pHA` | Yes | | Aquifer | `AQU1FRd7papthgdrwPTTq5JacJh8YtwEXaBfKU3bTz45` | Yes | | Tessera V | `TessVdML9pBGgG9yGks7o4HewRaXVAMuoVj4x83GLQH` | Yes | | HumidiFi | `9H6tua7jkLhdm3w8BvgpTn5LZNU7g4ZynDmCiNN3q6Rp` | Yes | | QuantumAMM | `QuaNtZsgYRe5Z9Bk4LZ4cTD9tbkVoyCNf1R2BN9bBDv` | Yes | | Scorch | `SCoRcH8c2dpjvcJD6FiPbCSQyQgu3PcUAWj2Xxx3mqn` | Yes | | ZeroFi | `ZERor4xhbUycZ6gb9ntrhqscUcZmAbQDjEAtCf4hbZY` | No | Scorch posts its prices through a separate program, `ojh19ojaKduoJZuaJADhcVGp4xt1TcdAvZmpVsCorch`, which Scorch swaps pass in as an account. That program moves no tokens itself, so it has no trade rows of its own. --- ## RFQ trades in DEX trade data These venues appear in `DEXTrades`, `DEXTradeByTokens` and the `Trading` cube under the following names. | Venue | `Dex.ProtocolName` | `Dex.ProtocolFamily` | Program | |---|---|---|---| | Jupiter Z | `order_engine` | `Jupiter` | `61DFfeTK…` and `2En5Y11S…` | | Tessera V | `tessera_v` | `Tessera` | `TessVdML…` | | HumidiFi | `humidifi` | `HumidiFi` | `9H6tua7j…` | | QuantumAMM | `quantum_amm` | `QuantumAMM` | `QuaNtZsg…` | | Scorch | `scorch` | `Scorch` | `SCoRcH8c…` | ### Latest Jupiter Z trades ```graphql query LatestJupiterZTrades { Solana { DEXTrades( limit: { count: 20 } orderBy: { descending: Block_Time } where: { Trade: { Dex: { ProtocolName: { is: "order_engine" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signature } Trade { Dex { ProgramAddress ProtocolName ProtocolFamily } Market { MarketAddress } Buy { Amount AmountInUSD Currency { Symbol MintAddress } Account { Owner } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } Account { Owner } } } } } } ``` How to read the result: - `Trade.Market.MarketAddress` is the maker's wallet. RFQ has no pool, so each maker is its own market. - `Trade.Buy.Account.Owner` and `Trade.Sell.Account.Owner` are the taker. - Do not use `Transaction.Signer` as the trader. On the main program the maker signs and pays gas, so the signer field holds the maker's wallet. - A native SOL side shows up as `11111111111111111111111111111111`, while the `fill` instruction names the wrapped SOL mint (`So111…112`). ### Trades and volume by venue ```graphql query RfqAndPropAmmVolume { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolName: { in: ["order_engine", "tessera_v", "humidifi", "quantum_amm", "scorch"] } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { hours_ago: 1 } } } } ) { Trade { Dex { ProtocolName ProtocolFamily } } trades: count volumeUSD: sum(of: Trade_Buy_AmountInUSD) } } } ``` :::caution Keep the Success filter `DEXTrades` returns trades from failed transactions unless you filter them out, and bots fire a lot of failing swaps at the prop AMMs. Between 15:10 and 15:30 UTC on 29 September 2026, failed transactions made up 92% of HumidiFi rows, 82% of Scorch rows, 66% of Tessera V rows and 56% of QuantumAMM rows, against under 1% for Jupiter Z. Keep `Transaction: { Result: { Success: true } }` in every query. ::: --- ## Anatomy of a Jupiter Z fill One instruction, three arguments, eleven accounts. ``` program: 61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH (IDL name: order_engine) method: fill arguments input_amount u64 exact amount the taker sends (raw, token decimals) output_amount u64 exact amount the taker receives (raw, token decimals) expire_at i64 unix timestamp the quote stops being valid accounts (positional) 0 taker 1 maker 2 taker_input_mint_token_account 3 maker_input_mint_token_account 4 taker_output_mint_token_account 5 maker_output_mint_token_account 6 input_mint 7 input_token_program 8 output_mint 9 output_token_program 10 system_program ``` The execution price is exact, so you never touch pool math: ``` price = (output_amount / 10^outDecimals) / (input_amount / 10^inDecimals) ``` There is no fee tier or curve to model. The number on chain is the fill. :::caution Account 2 is not always a token account When the taker pays with native SOL, position 2 holds the program ID itself as a stand-in for an unused optional account. Read mints from positions 6 and 8 rather than assuming every token account slot is populated. ::: --- ## Latest RFQ fills ```graphql query LatestRFQFills { Solana { Instructions( limit: { count: 20 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } Method: { is: "fill" } } } } ) { Block { Time Slot } Transaction { Signature Signer Fee } Instruction { Accounts { Address Token { Mint Owner } } Program { Method AccountNames Arguments { Name Type Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } ... on Solana_ABI_Integer_Value_Arg { integer } } } } } } } } ``` A trimmed real response: ```json { "Block": { "Slot": "436710297", "Time": "2026-08-02T05:57:11Z" }, "Transaction": { "Signature": "5y22FzbLk7iTPQTs6kMuLEjd3P7YGmdNvWM21G4LkFU3pydps7ou9HTkAdw2qRZWTbXhebdEyLGrhgFMJTM7D1Fc", "Signer": "CreQJ2t94QK5dsxUZGXfPJ8Nx7wA9LHr5chxjSMkbNft" }, "Instruction": { "Accounts": [ { "Address": "F8FEvP6ekyGhDQLsKopD2qgD1j3qcYeYWJ1cWotJnGhn" }, { "Address": "CreQJ2t94QK5dsxUZGXfPJ8Nx7wA9LHr5chxjSMkbNft" }, { "Address": "12To3szF9J3gJGUwYkPJD6Y8efHt3TxD6dsz3fyCddYe" }, { "Address": "6jz3UuC5tKeYGt5FiX18LRDEeceDmC55jmn5cDUL8wh7" }, { "Address": "BWZYEPYehnLddXBa31LUo5yDv4ns1tC4RskLrnsqHYfR" }, { "Address": "2rXQvUwk9P2gQhzoPvVwNFhJAKnSsjoidrXFko2qrqZt" }, { "Address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" }, { "Address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }, { "Address": "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" }, { "Address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }, { "Address": "11111111111111111111111111111111" } ], "Program": { "Method": "fill", "Arguments": [ { "Name": "input_amount", "Type": "u64", "Value": { "bigInteger": "3298000943" } }, { "Name": "output_amount", "Type": "u64", "Value": { "bigInteger": "3300746136" } }, { "Name": "expire_at", "Type": "i64", "Value": { "bigInteger": "1785650286" } } ] } } } ``` `Transaction.Signer` is the fee payer. On the main deployment that is always the maker, which is how you detect gasless RFQ. See [who pays gas](#who-pays-for-the-transaction). :::warning This response does not name the tokens The mints are in there (positions 6 and 8, `EPjFWdd5…` and `Es9vMFrz…`) but you get base58, not symbols or decimals. Two ways to fix that: decode positionally against your own token list, or use [Instruction Balance Updates](#which-currencies-actually-moved), which returns `Currency` metadata and USD values directly. ::: ### Decoding a fill Positions 6 and 8 are the mints, positions 0 and 1 the counterparties. Applied to the response above: ```js const KNOWN = { So11111111111111111111111111111111111111112: { symbol: "SOL", decimals: 9 }, EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: { symbol: "USDC", decimals: 6 }, Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: { symbol: "USDT", decimals: 6 }, }; function decodeFill(node) { const accounts = node.Instruction.Accounts.map((a) => a.Address); const args = Object.fromEntries( node.Instruction.Program.Arguments.map((a) => [a.Name, BigInt(a.Value.bigInteger)]) ); const [taker, maker] = accounts; const tokenIn = KNOWN[accounts[6]] ?? { symbol: accounts[6].slice(0, 4), decimals: 9 }; const tokenOut = KNOWN[accounts[8]] ?? { symbol: accounts[8].slice(0, 4), decimals: 9 }; const amountIn = Number(args.input_amount) / 10 ** tokenIn.decimals; const amountOut = Number(args.output_amount) / 10 ** tokenOut.decimals; return { time: node.Block.Time, taker, maker, feePayer: node.Transaction.Signer, pair: `${tokenIn.symbol}/${tokenOut.symbol}`, amountIn, amountOut, price: amountOut / amountIn, quoteValidForSec: Number(args.expire_at) - Math.floor(Date.parse(node.Block.Time) / 1000), }; } ``` Output: ```js { time: '2026-08-02T05:57:11Z', taker: 'F8FEvP6ekyGhDQLsKopD2qgD1j3qcYeYWJ1cWotJnGhn', maker: 'CreQJ2t94QK5dsxUZGXfPJ8Nx7wA9LHr5chxjSMkbNft', feePayer: 'CreQJ2t94QK5dsxUZGXfPJ8Nx7wA9LHr5chxjSMkbNft', pair: 'USDC/USDT', amountIn: 3298.000943, amountOut: 3300.746136, price: 1.0008323809020816, quoteValidForSec: 55 } ``` A 3,298 USDC to USDT swap at 1.00083, on a quote with 55 seconds left to live. --- ## Which currencies actually moved If you would rather not decode positions yourself, query the balance updates attached to the same instruction. This returns `Currency` with symbol and decimals, a signed decimal `Amount`, and `AmountInUSD`. ```graphql query RFQFillsWithCurrency { Solana { InstructionBalanceUpdates( limit: { count: 40 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } Method: { is: "fill" } } } BalanceUpdate: { Currency: { Native: false } } } ) { Block { Time } Transaction { Signature } BalanceUpdate { Amount AmountInUSD Currency { Symbol Name MintAddress Decimals } Account { Address Token { Owner } } } } } } ``` One fill comes back as a readable four-row set. Negative is the sender, positive the receiver: | Symbol | Amount | AmountInUSD | Token.Owner | |---|---:|---:|---| | USD1 | -56.995411 | -56.937057 | `7mXZXgRT6LR8iA…` (taker) | | USDC | -56.943005 | -56.934574 | `CreQJ2t94QK5ds…` (maker) | | USD1 | 56.995411 | 56.937057 | `CreQJ2t94QK5ds…` (maker) | | USDC | 56.943005 | 56.934574 | `7mXZXgRT6LR8iA…` (taker) | :::caution Native SOL sides behave differently `Currency: { Native: false }` keeps the SPL token sides and drops lamport noise. When one side of the trade is native SOL, that side disappears from the results and you will see only the maker's WSOL row. Remove the filter to catch it, but expect a native SOL side to emit both a lamport movement and a WSOL token update for the same value. Do not sum them. ::: Pair this with the fill instruction when you need `expire_at`, which balance updates do not carry. --- ## Stream fills in real time Change `query` to `subscription` and drop the ordering. ```graphql subscription RFQFillStream { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } Method: { is: "fill" } } } } ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { Address Token { Mint Owner } } Program { Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` Both Jupiter Z deployments in one stream: ```graphql subscription AllJupiterZFills { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { in: [ "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" "2En5Y11SEAGLNmEezTuRUCwTyzyNReHaMbSnS5gjGsL1" ] } Method: { is: "fill" } } } } ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { Address } Program { Address Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` The same `decodeFill` function above works on each pushed message. ## The money flows The Transfers cube gives you two USD-denominated rows per fill. It cannot filter on the RFQ program directly, so filter on the makers instead, which works because the maker is the fee payer. :::caution Do not hard-code the maker set The addresses below are placeholders. The active maker set is small and it rotates, so pull it from the [maker leaderboard query](#maker-leaderboard-and-market-share) and substitute the current values rather than copying these. ::: ```graphql query RFQTransferLegs { Solana { Transfers( limit: { count: 20 } where: { Transaction: { # replace with the current maker set, see the maker leaderboard query Signer: { in: [ "CreQJ2t94QK5dsxUZGXfPJ8Nx7wA9LHr5chxjSMkbNft" "MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa" "FkaLnX17cXZGyeu3kZGdHCNdFMJJzBrPPYVvd18B3MZp" ] } Result: { Success: true } } } orderBy: { descending: Block_Time } ) { Block { Time } Transaction { Signature } Transfer { Amount AmountInUSD Currency { Symbol MintAddress Decimals } Sender { Address } Receiver { Address } } } } } ``` This also catches the maker's own hedging transactions, since those share the same fee payer. Join back to the `fill` instruction by signature if you need fills only. --- ## Filter fills by asset Account-level filtering uses `Accounts: { includes: { Address: ... } }`. Pass a mint and you get every fill where that token was on either side. ```graphql query RFQFillsForAsset { Solana { Instructions( limit: { count: 25 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } } Accounts: { includes: { Address: { is: "XsoCS1TfEyfFhfvj8EtZ528L3CaKBDBRqRapnBbDF2W" } } } } } ) { Block { Time } Transaction { Signature } Instruction { Accounts { Address } Program { Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` That mint is SPYx (SP500 xStock). Swap in TSLAx `XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB` or anything from the [mint reference](#mint-reference). For a stable-quoted pair, price is one line. With `input_mint` USDC (6 decimals) and `output_mint` TSLAx (9 decimals): ``` price_usd_per_share = (input_amount / 1e6) / (output_amount / 1e9) ``` Invert when the direction is reversed. Both amounts are exact and the quote was firm, so this is a genuine executed print rather than a mid or an estimate. --- ## Quote expiry: how long a maker commits `expire_at` minus block time gives the validity remaining at settlement. It is one of the few places where a market maker's risk appetite is legible on chain. ```graphql query QuoteExpiry { Solana { Instructions( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } Method: { is: "fill" } } } } ) { Block { Time } Instruction { Program { Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` Jupiter Z quotes are minted with roughly a minute of validity and typically land within a few seconds of issuance, so the remaining validity clusters just under the ceiling. Mayan Swift intents carry a `deadline` an order of magnitude longer, because a cross-chain fill has to survive settlement latency on the far side. Watch the distribution rather than any single fill. Compression in remaining validity is a volatility signal from professional makers, and it shows up before anything you can read off an AMM. --- ## Maker leaderboard and market share ```graphql query RFQMakerActivity { Solana { Instructions( limit: { count: 30 } orderBy: { descendingByField: "fills" } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } Method: { is: "fill" } } } } ) { Transaction { Signer } Block { firstSeen: Time(minimum: Block_Time) lastSeen: Time(maximum: Block_Time) } fills: count gasUsd: sum(of: Transaction_FeeInUSD) } } } ``` Since the maker pays the fee on the main deployment, grouping by `Transaction.Signer` gives you the maker leaderboard for free. No extra join, no address list to maintain. The active maker set is small (low tens) and turns over, so treat any specific roster as a result you generate rather than a constant. Two patterns hold up across runs and are worth building around: - **Fill count and notional rank differently.** The maker with the most fills is usually not the maker moving the most money. Rank by both, or you will mistake a dust book for a dominant one. - **Makers specialise by size.** Some quote block flow at thousands of dollars a fill, others run dust books averaging a few dollars or less. Dividing notional by fills separates them immediately, and the spread they charge tracks that split (see [execution quality](#execution-quality-in-basis-points)). Notional is not returned directly, so pair the query above with [Instruction Balance Updates](#which-currencies-actually-moved) and sum `AmountInUSD` per maker. --- ## Who pays for the transaction ```graphql query RFQFeePayer { Solana { Instructions( limit: { count: 10 } orderBy: { descendingByField: "txs" } where: { Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } Method: { is: "fill" } } } } ) { Transaction { Signer Result { Success } } txs: count(distinct: Transaction_Signature) totalFeeUsd: sum(of: Transaction_FeeInUSD) } } } ``` Compare the returned `Signer` set against the takers (account 0) and makers (account 1). The two deployments differ by design: - On `61DFfeTK…` the fee payer is the maker, on essentially every fill. The taker pays nothing, which is what makes the flow gasless. - On `2En5Y11S…` the maker never pays. The cost falls on the taker or on a relayer submitting for them. Either way the fee sits close to the base rate: two signatures worth of lamports plus a negligible priority fee. RFQ fills barely bid in the priority-fee auction, because a firm off-chain price leaves nothing to front-run. Compare that against any AMM route on the same chain and the difference is a couple of orders of magnitude. --- ## Execution quality in basis points You need two sources: the RFQ fill, and an AMM reference price for the same minute. Pull the RFQ prints with [Latest RFQ fills](#latest-rfq-fills) filtered to one pair, then compute `price = output/input` with decimals applied. Then pull the AMM reference: ```graphql query AmmReferencePrice { Solana { DEXTradeByTokens( limit: { count: 100 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Price PriceInUSD Amount AmountInUSD } } } } ``` For a taker buying the base asset, `bps = (ref - rfq_price) / ref * 10000`. Invert the sign when selling. Positive means the taker beat the AMM mid. ### What to expect from the result Run this on a liquid pair such as SOL/USDC and the shape of the answer is consistent, even though the exact basis points move with volatility and with which makers are active. :::warning RFQ is usually not cheaper than the AMM on price Expect the median RFQ fill to price a few basis points *worse* than the AMM mid, with only a small minority of fills beating it. That gap is the maker's spread, and on liquid pairs it runs several times the AMM's own effective spread at retail size. If you are benchmarking venues on price alone, RFQ loses. Verify with your own window rather than trusting a number published here. ::: The advantage sits at the two ends of the size distribution: - **Small trades.** Gasless settlement dominates. When the fee to send an AMM swap is a meaningful fraction of a small trade, and a third of those swaps have to be retried, a few bps of spread is cheap by comparison. - **Large trades.** AMM price impact grows with size while the maker's quoted spread stays roughly flat. Past a certain notional the pool costs more than the spread, and that crossover is the number worth measuring for your own sizes. - **In between.** Roughly a wash on price, and RFQ wins on certainty instead. Fill sizes reflect that: the distribution is a barbell, with a large count of very small fills and most of the notional carried by a handful of large ones. Compute the AMM side by bucketing `AmountInUSD` and taking the absolute deviation from the minute mid, so you get the crossover for the pair and period you actually trade. --- ## Landing rate Bitquery indexes failed transactions, so you can measure how many attempts actually settle. Drop the `Success` filter and group by result. ```graphql query LandingRateComparison { Solana { rfq: Instructions( limit: { count: 4 } where: { Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } } } } ) { Transaction { Result { Success } } txs: count(distinct: Transaction_Signature) } jupiterRoute: Instructions( limit: { count: 4 } where: { Instruction: { Program: { Address: { is: "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4" } Method: { in: ["route", "route_v2", "shared_accounts_route", "shared_accounts_route_v2"] } } } } ) { Transaction { Result { Success } } txs: count(distinct: Transaction_Signature) } solfi: Instructions( limit: { count: 4 } where: { Instruction: { Program: { Address: { is: "SV2EYYJyRz2YhfXwXnhNAevDEui5Q6yrfyo13WtupPF" } Method: { is: "swap" } } } } ) { Transaction { Result { Success } } txs: count(distinct: Transaction_Signature) } } } ``` The ordering this produces is stable even as the absolute counts change hour to hour. Off-chain-quoted settlement lands almost every time it is submitted, because the price was agreed before the transaction was built and nothing on chain can move underneath it. AMM routing does not: a large share of submitted swaps fail on slippage or on a stale pool, and oracle-priced proprietary AMMs fare worst of all because bots race to hit quotes that have already moved. Arbitrage-bot spam inflates the AMM failure counts, and a retail-only figure would look better. The fees on those failures are still real and still paid. If you are choosing what to route through, run this for your own venues and weigh the landing rate against the spread, because the gap between the two families is far larger than the few basis points separating their prices. --- ## Tokenized equities on RFQ Two issuers of tokenized equities are active on Solana: xStocks from Backed (symbols ending `x`) and Ondo Global Markets (ending `on`). Both are quoted by RFQ makers, but they trade very differently. - **xStocks trade in pools as well.** On 28 September 2026 the 15 xStocks tickers listed below saw about 390,000 trades on Raydium CLMM and Orca alone. - **Ondo tickers barely do.** The same day, all the Ondo tickers below together had 20 pool trades. For them, RFQ fills are close to the only price print on chain. With the RFQ fills in DEX trade data, you can pull them with `DEXTradeByTokens` and keep them apart from pool trades by filtering on `order_engine`: ```graphql query TokenizedEquityRFQTrades { Solana { DEXTradeByTokens( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Trade: { Dex: { ProtocolName: { is: "order_engine" } } Currency: { MintAddress: { in: [ "Xsc9qvGR1efVDFGLrVsmkzv3qi45LTBjeUKSPmx9qEh" "XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB" "gEGtLTPNQ7jcg25zTetkbmF7teoDLcrfTnQfmn2ondo" "KeGv7bsfR4MheC1CkmnAVceoApjrkvBhHYjWb67ondo" ] } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Currency { Symbol MintAddress } Amount PriceInUSD Side { Amount Currency { Symbol } } Market { MarketAddress } } } } } ``` The four mints are NVDAx, TSLAx, NVDAon and TSLAon. Drop the `ProtocolName` filter to see RFQ and pool trades side by side. Older fills are not in the trade tables. ### The cross-issuer spread Both issuers list several of the same underlyings (S&P 500, Nasdaq, Tesla, Alphabet, NVIDIA, Meta, Microsoft, Intel, Circle, SpaceX). Decode a fill from each and you get two independent prints of the same asset, quoted by two independent market makers. In practice they track each other closely, usually well inside a percent. That is a useful sanity check on your decoding: if `GOOGLx` and `GOOGLon` disagree by orders of magnitude, you have a decimals bug rather than an arbitrage. It is also a genuine cross-issuer spread you can stream, and the moments it widens are the interesting ones. ### Liquidity is concentrated Expect a handful of makers per issuer. In the first half hour of trade data, three makers quoted every xStocks RFQ fill and two quoted every Ondo fill. Resolve the current set from `Trade.Market.MarketAddress` (or account index 1 of the `fill` instruction) rather than hard-coding addresses, because that is exactly the kind of thing that rotates. For the Ondo tickers, which barely trade in pools, a maker that stops quoting means the ticker stops trading, so a per-issuer maker heartbeat is a worthwhile alert. A large part of this flow also lands outside US market hours, when the underlying is closed. The maker is pricing a shut market and carrying the overnight gap risk, which is one reason the spread here is wider than on a crypto pair. ### Mint reference | Symbol | Name | Mint | |---|---|---| | SPYx | SP500 xStock | `XsoCS1TfEyfFhfvj8EtZ528L3CaKBDBRqRapnBbDF2W` | | QQQx | Nasdaq xStock | `Xs8S1uUs1zvS2p7iwtsG3b6fkhpvmwz4GYU3gWAmWHZ` | | TSLAx | Tesla xStock | `XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB` | | NVDAx | NVIDIA xStock | `Xsc9qvGR1efVDFGLrVsmkzv3qi45LTBjeUKSPmx9qEh` | | GOOGLx | Alphabet xStock | `XsCPL9dNWBMvFtTmwcCA5v3xWPSMEBCszbQdiLLq6aN` | | METAx | Meta xStock | `Xsa62P5mvPszXL1krVUnU5ar38bBSVcWAB6fmPCo5Zu` | | MSFTx | Microsoft xStock | `XspzcW1PRtgf6Wj92HCiZdjzKCyFekVD8P5Ueh3dRMX` | | AMZNx | Amazon.com xStock | `Xs3eBt7uRfJX8QUs4suhyU8p2M6DoUDrJyWBa8LLZsg` | | AAPLx | Apple xStock | `XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp` | | COINx | Coinbase xStock | `Xs7ZdzSHLU9ftNJsii5fCeJhoRWSC32SQGzGQtePxNu` | | CRCLx | Circle xStock | `XsueG8BtpquVJX9LVLLEGuViXUungE6WmK5YZ3p3bd1` | | MSTRx | MicroStrategy xStock | `XsP7xzNPvEHS1m6qfanPUGjNmdnmsLKEoNAnHjdxxyZ` | | HOODx | Robinhood xStock | `XsvNBAYkrDRNhA7wPHQfX3ZUXZyZLdnCQDfHZ56bzpg` | | INTCx | Intel xStock | `XshPgPdXFRWB8tP1j82rebb2Q9rPgGX37RuqzohmArM` | | SPCXx | SpaceX xStock | `Xs3oZwbHvqis4NYcf4YKWmEia2eC84wSiVrcYcTqpH8` | | SPYon | SPDR S&P 500 ETF (Ondo) | `k18WJUULWheRkSpSquYGdNNmtuE2Vbw1hpuUi92ondo` | | QQQon | Invesco QQQ (Ondo) | `HrYNm6jTQ71LoFphjVKBTdAE4uja7WsmLG8VxB8ondo` | | TSLAon | Tesla (Ondo) | `KeGv7bsfR4MheC1CkmnAVceoApjrkvBhHYjWb67ondo` | | NVDAon | NVIDIA (Ondo) | `gEGtLTPNQ7jcg25zTetkbmF7teoDLcrfTnQfmn2ondo` | | GOOGLon | Alphabet Class A (Ondo) | `bbahNA5vT9WJeYft8tALrH1LXWffjwqVoUbqYa1ondo` | | METAon | Meta Platforms (Ondo) | `fDxs5y12E7x7jBwCKBXGqt71uJmCWsAQ3Srkte6ondo` | | MSFTon | Microsoft (Ondo) | `FRmH6iRkMr33DLG6zVLR7EM4LojBFAuq6NtFzG6ondo` | | AAPLon | Apple (Ondo) | `123mYEnRLM2LLYsJW3K6oyYh8uP1fngj732iG638ondo` | | AMDon | AMD (Ondo) | `14diAn5z8kjrKwSC8WLqvBqqe5YmihJhjxRxd8Z6ondo` | | AVGOon | Broadcom (Ondo) | `1FWZtdWN7y38BSXGzbs8D6Shk88oL9atDNgbVz9ondo` | | ARMon | Arm Holdings plc (Ondo) | `15SsCZqCsM9fZGhTmP4rdJTPT9WGZKazDSsgeQ8ondo` | | CRCLon | Circle Internet Group (Ondo) | `6xHEyem9hmkGtVq6XGCiQUGpPsHBaoYuYdFNZa5ondo` | | INTCon | Intel (Ondo) | `cJpUMp5R7rZ6fGeLHbHhrRuJzK9mkyKDjZqNpT3ondo` | | MUon | Micron Technology (Ondo) | `Fz9edBpaURPPzpKVRR1A8PENYDEgHqwx5D5th28ondo` | | MRVLon | Marvell Technology (Ondo) | `FovBwhoV5KQjZCdhoM6jgXYwXLX3F8vgAfvmLH7ondo` | | SKHYon | SK Hynix (Ondo) | `Huyb2fyDDjSuDKCRWsN9ci2rmcgPo6NFiLbx9ZDondo` | | SNDKon | SanDisk (Ondo) | `EJmUVvDqAdfH5zEohkdS4234bi3c6iunqEMobjmondo` | | SPCXon | SpaceX (Ondo) | `wzAyQTorWyoVXuJKj2x8EqKEGJpS13z6EWE9z5Aondo` | | TSMon | Taiwan Semiconductor (Ondo) | `keybg184d4vyXeQdFqs4o99YsMg7xBthxTJ6Ky3ondo` | | GLWon | Corning (Ondo) | `YQzNQh2YSFQ6nh91E8Ja71U6JuZDLap5jJCsELGondo` | | USDon | Ondo US Dollar Token | `ZPFtoCe7WWqG4N3ZFRccS8T9SMBeHsd1Vmgv2i7ondo` | All Ondo mints use 9 decimals. The [xStocks API page](/docs/blockchain/Solana/xstocks-api) covers the pool-traded side of these assets. ### What else trades on RFQ Aggregate `AmountInUSD` from [Instruction Balance Updates](#which-currencies-actually-moved) grouped by currency pair and the mix is consistently unlike the Solana DEX tape. SOL against the majors leads, but a large block of volume is **stablecoin to stablecoin** (USDC/USDT and the newer dollar tokens), with wrapped BTC and ETH, a handful of large-cap tokens, and the tokenized equities making up the rest. Long-tail memecoin churn is largely absent. That mix is the signature of professional treasury and inventory flow rather than retail speculation, and it is the main reason RFQ notional looks small next to DEX notional while being far more concentrated per fill. --- ## Jupiter Limit Order v2 Resting orders rather than quotes, but the fill path has the same shape (`taker`, `maker`, `order`). ```graphql query JupiterLimitOrders { Solana { Instructions( limit: { count: 20 } orderBy: { descendingByField: "cnt" } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "j1o2qRpjcyUwEvwtcfhEQefh773ZgjxcVRry7LDqg5X" } Method: { in: ["initialize_order", "fill_order", "cancel_order"] } } } } ) { Instruction { Program { Method } } Transaction { Signer } cnt: count signers: count(distinct: Transaction_Signer) } } } ``` Two things fall out of that grouping and both are structural. Orders are cancelled far more often than they are filled, so treat `initialize_order` as intent rather than volume. And while many distinct makers create orders, the `fill_order` signer set collapses to a single Jupiter-operated keeper, which makes the fill path a single point of failure worth monitoring separately from the orders themselves. --- ## Mayan Swift: cross-chain intents Solana is both a source and a destination here. `init_order` starts an outbound intent, while `fulfill` and `settle` complete an inbound one. ```graphql query MayanSwiftIntents { Solana { Instructions( limit: { count: 20 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "mayan34VedncxdK2XobtvWFDXQASUTBXhUVzt2kKgny" } Method: { is: "init_order" } } } } ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { Address } Program { Method AccountNames Arguments { Name Type Value { ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` The `InitOrderParams` JSON carries the complete intent: ``` amount_in_min, amount_out_min user's limit price chain_dest, token_out destination chain (Wormhole chain id) and token deadline intent expiry (minutes, not seconds) gas_drop destination gas top-up fee_cancel, fee_refund failure-path economics addr_ref, fee_rate_ref referrer address and referral fee rate fee_rate_mayan protocol fee rate auction_mode auction type ``` `addr_ref` and `fee_rate_ref` together give you per-integrator revenue attribution: which frontend sourced the order, and what it earned. Outbound and inbound flows run at broadly similar rates, so Solana is a genuine two-way hub rather than mostly an exit. Decode `chain_dest` against Wormhole chain ids to get the current destination mix; the major EVM chains dominate it. :::note Solver concentration The trader side of Mayan is wide, with a distinct signer on almost every order. The solver side is not: fulfils come from a very small set of driver addresses, typically with one taking the large majority. Track drivers with account index 1 on `fulfill` and alert on that set shrinking, because it is the part of the system with the least redundancy. ::: To stream cross-chain flow leaving Solana: ```graphql subscription MayanOutboundIntents { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "mayan34VedncxdK2XobtvWFDXQASUTBXhUVzt2kKgny" } Method: { is: "init_order" } } } } ) { Block { Time } Transaction { Signature } Instruction { Accounts { Address } Program { Arguments { Name Value { ... on Solana_ABI_Json_Value_Arg { json } } } } } } } } ``` --- ## The on-chain quote tape Several proprietary market makers publish quote updates as top-level instructions that move zero tokens. They are not trades and appear in no trade table, yet they are the highest-frequency structured data on Solana. Use `Instruction.Depth` to tell them apart. Depth `0` is a standalone quote update. Depth `1` or deeper is a CPI from an aggregator router, meaning a real swap. ```graphql query QuoteTapeVsFills { Solana { Instructions( limit: { count: 10 } orderBy: { descendingByField: "cnt" } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "9H6tua7jkLhdm3w8BvgpTn5LZNU7g4ZynDmCiNN3q6Rp" } } } } ) { Instruction { Depth } cnt: count signers: count(distinct: Transaction_Signer) } } } ``` Swap the program address for any venue in [Family 2](#family-2-proprietary-market-maker-amms) and the depth-0 to depth-1 ratio sorts them into two architectures: - **Quote-posting.** Depth-0 instructions vastly outnumber routed fills, often by an order of magnitude. HumidiFi, Tessera V, QuantumAMM, Aquifer and BisonFi work this way (Scorch does the same through its separate price program), and the busiest of them emit updates at a rate measured in millions per day. This is a live market-maker quote feed sitting on chain, and it exists in no trade table. - **Oracle-at-swap.** Little or no depth-0 traffic, because the venue prices from an oracle at execution time. SolFi, GoonFi, ZeroFi and AlphaQ sit here. There is nothing to watch until a trade lands. The `signers` count is the second tell. A venue running its whole quote feed from a single signer is a different operational risk from one spreading it across dozens. :::caution Quote updates are not decoded Bitquery decodes the swaps on HumidiFi, Tessera V, QuantumAMM and Scorch (methods such as `swap`, `swap2`, `swapV3` and `swap2022`). Their quote updates still arrive undecoded, as raw `Instruction.Data` with `Program.Parsed: false`, and ZeroFi has no IDL at all. You can still measure how often each maker updates, and from which signer. ::: --- ## Notes on method This page deliberately states patterns and gives you the queries, rather than publishing point in time statistics that go stale. A few things to get right when you run them yourself: - **Value the stablecoin side.** For notional, take the stablecoin side at $1 where one exists and fall back to the SOL side otherwise. `AmountInUSD` on [Instruction Balance Updates](#which-currencies-actually-moved) already does this for you. - **Prefer medians for reference prices.** `average(of: Trade_PriceInUSD)` is badly skewed on thin pairs and will hand you a SOL price that is tens of percent wrong. Use a median over a liquid pair instead. - **A minute-median AMM price approximates the mid**, not a same-block quote. It is good enough for spread work on liquid pairs and misleading on illiquid ones. - **Size buckets need volume.** The interesting crossover sits above $100k, where fills are rare. Widen the window before drawing conclusions about large size. - **AMM landing rates include bot traffic.** A retail-only figure is higher. Compare like with like if you are using it to justify a routing decision. One open item: the second `order_engine` deployment is identified here from a shared maker set and matching IDL, not from protocol documentation. --- ## Related - [Solana Instructions API](/docs/blockchain/Solana/solana-instructions), the cube most queries here use - [Instruction Balance Updates](/docs/blockchain/Solana/solana-instruction-balance-updates), for currency and USD on each side of a fill - [Solana Transfers API](/docs/blockchain/Solana/solana-transfers) - [Solana Jupiter API](/docs/blockchain/Solana/solana-jupiter-api), the aggregator and routing side - [Tokenized Stocks API (xStocks)](/docs/blockchain/Solana/xstocks-api), pool-traded tokenized equities - [SolFi API](/docs/blockchain/Solana/SolFi-api) and [GoonFi API](/docs/blockchain/Solana/goonfi-api) - [Solana DEX Orders API](/docs/blockchain/Solana/Solana-DEX-Orders-API), limit-order book data --- ## Solana Shred Stream: Kafka Topics, Latency and How to Connect URL: https://docs.bitquery.io/docs/streams/solana-shred-streams/ Bitquery Solana Shred Stream over Kafka: shred-level transactions, DEX trades and token transfers before block confirmation. Topics, latency compared with gRPC and GraphQL, and connection setup. # Solana Shred Stream The Bitquery Solana Shred Stream delivers Solana transactions, DEX trades and token transfers over Kafka as soon as validators propagate the shreds that carry them. This happens before the block closes. Every message is parsed protobuf, with USD values added. You do not run a node and you do not decode raw shreds yourself. ## What is a Solana shred? On Solana, a shred is the smallest piece of a block. The leader splits the entries it produces into shreds and sends them to other validators through Turbine. Validators rebuild the block from those shreds. Shreds are the first form block data takes on the network, so data read at this stage arrives earlier than data read after the block is complete. Bitquery reads transactions at the shred level, parses them, and publishes them to Kafka. Because messages go out before the block closes: - transactions can arrive before the block is finalized; - the block header in a message may be incomplete; only `Slot` is guaranteed to be set; - messages are not guaranteed to arrive in slot order, and duplicates can occur, so deduplicate on transaction signature. ## Solana Shred Stream topics Three Kafka topics carry shred-level Solana data. All of them are protobuf. The schema is in [streaming_protobuf/solana](https://github.com/bitquery/streaming_protobuf/tree/main/solana). | Topic | Message type | What it carries | |---|---|---| | `solana.transactions.proto` | `ParsedIdlBlockMessage` | Transactions, parsed instructions, logs, instruction-level balance updates | | `solana.tokens.proto` | `TokenBlockMessage` | Token and SOL transfers, supply changes, account and instruction balance updates | | `solana.dextrades.proto` | `DexParsedBlockMessage` | DEX trades, order events and liquidity pool changes for Pump.fun, PumpSwap, Raydium, Meteora, Orca and other venues | Amounts carry USD equivalents (`AmountInUSD`, `FeeInUSD`, `PostBalanceInUSD` and similar). The full field reference is on the [Solana protobuf stream page](/docs/streams/protobuf/chains/Solana-protobuf). Perpetual futures are on a separate topic, the [Solana perpetuals stream](/docs/streams/protobuf/chains/Solana-perpetual-protobuf). ## Solana Shred Stream latency compared with gRPC and GraphQL Bitquery delivers real-time Solana data in three ways. All three read from the same pipeline. They differ in transport, filtering and how much data reaches you. | | Kafka Shred Stream | gRPC (CoreCast) | GraphQL subscription | |---|---|---|---| | Transport | Kafka, protobuf | gRPC, protobuf | WebSocket, JSON | | Server-side filtering | No, full topic | Yes, by address, program and token | Yes, full GraphQL filters | | Replay | From an offset within the 4-hour retention | No | No | | Runs in a browser | No | No | Yes | | Best for | Trading systems, indexers, consumers that cannot miss a message | Low-latency feeds filtered to a few programs or wallets | Prototypes, dashboards, filtered alerts | This was measured on Solana token transfers, with `solana.tokens.proto` and a GraphQL subscription consumed at the same time from the same server. Latency runs from block timestamp to application code: | | p50 | p99 | |---|---|---| | Kafka (`solana.tokens.proto`) | 383 ms | 1847 ms | | WebSocket (GraphQL subscription) | 405 ms | 2013 ms | Kafka arrived first for 77% of slots. Broker-to-consumer delivery alone was 17 ms at p50. Kafka also sends the complete message, about 33 times more bandwidth than a subscription that requests only some fields. The full method is on the [Kafka streaming concepts page](/docs/streams/kafka-streaming-concepts#measured-latency-kafka-vs-graphql-subscription). If you need a narrow, filtered feed, the [Solana gRPC streams](/docs/grpc/solana/introduction/) filter on the server and send less data. ## How to connect to the Solana Shred Stream 1. Get Kafka credentials from sales through the [official Telegram](https://t.me/Bloxy_info) or the [website form](https://bitquery.io/forms/api). IDE tokens do not work on Kafka. 2. Connect to the brokers `rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092` with SASL `SCRAM-SHA-512`. Port `9093` is the SSL variant. 3. Use a consumer group ID that starts with your username. 4. Subscribe to one of the three topics and parse messages with the [bitquery-pb2-kafka-package](https://pypi.org/project/bitquery-pb2-kafka-package/) for Python, or with the generated protobuf classes in Go or JavaScript. ```python from confluent_kafka import Consumer from solana import dex_block_message_pb2 conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092', 'security.protocol': 'SASL_PLAINTEXT', 'sasl.mechanism': 'SCRAM-SHA-512', 'sasl.username': 'YOUR_USERNAME', 'sasl.password': 'YOUR_PASSWORD', 'group.id': 'YOUR_USERNAME-shred', 'auto.offset.reset': 'latest', } consumer = Consumer(conf) consumer.subscribe(['solana.dextrades.proto']) while True: msg = consumer.poll(1.0) if msg is None or msg.error(): continue block = dex_block_message_pb2.DexParsedBlockMessage() block.ParseFromString(msg.value()) for tx in block.Transactions: for trade in tx.Trades: print(block.Header.Slot, trade.Dex.ProtocolName, trade.Buy.Currency.Symbol, trade.Sell.Currency.Symbol) ``` Read all partitions in parallel and keep the poll loop running. Messages for one slot share a partition. Messages stay on the broker for 4 hours. Full consumer guides: [Python](/docs/streams/protobuf/kafka-protobuf-python), [Go](/docs/streams/protobuf/kafka-protobuf-go), [JavaScript](/docs/streams/protobuf/kafka-protobuf-js). For offsets and lag, see the [Kafka operations cookbook](/docs/streams/kafka-operations). ## Preview the data with a GraphQL subscription The same DEX trades are available as a GraphQL subscription, so you can inspect the data in the [Bitquery IDE](https://ide.bitquery.io/) before you request Kafka access. This stream returns Pump.fun trades: ```graphql subscription { Solana { DEXTrades(where: { Trade: { Dex: { ProtocolName: { is: "pump" } } } }) { Block { Time Slot } Transaction { Signature } Trade { Dex { ProtocolName } Buy { Amount Currency { Symbol MintAddress } } Sell { Amount Currency { Symbol MintAddress } } } } } } ``` In the Kafka topic, the same trades are `DexTradeEvent` records in `solana.dextrades.proto`, with `Dex.ProtocolName` set to `pump`. ## Video tutorials - [Low-latency Solana data via Kafka](https://youtu.be/8Qo3NNC1zec) - [Track Pump.fun and PumpSwap trades with Kafka](https://youtu.be/UlqZ8DgzNLc) ## Related pages - [Solana protobuf stream field reference](/docs/streams/protobuf/chains/Solana-protobuf) - [Real-time Solana data: Geyser, GraphQL and Kafka compared](/docs/streams/real-time-solana-data) - [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts) - [Solana gRPC streams (CoreCast)](/docs/grpc/solana/introduction/) - [Filtering Kafka streams](/docs/streams/protobuf/filtering_kafka_streams) --- ## Solana Shred Streams URL: https://docs.bitquery.io/docs/streams/protobuf/chains/Solana-protobuf/ Solana Shred Streams with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. See examples in the Bitquery IDE. # Solana Shred Streams This section provides details about Bitquery's Solana Shred Streams via Kafka. The top-level Kafka section explains how we use Kafka Streams to deliver data. You can find the schema [here](https://github.com/bitquery/streaming_protobuf/tree/main/solana). Remember that Solana blocks are produced with a target block time of 400ms, in practice resulting in high throughput of approximately 4,000 transactions per second while achieving a theoretical maximum of 65,000 transactions per second (TPS). :::info USD Values All amounts in the Solana protobuf streams now include USD equivalents — token transfer amounts, DEX trade sides, transaction fees, and balance updates each carry an `...InUSD` field (e.g. `AmountInUSD`, `FeeInUSD`, `PostBalanceInUSD`). These are populated in real time on the streams. ::: ## Structure of On-Chain Data The Solana Protobuf Streams provide three main message types for different use cases: - `BlockMessage`: Basic blocks, transactions, and rewards - `TokenBlockMessage`: Focused on token transfers and currency metadata - `DexParsedBlockMessage`: Specialized for DEX (Decentralized Exchange) activity Perpetual futures activity has its own topic, `solana.perpetual.proto` (`PerpetualBlockMessage`) — documented on the [Solana Perpetuals Stream](/docs/streams/protobuf/chains/Solana-perpetual-protobuf) page. ### Block-Level Data Each block in the stream includes a `BlockHeader` with fields such as: - `Slot`: The slot number for this block - `Hash`: The unique identifier of the block - `ParentSlot`: The previous slot in the chain - `Height`: The block height - `Timestamp`: The Unix timestamp when this block was produced - `ParentHash`: The hash of the parent block ### Transaction-Level Data Transactions across all stream types share common elements: - `Signature`: The transaction's unique signature - `Status`: The execution status (Success/Error) - `Header`: Transaction metadata including fees and signers - `FeeInUsd`: Equivalent transaction fee in US dollars - `Index`: Position within the block #### Transaction Header The `Header` (`TransactionHeader`) carries: - `Fee`: Transaction fee in lamports - `FeePayer`: Account that paid the fee - `RecentBlockhash`: Blockhash the transaction was built against - `Signer`: Primary signer - `Signatures`: All transaction signatures - `Accounts`: Accounts referenced by the transaction (address, signer/writable flags, token info) - `TransactionConfig`: Execution parameters for V1 transactions (see below) #### V1 Transactions: `TransactionConfig` Solana V1 transactions store execution parameters in a dedicated message field instead of ComputeBudget program instructions. Bitquery exposes them in `Header.TransactionConfig`: | Field | Type | Description | | ----------------------------- | ------ | -------------------------------------------- | | `PriorityFee` | uint64 | Priority fee set for the transaction | | `ComputeUnitLimit` | uint32 | Maximum compute units the transaction can use | | `LoadedAccountsDataSizeLimit` | uint32 | Maximum size of account data that can be loaded | | `HeapSize` | uint32 | Requested heap size | All four fields are optional. - **V1 transactions:** `TransactionConfig` is set, and it is the **only** place these values appear. - **Legacy and V0 transactions:** `TransactionConfig` is **unset**. Read these values from the ComputeBudget program instructions in the instruction list, as before. :::tip To get priority fees or compute limits across all transaction versions, check `Header.TransactionConfig` first. If it is not set, fall back to decoding ComputeBudget instructions. ::: ```python from solana import block_message_pb2 def print_tx_config(raw_bytes: bytes): block = block_message_pb2.BlockMessage() block.ParseFromString(raw_bytes) for tx in block.Transactions: if tx.Header.HasField("TransactionConfig"): cfg = tx.Header.TransactionConfig print(tx.Signature.hex(), "priority fee:", cfg.PriorityFee, "compute unit limit:", cfg.ComputeUnitLimit) else: # Legacy / V0: decode ComputeBudget instructions instead pass ``` Use `bitquery-pb2-kafka-package` version 0.2.34 or later to get this field in Python. Transactions contain various types of instructions, which are the core of Solana's execution model: - `ProgramAccountIndex`: The program being called - `Data`: Encoded instruction data - `AccountIndexes`: Accounts referenced by this instruction - `BalanceUpdates`: SOL balance changes from this instruction ### Token Data The `TokenBlockMessage` stream provides detailed information about token transfers and balances: - `Transfer`: Records token movements with: - `Amount`: Number of tokens transferred - `Sender`: Source account - `Receiver`: Destination account - `Authority`: Account authorizing the transfer - `Currency`: Detailed token information - `AmountInUSD`: USD value of the transferred amount - `Currency`: Rich metadata for each token, including: - `Name`, `Symbol`, `Decimals` - `MintAddress`: Token's mint account - `MetadataAddress`: Metadata program account - `TokenCreators`: Original creators of the token - NFT properties like `SellerFeeBasisPoints` and `TokenStandard` - `PriceInUSD`: Current USD price of the token - `TotalSupplyInUSD`: USD value of the token's total supply The `solana.tokens.proto` topic uses this message type to share details of: #### Account Addresses - These are listed under the "Accounts" section of the transaction header. #### Balance Updates - These are listed under "BalanceUpdates", with each update linked to an account using the `AccountIndex`. - Each balance update has: - **PreBalance:** The balance of the account before the transaction. - **PostBalance:** The balance of the account after the transaction. - **Currency Details:** Information about the currency type (e.g., Solana (SOL), Wrapped Solana (WSOL)). - **PreBalanceInUSD / PostBalanceInUSD:** USD value of the balance before and after the transaction. #### Balance Updates After Each Instruction - These updates are shown under the "BalanceUpdates" section within each instruction of the transaction. - These updates reflect the immediate effect of an instruction on the balance of the involved wallets. - For example, if an instruction transfers a certain amount from one wallet to another, the balance update directly after this instruction will reflect the new balances for both wallets. #### Balance Updates After the Entire Transaction - These updates are shown under the "BalanceUpdates" section at the transaction level. - They show the final state of the balances after all instructions in that transaction have been executed. - This is essentially the final balance state of all wallets involved in that transaction. ### DEX (Decentralized Exchange) Data The `DexParsedBlockMessage` stream is specialized for decentralized exchange activity. Each transaction in this stream contains `Trades`, `OrderEvents`, and `PoolEvents` arrays, along with transaction-level balance summaries. #### DexInfo Details about the exchange program: - `ProgramAddress`: Address of the DEX program - `ProtocolName`: Name of the DEX (e.g., "cp_amm", "pump_amm") - `ProtocolFamily`: Family of DEX protocols (e.g., "Meteora", "Pumpswap", "Raydium") #### DexTradeEvent Records of trades executed on DEXs, including full instruction-level data: - `InstructionIndex`: Position of the instruction within the transaction - `Dex`: The `DexInfo` for this trade - `Market`: The trading pair information - `MarketAddress`: Pool/market address - `BaseCurrency` / `QuoteCurrency`: Detailed currency metadata for both sides of the pair (Name, Symbol, Decimals, MintAddress, MetadataAddress, TokenStandard, Uri, etc.) - `Buy` / `Sell`: Both sides of the trade, each containing: - `Amount`: Raw token amount (in the token's smallest unit) - `AmountInUsd`: USD value of the trade side - `Currency`: Detailed token metadata (Name, Symbol, Decimals, MintAddress, MetadataAddress, TokenStandard, etc.) - `Account`: The token account involved (Address, IsSigner, IsWritable) with an optional `Token` sub-object containing `Mint`, `Owner`, `Decimals`, `ProgramId`, and `Supply` - `Order`: Linked DEX order information when the trade fills a specific limit order (see `DexOrder` below) - `Fee`: DEX trading fee in the quote currency's smallest unit - `Royalty`: Creator royalties paid (in the quote currency's smallest unit) - `Instruction`: Full `ParsedIdlInstruction` containing: - `Program`: Parsed IDL program info (Address, Name, Method, Signature, Arguments with Name/Type/Json, and the full IDL JSON) - `AccountNames`: Ordered list of account names from the IDL - `Accounts`: Account details with token sub-objects (Mint, Owner, Decimals, ProgramId, Supply) - `Logs`: Program logs emitted during execution - `BalanceUpdates`: Native SOL balance changes caused by this instruction (with `AccountIndex`, `PreBalance`, `PostBalance`) - `TokenBalanceUpdates`: SPL token balance changes caused by this instruction (with `AccountIndex`, `PreBalance`, `PostBalance`) - `AncestorIndexes`, `CallerIndex`, `ExternalSeqNumber`, `InternalSeqNumber`, `Depth`: Instruction hierarchy and sequencing metadata - `Data`: Raw encoded instruction data #### DexOrderEvent Records of DEX order lifecycle events (open, update, cancel). Each event contains: - `InstructionIndex`: Position of the instruction within the transaction - `Type`: Order event type — `OPEN`, `UPDATE`, or `CANCEL` - `Dex`: The `DexInfo` for this order - `Market`: The trading pair information - `Order`: The `DexOrder` details: - `OrderId`: Unique identifier for the order - `BuySide`: Whether this is a buy (true) or sell (false) order - `LimitPrice`: Limit price set for the order - `LimitAmount`: Amount of tokens in the order - `LimitPriceInUsd` / `LimitAmountInUsd`: USD equivalents - `Account`: Token account for the order - `Owner`: Wallet that owns the order - `Payer`: Fee payer for the order transaction - `Mint`: Token mint address - `Instruction`: Full `ParsedIdlInstruction` (same structure as in `DexTradeEvent`) #### PoolLiquidityChangeEvent Records changes to liquidity pools (adds, removes, swaps that change pool reserves): - `InstructionIndex`: Position of the instruction within the transaction - `Dex`: The `DexInfo` for this pool - `Market`: The trading pair information - `BaseCurrency` / `QuoteCurrency`: Each side contains: - `ChangeAmount`: Amount added (positive) or removed (negative) - `PostAmount`: Pool balance after the change - `ChangeAmountInUsd` / `PostAmountInUsd`: USD equivalents - `Instruction`: Full `ParsedIdlInstruction` (same structure as in `DexTradeEvent`) - `Price`: the pool's own price after the event, as a `PoolPrice` message (field 7, from `streaming_protobuf v2.6.6`). It is nil when the event carries no price, so keep the pool's last priced event. - `Price`: quote per base in UI units, oriented as `Market.BaseCurrency` / `Market.QuoteCurrency` - `PriceInUSD`: `Price` × the quote currency's USD rate at that block. `0` when the quote has no rate - `Source`: `event` (read from the venue's swap or creation event) or `reserves` (quote reserve over base reserve of a constant-product pool) Consumers built on an older proto ignore field 7 and keep working. See [Solana Liquidity Pool Price API](/docs/blockchain/Solana/solana-pool-price) for which venues carry a price and how to read it. #### Transaction-Level Balance Summaries In addition to per-event balance updates, each `ParsedDexTransaction` includes aggregate balance summaries: - `TotalBalanceUpdates`: Aggregate native SOL (lamports) balance changes across all instructions in the transaction - `TotalTokenBalanceUpdates`: Aggregate SPL/Token-2022 token balance changes across all instructions in the transaction - `FeeInUsd`: USD value of the total transaction fee ### Using This Stream in Python, JavaScript, and Go Python, JavaScript, and Go code samples can be used with these streams by changing the topic to one of: The below is the topic -> message mapping : - `solana.transactions.proto` -> `ParsedIdlBlockMessage` - `solana.tokens.proto` -> `TokenBlockMessage` - `solana.dextrades.proto` -> `DexParsedBlockMessage` The Python package [bitquery-pb2-kafka-package](https://pypi.org/project/bitquery-pb2-kafka-package/) includes all schema and is up to date so you don't have to manually install schema files. ## Video Tutorial to Get Low Latency Solana Data via Kafka ## Video Tutorial to Get Real-time PumpSwap Trades via Bitquery Kafka Streams --- ## Solana Sniper Bot URL: https://docs.bitquery.io/docs/usecases/solana-sniper-bot/ Build Solana Sniper Bot: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. See examples in the Bitquery IDE. # Tutorial for Building a Solana Sniper Bot Using Bitquery Real-Time Solana Subscriptions and Jupiter Swap API This tutorial will guide you through building a Solana sniper bot using Bitquery for real-time Solana subscriptions and the Jupiter Swap API for executing swaps. By the end of this guide, you'll have a bot that listens for specific on-chain instructions and performs token swaps based on the detected instructions. > Note: This material is for educational and informational purposes only and is not intended as investment advice. The content reflects the author's personal research and understanding. While specific investments and strategies are mentioned, no endorsement or association with these entities is implied. Readers should conduct their own research and consult with qualified professionals before making any investment decisions. Bitquery is not liable for any losses or damages resulting from the application of this information. ## Tutorial Video ## Tutorial ### Prerequisites Before you begin, ensure you have the following: 1. **Node.js** and **npm** installed on your system (follow instructions [here](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)). 2. **Bitquery Free Developer Account** with OAuth token (follow instructions [here](/docs/authorization/how-to-generate/)). 3. **Solana Wallet** with some SOL for transaction fees. ### Step 1: Setting Up the Environment 1. **Initialize a new Node.js project:** ```bash mkdir solana-sniper-bot cd solana-sniper-bot npm init -y ``` 2. **Install the necessary dependencies:** ```bash npm install @solana/web3.js cross-fetch lodash @project-serum/anchor bs58 ``` ### Step 2: Creating the Bot 1. **Create a new file `index.js`:** ```bash touch index.js ``` 2. **Add the necessary imports:** ```javascript const { Connection, PublicKey, VersionedTransaction, Keypair, } = require("@solana/web3.js"); const fetch = require("cross-fetch"); const lodash = require("lodash"); const { Wallet } = require("@project-serum/anchor"); const bs58 = require("bs58"); ``` 3. **Define the Solana Instructions GraphQL query for Bitquery:** This query fetches new liquidity pools created on the Solana Raydium DEX along with token information. For detailed information on the Raydium API, check examples [here](/docs/blockchain/Solana/Solana-Raydium-DEX-API/) ```javascript const gql = (strings, ...values) => strings.reduce((final, str, i) => final + str + (values[i] || ""), ""); const query = gql` { Solana { Instructions( where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Method: { is: "initializeUserWithNonce" } Address: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } } } limit: { count: 1 } orderBy: { ascending: Block_Date } ) { Instruction { Accounts { Address } } } } } `; ``` Note: For real-time tracking of new tokens, use the subscription query below: ```javascript subscription { Solana { Instructions( where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Method: {is: "initializeUserWithNonce"}, Address: {is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"}}}} ) { Instruction { Accounts { Address } } } } } ``` 4. **Set up the Solana connection and wallet:** ```javascript const connection = new Connection("https://api.mainnet-beta.solana.com"); const walletPublicKey = new PublicKey("YOUR_PUBLIC_KEY"); const secretKeyUint8Array = new Uint8Array([/* YOUR_SECRET_KEY_ARRAY */]); const wallet = new Wallet(Keypair.fromSecretKey(secretKeyUint8Array)); ``` 5. **Define a function to fetch data from Bitquery:** ```javascript async function fetchGraphQL(query) { const response = await fetch("https://streaming.bitquery.io/graphql", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer YOUR_BITQUERY_OAUTH_TOKEN", }, body: JSON.stringify({ query }), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } ``` 6. **Fetch pool addresses from Bitquery:** ```javascript async function getPoolAddresses() { try { const data = await fetchGraphQL(query); const instructions = lodash.get(data, "data.Solana.Instructions", []); return instructions.map(({ Instruction: { Accounts } }) => ({ poolAddress: Accounts.length > 4 ? Accounts[4].Address : undefined, tokenA: Accounts.length > 8 ? Accounts[8].Address : undefined, tokenB: Accounts.length > 9 ? Accounts[9].Address : undefined, }))[0]; } catch (error) { console.error("Error fetching data:", error); return { poolAddress: "", tokenA: "", tokenB: "" }; } } ``` 7. **Execute a token swap using Jupiter API:** This code has been derived from sample mentioned in the official docs [here](https://dev.jup.ag/docs/swap/). We add checks for "TOKEN_NOT_TRADABLE" and "COULD_NOT_FIND_ANY_ROUTE" to accommodate delays in the Jupiter Swap API. ```javascript async function swapTokens(tokenA, tokenB) { try { const quoteUrl = `https://quote-api.jup.ag/v6/quote?inputMint=${tokenB}&outputMint=${tokenA}&amount=10000&slippageBps=150`; console.log("quote url ", quoteUrl); const quoteResponse = await fetch(quoteUrl); const quoteData = await quoteResponse.json(); if ( quoteData["errorCode"] != "TOKEN_NOT_TRADABLE" && quoteData["errorCode"] != "COULD_NOT_FIND_ANY_ROUTE" ) { const swapTransactionResponse = await fetch( "https://quote-api.jup.ag/v6/swap", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ quoteResponse: quoteData, userPublicKey: wallet.publicKey.toString(), wrapAndUnwrapSol: true, }), } ); const { swapTransaction } = await swapTransactionResponse.json(); const swapTransactionBuf = Buffer.from(swapTransaction, "base64"); console.log("swapTransactionBuf ", swapTransactionBuf); const transaction = VersionedTransaction.deserialize(swapTransactionBuf); transaction.sign([wallet.payer]); const rawTransaction = transaction.serialize(); const txid = await connection.sendRawTransaction(rawTransaction, { skipPreflight: false, maxRetries: 4, preflightCommitment: "confirmed", commitment: "confirmed", }); const confirmation = await connection.confirmTransaction( txid, "confirmed" ); console.log( `Transaction confirmed: ${confirmation.value.err ? "Error" : "Success"}` ); console.log(`Transaction successful: https://solscan.io/tx/${txid}`); } } catch (error) { console.error("Error during token swap:", error); } } ``` 8. **Define the main function to coordinate the steps:** ```javascript async function main() { const { tokenA, tokenB } = await getPoolAddresses(); await swapTokens(tokenA, tokenB); } main(); ``` ### Step 3: Running the Bot 1. **Replace placeholders:** - Replace `YOUR_PUBLIC_KEY` with your actual Solana wallet public key. - Replace `YOUR_SECRET_KEY_ARRAY` with your wallet's secret key array. - Replace `YOUR_BITQUERY_OAUTH_TOKEN` with your actual Bitquery OAuth token. 2. **Run the bot:** ```bash node index.js ``` ### Conclusion Congratulations! You've successfully built a Solana sniper bot similar to [SOL Sniper Bot](https://solsniperbot.net/) using Bitquery for real-time Solana subscriptions and the Jupiter Swap API for executing swaps. This bot actively listens for specific on-chain instructions and performs swaps based on the detected activities. Remember to monitor and manage your bot diligently, especially when operating on the mainnet with real funds. ### Disclaimer This tutorial is for educational purposes only. Trading cryptocurrencies involves significant risk, and you should consult with a professional advisor before making any investment decisions. --- ## Solana Solfi API URL: https://docs.bitquery.io/docs/blockchain/Solana/SolFi-api/ SolFi DEX on Solana: real-time trades, latest and streaming token prices, OHLC candles, top traders, buy and sell volume, and pair volatility via GraphQL. # SolFi DEX API :::tip Need real-time SolFi data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview). [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered SolFi swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical SolFi data older than ~30 days**, raw per-swap detail, or call / event context. ::: ## SolFi Trades in Real-Time This streams a message for every new SolFi trade, carrying the buy and sell sides, the block and the transaction. Open it in the [Bitquery IDE: realtime SolFi trades](https://ide.bitquery.io/Real-time-trades-on-Solfi-DEX-on-Solana). ```graphql subscription { Solana { DEXTrades(where: { Trade: { Dex: { ProtocolFamily: { is: "Solfi" } } } }) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress } PriceAgainstBuyCurrency: Price } } Block { Time } } } } ``` ## Latest Price of a Token on SolFi This returns the most recent trade for a token on SolFi, with the price in the quote token and in USD. Open it in the [Bitquery IDE: latest SolFi token price](https://ide.bitquery.io/latest-price-of-token-on-solfi). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProtocolFamily: {is: "Solfi"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Realtime Price feed of a Token on SolFi The same filter as a subscription pushes a message on every new trade, giving a live price feed instead of a single reading. Open it in the [Bitquery IDE: SolFi realtime price feed](https://ide.bitquery.io/realtime-price-of-token-on-solfi). ```graphql subscription{ Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProtocolFamily: {is: "Solfi"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## SolFi OHLC API If you want to get OHLC data for any specific currency pair on SolFi, you can use this api. Only use [this API](https://ide.bitquery.io/SolFi-OHLC-for-specific-pair) as query and not subscription websocket as Aggregates and Time Intervals don't work well with subscriptions. ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProtocolFamily: {is: "Solfi"}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Amount) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ## Get the Top Traders of a specific Token on SolFi DEX This ranks the wallets trading a given token on SolFi, here USDC (`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`). Run it as a plain request, not a WebSocket subscription: aggregates are recomputed per message on a subscription, so the totals come back wrong. Open it in the [Bitquery IDE: SolFi top traders](https://ide.bitquery.io/top-traders-of-a-token-on-solfi). ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProtocolFamily: {is: "Solfi"}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Side { Account { Address } Type } } bought: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sold: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } { "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } ``` ## Get trading volume, buy volume, sell volume of a token This reads the [Trading cube](/docs/trading/crypto-trades-api/trades-api/) rather than the chain-level `DEXTradeByTokens`. Every Trading row carries a vetted USD price and the cube covers roughly the last 30 days in full, while the Solana `archive` and `combined` datasets return about a fifth fewer trades than `realtime` over the same window, so volume totals taken from them read low. `Side` is the trader's own side. The example follows the WSOL/USDC market on SolFi; swap the two addresses for the pair you want, and widen `days_ago` up to the 30-day window. For longer spans use [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs/) with `sum(of: Volume_Usd)` over hourly intervals, which is pre-aggregated and far cheaper than scanning every trade. Open it in the [Bitquery IDE: SolFi trade volume](https://ide.bitquery.io/trade_volume-Solfi). ```graphql { Trading { Trades( where: { Pair: { Market: { ProtocolFamily: { is: "Solfi" }, Network: { is: "Solana" } } Token: { Address: { is: "So11111111111111111111111111111111111111112" } } QuoteToken: { Address: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Block: { Time: { since_relative: { days_ago: 7 } } } } ) { volumeUsd: sum(of: AmountsInUsd_Base) buy_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) sell_volume: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ``` ## Volatility of a Pair on SolFi Volatility is an important factor in trading world as it determines the fluctuation in price that implies the possibility of profit and risk of loss. Lesser volatility denotes that the pair is stable. [Here](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-Solfi-Dex-on-Solana_1) is the query to get the volatility for a selected pair in the last 1 hour. ```graphql query Volatility { Solana(dataset: realtime) { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Solfi" } } Buy: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } Sell: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Block: { Time: { after: "2025-06-06T01:00:00Z" before: "2025-06-06T02:00:00Z" } } } ) { volatility: standard_deviation(of: Trade_Buy_Price) } } } ``` --- ## Solana Staking Rewards API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-rewards/ Solana staking rewards: query the latest reward distributions on Solana and the rewards paid to a specific wallet address, with GraphQL examples. # Solana Rewards API Solana rewards are incentives given to investors and validators for staking their SOL tokens to secure the network. This section covers how to access information about the latest Solana rewards among other examples. ## Latest Rewards The query below helps track the most recent reward distributions on the Solana blockchain in real-time. You can find the query [here](https://ide.bitquery.io/Latest-Solana-Rewards) ```graphql subscription { Solana { Rewards(limit: {count: 10}) { Block { Hash Height Slot RewardsCount Time } Reward { RewardType PostBalance Index Commission Amount Address } } } } ``` ## Rewards for a Wallet Address If you're interested in tracking the rewards for a specific wallet address, you can modify the query to filter results based on the address. This allows stakeholders to monitor their own rewards or analyze rewards distribution to specific addresses over time. You can find the query [here](https://ide.bitquery.io/Rewards-for-a-wallet-address) ```graphql subscription { Solana { Rewards( limit: {count: 10} where: {Reward: {Address: {is: "HnfPZDrbJFooiP9vvgWrjx3baXVNAZCgisT58gyMCgML"}}} ) { Block { Hash Height Slot RewardsCount Time } Reward { RewardType PostBalance Index Commission Amount Address } } } } ``` ## Video Tutorial on Solana Rewards API | How to get Rewards Distribution data using Solana Rewards API --- ## Solana Token Holders API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-token-holders/ Solana token holders: top holders from historical transfers (V1) or real-time balance updates (V2), whale tracking, and how to choose the right API. # Solana Token Holders API Get real-time and historical token holder data for any SPL token on Solana. Bitquery provides two approaches to retrieve token holders; choose the one that fits your use case. ## Can I get Solana token holder data using Bitquery? Yes. Bitquery exposes Solana SPL holder analytics via GraphQL: use **V1** transfer-based aggregates for full history and top holders, or **V2** `BalanceUpdates` for fast snapshots on recently active tokens (roughly the last hours of balance updates). Pick V1 for long-lived tokens and trends; V2 for brand-new launches and near-real-time rankings. ## How do I track whale wallets and their token holdings on Solana? Use the V1 holder query to list the largest wallets by net balance, or V2 `BalanceUpdates` ranked by the sum of each wallet's balance changes for fresh launches. Set a minimum holding or post-process balances to focus on whales, then correlate with [Solana transfers](/docs/blockchain/Solana/solana-transfers/) or [DEX trades](/docs/blockchain/Solana/solana-dextrades/) for accumulation or distribution. ## Choosing the Right API Bitquery provides two versions of Solana APIs, each with different strengths for retrieving token holder data: | Feature | V1 API (Transfers) | V2 API (Balance Updates) | |---------|---------------------|--------------------------| | **Data coverage** | Complete historical data from token launch | Last ~12 hours of balance updates | | **Best for** | Any token, any age | Newly launched tokens (< 12 hours old) | | **Data freshness** | About 10 minutes behind real-time; the newest blocks can be incomplete | Real-time | | **Method** | Tokens received minus tokens sent, per address, over the whole transfer history | Sum of each wallet's balance changes inside the window | | **Query complexity** | Two sums (inflow by receiver, outflow by sender), joined in your code | One sum, ranked on the server: `sum(of: BalanceUpdate_Amount)` | | **Ideal use cases** | Tokens older than 12 hours, historical holder analysis, whale tracking | Tokens launched within the last 12 hours, Pump.fun launches, fast holder snapshots | For a full historical holder snapshot at scale, across many tokens, ask sales@bitquery.io about a [Data Store export](https://bitquery.io/datastore). :::tip When to use which? - **Token launched more than 12 hours ago** → Use **V1 API** (complete history) - **Token launched within the last 12 hours** → Use **V2 API** (faster, simpler) - **Need both speed and history** → Combine both: V2 for the latest snapshot, V1 for historical trends - **Need full holder history at scale** → Ask sales about a Data Store export ::: ## V1 API — Historical Token Holders via Transfers The V1 API works out each address's balance from its full transfer history: tokens received minus tokens sent. It covers any token, whatever its launch date. **Strengths:** - Full historical coverage from token genesis - Works for any SPL token, any age - Balances computed from on-chain transfer history **Limitation:** - Data lags about 10 minutes behind real-time, and the newest blocks can be incomplete, so a token launched in the last hour can show partial or negative balances. Use V2 for tokens under ~12 hours old. For more V1 Solana transfer examples, see the [V1 Solana Transfers documentation](https://docs.bitquery.io/v1/docs/Examples/Solana/transfers). ### Top Token Holders Get the top holders for any SPL token by calculating net balances from transfer history. **Try it live:** [Solana Token Holders V1](https://ide.bitquery.io/) ```graphql query TopHoldersV1($token: String!, $since: ISO8601DateTime) { solana(network: solana) { inflow: transfers( currency: { is: $token } date: { since: $since } success: { is: true } options: { limit: 25000, asc: "receiver.address" } ) { receiver { address } amount(calculate: sum) } outflow: transfers( currency: { is: $token } date: { since: $since } success: { is: true } options: { limit: 25000, asc: "sender.address" } ) { sender { address } amount(calculate: sum) } } } ``` ```json { "token": "943YczGfS95e1ZnUSMd5DPQrGXaKBS2zGR76htycpump", "since": "2026-02-19" } ``` ### How This Query Works 1. **`inflow`** groups the token's transfers by receiver and sums what each address received. 2. **`outflow`** groups the same transfers by sender and sums what each address sent. 3. **Balance** is inflow minus outflow for each address. Join the two lists on the address in your code, then sort by balance. 4. **The empty address** in `outflow` is the mint. Drop empty addresses from both lists, and drop addresses whose balance is zero or below. 5. **Amounts are raw units.** Divide by `10^decimals` (6 for Pump.fun tokens). Set `since` to the launch date or earlier. A later date leaves out the first transfers, and every balance that depends on them comes out wrong. Both sums must come from separate aliases. A single query that puts `sum_in: amount(calculate: sum)` and `sum_out: amount(calculate: sum)` on the same row reads the same transfers twice, so `sum_in - sum_out` is 0 for every address. ### Customization Options **Balances at a past date**: add `till` to the `date` filter of both aliases: ```graphql date: { since: "2026-02-19", till: "2026-03-01" } ``` **More addresses**: each alias returns up to its `limit`. For a token with more addresses than that, page through with `offset`, keeping the sort on the address so pages do not overlap (use `sender.address` in `outflow`): ```graphql options: { limit: 25000, offset: 25000, asc: "receiver.address" } ``` **Current holders only**: after the join, keep addresses whose inflow minus outflow is above zero. ## V2 API — Real-Time Token Holders via Balance Updates The V2 API reads Solana's balance update records in real time. It keeps only the last ~12 hours, so it gives a full holder list only for a token launched inside that window. **Strengths:** - Real-time data with minimal delay - One query, ranked on the server; no join in your code - Great for newly launched tokens and fast-moving markets **Limitation:** - Only covers the last ~12 hours of balance updates - Best suited for tokens launched within that window ### Top Token Holders Get the top 50 holders of a token launched within the last ~12 hours. **Try it live:** [Solana Token Holders V2](https://ide.bitquery.io/) ```graphql query TopHolders($token: String!) { Solana(dataset: realtime) { BalanceUpdates( limit: { count: 50 } orderBy: { descendingByField: "Holding" } where: { BalanceUpdate: { Currency: { MintAddress: { is: $token, not: "" } } } Transaction: { Result: { Success: true } } } ) { BalanceUpdate { Account { Owner } } Holding: sum(of: BalanceUpdate_Amount) } } } ``` ```json { "token": "token mint address" } ``` ### How This Query Works 1. **Fetches every balance change** of the token inside the real-time window, from successful transactions only. 2. **Groups by `Account.Owner`**, so each row is one wallet with all its token accounts together. 3. **`sum(of: BalanceUpdate_Amount)`** adds up each wallet's changes. For a token launched inside the window, that sum is the wallet's current balance, and a wallet that sold everything sums to 0. 4. **Sorted by holding**, largest first. Amounts are already in token units. Do not rank holders with `PostBalance(maximum: Block_Slot)`. It takes the balance at the highest slot, and an account can change several times in one slot. At a Pump.fun graduation a SOL-paired bonding curve goes from 206,900,000 tokens to 0 in one slot, and a wallet can sell out in several transactions in one slot. In our tests on Pump.fun tokens that graduated on 8 October 2026, that query showed emptied bonding curves and sold-out wallets holding 57,680,000 to 383,635,727 tokens; the true balance of each was 0. Adding `PostBalance: { gt: "0" }` makes it worse: an account that sold out keeps its last nonzero balance. To read one wallet's current balance, take its latest row ordered by slot and then transaction index, as in the [developer holdings query](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/#how-do-i-get-devs-holdings-of-a-pumpfun-token). ### Customization Options **Get more holders**: raise the limit. ```graphql limit: { count: 200 } ``` **Filter by minimum balance**: keep only wallets above a threshold. ```graphql Holding: sum(of: BalanceUpdate_Amount, selectWhere: { gt: "1000000" }) ``` Do not filter `PostBalance` in `where`. That drops balance changes, and the sums stop matching the balances. ## Use Cases ### Whale tracking (largest holders) Monitor large holders and track their accumulation or distribution patterns. Use V1 for historical whale behavior or V2 for real-time whale alerts on new tokens. See [How do I track whale wallets and their token holdings on Solana?](#how-do-i-track-whale-wallets-and-their-token-holdings-on-solana) above for the query approach. ### Token Distribution Analysis Analyze how evenly a token is distributed across holders. Calculate metrics like the Gini coefficient or top-10 holder concentration to assess decentralization. ### New Token Launch Monitoring Track holder growth for newly launched tokens (especially Pump.fun launches). Use V2 for instant holder snapshots within the first 12 hours. ### Holder Count Over Time Use V1 to track how the number of unique holders changes over different date ranges, revealing adoption trends. ### Airdrop Verification Verify that airdrop recipients actually hold the tokens by querying current balances. ### Smart Money Tracking Identify wallets that consistently hold tokens early in successful launches. Cross-reference with the [Solana Trader API](/docs/blockchain/Solana/solana-trader-API/) for deeper analysis. ## Best Practices 1. **Choose the right API for your use case** — V1 for historical/complete data, V2 for speed on new tokens 2. **Set appropriate date ranges in V1** — Narrower ranges reduce query complexity and points consumed 3. **Filter out zero balances** — Exclude wallets that have sold all tokens for cleaner results 4. **Account for token decimals** — Raw balances need to be divided by `10^decimals` for human-readable amounts 5. **Exclude known program accounts** — Filter out system programs, DEX pools, and bridge contracts for accurate retail holder counts 6. **Cache results** — Token holder data doesn't change every second; cache for 1–5 minutes to reduce API usage 7. **Combine V1 and V2** — Use V2 for the latest snapshot and V1 for historical trend analysis ## Related APIs - [Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/) — Real-time balance change monitoring - [Solana Transfers API](/docs/blockchain/Solana/solana-transfers/) — Track token transfers - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) — Trading activity for tokens - [Solana Trader API](/docs/blockchain/Solana/solana-trader-API/) — Trader analytics and smart money tracking - [Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/) — Token supply data - [Pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/) — Pump.fun token data ## Support For questions or issues: - [Bitquery Support](https://support.bitquery.io) - [Bitquery IDE](https://ide.bitquery.io) - [Bitquery Documentation](https://docs.bitquery.io) --- ## Solana Token Market Cap API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-token-marketcap-api/ Solana Token Market Cap API: stream Solana market cap, FDV, supply, and price using Bitquery Trading GraphQL APIs. See examples in the Bitquery IDE. # Solana Token Market Cap API ## Video Tutorial | How to Track Thousands of Solana Tokens in a single websocket subscription :::tip Need real-time Solana token market-cap data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered Solana token market-cap swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical Solana token market-cap data older than ~30 days**, raw per-swap detail, or call / event context. ::: Use Bitquery’s **Trading** API **`Tokens`** cube to stream or query **market cap**, **fully diluted valuation (USD)**, **total supply**, **price** (OHLC and averages), and **volume** for tokens on **Solana**. Filter with **`solana:`** plus the token **mint** in **`Token.Id`** / **`Currency.Id`**; ranked queries below use **`Token.Network`** **`Solana`**. For schema details and field meanings, see the **[Tokens cube](/docs/trading/crypto-price-api/tokens)** and **[Supply fields](/docs/trading/crypto-price-api/supply-fields)**. ## Related APIs - **[Ethereum Token Market Cap API](/docs/blockchain/Ethereum/token-supply/ethereum-token-marketcap-api)** — **`eth:`** ids - **[Base Token Market Cap API](/docs/blockchain/Base/base-token-marketcap-api)** — **`base:`** ids - **[Arbitrum Token Market Cap API](/docs/blockchain/Arbitrum/arbitrum-token-marketcap-api)** — **`arbitrum:`** ids - **[Polygon (Matic) Token Market Cap API](/docs/blockchain/Matic/matic-token-marketcap-api)** — **`matic:`** ids - **[BSC Token Market Cap API](/docs/blockchain/BSC/bsc-token-marketcap-api)** — **`bsc:`** ids - **[Crypto Price API — Tokens](/docs/trading/crypto-price-api/tokens)** — full `Tokens` cube reference --- ## How do I stream live Solana token market cap, price, and volume? Subscribe to **`Tokens`** where **currency id** includes **`solana`**, with **interval duration** greater than **1** (second). You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/solana-token-marketcap-stream). ```graphql subscription MyQuery { Trading { Tokens( where: { Currency: { Id: { includes: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` --- ## How do I get the latest market cap for a specific token on Solana? Use **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, and **`Token.Id`** with **`includesCaseInsensitive`** (e.g. **`solana:`** + mint). You can run this query [in the Bitquery IDE](https://ide.bitquery.io/specific-solana-token-latest-marketcap). ```graphql query { Trading { Tokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Token: { Id: { includesCaseInsensitive: "solana:JCsv6w5NGR9NWryUCQLD7gMHbSB9vZRAvgYqJTFKNT3K" } } Interval: { Time: { Duration: { gt: 1 } } } } ) { Token { Name Id Address Symbol } Block { Time } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } Price { Average { Mean } Ohlc { Open Low High Close } } Volume { Base BaseAttributedToUsd Quote Usd } } } } ``` Replace the `includesCaseInsensitive` value with your token’s **`solana:`** id. --- ## How do I stream Solana tokens with market cap above $1 million? Subscribe when **`Token.Id`** matches **Solana** (**`solana`**) and **`Supply.MarketCap`** **>** **1,000,000** (USD). You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/realtime-stream-solana-tokens-with-marketcap-above-1-million). ```graphql subscription { Trading { Tokens( where: { Token: { Id: { includesCaseInsensitive: "solana" } } Interval: { Time: { Duration: { gt: 1 } } } Supply: { MarketCap: { gt: 1000000 } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` :::tip Threshold and interval Tune **`Supply.MarketCap`** and **`Interval.Time.Duration`** for your alerts or dashboards. See **[Tokens cube](/docs/trading/crypto-price-api/tokens)** for more filters. ::: --- ## How do I get top Solana tokens by market cap? Ranks tokens on **Solana** by **`Supply.MarketCap`**, with **24h** window, **1s** interval, **$1,000+** USD volume, **`limitBy`** per **`Token_Id`**, up to **50** rows. **`Token.Network`** is **Solana**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-solana). ```graphql { Trading { Tokens( limit: { count: 50 } limitBy: { count: 1, by: Token_Id } orderBy: { descending: Supply_MarketCap } where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Interval: { Time: { Duration: { eq: 1 } } } Volume: { Usd: { gt: 1000 } } Token: { Network: { is: "Solana" } } } ) { Currency { Id Name Symbol } Price { Average { Mean(maximum: Block_Time) } } Volume { Base(maximum: Block_Time) Quote(maximum: Block_Time) Usd(maximum: Block_Time) } Token { Network Symbol Address } Supply { MarketCap(maximum: Block_Time) FullyDilutedValuationUsd(maximum: Block_Time) TotalSupply(maximum: Block_Time) } } } } ``` --- ## How do I get top Solana tokens by market cap change in 1 hour? **1-hour** OHLC (`Duration: { eq: 3600 }`), ordered by **`change_mcap`**: **(close − open) × total supply**. **`Token.Network`** is **Solana**. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/top-solana-tokens-by-Market-Cap-Change-1h). ```graphql { Trading { Tokens( limit: { count: 50 } orderBy: { descendingByField: "change_mcap" } where: { Interval: { Time: { Duration: { eq: 3600 } } } Token: { Network: { is: "Solana" } } } ) { Currency { Id Name Symbol } Token { Network Symbol Address } Supply { MarketCap FullyDilutedValuationUsd CirculatingSupply TotalSupply MaxSupply } change_mcap: calculate( expression: "($Price_Ohlc_Close-$Price_Ohlc_Open) * Supply_TotalSupply" ) Price { Ohlc { Open Close } } } } } ``` ## Video tutorial --- ## Solana Token Price API: Latest Price, Live Stream, OHLC URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-token-price-api/ Solana token price API: latest USD price of any SPL token from its top market, a live price stream, a multi-token watchlist, hourly OHLC and top tokens by volume. # Solana Token Price API Get the USD price of any Solana token over GraphQL: the latest price, a live stream, several tokens at once, hourly candles, and the most traded tokens right now. Every query uses the [Trading API](/docs/trading/trading-data-overview), which prices each token from its DEX trades and normalizes the result to USD. For one token, the most accurate price comes from its **top market**: the pool with the most trading volume, selected with `Ranking: { Position: { eq: 1 } }`. See [why the top market](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) for the details. :::note To run these queries outside the [Bitquery IDE](https://ide.bitquery.io), you need an API access token. [How to generate one ➤](/docs/authorization/how-to-generate/) ::: The examples use BONK (`DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263`). Replace it with any SPL token mint address. ## Latest price of a Solana token Returns the latest 1-minute candle of the token's top market. `Price.Ohlc.Close` is the current USD price. ```graphql { Trading { Pairs( where: { Token: { Address: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 60 } } } Price: { IsQuotedInUsd: true } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address Network } Price { IsQuotedInUsd Ohlc { Open High Low Close } } Ranking { Position Weight } Volume { Usd } Block { Time } } } } ``` ## Stream a Solana token price in real time The same filter as a WebSocket subscription, with 1-second intervals. Each message carries the newest price. ```graphql subscription { Trading { Pairs( where: { Token: { Address: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 1 } } } Price: { IsQuotedInUsd: true } } ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol Address } Price { IsQuotedInUsd Ohlc { Close } } Ranking { Position Weight } } } } ``` The top market can change as volume moves between pools, so read `Market.Address` from each message instead of assuming a fixed pool. ## Prices of several Solana tokens at once Pass a list of mint addresses. `limitBy` keeps one row, the newest, per token. ```graphql { Trading { Pairs( where: { Token: { Address: { in: [ "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" "So11111111111111111111111111111111111111112" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" ] } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 60 } } } Price: { IsQuotedInUsd: true } Block: { Time: { since_relative: { minutes_ago: 10 } } } } limit: { count: 10 } limitBy: { by: Token_Id, count: 1 } orderBy: { descending: Block_Time } ) { Token { Symbol Address } QuoteToken { Symbol } Market { Protocol } Price { Ohlc { Close } } Ranking { Position Weight } Block { Time } } } } ``` ## Hourly OHLC candles for a Solana token Hourly open, high, low and close for the last 24 hours, with USD volume per hour. Change `Duration` (in seconds) and `hours_ago` for other candle sizes and ranges. ```graphql { Trading { Pairs( where: { Token: { Address: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } Network: { is: "Solana" } } Ranking: { Position: { eq: 1 } } Interval: { Time: { Duration: { eq: 3600 } } } Price: { IsQuotedInUsd: true } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 24 } orderBy: { descending: Block_Time } ) { Token { Symbol } Market { Protocol Address } Price { Ohlc { Open High Low Close } } Volume { Usd } Block { Time } } } } ``` For more intervals and chart-ready candles, see the [OHLC API](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api). ## Top Solana tokens by trading volume, with prices The 10 Solana tokens with the most USD volume in the last hour, with their price. This uses the `Tokens` cube, which blends every pool a token trades in, which suits a chain-wide list. ```graphql { Trading { Tokens( where: { Token: { Network: { is: "Solana" } } Interval: { Time: { Duration: { eq: 3600 } } } Price: { IsQuotedInUsd: true } Block: { Time: { since_relative: { hours_ago: 1 } } } } limit: { count: 10 } limitBy: { by: Token_Id, count: 1 } orderBy: { descending: Volume_Usd } ) { Token { Symbol Name Address } Price { Average { Estimate } Ohlc { Close } } Volume { Usd } Block { Time } } } } ``` ## Related - [Pairs cube](/docs/trading/crypto-price-api/pairs): all price fields and ranking rules - [Tokens cube](/docs/trading/crypto-price-api/tokens): chain-wide prices and volume - [Solana token market cap API](/docs/blockchain/Solana/solana-token-marketcap-api) - [Solana token supply API](/docs/blockchain/Solana/token-supply-cube) --- ## Solana Token Search API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-search-tokens/ Solana token search: find tokens by name, symbol or mint address, with case-insensitive matching and wildcard patterns using likeCaseInsensitive filters. # Solana Token Search API ## Search Tokens on Solana You can search tokens on Solana using names or symbols using our APIs and get prices and other details. You can find the query [here](https://ide.bitquery.io/search-solana-tokens) ```graphql { Solana { DEXTrades( orderBy: { descending: Block_Time } limit: { count: 100 } limitBy: { by: Trade_Buy_Currency_MintAddress, count: 1 } where: { Trade: { Buy: { Currency: { Name: { includes: "pe" } } } } } ) { Trade { Buy { Price PriceInUSD Currency { Name Symbol MintAddress } } Sell { Currency { Name Symbol MintAddress } } } } } } ``` ## Search Tokens on Solana (Case Insensitive) You can search tokens on Solana using names or symbols case insensitively also using our APIs and get prices and other details. You can find the query [here](https://ide.bitquery.io/Currency-with-elon-inclusion). ```graphql { Solana { Transfers( where: { Transfer: { Currency: { Symbol: { includesCaseInsensitive: "elon" } } } } ) { Transfer { Currency { MintAddress Symbol } } count } } } ``` ## Search Tokens with Symbol on Solana using likeCaseInsensitive (Case Insensitive) Get tokens which have a certain specific symbol. This API is case insensitive. In this API we are getting tokens in descending order of their trade volume in last hour which has symbol `trump`. You can find the query [here](https://ide.bitquery.io/Token-Search-API---trump-symbol#). ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Block: { Time: { since: "2025-02-28T07:00:00Z" } } Trade: { Currency: { Symbol: { likeCaseInsensitive: "trump" } } } Transaction: { Result: { Success: true } } } limit: { count: 50 } orderBy: { descendingByField: "trade_volume" } ) { Trade { Currency { Name MintAddress Symbol } Dex { ProtocolName } Market { MarketAddress } Side { Currency { Name MintAddress Symbol } } } trade_volume: sum(of: Trade_Side_AmountInUSD) trades: count } } } ``` ## Search Tokens with Symbol on Solana using likeCaseInsensitive plus wildcard(%) (Case Insensitive) Get tokens which have a certain specific symbol `%pump` where "%" can replace any number of characters, its basically a placeholder. This API is case insensitive. In this API we are getting tokens in descending order of their trade volume in last hour which has symbol ending with "pump". You can find the query [here](https://ide.bitquery.io/token-search-api--pump-wildcard#). ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Block: { Time: { since: "2025-02-28T07:00:00Z" } } Trade: { Currency: { Symbol: { likeCaseInsensitive: "%pump" } } } Transaction: { Result: { Success: true } } } limit: { count: 50 } orderBy: { descendingByField: "trade_volume" } ) { Trade { Currency { Name MintAddress Symbol } Dex { ProtocolName } Market { MarketAddress } Side { Currency { Name MintAddress Symbol } } } trade_volume: sum(of: Trade_Side_AmountInUSD) trades: count } } } ``` ## Search Tokens with Symbol on Solana using likeCaseInsensitive plus wildcard(\_) (Case Insensitive) Get tokens which have a certain specific symbol `p_e` where "\_" will replace 1 character, its basically a placeholder for 1 character. This API is case insensitive. In this API we are getting tokens in descending order of their trade volume in last hour. You can find the query [here](https://ide.bitquery.io/Token-Search-API-for-symbol---p_e-wildcard#). ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Block: { Time: { since: "2025-02-28T07:00:00Z" } } Trade: { Currency: { Symbol: { likeCaseInsensitive: "p_e" } } } Transaction: { Result: { Success: true } } } limit: { count: 50 } orderBy: { descendingByField: "trade_volume" } ) { Trade { Currency { Name MintAddress Symbol } Dex { ProtocolName } Market { MarketAddress } Side { Currency { Name MintAddress Symbol } } } trade_volume: sum(of: Trade_Side_AmountInUSD) trades: count } } } ``` ## Search Tokens with MintAddress on Solana using likeCaseInsensitive (Case Insensitive) Get tokens which have a certain specific address `%pump` where "%" can replace any number of characters, its basically a placeholder. This API is case insensitive. In this API we are getting tokens in descending order of their trade volume in last hour which has mint address ending with "pump". You can find the query [here](https://ide.bitquery.io/Token-search-api-in-mint-address#). ```graphql query MyQuery { Solana { DEXTradeByTokens( where: { Block: { Time: { since: "2025-02-28T07:00:00Z" } } Trade: { Currency: { MintAddress: { likeCaseInsensitive: "%pump" } } } Transaction: { Result: { Success: true } } } limit: { count: 50 } orderBy: { descendingByField: "trade_volume" } ) { Trade { Currency { Name MintAddress Symbol } Dex { ProtocolName } Market { MarketAddress } Side { Currency { Name MintAddress Symbol } } } trade_volume: sum(of: Trade_Side_AmountInUSD) trades: count } } } ``` ## Video Tutorial | Token Search API Overview | Search Tokens efficiently using symbol, address, etc --- ## Solana Token Supply API URL: https://docs.bitquery.io/docs/blockchain/Solana/token-supply-cube/ Track Solana token supply with Bitquery GraphQL: subscribe to supply changes, query mint and burn events, and read circulating supply for any SPL token. # Solana Token Supply API In this section we will see how to get Solana Token Supply information using our API. For token prices, see the [Solana Token Price API](/docs/blockchain/Solana/solana-token-price-api). Supply metrics are part of the broader [Token API](https://bitquery.io/products/digital-assets) — transfers, supply and new token creation across chains. ## Overview The **Solana Token Supply API** provides comprehensive access to real-time token supply data on the Solana blockchain. This API enables you to track token creation, monitor supply changes, calculate market capitalization, and analyze token burn events with detailed metadata and real-time updates. ## 📋 Table of Contents - **[Subscribe to Token Supply Changes](#subscribe-to-token-supply-changes)** - Real-time supply monitoring - **[Get Supply of Specific Token](#get-supply-of-specific-token)** - Individual token supply tracking - **[Circulating Supply of a Solana Token](#circulating-supply-of-a-solana-token)** - Circulating supply, total supply and market cap in one query - **[Token Creation Tracking](#token-creation-tracking)** - New token creation events - **[Market Cap Analysis](#market-cap-analysis)** - Market capitalization queries - **[Token Burn Events](#token-burn-events)** - Burn event monitoring - **[FAQ](#faq)** - Common questions about Solana token supply - **[Video Tutorials](#video-tutorials)** - Step-by-step guides ## 🔗 Related Solana APIs - **[Solana Token Price API](/docs/blockchain/Solana/solana-token-price-api)** - Latest USD price, live price stream and OHLC for any SPL token - **[Solana Instructions API](/docs/blockchain/Solana/solana-instructions/)** - Track token creation and burn instructions - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor balance changes from supply updates - **[Solana Transfers API](/docs/blockchain/Solana/solana-transfers/)** - Track transfers that affect token supply - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Monitor trading activities impacting supply - **[Solana Fees API](/docs/blockchain/Solana/solana_fees_api/)** - Analyze fees from supply-related transactions ## Subscribe to Token Supply Changes This subscription will return the token supply changes in realtime. `PostBalance` will give you the current supply. Check the query [here](https://ide.bitquery.io/token-supply-updates-sub) For tracking the instructions that cause these supply changes (like token creation and burning), see our **[Solana Instructions API](/docs/blockchain/Solana/solana-instructions/)**. ```graphql subscription { Solana { TokenSupplyUpdates { TokenSupplyUpdate { Amount Currency { MintAddress Name } PreBalance PostBalance } } } } ``` ## Get Supply of specific Token This query will return the latest token supply of a specific token. We are getting here supply for this `6D7NaB2xsLd7cauWu1wKk6KBsJohJmP2qZH9GEfVi5Ui` token `PostBalance` will give you the current supply for this token. Check the query [here](https://ide.bitquery.io/token-supply_2) ```graphql { Solana { TokenSupplyUpdates( limit: { count: 1 } orderBy: { descending: Block_Time } where: { TokenSupplyUpdate: { Currency: { MintAddress: { is: "token mint address" } } } } ) { TokenSupplyUpdate { Amount Currency { MintAddress Name } PreBalance PostBalance } } } } ``` ## Circulating supply of a Solana token This query returns the circulating supply, total supply and market cap of one Solana token from the [Trading cube](/docs/trading/crypto-price-api/tokens). The example uses Jupiter (`JUP`), filtered by its currency Id `jup` on the Solana network. Replace the Id with the currency Id of the token you need. Circulating supply is the part of the supply available to the market, while total supply is every token issued on-chain, including locked and unvested tokens. `MarketCap` is circulating supply times the USD price, and `FullyDilutedValuationUsd` is total supply times the USD price. See [Supply fields](/docs/trading/crypto-price-api/supply-fields) for how each field is derived. [Run this query in the IDE](https://ide.bitquery.io/solana-token-circulating-supply-total-supply-market-cap) ```graphql { Trading { Tokens( where: {Currency: {Id: {is: "jup"}}, Token: {Network: {is: "Solana"}}, Interval: {Time: {Duration: {eq: 60}}}} lim