# 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 API - Base Chain Token Trades & Transaction Data: query and stream Base on-chain data with Bitquery GraphQL examples for developers. # 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, …) 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 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 new 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 — 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 are append-only records.** An address returns one row per chain, per label, per recording pass, so the same label recurs with different `RecordedAt` values. Fold that into a current view with `limitBy` — [shown below](#how-to-get-only-the-current-labels). ## 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-31T13:11:26Z" } ] } } ``` ## How to get only the current labels Because records accumulate, 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 — 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 — 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 } } } ``` ## 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 — you cannot exclude addresses server-side. | | `Chain` | `is`, `in`, `not`, `notIn`, `like`, `includes`, `startsWith`, … | Exact chain slugs — see 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 maps to many chains. | | `Label.Type` | String | Label category — see 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 labeling pipeline wrote this record. Re-confirmation appends a new record rather than updating the old one. | ### 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 operator 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** — 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 labeled addresses | Poll with `RecordedAt: {since: …}` | ## 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 --- ## Aerodrome Finance API — Base DEX Trades & Liquidity URL: https://docs.bitquery.io/docs/blockchain/Base/aerodrome-base-api/ Base Aerodrome Base API: query and stream Base on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # Aerodrome Finance API - Base DEX Trades, Liquidity Pools, Token Analytics :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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. [Get pool liquidity on Aerodrome Finance — Query ➤](https://ide.bitquery.io/Liquidity-of-a-Pool_2)
Click to expand GraphQL query **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```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" }) } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: combined, network: base) { BalanceUpdates( where: { BalanceUpdate: { Address: { is: "0x1e039aade407a94df380649b33b52cb8ad41c755" } } Currency: { SmartContract: { in: [ "0x4200000000000000000000000000000000000006" "0xa999542c71febba77602fbc2f784ba9ba0c850f6" ] } } } orderBy: { descendingByField: "balance" } ) { Currency { Name } balance: sum(of: BalanceUpdate_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 API: query and stream Base on-chain data with Bitquery GraphQL examples for developers. Covers archive history and realtime data. # 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 Documentation: query and stream Algorand on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 API: query and stream Algorand on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 Arguments API: query and stream Algorand on-chain data with Bitquery GraphQL examples for developers. Covers archive history and realtime data. # 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 API - Query Blocks by Proposer: query and stream Algorand on-chain data with Bitquery GraphQL examples for developers. # 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 API: query and stream Algorand on-chain data with Bitquery GraphQL examples for developers. Built for traders and analytics teams. # 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. :::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 API: query and stream Algorand on-chain data with Bitquery GraphQL examples for developers. # 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 API: query and stream Algorand on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # 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) on a free account. ## 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 API Documentation: query and stream Arbitrum on-chain data with Bitquery GraphQL examples for developers. Keep queries fast with indexed filters. # 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 **9 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 :::caution Deprecated APIs On EVM, **`BalanceUpdates`** and **`TokenHolders`** were deprecated as of **20 May 2026** and removed on **15 June 2026**. Use **`EVM.Balances`** (this page) and **[Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api)** (`EVM.Holders`) instead. ::: 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 Cross Chain API: query and stream Arbitrum on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 Kafka or gRPC 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 **9 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 API: query and stream Arbitrum on-chain data with Bitquery GraphQL examples for developers. # 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 API: query and stream Arbitrum on-chain data with Bitquery GraphQL examples for developers. # 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 API & Streams: query and stream Arbitrum on-chain data with Bitquery GraphQL examples for developers. # 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 API: query and stream Arbitrum on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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) on a free account; 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) --- ## 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/) --- ## 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 Documentation URL: https://docs.bitquery.io/docs/examples/futures-dexs/asterdex-api/ AsterDEX API Documentation: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. See examples in the Bitquery IDE. # AsterDEX API Documentation - Complete Guide to BNB Smart Chain Perpetual Futures Trading :::info Perp DEX data on other chains This page covers AsterDEX on BNB Smart Chain via decoded contract events. For dedicated perpetual-futures cubes — orders, fills, positions, PnL, liquidations, funding and open interest — see the [**Perp DEX API**](/docs/perpetuals/) section. ::: ## Quick Start Guide ### Prerequisites for AsterDEX API Integration Before integrating AsterDEX APIs, ensure you have: 1. **Bitquery Account**: Sign up at [ide.bitquery.io](https://ide.bitquery.io/) for API access 2. **GraphQL Knowledge**: Basic understanding of GraphQL query syntax 3. **BNB Smart Chain Familiarity**: Knowledge of BSC addresses and transactions 4. **Development Environment**: Any programming language with HTTP request capabilities ### 5-Minute Setup ```javascript // Example: Fetch latest AsterDEX trades const query = ` { EVM(dataset: realtime, network: bsc) { Events( where: {LogHeader: {Address: {is: "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0"}}} orderBy: {descending: Block_Time} limit: {count: 10} ) { Block { Time } Transaction { Hash } Log { Signature { Name } } } } } `; fetch("https://streaming.bitquery.io/graphql", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer YOUR_API_KEY", }, body: JSON.stringify({ query }), }); ``` ## Smart Contract Information | Contract Type | Address | Network | Purpose | | -------------------------- | ------------------------------------------------------------------------------------- | --------------------- | -------------------------------------- | | **AsterDEX Main Contract** | `0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0` | BNB Smart Chain (BSC) | Core perpetual futures trading logic | | **Network ID** | `56` | BNB Smart Chain | Main BSC network identifier | | **Block Explorer** | [bscscan.com](https://bscscan.com/address/0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0) | BSC Explorer | Contract verification and transactions | --- ## AsterDEX Order Lifecycle The AsterDEX Order Lifecycle is defined by the sequence of smart contract events emitted during the creation, execution, modification, and closing of trades on the AsterDEX protocol deployed on BNB Smart Chain (BSC). Using the ABI, we can trace the major steps of a trade as follows: ### 1. Order Creation A trader begins by opening a position using one of the following contract calls: - `openMarketTrade` or `openMarketTradeBNB` — for immediate market orders - `openLimitOrder` or `openLimitOrderBNB` — for pending limit orders These functions emit events like: - `OpenMarketTrade(user, tradeHash, trade)` — signals a new market trade - `OpenLimitOrder(user, orderHash, data)` — logs the creation of a limit order These events include key parameters: - **Pair base** (trading pair symbol) - **isLong flag** (direction) - **tokenIn, amountIn** (input asset and margin) - **qty** (position size) - **price, stopLoss, takeProfit** - **broker** (affiliate ID) ### 2. Trade Pending / Validation After the trade is created, AsterDEX emits `MarketPendingTrade` or `PredictAndBetPending` events to indicate the trade or bet is awaiting price validation or oracle callback. For limit orders, this pending state continues until market conditions are met. ### 3. Trade Execution When the trade conditions are satisfied (for market or limit execution), the contract emits: - `ExecuteLimitOrderSuccessful(user, orderHash)` — for executed limit orders - `ExecuteLimitOrderRejected(user, orderHash, refund)` — if conditions are invalid - `MarketTradeCallback` — finalizes market trade once the external price feed confirms execution Once executed, the trader's position is stored, and Bitquery indexes these on-chain records as open trades. ### 4. Margin Update (Optional) Traders can adjust their position margin using the `addMargin` or `updateMargin` functions, which emit: - `UpdateMargin(user, tradeHash, beforeMargin, margin)` — updates collateral These events help Bitquery track capital movement within an active position. ### 5. Stop-Loss / Take-Profit / Liquidation During the trade's lifecycle, risk management parameters can trigger automatically. The following events define these actions: - `UpdateTradeSl` / `UpdateTradeTp` / `UpdateTradeTpAndSl` — manual stop-loss or take-profit updates - `ExecuteTpSlOrLiq` — executed close due to stop-loss, take-profit, or liquidation condition - `ExecuteCloseRejected` — if the closing execution fails or is invalid These events are captured by Bitquery and can be used to determine close reason and realized PnL. ### 6. Trade Closing A trade is closed manually or automatically, resulting in: - `CloseTradeSuccessful(user, tradeHash, closeInfo)` — main closing event, includes closePrice, fundingFee, closeFee, pnl, holdingFee - `CloseTradeReceived` — indicates funds have been distributed to the trader - `CloseTradeAddLiquidity` / `CloseTradeRemoveLiquidity` — if closing affects liquidity pools Bitquery records these closing events, linking them with the original tradeHash and calculating total realized profit or loss. ### 7. Settlement and Fee Distribution When a trade closes, associated fees are emitted as separate events: - `OpenFee` / `CloseFee` — show DAO, broker, and pool fee splits - `FundingFeeAddLiquidity` — transfers funding fees into liquidity pools - `WithdrawRevenue` — shows DAO or broker withdrawals of earned fees These events help reconstruct the entire economic flow of a trade — from initiation to settlement. ### 8. Post-Trade State Updates Finally, market-level updates are emitted periodically: - `UpdatePairAccFundingFeePerShare` — funding rate updates - `UpdatePairPositionInfo` — updates aggregate long/short positions for a pair These allow Bitquery to display aggregate market metrics, such as open interest, funding rates, and average entry prices. ## Summary of Core Events | Stage | Key Events | Description | | ------------------ | ----------------------------------------------------------- | ------------------------------- | | **Order Open** | `OpenMarketTrade`, `OpenLimitOrder` | Creation of new orders | | **Pending** | `MarketPendingTrade`, `PredictAndBetPending` | Waiting for oracle / validation | | **Execution** | `ExecuteLimitOrderSuccessful`, `MarketTradeCallback` | Order filled | | **Margin Update** | `UpdateMargin` | Margin increased or decreased | | **Risk Triggers** | `ExecuteTpSlOrLiq`, `UpdateTradeSl`, `UpdateTradeTp` | Stop-loss/TP triggered | | **Close** | `CloseTradeSuccessful`, `CloseTradeReceived` | Trade settled | | **Fees** | `OpenFee`, `CloseFee`, `FundingFeeAddLiquidity` | Fee settlements | | **Market Updates** | `UpdatePairPositionInfo`, `UpdatePairAccFundingFeePerShare` | Aggregate pair data refresh | Bitquery indexes all of these events in real-time, linking them to transactions, blocks, and traders—enabling complete lifecycle tracking of each AsterDEX trade via API or stream. --- ## AsterDEX API Examples ### 1. All Events of AsterDEX Monitor all events emitted by the AsterDEX contract to track all platform activities. **Query Link**: [All events of AsterDEX](https://ide.bitquery.io/All-events-of-AsterDEX) ```graphql { EVM(dataset: realtime, network: bsc) { Events( limit: { count: 20 } where: { LogHeader: { Address: { is: "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0" } } } ) { count Log { Signature { Name Signature } } } } } ``` ### 2. OpenMarketTrade Events `OpenMarketTrade` is when a user opens a market trade. The following API provides all newly opened market trades on AsterDEX. **Query Link**: [AsterDEX - OpenMarketTrade](https://ide.bitquery.io/AsterDEX---OpenMarketTrade) Similarly, we can get all newly created Limit Orders by following the `OpenLimitOrder` event. #### Difference between OpenLimitOrder and OpenMarketTrade | Feature | OpenLimitOrder | OpenMarketTrade | | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | **Purpose** | Creates a limit order — an instruction to open a trade only when price conditions are met. | Opens a market trade immediately at the current market price. | | **Function Call** | `openLimitOrder()` or `openLimitOrderBNB()` | `openMarketTrade()` or `openMarketTradeBNB()` | | **Emitted Event** | `OpenLimitOrder(address user, bytes32 orderHash, IBook.OpenDataInput data)` | `OpenMarketTrade(address user, bytes32 tradeHash, IBook.OpenDataInput trade)` | | **Execution Timing** | Delayed – waits for trigger (price crossing limit, oracle validation). | Immediate – executes as soon as transaction is confirmed. | | **Order State After Creation** | Becomes pending — monitored by AsterDEX Keeper or Chainlink callback. | Becomes active trade instantly. | | **Follow-up Events** | • `ExecuteLimitOrderSuccessful` (when executed)
• `ExecuteLimitOrderRejected` (if canceled/invalid)
• `CancelLimitOrder` (if user cancels) | • `MarketPendingTrade` (waiting oracle)
• `MarketTradeCallback` (execution confirmation)
• `PendingTradeRefund` (if failed) | | **Event Parameters (data struct)** | pairBase, isLong, tokenIn, amountIn, qty, price, stopLoss, takeProfit, broker | Same struct, but price acts as execution price instead of limit trigger. | ### 3. All Recent Liquidations on AsterDEX When there is a liquidation event on AsterDEX, it emits `ExecuteCloseSuccessful` event with `executionType` 2. **Query Link**: [AsterDEX - All latest Liquidations](https://ide.bitquery.io/AsterDEX---All-latest-Liquidations) #### ExecutionTypes Explained There are 4 executionTypes: - **0 – TakeProfit (TP)** → closed because TP hit (handled by `executeTpSlOrLiq`) - **1 – StopLoss (SL)** → closed because SL hit (your sample shows `executionType = 1` with negative PnL, consistent with SL) - **2 – Liquidation (LIQ)** → closed by liquidation (also through `executeTpSlOrLiq`) - **3 – Manual/Market close** → user (or UI) explicitly requested a close via `closeTrade(...)`; still emits `ExecuteCloseSuccessful` with this code. (This path does not go through `executeTpSlOrLiq` but the event includes the same enum.) ### 4. Getting All the Details of a Trade In AsterDEX every trade has an Order Hash, using which you can track the whole lifecycle of that trade. For example, for this OrderHash `5d5a2a37ef2afff8ce95101930507af4a255e271f5201658ea2660bc3baf6605` You can check all related events using the following query. This query takes time as we are querying arguments which are not indexed inside our database. You can use any latest trade to make it fast. **Query Link**: [All details of trade - 5d5a2a37ef2afff8ce95101930507af4a255e271f5201658ea2660bc3baf6605](https://ide.bitquery.io/All-details-of-trade---5d5a2a37ef2afff8ce95101930507af4a255e271f5201658ea2660bc3baf6605_7) #### Example Trade Lifecycle Here are all the emitted events for this trade and related transactions: 1. **OpenLimitOrder** - `0x67b7fe335e05599ae6b316b348c23055e152282638bd4e9e6219283a46789613` 2. **UpdateOrderSl** - `0x1b22bb4787efb3c40aca9093aedd70a59a9767ad7c3f3b19a29048f6514ca5dc` 3. **OpenMarketTrade** - `0x0b318a469ebc6f648d0c3a7e95705aa72c807f9248b21b451963970936ee48a0` 4. **ExecuteLimitOrderSuccessful** - `0x0b318a469ebc6f648d0c3a7e95705aa72c807f9248b21b451963970936ee48a0` 5. **UpdateTradeSl** - `0x6cb3d98e95f78e3708665c35481c04a96080b0ce4a3afd2b53cf4a49c164209d` 6. **CloseTradeReceived** - `0x2e24c951abbfb2cdea92b4f7157f52727b21761bc26368614a40a3d86137ba2e` 7. **ExecuteCloseSuccessful** - `0x2e24c951abbfb2cdea92b4f7157f52727b21761bc26368614a40a3d86137ba2e` Similarly, you can query any event using our events API. You can check this API to see the complete list of events: [All events of AsterDEX](https://ide.bitquery.io/All-events-of-AsterDEX) ### 5. Following a Specific AsterDEX Trader Using Bitquery's APIs you can follow specific traders on AsterDEX to check all their latest activities. **Query Link**: [Traders data - 0x2b7363708984aa25a90450cfca7bedaf6804115c](https://ide.bitquery.io/Traders-data---0x2b7363708984aa25a90450cfca7bedaf6804115c) This is a very interesting address (`0x2b7363708984aa25a90450cfca7bedaf6804115c`), it looks like it's market making on AsterDEX. You can look for `Transaction -> From` or in some cases the address might be in arguments, for example: [Traders specific event](https://ide.bitquery.io/Traders-specific-event) You can actually merge these two queries. Here is an example: [Combined Traders data - 0x01554d63537d3c62715826a268d4eab645d64b92](https://ide.bitquery.io/Copy-of-Traders-data---0x01554d63537d3c62715826a268d4eab645d64b92) --- ## Complete List of AsterDEX Events Here is the complete list of all events emitted by the AsterDEX smart contract with their signatures: | Event Name | Signature | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **PendingPredictionRefund** | `PendingPredictionRefund(address,uint256,uint8)` | | **MarketPendingTrade** | `MarketPendingTrade(address,bytes32,(address,bool,address,uint96,uint80,uint64,uint64,uint64,uint24))` | | **OpenFee** | `OpenFee(address,uint256,uint256,uint24,uint256,uint256)` | | **CloseTradeAddLiquidity** | `CloseTradeAddLiquidity(address,uint256)` | | **ExecuteLimitOrderSuccessful** | `ExecuteLimitOrderSuccessful(address,bytes32)` | | **CloseTradeReceived** | `CloseTradeReceived(address,bytes32,address,uint256)` | | **UnStake** | `UnStake(address,uint256)` | | **BurnFee** | `BurnFee(address,address,uint256,uint256,uint256,uint256)` | | **FundingFeeAddLiquidity** | `FundingFeeAddLiquidity(address,uint256)` | | **OpenLimitOrder** | `OpenLimitOrder(address,bytes32,(address,bool,address,uint96,uint80,uint64,uint64,uint64,uint24))` | | **CloseTradeRemoveLiquidity** | `CloseTradeRemoveLiquidity(address,uint256)` | | **SettlePredictionSuccessful** | `SettlePredictionSuccessful(uint256,bool,uint256,address,uint256,uint256)` | | **MintAlp** | `MintAlp(address,address,uint256,uint256)` | | **ExecuteCloseRejected** | `ExecuteCloseRejected(address,bytes32,uint8,uint64,uint64)` | | **UpdatePairAccFundingFeePerShare** | `UpdatePairAccFundingFeePerShare(address,uint256,int256,uint256)` | | **UpdateOrderSl** | `UpdateOrderSl(address,bytes32,uint256,uint256)` | | **CloseFee** | `CloseFee(address,uint256,uint256,uint24,uint256,uint256)` | | **CloseTradeSuccessful** | `CloseTradeSuccessful(address,bytes32,(uint64,int96,uint96,int96,uint96))` | | **UpdateMargin** | `UpdateMargin(address,bytes32,uint256,uint256)` | | **MintFee** | `MintFee(address,address,uint256,uint256,uint256,uint256)` | | **PredictAndBet** | `PredictAndBet(address,uint256,(address,uint96,address,uint96,address,uint96,uint32,uint64,uint40,uint24,bool,uint8))` | | **BurnRemoveLiquidity** | `BurnRemoveLiquidity(address,address,uint256)` | | **UpdateSlippageConfig** | `UpdateSlippageConfig(uint16,uint8,uint256,uint256,uint16,uint16,uint256,uint256)` | | **PendingTradeRefund** | `PendingTradeRefund(address,bytes32,uint8)` | | **PredictionCloseFee** | `PredictionCloseFee(address,uint256,uint256,uint24,uint256,uint256)` | | **PredictAndBetPending** | `PredictAndBetPending(address,uint256,(address,uint96,address,uint96,address,uint64,uint24,bool,uint128,uint8))` | | **UpdatePairPositionInfo** | `UpdatePairPositionInfo(address,uint256,uint256,uint256,int256,uint64,uint64)` | | **OpenMarketTrade** | `OpenMarketTrade(address,bytes32,(address,uint32,uint64,address,address,uint96,uint64,uint64,uint24,bool,uint96,int256,uint96,uint40,uint80,uint40,uint256))` | | **ExecuteCloseSuccessful** | `ExecuteCloseSuccessful(address,bytes32,uint8,(uint64,int96,uint96,int96,uint96))` | | **CancelLimitOrder** | `CancelLimitOrder(address,bytes32)` | | **UpdateTradeTp** | `UpdateTradeTp(address,bytes32,uint256,uint256)` | | **UpdateTradeSl** | `UpdateTradeSl(address,bytes32,uint256,uint256)` | | **MintAddLiquidity** | `MintAddLiquidity(address,address,uint256)` | | **BurnAlp** | `BurnAlp(address,address,address,uint256,uint256)` | --- ## Developer Integration Guide ### Getting Started with AsterDEX APIs 1. **Access Bitquery GraphQL IDE**: All AsterDEX APIs are accessible through [Bitquery's GraphQL IDE](https://ide.bitquery.io/) 2. **Use the Contract Address**: The main AsterDEX contract address is `0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0` on BNB Smart Chain 3. **Choose Your Network**: Always specify `network: bsc` for BNB Smart Chain queries 4. **Filter by Events**: Use the event signatures from the complete list above to track specific trading activities ### Common Use Cases **Trading Dashboard**: - Track `OpenMarketTrade` and `OpenLimitOrder` for new positions - Monitor `CloseTradeSuccessful` for position closures - Display `UpdateMargin` events for margin changes **Risk Management**: - Monitor `ExecuteCloseSuccessful` with `executionType: 2` for liquidations - Track `UpdateTradeSl` and `UpdateTradeTp` for stop-loss and take-profit updates - Alert on funding rate changes via `UpdatePairAccFundingFeePerShare` **Analytics Platform**: - Aggregate trading volumes from all position opening/closing events - Analyze trader behavior using specific trader addresses - Calculate platform fees from `OpenFee` and `CloseFee` events **Arbitrage Monitoring**: - Watch for price discrepancies in `MarketPendingTrade` events - Monitor funding rates for cross-platform opportunities - Track liquidation events for potential arbitrage ## Best Practices for AsterDEX API Integration ### Performance Optimization **Efficient Query Design:** - Use specific event names instead of querying all events - Implement proper pagination for large datasets - Cache frequently accessed data to reduce API calls - Use GraphQL field selection to minimize response size **Real-time Data Handling:** ```javascript // Optimized query for high-frequency trading applications const optimizedQuery = `{ EVM(dataset: realtime, network: bsc) { Events( where: { Log: {Signature: {Name: {in: ["OpenMarketTrade", "ExecuteCloseSuccessful"]}}} LogHeader: {Address: {is: "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0"}} } orderBy: {descending: Block_Time} limit: {count: 50} ) { Block { Time Number } Arguments { Name Value } } } }`; ``` ### Security Considerations **API Key Management:** - Store API keys securely using environment variables - Implement API key rotation for production applications - Use read-only permissions when possible - Monitor API usage and set up alerts for unusual activity **Data Validation:** - Always validate contract addresses and event signatures - Implement checksum verification for address fields - Cross-reference critical data with multiple sources - Set up monitoring for data anomalies ### Error Handling and Reliability **Robust Integration Pattern:** ```javascript async function fetchAsterDEXData(retries = 3) { try { const response = await fetch(BITQUERY_ENDPOINT, { method: "POST", headers: { Authorization: `Bearer ${API_KEY}` }, body: JSON.stringify({ query }), }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return await response.json(); } catch (error) { if (retries > 0) { console.log(`Retrying... ${retries} attempts remaining`); await new Promise((resolve) => setTimeout(resolve, 1000)); return fetchAsterDEXData(retries - 1); } throw error; } } ``` ### Scaling Your Application **Production Deployment:** - Implement connection pooling for high-throughput applications - Use caching layers (Redis/Memcached) for frequently accessed data - Set up monitoring and alerting for API performance - Plan for rate limit management and backoff strategies **Data Processing Pipeline:** - Process events in chronological order for accurate state tracking - Implement event deduplication for reliability - Use event sourcing patterns for complex trading logic - Set up data backup and recovery procedures ### Additional Resources - [Bitquery Documentation](https://docs.bitquery.io/) - [GraphQL Query Guide](/docs/graphql/query/) - [BNB Smart Chain Explorer](https://bscscan.com/) - [Production Deployment Guide](/docs/start/getting-updates/) - [API Rate Limits](/docs/graphql/limits/) ## What You Can Build with AsterDEX API Integration With Bitquery's AsterDEX integration, developers can build: - **Query all trades, swaps, and liquidity pool activity** on AsterDEX - **Monitor trader, token pairs, and pool performance** in real-time - **Stream real‑time on‑chain events** (swaps, stop loss & take profit updates, liquidations) as they occur ## Related Resources ### Bitquery Platform - [Bitquery GraphQL IDE](https://ide.bitquery.io/) - [Bitquery Documentation](https://docs.bitquery.io/) - [BNB Smart Chain APIs](/docs/blockchain/BSC/) ### Support For technical support and questions: - **Bitquery Support**: [Telegram Community](https://t.me/bloxy_info) --- _This comprehensive AsterDEX API documentation provides complete coverage of perpetual futures trading data on BNB Smart Chain. From order lifecycle tracking to liquidation monitoring, developers have access to all the tools needed to build sophisticated DeFi trading applications. All API examples include real contract addresses and working GraphQL queries for immediate implementation._ --- ## 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 DEXtrades API URL: https://docs.bitquery.io/docs/blockchain/BSC/bsc-dextrades/ BNB Chain DEXtrades API: get BNB Chain DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Built for traders and analytics teams. # BNB 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 **9 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/ BNB Chain Gra Fun API: query and stream BNB Chain on-chain data with Bitquery GraphQL examples for developers. Keep queries fast with indexed filters. # 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 **9 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 :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. 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. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: :::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 **9 chains in one API**. Use this page when you need **historical PancakeSwap data older than ~30 days**, raw per-swap detail, or call / event context. ::: 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 - **Cloud Solutions**: Access EVM data through AWS, GCP, and Snowflake or your custom cloud solution. - **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 Using [this](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades) API we could query the most recent trades on PancakeSwap.
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](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades---Stream_2) subscription allows to subscribe to the latest trades on Pancake Swap.
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 Using [this](https://ide.bitquery.io/Mempool---Latest-BSC-PancakeSwap-v3-dextrades---Stream_1) subscription you could stream the latest trades in the Mempool, that is streaming the unconfirmed trades.
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](https://ide.bitquery.io/BSC-PancakeSwap-v3-Trades-for-a-token) API endpoint returns the latest trades of a particular token on Pancake Swap. The token address is `0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82` for this example. You could also stream the latest trades of the mentioned token using this [subscription](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 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-on-pancakeswap-bsc). > 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" } } } } ) { Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } 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) } } } ```
## 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. Try out the API [here](https://ide.bitquery.io/trade_volume_bsc_pancakeswap).
Click to expand GraphQL query ```graphql query MyQuery { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" } } Dex: { OwnerAddress: { is: "0x0bfbcf9fa4f9c56b0f40a671ad40e0805a091865" } } } TransactionStatus: { Success: true } Block: { Time: { since: "2025-02-12T00:00:00Z" } } } ) { 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 Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. Try out the API [here](https://ide.bitquery.io/get-metadata-pancakeswap) in the Bitquery Playground.
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](https://ide.bitquery.io/bsc-pancakeswap-ohlc-using-trading-api) API endpoint provides the OHLC/ K-Line data for a given token against other specified token. 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](https://ide.bitquery.io/Percentage-price-change-for-a-pancake-swap-token) query returns the price change percentage for a token traded on Pancake Swap in the time periods of `24hr`, `1hr` and `5 min` using [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](https://ide.bitquery.io/New-pools-created-on-PancakeSwap-v3) query returns the latest liquidity pool creation events on Pancake Swap.The same event could be streamed using [this](https://ide.bitquery.io/Stream---New-pools-created-on-PancakeSwap-v3) subscription. 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. Using [this](https://ide.bitquery.io/Stream---Liqiidity-add-for-all-tokens-on-PancakeSwap-v3) subscription we can subscribe to the liquidity addition event for liquidity pools on Pancake Swap and get the addition events 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 Using [this](https://ide.bitquery.io/Stream---Liquidity-remove-for-all-tokens-on-PancakeSwap-v3) subscription, liquidity removal events could be streamed for Pancake Swap Exchange.
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](https://ide.bitquery.io/Pool-reserves-on-Pancakeswap-v3-pool) endpoint returns the latest pool reserves for a Pancake Swap liquidity pool by specifying the pair address of the currencies, which is `0xafb2da14056725e3ba3a30dd846b6bbbd7886c56` for this example.
Click to expand GraphQL query **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```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 } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql { EVM(dataset: combined, network: bsc) { BalanceUpdates( where: { Currency: { SmartContract: { in: [ "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82" "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" ] } } BalanceUpdate: { Address: { is: "0xafb2da14056725e3ba3a30dd846b6bbbd7886c56" } } } ) { sum(of: BalanceUpdate_Amount, selectWhere: { gt: "0" }) Currency { Name Symbol SmartContract Decimals } } } } ```
## All Pairs of a Token on Pancake Swap [This](https://ide.bitquery.io/All-pools-of-a-token-on-pancake-swap_2) query returns all the the token pairs for the specified currency on Pancake Swap. 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: query BNB Chain Uniswap trades, pools, and prices with Bitquery GraphQL DEX APIs. Copy GraphQL snippets for production apps. # BSC Uniswap API This section provides you with a set of queries that provides an insight about the Uniswap DEX on BSC. ## 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"}, Protocol: {is: "uniswap_v3"}}}} ) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` ## Get Latest Trades on Uniswap v3 Below query will subscribe you to the latest DEX Trades on BSC Uniswap v3. Try out the API [here](https://ide.bitquery.io/uniswap-v3-trades-bsc) ```graphql query MyQuery { EVM(dataset: realtime, network: bsc) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} 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 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-on-uniswapv3-bsc). ```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: "uniswap_v3"}}}} ) { Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } 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) } } } { "network": "bsc", "token": "0x55d398326f99059ff775485246999027b3197955" } ``` ## OHLC in USD of a Token This query retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on Uniswap v3 over a defined time period and interval. You can try out the API [here](https://ide.bitquery.io/OHLC-on-BSC-Uniswap-v3) on Bitquery Playground. ```graphql { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( orderBy: {descendingByField: "Block_testfield"} where: {Trade: {Currency: {SmartContract: {is: "0x55d398326f99059ff775485246999027b3197955"}}, PriceAsymmetry: {lt: 0.1}, Dex: {ProtocolName: {is: "uniswap_v3"}}, 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: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } count } } } ``` ## 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 `0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c`. Try out the API [here](https://ide.bitquery.io/trade_volume_bsc_uniswapv3). ```graphql query MyQuery { EVM(network: bsc) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"}}}, TransactionStatus: {Success: true}, Block: {Time: {since: "2025-02-12T00:00:00Z"}}} ) { 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 will fetch you the top bought tokens on uniswap v3. Try out the query [here](https://ide.bitquery.io/top-bought-tokens-on-bsc-uniswap-v3). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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" } ``` ## Get top sold tokens on uniswap v3 This query will fetch you the top bought tokens on uniswap v3. Try out the query [here](https://ide.bitquery.io/top-sold-tokens-on-bsc-uniswap-v3). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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" } ``` ## Get Metadata of a token Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. Try out the API [here](https://ide.bitquery.io/get-metadata_1) in the Bitquery Playground. ```graphql query MyQuery { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Currency: {SmartContract: {is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"}}, Dex: {ProtocolName: {is: "uniswap_v3"}}}} ) { 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 Documentation: query and stream BNB Chain on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 **9 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 Kafka or gRPC streams. # BSC Balance API :::caution Deprecated API `EVM.BalanceUpdates` was deprecated as of **20 May 2026** and removed on **15 June 2026**. Use **`EVM.Balances`** (this page) instead. ::: 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/ BSC Data - BNB Chain Export for Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # BSC Data - BNB Chain Bitquery provides **BSC (BNB Chain) blockchain data dumps** in **Parquet format**, 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: ``` 35000000_35000049.parquet ``` ## Real-Time vs Batch Data Access Cloud data dumps 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 API: query and stream BNB Chain on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 API: query and stream BNB Chain on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 API - Bitquery: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Built for traders and analytics teams. # 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 **9 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/) - [PumpFun 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 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 **[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. :::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 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 Trades API](/docs/blockchain/robinhood/robinhood-trades). --- ## Balance Update Cube URL: https://docs.bitquery.io/docs/cubes/balance-updates-cube/ How the BalanceUpdates cube models per-change balance history, what Type attribution it offers, and when to use Balances or Holders instead. # Balance Update Cube :::danger EVM and Tron: `BalanceUpdates` sunsets 10 August 2026 `EVM.BalanceUpdates`, `EVM.TokenHolders` and `Tron.BalanceUpdates` **stop working on 10 August 2026**. They still return live data today, so nothing has broken yet — but every query using them needs migrating before that date. (`EVM.TokenHolders` has already gone and now returns `no table can query TokenHolder`.) Move to the [**`Balances` and `Holders` cubes**](/docs/cubes/balances-cube), which read from aggregate-state tables and return the current balance directly, so you no longer sum deltas yourself. See the [migration mapping](/docs/cubes/balances-cube#migrating-from-balanceupdates). **Solana is not affected.** `Solana.BalanceUpdates` and `Solana.InstructionBalanceUpdates` are the current APIs there and are not deprecated — Solana has no `Balances` cube. This page remains the right reference for Solana. **Per-change becomes per-day, by design.** `Balances` carries **daily aggregates** (`Block.Date`), not one row per change, so balance history is a single cheap query rather than a scan you aggregate yourself. What does not carry over is sub-daily attribution: `BalanceUpdates` exposes `Type` (`transfer`, `fee`, `block_reward`, …) per change and the daily grain has no equivalent. If you need *why* a balance moved rather than *what it became*, reconstruct it from [`Transfers`](/docs/cubes/transfers-cube) plus transaction context. ::: Our `BalanceUpdates` cube is designed to provide historical and realtime balance updates. This cube provides multiple ways to query historical balance data. ## What is Balance Update? Any update (Change) in the balance for any address by any means is a balance update. `BalanceUpdates` covers various types of balance changes on the blockchain depending on the blockchain, including token transfers, miner/validator rewards, staking-related on-chain rewards, fees, etc. Let’s see an example of the BalanceUpdates API. You can run the following api [using this link](https://ide.bitquery.io/Balance-update-API-explanation). ```graphql { EVM(dataset: realtime, network: eth) { BalanceUpdates( limit: {count: 100} where: {BalanceUpdate: {Amount: {ge: "0.001"}, AmountInUSD: {ge: "1"}, Address: {in: ["0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8"]}}} orderBy: {descending: Block_Time} ) { BalanceUpdate { Address Amount AmountInUSD Id Type URI } Block { Number Time } Currency { Name SmartContract Symbol } Log { LogAfterCallIndex Index } Transaction { Hash } } } } ``` Let’s understand the BalanceUpdate cube based on the above API example. In this API, we get balance updates for the two addresses mentioned, where the currency is ETH(0x) and USDT, the date is after 1 January 2024, and the amount is greater than 0.001, and the USD amount of the balance update is greater than 1. As a result, we get balance update amount, currency, block, transaction, and log data. As you can see, we have used many filters in the `where` condition. Our filtering is very flexible to help you pull balance updates in a block, transaction, for an address, currency, NFT, etc. It doesn't stop there; you can also check balance updates of specific amounts or time, and in addition, you can try getting balance updates of various types, for example, getting balance updates which are ` Block rewards`` or `fee``or`transfers` . ## Does Balance Update include the Transaction Fees? When querying balance updates for a specific address, it's important to understand whether the balance updates reflect the inclusion of transaction fees. This can be clarified through the following query and explanation: ### Query ```graphql query MyQuery { EVM(dataset: archive, network: eth) { Transactions( where: { Transaction: { From: { is: "0x000338F2C046EE21C0a348481f3b21e251bf6dAA" } } } ) { Total_Fees: sum(of: Fee_SenderFee) } } EVM(dataset: archive, network: eth) { BalanceUpdates( where: { BalanceUpdate: { Address: { is: "0x000338F2C046EE21C0a348481f3b21e251bf6dAA" } } Block: { Time: { till: "2024-06-30T23:59:59Z" } } } ) { Currency { Name SmartContract Symbol } balance: sum(of: BalanceUpdate_Amount, selectWhere: { gt: "0" }) } } } ``` ### Query Result ```json { "EVM": { "BalanceUpdates": [ { "Currency": { "Name": "Ethereum", "SmartContract": "0x", "Symbol": "ETH" }, "balance": "0.010000000000000000" } ], "Transactions": [ { "Total_Fees": "0.000466997357182825" } ] } } ``` ### Explanation - **Transactions**: This part of the query calculates the total transaction fees paid by the specified address (`0x000338F2C046EE21C0a348481f3b21e251bf6dAA`). The total fees are returned as `0.000466997357182825 ETH`. - **BalanceUpdates**: This part of the query calculates the total balance updates for the specified address up to the given time (`2024-06-30T23:59:59Z`). The balance is returned as `0.010000000000000000 ETH`. ### Calculation To determine the final balance after accounting for transaction fees, you can subtract the total transaction fees from the balance updates: ``` Final Balance = BalanceUpdates - Total_Fees = 0.010000000000000000 ETH - 0.000466997357182825 ETH = 0.009533002642817175 ETH ``` 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. In this example, the final balance after accounting for transaction fees is `0.009533002642817175 ETH`. ## Aggregation in BalanceUpdates Cube We usually perform aggregations in real time to maintain API flexibility. BalanceUpdate cube provides powerful aggregation, which can help aggregate data based on time, amount, address, currency, type, transaction, block, NFT, etc. Using aggregation, you can balance an address at any given date, time, or block height. Let’s understand with an example. You can run following query [using this link](https://ide.bitquery.io/Balance-of-an-address_4). **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Balances( where: { Balance: { Address: { is: "0xcf1DC766Fc2c62bef0b67A8De666c8e67aCf35f6" } } } orderBy: { descending: Balance_Amount } ) { Currency { Name } Balance { Amount(selectWhere: { gt: "0" }) } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: combined, network: eth) { BalanceUpdates( where: { BalanceUpdate: { Address: { is: "0xcf1DC766Fc2c62bef0b67A8De666c8e67aCf35f6" } } } orderBy: { descendingByField: "balance" } ) { Currency { Name } balance: sum(of: BalanceUpdate_Amount, selectWhere: { gt: "0" }) } } } ```
In the above query, we are summing the balance update amount to get the current address balance for all tokens. Another variant is where we get balance, which is earned using a block reward till 1st Jan 2024. You can run following query [using this link](https://ide.bitquery.io/Block-reward-balance). ```graphql query MyQuery { EVM(dataset: combined, network: eth) { BalanceUpdates( where: { BalanceUpdate: { Address: { is: "0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326" } } } ) { Currency { Name } Block_reward_balance: sum( of: BalanceUpdate_Amount selectWhere: { gt: "0" } if: { BalanceUpdate: { Type: { is: block_reward } } Block: { Date: { till: "2024-01-01" } } } ) } } } ``` You can write the above query in the following manner, too. You can run following query [using this link](https://ide.bitquery.io/Balance-of-address-based-on-block-reward---alternative-way). ```graphql query MyQuery { EVM(dataset: combined, network: eth) { BalanceUpdates( where: { Block: { Date: { till: "2024-01-01" } } BalanceUpdate: { Type: { is: block_reward } Address: { is: "0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326" } } } ) { Currency { Name } Block_reward_balance: sum(of: BalanceUpdate_Amount) } } } ``` Let’s show another example where we aggregate data based on currency to get common token holders of NFT tokens. You can run following query [using this link](https://ide.bitquery.io/Common-token-holder_1). ```graphql { EVM(dataset: combined) { BalanceUpdates( orderBy: { descendingByField: "token1" } limit: { count: 1000 } where: { Currency: { SmartContract: { in: [ "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d" "0x60e4d786628fea6478f785a6d7e704777c86a7c6" ] } } } ) { BalanceUpdate { Address } token1: sum( of: BalanceUpdate_Amount if: { Currency: { SmartContract: { is: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d" } } } selectWhere: { gt: "0" } ) token2: sum( of: BalanceUpdate_Amount if: { Currency: { SmartContract: { is: "0x60e4d786628fea6478f785a6d7e704777c86a7c6" } } } selectWhere: { gt: "0" } ) } } } ``` --- ## 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 supersede the older `BalanceUpdates` approach of summing deltas yourself. They 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`, which are the current APIs there — not deprecated. ::: ## 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 TokenHolders($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 [Bitquery Cloud exports](/docs/cloud/) 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`. | ## Migrating from `BalanceUpdates` If you previously summed balance deltas, the translation is mechanical: | Old (`BalanceUpdates`) | New | | --- | --- | | `BalanceUpdates(where: {BalanceUpdate: {Address: {is: …}}})` | `Balances(where: {Balance: {Address: {is: …}}})` | | `balance: sum(of: BalanceUpdate_Amount, selectWhere: {gt: "0"})` | `Balance { Amount(selectWhere: {gt: "0"}) }` | | `BalanceUpdate { Address }` | `Balance { Address }` | | `BalanceUpdate { AmountInUSD }` | `Balance { AmountInUSD }` | | Top holders via `sum` + `orderBy: {descendingByField: "balance"}` | `Holders(date: …, orderBy: {descending: Balance_Amount})` | The important conceptual change: **you no longer aggregate.** `Balances` already holds the summed state, so a `sum(of: …)` over balance updates becomes a plain field read. :::danger Deadline: 10 August 2026 `EVM.BalanceUpdates`, `EVM.TokenHolders` and `Tron.BalanceUpdates` **sunset on 10 August 2026**. They still return live data today, so nothing has broken yet — but anything still calling them stops working on that date. `EVM.TokenHolders` has already been withdrawn ahead of the others and now returns `no table can query TokenHolder`. ::: ### Per-change history becomes daily aggregates This is the deliberate design change, not a missing feature. `BalanceUpdates` gave you **one row per change**. `Balances` gives you **one row per address per day**, exposed as `Block.Date`. For most balance questions the daily grain is what you actually wanted, and it is far cheaper: a 30-day balance history is one query returning 30 rows, rather than a scan over every change in that period which you then aggregate yourself. ```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) | What genuinely does not carry over is **sub-daily change attribution**. `BalanceUpdates` exposed `Type` (`transfer`, `fee`, `block_reward`, …) per change; the daily aggregate has no equivalent. If you need to know *why* a balance moved rather than *what it became*, reconstruct it from [`Transfers`](/docs/cubes/transfers-cube) plus transaction context. ## Related - [Address Labels API](/docs/labels/address-labels-api) — identify which of those addresses are exchanges, contracts, or known entities - [Balance Updates cube](/docs/cubes/balance-updates-cube) — per-change history and change attribution - [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. | --- ## 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 API Documentation: query and stream Base on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # 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 **9 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) ## 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 :::caution Deprecated APIs On EVM, **`BalanceUpdates`** and **`TokenHolders`** were deprecated as of **20 May 2026** and removed on **15 June 2026**. Use **`EVM.Balances`** (this page) and **[Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api)** (`EVM.Holders`) instead. ::: 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/ Base Bankr (Doppler) API: query and stream Base on-chain data with Bitquery GraphQL examples for developers. Built for traders and analytics teams. # 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 **9 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/ Base Clanker API: query and stream Base on-chain data with Bitquery GraphQL examples for developers. Great for bots, dashboards, and alerts. # Base Clanker API This section provides you with a set of queries that provides an insight about the Clank fun. Clank.fun is a platform on the Base blockchain that allows users to launch and trade meme coins. Each coin is deployed as an ERC-20 token on Uniswap V3 with permanently locked single-sided liquidity of 1,000,000,000 coin. To launch a token, users must hold at least 1,000,000 $CLANKFUN tokens. Token creators earn 0.4% of the trading volume in liquidity provider (LP) fees, which can be claimed anytime on clanker.world. You can see [Uniswap guide](/docs/blockchain/Base/base-uniswap-api/) to get latest trades of these tokens, top traders, OHLCV, get token metadata, top bought tokens, top sold tokens, etc. 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 Below query will get you latest tokens created using Clank.fun. The query respose will contain `name`, `symbol`, `tokenAddress`, `deployer`, `supply`, `fid` and `positionId` of the created token. Try out the API in the Bitquery IDE playground [here](https://ide.bitquery.io/Latest-token-created-on-Clanker-on-Base). ```graphql { EVM(network: base) { Events( limit: { count: 10 } orderBy: [{ descending: Block_Time }, { descending: Transaction_Index }] where: { Log: { Signature: { Name: { is: "TokenCreated" } } } LogHeader: { Address: { is: "0x375C15db32D28cEcdcAB5C03Ab889bf15cbD2c5E" } } } ) { Block { Time } Transaction { From Hash } 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 } } } Log { Signature { Name } } } } } ``` ## Latest Token created by specific user using Clanker Below query will get you latest tokens created by a particular address using Clank.fun. The query respose will contain `name`, `symbol`, `tokenAddress`, `deployer`, `supply`, `fid` and `positionId` of the created token. Try out the API in the Bitquery IDE playground [here](https://ide.bitquery.io/Latest-token-created-on-Clanker-on-Base-by-specific-user). ```graphql { EVM(network: base) { Events( limit: { count: 10 } orderBy: [{ descending: Block_Time }, { descending: Transaction_Index }] where: { Transaction: { From: { is: "0x002f07b0d63e8ac14f8ef6b73ccd8caf1fef074c" } } Log: { Signature: { Name: { is: "TokenCreated" } } } LogHeader: { Address: { is: "0x375C15db32D28cEcdcAB5C03Ab889bf15cbD2c5E" } } } ) { Block { Time } Transaction { From Hash } 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 } } } Log { Signature { Name } } } } } ``` --- ## 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) on a free account. 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 Network Coins API: query and stream Base on-chain data with Bitquery GraphQL examples for developers. Great for bots, dashboards, and alerts. # Base Network Coins API :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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](https://ide.bitquery.io/Top-Holders-for-Aero-Token) we can get the list of Top 10 token holders for AERO Coins, where `0x940181a94A35A4569E4529A3CDfB74e38FD98631` is the contract address of the AERO coin. ```graphql query MyQuery { EVM(network: base) { BalanceUpdates( where: { Currency: { SmartContract: { is: "0x940181a94A35A4569E4529A3CDfB74e38FD98631" } } } orderBy: { descendingByField: "balance" } limit: { count: 10 } ) { BalanceUpdate { Address } balance: sum(of: BalanceUpdate_AmountInUSD, selectWhere: { ne: "0" }) 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/ Base PancakeSwap Infinity API: query and stream Base on-chain data with Bitquery GraphQL examples for developers. Built for traders and analytics teams. # Base PancakeSwap Infinity API Bitquery provides PancakeSwap Infinity (Base) data through APIs, Streams and Data Dumps. The below graphQL APIs and Streams are examples of data points you can get with Bitquery 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 Below query will subscribe you to the latest DEX Trades on PancakeSwap Infinity. Try out the API [here](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 Below query will get you Latest Price of a token on PancakeSwap Infinity. Try out the API [here](https://ide.bitquery.io/Get-Latest-Price-of-a-token-on-PancakeSwap-Infinity) ```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 This query will fetch you top traders of a token on PancakeSwap Infinity for the selected network. You can test the query [here](https://ide.bitquery.io/top-traders-of-a-token-on-pancakeswap). ```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"}}}} ) { Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } 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) } } } { "network": "base", "token": "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } ``` ## OHLC in USD of a Token This query retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on PancakeSwap Infinity over a defined time period and interval. You can try out the API [here](https://ide.bitquery.io/OHLC-on-BASE-pancakeswap-infinity) on Bitquery Playground. ```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: { ProtocolName: { is: "pancakeswap_infinity" } } } } 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 } } } ``` ## 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 `0x22af33fe49fd1fa80c7149773dde5890d3c76f3b` on PancakeSwap Infinity. Try out the API [here](https://ide.bitquery.io/trade_volume_base_pancakeswap_infinity). ```graphql query MyQuery { EVM(network: base) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } } Dex: { ProtocolName: { is: "pancakeswap_infinity" } } } TransactionStatus: { Success: true } Block: { Time: { since: "2025-02-12T00:00:00Z" } } } ) { 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 This query will fetch you the top bought tokens on PancakeSwap Infinity. Try out the query [here](https://ide.bitquery.io/top-bought-tokens-on-pancakeswap_infinity). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "pancakeswap_infinity"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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": "base" } ``` ## Get top sold tokens on PancakeSwap Infinity This query will fetch you the top bought tokens on PancakeSwap Infinity. Try out the query [here](https://ide.bitquery.io/top-sold-tokens-on-pancake-infinty). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "pancakeswap_infinity"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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": "base" } ``` ## Get Metadata of a token Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. Try out the API [here](https://ide.bitquery.io/get-metadata-for-base-pancakeswap-infnity-token) in the Bitquery Playground. ```graphql query MyQuery { EVM(network: base, dataset: realtime) { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { SmartContract: { is: "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } } 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 Kafka or gRPC 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 - **Historical Data**: Access complete historical balance change data since Base genesis - **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 - Historical data with complete change history - 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: query Base Uniswap trades, pools, and prices with Bitquery GraphQL DEX APIs. Built for traders and analytics teams. # 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 **9 chains in one API**. Use this page when you need **historical Base Uniswap data older than ~30 days**, raw per-swap detail, or call / event context. ::: Bitquery provides Uniswap data through APIs, Streams and Data Dumps. ## 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: { Trade: { Dex: { ProtocolFamily: { is: "Uniswap" } } } } ) { Block { Time } Transaction { Hash } Trade { Dex { ProtocolName SmartContract } Buy { Amount Buyer Currency { Symbol SmartContract } } Sell { Amount Seller Currency { Symbol SmartContract } } } } } } ``` `ProtocolFamily: "Uniswap"` covers every Uniswap version on Base. Narrow to one with `ProtocolName` (for example `uniswap_v3`), or to a single pool with `Trade: { Dex: { SmartContract: { is: "" } } }`. The below graphQL APIs and Streams are examples of data points you can get with Bitquery for Uniswap on Base. 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 Below query will subscribe you to the latest DEX Trades on Uniswap v3. Try out the API [here](https://ide.bitquery.io/uniswap-v3-trades_2) ```graphql query MyQuery { EVM(dataset: realtime, network: base) { DEXTrades( where: { Trade: { Dex: { ProtocolName: { is: "uniswap_v3" } } } } 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 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-on-uniswapv3_4). ```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: "uniswap_v3"}}}} ) { Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } 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) } } } { "network": "base", "token": "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } ``` ## OHLC in USD of a Token This query retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on Uniswap v3 over a defined time period and interval. You can try out the API [here](https://ide.bitquery.io/OHLC-on-BASE-Uniswap-v3) on Bitquery Playground. ```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: { ProtocolName: { is: "uniswap_v3" } } } } 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 } } } ``` ## 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 `0x22af33fe49fd1fa80c7149773dde5890d3c76f3b`. Try out the API [here](https://ide.bitquery.io/trade_volume_base_uniswapv3). ```graphql query MyQuery { EVM(network: base) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } } } TransactionStatus: { Success: true } Block: { Time: { since: "2025-02-12T00:00:00Z" } } } ) { 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 will fetch you the top bought tokens on uniswap v3. Try out the query [here](https://ide.bitquery.io/top-bought-tokens-on-uniswap-v3). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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": "base" } ``` ## Get top sold tokens on uniswap v3 This query will fetch you the top bought tokens on uniswap v3. Try out the query [here](https://ide.bitquery.io/top-sold-tokens-on-uniswap-v3). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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": "base" } ``` ## Get Metadata of a token Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. Try out the API [here](https://ide.bitquery.io/get-metadata-for-base-uniswap-token) in the Bitquery Playground. ```graphql query MyQuery { EVM(network: base, dataset: realtime) { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Currency: { SmartContract: { is: "0x22af33fe49fd1fa80c7149773dde5890d3c76f3b" } } Dex: { ProtocolName: { is: "uniswap_v3" } } } } ) { Trade { Currency { Name Symbol SmartContract ProtocolName HasURI Fungible Decimals } } } } } ``` ## Building with Bitquery and Uniswap API Check [this](/docs/usecases/base-sniper-bot/) guide to get started with building projects with real world value using Bitquery Uniswap 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 Kafka or gRPC 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/ Base Zora API: query and stream Base on-chain data with Bitquery GraphQL examples for developers. Scale further with Kafka or gRPC streams. # 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 This query retrieves the list of newly created tokens on Zora Launchpad by monitoring transfers where new tokens are minted (sender is the zero address) with a specific amount. Try out the API [here](https://ide.bitquery.io/Newly-created-zora-tokens#) in the Bitquery IDE. ```graphql { EVM(network: base) { Transfers( orderBy: { descending: Block_Time } limit: { count: 10 } where: { Call: { Create: true } Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } Amount: { eq: "1000000000" } } Transaction: { To: { is: "0x5ff137d4b0fdcd49dca30c7cf57e578a026d2789" } } } ) { Transfer { Sender Receiver Amount AmountInUSD Currency { Name Symbol SmartContract Decimals } } Transaction { From To Hash } Block { Time } } } } ``` You can also stream the latest tokens created in real-time using [this subscription](https://ide.bitquery.io/Newly-created-zora-tokens-stream). ## 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 saved IDE query also matches transactions with **`Transaction.From`** equal to `0x152a04d9fde2396c01c05f065a00bd5f6edf5c88d` in the same `any` group—adjust or remove that branch if you only need wallet-based matches. [Run in Bitquery IDE](https://ide.bitquery.io/all-zora-trades-for-a-specific-wallet-up-till-a-block-height) ```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: "0x152a04d9fde2396c01c05f065a00bd5f6edf5c88d" } } } ], 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 } } } } } ``` **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 API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 **9 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 last 8 hours of Solana Instructions data so this query will not return anything for the Believe Launchpad token which was created more than 8 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 API: query and stream BNB Chain on-chain data with Bitquery GraphQL examples for developers. Great for bots, dashboards, and alerts. # Binance Meme Rush API :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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/) - [PumpFun 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 - **Cloud Solutions**: Access EVM data through AWS, GCP, and Snowflake integrations - **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) ::: Try the API example [here](https://ide.bitquery.io/Get-bonding-curve-progress-for-a-specified-meme-rush-token).
Click to expand GraphQL query ```graphql query MyQuery ($token: String){ EVM(dataset: combined, network: bsc) { BalanceUpdates( where: {BalanceUpdate: {Address: {is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b"}}, Currency: {SmartContract: {is: $token}}} orderBy: {descendingByField: "balance"} ) { Currency { Name } balance: sum(of: BalanceUpdate_Amount) BalanceUpdate { Address } Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($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%. You can run and test the saved query [here](https://ide.bitquery.io/Meme-Rush-Tokens-between-95-and-100-bonding-curve-progress_1).
Click to expand GraphQL query ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { BalanceUpdates( limit: { count: 10 } where: { BalanceUpdate: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } Currency: { SmartContract: { startsWith: "0x4444" } } } orderBy: { descendingByField: "balance" } ) { Currency { SmartContract Name } balance: sum( of: BalanceUpdate_Amount selectWhere: { ge: "200000000", le: "240000000" } ) BalanceUpdate { Address } Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($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. You can test the query [here](https://ide.bitquery.io/marketcap-total-holders-metrics-query).
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) } BalanceUpdates(where: { Currency: { SmartContract: { is: $token } } }) { holders: uniq(of: BalanceUpdate_Address, selectWhere: { gt: "0" }) } } 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. Test the API [here](https://ide.bitquery.io/Get-liquidity-of-a-meme-rush-token).
Click to expand GraphQL query **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```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 { Amount } Balance { Address } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { BalanceUpdates( where: {BalanceUpdate: {Address: {is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b"}}, Currency: {SmartContract: {is: "0x44442202ff27ee2297c128d0c1ae43a0fbb35701"}}} orderBy: {descendingByField: "balance"} ) { Currency { Name } balance: sum(of: BalanceUpdate_Amount) BalanceUpdate { Address } } } } ```
--- ## Bitcoin API Documentation URL: https://docs.bitquery.io/docs/blockchain/Bitcoin/ Bitcoin API Documentation: query and stream Bitcoin on-chain data with Bitquery GraphQL examples for developers. Copy GraphQL snippets for production apps. # 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 API - Get BTC Balance: query and stream Bitcoin on-chain data with Bitquery GraphQL examples for developers. # 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) } } } ``` ## 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 API: query and stream Bitcoin on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # 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 Coinpath API - Trace BTC Fund Flows Across Addresses: query and stream Bitcoin on-chain data with Bitquery GraphQL examples for developers. # 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 :::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 Data - Snowflake, AWS S3, GCP BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Bitcoin Data Bitquery provides **Bitcoin blockchain data dumps** in **Parquet format**, 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: ``` 859350_859399.parquet ``` ## Real-Time vs Batch Data Access Cloud data dumps 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 Outputs: query and stream Bitcoin on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # 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 Transactions: query and stream Bitcoin on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 API: query and stream Bitcoin on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # 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 trial expired, or a free tier hasn't been activated. - 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/). ### `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 various interfaces such as GraphQL APIs. ## 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(trigger_on: head) { Transactions { Block { Hash Number Date } count } } } ``` ## Cloud Data Storage If you build your applications in cloud or you need raw data for deep investigations or even machine learning algorithms, use the cloud data storage. It contains optimized data for applications on different levels - from the raw data from blockchain nodes to the parsed protocols as DEX (decentralized exchanges) or NFT (non-fungible tokens). ![AWS S3 bucket](/img/aws/s3_bucket.png) ## 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` | ## 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/ API Comparison: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Great for bots, dashboards, and alerts. # 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 | ## 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 BalanceUpdates, 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) on a free account. ```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, plus the Trading APIs, Perpetuals, Stablecoins, Prediction Markets and Cross-chain collections | | `https://graphql.bitquery.io` | Bitcoin, Litecoin, Bitcoin Cash, Bitcoin SV, 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 20%) - 💳 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 20%) - 💳 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 | $39 | 100,000 | 30 | 3 | — | — | — | 1 | | **Pro** | $99 | $79 | 1,000,000 | 90 | 6 | 100 | 100,000 min | 5 GB | 2 | | **Scale** ⭐ (recommended) | $299 | $239 | 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 20% 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 | $40 | | **Stream-minutes** | +200,000 streaming minutes | $50 | $40 | | **Stream data** | +5 GB of stream traffic | $50 | $40 | | **MCP credits** | Credits for MCP / AI agent requests | from $15/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: stream-minutes and stream data drop about 40% at the mid pack and 70% at the top. ### 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 | | --- | --- | --- | | Ethereum, BNB Chain (BSC), Base, Arbitrum, Optimism, Polygon, Tron, Robinhood | **Historical Trading Data** · **Historical Transfers + Balances + Holders** | from $105/mo per chain, per pack | | Solana | **Historical OHLCV & Token Price** · **Historical Token Transfers & Balances** | $210/mo · $400/mo | | Bitcoin, Bitcoin Cash, Litecoin, Dogecoin, Dash, Zcash | **Chain Data (historical included)** | $200/mo per chain | | Polymarket | **Historical Data** (from 1 September 2025) | $120/mo | | All chains | **Address Label Data (multi-chain)** | $79.20/mo | Bundles cover the seven 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 have no self-serve historical add-on — historical access to those is part of Enterprise. 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).** When you first sign up, you’ll get 10K free points for the first month on the Developer plan. 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 20%), pay by card, cancel anytime. - **Top up credits** — at step 2 of checkout, add **1 Million API points**, **100k Stream-minutes**, or **1 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? When you select `dataset:realtime` you are charged at 5 points per cube irrespective of the number of records you query. Here's how it works: - **Rate**: Each cube is charged at the rate of 5 points per cube. If multiple cubes are used within a single query, each is billed individually. ### Example ```graphql { EVM(network: eth, dataset: realtime) { Transactions { Block { Hash } } } } ``` In the example above, querying the `Transactions` data cube within the Ethereum (`eth`) network consumes 5 points. The complexity of the query or the volume of data requested does not affect the points charged. ## 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 This guide provides a structured path to learn Bitquery APIs progressively, from basic concepts to advanced implementations. ## 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 effectively 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/)** - Understand query structure and syntax 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)** - Understand and fix common issues ## Advanced (2-4 hours) 1. **[Platform-Specific APIs](/docs/blockchain/Solana/)** - Deep dive into Solana, Ethereum, etc. 2. **[Integration Examples](/docs/category/how-to-guides/)** - Real-world application examples 3. **[Performance Optimization](/docs/graphql/optimizing-graphql-queries/)** - Optimize your queries for production 4. **[Contributing](/docs/contribution-guidelines)** - Help improve the documentation ## Choose Your Path ### For Traders - Start with **[Crypto Price APIs](/docs/start/starter-queries#latest-price-of-any-token)** - Learn **[Real-time Price Streams](/docs/start/starter-subscriptions)** - 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, and AML forensics 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, and Robinhood Chain. 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** | Free tier with a Bitquery account. Beyond that it meters against your existing plan. | | **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`, then sign in with your Bitquery account when the first tool runs. - **Cursor:** Settings, MCP, Add new MCP server, URL `https://mcp.bitquery.io`; or put the `mcp-remote` command in `.cursor/mcp.json`. No API key is pasted anywhere; OAuth 2.1 handles sign-in and a free 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` 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`. 4. Authenticate with your Bitquery account when prompted. ### Cursor Easiest path: 1. Settings → **MCP → Add new MCP server**. 2. URL: `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. ### 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`. 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 free 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 or gRPC stream. - **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."_ 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; free account works | | 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 nine chains | | 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` - `Solana` root — Solana - `Tron` root — Tron - `Hyperliquid` root — Hyperliquid perpetuals - `Trading` root — cross-chain prices and trades, no `network` argument **Everything else is V1 only**: Bitcoin, Litecoin, Bitcoin Cash, Dogecoin, Dash, Zcash, Cardano, Ripple, Stellar, Algorand, Avalanche, Celo, Fantom, Cronos, Klaytn, Moonbeam. V1 groups chains under a shared root with a `network` argument: - `bitcoin(network: bitcoin | litecoin | bitcash | dogecoin | dash | zcash)` - `ethereum(network: avalanche | celo_mainnet | fantom | cronos | klaytn | moonbeam | ...)` - `cardano(network: cardano)`, `ripple(network: ripple)`, `stellar(network: stellar)`, `algorand(network: algorand)`, `solana(network: solana)` **Ethereum, BSC, Tron and Polygon are being migrated off V1. Always query them on V2**, even though the V1 schema still accepts them. **Root names carry the version.** V1 roots are lowercase — `ethereum(`, `tron(`, `solana(`, `bitcoin(`. V2 roots are capitalised — `EVM(`, `Tron(`, `Solana(`, `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`. 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. 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. --- ## 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` is currently broken** — every Solana cube returns a 500 on `dataset: combined`. Use `realtime` for recent and `archive` for history. **`BalanceUpdates` is being retired.** Do not write new queries against it. **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 legs.** Deduplicate on `(TransactionHeader.Hash, Trader.Address, Side, Amounts.Base)` before reporting exact trade counts or volumes. A row is a swap **leg**, 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. --- ## 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), what the archive actually contains, rate limits, history depth and cross-chain coverage. # Bitquery vs Hyperliquid's free data 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. The public `s3://hyperliquid-archive` bucket is narrower than people assume: | | Included | Not included | | --- | --- | --- | | `market_data/` | **L2 book snapshots** | — | | `asset_ctxs/` | Asset contexts | — | | Everything else | — | **Trades, candles and spot data are explicitly not provided via S3** | Hyperliquid's own documentation also states that data is uploaded roughly **once a month**, with **no guarantee of timely updates**, and that **data may be missing**. So if you are backtesting on fills, building candles from trades, or studying spot markets, the free archive does not cover it — 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 for **your own account**. 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 | Not served | 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. ::: ## Full comparison | Capability | HL Info API | HL S3 archive | Bitquery | | --- | --- | --- | --- | | Cost | Free | Free | Paid | | Book granularity | L2 aggregated (L3 for own account only) | L2 snapshots | **L3 market-by-order, market-wide** | | Trades / fills market-wide | Bare price/size/side | **Not provided** | Full: direction, fees, leverage, size-before, realized PnL | | Candles | Via REST, pagination-limited | **Not provided** | `Candles` cube, any interval | | Spot markets | Yes | **Not provided** | Yes | | Liquidations market-wide | Per-address only | Not provided | Exchange-wide, with method, mark price, leverage | | Funding per trader | Per-address only | Not provided | `PerpFundings`, market-wide | | Open positions | Per-address snapshot | Not provided | `CurrentPositions`, whole market, sortable | | Raw L1 actions | Not exposed | Not provided | `SignedActions` | | Update cadence | Real time | ~Monthly, no guarantee | Real time | | Completeness guarantee | — | **Stated: data may be missing** | SLA available | | History depth | Snapshot + limited REST | Since inception (L2 only) | Rolling ~30 days via API; **full archive via [Data Lake](/docs/data-lake/)** | | Delivery | WebSocket / REST | S3 files | GraphQL, WebSocket, Kafka (protobuf) | | Rate limits | Yes, per-connection and per-endpoint | S3 egress | 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: {Symbol: {is: "BTC"}} Interval: {Time: {Duration: {eq: 3600}}} } ) { Interval { Time { Start Duration } } Market { Symbol Kind } Ohlc { Open High Low Close Volume } } } } ``` 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. - **API history depth.** The GraphQL cubes serve a rolling ~30-day window. Deeper history is a [Data Lake](/docs/data-lake/) or enterprise export, not a plan upgrade. ## Where Bitquery is decisive - **L3 with wallet attribution, market-wide** — not available from the native API at all. - **Trades, candles and spot history** — explicitly absent from the free archive. - **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. ## Next steps - [Hyperliquid API overview](/docs/perpetuals/hyperliquid) — every cube - [L3 Order Book API](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) - [Track Order Flow by Wallet](/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet) - [Blockchain Data Lake](/docs/data-lake/) — full archive access - [Data Coverage & Retention](/docs/graphql/data-coverage-retention) — exact windows per cube --- ## Blockchain Data APIs Overview URL: https://docs.bitquery.io/docs/blockchain/introduction/ Explore Bitquery multi-chain blockchain APIs for trades, transfers, balances, NFTs, mempool data, and real-time streams. # Blockchain Data APIs Bitquery provides the most comprehensive blockchain data platform, offering real-time and historical access to data across **40+ blockchains** including Bitcoin, Ethereum, Solana, BSC, Arbitrum, Base, Polygon, Tron, and more. Our platform serves as the backbone for thousands of developers building DeFi applications, 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/)** - **[opBNB](/docs/blockchain/supported-chains/)** (IDE / limited docs) - **[Robinhood](/docs/blockchain/robinhood/)** **Non-EVM Chains:** - **[Solana](/docs/blockchain/Solana/)** - **[Tron](/docs/blockchain/Tron/)** - **[TON](/docs/blockchain/supported-chains/)** (limited support) - **[Bitcoin](/docs/blockchain/Bitcoin/)** - **[Cardano](/docs/blockchain/Cardano/)** ### **V1 APIs** Our comprehensive V1 API supporting 40+ blockchains with historical data: **Supported Blockchains:** Bitcoin, Ethereum, Solana, BSC, Polygon, Bitcoin Cash, Litecoin, Bitcoin SV, Dash, Zcash, Avalanche, Klaytn, Celo, Moonbeam, Fantom, Cronos, Cosmos, Hedera, Flow, EOS, Ripple (XRP), Stellar, Algorand, Cardano, Filecoin, and more. **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/)** - Comprehensive APIs with 40+ blockchain support ## Bitquery's Core Blockchain Data Capabilities **Popular APIs:** [Solana API](/docs/blockchain/Solana/) (DEX trades, Pump.fun, Raydium) · [Polymarket API](/docs/examples/polymarket-api/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 - **Seamless Integration**: Combine historical and real-time data in single applications **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 :::note Migration Notice Chains from the Early Access Program (EAP) have moved to v2. - **Existing customers**: You can continue using the EAP endpoint without making any changes. - **New users**: You must use the v2 endpoint for all blockchains. ::: **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 **Trigger Options:** - **`trigger_on: head`**: Receive data as soon as new blocks are mined - **`trigger_on: block`**: Trigger on specific block conditions - **Custom triggers**: Set up triggers based on specific data conditions **WebSocket Endpoint**: `wss://streaming.bitquery.io/graphql` ```graphql subscription { EVM(network: eth, trigger_on: head) { DEXTrades( where: { Trade: {Amount: {gt: "10000"}} Protocol: {Name: {in: ["Uniswap", "SushiSwap"]}} } ) { Block { Time Number } Transaction { Hash From To } Trade { Amount Price BuyAmount SellAmount } Protocol { Name Type } Currency { Symbol Name } } } } ``` **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, trigger_on: head) { DEXTrades { Block { Time } Trade { Amount } Protocol { Name } } } } `, }, { 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 ### **Cloud Data Storage & Data Export** Raw and processed data available in cloud storage for machine learning, deep analysis, and data export capabilities. **Cloud Storage Features:** - **AWS S3 Integration**: Direct access to optimized data formats - **Historical Data**: Complete blockchain history since genesis - **Multiple Formats**: JSON, Parquet, Protocol Buffers, and CSV - **Partitioned Data**: Optimized for time-based and blockchain-based queries - **Compression**: Efficient storage with gzip and snappy compression **Data 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**: 10,000 API points for 1 month, no credit card required - Access to all blockchain data and real-time 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: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Covers archive history and realtime data. # 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 structured data that you can stream directly into your own systems. 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 parsed and normalized by Bitquery and stored as a **Protobuf** message. We publish the [**schema**](https://github.com/bitquery/streaming_protobuf) so you decode it on your side with a single documented definition, which is the same schema used for our Kafka streams. 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 already parsed into a structured Protobuf format and stored as objects, 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. 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), covering trades, orders, book updates, liquidations, funding, TWAPs, signed actions and OHLCV candles 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 schema lives under [`hyperliquid/`](https://github.com/bitquery/streaming_protobuf/tree/main/hyperliquid) and has three top-level entry points: | Message | Defined in | Carries | | --- | --- | --- | | `HyperliquidCoreBlockMessage` | `hyperliquid_block_message.proto` | Parsed trades, order updates, book updates, liquidations, funding, TWAPs, leverage updates and signed actions — the shape behind the [Hyperliquid cubes](/docs/perpetuals/hyperliquid) | | `HyperCoreBlock` / `HyperCoreBlocks` | `hypercore.proto` | Raw hypercore feed: fills, order statuses, raw book diffs, TWAP statuses, oracle updates, misc events, core writer actions | | `CandlesBlockMessage` | `candles.proto` | OHLCV candles per market and interval | All three are in the `hyperliquid` module of [`bitquery-pb2-kafka-package`](https://pypi.org/project/bitquery-pb2-kafka-package/), and they are the same definitions used by the `hyperliquidcore.messages.proto` and `hyperliquid.candles.proto` Kafka topics. One decoder covers both the archive and the live stream, which is the point for backtesting: the code that replays history is the code that runs in production. ```python from hyperliquid.hyperliquid_block_message_pb2 import HyperliquidCoreBlockMessage msg = HyperliquidCoreBlockMessage() msg.ParseFromString(lz4.frame.decompress(raw)) ``` The [Hyperliquid API](/docs/perpetuals/hyperliquid) serves the same datasets over GraphQL and WebSocket within the API's rolling retention window. Use the data lake when you need history beyond it — 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 a worked example, see [Extract transfers from a block](./extract-transfers/). ### 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 in Cloud](/docs/cloud/) covers curated, ready-to-use Parquet data dumps for analytics and warehousing. - [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 same 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/ Blockchain Data in Cloud from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. See examples in the Bitquery IDE. # Blockchain Data in Cloud Bitquery provides ready-to-use blockchain **data dumps** 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 Our cloud data export service delivers **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** – Complete blockchain history from genesis blocks - **Multi-Chain Support** – Access data from major blockchain networks - **Cost-Effective** – Pay only for the data you need, when you need it - **Scalable** – Handle petabytes of blockchain data with ease ## Available Blockchain Data Dumps Bitquery provides comprehensive cloud data dumps 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. ### [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. ### [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. ### [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. ### [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 legs, 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: - **Order Statuses** – Full order lifecycle: open, canceled, filled, triggered, and every rejection reason - **Book Diffs** – **L4** per-order book deltas with the owning address and order id - **Fills** – Both sides of every match, with realized PnL, fee, fee token, and liquidation detail - **Oracle Updates** – Mark, spot, and external perp price inputs, and the resulting oracle prices - **Misc Events** – Deposits, withdrawals, transfers, funding, delegation, validator rewards - **TWAP Statuses** – TWAP order state, executed size and notional, terminal status - **Core Writer Actions** – HyperEVM to HyperCore actions, with the originating EVM transaction hash **Use Cases:** Perp market microstructure research, order book reconstruction at L4, maker and taker behaviour analysis, per-wallet realized PnL, liquidation forensics, HIP-3 builder market analysis, backtesting against full order flow. ### [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. ### [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. ## 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** – Reduces storage costs by up to 90% - **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/ │ ├── order_statuses/ │ ├── book_diffs/ │ ├── fills/ │ ├── oracle_updates/ │ └── ... └── 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 dumps 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 - Easily request more files from the same bucket/prefix if you need additional data - 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_24053999.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 that can handle millions of transactions and events per second. Our cloud-native architecture supports both batch and streaming data pipelines for comprehensive blockchain analytics. ### Real-Time Streaming Architecture Build low-latency applications with **sub-second data delivery** 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** – Sub-100ms data delivery for time-sensitive applications ### Scalable Cloud Solutions Design and deploy **horizontally scalable solutions** that can handle: - **High Throughput** – Process millions of transactions per day - **Concurrent Users** – Support thousands of simultaneous connections - **Data Volume** – Handle petabytes of historical and real-time data - **Global Scale** – Deploy across multiple cloud regions for low latency ### Performance Benchmarks Our cloud solutions support: - **Latency**: Sub-100ms for real-time streams, sub-second for batch queries - **Throughput**: Millions of transactions per second processing capability - **Scalability**: Auto-scaling from zero to thousands of concurrent connections - **Availability**: 99.9% uptime SLA with multi-region redundancy - **Data Freshness**: Real-time data with <1 second delay from blockchain ## 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 Cloud data dumps are optimized for **batch analytics and historical workloads**. They provide: - **Complete Historical Data** – Access to full blockchain history - **Cost-Effective Storage** – Optimized compression reduces costs - **Batch Processing** – Ideal for ETL pipelines and scheduled analytics - **Data Warehousing** – Perfect for building comprehensive data lakes 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 ## 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/), [Solana](/docs/cloud/solana/), [Tron](/docs/cloud/tron/), [Bitcoin](/docs/cloud/bitcoin/), or [BSC](/docs/cloud/bsc/) 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 blockchain data dumps - [Solana Data Export](/docs/cloud/solana/) – Solana blockchain data dumps - [Tron Data Export](/docs/cloud/tron/) – Tron blockchain data dumps - [Bitcoin Data Export](/docs/cloud/bitcoin/) – Bitcoin blockchain and OMNI data - [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 Select blocks attribute controls real time and combined database queries in terms of which block data to include in the result set. It has the following options: * ```trunk``` (default) will include only blocks that are on the main current trunk (having the maximum height on tip) * ```tree``` all tree, combining trunk and branches * ```branches``` for only branched blocks (not on trunk) :::tip You need ```tree``` and ```branches``` only in a very special case, when you need to analyze the reorganization tree of the blockchain. ::: :::tip ```tree``` option may be faster to query in some cases ::: --- ## 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) on a free account; Solana queries go to the `eap` endpoint. 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/ Breaking Down Price Streams in Detail via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. # Breaking Down Price Streams in Detail This section is not necessary reading to start using the APIs; it explains how we have set up and designed the APIs and what algorithmic rules we follow to show data. You can go to the [examples section](/docs/trading/crypto-price-api/examples) to start using it. For how prices and volumes are computed (trade filtering, volume-weighted token/currency pricing, and field semantics), see **[Price Index Algorithm (March 11 2026 Update)](/docs/trading/crypto-price-api/price-index-algorithm)**. ## Understanding Base and Quote in Pairs API This section explains the design philosophy and algorithmic choices behind the Pairs data cube, specifically how we determine the base and quote tokens in a trading pair. In every trading pair, one token is designated as the base, and the other as the quote. The price you see is how much of the quote token is needed to buy 1 unit of the base token. For example: If SOL/USDC = 180.0, then 1 SOL costs 180 USDC. Here, SOL is the base and USDC is the quote. But how do we determine which token is the base and which is the quote? price feed: pairs -> base and quote differentiated ### The Logic Behind Quote Token Selection We use the following rules to determine the **quote** token: 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 Assets 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), we choose the native token as 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 of the above rules apply (i.e., two non-stable, non-native tokens), we determine the quote **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 ensures that the quote is the more liquid asset, which leads to more stable and usable price data. --- ## Build AI Trading Agents with Bitquery Base Chain Data URL: https://docs.bitquery.io/docs/blockchain/Base/ai-agent-base-data/ Build AI Trading Agents with Bitquery Base Chain Data: query and stream Base on-chain data with Bitquery GraphQL examples for developers. # 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 9 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 } } } } } ``` :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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.
Click to expand GraphQL query ```graphql query BaseTokenHolders($tokenAddress: String!) { EVM(network: base, dataset: combined, aggregates: yes) { BalanceUpdates( orderBy: { descendingByField: "balance" } limit: { count: 50 } where: { Currency: { SmartContract: { is: $tokenAddress } } } ) { Currency { Name Symbol SmartContract } balance: sum(of: BalanceUpdate_Amount, selectWhere: { gt: "0" }) } } } ```
**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, aggregates: yes) { BalanceUpdates( where: { BalanceUpdate: { Address: { is: $walletAddress } } } orderBy: { descendingByField: "balance" } ) { BalanceUpdate { Address } Currency { Name Symbol SmartContract } balance: sum(of: BalanceUpdate_Amount, selectWhere: { gt: "0" }) } } } ```
**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/ Build AI Trading Agents with Bitquery Solana Data: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. # 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 9 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. [Run Query](https://ide.bitquery.io/top-100-holders-of-USDC-token-on-Solana)
Click to expand GraphQL query ```graphql query MyQuery { Solana { BalanceUpdates( orderBy: { descendingByField: "BalanceUpdate_Holding_maximum" } where: { BalanceUpdate: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Transaction: { Result: { Success: true } } } ) { BalanceUpdate { Currency { Name MintAddress Symbol } Account { Address } Holding: PostBalance(maximum: Block_Slot, selectWhere: { gt: "0" }) } } } } ```
**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.com](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. ## 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-100ms pipelines, 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) on a free account. ## 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** (8 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), [early access program](/docs/graphql/dataset/EAP). - **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 9 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', 'X-API-KEY': 'BQYuTITWanwYGz0YLGdcWSADO74o5RTX', 'Authorization': 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 be using a simple fromula given below to calculate and trace the real-time balance changes. To execute this formula through code we will build two files (namely balance.js and index.js). ``` Current Balance = sum(all_balance_updates) + steam_balance_updates ``` ## 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 calculate the summation of all the Balance Updates till yet, 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 BalanceUpdates(\n where: {BalanceUpdate: {Address: {is: \"\"}}, Currency: {SmartContract: {is: \"0x\"}}}\n ) {\n sum(of: BalanceUpdate_Amount)\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': 'BQYuTITWanwYGz0YLGdcWSADO74o5RTX', '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.BalanceUpdates[0].sum) return response.data.data.EVM.BalanceUpdates[0].sum; } 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 BalanceUpdates(\n where: {BalanceUpdate: {Address: {is: \"${currentAddress}\"}}, Currency: {SmartContract: {is: \"0x\"}}}\n ) {\n sum(of: BalanceUpdate_Amount)\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. ``` 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{ BalanceUpdates( where: { BalanceUpdate: { Address: { is: "${currentAddress}" } }, Currency: {SmartContract: {is: "0x"}} } ) { BalanceUpdate { Amount } } } }`, }, }); 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 Documentation: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. Scale further with Kafka or gRPC streams. # 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 API - Query Blocks by Height, Slot & Epoch: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. # 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 API - Trace ADA Flows Across Multiple Hops: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. # 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. :::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/ Cardano Djed: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 Inputs and Outputs API: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 Mints API - Track Native Token Mints: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. # 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 API - Fees, Inputs, Outputs & Mints: query and stream Cardano on-chain data with Bitquery GraphQL examples for developers. # 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 - [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 from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. 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 ethereum data from 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. --- ## 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**. ::: :::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 ::: --- ## Contributing to V2 Documentation URL: https://docs.bitquery.io/docs/contribution-guidelines/ Contributing to V2 Documentation: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # Contributing to V2 Documentation ## New contributors Welcome to the Bitquery documentation community! We are excited to have you contribute to our [documentation](https://docs.bitquery.io/) and help us make it the best it can be. Currently, we have opened V2 APIs to contributions and will soon set up V1 for open-source contributions as well. ### How to contribute Here are the steps on how to contribute to the Bitquery documentation: 1. Find a topic to contribute to. You can browse the existing documentation to see if there are any areas that you are interested in improving, or you can check the open issues on GitHub to see if there are any specific documentation tasks that need to be done. 2. Fork the repository. Once you have found a topic to contribute to, fork the Bitquery documentation repository: [https://github.com/bitquery/streaming-data-platform-docs](https://github.com/bitquery/streaming-data-platform-docs) to your own GitHub account. This will create a copy of the repository that you can work on locally. 3. Clone the forked repository to your local machine using Git. 4. Create a new branch. Create a new branch for your changes. This will allow you to isolate your changes from the main codebase and make it easier to review and merge your changes later. 5. Make your changes. Make the necessary changes to the documentation.Be sure to follow the query explanation guidelines mentioned below. 6. Commit your changes. Once you are finished making your changes, commit your changes to your local branch. Be sure to include a descriptive commit message. 7. Push your changes to your GitHub branch. 8. Create a pull request. Create a pull request to the main Bitquery documentation repository. Be sure to include a descriptive title and description for your pull request. ![pull request](/img/pullrequest.png) 9. Respond to feedback. Once your pull request has been submitted, the maintainers of the Bitquery documentation repository will review your changes and provide feedback. Be sure to respond to any feedback that you receive. 10. Merge your pull request. Once your pull request has been approved, the maintainers of the Bitquery documentation repository will merge it into the main codebase. ### Query format and description To write a query for the Bitquery documentation, please follow the following format: - Heading in H3 - Explanation with link to saved query on IDE - Query The heading should be a concise description of the query. The explanation should provide more context about the query and why it is useful. The query should be the actual GraphQL query that you used to generate the results. ### Where can I go for help? If you need help contributing to the Bitquery documentation, please feel free to reach out to us on the telegram [https://t.me/Bloxy_info](https://t.me/Bloxy_info) ### Additional tips • Be sure to test your changes before submitting a pull request. Please use the [Bitquery GraphQL IDE](https://ide.bitquery.io/?endpoint=https://streaming.bitquery.io/graphql) to test your queries. • Be sure to write descriptive commit messages. • Be responsive to feedback from the maintainers of the Bitquery documentation repository. ## Documentation maintenance & governance To keep the docs answering what users actually ask, maintainers follow a few standing rules: - **Docs-first support.** Any question answered twice in support (Telegram/tickets) becomes a new or updated docs page within a week — the answer is already written, converting it takes ~30 minutes. Share the docs link, not a one-off reply. - **Capture IDE snippets.** A saved `ide.bitquery.io` query shared as a support answer should be embedded in the relevant docs page, not left only in chat. - **Evergreen facts.** Never embed point-in-time numbers or dated tables in a page. Express retention as rolling windows ("last 30 days", "since the chain was onboarded"). Any unavoidable absolute date lives in one place — the [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) matrix — and is linked from elsewhere. - **Ship docs with the feature.** A new chain, cube, stream, or topic ships with its docs page on day one, including its row in the retention matrix. - **Link hygiene.** `yarn check-links` runs in CI and must pass. Use root-relative internal links with a trailing slash; never absolute `https://docs.bitquery.io/...` self-links. Run `yarn check-links --report` periodically to review orphaned pages, dead ends, thin pages, and untagged code fences. - **Page checklist.** Purpose clear in the first two sentences; every query explained (when to use it, key fields, a run-in-IDE link, a note on the response); a `## Next steps` block of related links; an `` block on high-traffic pages (it emits FAQPage JSON-LD for AI answer engines). --- ## 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 nine 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 and Robinhood Chain 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: eth)`, 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, nine 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 Kafka or gRPC 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/ Query currency-level crypto prices and conversions with Bitquery Trading APIs, including GraphQL examples and streaming options. # Currency Cube The Currency Cube provides a unified, chain-agnostic price for an asset in USD, such as Bitcoin by aggregating prices and volumes from all its representations (e.g., WBTC, cbBTC, and other bridged or wrapped forms) across all supported chains. This multi-chain cryptocurrency price data approach ensures consistent pricing across different blockchain implementations. :::note Use this for cross-chain assets, not for a single token Currency prices aggregate **across chains and token representations**, so use this cube 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). Note that `Ranking` is **not** available on `Currencies` — it exists on `Trades`, `Pairs`, and `Tokens` only. ::: ### How OHLC is Calculated The OHLC values (Open, High, Low, Close) describe a **single computed cross-chain index series** for the asset over the selected interval (e.g., 60 seconds). Within each interval the cube tracks the decay-weighted, volume-weighted blend of the asset's token representations — see [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) — 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 volume-weighted blend, an extreme print on a single chain — especially a thin one — is damped and may never reach the currency candle at all. A single representation can print far outside the currency's High/Low band without moving it. 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` rather than relying on the currency candle to surface it. ::: **Volume.Quote vs Volume.Usd**: For USD-based pricing, `Volume.Quote` is the sum of quote token amounts (not USD). Use `Volume.Usd` for USD totals. See [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) for details. ```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 (March 11 2026: see Price Index Algorithm) 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 } } } } } ``` ### Supply - **`Supply`**: Currency-level supply and USD valuation metrics for the asset (aligned with the same `Supply` fields on Tokens and Pairs). See [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) for definitions of each subfield. --- ## Crypto MarketCap API & Market Data URL: https://docs.bitquery.io/docs/trading/crypto-price-api/crypto-marketcap-api/ Crypto MarketCap API & Market Data via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. # Crypto MarketCap API and Market Data The **Crypto MarketCap API** is part of the Crypto Price APIs: you can **query** USD **market capitalization** and related **supply** fields, or **stream** them in **real time** for many chains using GraphQL **subscriptions** or the **`trading.prices`** Kafka topic described in the [Crypto Price API introduction](/docs/trading/crypto-price-api/). Those metrics are returned on the **`Supply`** object on **Currencies**, **Tokens**, and **Pairs** rows (`MarketCap`, `CirculatingSupply`, `TotalSupply`, and others). Field semantics are documented in the [Supply fields reference](/docs/trading/crypto-price-api/supply-fields). For intervals, cubes, and streaming setup, use the [Crypto Price API introduction](/docs/trading/crypto-price-api/). ## How do I get the USD market cap of a single token? {#how-do-i-get-usd-market-cap-of-a-single-token} Set token **address** and read **`Supply.MarketCap`** from the query below. See the [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) for related supply fields. You can also stream this in real-time by adding the keyword "subscription" at the top. [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 } } } } ``` ## How do I list top tokens by market cap on a blockchain? {#how-do-i-list-top-tokens-by-market-cap-on-a-blockchain} In this API, we fetch top tokens by MarketCap on Solana. Change Network fields to get top tokens for a different network or remove to get top tokens across all. We also add `Volume: {Usd: {gt: 1000}` filter to remove low-volume tokens. See the [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) for related supply fields. You can also stream this in real-time by adding the keyword "subscription" at the top. [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" } } } ) { 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 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 **`Supply.TotalSupply`** and related fields from the query below. See the [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) for related supply fields. You can also stream this in real-time by adding the keyword "subscription" at the top. ```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 } } } } ``` ## How do I rank tokens by 1-hour market cap change? {#how-do-i-rank-tokens-by-1-hour-market-cap-change} Set **`Token: { Network: { is: "..." } }`** and a **1 hour** interval and read ranked **`change_mcap`** from the query below. See the [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) for related supply fields and [expressions](/docs/graphql/capabilities/expression/) for `calculate`. You can also stream this in real-time by adding the keyword "subscription" at the top. [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 } } } } } ``` ## Crypto Market Data APIs — OHLCV, K-Line, Charts, Token Prices, Volume, Supply This section aggregates commonly used queries for market data across chains, pairs, and exchanges. These examples show how to use Bitquery’s **real-time crypto price API** for getting crypto market data. You can also use the chat agent at the bottom of the docs site—it is trained on our documentation and IDE queries. ## 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 **interval** to stream OHLC, volume, and **`Supply`** (including **MarketCap**) for many tokens on that chain in one feed. The following stream provide 60 second aggregated data. For information on all available time intervals, see the supported intervals documentation [here](/docs/trading/crypto-price-api/#supported-time-intervals). [Run Query](https://ide.bitquery.io/Aggregated-Price-of-all-tokens-in-real-time-on-one-chain_1)
Click to expand GraphQL query ```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} Use **`Trading.Pairs`** with **`Currency`** and **`QuoteCurrency`** ids and your desired **interval** (for example 1s) to stream OHLC, volume, and supply metrics for that pair. [Run Query](https://ide.bitquery.io/Token-OHLC-Stream-1-second-Multi-Chains)
Click to expand GraphQL query ```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} Query **`Trading.Tokens`** with a **300s** interval, filter by **minimum USD volume**, and use **`calculate`** on OHLC open/close to derive **% change**—ideal for short-term movers and dashboards. [Run Query](https://ide.bitquery.io/5-minute-price-change-api)
Click to expand GraphQL query ```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") } } } ```
## Recommended: stream trades via `Trading.Trades` For real-time multi-chain trades **with USD price, market cap, and supply on every row** (MEV-filtered, 9 chains in one stream), subscribe to [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) — run it [in the IDE](https://ide.bitquery.io/Trading-API-Live-Trades-All-Chains). The chain-level `DEXTrades` subscriptions below are for per-protocol/pool detail and transaction context. ```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} Stream **`Solana { DEXTrades { … } }`** as a **subscription** to receive each swap with **buy/sell**, **price in USD**, and **DEX protocol** as trades are indexed. [Run Query](https://ide.bitquery.io/solana-trades-subscription_3)
Click to expand GraphQL query ```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} Use **`EVM(network: eth) { DEXTrades { … } }`** in a **subscription** to stream decoded swaps with **transaction**, **log**, and **buy/sell** legs for EVM DEX activity. [Run Query](https://ide.bitquery.io/Ethereum-dextrades)
Click to expand GraphQL query ```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} Subscribe to **`EVM(network: bsc).DEXTrades`** for **PancakeSwap** and other BSC DEX fills with **block**, **receipt**, and **trade** details. [Run Query](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades---Stream)
Click to expand GraphQL query ```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`** with **`ProtocolName` in `uniswap_v3`, `uniswap_v2`, `uniswap_v1`** to stream only **Uniswap** family pools on **mainnet**. [Run Query](https://ide.bitquery.io/uniswap-all-versions-trades-stream)
Click to expand GraphQL query ```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`** with **1s** **`Interval`** streams open/high/low/close, **volume**, and **market cap** fields for the selected **base/quote** currency ids. [Run Query](https://ide.bitquery.io/Token-OHLC-Stream-1-second-Multi-Chains)
Click to expand GraphQL query ```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} Compare **`Trading.Pairs`** rows for the same **currency** / **quote** across **markets** and **networks**; use **`limitBy`** on **market address** to sample best venues for **arbitrage** research. [Run Query](https://ide.bitquery.io/Find-arbitrage-opportunity-with-same-token-across-chains)
Click to expand GraphQL query ```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 } } } } ```
## How do I stream second-level Uniswap pair OHLC (K-line)? {#how-do-i-stream-uniswap-pairs-ohlc-seconds} Subscribe to **`Trading.Pairs`** filtered by **Uniswap protocols** and **1s** interval to power **sub-minute** charts and **HFT** analytics. [Run Query](https://ide.bitquery.io/Stream-all-Uniswap-Seconds-OHLC-Kline)
Click to expand GraphQL query ```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} Listen to **`Mint`** logs on the **PancakeSwap v3** pool manager contract to catch **new liquidity** added to pools on **BNB Chain**. [Run Query](https://ide.bitquery.io/Stream---Liqiidity-add-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: "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 } } } } } } ```
## How do I stream PancakeSwap v3 liquidity removals on BSC? {#how-do-i-stream-pancakeswap-v3-liquidity-removals-on-bsc} Filter **`Burn`** signatures on the same **PancakeSwap v3** manager to track **liquidity withdrawals** in real time. [Run Query](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 } } } } } } ```
## How do I stream Raydium liquidity adds on Solana? {#how-do-i-stream-raydium-liquidity-adds-on-solana} Subscribe to **`Solana.DEXPools`** with **Raydium’s program** and **positive base change** to detect **new liquidity** deposited into **Raydium** pools. [Run Query](https://ide.bitquery.io/liquidity-addition-for-radium_1)
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 PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
## How do I stream Raydium liquidity removals on Solana? {#how-do-i-stream-raydium-liquidity-removals-on-solana} Use the same **Raydium** program filter with **negative** **`ChangeAmount`** on the base side to stream **liquidity withdrawals**. [Run Query](https://ide.bitquery.io/liquidity-removal-for-radium_1)
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 PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
## How do I stream Orca Whirlpool liquidity adds on Solana? {#how-do-i-stream-orca-whirlpool-liquidity-adds} Filter **`DEXPools`** by **Orca Whirlpool program address** and **positive** base **change** to stream **liquidity deposits** into **Whirlpool** pools. [Run Query](https://ide.bitquery.io/liquidity-addition-for-orca-whirlpool_1)
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 PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
## How do I stream Orca Whirlpool liquidity removals on Solana? {#how-do-i-stream-orca-whirlpool-liquidity-removals} With **Orca’s program** and **negative** base **change**, stream **liquidity removals** from **Whirlpool** markets. [Run Query](https://ide.bitquery.io/liquidity-removal-for-orca-whirlpool_1)
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 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} Query **`EVM(network: eth, dataset: combined).Events`** for **`Burn`** logs on the **Uniswap V2 Router** to track **liquidity** pulled from **pairs**. [Run Query](https://ide.bitquery.io/uniswap-v2-liquidity-removed)
Click to expand GraphQL query ```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 } } } } ```
## How do I find addLiquidityETH calls for a token pair on Ethereum? {#how-do-i-find-addliquidityeth-calls-on-ethereum} Use **`EVM(dataset: archive).Calls`** with **`Call.Signature.Name`** **`addLiquidityETH`** and **argument** filters to audit **liquidity adds** routed through the **router** for a given **token** and **tx** pattern. [Run Query](https://ide.bitquery.io/addLiquidityETH_function)
Click to expand GraphQL query ```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 } } } } } ```
## Related DEX, launchpad & trading APIs {#related-dex-launchpad-trading-apis} Use these pages when you need **protocol-specific** filters, **bonding curves**, **pool** events, or **full DEX** examples that pair with **Crypto Price** / **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 + 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 (where documented) - [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 & 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 --- ## 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 nine 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 The Bitquery Crypto Price API returns the price of any token that trades on-chain, not only listed coins: real-time and the last 30 days for Solana, Ethereum, BNB Smart Chain, Base, Arbitrum, Optimism, Polygon, Tron and Robinhood Chain, in USD or against any quote token. Every row carries OHLC for intervals from one second up, mean and moving-average prices, volume, 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) on a free account; the trial includes complete history. For older candles, use [DEXTradeByTokens](/docs/cubes/dextradesbyTokens) or the [Solana historical page](/docs/blockchain/Solana/historical-aggregate-data/). :::tip Real-time + last ~30 days only The Crypto Price API cubes (`Trading.Tokens`, `Trading.Currencies`, `Trading.Pairs`) are part of the **Trading cube** family — built for **real-time and the last ~30 days**. For OHLC built from raw trades **older than ~30 days**, use chain-level [`DEXTradeByTokens`](/docs/cubes/dextradesbyTokens) instead. See the [**Trading Data Overview**](/docs/trading/trading-data-overview) for the side-by-side comparison. For a product-level overview — supported chains, OHLCV, USD pricing and plans — see the [Crypto Price API](https://bitquery.io/products/crypto-price-api) page. ::: Bitquery provides **Crypto Price APIs and Streams** via GraphQL and [Kafka](https://github.com/bitquery/streaming_protobuf/blob/feature/trading/market/price_index.proto). This **cryptocurrency price API** delivers comprehensive pricing data across multiple blockchains. These tools let you stream and query aggregated price data in USD or other paired currencies based on time and volume for all tokens across EVM, Solana, Tron, and other supported chains. Our **crypto prices api** is the **main** source for **real-time** pricing and **OHLC**; for **historical** OHLC from DEX trades, use **`DEXTradeByTokens`** as described in the [OHLC documentation](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/). The Crypto Price API provides more than just pair prices, it also includes [OHLCV (K-Line)](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/), Simple Moving Averages (SMA), Weighted Moving Averages (WMA), mean prices, and other key price-related statistics. While you can access the aggregated price for a single trading pair, the Price Index also supports cross-chain and cross-DEX aggregation, giving you a unified view of token prices across multiple ecosystems. **OHLC & K-lines:** Use this **Crypto Price API** as the **primary** source. For **historical** OHLC (long backfills, archive data, or trade-built candles), use **`DEXTradeByTokens`** (see [OHLC guide — when to use DEX](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/#crypto-price-api-vs-dextradebytoken)). ## Key Features of These APIs - **Pre-aggregated data**: OHLC, SMA, WMA, EMA, and mean prices calculated automatically - **Real-time streaming**: 1-second granularity via GraphQL subscriptions and Kafka - **Multi-chain support**: Ethereum, Solana, BSC, Arbitrum, Base, Optimism, Polygon, Robinhood, and more - **Clean data**: Automatic filtering of low-quality trades and outliers - **Cross-chain aggregation**: Unified view of token prices across multiple ecosystems ## List of Supported Networks - Arbitrum - Base - Matic - Ethereum - Solana - Binance Smart Chain - Tron - Optimism - Robinhood :::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` | ::: ## Available Endpoints - **[Streaming Endpoint](https://ide.bitquery.io/?endpoint=https://streaming.bitquery.io/graphql)** - **[NPM SDKs](https://www.npmjs.com/package/bitquery-crypto-price)** ## 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. If instead you want 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 **top market** rather than a blend across all of its pools, which matters for tokens with fragmented liquidity. ::: [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 } } } } } ``` ## What is the Crypto Price API (Price Index) and Why Does It Matter? The Crypto price API/Stream (Price Index) provides real-time, aggregated price data with ultra-low latency across multiple trading pairs, tokens, decentralized exchanges (DEXs), and blockchains. It's the first product of its kind, designed to help developers access accurate, up-to-the-second prices for building financial applications. This real-time crypto price API delivers multi-chain cryptocurrency price data essential for trading bots, DeFi protocols, and blockchain price feed applications. Whether you're looking for a **free crypto price api** for development or production-grade pricing data, our platform offers flexible access to comprehensive market data. ### Data Processing Pipeline 1. **Data Ingestion**: Onchain data is collected and parsed from supported DEXs across all chains 2. **Quality Filtering**: Trades with zero amount or below decimal precision (e.g. < 10^decimals/10,000) are filtered out. See [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) for details. 3. **Aggregation**: Price data is aggregated by time intervals (1s, 3s, 5s, etc.) and volume thresholds 4. **Metric Calculation**: OHLC, moving averages, and other statistical measures are pre-calculated 5. **Distribution**: Data is made available via GraphQL subscriptions and Kafka streams This API serves as the foundational layer of our trading-focused data suite, designed to provide developers with accurate, up-to-the-second prices for building financial applications. ## Technical Specifications ### Data Format - **Response Format**: GraphQL JSON or Protobuf ( For Kafka) - **Streaming Protocol**: WebSocket (GraphQL subscriptions) or Kafka Stream in Protobuf - **Update Frequency**: Real-time with 1-second granularity - **Data Retention**: Rolling ~30 days of historical data available for querying; older history via chain-level [`DEXTradeByTokens`](/docs/trading/trading-data-overview/) ### Supported Price Metrics - **OHLC**: Open, High, Low, Close prices - **Moving Averages**: Simple (SMA), Weighted (WMA), Exponential (EMA) - **Volume**: Base token, Quote token, USD equivalent - **Price Statistics**: Mean, median, weighted average ### Supported Supply Metrics - Market Cap - Fully Diluted Valuation Usd - Circulating Supply - Total Supply - Max Supply ### Moving Average Calculation Window All moving averages (Simple Moving Average, Weighted Moving Average, and Exponential Moving Average) use a **window size of 5 entries** for calculation, regardless of the time interval: - **1-second interval**: 5 entries of 1 second each - **60-second interval**: 5 entries of 60 seconds each - **3600-second interval**: 5 entries of 3600 seconds (1 hour) each This consistent window size ensures comparable moving average calculations across all time intervals. ## Accessing the API Crypto Price API stream with pre-calculated OHLC in the response This stream has pre-calculated OHLC data in the response which you can feed directly to your charting solution without additional calculations. Our **cryptocurrency price api** is accessible through GraphQL queries and subscriptions, making it easy to integrate into your applications. The **crypto prices api** supports **real-time streaming** and **recent OHLC history** (**rolling 30 days**); for **older** OHLC, use **`DEXTradeByTokens`** as in the [OHLC guide](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/#crypto-price-api-vs-dextradebytoken). > **Note**: Most queries can be converted to a GraphQL stream (WebSocket) by changing the keyword `query` to `subscription`. > Trading cube queries are the exception — `selectWhere`, `if`, most statistical metrics and `interval:` do not > survive the conversion, and `calculate` behaves differently. See > [What does not survive streaming](/docs/subscriptions/what-does-not-survive-streaming/). ## Kafka Topic for Crypto Price Stream: `trading.prices` This Kafka topic delivers **real-time, pre-aggregated price data** for tokens, currencies, and trading pairs across all supported blockchains. The data structure is a combination of all 3 cubes described in next section. Schema for the proto topic is [here](https://github.com/bitquery/streaming_protobuf/tree/main/market). The [python package](https://pypi.org/project/bitquery-pb2-kafka-package/) and [npm package](https://www.npmjs.com/package/bitquery-protobuf-schema) already have all schema updated. Each message contains: - **Price metrics** – OHLC (Open, High, Low, Close), Mean Price, SMA, WMA, EMA in USD - **Volume data** – Base, Quote, and Base in USD - **Supply data** – currency-level MarketCap, FullyDilutedValuationUsd, CirculatingSupply, TotalSupply, and MaxSupply ([Supply fields reference](/docs/trading/crypto-price-api/supply-fields)) - **Interval-based aggregation** – fixed durations (1s, 3s, 5s, 10s, etc.) - **Clean feed** – low-quality and outlier trades are filtered automatically for accuracy as per the price algorithm discussed above. > **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. ## Cubes in the API The Price APIs have three core data cubes: - **Tokens**: One blended price per token per chain, aggregated across every pool the token trades in. Use it for chain-wide streams and per-chain aggregates. - **Currencies**: An aggregated view of tokens that represent the same underlying asset. For example, tokens like cbBTC, WBTC, and other Bitcoin-wrapped tokens are all grouped under the Bitcoin currency. - **Pairs**: Price and volume data for token pairs on specific markets/protocols. E.g., SOL/USDC on Raydium (Solana) or ETH/USDT on Uniswap (Ethereum). **This is also the recommended cube for a specific token's price** — filter to its top market with [`Ranking: { Position: { eq: 1 } }`](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). > Note: Expressions are supported in this API. ### Currencies Currencies are representation of all tokens on various chains supported in Crypto Price API(Price Index). For example, take the case of Bitcoin, while it is a native token on Bitcoin chain, it is also traded on EVM chains as WBTC ( wrapped BTC). Now all these representations of BTC are represented as a single currency. > Note: We include `Volume: {Usd: {gt: 5}}` to further remove extreme outliers; the stream already pre-filters outliers—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 } } } } } ``` #### How does the above query work? It takes amounts and prices from all chains that use BTC and wrapped versions (including bridged versions) and presents an aggregated view. The OHLC, mean and other values represent a stable BTC picture. ### Tokens Let's say you don't want a chain agnostic view, but want to focus on a particular chain. How to stream or query prices for it? This is where tokens come in. > **Note:** the price below 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 top market instead — recommended whenever you care about one specific token. > Note: We include `Volume: {Usd: {gt: 5}}` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } } ``` We filter for specific tokens using the token `Address` and `Network`. If you need to stream all token prices on say Solana, simply set `Network` to `solana`. > Note: We include `Volume: {Usd: {gt: 5}}` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } } ``` ### Pairs This is the 3rd cube in these set of APIs. The Pairs cube gives you price, volume, and market-level trading data between two tokens — a base token and a quote token. We will breakdown in detail how base token and Quote are chosen in the next section. > **Recommended for single-token prices:** add `Ranking: { Position: { eq: 1 } }` to a Pairs query to get a token's price from its **top market** — the pool carrying the most volume for it. 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. > Note: We include `Volume: {Usd: {gt: 5}}` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } } ``` ## Understanding Intervals Unlike DEXtrades APIs, the intervals here are fixed and cannot be arbitrary. ### Supported Time Intervals The following durations (in seconds) are supported for querying or streaming historical and real-time data, unlike DEX APIs, these intervals are fixed, other values are not supported. `1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600` ### Supported Volume Aggregation Levels Use `TargetVolume` to get price intervals aggregated over a volume threshold: `1000, 10000, 100000, 1000000 (USD)` ## When to Choose Which Cube (Token, Currency, Pair)? :::tip The short answer For the price of a **specific token**, use **`Pairs` with `Ranking: { Position: { eq: 1 } }`** — see [Getting the Most Accurate Token Price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). Use `Tokens` for chain-wide streams and per-chain aggregates, and `Currencies` for one cross-chain number per asset. ::: ### Use the **`Pairs`** cube when: - You want the **price of a specific token** — filter to its top market with `Ranking: { Position: { eq: 1 } }` so thin pools do not affect the number ([how and why](/docs/trading/crypto-price-api/pairs#most-accurate-token-price)). - You want **pair-level trading data** (e.g., SOL/USDC, ETH/DAI). - You’re analyzing trading activity **on a specific market or DEX** (e.g., Uniswap, PancakeSwap, Raydium). - You need **OHLC, volume, liquidity**, and market-specific pricing between two tokens. - You're exploring **price arbitrage** or spreads across chains or platforms. ### Use the **`Tokens`** cube when: - You want a **firehose** of price updates for every token on a chain. - You want **one chain-wide number per token**, blended across all of its pools, rather than the price on a single market. - You're interested in **aggregate volume across all of a token's pools**, or the currency-level `Supply` and `MarketCap` fields. > For a **single token's price**, prefer `Pairs` with rank 1: the `Tokens` price is a volume-weighted blend of every pool, so thin pools can pull it away from the primary market. See [Tokens cube](/docs/trading/crypto-price-api/tokens). ### Use the **`Currencies`** cube when: - You want a **chain-agnostic view** of a token (e.g., BTC across Bitcoin, Ethereum (WBTC), Solana, etc.). - You need a **global price** for a currency, combining its various representations. - You're looking for **aggregated OHLC and average prices** for a token across chains. ## Crypto Price API for TradingView With the new Price API, you can simply feed the stream to your custom datafeed object in the TradingView code and have it update charts in real-time. - A sample tutorial is available [here](/docs/usecases/tradingview-subscription-realtime/getting-started/) - The stream is available ready-to-chart SDK [here](https://www.npmjs.com/package/@bitquery/tradingview-sdk). Simply copy paste the advanced charting library into the correct folder, add Bitquery access token and it is ready. ## Video Tutorial | Introduction to Crypto Price APIs --- ## 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/ Fetch token USD prices, market stats, and history with Bitquery crypto price APIs using GraphQL queries and live subscriptions. # Tokens Cube :::tip Looking for one token's price? Use the Pairs cube with rank 1 The price on this cube is a **volume-weighted blend of every pool** where the token is the base asset. That is what you want for a chain-wide number or a firehose of all tokens on a chain. But for a **specific token** — especially one whose liquidity is spread across many pools — thin pools contribute to the blend and can pull the price away from where the token actually trades. For a single token's price, 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. ::: The **Tokens** cube provides chain-specific, aggregated price and volume data for individual tokens. For a **query** example that returns tokens with volume and average price over the last 24h (including conditional metrics for 1h, 4h, 24h), see [Aggregated Token Data](https://ide.bitquery.io/aggregated-data) or the [Crypto Price API examples](/docs/trading/crypto-price-api/examples#aggregated-token-data-volume--price-last-24h). ### Fields in the Schema ```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 } } } } ``` ### Key Points to Understand: - **What is the Tokens Cube?** The **Tokens** cube provides chain-specific, aggregated price and volume data for individual tokens. This includes OHLC values, moving averages, and volume across **all pairs** the token is traded with. - **Volume Section Explained:** - `Base`: Volume of the token itself (the token in question) for all pairs. - `Quote`: Sum of **quote token** amounts (the tokens it traded against). This is not USD—for USD amounts use `Usd`. (As of March 11 2026, see [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm).) - `Usd`: Total volume in USD. Use this when you need USD amounts. - **IsQuotedInUsd**: A boolean indicating whether the OHLC and average prices are expressed in USD (`true`) or in the quote token's value (`false`). - **Clarification on "Quote":** The **Tokens** cube **does not show the specific quote tokens** used in each trade. Instead, it aggregates across all pairs the token is involved in—regardless of which token acted as the quote in those trades. - If you need **pair-level granularity** (i.e., to know exactly which token was the quote in a specific pair), use the **Pairs Cube** instead. - **Where the blend can mislead:** because every pool contributes in proportion to its decay-weighted volume, tokens with **fragmented liquidity** (one primary pool plus a tail of thin ones) can report a price that drifts from the primary market. 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. - **`Supply`**: Currency-level metrics for the asset (aggregated across chains); price and volume on the row remain chain-specific. See [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) for each subfield (`CirculatingSupply`, `TotalSupply`, `MaxSupply`, `MarketCap`, `FullyDilutedValuationUsd`). ## Field notes ### `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. ### `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). ### 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 | `Price.IsQuotedInUsd` is a constant `true` here — filtering on `false` returns nothing. :::caution `(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 — which is a metadata-arrival split on freshly launched tokens. Aggregate by `Token.Id` rather than treating one row as one token. Do not build a natural key from metadata columns: `Symbol` can change. ::: --- ## Crypto Tokens OHLC Candle K-Line API URL: https://docs.bitquery.io/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/ Crypto Tokens OHLC Candle K-Line API via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. # Crypto Tokens OHLC Candle K-Line API - Real-Time & Historical Price Data Get real-time and historical OHLC (Open, High, Low, Close) candle data, K-line charts, and price analytics for crypto tokens across all supported blockchains including Ethereum, Solana, BSC, Polygon, Tron, and Robinhood. **Recommendation:** Use the **[Crypto Price API](/docs/trading/crypto-price-api/)** as your **main source** for OHLC and K-line data—**real-time streams** and **pre-aggregated** bars (low-latency, easy to use). When you need **full historical OHLC** (deep backfill, archive ranges, or candles built from raw DEX trades), use **`DEXTradeByTokens`** on **`EVM`** or **`Solana`** and aggregate trades into candles—see [comparison below](#crypto-price-api-vs-dextradebytoken). ## How do I get OHLCV data for a token using Bitquery? {#how-do-i-get-ohlcv-data-for-a-token-using-bitquery} **Use the [Crypto Price API](/docs/trading/crypto-price-api/) first** (`Trading` → `Tokens`, `Pairs`, or `Currencies`): **pre-aggregated OHLC**, streaming, and intervals such as **1-second** and **1-minute**, with a **clean, multi-DEX index** view. **For historical OHLC** beyond what the Price API covers, switch to **`DEXTradeByTokens`** (or chain-specific DEX docs): bucket with **`Block { Time(interval: { count, in: minutes | hours | days }) }`** and derive open/high/low/close from **`PriceInUSD`** / **`Trade_Price`**. See [Crypto Price API vs DEXTradeByTokens](#crypto-price-api-vs-dextradebytoken) and the quick table below. ## OHLCV & 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:** [Crypto Price API](/docs/trading/crypto-price-api/) ; **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) (for **historical** OHLC or DEX-level control) | | How do I get historical OHLCV for a Solana token? | **Main OHLC:** [Crypto Price API — Quick start](/docs/trading/crypto-price-api/#quick-start) · [Tokens cube](/docs/trading/crypto-price-api/tokens/) · **Historical / DEX:** [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 using Bitquery API? | **Recommended:** [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) — prices from the token's top market rather than a blend across all its pools | | How do I get price change percentage for a token? | [Price change](/docs/start/starter-queries/#volume-of-multiple-tokens-across-different-chains) | | How do I get 1-minute OHLC candles for a DEX pair? | **Main:** [Your first OHLC query](#your-first-ohlc-query) (`Duration: { eq: 60 }`) · [Pairs cube](/docs/trading/crypto-price-api/pairs/) · **Historical:** [DEX OHLC pattern](/docs/cubes/dextradesbyTokens/#how-do-i-get-ohlc-in-a-dextradebytokens-query) | | 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 (top market)](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) · [Crypto Price API — Quick start](/docs/trading/crypto-price-api/#quick-start) · [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/) | ## What is OHLC Data? OHLC (Open, High, Low, Close) data, also known as candlestick or K-line data, is the foundation of technical analysis in cryptocurrency trading. Each OHLC candle represents price movement over a specific time interval: - **Open**: The first price recorded in the interval - **High**: The highest price reached during the interval - **Low**: The lowest price reached during the interval - **Close**: The last price recorded in the interval Our [Crypto Price API](/docs/trading/crypto-price-api/) provides pre-aggregated OHLC data with ultra-low latency—**use it as the main source** for live charts and typical OHLC needs. **Historical OHLC:** For **deep history** or candles computed from **raw DEX trades**, use **[DEXTradeByTokens](/docs/cubes/dextradesbyTokens/)** on **EVM** or **Solana** (with `dataset: combined` or `archive` as needed). ## Getting Started ### **Quick Start Steps** 1. **Get API Key**: Sign up at [Bitquery IDE](https://ide.bitquery.io) to get your API key 2. **Choose your method** - **GraphQL queries**: For one-off APIs - **WebSocket Streams**: For real-time data feeds - **Kafka**: For high-throughput applications with high degree of relibility 3. **Select the Right Cube**: Choose between Currency, Tokens, or Pairs based on your needs 4. **Start with Examples**: Use our ready-to-run examples below ### **Your First OHLC Query** {#your-first-ohlc-query} Get real-time Bitcoin OHLC data across all chains: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ## Why Use Our OHLC API? ### **Pre-Aggregated Data** - No need to calculate OHLC from raw trade data - Ready-to-use candlestick data for any time interval - Optimized for performance and accuracy - Uses pre-aggregated price data updated in real-time ### **Multi-Chain Support** - Get OHLC data across all major blockchains - Chain-agnostic currency views (e.g., Bitcoin across all chains) - Cross-chain price aggregation ### **Real-Time Streaming** - WebSocket subscriptions for live OHLC updates - Kafka streams for high-throughput applications - Sub-second latency for trading applications ### **Advanced Analytics** - Moving averages (SMA, WMA, EMA) - Volume-weighted prices - Price change calculations - Technical indicators ## Crypto Price API vs DEXTradeByToken {#crypto-price-api-vs-dextradebytoken} **Default for OHLC:** Use the **Crypto Price API** as the **primary** source for real-time and standard OHLC. Use **`DEXTradeByTokens`** when you need **full historical** OHLC or trade-based aggregation over long ranges. | Feature | Crypto Price API | DEXTradeByTokens | |---------|------------------|-----------------| | **Data Availability** | Real-time + **recent** OHLC (Price Index) | Real-time + **full** historical (with `dataset: combined` / `archive` as supported) | | **Data Processing** | Pre-aggregated and real time aggregation of price data | Raw trades aggregated on-the-fly in your query | | **Data Quality** | Filtered, clean price feed, second level | Trade Level Price | ### **When to Use Crypto Price API:** - **Default for OHLC and K-lines**—live streaming and pre-aggregated bars - Real-time trading applications requiring normalized pricing - Live charting and dashboards with aggregated price feeds - High-frequency trading strategies with sub-second updates - Limit order execution with reliable mark prices - Futures trading and derivatives pricing - Lending and borrowing protocols requiring accurate rates - DeFi applications needing real-time price oracles - Any application requiring reliable real-time price streams - Fixed time intervals available due to pre-aggregated data ### **When to Use DEXTradeByTokens API:** - **Historical OHLC** and long-range backfills - When you need **actual per-trade** detail not only index OHLC - **Full** price history, custom intervals, or archive-backed ranges - Any time interval can be used because aggregation is defined in the query over trades ## Supported Time Intervals Our [Crypto Price API](/docs/trading/crypto-price-api/) OHLC API supports fixed time intervals optimized for different trading strategies: | 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**, so a typo reads as "this token has no data" rather than "unsupported interval". :::danger The Duration filter is effectively mandatory The cube stores **all ten durations simultaneously**. A query without `Interval: { Time: { Duration: { eq: ... } } }` returns one row per duration for the same timestamp, so any aggregate over it is inflated roughly **ten-fold**: ```graphql where: { Interval: { Time: { Duration: { eq: 3600 } } } # never omit this ... } ``` Without it, a `sum(of: Volume_Usd)` over a window returns close to ten times the real figure. Row counts behave the same way — the unfiltered count equals the sum of the ten per-duration counts exactly. ::: ### 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 simply absent — there is no gap filling and no zero-volume filler. Do not assume a contiguous series; reindex client-side if you need one. ### Multiple timeframes in one request `Duration` accepts the full `OLAP_Integer` comparator set — `eq`, `ne`, `in`, `notIn`, `gt`, `ge`, `lt`, `le` — so you can pull several timeframes at once and split them client-side on `Interval.Time.Duration`: ```graphql Interval: { Time: { Duration: { in: [60, 300, 3600] } } } ``` Combining two comparators applies 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, varying by 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 Durations above 3600s do not exist natively, but you can **roll native candles up to any multiple** with the `interval:` argument 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: "...", till: "..." } } } 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`, so 4-hour, 12-hour, daily and weekly candles all come from the same pattern. :::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 :::caution Not currently available Volume-based intervals are **not currently available**. `Interval.VolumeBased` is `false` and `Interval.TargetVolume` is `0` on every row, and filtering on either (`Interval: { VolumeBased: true }` or any `Interval: { TargetVolume: ... }` value) returns **zero rows** with HTTP 200 and no error — so a query written against them looks like a token with no data rather than an unsupported feature. Use time-based intervals via `Interval: { Time: { Duration: { eq: } }}` instead, and apply a volume threshold in the `where` clause with `Volume: { Usd: { gt: ... } }`. ::: ## Choosing the Right Cube for OHLC Data The [Crypto Price API](/docs/trading/crypto-price-api/) offers three different cubes for accessing OHLC data. Understanding which cube to use is crucial for getting the right data for your specific use case: Before we dive into the cubes, let's clarify the key terminology: **Currency** - The underlying asset (e.g., BTC, ETH, SOL) **Token** - Specific implementations of a currency on blockchains (e.g., cbBTC, WBTC are Bitcoin tokens) **Pair** - Trading pairs between two assets (e.g., cbBTC/ETH, WBTC/ETH, WBTC/SOL) ### **Currency Cube** - Chain-Agnostic Aggregated View Use the **Currency** cube when you want a unified price view of an asset across all blockchains. **Key Features:** - Aggregates all token representations of the same underlying asset for example for BTC it will combine multiple tokens like WBTC, cbBTC, LBTC etc. - Can provide both chain specific and chain agnostic prices - Can provide only USD-quoted prices - Can combine volume and price data from all chains [Learn more about Currency Cube ➤](/docs/trading/crypto-price-api/currency/) ### **Tokens Cube** - Chain-Wide Blended Candles Use the **Tokens** cube when you want one candle per token per chain, or a stream of candles for every token on a chain. **Key Features:** - Aggregates across all pairs for that token - Can provide both chain specific and chain agnostic prices - Can provide only USD-quoted prices - Can combine volume and price data from all chains > Because the candle blends every pool where the token is base, thin pools contribute to it as well. For candles on **one specific token**, prefer the Pairs cube with rank 1 (below). [Learn more about Tokens Cube ➤](/docs/trading/crypto-price-api/tokens/) ### **Pairs Cube** - Top Market and Pair-Specific Candles Use the **Pairs** cube for OHLC on a specific market — and, with the rank filter, for the most accurate candles on a specific **token**. **Key Features:** - **Recommended for a single token:** add `Ranking: { Position: { eq: 1 } }` to get candles from the token's top market instead of a blend across all pools ([how and why](/docs/trading/crypto-price-api/pairs#most-accurate-token-price)) - Pair-specific OHLC data (e.g., ETH/USDC on Uniswap) - Can be quoted in USD or quote token - Market/DEX-specific data - Most granular level of price data [Learn more about Pairs Cube ➤](/docs/trading/crypto-price-api/pairs/) ## Real-Time OHLC Stream Examples ### 1. Live Bitcoin OHLC Across All Chains Stream real-time Bitcoin OHLC data aggregated from all supported blockchains (Bitcoin, Ethereum WBTC, Solana, etc.) with 60-second intervals: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ### 2. Ethereum OHLC on All DEXs Get real-time Ethereum OHLC data from all decentralized exchanges: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ### 3. Solana Token OHLC Stream Monitor all Solana tokens with real-time OHLC data: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ## Historical OHLC Queries **Note:** These examples use the **Crypto Price API** for **recent** OHLC. For **full historical** OHLC, use **[DEXTradeByTokens](/docs/cubes/dextradesbyTokens/)**. ### 1. Bitcoin OHLC (Crypto Price API) Recent Bitcoin OHLC using the Crypto Price API (time range in the query matches what the Price Index supports). [Run Query](https://ide.bitquery.io/historical-Bitcoin-OHLC-data-for-the-last-7-days) > Note: We include `Volume: { Usd: { gt: 5 } }` in most examples to remove extreme outliers. The example uses a relative time window in `Block.Time`. ```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 } } } } } ``` ### 2. Top 10 Tokens by 5-Minute Price Change Find the biggest movers with OHLC data and price change calculations: > Note: We include `Volume: { Usd: { gt: 5 } }` in most examples to remove extreme outliers; this example already filters by `Volume: { Usd: { gt: 100000 } }`. ```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) ## DEX-Specific OHLC Streams ### 1. Uniswap v3 OHLC Stream Monitor all tokens on Uniswap v3 with 1-second OHLC data: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ### 2. Raydium OHLC Stream (Solana) Track all tokens on Raydium with real-time OHLC data: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ### 3. PancakeSwap v3 OHLC Stream (BSC) Monitor BSC tokens on PancakeSwap v3: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ## Kafka Streaming for OHLC Data For high-throughput applications, use our Kafka streams to get real-time OHLC data: ### Kafka Topic: `trading.prices` The Kafka topic delivers real-time, pre-aggregated OHLC data for all supported tokens and currencies. **Schema**: [Protobuf Schema](https://github.com/bitquery/streaming_protobuf/tree/main/market) **Packages**: - [Python Package](https://pypi.org/project/bitquery-pb2-kafka-package/) - [NPM Package](https://www.npmjs.com/package/bitquery-protobuf-schema) ### Kafka Consumer Example (Python) ```python from kafka import KafkaConsumer # Configure Kafka consumer consumer = KafkaConsumer( 'trading.prices', bootstrap_servers=['your-kafka-broker:9092'], value_deserializer=lambda m: bitquery_pb2.PriceIndexMessage().ParseFromString(m) ) # Consume OHLC data for message in consumer: price_data = message.value # Extract OHLC data ohlc = price_data.price.ohlc print(f"Token: {price_data.token.symbol}") print(f"Open: {ohlc.open}") print(f"High: {ohlc.high}") print(f"Low: {ohlc.low}") print(f"Close: {ohlc.close}") print(f"Volume: {price_data.volume.usd}") print("---") ``` ### Kafka Consumer Example (Node.js) ```javascript const kafka = require('kafkajs'); const { PriceIndexMessage } = require('bitquery-protobuf-schema'); const client = kafka({ clientId: 'ohlc-consumer', brokers: ['your-kafka-broker:9092'] }); const consumer = client.consumer({ groupId: 'ohlc-group' }); async function run() { await consumer.connect(); await consumer.subscribe({ topic: 'trading.prices' }); await consumer.run({ eachMessage: async ({ topic, partition, message }) => { const priceData = PriceIndexMessage.decode(message.value); // Extract OHLC data const ohlc = priceData.price.ohlc; console.log(`Token: ${priceData.token.symbol}`); console.log(`Open: ${ohlc.open}`); console.log(`High: ${ohlc.high}`); console.log(`Low: ${ohlc.low}`); console.log(`Close: ${ohlc.close}`); console.log(`Volume: ${priceData.volume.usd}`); console.log('---'); }, }); } run().catch(console.error); ``` ## TradingView Integration Our OHLC API is perfect for TradingView charting. Use our ready-to-use SDK: ### TradingView SDK ```javascript const datafeed = new BitqueryTradingViewDatafeed({ apiKey: 'your-bitquery-api-key', token: 'BTC', // or any supported token interval: '1m', // 1m, 5m, 15m, 1h, etc. }); // Initialize TradingView widget const widget = new TradingView.widget({ symbol: 'BTC/USD', interval: '1m', container: 'tradingview_chart', datafeed: datafeed, library_path: '/tradingview/', locale: 'en', disabled_features: ['use_localstorage_for_settings'], enabled_features: ['study_templates'], charts_storage_url: 'https://saveload.tradingview.com', charts_storage_api_version: '1.1', client_id: 'tradingview.com', user_id: 'public_user_id', fullscreen: false, autosize: true, }); ``` [Get TradingView SDK ➤](https://www.npmjs.com/package/@bitquery/tradingview-sdk) ## Advanced OHLC Analytics ### 1. Price Change Analysis Calculate percentage price changes using expressions: ```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") } } } ``` ### 2. Volume-Weighted OHLC Get volume-weighted OHLC data for more accurate price representation: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } } ``` ### 3. Cross-Chain Arbitrage Detection Find arbitrage opportunities using OHLC data across chains: > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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) ## Can I get 1-minute historical OHLC data for a full year? {#can-i-get-1-minute-historical-ohlc-data-for-a-full-year} **Crypto Price API:** best for **live and recent** OHLC; an unbroken **one-year 1-minute** series may exceed what the Price Index is designed to serve—check your **plan** and try coarser intervals or **DEX-derived** data for deep history. **DEXTradeByTokens:** bucket with **`Time(interval: { count: 1, in: minutes })`** and a **365-day** **`Block.Time`** range; **minutes with no trades** will be **empty** or **sparse**, and the query can be **heavy**. Prefer **hourly/daily** bars or export **raw trades** for backfill. See [Historical Solana aggregate data](/docs/blockchain/Solana/historical-aggregate-data/) and [DEXTradesByTokens OHLC](/docs/cubes/dextradesbyTokens/#how-do-i-get-ohlc-in-a-dextradebytokens-query). ## Supported Blockchains Our OHLC API supports all major blockchains: - **Ethereum** - ETH, ERC-20 tokens - **Solana** - SOL, SPL tokens - **Binance Smart Chain (BSC)** - BNB, BEP-20 tokens - **Polygon** - MATIC, ERC-20 tokens - **Arbitrum** - ETH, ERC-20 tokens - **Optimism** - ETH, ERC-20 tokens - **Base** - ETH, ERC-20 tokens - **Tron** - TRX, TRC-20 tokens ## API Endpoints - **GraphQL Endpoint**: `https://streaming.bitquery.io/graphql` - **Kafka Broker**: `streaming.bitquery.io:9092` - **Topic**: `trading.prices` ## Best Practices 1. **Choose the right API**: Use [Crypto Price API](/docs/trading/crypto-price-api/) as the **main** source for OHLC; use [DEXTradeByTokens](/docs/cubes/dextradesbyTokens/) for **historical** OHLC from DEX trades 2. **Choose the Right Interval**: Use 1s for high-frequency trading, 1m for standard charting 3. **Use USD Quoting**: Set `IsQuotedInUsd: true` for consistent price comparison ## Support - **Documentation**: [Crypto Price API Docs](/docs/trading/crypto-price-api/) - **IDE**: [Bitquery IDE](https://ide.bitquery.io) - **Community**: [Discord](https://discord.gg/bitquery) - **Support**: [Contact Support](https://support.bitquery.io) --- *Get started with real-time OHLC data today and build the next generation of crypto trading applications.* --- ## 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` | 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`. ### 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/ Get crypto trading pair prices, volume, and OHLC with Bitquery Trading APIs using GraphQL queries and real-time stream options. # Pairs Cube The Pairs cube provides trading data for a base token traded against a quote token on a particular DEX or protocol. ## Getting 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 currently contributing the most volume to that token's price — rather than a value blended across every pool the token trades in. ::: ### 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, computed as a **volume-weighted blend of every pool** where the token is the base asset (see [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm)). That blend is the right answer when you want a single chain-wide number, and for a token whose liquidity sits in one deep pool the blended price and the top-market price agree closely. Fragmented tokens behave differently. When the same token trades across many pools — one primary pool plus a long tail of thin ones — every pool contributes to the blend in proportion to its decay-weighted volume. Thin pools quote wider, move on small trades, and can sit at prices the primary market has already left. Their share of the blend pulls the reported number away from the price you could actually trade at. Filtering `Pairs` to `Ranking.Position = 1` avoids that: you get the quote from the single market carrying the most volume for that token, which is the closest thing to an executable price. | 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: ... }` — see the note below | :::caution `Market.Address` is not the pool on EVM `Pool.Address` is the portable pool key and is the right filter on every chain. `Market.Address` means different things per chain: | Chain family | `Market.Address` | `Market.Program` | `Pool.Address` | | --- | --- | --- | --- | | EVM and Tron | the protocol **factory**, and an empty string for singleton protocols (uniswap_v4, balancer_v2, curve, fluid_dex) | the pool contract | the pool | | Solana | the pool | the DEX program | the pool | Filtering an EVM pool by `Market: { Address: ... }` therefore matches the factory and silently returns a **different pool's** data. ::: ## What Pairs adds over Tokens `Pairs` is `Tokens` **plus venue and quote identity** — there are no Tokens-only field paths. If you do not need `Market`, `Pool` or `QuoteToken`, query `Tokens`: it is the cheaper shape for the same price and volume data. `Pairs` carries **no liquidity, reserve or TVL data** — there is no such field and nothing in its filter surface. For pool depth, use the chain-level `DEXPools` cube, or a [cloud export](/docs/cloud/) for historical depth. ### 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. `Pool.Id` is empty on Solana, Tron and classic factory-per-pool AMMs. It is **populated on singleton-contract protocols** — Uniswap v4 and PancakeSwap Infinity — where it carries the pool identity that `Market.Address` cannot, because there `Market.Address` is empty and `Pool.Address` is the shared PoolManager. ## Ranking: how `Position` and `Weight` behave `Ranking.Position` is a **competition rank** by `Ranking.Weight` descending — 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`. `Ranking.Weight` is in `[0, 1]` per row, and the per-token sum is centred on 1.0 but is **not guaranteed to equal it** — sums well above and below 1 both occur. **Normalise before treating weights as shares**; do not assume the blend is an identity. :::caution `Position: { eq: 1 }` silently drops tokens Filtering to rank 1 returns only tokens whose top market **traded in that interval**. A token whose rank-1 market was quiet is omitted entirely — a few percent of tokens per interval, varying by chain. For coverage, widen the interval or fall back to `Tokens`. ::: Chain-wide rank-1 sweeps are fast — a few seconds for a short interval, longer for hour-to-day windows returning tens of thousands of tokens. ### Latest price of a token from 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. :::note `Price.IsQuotedInUsd` selects a denomination — it does not de-duplicate `IsQuotedInUsd` is a **denomination mode**, not a row multiplier. Markets are **not** published twice: an unfiltered query returns the USD rendering only, byte-identical to `IsQuotedInUsd: true`. You cannot retrieve both renderings in one result set, even by asking for both explicitly with `any:`. Setting it to `false` re-renders the same markets and intervals in quote-token units: only the `Price.*` fields change, while `Volume`, `Ranking` and `Supply` are identical between modes. You therefore do not need this filter to avoid duplicates — there are none. Set it to `false` only when you deliberately want the price in quote-token terms. Prices are in USD even when the quote token is WSOL or another non-stable asset, because the index normalizes the quote side — see [How Pool Prices Are Normalized](/docs/trading/crypto-price-api/price-index-algorithm#how-pool-prices-are-normalized-to-the-current-quote-token). ::: ### Stream the same 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. ### Watchlist: top-market price for several tokens Add `limitBy` to collapse the result to one current row per token: :::caution Group by `Token_Id`, not `Token_Address` Native assets carry an **empty** `Token.Address` — ETH on Ethereum, Arbitrum, Base and Optimism, BNB on BSC and MATIC on Matic all share `""`. Grouping by `Token_Address` silently collapses every one of them into a single row. `Token_Id` is unique per token per network. ::: [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 } } } } ``` ### Reading `Ranking.Weight` `Weight` is that market's share of the token's total decay-weighted volume, a float in `[0, 1]`; weights across all contributing pools sum to 1. Treat it as a confidence signal on the blended price: - **Weight close to 1** — a single pool drives essentially the whole token price. The blended `Tokens` price and the rank-1 price will be nearly identical, so either works. - **Low weight** — liquidity is fragmented across many pools and the blended price mixes all of them. This is exactly the case where the rank-1 price and the blended price diverge, and where the rank-1 price is the one you want. `Position` and `Weight` are computed over the rolling **1-hour, decay-weighted** window described in the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm#ranking-on-trades-pairs-and-tokens) — not over the interval of the row you are reading. A rank-1 row can therefore report less `Volume.Usd` for its own interval than a lower-ranked row does for another. ### Things to know - **Rank 1 does not imply USD.** The rank filter selects the market, not the price denomination — always pair it with `Price: { IsQuotedInUsd: true }` (or read the `IsQuotedInUsd` field on each row) so you are not mixing USD and quote-token prices. - **The top market can change.** Ranking is recomputed as volume moves, 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 instead of assuming a fixed pool. - **Always scope the query.** A rank filter is not a substitute for a token filter: 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. - **Want the runner-up markets too?** Use `Ranking: { Position: { in: [1, 2, 3] } }` to compare a token's main venues — useful for spread and arbitrage checks. You can also sort by `orderBy: { descending: Ranking_Weight }`. - **`Ranking` does not exist on `Currencies`.** It is available on `Trades`, `Pairs`, and `Tokens` only. ## Schema and Fields ```graphql { Trading { Pairs( where: {Market: {Network: {is: "Solana"}, Address: {in: ["PAIR ADDRESS HERE"]}}, Interval: {Time: {Duration: {eq: 300}}}, Price: {IsQuotedInUsd: true}} 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 } } } } ``` - `Volume.Base`: Total amount of base token traded during the interval. - `Volume.Quote`: Sum of **quote token** amounts traded (e.g. USDT, USDC). For USD-base pairs this is not USD—it is the total in quote token units. For USD amounts use `Volume.Usd`. (As of March 11 2026, see [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm) for details.) - `Volume.Usd`: Total trade volume in USD. Use this when you need USD amounts. - `Volume.BaseAttributedToUsd`: Portion of the `Volume.Base` that was traded against quote tokens with known USD prices. Used to accurately calculate average USD price. - `Price.Ohlc.*`: OHLC candles (Open, High, Low, Close) for the interval, computed using only trades with known USD values. - `Price.IsQuotedInUsd`: Boolean flag indicating if the price values are quoted in USD. If `false`, the price is in quote token terms. - **`Supply`**: Currency-level metrics for the asset (not pair- or pool-specific). See [Supply fields reference](/docs/trading/crypto-price-api/supply-fields) for definitions of each subfield. A rough pseudo-code of how price is calculated: ``` if quoteInUsd { vol.AveragePrice.Price = vol.AveragePrice.Usd / vol.AveragePrice.BaseAttributedToUsd } else { vol.AveragePrice.Price = vol.AveragePrice.Quote / vol.AveragePrice.Base } ``` For an in-depth breakdown of how quote and base are assigned, see [Breaking Down Price Streams in Detail](/docs/trading/crypto-price-api/in-depth). It is not necessary for basic use. --- ## 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 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 **9 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? --- ## DEXPools Cube on EVM Chains URL: https://docs.bitquery.io/docs/cubes/evm-dexpool/ DEXPools Cube on EVM Chains: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. See examples in the Bitquery IDE. # 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 for Solana: Pairs, Trades, OHLC and Live Streams URL: https://docs.bitquery.io/docs/blockchain/Solana/DEXScreener/solana_dexscreener/ What the public DEX Screener API covers and lacks, and how to get the same Solana pair data with history, OHLC 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/). - **Cloud datasets** as Parquet exports to S3, GCS, Snowflake or BigQuery for bulk history. See [cloud datasets](/docs/cloud/). ## 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/) - [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 vs DEXTradeByTokens vs Trades cube: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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; 9 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**, and **Robinhood** 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/ DEXTradesByTokens Cube: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Keep queries fast with indexed filters. # 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 **9 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). --- ## 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", "X-API-KEY": "BQY7em4KPZ9CMvjl4aUUOPf2hqEBIHF1", Authorization: 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. You can test the saved query on ide [here](https://ide.bitquery.io/Current-liquidity-and-initial-liquidity-of-pools-on-etherum). ```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: BalanceUpdates( where: {BalanceUpdate: {Address: {in: $poolAddresses}}} orderBy: {descendingByField: "balance"} ) { Currency { Name SmartContract Symbol } balance: sum(of: BalanceUpdate_Amount, selectWhere: {gt: "0"}) BalanceUpdate { Address } } } } `, variables: { poolAddresses }, }); let config = { method: "post", maxBodyLength: Infinity, url: "https://streaming.bitquery.io/graphql", headers: { "Content-Type": "application/json", "X-API-KEY": "BQYD4KszrYRIhb3cjIylKVLILgZfV0Ai", Authorization: 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", "X-API-KEY": "BQYD4KszrYRIhb3cjIylKVLILgZfV0Ai", Authorization: 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 Does Data Go? 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 S3 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 cloud/S3 export). 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 API keeps, use a cloud/S3 export or an Enterprise historical plan (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/) and the [Early Access Program datasets](/docs/graphql/dataset/EAP/) for details. :::caution `combined` is not available everywhere, and does not always fail cleanly Two cases to know about before you rely on `combined`: - **Solana** — every `Solana(dataset: combined)` cube tested returns a ClickHouse **500** on the `/graphql` endpoint. Use `realtime` for recent data and `archive` for history until this is resolved. - **EVM `Events` and `Calls`** — also return a 500 on `combined`, while `Transfers`, `Transactions`, `Blocks` and the DEX cubes work. 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** | ~3 months (Ethereum: full history) | ✅ | ~3 months on all EVM chains **except Ethereum**, which keeps full history. Older data on any chain (including Ethereum) via S3 export. `combined` currently 500s on these two cubes — use `archive`. | | Mempool | ✅ (stream) | — | — | Pending-tx data is realtime only. | ### 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** | — | ✅ | Same trades as above, far shorter window. See the note below. | | 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** | via S3 | ✅ | Deep history via S3 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 [cloud export](/docs/cloud/). | | `Transactions` / `Blocks` / `Rewards` / `DEXOrders` / `TokenSupplyUpdates` | ✅ **~12 hours** | — | ✅ | | :::warning Two Solana cubes carry the same trades with very different depth `DEXTrades` retains roughly **12 hours**; `DEXTradeByTokens` retains roughly **7 days** — about 15× longer, from the same underlying trades. 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. | ### 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 an S3 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. | ### Hyperliquid Hyperliquid core is an L1 order-book exchange, so its cubes carry exchange events rather than EVM blocks. All `Hyperliquid` cubes share one window. | Cube | realtime / API | Archive | Kafka | Notes | |---|---|---|---|---| | `Trades`, `Candles` | ✅ **~30 days** | Full history via [Data Lake](/docs/data-lake/) | ✅ | Fills and OHLCV candles per market/interval. | | `Orders`, `BookUpdates`, `Twaps` | ✅ **~30 days** | Full history via Data Lake | ✅ | Order lifecycle and book deltas. | | `PerpLiquidations`, `PerpFundings`, `CurrentPositions`, `TraderLeverageUpdates` | ✅ **~30 days** | Full history via Data Lake | ✅ | Per-trader funding, positions and leverage. | | `MarkPrices`, `PriceUpdates` | ✅ **~30 days** | Full history via Data Lake | ✅ | Mark price and oracle/reference updates. | | `SignedActions` | ✅ **~30 days** | Full history via Data Lake | ✅ | Raw signed L1 actions. | :::note Hyperliquid history lives in the Data Lake, not the API The API window is a rolling **~30 days** — enough for bots, dashboards and monitoring. Backtests and multi-year research are served by the [Blockchain Data Lake](/docs/data-lake/), which holds the complete Hyperliquid archive over S3 using the **same protobuf schema** as the Kafka streams. One decoder covers both, so replay code and production code are the same code. Note this is deeper than Hyperliquid's own public archive: `s3://hyperliquid-archive` holds L2 book snapshots and asset contexts only — no trades, candles or spot — refreshed roughly monthly with no completeness guarantee. Contact [sales@bitquery.io](mailto:sales@bitquery.io) for archive access. ::: ## Kafka is not a historical firehose Kafka (and Solana gRPC) deliver **realtime data plus a small backfill window (hours, not history)**. If you connect a fresh consumer, you get recent messages forward — not the chain from genesis. For anything older than the backfill window, use GraphQL (within the API's retention) or a cloud/S3 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: - **Blockchain Data Lake** — the complete archive from genesis to tip, streamed over S3 as Protobuf, using the same schema as the Kafka streams. This is the route for Hyperliquid history and for full-chain backfills. See [Data Lake](/docs/data-lake/). - **Cloud / S3 datasets** — Parquet exports of raw + decoded data into your own store. See [Cloud datasets](/docs/cloud/). - **Enterprise plans** — the self-serve plans (Personal/Pro/Scale) share a rolling window (about 30-day trades and 4–8h on-chain data); complete history requires an Enterprise plan or a historical export. 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/) - [Cloud datasets (Parquet / S3)](/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', 'X-API-KEY' => 'BQYVRzw02D5V2rWpWFii1pEbgLWCdx1y', 'Authorization' => 'Your Bitquery oAuth 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, trigger_on: head) { 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 (last 8 hours) - `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/) 4. **Check Examples**: See more examples in [Starter Queries](/docs/start/starter-queries) 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 Builder Terms Explaination: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 Builder Terms Explanation: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 dumps for EVM-base chains like Ethereum, BSC, Base, Polygon/Matic, Optimism, Robinhood, etc.** in parquet format 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://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/balance_updates.js) - **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. The complete list of Parquet files is stored 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 Beacon 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 a few scam tokens carry balances near `2^256`, which overflow even a `DECIMAL(38, 18)`; filter those out or cast to `DECIMAL(76, 18)` if your engine supports it. ### Row Grain and Deduplication The grain is `(Balance_Address, Currency_SmartContract, Currency_ProtocolName)`. Hybrid tokens such as ERC-404 emit under more than one standard, so the same address and contract can appear on multiple rows — about 4,600 such pairs in the sample. These rows often repeat the **same** balance under a different `Currency_ProtocolName`, 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"]]) ``` ## Other Ways to Access EVM Data Cloud data dumps 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 and Robinhood Chain: what each holds, how far back, 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`, `BalanceUpdates`, `Transactions`, `Calls`, `Events`, `Blocks` and `MinerRewards`. A query written for Ethereum runs on BNB Chain, Base, Arbitrum, Optimism, Polygon or Robinhood Chain 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. 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 | | `BalanceUpdates` | One balance change with its type | Balance history and reasons for a change | | `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` and `robinhood` work in `EVM(network: ...)`. The chain hubs under [Blockchain](/docs/blockchain/Ethereum/) carry worked examples per chain; the schema is the same. ## 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 | --- ## 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 Kafka or gRPC 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. --- ## Early Access Program URL: https://docs.bitquery.io/docs/graphql/dataset/EAP/ Early Access Program in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. See examples in the Bitquery IDE. # Early Access Program :::note Migration Notice Chains from the Early Access Program (EAP) have moved to v2. - **Existing customers**: You can continue using the EAP endpoint without making any changes. - **New users**: You must use the v2 endpoint for all blockchains. ::: ## Early Access Program (EAP) The Early Access Program (EAP) provided users with access to streaming data across various blockchain networks, including Solana, Matic, and more. These chains have now been migrated to the v2 endpoint. ## How to Access v2 APIs You can access v2 APIs through the Bitquery IDE interface. Navigate to [Bitquery IDE](https://ide.bitquery.io/) to get started. You can find examples on [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades/) and Matic in our examples section. ## How to Authorize Requests APIs use OAuth token mechanism for authentication. Read more on how to generate a token [here](/docs/authorization/how-to-generate/) --- ## 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 API - Best Blockchain Data API for Developers: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. # 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 **9 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**: 100,000 API points for 1 month. 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 :::caution Deprecated API `EVM.BalanceUpdates` was deprecated as of **20 May 2026** and removed on **15 June 2026**. Use **`EVM.Balances`** (this page) instead. ::: 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 API: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 nine 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 :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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 optional cloud connectors (AWS, GCP, Snowflake) 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 - **Cloud Solutions**: Access EVM data through AWS, GCP, and Snowflake integrations - **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. You can find the query [here](https://ide.bitquery.io/Get-liquidity-of-a-pair_1) **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```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 } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: archive, network: eth) { BalanceUpdates( where: {BalanceUpdate: {Address: {is: "0xc2eaB7d33d3cB97692eCB231A5D0e4A649Cb539d"}}, Currency: {SmartContract: {in: ["0xaaeE1A9723aaDB7afA2810263653A34bA2C21C7a","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"]}}} orderBy: {descendingByField: "balance"} ) { Currency { Name } balance: sum(of: BalanceUpdate_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 9 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. :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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. You can find the query [here](https://ide.bitquery.io/Get-liquidity-of-a-pair_1) **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```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 } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: archive, network: eth) { BalanceUpdates( where: {BalanceUpdate: {Address: {is: "0xc2eaB7d33d3cB97692eCB231A5D0e4A649Cb539d"}}, Currency: {SmartContract: {in: ["0xaaeE1A9723aaDB7afA2810263653A34bA2C21C7a","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"]}}} orderBy: {descendingByField: "balance"} ) { Currency { Name } balance: sum(of: BalanceUpdate_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 Eth Gasprice URL: https://docs.bitquery.io/docs/blockchain/Ethereum/ethers-library/eth_gasPrice/ Ethereum Eth Gasprice: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # eth_gasPrice In this section, we will build a data stream that returns the gas fee of the latest transaction in WEI. Unlike any JSON RPC method like eht_gasPrice that returns the hexadecimal equivalent of an integer representing the current gas price in WEI, this returns the integer value itself. [This](https://ide.bitquery.io/eth_gasPrice_1) is the stream that returns the current gas price in `WEI`. ``` graphql subscription { EVM { Transactions { Transaction { Gas } ChainId } } } ``` The above stream returns the following response. ``` json { "EVM": { "Transactions": [ { "ChainId": "1", "Transaction": { "Gas": "100000" } }, ] } } ``` --- ## Ethereum Eth Getbalance API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/ethers-library/eth-getbalance/ Ethereum Eth Getbalance API: fetch current and historical Ethereum balances with Bitquery GraphQL balance queries. Works with WebSocket live subscriptions. # eth_getBalance Ethereum getBalance is an API endpoint that retrieves the balance for a particular address for any given currency on the Ethereum blockchain. In this section we will see how to create queries that serves as an alternative for the eth_getBalance JSON RPC method and how to customize it to get data we need. ## eth_getBalance for One Address ### Get balance for all currencies [Run in IDE](https://ide.bitquery.io/ethereum-balances-address) ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549" } } } ) { Currency { Name Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` ### Get balance for one currency [Run in IDE](https://ide.bitquery.io/ethereum-balances-native-eth) Returns the balance for native ETH (`SmartContract: "0x"`). ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549" } } Currency: { SmartContract: { is: "0x" } } } ) { Currency { Name Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` ## eth_getBalance for Multiple Addresses Query each address in the `in` list. [Run in IDE](https://ide.bitquery.io/ethereum-balances-multiple-addresses) ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { in: [ "0xD51a44d3FaE010294C616388b506AcdA1bfAAE46", "0x6d07d7bac25d9e836bbceb3ed5e2a910214de846", "0x354e9fa5c6ee7e6092158a8c1b203ccac932d66d" ] } } } ) { Currency { Name Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` --- ## Ethereum Eth Getcode URL: https://docs.bitquery.io/docs/blockchain/Ethereum/ethers-library/eth_getCode/ Ethereum Eth Getcode: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Covers archive history and realtime data. # eth_getCode In this section we will build a query that serves as an alternative to the eth_getCode JSON RPC method. However unlike the method that requires two arameters, namely `address` and `block number`, this API only needs an `address`. The [below](https://ide.bitquery.io/eth_getCode) query serves as the alternative API to the method, with address as `0xc923D39fA2d97fb4B660Fc66DAdB1421605975E0`. ``` graphql { EVM(dataset: archive, network: eth) { creates: Calls( where: { Call: { To: { is: "0xc923D39fA2d97fb4B660Fc66DAdB1421605975E0" }, Create: true } } ) { Call { Output } } } } ``` --- ## Ethereum Eth Getlogs URL: https://docs.bitquery.io/docs/blockchain/Ethereum/ethers-library/eth_getLogs/ Ethereum Eth Getlogs: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # eth_getLogs In this section, we will see how we can use Bitquery APIs as an alternative to the eth_getLogs JSON RPC method and return an array of `Logs` object matching the filter object(*optional). The Logs object consist of the following data. - `removed`: (boolean) true when the log was removed, due to a chain reorganization. false if it's a valid log. - `logIndex`: Log index position in the block. Null when it is a pending log. - `transactionIndex`: Hexadecimal of the transactions index position from which the log created. Null when it is a pending log. - `transactionHash`: 32 bytes. Hash of the transactions from which this log was created. Null when it is a pending log. - `blockHash`: 32 bytes. Hash of the block where this log was in. Null when it is a pending log. - `blockNumber`: Block number where this log was in. Null when it is a pending log. - `address`: 20 bytes. Address from which this log originated. - `data`: Contains one or more 32-bytes non-indexed arguments of the log. - `topics`: An array of 0 to 4 indexed log arguments, each 32 bytes. ## Get Latest Logs [This](https://ide.bitquery.io/eth_getLogs_1) subscription API returns the stream of thelatest logs for the `Ethereum Mainnet`. Now note that there is currently no filter in place. ``` graphql subscription { EVM { Events { Block { Hash Number } Transaction { Hash Index } LogHeader { Address Data Index Removed } Topics { Hash } } } } ``` ## Get Logs with Filteration Now, just like the orignal eth_getLogs method, Bitquery APIs provides the option to filter out the `Logs` based on the following parameeters. - `address`: (optional) Contract address (20 bytes) or a list of addresses from which logs should originate. - `topics`: (optional) Array of 32 bytes DATA topics. Topics are order-dependent. - `blockhash`: (optional) Restricts the logs returned to the single block referenced in the 32-byte hash blockHash. ### Get Logs Originated From an Address [This](https://ide.bitquery.io/eth_getLogs-with-filters) API returns the logs originated from a fixed address, which is `0x7d4a7be025652995364e0e232063abd9e8d65e6e` in this case. Also, unlike the JSON RPC method you can fiter out the `Logs` from multiple addresses using [this](https://ide.bitquery.io/eth_getLogs-with-filters_1) API. ``` graphql { EVM { Events( where: {LogHeader: {Address: {is: "0x7d4a7be025652995364e0e232063abd9e8d65e6e"}}} limit: {count: 10} ) { Block { Hash Number } Transaction { Hash Index } LogHeader { Address Data Index Removed } Topics { Hash } } } } ``` ### Filter Logs on Topics [This](https://ide.bitquery.io/eth_getLogs-with-filters_2) query filters outs the `Logs` based on the `topics`. Also, [this](https://ide.bitquery.io/eth_getLogs-with-filters_3) query filters out the Logs based on multiple `Topics`. ``` graphql { EVM { Events( where: { Topics: { includes: { Hash: { is:"e1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c" } } } } ) { Block { Hash Number } Transaction { Hash Index } LogHeader { Address Data Index Removed } Topics { Hash } } } } ``` ### Get Logs from a Block Using [this](https://ide.bitquery.io/eth_getLogs-with-filters_4) query, you can get the `logs` that belong to a particular `block` by using `blockHash` as a filter. Here `0xa0e1c15b905f4ed6f4e466b2693791ffc6be6ccd3a2a95d403585799ab5fecd9` is the parameter used for filteration. ``` graphql { EVM { Events( where: { Block: { Hash: { is: "0xa0e1c15b905f4ed6f4e466b2693791ffc6be6ccd3a2a95d403585799ab5fecd9" } } } ) { Block { Hash Number } Transaction { Hash Index } LogHeader { Address Data Index Removed } Topics { Hash } } } } ``` --- ## Ethereum Eth Subscribe URL: https://docs.bitquery.io/docs/blockchain/Ethereum/ethers-library/eth_subscribe/ Ethereum Eth Subscribe: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # eth_subscribe Ethereum Subscription API allows developers to build websockets that receive real-time notifications about the Ethereum blockchain. In this section we will see how to create subscription for each eth_subscribe JSON RPC method and how to customize it to get data we need. ## eth_subscribe(“pendingTransactions”) To subscribe to incoming pending transactions, use the below subscription. You can run it [here](https://ide.bitquery.io/eth_subscribependingTransactions) ```graphql subscription { EVM(mempool: true) { Transactions { Transaction { CostInUSD Cost Data From Hash To Type ValueInUSD Value Time Index Gas } TransactionStatus { FaultError EndError Success } } } } ``` ## eth_subscribe("logs") You can subscribe to all incoming logs filtered by any of the fields including method signature, tx value,sender , receiver and so on. In the below example we are tracking only logs where the method name is `transfer`. You can run it [here](https://ide.bitquery.io/eth_subscribelogs) ```graphql subscription { EVM(mempool: true) { Events(where: {Log: {Signature: {Name: {is: "Transfer"}}}}) { Log { SmartContract Signature { Name Signature } } Block { Number Hash Time } Transaction { Hash From ValueInUSD Value To Type } LogHeader { Data Address Index Removed } } } } ``` ## eth_subscribe("newBlockHeaders") You can subscribe to new blocks as they arrive in real-time. This includes information about the new block, such as its block number, hash,transaction count and timestamp. ```graphql subscription { EVM { Blocks { Block { Number ParentHash Hash TxCount Time } } } } ``` --- ## Ethereum Events API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/events/events-api/ Ethereum Events API: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 } } } } ``` --- ## 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 **9 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 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 :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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 changes in balance after each transaction in the mempool, even before it is confirmed. You can run it [here](https://ide.bitquery.io/Mempool-balance-updates-on-Ethereum-Arbitrum-BNB-subscription) ```graphql subscription { EVM(network: eth, mempool: true) { BalanceUpdates { Currency { Name } Block { Date } BalanceUpdate { Amount Type } 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 and the count below is zero in any window. 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 :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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, ordered by the sum of the token balances in descending order. **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```graphql { EVM(network: eth, dataset: combined) { Balances( limit: { count: 100 } orderBy: { descending: Balance_Amount } where: { Currency: { SmartContract: { is: "0xf5b0a3efb8e8e4c201e2a935f110eaaf3ffecb8d" } } } ) { Balance { Address } Balance { Amount } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql { EVM(network: eth, dataset: combined) { BalanceUpdates( limit: { count: 100 } orderBy: { descendingByField: "balance" } where: { Currency: { SmartContract: { is: "0xf5b0a3efb8e8e4c201e2a935f110eaaf3ffecb8d" } } } ) { BalanceUpdate { Address } balance: sum(of: BalanceUpdate_Amount) } } } ```
**Parameters** - `network`: This specifies the Ethereum network to use. In this case, the network is "eth". - `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 - `balance`: This field returns the sum of the token balances associated with the Ethereum address. ## All NFTs owned by an address ```graphql { EVM(network: eth, dataset: combined) { BalanceUpdates( limit: { count: 100 } orderBy: { descending: BalanceUpdate_Amount } where: { BalanceUpdate: { Address: { is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03" } } Currency: { Fungible: false } } ) { Currency { Fungible Symbol SmartContract Name HasURI Delegated Decimals } BalanceUpdate { Id Amount Address URI } } } } ``` **Parameters** - `EVM(network: eth, dataset: combined)`: specifies that we want to query the [combined](/docs/graphql/dataset/combined) dataset of the Ethereum blockchain. - `BalanceUpdates`: specifies that we want to retrieve balance updates for a specific smart contract. - `where: { Currency: { SmartContract: { is: "0xBE223020724CC3e2999f5dCeDA3120484FdBfef7" } }, BalanceUpdate: { Address: { is: "0xb92505a3364B7C7E333c05B44cE1E55377fC43cA" }, Amount: { gt: "0" } } }`: specifies the filter condition to retrieve balance updates for a specific smart contract with address "0xBE223020724CC3e2999f5dCeDA3120484FdBfef7" and a specific address "0xb92505a3364B7C7E333c05B44cE1E55377fC43cA" which has a balance greater than 0. **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. - `Delegated`: specifies if the currency is delegated. - `BalanceUpdate`: returns the balance update information for the specified address. - `Id`: returns the ID of the balance update. - `Amount`: returns the amount of the balance update. - `Address`: returns the address of the balance update. ## 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". - `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) on a free account. ## 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 } } } } ``` The older way, summing `BalanceUpdates` per address, is retired; the [Balances and Holders cubes](/docs/cubes/balances-cube) page maps each old query to its replacement. ## 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 :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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. The API leverages the BalanceUpdates method, which keeps track of all balance updates. Alternatively, you can achieve similar results by utilizing the Transfers API. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { BalanceUpdates( orderBy: { descending: Block_Time } limit: { count: 1 } where: { BalanceUpdate: { Id: { eq: "9996" } } Currency: { Fungible: false SmartContract: { is: "0x8a90cab2b38dba80c64b7734e58ee1db38b8992e" } } } ) { Currency { Name SmartContract } BalanceUpdate { Address Amount Id } 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** - `Currency` : Specifies the NFT currency. `Name` represents the currency name, and `SmartContract` contains its smart contract address. - `BalanceUpdate` : Contains the address of the NFT holder, along with the amount and ID of the token involved in the balance update. - `Block` : Includes the block number and date. You can find the graphql query [here](https://ide.bitquery.io/Who-owns-specific-NFT). ## 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. **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Balances( orderBy: { descending: Balance_Amount } limit: { count: 10 } where: { Currency: { SmartContract: { is: "0x7dD4F223D9155F412790D696Fa30923489d4Ad34" } } } ) { Balance { Address } Balance { Amount(selectWhere: { gt: "0" }) } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: combined, network: eth) { BalanceUpdates( orderBy: { descendingByField: "Balance" } limit: { count: 10 } where: { Currency: { SmartContract: { is: "0x7dD4F223D9155F412790D696Fa30923489d4Ad34" } } } ) { BalanceUpdate { Address } Balance: sum(of: BalanceUpdate_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` : Specifies the balance amount in the results. - `BalanceUpdate` : The `Address` field specifies the address who holds the NFT. You can find the graphql query [here](https://ide.bitquery.io/top-token-holders-of-Moonwalker-NFT). ## 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) token holders of a NFT token [using following query](https://ide.bitquery.io/past-token-holder-of-a-token_1). ```graphql { EVM(dataset: combined) { BalanceUpdates( limit: {count: 10} where: {Currency: {Fungible: false, SmartContract: {is: "0x364c828ee171616a39897688a831c2499ad972ec"}}} ) { BalanceUpdate { Address } Block { lastHoldingDate: Time( maximum: Block_Time if: {Currency: {SmartContract: {is: "0x364c828ee171616a39897688a831c2499ad972ec"}}} ) fistHoldingDate: Time( minimum: Block_Time if: {Currency: {SmartContract: {is: "0x364c828ee171616a39897688a831c2499ad972ec"}}} ) } sum(of: BalanceUpdate_Amount, selectWhere: {le: "0"}) } } } ``` --- ## 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, trigger_on: head) { 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/ Ethereum Pepe API: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # 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 Smartcontract Filterby URL: https://docs.bitquery.io/docs/blockchain/Ethereum/calls/smartcontract-filterby/ Ethereum Smartcontract Filterby: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 :::caution Deprecated API `EVM.TokenHolders` was deprecated as of **20 May 2026** and removed on **15 June 2026**. Use **`EVM.Holders`** (this page) instead. 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 **9 chains in one API**. Use this page when you need **historical token trade data older than ~30 days**, raw per-swap detail, or call / event context. ::: 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 The below query will get you the realtime DEX trades happening on Ethereum Mainnet. Open it in the GraphQL IDE using this [link](https://ide.bitquery.io/subscribe-to-dex-trades-on-ethereum-mainnet_2).
Click to expand GraphQL subscription ```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`). See a video explanation [here](https://www.youtube.com/watch?v=K_H3to_nIdY).
Click to expand GraphQL query and 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.
Click to expand GraphQL query and 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 Below API gets you the first 500 buyers of a specific ERC-20 token, here as example we have taken this token `0x3c3a81e81dc49A522A592e7622A7E711c06bf354`. Try the API [here](https://ide.bitquery.io/first-500-buyers-of-a-ERC20-token_1#).
Click to expand GraphQL query ```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.
Click to expand GraphQL query ```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 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_1#).
Click to expand GraphQL query and variables ```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 Use below query to get top 10 Eth Tokens by Price Change in last 1h. Test the query [here] (https://ide.bitquery.io/Top-10-eth-tokens-by-price-change-in-last-1-hr_2).
Click to expand GraphQL query and variables ```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:
Click to expand GraphQL query and variables ```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 } } } } } ```
![image](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)
{" "} Click to expand GraphQL query and variables ```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 Run this for analytics related to token trades:
Click to expand GraphQL query ```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_SmartContract) amount: sum(of: Trade_Amount) usd: sum(of: Trade_AmountInUSD) usd2: sum(of: Trade_Side_AmountInUSD) buyers: uniq(of: Trade_Buyer) sellers: uniq(of: Trade_Sender) 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)
Click to expand GraphQL query ```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 Fetch the top 100 traders by volume USD:
Click to expand GraphQL query and 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 } } } } ) { 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) } } } { "network": "eth", "token": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599" } ```
![image](https://github.com/user-attachments/assets/302c2be2-5ebe-4fa3-8fe4-c7e8f3bc6e23) 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
Click to expand GraphQL query and 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" } ```
![image](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
Click to expand GraphQL query and 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" } ```
![image](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
Click to expand GraphQL query and 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" } ```
![image](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
Click to expand GraphQL query ```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" } ```
![image](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
Click to expand GraphQL query and 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 } } } } } ) { 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) } } } { "network": "eth", "token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "base": "0x0ccae1bc46fb018dd396ed4c45565d4cb9d41098" } ```
![image](https://github.com/user-attachments/assets/baaf62ee-9cbe-4d3b-bf53-c29a196a46bb) 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
Click to expand GraphQL query and 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" } ```
![image](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
Click to expand GraphQL query and variables ```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": "eth" } ```
![image](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
Click to expand GraphQL query ```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": "eth" } ```
![image](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
Click to expand GraphQL query ```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": "eth" } ```
![image](https://github.com/user-attachments/assets/2940bea4-b27f-4e74-afc4-1d433a45a31b) You can check the data here on [DEXrabbit](https://dexrabbit.bitquery.io/eth). ## Latest Token Trades
Click to expand GraphQL query ```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: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } } } ) { /* fields */ } } } ```
Open it with this [link](https://ide.bitquery.io/latest-trades-for-a-token---both-buy-and-sell). ## Token trade from a specific DEX
Click to expand GraphQL query ```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 */ } } } ```
Open it with this [link](https://ide.bitquery.io/token-trades-for-a-specific-DEX_1). ## Subscribe to new token trades (WebSocket)
Click to expand GraphQL subscription ```graphql subscription { EVM(network: eth, trigger_on: head) { buyside: DEXTrades( orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } } ) { /* fields */ } sellside: DEXTrades( orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } } } ) { /* fields */ } } } ```
Open it with this [link](https://ide.bitquery.io/latest-token-trades-subscription). ## OHLC in USD of a Token
Click to expand GraphQL query ```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: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } count } } } ```
## Get Token Metadata
Click to expand GraphQL query ```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
Click to expand GraphQL query ```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
Click to expand GraphQL query ```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
Click to expand GraphQL query ```graphql query MyQuery { EVM { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xB8c77482e45F1F44dE1745F52C74426C631bDD52" } } } TransactionStatus: { Success: true } Block: { Time: { since: "2025-02-12T00:00:00Z" } } } ) { 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)
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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
Click to expand GraphQL query ```graphql { EVM(dataset: archive, network: bsc) { buyside: DEXTradeByTokens( limit: { count: 30 } orderBy: { descendingByField: "Block_time_field" } where: { Trade: { Side: { Currency: { SmartContract: { is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" } } Amount: { ge: "0" } Type: { is: buy } } 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) distinctBuyer: count(distinct: Trade_Buyer) distinctSeller: count(distinct: Trade_Seller) distinctSender: count(distinct: Trade_Sender) distinctTransactions: count(distinct: Transaction_Hash) total_sales: count( if: { Trade: { Side: { Currency: { SmartContract: { is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" } } } } } ) total_buys: count( if: { Trade: { Currency: { SmartContract: { is: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" } } } } ) 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
Click to expand GraphQL query ```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
Click to expand GraphQL query ```graphql { EVM(dataset: archive, network: eth) { buyside: DEXTrades( limit: { count: 10 } limitBy: { by: Transaction_From, count: 1 } orderBy: { ascending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } } } ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { 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)
Click to expand GraphQL query ```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).
Click to expand GraphQL query ```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.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-eth-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: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } } } } ) { 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) on a free account. 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 - **Historical Data**: Access complete historical balance change data since Ethereum genesis - **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 - Historical data with complete change history - 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. The same schema powers our multi-chain [DEX API](https://bitquery.io/products/dex), so every query below also works across PancakeSwap, Raydium and 300+ other venues. To get details on Uniswap v3 Positions, check the examples available in [this page](/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/) ## 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)
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 includes trading metrics like SMA, EMA, VWAP, and more. [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 on Uniswap v1–v4, [Run query](https://ide.bitquery.io/Latest-Trades-of-a-Pair-on-Uniswap):
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 on Uniswap v1–v4, [test the query here](https://ide.bitquery.io/Top-Traders-of-a-Token_8):
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"] } } } } ) { 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) } } } ```
## Uniswap v2 Pair Trade Stats Get CHEFDOG/WETH v2 pooled stats (volume, bought, sold):
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: buy } } } } ) sold: sum( of: Trade_Amount if: { Trade: { Side: { Type: { is: sell } } } } ) 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) [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 Identify the top 100 active Uniswap v3 traders since April 1, 2025:
Click to expand GraphQL query ```graphql query ActiveUniswapTraders { EVM(dataset: archive, network: eth) { DEXTradeByTokens( where: { Trade: { Dex: { OwnerAddress: { is: "0x1f98431c8ad98523631ae4a59f267346ea31f984" } } } Block: { Date: { after: "2025-04-01" } } } limit: { count: 100 } orderBy: { descendingByField: "tradeCount" } ) { Trader: Trade { Seller } 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. 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
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 more [here](/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 Block URL: https://docs.bitquery.io/docs/data-lake/extract-transfers/ Extract Transfers from a Block: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # Extract Transfers from a Block This page shows how to pull transfers out of a streamed block. It builds on the streaming and decoding steps from the [overview](./), 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 shape applies 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. 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. --- ## 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 `eap` 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/eap" 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 API - BSC Launchpad Token Analytics and Trading Data: query and stream BNB Chain on-chain data with Bitquery GraphQL examples for developers. # 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 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 **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. :::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 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 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 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 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/ BNB Chain Four Meme API: query and stream BNB Chain on-chain data with Bitquery GraphQL examples for developers. Keep queries fast with indexed filters. # Four Meme API :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. 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. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: :::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 **9 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/) - [PumpFun 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 **`BalanceUpdate.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 - **Cloud Solutions**: Access EVM data through AWS, GCP, and Snowflake integrations - **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: [Query Link](https://ide.bitquery.io/Get-balance-of-an-address-for-a-specified-currency_1).
Click to expand GraphQL query **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```graphql query MyQuery($token: String) { EVM(network: bsc) { Balances( where: { Balance: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } Currency: { SmartContract: { is: $token } } } ) { Currency { Name Symbol } Balance { Amount } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery($token: String) { EVM(dataset: combined, network: bsc) { BalanceUpdates( where: {BalanceUpdate: {Address: {is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b"}}, Currency: {SmartContract: {is: $token}}} orderBy: {descendingByField: "balance"} ) { Currency { Name } balance: sum(of: BalanceUpdate_Amount) BalanceUpdate { Address } } } } ```
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%. You can run and test the saved query [here](https://ide.bitquery.io/Get-Four-Meme-Tokens-which-are-above-95-Bonding-Curve-Progress).
Click to expand GraphQL query **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```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" }) } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { BalanceUpdates( limit: { count: 100 } where: { BalanceUpdate: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } } orderBy: { descendingByField: "Bonding_Curve_Progress_precentage" } ) { Currency { SmartContract Name } balance: sum( of: BalanceUpdate_Amount selectWhere: { ge: "200000000", le: "240000000" } ) BalanceUpdate { Address } Bonding_Curve_Progress_precentage: calculate( expression: "100 - ((($balance - 200000000) * 100) / 800000000)" ) } } } ```
## 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 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 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 $time_24hr_ago: DateTime $time_1hr_ago: DateTime $time_5min_ago: DateTime ) { EVM(network: bsc) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: $currency } } } 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": "0x9b48a54bcce09e59b0479060e9328ab7dbdb0d40", "time_24hr_ago": "2024-03-23T15:00:00Z", "time_1hr_ago": "2024-03-24T14:00:00Z", "time_5min_ago": "2024-03-24T15:55:00Z" } ```
## 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. Try the API [here](https://ide.bitquery.io/Top-tokens-in-800-M-and-900-M-liquidity-range).
Click to expand GraphQL query **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```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" }) } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { BalanceUpdates( where: { BalanceUpdate: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } } orderBy: { descendingByField: "balance" } ) { Currency { Name Symbol SmartContract } balance: sum( of: BalanceUpdate_Amount selectWhere: { gt: "800000000", le: "900000000" } ) BalanceUpdate { Address } } } } ```
## 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. You can test the query [here](https://ide.bitquery.io/zeyouBitquery-metrics-query).
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) } BalanceUpdates(where: { Currency: { SmartContract: { is: $token } } }) { holders: uniq(of: BalanceUpdate_Address, selectWhere: { gt: "0" }) } } 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. Test the API [here](https://ide.bitquery.io/Get-liquidity-of-a-fourmeme-token).
Click to expand GraphQL query **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```graphql query MyQuery { EVM(network: bsc) { Balances( where: { Balance: { Address: { is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b" } } Currency: { SmartContract: { is: "0x87c5b3da05b062480b55c2dbf374ccd084f74444" } } } ) { Currency { Name } Balance { Amount } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { EVM(dataset: combined, network: bsc) { BalanceUpdates( where: {BalanceUpdate: {Address: {is: "0x5c952063c7fc8610FFDB798152D69F0B9550762b"}}, Currency: {SmartContract: {is: "0x87c5b3da05b062480b55c2dbf374ccd084f74444"}}} orderBy: {descendingByField: "balance"} ) { Currency { Name } balance: sum(of: BalanceUpdate_Amount) BalanceUpdate { Address } } } } ```
--- ## 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? | **Not documented on this page yet** — add minimum interval, aggregation options, and any rate or streaming limits you want to communicate publicly. | ## 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 **9 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 Solana API | Trending Tokens URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-gmgn-api/ GMGN Solana API | Trending Tokens: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # GMGN Solana API :::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 **9 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 ::: ## 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—common source for **Solana** screener UIs. - **[Solana DEXScreener API](/docs/blockchain/Solana/DEXScreener/solana_dexscreener)** — **DEXScreener**-style Solana **pair** and **price** examples. - **[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 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#). ```graphql query MyQuery { Solana(dataset: combined) { DEXTradeByTokens( where: { Block: { Time: { since: "2025-02-10T07:00:00Z" } } Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "token mint address" } } 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 } } } } ) } } } ``` ## 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 pair legs**, 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 9 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 nine 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 `eap` 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 9 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 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 and Robinhood Chain. 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` and `robinhood` 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 from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Getting Ethereum Data from AWS Bucket We are now offering raw blockchain data on Amazon S3, taking a step towards providing a faster way to build dApps. 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-cloud-data-dump-sample.git 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. --- ## Getting Latest Pairs URL: https://docs.bitquery.io/docs/blockchain/Ethereum/dextrades/latest-trading-pairs-api/ Getting Latest Pairs: get Ethereum DEX swaps, prices, and OHLC with Bitquery GraphQL queries and live streams. Keep queries fast with indexed filters. # Getting Latest 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) --- ## 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`). --- ## 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 that are Enterprise only Cardano, Ripple, Stellar, Algorand, Filecoin, Avalanche, Celo, Cronos and Klaytn have **no self-serve historical add-on**. Historical access to those is part of an Enterprise plan — [contact sales](https://bitquery.io/forms/api). :::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} With the exception of Solana, Bitquery provides complete historical data (from genesis onward) for all supported blockchains. For Solana, full historical token transfers are available via the V1 API, while in V2, Bitquery offers price aggregates starting from 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 ![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) } } } ``` --- ## 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. :::note A dataset error may mean you are on a deprecated cube `dataset: combined` is supported by the current `Balances` and `Holders` cubes, but **not** by the deprecated `BalanceUpdates` / `TokenHolders` cubes they replaced. Running `EVM(dataset: combined) { BalanceUpdates }` on Ethereum fails with a database error such as `Database eth does not exist`, which looks like an outage or a permissions problem and is neither. If you hit that, check whether you are on a deprecated cube before debugging the join. See [Balances & Holders](/docs/cubes/balances-cube/). ::: ### 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. ::: :::info Migrated from the deprecated `BalanceUpdates` cube This example previously used `BalanceUpdates` with `sum(of: BalanceUpdate_Amount)`. `BalanceUpdates` is deprecated in favour of `Balances`, which exposes the current balance directly and supports `realtime`, `archive` and `combined`. The old cube does not support `combined`, so the original form of this query fails on Ethereum. ::: --- ## 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 or gRPC streams. # 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 or gRPC streams. # 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 9 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 within the context of EVM TokenHolders 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": { "TokenHolders": [ { "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. --- ## 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`. ::: --- ## 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 | $39/mo | 100K | 30 / min | — | | Pro | $99/mo | $79/mo | 1M | 90 / min | 100 | | Scale | $299/mo | $239/mo | 5M | 240 / min | 1,000 | | Enterprise | Custom | Custom | Custom | Custom | Unlimited | Annual billing saves 20% 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). A call costs about **5 points**, so points ÷ 5 ≈ included calls (e.g. Scale's 5M points ≈ 1M calls). 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 costs about 5 points**, adjusted by how much data it scans. 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 **$40 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**, across **all chains with complete history**. No card required. ## 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, pagination, and [starter trader / PnL examples](/docs/start/starter-queries/). 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', 'X-API-KEY': 'BQYuTITWanwYGz0YLGdcWSADO74o5RTX', 'Authorization': 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 from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # How to Fetch Ethereum Data with AppSync and AWS Lambda We will be using Lambda functions to use Ethereum data from [S3 buckets](/docs/cloud/evm/) 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 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 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 — 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 and signed actions over GraphQL and WebSocket. # Hyperliquid API 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 dataset is available both as a **GraphQL query** and as a **WebSocket subscription** (real-time stream) — change `query` to `subscription` and drop `limit`/`orderBy`. :::info How far back the API goes The `Hyperliquid` cubes serve a **rolling ~30-day window**. That covers live streaming and recent history, which is what most bots, dashboards and monitoring need. For deeper history — backtests, multi-year research, full archive exports — use the [Blockchain Data Lake](/docs/data-lake/), which serves the complete archive over S3 using the same protobuf schema as the Kafka streams. Contact [sales@bitquery.io](mailto:sales@bitquery.io) for archive access and custom export ranges. ::: :::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 # current open perp positions per trader MarkPrices # latest mark price per market Orders # order lifecycle: placed, filled, canceled, rejected PerpFundings # per-trader funding payments PerpLiquidations # perp liquidations PriceUpdates # oracle / reference price updates SignedActions # raw signed L1 actions (order, cancel, modify, ...) TraderLeverageUpdates # leverage / margin-mode changes Trades # fills with direction, fees, leverage, PnL Twaps # TWAP order lifecycle } } ``` | 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` | | 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 | | [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 | ## Why Bitquery instead of the native Hyperliquid WebSocket API? 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 — no market-wide stream, no trader discovery | 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 | | Historical data | Live + snapshot only; separate REST with pagination limits. The public `s3://hyperliquid-archive` bucket holds **L2 book snapshots and asset contexts only** — no trades, candles or spot — updated roughly monthly with no completeness guarantee | Same GraphQL query for history and live stream over a rolling ~30-day window; full archive via the [Data Lake](/docs/data-lake/) | | 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 is bare price/size/side | Direction, fees, leverage, size-before, realized PnL 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) | | 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 | | 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 | `BTC`, `HYPE`, `AAPL` | | `CoinRaw` | Raw Hyperliquid coin id; HIP-3 markets are prefixed with their deployer namespace | `BTC`, `xyz:SMSN`, `mkts:AAPL` | | `Kind` | Market class | `perp`, `spot`, `hip3` | | `IsPerp` | `true` for perpetual markets (including HIP-3 perps) | `true` / `false` | | `Protocol` | HIP-3 deployer namespace, empty for native markets | `xyz`, `mkts` | | `MaxLeverage` | Maximum leverage allowed on the market | `40` | **HIP-3** markets are builder-deployed perps — tokenized stocks (`mkts:AAPL`), indices (`xyz:KR200`, `TOTAL2`) and other synthetic assets trade alongside native Hyperliquid perps and appear in the same cubes with `Kind: hip3`. `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`. - `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 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` | [hyperliquid/candles.proto](https://github.com/bitquery/streaming_protobuf/blob/main/hyperliquid/candles.proto) | | `hyperliquidcore.messages.proto` | [hyperliquid/hypercore.proto](https://github.com/bitquery/streaming_protobuf/blob/main/hyperliquid/hypercore.proto) | See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts) for access and consumer setup. --- ## Hyperliquid Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/hyperliquid/ Hyperliquid Core (HyperCore) data - Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Hyperliquid (HyperCore) Data Bitquery provides **Hyperliquid Core data dumps** in **Parquet format**, 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. It is an **event stream, not a state chain**: there are no blocks, transactions, or transfers tables. Every row is an exchange event (an order status change, a book delta, a match), and every row carries `Block_Number` and `Block_Time`, so datasets join on block without a separate blocks table. ## Available Hyperliquid Topics | Topic | Grain | What it holds | | --- | --- | --- | | `order_statuses` | one row per order lifecycle event | Full order lifecycle: `open`, `canceled`, `filled`, `triggered`, and every `*Rejected` state, with TIF, trigger conditions, and TP/SL children | | `book_diffs` | one row per order-level book delta | **L4** book changes — `new` / `update` / `remove`, each with the owning address, order id, price and size | | `fills` | one row per counterparty per match | Both sides of every match, with realized PnL, fee, fee token, taker flag, and liquidation detail | | `oracle_updates` | one row per oracle publication | Mark, spot, and external perp price inputs, plus the resulting oracle prices per coin | | `misc_events` | one row per ledger event | Deposits, withdrawals, transfers, funding, delegation, validator rewards | | `twap_statuses` | one row per TWAP state change | TWAP order state: total size, executed size and notional, duration, terminal status | | `core_writer_actions` | one row per HyperEVM→HyperCore action | Actions submitted to HyperCore from HyperEVM contracts, with the originating EVM transaction hash | Pick `fills` for executed volume and realized PnL, `order_statuses` for intent and rejection analysis, and `book_diffs` when you need to rebuild the book at an arbitrary instant. ### Why L4 Matters Hyperliquid's own free archive publishes **L2 book snapshots** and asset contexts. This dataset is a different shape: `book_diffs` carries **per-order deltas** with the owning address and order id. An L2 snapshot tells you the book was 12 deep at a price; an L4 diff stream tells you *which* order moved and *whose* it was. Queue position, order lifetime, maker behaviour, and spoofing patterns are only recoverable at L4. Likewise, `order_statuses` includes orders that **never traded**. Rejects and cancels are invisible in any trades-only dataset — and in the sample below they are 96% of all 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) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid//.parquet ``` **Sample Parquet downloads (public S3)** - **Order Statuses** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/order_statuses/1075858800_1075858999.parquet) - **Book Diffs (L4)** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/book_diffs/1075858800_1075858999.parquet) - **Fills** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/fills/1075858800_1075858999.parquet) - **Oracle Updates** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/oracle_updates/1075858800_1075858999.parquet) - **Misc Events** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/misc_events/1075858800_1075858999.parquet) - **TWAP Statuses** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/twap_statuses/1075858000_1075858199.parquet) - **Core Writer Actions** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/core_writer_actions/1075858000_1075858199.parquet) The samples come from one continuous slice — blocks `1075858000`–`1075858999`, about **66 seconds** of live HyperCore. Event counts in that slice: | Topic | Records | | --- | ---: | | `order_statuses` | 142,955 | | `book_diffs` | 89,241 | | `fills` | 1,552 | | `misc_events` | 32 | | `oracle_updates` | 24 | | `core_writer_actions` | 10 | | `twap_statuses` | 3 | ## Hyperliquid Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── hyperliquid/ ├── book_diffs/ │ ├── _.parquet │ └── ... ├── core_writer_actions/ │ ├── _.parquet │ └── ... ├── fills/ │ ├── _.parquet │ └── ... ├── misc_events/ │ ├── _.parquet │ └── ... ├── oracle_updates/ │ ├── _.parquet │ └── ... ├── order_statuses/ │ ├── _.parquet │ └── ... └── twap_statuses/ ├── _.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Files hold **200 blocks** each, and HyperCore produces roughly 14 blocks per second, so one file is about 14 seconds of market activity. File sizes track activity rather than block count — in the sample, two `order_statuses` files covering the same 200 blocks each are 279 KB and 6.4 MB. **A range with no events produces no file.** `fills` and `book_diffs` have no file for `1075858000_1075858199` because nothing matched in those blocks. Discover files under a prefix rather than generating names from a stride. ## Common Columns Every topic carries these two columns, and they are the join key across topics: | Column | Type | Description | | --- | --- | --- | | `Block_Number` | string | HyperCore block height | | `Block_Time` | string | Block timestamp, **epoch nanoseconds** | Each topic then prefixes its own fields with the topic's singular name — `Fill_*`, `OrderStatus_*`, `BookDiff_*`, `OracleUpdate_*`, `MiscEvent_*`, `TwapStatus_*`, `CoreWriterAction_*` — with nested structures flattened using `_`, for example `OrderStatus_Order_Coin` and `OrderStatus_Builder_Fee`. ## Correctness Notes Five things about this dataset will silently produce wrong numbers if you treat it like an EVM chain export. ### 1. Numbers Are Strings, Including `Block_Number` Prices, sizes, PnL, fees, timestamps, and the block height itself are stored as **strings**, not numerics. This is deliberate — exchange decimals must not pass through a float. Cast explicitly, and use `Decimal` rather than `float` for money: ```python from decimal import Decimal df["px"] = df.Fill_Px.map(Decimal) df["block"] = df.Block_Number.astype("int64") ``` Summing `Fill_Px` as float across a large export will drift; `Decimal` will not. ### 2. Every Match Appears Twice `fills` carries **one row per counterparty**, so a single match produces two rows — one taker, one maker. In the sample, 1,552 fill rows are exactly 776 `Fill_Crossed = true` and 776 `false`, resolving to 781 unique `(Block_Number, Fill_Coin, Fill_Tid)` keys. Summing `Fill_Sz` across the raw table **double-counts volume**. Filter to one side: ```sql SELECT SUM(CAST(Fill_Sz AS DECIMAL(38,8))) FROM hyperliquid_fills WHERE Fill_Crossed = true -- taker side only ``` ### 3. `Fill_Hash` Is Not a Join Key One L1 transaction spans many matches, and TWAP fills carry 32 zero bytes on both sides. In the sample, 1,552 rows share only 464 distinct hashes, and 156 rows have an all-zero hash. Key trades on **`(Block_Number, Fill_Coin, Fill_Tid)`** instead. ### 4. Rejected Orders Dominate `order_statuses` `order_statuses` is a record of *intent*, and most intent never trades. The sample's 142,955 order events break down as: | Status | Records | | --- | ---: | | `badAloPxRejected` | 49,095 | | `open` | 44,184 | | `canceled` | 42,895 | | `perpMarginRejected` | 2,979 | | `iocCancelRejected` | 1,773 | | `reduceOnlyCanceled` | 918 | | `filled` | 793 | | `insufficientSpotBalanceRejected` | 206 | | `reduceOnlyRejected` | 59 | | `minTradeNtlRejected` | 31 | Only **793 of 142,955** events — about 0.55% — are `filled`. `badAloPxRejected` alone is a third of the file: post-only (`Alo`) orders priced through the book, rejected rather than crossed. `Alo` is 138,929 of the 142,955 `Tif` values, so this dataset is dominated by market makers quoting and requoting. Filter on `OrderStatus_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` | nanoseconds | | `OrderStatus_Time` | nanoseconds | | `Fill_Time` | milliseconds | | `OrderStatus_Order_Timestamp` | milliseconds | | `TwapStatus_State_Timestamp` | milliseconds | In the sample, the same event carries `Block_Time = 1784285089551711280` and `Fill_Time = 1784285089551`. ### Schema Varies Between Files A column that is entirely null across one file is written with Parquet's **null type**, while the same column in a busier file is typed `string`. Concatenating files with a strict reader fails: ```python # fails: Fill_TwapId is null in one file, string in the other pa.concat_tables(tables) # works pa.concat_tables(tables, promote_options="permissive") ``` In Spark or Athena, declare the schema explicitly rather than inferring it from a single file. ## The `Coin` Namespace `Fill_Coin`, `OrderStatus_Order_Coin`, and `BookDiff_Coin` cover four market types in one column. The sample holds 336 distinct coins: | Form | Meaning | Sample events | | --- | --- | ---: | | `HYPE`, `BTC` | Plain perpetual | 83,665 | | `xyz:...` | HIP-3 builder-deployed perp | 55,746 | | `@107` | Spot pair, by index | 3,360 | | `#1890` | Outcome / prediction token | 184 | Filter by prefix to isolate a market type — HIP-3 perps are already 39% of order events in this slice, so leaving them in a "Hyperliquid perps" aggregate will not give you the numbers you expect. ## Topic Schemas `Block_Number` and `Block_Time` are omitted below. ### fills One row per counterparty per match. 1,552 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `Fill_User` | string | Address of this side of the match | | `Fill_Coin` | string | Market — see the Coin namespace above | | `Fill_Side` | string | `B` (buy) or `A` (sell/ask) | | `Fill_Px`, `Fill_Sz` | string | Execution price and size | | `Fill_StartPosition` | string | **Signed position before the fill** — negative is short. Not a money amount | | `Fill_Dir` | string | Human-readable direction: `Open Long`, `Close Short`, `Long > Short`, `Buy`, `Sell` | | `Fill_ClosedPnl` | string | Realized PnL on this fill. Non-zero on 704 of 1,552 sample rows | | `Fill_Fee`, `Fill_FeeToken` | string | Fee paid and its token — `USDC` on 1,524 sample rows, also `HYPE` and spot indices | | `Fill_Hash` | string | L1 transaction hash — **not unique per fill**, all-zero for TWAP | | `Fill_Oid`, `Fill_Tid` | string | Order id and trade id. `Tid` identifies the match | | `Fill_Crossed` | bool | `true` on the taker side, `false` on the maker side | | `Fill_Time` | string | Fill timestamp, **epoch milliseconds** | | `Fill_Cloid` | string | Client order id, when the trader supplied one | | `Fill_TwapId` | string | Parent TWAP order, when the fill came from one | | `Fill_BuilderFee`, `Fill_Builder` | string | Builder-code fee and the builder address | | `Fill_DeployerFee` | string | HIP-3 deployer fee | | `Fill_PriorityGas` | string | Priority gas paid | | `Fill_Liquidation_*` | mixed | `LiquidatedUser`, `MarkPx`, `Method` — populated only on liquidations | | `Fill_Extra` | string | Forward-compatibility map | ### order_statuses One row per order lifecycle event. 142,955 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `OrderStatus_User` | string | Order owner | | `OrderStatus_Status` | string | `open`, `canceled`, `filled`, `triggered`, or a `*Rejected` variant | | `OrderStatus_Time` | string | Status timestamp, **epoch nanoseconds** | | `OrderStatus_Order_Coin` | string | Market | | `OrderStatus_Order_Side` | string | `B` or `A` | | `OrderStatus_Order_LimitPx` | string | Limit price | | `OrderStatus_Order_Sz` | string | Remaining size | | `OrderStatus_Order_OrigSz` | string | Original size — compare with `Sz` to size a partial fill | | `OrderStatus_Order_Oid` | string | Order id — join to `fills.Fill_Oid` and `book_diffs.BookDiff_Oid` | | `OrderStatus_Order_Timestamp` | string | Order placement time, **epoch milliseconds** | | `OrderStatus_Order_OrderType` | string | Order type | | `OrderStatus_Order_Tif` | string | Time in force: `Alo`, `Ioc`, `Gtc`, `FrontendMarket` | | `OrderStatus_Order_TriggerCondition` | string | Trigger condition text | | `OrderStatus_Order_TriggerPx` | string | Trigger price | | `OrderStatus_Order_IsTrigger` | bool | Whether this is a trigger order | | `OrderStatus_Order_IsPositionTpsl` | bool | Position-level take-profit / stop-loss | | `OrderStatus_Order_ReduceOnly` | bool | Reduce-only flag | | `OrderStatus_Order_Cloid` | string | Client order id | | `OrderStatus_Order_Children` | string | Child TP/SL bracket orders | | `OrderStatus_Hash` | string | L1 transaction hash | | `OrderStatus_Builder_Address`, `OrderStatus_Builder_Fee` | string, int64 | Builder code attribution | ### book_diffs One row per order-level book change — the L4 stream. 89,241 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `BookDiff_User` | string | Owner of the order that changed | | `BookDiff_Oid` | string | Order id | | `BookDiff_Coin` | string | Market | | `BookDiff_Side` | string | `B` (bid, 47,697 rows) or `A` (ask, 41,544 rows) | | `BookDiff_Px` | string | Price level | | `BookDiff_Kind` | string | `new` (43,699), `remove` (44,120), or `update` (1,422) | | `BookDiff_Sz` | string | Size on `new` | | `BookDiff_OrigSz`, `BookDiff_NewSz` | string | Size before and after on `update` | Apply the diffs in `Block_Number` order to reconstruct the book at any instant. `new` and `remove` nearly balance in a steady market — the small excess of removals over additions is the book shrinking across the slice. ### oracle_updates One row per oracle publication. 24 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `OracleUpdate_UpdateClass` | string | `Deployer` (19 rows) or `Fallback` (5 rows) | | `OracleUpdate_MarkPxInputs` | string | Per-publisher mark price inputs | | `OracleUpdate_SpotPxInputs` | string | Spot price inputs | | `OracleUpdate_ExternalPerpPxInputs` | string | External venue perp prices | | `OracleUpdate_OraclePxs_CoinToMarkPx` | string | Resulting mark price per coin | | `OracleUpdate_OraclePxs_CoinToOraclePx` | string | Resulting oracle price per coin | | `OracleUpdate_OraclePxs_CoinToExternalPerpPx` | string | External perp price per coin | Oracle prices drive funding and liquidation, so join these to `fills` on `Block_Number` when reconstructing why a liquidation fired. ### misc_events One row per ledger event. 32 rows in the sample, across `LedgerUpdate` (27), `CWithdrawal` (2), `GossipPriorityAuctionRestart` (2), and `ValidatorRewards` (1). | Column | Type | Description | | --- | --- | --- | | `MiscEvent_InnerType` | string | Which event variant this row carries — read it before any other field | | `MiscEvent_Time` | string | Event timestamp | | `MiscEvent_Hash` | string | L1 transaction hash | | `MiscEvent_LedgerUpdate_Users` | list\ | Accounts affected | | `MiscEvent_LedgerUpdate_Delta_Type` | string | Deposit, withdraw, transfer, spot transfer, and so on | | `MiscEvent_LedgerUpdate_Delta_Amount`, `_Usdc`, `_UsdcValue` | string | Amounts, with the USDC-denominated value | | `MiscEvent_LedgerUpdate_Delta_Fee`, `_FeeToken`, `_NativeTokenFee` | string | Fees on the ledger movement | | `MiscEvent_CWithdrawal_*` | mixed | `Amount`, `User`, `IsFinalized` for chain withdrawals | | `MiscEvent_CDeposit_*`, `MiscEvent_Delegation_*`, `MiscEvent_Funding_*` | mixed | Populated for their respective `InnerType` | This is a **sparse union table**: only the column family matching `MiscEvent_InnerType` is populated on a given row, and unused families are null for the whole file. See the schema note above. ### twap_statuses One row per TWAP state change. 3 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `TwapStatus_TwapId` | string | TWAP order id — join to `Fill_TwapId` | | `TwapStatus_State_Coin`, `_User`, `_Side` | string | Market, owner, direction | | `TwapStatus_State_Sz` | string | Total size to execute | | `TwapStatus_State_ExecutedSz`, `_ExecutedNtl` | string | Size and notional executed so far | | `TwapStatus_State_Minutes` | int64 | Duration the TWAP runs over | | `TwapStatus_State_Timestamp` | string | Start time, **epoch milliseconds** | | `TwapStatus_State_ReduceOnly`, `_Randomize` | bool | TWAP flags | | `TwapStatus_Status` | string | Terminal status, e.g. `finished` | | `TwapStatus_StatusError` | string | Error text when the TWAP failed | ### core_writer_actions One row per action submitted to HyperCore from a HyperEVM contract. 10 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `CoreWriterAction_User` | string | Address that submitted the action | | `CoreWriterAction_Nonce` | string | Action nonce | | `CoreWriterAction_EvmTxHash` | string | **Originating HyperEVM transaction** — the bridge back to EVM data | | `CoreWriterAction_Action_Type` | string | Action variant, e.g. `SystemSpotSendAction`, `SystemSendAssetAction` | | `CoreWriterAction_Action_Destination`, `_Token`, `_Wei` | mixed | Transfer target, token index, amount | | `CoreWriterAction_Action_DestinationDexOrSpot`, `_SourceDexOrSpot` | int64 | Venue routing | | `CoreWriterAction_Action_Orders` | list | Orders placed by the action | | `CoreWriterAction_Action_Builder`, `_MaxFeeRate` | mixed | Builder-code attribution | `CoreWriterAction_EvmTxHash` is the join key to HyperEVM transaction data, making this the one table that links the two halves of Hyperliquid. ## Joining Topics Every topic carries `Block_Number`, and the order id threads the trading tables together: ```sql -- taker fills with the order that produced them SELECT f.Fill_Coin, f.Fill_Px, f.Fill_Sz, f.Fill_ClosedPnl, o.OrderStatus_Order_Tif, o.OrderStatus_Order_ReduceOnly FROM hyperliquid_fills f JOIN hyperliquid_order_statuses o ON f.Fill_Oid = o.OrderStatus_Order_Oid AND o.OrderStatus_Status = 'filled' WHERE f.Fill_Crossed = true ``` Because one order produces many status events and many fills, join on `Oid` plus a status filter, or aggregate one side first — otherwise you get a cross product. ## Reading Files in Python ```python from decimal import Decimal BASE = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/" RANGE = "1075858800_1075858999" fills = pd.read_parquet(f"{BASE}fills/{RANGE}.parquet") orders = pd.read_parquet(f"{BASE}order_statuses/{RANGE}.parquet") # taker side only — every match is in the file twice taker = fills[fills.Fill_Crossed] taker = taker.assign( px=taker.Fill_Px.map(Decimal), sz=taker.Fill_Sz.map(Decimal), ) print("matches:", len(taker), "of", len(fills), "fill rows") print("notional:", (taker.px * taker.sz).sum()) # realized PnL by wallet pnl = fills.assign(pnl=fills.Fill_ClosedPnl.map(Decimal)).groupby("Fill_User").pnl.sum() print(pnl.sort_values().tail()) # order flow is mostly rejects, not trades print(orders.OrderStatus_Status.value_counts().head()) ``` ## Real-Time vs Batch Data Access Cloud data dumps 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 exports and the live streams share the same field definitions, so a backtest reading this archive and a production consumer reading the stream decode with the same generated code. --- ## 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 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 complete funding history of any address. :::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-09-04T09:00:00.048813Z" }, "Funding": { "Market": { "Symbol": "XYZ100" }, "Amount": "-15.217007", "Rate": "0.0000096689", "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. 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 } } 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 } } ticks: count paid: sum(of: Funding_Amount) } } } ``` ## Funding over a date range Add a `Block: {Time: ...}` filter to bound the export to a tax year, a quarter or any window. 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-09-01T00:00:00Z", till: "2026-09-04T00: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. ## 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. - `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 accumulated funding, 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. :::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 traded size over the last 24 hours, with distinct trader counts. 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: "volume"} where: { Trade: {Market: {Kind: {is: "hip3"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Trade { Market { Symbol CoinRaw Protocol } } volume: sum(of: Trade_Execution_Size) trades: count 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**. 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} where: {Trade: {Market: {CoinRaw: {is: "xyz:SP500"}}}} ) { Block { Time } Trade { Market { Symbol CoinRaw Kind Protocol } Execution { Price Size Side Direction IsAggressor Oid Tid } Fees { Fee FeeToken BuilderFee } Position { Leverage IsCross SizeBefore RealizedPnl } Trader { Address } } } } } ``` Change `CoinRaw` to any market from the discovery query — `xyz:NVDA`, `xyz:TSLA`, `xyz:GOLD`, `mkts:USTECH`, `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 | | `oracle` | the published oracle price | | `extPerpInput` | external perp reference, where used | 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, `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: 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: "minute_Time"} where: { Trade: {Market: {CoinRaw: {is: "xyz:SP500"}}} Block: {Time: {since_relative: {hours_ago: 6}}} } ) { minute: Block { Time(interval: {in: minutes, count: 5}) } 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. ## 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 } 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} where: {Liquidation: {Market: {Kind: {is: "hip3"}}}} ) { Block { Time } Liquidation { Market { Symbol CoinRaw Protocol } LiquidatedUser Liquidator MarkPx Method Execution { Price Size Side } Position { Leverage SizeBefore RealizedPnl } } } } } ``` `Method` distinguishes a `market` liquidation from a `backstop` one. ## 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. - **`Position.SizeBefore` is a signed position size** before the fill, negative for short. It is 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 (shorter for signed actions). For longer ranges, see [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) or contact [sales@bitquery.io](mailto:sales@bitquery.io) for a historical export. ## 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 L3 Order Book API — 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 L3 Order Book API 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. ## 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 only exposes order-level detail for *your own* account (`orderUpdates`, `userFills`); 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/) ::: ## Order updates Every order event carries `Status` (`open`, `filled`, `canceled`, `rejected`, ...), `OrderType` (`Limit`, trigger types like Stop Market / Take Profit), time-in-force `Tif` (`Gtc`, `Ioc`, `Alo`), the limit price, the current and original size, and trigger settings for conditional orders. Run it in the IDE: [Hyperliquid Recent Orders ➤](https://ide.bitquery.io/hyperliquid-recent-orders) ```graphql query { Hyperliquid { Orders( limit: {count: 50} where: {Block: {Time: {since_relative: {minutes_ago: 1}}}} ) { Block { Time } Order { Market { Symbol Kind } Oid Status 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. - `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 } Oid Status OrderType Tif Side LimitPx Size OrigSz IsTrigger ReduceOnly Trader { Address } } } } } ``` ## Order book updates `BookUpdates` streams **deltas of the on-chain order book**. `Kind` is `new` (level added), `change` (size changed) or `remove` (order left the book); with `Px`, `Size`, `SizeBefore`, the order `Oid` and the trader behind the order. Consume the stream and apply the deltas to maintain a live book. 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 { Time } BookUpdate { 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..."}}}`. ## TWAP orders `Twaps` tracks the lifecycle of TWAP orders: `State.Status` moves from `activated` through execution to `finished` (or `terminated`), 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 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 Liquidation History by Wallet 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 complete liquidation history**. 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. :::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. `Position.SizeBefore` is the signed size that existed immediately before the liquidation — negative for a short. 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} where: {Liquidation: {LiquidatedUser: {is: "0x2b5dba3bc4cbb1b94d1e57fcbe0fbc82731ce5f2"}}, Block: {Time: {since_relative: {days_ago: 3}}}} ) { Block { Time } Liquidation { Market { Symbol Kind } Method MarkPx LiquidatedUser Execution { Price Size Side Direction Hash } Position { Leverage IsCross Side SizeBefore } Fees { Fee FeeToken } } } } } ``` Sample response: ```json { "Block": { "Time": "2026-09-04T09:58:14.257546Z" }, "Liquidation": { "Market": { "Symbol": "SKR" }, "Method": "market", "MarkPx": "0.024767", "LiquidatedUser": "0x2b5dba3bc4cbb1b94d1e57fcbe0fbc82731ce5f2", "Execution": { "Price": "0.024831", "Size": "2663.0", "Side": "Buy", "Direction": "Close Short" }, "Position": { "Leverage": 3, "IsCross": false, "Side": "Short", "SizeBefore": "-2663.0" }, "Fees": { "Fee": "0.028565", "FeeToken": "USDC" } } } ``` `Execution.Direction` reads `Close Short` because liquidating a short is a buy that closes it — the direction describes the effect on the liquidated position, not the trader's intent. ## Liquidation totals per market One row per market and method, with the number of liquidation events, the total size closed and the fees charged. 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: "0x2b5dba3bc4cbb1b94d1e57fcbe0fbc82731ce5f2"}}, Block: {Time: {since_relative: {days_ago: 3}}}} ) { Liquidation { Market { Symbol } Method } events: count size: sum(of: Liquidation_Execution_Size) fees: sum(of: Liquidation_Fees_Fee) } } } ``` ## Liquidations over a date range Bound the export to a tax year, a quarter, or the window around a specific market event. 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} where: { Liquidation: {LiquidatedUser: {is: "0x2b5dba3bc4cbb1b94d1e57fcbe0fbc82731ce5f2"}} Block: {Time: {since: "2026-09-01T00:00:00Z", till: "2026-09-04T00:00:00Z"}} } ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx Execution { Price Size Side Direction } Position { Leverage IsCross Side SizeBefore } Fees { Fee FeeToken } } } } } ``` ## Backstop liquidations only Filter on `Method` to isolate the liquidations the backstop vault absorbed rather than the open market. These carry different `Execution.Direction` values from ordinary liquidations — `Auto-Deleveraging` and `Partial Borrow Liquidation` both appear here. 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: "0x2b5dba3bc4cbb1b94d1e57fcbe0fbc82731ce5f2"} Method: {is: "backstop"} } Block: {Time: {since_relative: {days_ago: 3}}} } ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx Execution { Price Size Side Direction } Position { Leverage IsCross SizeBefore } } } } } ``` ## 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: "0x2b5dba3bc4cbb1b94d1e57fcbe0fbc82731ce5f2"}}} ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx LiquidatedUser Execution { Price Size Side Direction } Position { Leverage IsCross Side SizeBefore } } } } } ``` Drop the `where` clause to stream every liquidation on the exchange, or swap the address for a list to watch a set of accounts. ## Notes - `Liquidator` is empty on open-market liquidations; it is populated when a specific liquidator address takes the position. - A single blow-up can produce several records — one per market the account held. - 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, current open positions and leverage changes 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. Run it in the IDE: [Hyperliquid Liquidations ➤](https://ide.bitquery.io/hyperliquid-liquidations) ```graphql query { Hyperliquid { PerpLiquidations(limit: {count: 50}, orderBy: {descending: Block_Time}) { Block { Time } Liquidation { Market { Symbol Kind } Method MarkPx Liquidator LiquidatedUser Execution { Price Size Side Direction Hash } Position { Leverage IsCross Side SizeBefore } 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 Execution { Price Size Side } Position { Leverage IsCross SizeBefore } } } } } ``` ## 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. 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}) { 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. ## Current positions `CurrentPositions` is a **state cube** with the currently open perp positions: signed `Size` (negative = short, empty = flat), leverage, margin mode, accumulated `Funding` and `RealizedPnl`. Run it in the IDE: [Hyperliquid Current Positions ➤](https://ide.bitquery.io/hyperliquid-current-positions) ```graphql query { Hyperliquid { CurrentPositions( limit: {count: 50} orderBy: {descending: LastTime} where: {Market: {Symbol: {is: "BTC"}}} ) { LastBlock LastTime Market { Symbol Kind } Position { Size Leverage IsCross Funding RealizedPnl } Trader { Address } } } } ``` Swap the filter to `where: {Trader: {Address: {is: "0x..."}}}` to get every open position of one trader. ## 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 } } } } } ``` All four cubes stream over WebSocket with the same shape — change `query` to `subscription` and drop `limit`/`orderBy`. --- ## 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 with Bitquery GraphQL and WebSocket, covering native perps, spot and HIP-3 builder markets like tokenized stocks. # Hyperliquid Mark Prices & Price Updates API This page covers the `MarkPrices` and `PriceUpdates` cubes: the current mark price of every market, and the underlying oracle / reference price feed. :::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 market with the latest mark price and the block it was last updated at. It includes HIP-3 markets, so tokenized stocks (`mkts:AAPL`, `mkts:GOOGL`) and indices are covered too. 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: {Symbol: {is: "BTC"}}}` (or `CoinRaw` for HIP-3 markets, since symbols can repeat across deployer namespaces). ## Price updates `PriceUpdates` is the event feed the mark prices are built from. `Kind` distinguishes the source — values observed include `spotInput`, `extPerp` and `extPerpInput` — and `DailyPx` carries the daily reference price when present. `UpdateClass` is `Normal` in regular operation. 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 tradeable OHLCV rather than oracle prices, use [Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api#ohlcv-candles). --- ## Hyperliquid Signed Actions API URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-signed-actions-api/ Query and stream raw signed L1 actions on Hyperliquid with Bitquery: order, cancel, modify, batchModify, updateLeverage and more, with signer, broadcaster, bundle hash and status. # Hyperliquid Signed Actions API `SignedActions` is the lowest-level Hyperliquid cube: every **signed user action** submitted to the L1 — order placements, cancels, modifies, leverage updates, transfers and the rest — before they materialize as orders, trades or position changes. :::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}) { 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: `order`, `cancel`, `cancelByCloid`, `modify`, `batchModify`, `updateLeverage`, `twapOrder`, and other Hyperliquid exchange actions. - `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, or an error status for rejected ones; `Response` (raw string field) carries the node response. - `Action` — the raw action payload as a JSON string, when you need parameters beyond the typed fields. - `Leverage { Asset Value IsCross }` is populated for `updateLeverage` actions. Filter examples: - One account's activity: `where: {User: {is: "0x..."}}` - Only leverage updates: `where: {ActionType: {is: "updateLeverage"}}` - Failed actions: `where: {Status: {not: "ok"}}` As with every Hyperliquid cube, 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. --- ## 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 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` through execution to `finished` (or `terminated`). 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. 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: "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2" } } } Block: {Time: {since_relative: {days_ago: 3}}} } ) { 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-09-04T09:42:28.039330Z" }, "Twap": { "TwapId": "2180078", "Market": { "Symbol": "GOLD" }, "Order": { "Side": "Sell", "Size": "40.0", "ReduceOnly": true, "Randomize": true }, "Interval": { "DurationMinutes": 240 }, "State": { "Status": "finished", "ExecutedSize": "40.0", "ExecutedNotional": "178900.30962" } } } ``` ## 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. 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 } where: { Trade: {TwapId: {eq: "2180078"}} Block: {Time: {since_relative: {days_ago: 3}}} } ) { Block { Time } Trade { TwapId Market { Symbol } Execution { Price Size Side Direction Tid } Fees { Fee FeeToken } Position { RealizedPnl } Trader { Address } } } } } ``` `TwapId` is a big integer, so the filter operator is `eq`, not `is`. A long TWAP can produce more fills than one page holds — TWAP `2180078` has 522. 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: "2180078"}} Block: {Time: {since_relative: {days_ago: 3}}} } ) { 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 `2180078` this returns 522 fills totalling exactly the 40.0 size on the parent order, at an average price of 4472.40, with 161.01 USDC of fees and 12,061.51 of realized PnL. That reconciliation — parent `ExecutedSize` equals the sum of child fill sizes — is the check most exports fail. ## 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 } where: { Trade: { IsTwap: true Trader: { Address: { is: "0x1e6db0fdf1a0f6edb78753184eb0fe5485c2eef2" } } } Block: {Time: {since_relative: {days_ago: 3}}} } ) { Block { Time } Trade { TwapId Market { Symbol } Execution { Price Size Side Direction Tid } Fees { Fee FeeToken } Position { 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, 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. :::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), the position it changed (leverage, margin mode, size before, realized PnL) and fees. `Direction` is one of `Open Long`, `Open Short`, `Close Long`, `Close Short`. 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} where: {Block: {Time: {since_relative: {minutes_ago: 10}}}} ) { Block { Number Time } Trade { Market { Symbol CoinRaw Kind IsPerp Protocol } Execution { Price Size Side Direction IsAggressor Oid Tid Hash } Fees { Fee FeeToken BuilderFee } IsTwap Position { Leverage IsCross Side SizeBefore RealizedPnl } Trader { Address Vault Signer } } } } } ``` Notes on the payload: - `Execution.Tid` is the trade id, `Oid` the order id that got filled, `Hash` the action hash. - `Fees.Fee` is in `FeeToken` (usually USDC); a **negative fee is a maker rebate**. - `Position.SizeBefore` is the signed position size before the fill (negative = short); `RealizedPnl` is the PnL realized by this fill. - `IsTwap: true` marks fills produced by a TWAP order (see [TWAPs](/docs/perpetuals/hyperliquid/hyperliquid-orders-api#twap-orders)). ### 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..."}}}}`. ## 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 Oid Tid } Fees { Fee FeeToken } IsTwap Position { Leverage IsCross Side RealizedPnl } Trader { Address } } } } } ``` ## OHLCV candles The `Candles` cube provides OHLCV per market and interval. `Interval.Time.Duration` is the candle length in **seconds** (e.g. `60` for one minute), `Start` the interval open time. OHLCV values are floats. 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: "mkts:AAPL"}}}` for the tokenized-stock market. ### 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. --- ## 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 | | -------------------- | ---------------------------- | ---------------------- | ----------------- | ------------------------------- | | **BalanceUpdates** | BalanceUpdate_Address | Currency_SmartContract | Transaction_Hash | — | | **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 | — | | **TokenHolders** | 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 | | -------------------- | ---------------------------- | ---------------------- | ----------------- | ------------------------------- | | **BalanceUpdates** | BalanceUpdate_Address | Currency_SmartContract | Transaction_Hash | — | | **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 | — | — | | **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. --- ## 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) ## 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.*`**. #### 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) ### 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/hypercore.proto](https://github.com/bitquery/streaming_protobuf/blob/main/hyperliquid/hypercore.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` — trades, orders, book updates, liquidations, funding, TWAPs and signed actions - `hyperliquid.candles.proto` — OHLCV candles per market and interval ### 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, ensuring efficient message consumption and processing is crucial for maintaining low latency and high throughput. 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 and Robinhood Chain | [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) | The full topic list with names, including Hyperliquid, 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 API - Solana - New Tokens, Trades, Live Prices: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. # 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 **9 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 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 API 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 API [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. 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/ Limit Order Price API via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. See examples in the Bitquery IDE. # Limit Order Price API: Crypto Price API for Limit Orders ## The Problem: Why Raw Trade Data Fails for Limit Orders Finding reliable price for limit order execution is critical for automated trading systems. Raw DEX trade data creates unreliable price signals that trigger false limit order executions, making a dedicated limit order price API essential for trading platforms. ### **Pool-Based Monitoring Issues** Current platforms monitor pool-based DEX streams filtered by specific addresses, but sometimes even a $500 trade can move prices 20-50% in less liquid pools: - **False triggers**: Price spikes cause unintended executions, requiring complex retry logic - **No pre-execution validation**: Systems skip validation to avoid latency, relying on user slippage tolerance - **User behavior**: Traders gravitate toward liquid pools, leaving smaller pools vulnerable - **System complexity**: Sophisticated retry mechanisms needed for erratic executions - **Poor execution**: Bad price signals reduce user confidence ### **Cross-DEX Price Fragmentation** The same token can trade at vastly different prices (e.g., $100 on Uniswap vs $95 on SushiSwap) due to liquidity isolation, arbitrage delays, and varying AMM formulas. ## The Solution: Aggregated Price Streams Bitquery's [Crypto Price API for limit orders](/docs/trading/crypto-price-api/) provides **aggregated price data** with built-in dampening mechanisms, serving as a reliable limit order price API: **Multi-pool aggregation** across all major DEXs **Cross-chain price discovery** for market-wide pricing **Real-time USD pricing** with built-in conversion **Time & volume thresholds** preventing manipulation [Try the API live ➤](https://ide.bitquery.io/1-second-crypto-price-stream) ### How Price Aggregation Works #### 1. **Time-Based Aggregation (1s to 1h)** - **1-3s**: High-frequency trading with minimal smoothing - **5s**: Optimal for most automated platforms - **30s**: Swing trading with reduced noise - **1h**: Long-term portfolio management #### 2. **Volume Thresholds ($1K to $1M)** - **$1K+**: Small-cap tokens - **$10K+**: Mid-cap tokens - **$100K+**: High-cap tokens - **$1M+**: Enterprise stability #### 3. **Multi-Chain Coverage** - **Ethereum**: Uniswap, SushiSwap, Curve, 1inch - **Solana**: Raydium, Orca, Jupiter - **BSC**: PancakeSwap, Venus - **Cross-chain normalization** for unified pricing #### 4. **Trade Filtering** Trades are excluded only when the trade amount is zero or below decimal precision (e.g. < 10^decimals/10,000), avoiding precision loss. Moving averages (SMA, WMA, EMA) and anomaly-resistant OHLC are still calculated on the resulting feed. For full details see the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). ## TradingView Integration TradingView integration can be achieved through a custom datafeed that connects to Bitquery's real-time price streams. The datafeed supports multiple timeframe resolutions (1s to 1h), subscribes to real-time OHLC data via WebSocket, and provides the structured bar data format that TradingView requires for live chart updates. This enables professional-grade charting with institutional-quality aggregated price data. [View live TradingView demo ➤](https://github.com/bitquery/tradingview-subscription-realtime/tree/main#demo) ### **Production Resources** **Complete Tutorial**: Follow our comprehensive [TradingView Real-Time Streaming Tutorial](/docs/usecases/tradingview-subscription-realtime/getting-started/) that shows how to integrate Bitquery's Crypto Price API with TradingView's Advanced Charts. **Production-Ready Code**: - **GitHub Repository**: [Complete implementation examples](https://github.com/bitquery/tradingview-subscription-realtime/tree/main) - **NPM SDK**: [`@bitquery/tradingview-sdk`](https://www.npmjs.com/package/@bitquery/tradingview-sdk) - Ready-to-chart SDK with copy-paste integration **Quick Start**: Simply copy the Advanced Charting Library into your project, add your Bitquery access token, and you're ready to stream real-time crypto price data to TradingView charts. ## Raw vs Aggregated Price Data: Real Examples ### **Raw Trade Data Issues (DEXTradeByTokens API)** Using raw DEX trade data directly can lead to unreliable limit order triggers. Here's what you typically see: **Example: ETH Price Volatility from Raw Trades** ```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) **Typical Raw Data Results:** - **12:00:01** - $2,420.15 (normal trade) - **12:00:02** - $3,890.44 (**+60% spike** from $500 sandwich attack) - **12:00:03** - $2,418.33 (back to normal) - **12:00:04** - $1,205.67 (**-50% crash** from MEV bot) - **12:00:05** - $2,422.89 (normal again) **Result**: Your limit orders at $2,500 would trigger falsely on the $3,890 spike, executing at poor prices. ### **Aggregated Price Data Solution (Crypto Price API)** The same ETH data through aggregated price feeds provides stability: **Example: ETH Price with 5-Second Time Aggregation** ```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) **Aggregated Results (Same Time Period):** - **12:00:05** - OHLC: $2,420/$2,425/$2,418/$2,423 (**Stable range**) - **Mean Price**: $2,421.50 (outliers filtered) - **Volume**: $847,500 (sufficient for reliability) **Result**: Your limit order at $2,500 remains inactive, preventing false execution. ## Types of Aggregation Available ### **1. Time-Based Aggregation** **Available Intervals**: `1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600` seconds **Use Cases by Interval:** - **1-3 seconds**: High-frequency trading with minimal smoothing - **5-10 seconds**: Standard automated trading platforms - **30-60 seconds**: Swing trading and portfolio management - **15+ minutes**: Long-term position management **Production Examples**: - [Real-time 1-second price stream ➤](https://ide.bitquery.io/1-second-crypto-price-stream) - [Multi-timeframe aggregation ➤](https://ide.bitquery.io/crypto-price-multiple-intervals) ### **2. Volume-Based Aggregation** :::caution Not currently available Volume-based intervals are **not currently available**. Filtering on `Interval: { TargetVolume: ... }` or `Interval: { VolumeBased: true }` returns **zero rows**, with HTTP 200 and no error — the query looks like it simply found nothing. To approximate the same intent, use a time interval and filter on volume in the `where` clause: ```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 } } } } ``` ::: **Example Results**: - **$100k volume threshold**: Price updates only when $100k+ traded - **Result**: Ultra-stable pricing, immune to low-volume manipulation - **Update frequency**: Variable (every 30 seconds to 5 minutes depending on activity) ### **3. Multi-Chain Currency Aggregation** **Cross-chain Bitcoin pricing example:** ```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) **Aggregation Sources**: - Native BTC on Bitcoin network - WBTC on Ethereum - Wrapped BTC on Solana - cbBTC on Base **Result**: True market-wide Bitcoin price, not isolated to single chain. ### **4. Pair-Specific Market Data** :::tip Track the deepest market instead of hardcoding one Pinning a limit order to a **named** pool reintroduces the single-pool risk described above — that pool can thin out or stop being where the token trades. Adding **`Ranking: { Position: { eq: 1 } }`** to a `Pairs` query instead follows the token's **top market** automatically: you get the price from the deepest pool at any moment, and thin pools cannot influence it. This is the complement to blended aggregation, not a contradiction of it. Blended [`Tokens`](/docs/trading/crypto-price-api/tokens) prices dampen spikes by mixing every pool, including thin ones; rank-1 removes the thin pools entirely and quotes the market with the most volume. Use blended prices when you want smoothing across the whole market, and rank-1 when you want the price you could actually execute against. See [Getting the Most Accurate Token Price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). ::: **Example: SOL/USDC on Raydium** ```graphql subscription { Trading { Pairs( where: { Market: {Protocol: {is: "Raydium"}} Token: {Symbol: {is: "SOL"}} QuoteToken: {Symbol: {is: "USDC"}} } ) { Price { Ohlc { Close } } Volume { Base Quote Usd } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ``` [Try SOL/USDC pair data ➤](https://ide.bitquery.io/SOL-USDC-pair-trading-data) **Use Case**: Market-making, arbitrage detection, DEX-specific strategies. ## Production Resources & Documentation ### **Implementation Guides** - **[Crypto Price API Documentation](/docs/trading/crypto-price-api/)** - Complete API reference with live examples - **[DEX Trade Filtering Guide](/docs/usecases/how-to-filter-anomaly-prices/)** - How to handle raw data anomalies - **[OHLC Candlestick API](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/)** - Ready-to-chart data with [live Bitcoin OHLC example ➤](https://ide.bitquery.io/bitcoin-currency-price-stream) - **[DEXTradeByTokens API](/docs/cubes/dextradesbyTokens/)** - Raw trade data for comparison ### **Real-Time Streaming** - **GraphQL Endpoint**: `https://streaming.bitquery.io/graphql` ([Try in IDE ➤](https://ide.bitquery.io/?endpoint=https://streaming.bitquery.io/graphql)) - **Kafka Topic**: `trading.prices` ([Schema & SDKs ➤](https://github.com/bitquery/streaming_protobuf/tree/main/market)) - **WebSocket Subscriptions**: Convert any query to `subscription` for real-time data ([WebSocket Guide ➤](/docs/subscriptions/websockets/)) ## **Proven Production Benefits** Based on real trading platform implementations ([see live comparison ➤](https://ide.bitquery.io/raw-vs-aggregated-price-comparison)): - **81% reduction** in false triggers from price spike dampening - **Eliminated retry logic complexity** through built-in price stability - **Universal pool coverage** removing need for manual liquidity selection - **Improved execution quality** leading to higher user confidence - **Reduced system latency** by eliminating pre-execution quote validation needs ## **Technical Advantages Over Raw Price Feeds** - **Time-based aggregation**: 1-second to 1-hour intervals proven in production - **Volume thresholds**: $1K to $1M+ filtering ensuring significant trading activity - **Multi-pool aggregation**: Comprehensive price discovery across all major DEXs - **Real-time USD pricing**: Built-in conversion eliminating additional API calls - **Bad trade filtering**: Automatic removal of outliers and routing anomalies [Explore all technical features ➤](/docs/trading/crypto-price-api/#key-features-of-these-apis) Ready to implement our crypto price API for limit orders in your trading system? **Get Started with Our Limit Order Price API:** - [Try live examples in our IDE ➤](https://ide.bitquery.io/?query_name=crypto-price-examples) - [Read the complete API documentation ➤](/docs/trading/crypto-price-api/) - [Download SDKs and schemas ➤](https://github.com/bitquery/streaming_protobuf/tree/main/market) - [Join our community ➤](https://t.me/Bloxy_info) Join trading platforms that have already upgraded from unreliable raw data to our enterprise-grade limit order price API for reliable price for limit order execution. --- ## 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 plan, and switching between monthly and annual billing (annual saves 20%) - **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 plan 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 plan 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 `eap` 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/) --- ## 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 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) with a free trial token. 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 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 Meteora DLMM 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 **9 chains in one API**; filter `Pair: { Market: { Protocol: { is: "lb_clmm" } } }` for DLMM. [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) gives pre-aggregated OHLC per DLMM pool down to one second, so you never build candles yourself. Worked examples are in [DLMM trades with USD price, market cap and supply](#dlmm-trades-with-usd-price-market-cap-and-supply) below. Reach for the chain-level queries on this page when you need what the Trading API does not carry: **history older than the Trading window** (about 30 days), pool reserves, per-instruction detail such as pool creation, or call / event context. ::: :::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} This subscription streams DLMM swaps as they land, filtered by the program address `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo`. `Trade.Buy.Currency` is what the trader received and `Trade.Sell.Currency` what the trader paid; `Trade.Market.MarketAddress` is the DLMM pool and `Transaction.Signer` the wallet that signed. `AmountInUSD` and `PriceInUSD` give the USD view of each side. You can run the subscription [in the Bitquery IDE](https://ide.bitquery.io/Real-time-trades-on-MeteoraDLMM-DEX-on-Solana). ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signature Signer } Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Market { MarketAddress } Buy { Currency { Name Symbol MintAddress } Amount AmountInUSD Account { Address Owner } PriceAgainstSellCurrency: Price PriceInUSD } Sell { Currency { Name Symbol MintAddress } Amount AmountInUSD Account { Address Owner } PriceAgainstBuyCurrency: Price PriceInUSD } } } } } ``` For the lowest latency, the same trades 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/). ## 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 } } } } ``` ## 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`. Swap in any mint and quote. `Trade.Currency` is the token you price, `Trade.Side.Currency` the quote it traded against, `Trade.Price` the price in the quote token and `Trade.PriceInUSD` the USD price; `Trade.Market.MarketAddress` tells you which DLMM pool printed the trade. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/latest-price-of-a-token-on-DLMM). ```graphql { Solana { DEXTradeByTokens( limit: { count: 1 } orderBy: { descending: Block_Time } where: { Trade: { Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } Currency: { MintAddress: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Price PriceInUSD Market { MarketAddress } Currency { Symbol } Side { Currency { Symbol } } } } } } ``` This is the last DLMM print for that pair. For a token's price across every venue, weighted to its most liquid market, use `Trading.Pairs` with `Ranking.Position` 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: one message per TRUMP/USDC trade on DLMM with the price of that print. `Side.Type` is `buy` when the trader bought TRUMP and `sell` when they sold it. You can run the subscription [in the Bitquery IDE](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-Meteora-DLMM). ```graphql subscription { Solana { DEXTradeByTokens( where: { Trade: { Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } Currency: { MintAddress: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Market { MarketAddress } Price PriceInUSD Amount Side { Amount Type } } } } } ``` ## Meteora DLMM OHLC API One-minute candles for TRUMP/USDC on DLMM built from `DEXTradeByTokens`: `open` and `close` are the prices at the lowest and highest slot in each interval, `high` and `low` the extremes, `volume` the TRUMP amount and `volumeUsd` the USD value. `PriceAsymmetry` is the absolute difference between the two sides' USD prices divided by their sum, computed only when both tokens have a USD price, so `PriceAsymmetry: { lt: 0.1 }` keeps trades whose sides agree to within roughly 20 percent and removes most bad prints. Change `interval` for other timeframes and `limit` for more candles. :::note Run this as a query, not a subscription: aggregates and time intervals do not work well over WebSocket. ::: You can run this query [in the Bitquery IDE](https://ide.bitquery.io/Meteora-DLMM-OHLC-API). ```graphql { Solana { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } limit: { count: 10 } where: { Trade: { Currency: { MintAddress: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } PriceAsymmetry: { lt: 0.1 } } Transaction: { Result: { Success: true } } } ) { Block { Timefield: Time(interval: { in: minutes, count: 1 }) } volume: sum(of: Trade_Amount) volumeUsd: sum(of: Trade_Side_AmountInUSD) Trade { high: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Slot) close: Price(maximum: Block_Slot) } count } } } ``` ### Pre-built DLMM candles from the Trading cube `Trading.Pairs` already aggregates every DLMM pool into OHLC, average price, volume and market cap per interval. This query returns the latest one-minute candle for TRUMP on DLMM quoted in USD. `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 } } } } ``` ## 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 token balances after the event, `PostAmountInUSD` their USD value, and `ChangeAmount` the signed change the event caused. This query returns the latest state of the TRUMP/USDC DLMM 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: "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. Each message is one reserve change with the pool, both currencies and the post-event balances. ```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 } } } } } ``` ## 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 traded in TRUMP on DLMM over the last 24 hours, with the amount each wallet bought and sold. `Trade.Account.Owner` is the trader's wallet. On Solana, `Side.Type` is the trader's action on `Trade.Currency`: `buy` rows are purchases of the token in the filter and `sell` rows are sales. :::note Run this as a query, not a subscription, because aggregates over WebSocket return wrong results. `Trade.Side.Account` is not available as an aggregate dimension on the `archive` and `combined` datasets. ::: You can run the query [in the Bitquery IDE](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DLMM-DEX). ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } where: { Trade: { Currency: { MintAddress: { is: $token } } Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } } Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { 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) trades: count } } } { "token": "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } ``` ## 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/USDC on DLMM from the `combined` dataset, which joins realtime and archive: total volume in TRUMP and in USD, USD volume split into buys and sells, and the count of each. Widen `days_ago` for longer windows; the archive reaches back to mid-2024. You can run the query [in the Bitquery IDE](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token_3). ```graphql query MyQuery { Solana(dataset: combined) { DEXTradeByTokens( where: { Block: { Time: { since_relative: { days_ago: 7 } } } Transaction: { Result: { Success: true } } Trade: { Currency: { MintAddress: { is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN" } } Side: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } Dex: { ProgramAddress: { is: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" } } } } ) { Trade { Currency { Symbol MintAddress Decimals } Side { Currency { Symbol 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 } } } } ) buys: count(if: { Trade: { Side: { Type: { is: buy } } } }) sells: count(if: { Trade: { Side: { Type: { is: sell } } } }) } } } ``` ## DLMM trades with USD price, market cap and supply The [Trades cube](/docs/trading/crypto-trades-api/trades-api/) (`Trading.Trades`) is trader-centric: one MEV-filtered row per swap, `Side` from the trader's point of view, `PriceInUsd`, `AmountsInUsd`, market cap and circulating supply on every row. Filter `Pair.Market.Protocol` `lb_clmm` to stream DLMM swaps across all pools in one subscription. See [DEXTrades vs DEXTradeByTokens vs Trading.Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades/) for when to use which. ```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 ProtocolFamily } Token { Symbol Address } QuoteToken { Symbol Address } } } } } ``` The same body runs as a query with `limit: { count: 10 }`, `orderBy: { descending: Block_Time }` and a `Block: { Time: { since_relative: { minutes_ago: 10 } } }` filter for the latest DLMM swaps. Add `Pair: { Token: { Address: { is: "" } } }` to follow one token, or reuse the PnL leaderboard pattern from the [Meteora DBC page](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/#top-traders-by-pnl-for-a-specific-meteora-dbc-token-last-30-minutes) with a DLMM `Market.Address`. ## 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 Dynamic Bonding Curve API](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/) - [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/) --- ## Meteora Dynamic Bonding Curve API URL: https://docs.bitquery.io/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/ Meteora Dynamic Bonding Curve API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. See examples in the Bitquery IDE. # Meteora Dynamic Bonding Curve API :::tip Need real-time Meteora DBC 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 Meteora DBC swaps with **USD price, market cap, and supply on every row** across **9 chains in one API**. Use this page when you need **historical Meteora DBC data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section we will see some API examples on tracking tokens on Meteora's dynamic bonding curve. :::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/) ::: ## Meteora DBC Trades in Real-Time The below query gets real-time information whenever there's a new trade on the Meteora DBC including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. You can run the query [here](https://ide.bitquery.io/Real-time-trades-on-Meteora-Dynamic-Bonding-Curve-on-Solana) ```graphql subscription { Solana { DEXTrades( where: { 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 Latest created pools on Meteora DBC Below query will give you the latest created Meteora DBC in realtime. You can test the query [here](https://ide.bitquery.io/token-creations-on-meteora-DBC) ```graphql subscription MyQuery { Solana { Instructions( where: { Instruction: { 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 } } } } ``` ## Track latest migrated Meteora DBC tokens Below query will give you the latest migrated tokens Meteora DBC in realtime. You can test the query [here](https://ide.bitquery.io/meteora-DBC-token-migrations-to-Meteors-DEX) ```graphql subscription MyQuery { Solana { Instructions( where: { Instruction: { 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 } } } } ``` ## Track Meteora DBC, LetsBonk.fun, Raydium Launchlab, Boop.fun and Moonit 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 } } } } ``` ## Check if the list of tokens has migrated from Meteora DBC Below query will give you the response for each token in the list if the token has graduated from Meteora DBC. Try out the query [here](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":["token mint address-1","token mint address-2","token mint address-3"] } ``` ## Market cap (Trading API) Use **Trading** **`Pairs`** with **`Market.Protocol`** **`dynamic_bonding_curve`** for aggregated **market cap**, **FDV**, **supply**, **price**, and **volume** on Meteora DBC. Replace **`solana:`** in **`Token.Id`** with your token. ### Get latest market cap for a specific Meteora DBC token **`limit: { count: 1 }`**, **`orderBy: { descending: Block_Time }`**, **`Token.Id`** with **`includesCaseInsensitive`**, interval duration **> 1** second, **`Market.Protocol`** **`dynamic_bonding_curve`**. Run the query [in the Bitquery IDE](https://ide.bitquery.io/specific-meteora-dbc-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: "dynamic_bonding_curve" } } } ) { 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 Meteora DBC tokens with market cap above $10K Subscribe when the token is on **Solana**, **`Market.Protocol`** is **`dynamic_bonding_curve`**, **`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-meteora-dbc-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: "dynamic_bonding_curve" } } } ) { Currency { Name Id Symbol } Token { Name Symbol Id Address Network } Market { Protocol ProtocolFamily } Supply { TotalSupply FullyDilutedValuationUsd MarketCap } } } } ```
## Latest Price of a Token on Meteora DBC You can use the following query to get the latest price of a token on Meteora DBC on Solana. You can run this query using this [link](https://ide.bitquery.io/latest-price-of-a-meteora-dbc-token). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN"}}, Currency: {MintAddress: {is: "token mint address"}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Meteora DBC OHLC API If you want to get OHLC data for any specific currency pair on Meteora DBC, you can use this api. Only use [this API](https://ide.bitquery.io/Meteora-DBC-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: "token mint address"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, 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 the Top Traders of a specific Token on Meteora DBC The below query gets the Top Traders of the specified Token `4kJkgxzuk1gcjsgRSVhdeSiC15ibQLRDKTuqtf2i16Dm` on Meteora DBC. 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/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DBC) ```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) } } } { "token": "token mint address" } ``` ## 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 `4kJkgxzuk1gcjsgRSVhdeSiC15ibQLRDKTuqtf2i16Dm`. Try out the API [here](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token). ```graphql query MyQuery { Solana(dataset: combined) { DEXTradeByTokens( where: {Block: {Time: {since: "2025-05-23T09:00:00Z", till: "2025-05-23T11:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "token mint address"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, 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}}}} ) } } } ``` ## Volatility of a Pair on Meteora Dynamic 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-a-Pair-on-Meteora-Dynamic) is the query to get the volatility for a selected pair in the last 24 hours. ```graphql query Volatility { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN" } } Buy: { Currency: { MintAddress: { is: "token mint address" } } } Sell: { Currency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } Block: { Time: { after: "2025-05-23T09:00:00Z" before: "2025-05-23T11:00:00Z" } } } ) { volatility: standard_deviation(of: Trade_Buy_Price) } } } ``` --- ## 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 Meteora DBC With Price, Market Cap, and Supply Stream **all Meteora DBC DEX trades** in real time with **USD price**, **market cap**, **FDV**, **circulating supply**, and **transaction fee** data. Filter by **`Pair.Market.Protocol: dynamic_bonding_curve`** to capture every swap across Meteora DBC in a single subscription. You can run this subscription [in the Bitquery IDE](https://ide.bitquery.io/Get-All-DEX-Trades-on-DBC-With-Price-Market-Cap-and-Supply).
Click to expand GraphQL query ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Protocol: { is: "dynamic_bonding_curve" } } } } ) { 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 Meteora DBC Token (Last 30 Minutes) Rank traders by **`PnL`** on one 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-meteora-DBC-token-curve_2).
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: "GowkHeDkWv5zvw7RmF9SHeNgxZVDzrVhn9MGBAk1Kfcn" } } } } ) { 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" } }) } } } ```
--- --- ## 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/Kafka/gRPC. ## 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/) | | 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.** Raw Solana trades cover a rolling recent window via API; OHLC aggregates go back further; deep raw history is via S3 export. See the matrix. - **Note:** deep historical Solana *instructions by signature* are not available — consume them 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/Kafka/gRPC rather than webhooks. **[confirm your delivery needs]** ## 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) --- ## 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. - **`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) on a free account. 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/ NFTs Tracking Across Chains: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. See examples in the Bitquery IDE. # NFTs Tracking Across Chains :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: Effortlessly check NFTs across different chains. [You can run the query here](https://ide.bitquery.io/multi-chain-NFT-updates) By using GraphQL Aliasing and Fragments to combine queries for multiple blockchains in a single API call we simplify complex data aggregation across various chains for more organized handling. In this query below we can NFT balances for the address `0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03` across multiple chains. Replace it with a wallet address whose NFT balance you need. ```graphql query MyQuery { binance: EVM(network: bsc, dataset: archive) { BalanceUpdates( limit: {count: 10} orderBy: {descending: BalanceUpdate_Amount} where: {BalanceUpdate: {Address: {is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03"}}, Currency: {Fungible: false}} ) { Currency { Fungible Symbol SmartContract Name HasURI Delegated Decimals } BalanceUpdate { Id Amount Address URI } } } eth: EVM(network: eth, dataset: archive) { BalanceUpdates( limit: {count: 10} orderBy: {descending: BalanceUpdate_Amount} where: {BalanceUpdate: {Address: {is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03"}}, Currency: {Fungible: false}} ) { Currency { Fungible Symbol SmartContract Name HasURI Delegated Decimals } BalanceUpdate { Id Amount Address URI } } } arbitrum: EVM(network: arbitrum, dataset: archive) { BalanceUpdates( limit: {count: 10} orderBy: {descending: BalanceUpdate_Amount} where: {BalanceUpdate: {Address: {is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03"}}, Currency: {Fungible: false}} ) { Currency { Fungible Symbol SmartContract Name HasURI Delegated Decimals } BalanceUpdate { Id Amount Address URI } } } optimism: EVM(network: optimism, dataset: archive) { BalanceUpdates( limit: {count: 10} orderBy: {descending: BalanceUpdate_Amount} where: {BalanceUpdate: {Address: {is: "0xaba7161a7fb69c88e16ed9f455ce62b791ee4d03"}}, Currency: {Fungible: false}} ) { Currency { Fungible Symbol SmartContract Name HasURI Delegated Decimals } BalanceUpdate { Id Amount Address URI } } } } ``` --- ## 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 In this guide, we will see how to get OHLCV (Open, High, Low, Close, Volume) candlestick data—or 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 guide 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)` 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 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: combined) { DEXTradeByTokens( orderBy: { descendingByField: "Block_Timefield" } where: { 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: combined) { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {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/) --- ## Optimism API Documentation URL: https://docs.bitquery.io/docs/blockchain/Optimism/ Optimism API Documentation: query and stream Optimism on-chain data with Bitquery GraphQL examples for developers. Keep queries fast with indexed filters. # 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 **9 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 :::caution Deprecated APIs On EVM, **`BalanceUpdates`** and **`TokenHolders`** were deprecated as of **20 May 2026** and removed on **15 June 2026**. Use **`EVM.Balances`** (this page) and **[Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api)** (`EVM.Holders`) instead. ::: 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 Uniswap v3, which carries most of the swaps, Uniswap v4, the `aerodrome_v1` family, which on Optimism holds pools and vaults built on the Velodrome and Aerodrome code base, Tarot's vaults among them, 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) - [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) on a free account. ## 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) on a free account. ## 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) on a free account. 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 :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: 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 (roughly last ~8 hours) 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) { BalanceUpdates(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. **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```graphql { EVM(network: bsc, dataset: combined) { Balances( limit: { count: 1000 } orderBy: { descending: Balance_Amount } where: { Currency: { SmartContract: { is: "0xc748673057861a797275cd8a068abb95a902e8de" } } } ) { Balance { Address } Balance { Amount } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql { EVM(network: bsc, dataset: combined) { BalanceUpdates( limit: { count: 1000 } orderBy: { descendingByField: "balance" } where: { Currency: { SmartContract: { is: "0xc748673057861a797275cd8a068abb95a902e8de" } } } ) { BalanceUpdate { Address } balance: sum(of: BalanceUpdate_Amount) } } } ```
In the above example, we use the SUM metric to sort the responses. We give an [alias](/docs/graphql/metrics/alias/) to the sum field (Balance) and sort the responses from highest to lowest sum. ### 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/ Solana Orca DEX API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 **9 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: {is: "initializePool"}, 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: {is: "collectFees"}}}} ) { 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: {is: "collectReward"}}}} ) { 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) | 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 Documentation: query and stream Polygon on-chain data with Bitquery GraphQL examples for developers. # 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 **9 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 :::caution Deprecated APIs On EVM, **`BalanceUpdates`** and **`TokenHolders`** were deprecated as of **20 May 2026** and removed on **15 June 2026**. Use **`EVM.Balances`** (this page) and **[Token Holders API](/docs/blockchain/Ethereum/token-holders/token-holder-api)** (`EVM.Holders`) instead. 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 9 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 **9 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 9 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 Matic Uniswap API: query Polygon Uniswap trades, pools, and prices with Bitquery GraphQL DEX APIs. Copy GraphQL snippets for production apps. # Matic Uniswap API This section provides you with a set of queries that provides an insight about the Uniswap DEX on MATIC. ## 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"}, Protocol: {is: "uniswap_v3"}}}} ) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Trader { Address } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` ## Get Latest Trades on Uniswap v3 Below query will subscribe you to the latest DEX Trades on MATIC Uniswap v3. Try out the API [here](https://ide.bitquery.io/uniswap-v3-trades-matic) ```graphql query MyQuery { EVM(dataset: realtime, network: matic) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} 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 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-on-uniswapv3-matic). ```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: "uniswap_v3"}}}} ) { Trade { Dex { OwnerAddress ProtocolFamily ProtocolName } 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) } } } { "network": "matic", "token": "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270" } ``` ## OHLC in USD of a Token This query retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on Uniswap v3 over a defined time period and interval. You can try out the API [here](https://ide.bitquery.io/OHLCV-on-MATIC-uniswap-v3#) on Bitquery IDE. ```graphql { EVM(network: bsc, dataset: realtime) { DEXTradeByTokens( orderBy: {descendingByField: "Block_testfield"} where: {Trade: {Currency: {SmartContract: {is: "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270"}}, PriceAsymmetry: {lt: 0.1}, Dex: {ProtocolName: {is: "uniswap_v3"}}, 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: Price(maximum: Trade_Price) low: Price(minimum: Trade_Price) open: Price(minimum: Block_Number) close: Price(maximum: Block_Number) } count } } } ``` ## 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 `0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270`. Try out the API [here](https://ide.bitquery.io/trade_volume_matic_uniswapv3). ```graphql query MyQuery { EVM(network: matic) { DEXTradeByTokens( where: {Trade: {Currency: {SmartContract: {is: "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270"}}}, TransactionStatus: {Success: true}, Block: {Time: {since: "2025-02-12T00:00:00Z"}}} ) { 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 will fetch you the top bought tokens on uniswap v3. Try out the query [here](https://ide.bitquery.io/top-bought-tokens-on-matic-uniswap-v3_4). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "buy"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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": "matic" } ``` ## Get top sold tokens on uniswap v3 This query will fetch you the top bought tokens on uniswap v3. Try out the query [here](https://ide.bitquery.io/top-sold-tokens-on-matic-uniswap-v3). ```graphql query timeDiagram($network: evm_network) { EVM(network: $network) { DEXTradeByTokens( orderBy: {descendingByField: "sell"} limit: {count: 100} where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v3"}}}} ) { Trade { Currency { Symbol Name SmartContract } Dex{ ProtocolName } } 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": "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) on a free account. ## 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 **9 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 & Tech Markets API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 ultra-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 API - Advanced Analytics: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 7 days** of data. Use it together with the [Polymarket API](/docs/examples/polymarket-api/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 Confirm **USDC.e**, **Conditional Tokens**, and **exchange** addresses on Polygon from [Polymarket](https://polymarket.com/) or block explorers before production use; upgradeable deployments can change over time. ::: :::note Dataset: `realtime` and retention Polymarket prediction-market data on Polygon (**`PredictionTrades`**, **`PredictionSettlements`**, and related examples on this page) must use **`dataset: realtime`**. This dataset holds roughly the **last 7 days**—use time filters that fall inside that window. ::: --- ## Overview | Topic | API | What you get | | ------------------------------------ | --------------------------------- | ------------------------------------------------------------------------------------- | | **TVL Polymarket** | `TransactionBalances` | Latest **USDC.e** balance 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 **USDC.e** (`0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174`) held by **Conditional Tokens** and **neg-risk wrapped collateral** contracts. Extend the `Address` list if you track additional custodians. [Run in Bitquery IDE](https://ide.bitquery.io/Polymarket-TVL) ```graphql query PolymarketUSDCBalancesTVL { EVM(dataset: realtime, network: matic) { TransactionBalances( where: { TokenBalance: { Address: { in: [ "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045" "0x3A3BD7bb9528E159577F7C2e685CC81A765002E2" ] } Currency: { SmartContract: { is: "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-03-20", "PolymarketContractAddresses": [ "0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e", "0xc5d563a36ae78145c45a50134d48a1215220f80a" ] } ``` --- ## 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/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 Guide - Data & Query Reference URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-api/ Which Polymarket API to use for each job: trades and prices, positions and redemptions, market lifecycle, wallet activity and real-time streams. # Polymarket API Guide - Data & Query Reference The Bitquery Polymarket API provides prediction market data on Polygon via GraphQL. Use **`dataset: realtime`** on `EVM` queries for **`PredictionTrades`**, **`PredictionSettlements`**, and related prediction-market APIs—this dataset retains roughly the **last 7 days**. Use it to query trades, settlements, market metadata, and volume; filter by condition_id, outcome token, or trade size; and access data via REST, WebSocket subscriptions, or Kafka streams. Filter by Polymarket using `ProtocolName: "polymarket"` or `Marketplace.ProtocolName` in your queries. 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 Polymarket prediction-market data on Polygon requires **`dataset: realtime`** (~**7 days** of rolling history). Add `dataset: realtime` to the `EVM(...)` argument in your GraphQL examples when using prediction trades and settlements. ::: --- ## 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 ultra-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 } } } ``` --- ## Support For questions and technical support: - [Bitquery Telegram](https://t.me/bloxy_info) --- ## Polymarket API Vs Bitquery Polymarket URL: https://docs.bitquery.io/docs/API-Blog/polymarket-api-vs-bitquery-polymarket-api/ Polymarket API Vs Bitquery Polymarket: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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. ## 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 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/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 first-class. 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 7 days**. For longer windows, a **full historical dataset is available via [Bitquery Cloud](/docs/cloud/) on request**, 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/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 | Purpose-built: [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 / USDC custody balances** | Not exposed | Yes, via TransactionBalances on Conditional Tokens + neg-risk collateral | | **Historical depth** | Full CLOB history | realtime dataset ~last 7 days; full historical dataset available via [Bitquery Cloud](/docs/cloud/) on request | | **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/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. ## Bottom line The two APIs are not rivals; they answer different questions. 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-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/) - [DexRabbit Polymarket Predictions dashboard](https://dexrabbit.bitquery.io/polymarket-predictions) --- ## Polymarket Bitcoin Up or Down API & Websocket URL: https://docs.bitquery.io/docs/examples/polymarket-api/bitcoin-polymarket-api/ Polymarket Bitcoin Up or Down API & Websocket: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 **ultra-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/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 API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Built for traders and analytics teams. # 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/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 **ultra-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 Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/polymarket/ Polymarket Data - Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Polymarket Data Bitquery provides **Polymarket data dumps** in **Parquet format**, 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**. Polymarket runs on **Polygon (Matic)**, so all Polymarket datasets live under the `matic/` prefix. ## 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** – Market resolution events such as 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 how a market resolves 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. ## Real-Time vs Batch Data Access Cloud data dumps are optimized 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** --- ## Polymarket Insider & Fresh-Wallet Detection API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-insider-detection-api/ Polymarket Insider & Fresh-Wallet Detection API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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`). [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/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 Markets API URL: https://docs.bitquery.io/docs/examples/polymarket-api/polymarket-markets-api/ Polymarket Markets API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Keep queries fast with indexed filters. # Markets API Find markets on Polymarket using various filters, including **market slug**, **event slug**, **condition ID**, and **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/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/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 API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Run it in the IDE, then ship in your app. # 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 **ultra-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/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 — 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 typically need to either run your own Polygon archive node, index trades from the Conditional Tokens Framework (CTF), and resolve market metadata yourself — or you 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 — 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 — same shape, three different 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 — 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 — no additional rendering hop needed. ## 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** — not 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 — just ensure 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 The same Bitquery primitives unlock plenty of adjacent products on top of Polymarket: - **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 & User Activity API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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/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—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/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 Wallet Realized PnL & Win Rate (Pattern): Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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!, $title: String!, $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/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/) | --- ## Pons Launchpad API on Robinhood Chain: Launches and Trades 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: Launches and Trades **[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. 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) on a free account. Live data and the last month of `Trading` cube history are on every plan; history back to the first V2 launch sits on the `archive` dataset, which the trial includes and paid plans add through the Robinhood archive add-on (see [Historical Pons data](#historical-data)). ## Video Tutorial | Pons Launchpad API on Robinhood Chain - Track Launches, Trades & Graduations ## 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 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 leg — from the launch config, not 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, including the trial. - **`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 includes complete history. 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 reaches back further than decoded event names (Calls archive retention is planned to cap at roughly 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 } } } } ``` `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 } } } } ``` ### 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` coverage starts **2026-08-12** (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 legs** (`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 } } } } } } ``` 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 leg (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 } } } } } } ``` 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 } } } } ``` ```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 } } } } } ``` :::note Legs 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 trade leg** — no deduplication is needed. No dedup pass is needed before summing volume. One user swap can still fan out into several routed legs across different quote pairs in the same transaction, so summing every leg 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 — value the pool from the quote leg. ### 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). --- ## 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 } } } } ``` ```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 } } } } } } ``` ```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 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 --- ## 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. :::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 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 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 --- ## Prediction Market API URL: https://docs.bitquery.io/docs/examples/prediction-market/prediction-market-api/ Prediction Market API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Covers archive history and realtime data. # 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:** Currently **Polygon** (`network: matic`). 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/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 Managements API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 API: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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/ Price Index Algorithm via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. See examples in the Bitquery IDE. # Price Index Algorithm This page describes how the Price Index (Crypto Price API) filters trades and computes prices for tokens and currencies. It is the single source of truth for the algorithm in effect from **April 2026**. ## Which Trades Are Filtered Out A trade is **excluded** from price and volume calculations only if: 1. **Zero amount**: The trade amount is 0. 2. **Below decimal precision**: The trade amount is so small that it would be lost to precision. For a token with `D` decimal places, trades with amount less than `10^D / 10,000` are excluded. **Example**: USDT has 9 decimals. So `10^9 / 10,000 = 100,000` in the smallest units, i.e. **0.00001 USDT**. Any trade smaller than 0.00001 USDT is not accounted for, to avoid precision loss. In other words: a trade must have at least 10,000 units of decimal precision (e.g. for 9 decimals, at least 0.00001 of the token). ## Time Window and Volume Weighting Price and volume aggregation use a **1-hour rolling** window. Each trade (or price entry) contributes to volume weighting with a factor **`exp(-decayRate × age)`**, where **age** is how far back in time the entry lies within that window (0 at the newest edge, increasing toward the older edge). That gives **exponential decay** toward older data: the **most recent** entries contribute **~100%** of their raw volume, while an entry at the **midpoint** of the window contributes **50%** of its volume (**50% exponential average** profile relative to the window). Volume weight decays from the newest edge of the 1-hour window toward older trades Aggregations (pool, token, and **non-stablecoin** currency) use these **decayed** volume contributions instead of raw sums over the window. Trade filtering, exponential decay within the 1-hour window, and effective volume per market ## How Token Prices Are Determined Token prices are determined by **volume-weighted aggregation** over eligible trades in the **last hour**, using decayed volumes as above. ### Step 1: Identify pairs where the token is base We determine in which pairs the token acts as the **base** currency. A token can be quote in one pair (e.g. PUMP/WSOL) and base in another (e.g. WSOL/USDT); for token price we only use pairs where the token is **base**. ### Step 2: Aggregate from pools to token price For each such pair we use the markets (DEX pools) where it is traded. Conceptually, for pools that trade the same logical pair, the combined price uses **volume-weighted** pooling with **decayed** base-token volumes over the 1-hour window: ``` price(USD) = sum( price(p) × effectiveVolume(p) ) / sum( effectiveVolume(p) ) ``` Where: - **price(p)** = latest price of a trade in pool `p` (in USD; see [How Pool Prices Are Normalized to the Current Quote Token](#how-pool-prices-are-normalized-to-the-current-quote-token) below). - **effectiveVolume(p)** = sum of **base-token** amounts for trades in pool `p` in the window, each multiplied by **`exp(-decayRate × age)`** for that trade. The **token** price is then the same style of **volume-weighted** combination across all pairs where the token is base, again using decayed volumes. Multi-market aggregation to token price, market sort, volume-weighted blend, and API ranking ## How Currency Prices Are Determined The same rules apply for **non-stablecoin** currencies: a **1-hour** window, **exponentially decayed** volume weights (50% at the midpoint), and aggregation over **tokens** (volume and prices of each token representation) instead of over pairs and pools. Currency price is the volume-weighted combination of its token representations (e.g. WBTC, cbBTC, etc.) across chains. **Stablecoins** are **not** included in this trade-based currency path. Processing skips them in the currency aggregation loop that builds prices from DEX trades; stablecoin USD (or peg) prices come from a **separate pipeline** fed by an **external** spot source, **not** from decay-weighted DEX trade aggregation. **Ranking** is **not** exposed on currency-level responses. Internal logic may still derive token→currency weights while computing prices, but only **pair** and **token** updates are given a **`Ranking`** on the outbound message—do not look for **`Ranking`** on currency entities in the API. ## Ranking on Trades, Pairs, and Tokens The API for **Trades**, **Pairs**, and **Tokens** exposes a **Ranking** object with two fields. It does **not** appear on **currencies** (see [How Currency Prices Are Determined](#how-currency-prices-are-determined)): | Field | Meaning | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Position** | **1-based** index describing **priority** when multiple sources contribute: order of the **pair** in **token price**, or of the **token** among representations that feed a **non-stablecoin** currency blend. Lower number means higher priority in that ordering. | | **Weight** | Float in **`[0, 1]`** — this pool's share of the total decay-weighted volume at the current moment. Reflects how much this pool drives the blended token price. Weights across all contributing pools for a given token sum to 1. | Use **Position** for display order or precedence; use **Weight** for how much each contributor matters in the blended price. :::tip Practical use: pricing a token from its top market Filtering **`Pairs`** to **`Ranking: { Position: { eq: 1 } }`** gives you a token's price on the single market contributing the most decay-weighted volume, instead of the blend across all of its pools. This is the recommended way to price a specific token — see [Getting the Most Accurate Token Price](/docs/trading/crypto-price-api/pairs#most-accurate-token-price) for queries, streaming, and caveats. ::: ### Example: filter by ranking position Filter pairs in **`where`** using **`Ranking.Position`** when you only want rows that are among the top contributors to the token price (for example positions **1**, **2**, and **3**). Request **`Ranking { Position Weight }`** on each pair to see both the rank and that pair’s **relative weight** in the blend. **`Weight`** is normally used as a returned field rather than as a filter. ```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 } } } } } ``` ## Volume and Amounts: Quote Token Amounts vs USD When pricing is in USD (USD-base): - **GraphQL** `Volume { Quote }` and **Protobuf** `Amounts.Quote` = **sum of quote token amounts** (e.g. sum of USDT, USDC, etc. amounts), **not** sum of USD. - For **USD amounts** use **`Volume { Usd }`** (GraphQL) and **`Amounts.Usd`** (Protobuf) as before. So for USD-based pricing, use `Volume.Usd` / `Amounts.Usd` when you need USD totals; use `Volume.Quote` / `Amounts.Quote` when you need the total in quote token units. ## How Pool Prices Are Normalized to the Current Quote Token The **latest price of a trade in a pool** is not taken at the time that trade happened. It is **normalized** using the **current** price of the quote token at the time when the weighting is performed. So the quote side of the price is evaluated at weighting time, not at the time of the last trade in the pool. This keeps aggregated prices consistent with current quote token (e.g. stablecoin) valuation. --- ## 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` (or `/eap` for Solana) 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 Documentation: Trades, Prices, OHLCV, Launches URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/ Pump.fun has no hosted API. Query Pump.fun trades, launches, prices, OHLCV, bonding curves and graduations on Solana over GraphQL, WebSocket, gRPC and Kafka. # Pump.fun API Documentation: Trades, Prices, OHLCV, Launches Pump.fun 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. This page is the query reference for the Bitquery Pump.fun API, which reads that activity from the 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`. Every query runs as written in the [Bitquery IDE](https://ide.bitquery.io) with a free trial token. Delivery options, latency and pricing are on the [Pump.fun API product 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 **9 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. ::: For data points not covered here, ask [support](https://t.me/Bloxy_info). :::tip **Try Our PumpFun Token Sniffer** Want to analyze Pump.fun tokens for potential phishing risks? 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/) - [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 Pump.fun tokens](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, token creation, and bonding curve data by this program ID. ``` 6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P ``` Use this program ID when filtering Solana instructions or token supply updates for Pump.fun tokens. 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" } }`. Tokens 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`). Bonding-curve tokens trade for hours, not months, so the examples on this page that need a market that will still exist 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? Use Bitquery's `TokenSupplyUpdates` subscription filtered by the Pump.fun program `create` or `create_v2` method to get metadata, supply, and dev address of newly created tokens in real time. [Try New Pump.fun Tokens Query ➤](https://ide.bitquery.io/newly-created-PF-token-dev-address-metadata_8)
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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 token creation events with mint address, bonding curve, metadata, creator, name, symbol, and URI. [Track Pump.fun token launches in realtime — Stream ➤](https://ide.bitquery.io/Track-new-token-launches-on-Pump-Fun-in-realtime0_7)
Click to expand GraphQL query ```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? [All Pump.fun tokens created by an address — Query ➤](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? Check out our [Money Flow API](https://docs.bitquery.io/v1/docs/Examples/coinpath/money-flow-api#funding-history-of-address) to track fund movements and understand creator behavior. :::
Click to expand GraphQL query ```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 Pump.fun tokens created by a specific wallet 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 tokens created by a wallet), use the dedicated count query below. - **[Run query: list tokens created by wallet](https://ide.bitquery.io/Pumpfun-tokens-created-by-a-wallet-historical#)** - **[Run query: count of tokens created by wallet](https://ide.bitquery.io/Count-of-Pumpfun-tokens-created-by-a-wallet-historical#)**
Click to expand GraphQL query ```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? Now you can track the newly created Pump.fun Tokens along with their dev address, metadata and supply. `PostBalance` will give you the current supply for the token. [Newly created Pump.fun tokens with dev, metadata — Stream ➤](https://ide.bitquery.io/newly-created-PF-token-dev-address-metadata_9)
Click to expand GraphQL query ```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. If you need to check for a old pump.fun token if it was created with Mayhem mode `true` or `false` then 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? Track Pump.fun tokens created in real time with Mayhem mode enabled. This API lets you monitor all new tokens launched with Mayhem set to true. Try the API [here](https://ide.bitquery.io/Track-Mayhem-Mode-enabled-Pumpfun-Tokens-in-realtime).
Click to expand GraphQL query ```graphql subscription MyQuery { Solana { Instructions( where: {Instruction: {Program: {Address: {is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"}, Method: {in: ["create", "create_v2"]}, Arguments: {includes: {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 of a Pump Fun Token — Query ➤](https://ide.bitquery.io/check-mayhem-mode-of-a-pump-fun-token_1)
Click to expand GraphQL query ```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 utilize 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)
Click to expand GraphQL query ```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 Pump.fun token prices. The example token is PUMP on PumpSwap; for a token still on the bonding curve, filter `Market.Program` to `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` instead. PumpFun Token prices against SOL Stream [Pump.fun token latest price in USD — Query ➤](https://ide.bitquery.io/solana-token-price-using-price-api)
Click to expand GraphQL query ```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 Pump.fun token price in real time — Stream ➤](https://ide.bitquery.io/Price-of-a-pump-fun-token-using-price-index-in-usd)
Click to expand GraphQL query ```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? Use the below query to get top 10 Pump.fun tokens by price change in the last 5 minutes. Test the query [here](https://ide.bitquery.io/Top-10-pump-fun-tokens-by-Price-change-in-last-5min_1).
Click to expand GraphQL query ```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 `dataset: combined`, some fields like `Trade_Side` may be limited. [OHLC for a token on Pump.fun — Query ➤](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 :::
Click to expand GraphQL query ```graphql { Solana(dataset: combined) { 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: combined`, `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 — Pump.fun Query ➤](https://ide.bitquery.io/ATH-Market-Cap-of-Pump-Fun-Tokens-in-a-Specific-Timeframe)
Click to expand GraphQL query ```graphql { Solana(dataset: combined) { 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 [Pump.fun token price change over time — Query ➤](https://ide.bitquery.io/price-change-over-x-minutes)
Click to expand GraphQL query ```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)** and [starter PnL queries](/docs/start/starter-queries/)). 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 ➤](https://ide.bitquery.io/Pumpfun-DEX-Trades-stream)
Click to expand GraphQL query ```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 a Pump.fun token — Query ➤](https://ide.bitquery.io/get-latest-trades-of-a-pump-fun-token_6)
Click to expand GraphQL query ```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 of a Pump.fun token — Query ➤](https://ide.bitquery.io/trade-volume-7-days)
Click to expand GraphQL query ```graphql query MyQuery { Solana(dataset: combined) { 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 for any token — Query ➤](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 get all tokens traded on Pump.fun in the last 1 hour, use a query that filters trades by the Pump.fun protocol and a block time within the past hour. 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: [All Pumpfun Tokens traded in last 1 hour — Query ➤](https://ide.bitquery.io/all-tokens-traded-on-Pumpfun-in-the-last-1-hour_1)
Click to expand GraphQL query ```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 tokens on Pump.fun that have reached a specific market capitalization threshold, you can use the following Bitquery GraphQL example. This query 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. [View Pump.fun tokens that reached a specific market cap — Query ➤](https://ide.bitquery.io/How-do-I-get-tokens-that-reached-a-specific-market-cap-on-Pumpfun)
Click to expand GraphQL query ```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. [Pump.fun token detailed trade stats — Query ➤](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair_10)
Click to expand GraphQL query ```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? Get wallet addresses of the first 100 accounts that bought a token. DEXTrades on Solana keeps only the recent window, so use a token launched within it. [First 100 buyers of a Pump.fun token — Query ➤](https://ide.bitquery.io/get-first-100-buyers-of-a-token_1)
Click to expand GraphQL query ```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 above query to evaluate holdings [Holdings of first 100 buyers — Pump.fun Query ➤](https://ide.bitquery.io/balance-of-a-specific-token-at-the-specific-account-address)
Click to expand GraphQL query ```graphql query MyQuery { Solana { BalanceUpdates( where: { BalanceUpdate: { Account: { Token: { Owner: { in: [ "ApRJBQEKfmcrViQkH94BkzRFUGWtA8uC71DXu6USdd3n" "9nG4zw1jVJFpEtSLmbGQpTnpG2TiKfLXWkkTyyRvxTt6" ] } } } Currency: { MintAddress: { is: "token mint address" } } } } ) { BalanceUpdate { Account { Token { Owner } } balance: PostBalance(maximum: Block_Slot) } } } } ```
## 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 of a Pump.fun token — Query ➤](https://ide.bitquery.io/get-all-the-trading-pairs-of-a-specific-token)
Click to expand GraphQL query ```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? Gets pool token balances for liquidity estimation across multiple known pool accounts [Pump.fun pools and token balances — Query ➤](https://ide.bitquery.io/Get-Liquidity-of-Pumpfun-Pools)
Click to expand GraphQL query ```graphql { Solana { BalanceUpdates( where: { BalanceUpdate: { Currency: { Native: false } PostBalance: { gt: "0" } Account: { Owner: { in: [ "7jVYY8nUjbt5gzLt3tZJaHD9NSMyaTuvPhJLfazmjjyy" "7iDwUGUDLccKdWN5hUppoqxLeUMjw7BieQAFdTwj3F5V" ] } } } } # add pool address here limit: { count: 10 } orderBy: { descending: Block_Time } ) { BalanceUpdate { Account { Token { Owner } Owner Address } Currency { MintAddress Native } Liquidity: PostBalance(maximum: Block_Slot) } } } } ```
### 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 — Pump.fun Query ➤](https://ide.bitquery.io/mcap-liquidity-bonding-curve-volume-supply-of-a-token-in-time-frame_1)
Click to expand GraphQL query ```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 token transitions to PumpSwap. DEXPools keeps only the recent window, so the token must have graduated within it; drop the `Market` filter to list every recent graduation. [Last Pump.fun trade before PumpSwap — Query ➤](https://ide.bitquery.io/pump-fun-token-graduating-to-pumpswap)
Click to expand GraphQL query ```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 token holdings [Developer holdings of a Pump.fun token — Query ➤](https://ide.bitquery.io/trading-volume-of-a-token-pump-fun)
Click to expand GraphQL query ```graphql query MyQuery($dev: String, $token: String) { Solana { BalanceUpdates( where: { BalanceUpdate: { Account: { Owner: { is: $dev } } Currency: { MintAddress: { is: $token } } } } ) { BalanceUpdate { balance: PostBalance(maximum: Block_Slot) } } } } ``` ```json { "dev": "8oTWME5BPpudMksqEKfn562pGobrtnEpNsG66hBBgx92", "token": "token mint address" } ```
### How do I get top 10 token holders of a Pump.fun token? Returns wallet addresses and holdings of top 10 token holders [Top 10 holders of a Pump.fun token — Query ➤](https://ide.bitquery.io/top-token-holders-for-a-pump-fun-token)
Click to expand GraphQL query ```graphql query MyQuery { Solana(dataset: realtime) { BalanceUpdates( limit: { count: 10 } orderBy: { descendingByField: "BalanceUpdate_Holding_maximum" } where: { BalanceUpdate: { Currency: { MintAddress: { is: "token mint address" } } } Transaction: { Result: { Success: true } } } ) { BalanceUpdate { Currency { Name MintAddress Symbol } Account { Address } Holding: PostBalance(maximum: Block_Slot) } } } } ```
### 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 of a Pump.fun token — Query ➤](https://ide.bitquery.io/top-traders-of-a-pump-fun-token_2)
Click to expand GraphQL query ```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 Pump.fun token creators — Query ➤](https://ide.bitquery.io/Top-pump-fun-token-creators_2) :::tip Want to dive deeper into a creator's background? Use our [Money Flow API](https://docs.bitquery.io/v1/docs/Examples/coinpath/money-flow-api#funding-history-of-address) to analyze funding history and trace the source of funds for any Pump.fun creator. :::
Click to expand GraphQL query ```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 elaborative API approach uses two queries to detect if a Pump.fun 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. Pick a token launched within the recent window, since the Transfers and DEXTrades cubes on Solana keep no archive. 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 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-pump-fun-token_1#)
Click to expand GraphQL query ```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#)
Click to expand GraphQL query ```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 ## 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 Pump.fun tokens by market cap — Query ➤](https://ide.bitquery.io/top-pump-fun-tokens-by-marketcap)
Click to expand GraphQL query ```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. [Pump.fun tokens above 10K market cap — Stream ➤](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 } } } } ```
### 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. [Pump.fun “King of the Hill” tokens — Stream ➤](https://ide.bitquery.io/realtime-stream-of-King-of-the-Hill-Pumpfun-tokens-30K35K-market-cap#)
Click to expand GraphQL 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).
Click to expand GraphQL query ```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).
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: "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. Filter **`Instruction.Program.Method: "collect_creator_fee"`** and **`Instruction.Program.Address: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"`** to get balance updates showing who collected, how much, and from which token. You can run this query [in the Bitquery IDE](https://ide.bitquery.io/latest-creator-fees-pumpfun#).
Click to expand GraphQL query ```graphql { Solana(network: solana) { InstructionBalanceUpdates( limit: {count: 10} orderBy: {descending: Block_Time} where: {Instruction: {Program: {Method: {is: "collect_creator_fee"}, 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 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 ### 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 with `dataset: combined`, avoid `Trade_Side`, `Trade_Side_Type`, and similar realtime-only fields. --- ## Pump.fun Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/pumpfun/ Pump.fun Data - Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Pump.fun Data Bitquery provides **Pump.fun data dumps** in **Parquet format**, 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)** - **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 ```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_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/`, partitioned by slot range, `_.parquet`: ``` 415261250_415261499.parquet ``` - **OHLCV** – `Pumpfun_Sample/ohlcv/`, one file per token, named by the token mint address, `.parquet`: ``` 2ra5idczuCQhDe1U5D52G8Rms6hzHuHeTqP51fdHpump.parquet ``` ## Real-Time vs Batch Data Access Cloud data dumps 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/) - **GraphQL subscriptions** --- ## 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 **9 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 fully exhaustive Pump.fun API documentation is available [here](/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 **9 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 You can find more details about the Solana Shred Streams provided by Bitquery [here](/docs/streams/protobuf/chains/Solana-protobuf/) and Python code examples [here](/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. --- ## PumpFun API Documentation URL: https://docs.bitquery.io/docs/blockchain/Solana/Pumpfun/ Index of Bitquery's Pump.fun APIs on Solana — pick the right page for trades, bonding curve and market cap, PumpSwap, or migration tracking. # PumpFun API Documentation :::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 **9 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/) | 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). In this section, we will see how to fetch PumpFun-related data via **Bitquery APIs** and **Streams**. 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 is the PumpFun API? 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, etc. - **Token Liquidity** - **Token Price Change** - **Historical Data for Aggregated Metrics** ## What are the capabilities of the Bitquery PumpFun API? 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—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 ## 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; 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**. ## 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/). ## PumpFun APIs - [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/) ## 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 --- ## 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 **9 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 8 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/ Quick Start Examples via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. See examples in the Bitquery IDE. # Quick Start Examples ## Most Accurate Price for a Token (Top Market, Rank 1) {#most-accurate-price-for-a-token} The recommended way to price a **specific token**: query the `Pairs` cube with `Ranking: { Position: { eq: 1 } }` to get the price from the token's **top market** — the pool currently carrying the most volume for it — instead of a value blended across every pool it trades in. Thin, fragmented pools therefore cannot pull the number away from the market 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 }` in the filter — every market also publishes rows priced in **quote token units**, so without it a WBTC/WSOL market would return the price of WBTC in SOL rather than in dollars. `Ranking.Weight` tells you how concentrated the token's liquidity is: near 1 means a single pool drives the price; a low value means it is fragmented across many pools — the case where this query differs most from the blended `Tokens` price. Change `query` to `subscription` and drop `limit`/`orderBy` to stream it live. ## Real-Time Token Prices in USD on Solana Stream live OHLC (Open, High, Low, Close) price and volume data for all tokens on Solana, quoted directly in USD. Useful for dashboards, analytics, or bots that need stable fiat-based prices. Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them denominated in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/Real-Time-USD-price-on-solana-chain_2) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } } ``` ## Real-Time Token Prices in Quote Pair (USDC, USDT, etc.) Stream live OHLC prices for Solana tokens denominated in their trading pair token (e.g., USDC, USDT, or another crypto), instead of direct USD. Great for analyzing token behavior relative to stablecoins or other assets. Here we have selected the filter `Price: {IsQuotedInUsd: false}`, this means that any price values such as OHLC or Average indicators will be in quote currency. If you want them denominated in USD, change the filter to `Price: {IsQuotedInUsd: true}`. [Run Stream ➤](https://ide.bitquery.io/Real-Time-usd-price-on-solana-chain-in-paired-token) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 Stream real-time OHLC and volume data for Solana tokens specifically paired against SOL or WSOL. Useful when building apps or bots that want token values expressed relative to Solana’s native currency. Here we have selected the filter `Price: {IsQuotedInUsd: false}`, this means that any price values such as OHLC or Average indicators will be in quote currency. If you want them denominated in USD, change the filter to `Price: {IsQuotedInUsd: true}`. [Run Stream ➤](https://ide.bitquery.io/Real-Time-usd-price-on-solana-against-WSOLSOL) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 & Price, Last 24h) Get a snapshot of tokens with aggregated USD volume and average price over the last 24 hours. The query uses `limitBy: { count: 1, by: Token_Id }` to return one row per token, and conditional metrics (`Volume.Usd(if: ...)`, `Price.Average.Mean(..., if: ...)`) to show volume and price for the last 1h, 4h, and 24h. Useful for dashboards, top-movers lists, or comparing short-term vs daily metrics. > The `Tokens` cube is the right choice here: volume is summed across all of a token's pools. Note that its prices are blended across those pools too — to price one specific token from its top market instead, use [Pairs with rank 1](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). [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}}}} ) { Token { Address Id IsNative Name Network Name Symbol TokenId } 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 MarketCap FullyDilutedValuationUsd } } } } ``` ## OHLC of a currency on multiple blockchains This query retrieves the OHLC (Open, High, Low, Close) prices of a currency(in this eg Bitcoin; it will include all sorts of currencies whose underlying asset is Bitcoin like cbBTC, WBTC, etc) across all supported blockchains, aggregated into a given time interval (e.g., 60 seconds in this example). [Run Stream ➤](https://ide.bitquery.io/OHLC-of-a-currency-on-multiple-blockchains) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 Mention the chain/network using the `Token: {Network}` filter. Available values: `Ethereum`, `Solana`, `Base`, `Optimism`, `Opbnb`, `Matic`, `Arbitrum`, `Binance Smart Chain`, `Tron`. The available duration intervals are listed [here](/docs/trading/crypto-price-api/#understanding-intervals). In Tokens cube, only `IsQuotedInUsd:true` is supported so you will see OHLC and Price values in USD only. Stream real-time OHLC (Open, High, Low, Close) prices, trading volume, and moving averages for all tokens on a specific blockchain (e.g., Solana). Useful for market dashboards or monitoring live token activity on one chain. [Run Stream ➤](https://ide.bitquery.io/Aggregated-Price-of-all-tokens-in-real-time-on-one-chain) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 This subscription fetches real-time OHLC (Open, High, Low, Close) price data for a token pair across different blockchains. For **native tokens**, you only need to specify their ID (e.g., `bid:eth` for ETH). Here we have selected the filter `Price: {IsQuotedInUsd: false}`, this means that any price values such as OHLC or Average indicators will be in terms of quote currency instead of USD. If you want them in USD, change the filter to `Price: {IsQuotedInUsd: true}`. [Run Stream ➤](https://ide.bitquery.io/Token-OHLC-Stream-1-second-Multi-Chains_1) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } } ``` ## Find Price Arbitrage Opportunity of Pair Across Chains Compare token prices (e.g., BTC/USDT) across multiple markets and chains to identify arbitrage opportunities. Returns one latest price per market. Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/Find-arbitrage-opportunity-with-same-token-across-chains_1) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } ``` ## 5 Minute Price Change API Fetch the top 10 tokens by 5-minute percentage price change (USD-based), only including tokens with at least $100k trading volume. Ideal for building a "top movers" list. > Scanning every token on a chain is exactly what the `Tokens` cube is for. Once you have picked a token out of the list, price it from its top market with [Pairs + rank 1](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. This stream uses [expressions](/docs/graphql/capabilities/expression/) [Run Stream ➤](https://ide.bitquery.io/5-minute-price-change-api_2) > Note: We include `Volume: { Usd: { gt: 5 } }` in most examples to remove extreme outliers; this stream already filters by `Volume: { Usd: { gt: 100000 } }`. ```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 Stream the top 10 tokens on Solana by 5-minute price change (in USD), filtered by $100k+ volume. Updates continuously. > As above, this is a chain-wide scan. For a watchlist of specific tokens, stream their top markets instead — see [Watchlist: top-market price for several tokens](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. This stream uses [expressions](/docs/graphql/capabilities/expression/) [Run Stream ➤](https://ide.bitquery.io/5-minute-price-change-api-on-solana_6) > Note: We include `Volume: { Usd: { gt: 5 } }` in most examples to remove extreme outliers; this stream already filters by `Volume: { Usd: { gt: 100000 } }`. ```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 Calculate the percentage drawdown (price decline) for tokens of a specific currency (e.g., Bitcoin) over a 1-hour interval. This query uses [expressions](/docs/graphql/capabilities/expression/) to calculate drawdown as: `((Close - Open) / Open) * 100`. > This compares a currency's token representations against each other, so `Tokens` fits. To measure one token's drawdown on the market where it actually trades, run the same expression against [Pairs with rank 1](/docs/trading/crypto-price-api/pairs#most-accurate-token-price). > **Note:** You can use `Token: {Address: {is: "token_address"}}` filter instead of `Currency: {Id: {is: "bid:bitcoin"}}` to filter by token address. We include `Volume: { Usd: { gt: 10 } }` to filter out tokens with very low trading volume. [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) Rank Solana tokens by 5-minute price change, restricted to tokens with meaningful volume. 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). Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them denominated in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/5-minute-price-change-api-on-solana_5) > Note: We include `Volume: { Usd: { gt: 5 } }` in most examples to remove extreme outliers; this stream already filters by `Volume: { Usd: { gt: 100000 } }`. ```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") } } } ``` ## PumpAMM 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Real-time (1-second interval) price, OHLC, volume, and moving averages for Pump.fun AMM tokens on Solana. Useful for high-frequency trading bots. Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/PumpAMM-tokens-1-second-price-stream-with-OHLC_1) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Real-time (1s) stream of prices, OHLC, and volumes for tokens traded on Heaven DEX (Solana). Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/Heaven-DEX-tokens-1-second-price-stream-with-OHLC) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Real-time (1s) OHLC, price, and volume feed for Meteora DBC DEX on Solana. Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/Meteora-DBC-DEX-tokens-1-second-price-stream-with-OHLC) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } ``` ## Raydium Launchlab 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Monitor Raydium Launchlab token listings on Solana with 1-second OHLC and volume streams. Perfect for tracking new token launches. Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/Raydium-Launchpad-DEX-tokens-1-second-price-stream-with-OHLC) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders 1-second OHLC and volume stream for tokens traded on Uniswap v3 (Ethereum). Great for bot trading strategies. Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/Uniswap-v3-DEX-tokens-1-second-price-stream-with-OHLC) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Stream 1-second OHLC, price, and volume data from Sushiswap DEX (Ethereum). Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/Sushiswap-DEX-tokens-1-second-price-stream-with-OHLC) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } ``` ## PancakeSwap v3 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders 1-second OHLC and volume stream for tokens traded on PancakeSwap v3 (Ethereum). Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/PancakeSwap-v3-DEX-tokens-1-second-price-stream-with-OHLC_1) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } ``` ## FourMeme 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Track token activity (OHLC, price, volume) every 1 second on FourMeme DEX (BSC). Here we have selected the filter `Price: {IsQuotedInUsd: true}`, this means that any price values such as OHLC or Average indicators will be in USD. If you want them in quote currency, change the filter to `Price: {IsQuotedInUsd: false}`. [Run Stream ➤](https://ide.bitquery.io/FourMeme-DEX-tokens-1-second-price-stream-with-OHLC) > Note: We include `Volume: { Usd: { gt: 5 } }` to further remove extreme outliers; the stream already pre-filters outliers—this is an additional check. ```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 } } } } ``` --- ## 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 } } } } } ``` --- ## 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 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 **9 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. 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 URL: https://docs.bitquery.io/docs/blockchain/Solana/launchpad-raydium/ Raydium Launchpad API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Works with WebSocket live subscriptions. # 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 **9 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)** | < 100ms | 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 9 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**: < 100ms (ultra-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) | < 100 ms (ultra-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, archival, 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 `ethereum.dextrades`, `solana.transactions`, 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/)** - **[Solana](/docs/blockchain/Solana/)** - **[TRON](/docs/blockchain/Tron/)** - **[TON](/docs/blockchain/supported-chains/)** (limited support; see coverage matrix) ### gRPC Streams: - **[Solana](/docs/blockchain/Solana/)** (with more blockchains coming soon) ## 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) with our [starter queries](/docs/start/starter-queries/) --- 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 along with a stream that constantly provides the Balance Update 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 = sum(all_balance_updates) + stream_balance_updates ``` 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: - subscriptions, where realtime dataset is a source of the new updates - query the latest data available with minimum delay (up to the current block) 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 dumps** in **Parquet format**, 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 ``` ## Real-Time vs Batch Data Access Cloud data dumps 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 Balances API — Wallet Portfolios & History URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-balances-api/ Query Robinhood wallet balances with Bitquery GraphQL: full portfolios, multi-address batches, wallet profiling, and balance history as of any date. # Robinhood Balances API — Wallet Portfolios & History Query **wallet balances on Robinhood** with Bitquery GraphQL. The `EVM.Balances` cube returns **computed balances with built-in aggregates** — amount, USD value, first/last change time, and update count — grouped by whatever dimensions you select: one wallet's full portfolio, a batch of wallets, or network-wide per-currency totals, all in single calls that would take thousands of `eth_getBalance` / `balanceOf` RPCs. For token-centric holder rankings and counts, use the dedicated [Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/). Every query on this page 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 Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/) - [Robinhood Token Supply API](/docs/blockchain/robinhood/robinhood-token-supply/) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) - [Robinhood Trades](/docs/blockchain/robinhood/robinhood-trades/) (for prices to value non-ETH holdings) - [Robinhood Events API](/docs/blockchain/robinhood/robinhood-events-api/) ::: **On this page:** [Concepts](#datasets-grouping-and-selectwhere) · [Portfolio](#all-token-balances-of-an-address-portfolio) · [As-of-date](#balance-as-of-a-date-time-travel) · [Single token](#native-eth-and-single-token-balances) · [Multi-address](#balances-for-multiple-addresses) · [Wallet profile](#wallet-profile-first-seen-last-active-update-count) · [Currency totals](#network-wide-per-currency-totals) · [FAQ](#faq) --- ## Why query balances here instead of an RPC loop | | Node RPC (`eth_getBalance` / `balanceOf` calls) | Bitquery Balances | | --- | --- | --- | | Whole portfolio | One call **per token** you already know about | One call returns every token the wallet holds | | Token holders | Impossible without indexing all transfers yourself | One sortable query on the [Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/) | | History | Archive node + block-pinned calls | `Block.Date.till` gives the balance as of any date | | Extras | — | USD value, first/last change time, update count | --- ## Datasets, grouping, and selectWhere - Use **`dataset: combined`** — balances are computed from history, and combined guarantees the full picture. - **Grouping follows your selection.** Filter/select `Balance.Address` to get per-wallet rows; select only `Currency` to get network-wide per-currency totals; select both for wallet × token rows. - **`selectWhere` filters aggregated results** (like SQL `HAVING`): `Amount(selectWhere: { gt: "0" })` drops zero/dust rows after the balance is computed. Amount thresholds are strings. - **`AmountInUSD` is populated for native ETH; token rows generally return `0`.** USDG is a dollar stablecoin, so its `Amount` is effectively USD; value other tokens by joining prices from the [Trades API](/docs/blockchain/robinhood/robinhood-trades/). --- ## All token balances of an address (portfolio) ▶️ [Run in IDE](https://ide.bitquery.io/wallet-token-balances-robinhood-chain) Everything a wallet holds in one call. The `selectWhere` keeps only non-zero rows. ```graphql { EVM(network: robinhood, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x9c0489b89ae473de6edcb159f21c3019ba730282" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` --- ## Balance as of a date (time travel) Add `Block.Date.till` to compute the same portfolio **as of any date** — audits, tax snapshots, "what did this whale hold before the launch". A date before the wallet's first activity returns no rows. ```graphql { EVM(network: robinhood, dataset: combined) { Balances( where: { Block: { Date: { till: "2026-07-20" } } Balance: { Address: { is: "0x9c0489b89ae473de6edcb159f21c3019ba730282" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` --- ## Native ETH and single-token balances Filter `Currency.Native: true` for the ETH balance, or pin one contract for a single token — with the change-history aggregates included. ```graphql { EVM(network: robinhood, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x9c0489b89ae473de6edcb159f21c3019ba730282" } } Currency: { Native: true } } ) { Currency { Symbol Native } Balance { Amount AmountInUSD } } } } ``` ```graphql { EVM(network: robinhood, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x9c0489b89ae473de6edcb159f21c3019ba730282" } } Currency: { SmartContract: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } } } ) { Currency { Symbol SmartContract } Balance { Amount AmountInUSD FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Balances for multiple addresses Batch a watchlist with `Address.in` — one row per address (per selected currency). ```graphql { EVM(network: robinhood, dataset: combined) { Balances( where: { Balance: { Address: { in: [ "0x9c0489b89ae473de6edcb159f21c3019ba730282" "0xcaf681a66d020601342297493863e78c959e5cb2" ] } } Currency: { Native: true } } ) { Balance { Address Amount AmountInUSD } } } } ``` --- ## Token holders Holder rankings, counts, whale floors, distribution stats, and dormancy screens have a dedicated cube and page — see the **[Robinhood Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/)**. --- ## Wallet profile: first seen, last active, update count The built-in aggregates turn balances into a wallet profiler: `FirstChangeTime` (when the wallet first touched each asset), `LastChangeTime` (most recent activity), and `UpdateCount` (how many balance changes) — age, dormancy, and activity signals with no extra indexing. ```graphql { EVM(network: robinhood, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x9c0489b89ae473de6edcb159f21c3019ba730282" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Network-wide per-currency totals With no address dimension, rows group per currency: `Amount` becomes the **total held across all addresses**, with network-level change stats — the full field set of the cube on display. ```graphql { EVM(network: robinhood, dataset: combined) { Balances(limit: { count: 10 }) { Currency { Decimals Symbol SmartContract DelegatedTo Fungible HasURI Name Native ProtocolName } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- :::tip Continuous balance data via Kafka Need balance changes as a continuous feed? Bitquery delivers Robinhood token data as **Kafka streams** (protobuf topic `robinhood.tokens.proto`) with consumer-group scaling and replay. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). ::: --- ## Use-case patterns | Goal | Approach | | --- | --- | | Wallet / portfolio page | [Portfolio query](#all-token-balances-of-an-address-portfolio); poll on an interval for live UX | | Tax / audit snapshots | [Balance as of a date](#balance-as-of-a-date-time-travel) with `Block.Date.till` | | Token distribution, rich lists & whales | [Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/) rankings, counts, and balance floors | | Wallet profiling (age, dormancy) | [First/last change + update count](#wallet-profile-first-seen-last-active-update-count) | | Exchange / custody monitoring | [Multi-address batch](#balances-for-multiple-addresses) on a polling schedule | | Supply-side view | [Per-currency totals](#network-wide-per-currency-totals), or the [Token Supply API](/docs/blockchain/robinhood/robinhood-token-supply/) | --- ## Tips 1. Always use **`dataset: combined`** for balance queries — balances are computed from full history. 2. Remember grouping follows selection: add or drop `Balance.Address` / `Currency` fields to pivot between wallet, token, and network views. 3. Use `selectWhere` (post-aggregation) for balance thresholds; regular `where` filters raw rows before aggregation. 4. `AmountInUSD` is native-ETH-only in practice — USDG's `Amount` ≈ dollars; price other tokens via the [Trades API](/docs/blockchain/robinhood/robinhood-trades/). 5. For holder rankings and counts, use the dedicated [Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/) — its `Holders` cube is built for the token-centric view. 6. An as-of-date query before a wallet's first activity returns no rows — that's the correct answer, not an error. --- ## FAQ ### How do I get all token balances of a Robinhood address? Query `EVM.Balances` on `dataset: combined` filtered by `Balance.Address`, selecting `Currency` and `Balance.Amount` — one call returns the full portfolio. Add `Amount(selectWhere: {gt: "0"})` to hide dust and emptied positions. ### How do I get the balance at a past date? Add `Block: { Date: { till: "YYYY-MM-DD" } }` to any balance query — the cube recomputes balances as of that date. See [time travel](#balance-as-of-a-date-time-travel). ### How do I list the top holders of a token? Use the dedicated [Token Holders API](/docs/blockchain/robinhood/robinhood-token-holders-api/) — its `Holders` cube returns sortable holder rankings, holder counts, distribution stats, and dormancy screens. ### Why is AmountInUSD 0 for my token balances? USD enrichment covers native ETH; token rows generally return `0`. USDG is a dollar stablecoin (read `Amount` as USD), and other tokens can be valued by joining prices from the [Trades API](/docs/blockchain/robinhood/robinhood-trades/). ### Can I stream balances in real time? `Balances` is a query cube — poll it on your interval for live UX. For continuous balance-change feeds at firehose scale, Bitquery delivers Robinhood token data over [Kafka streams](/docs/streams/kafka-streaming-concepts/). ### Is this a replacement for eth_getBalance? For anything beyond a single known token it's strictly stronger: whole portfolios, holder lists, holder counts, historical as-of-date balances, and change aggregates come from single queries instead of RPC loops over an archive node. --- ## Robinhood Calls & Traces API — 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. # Robinhood Calls & Traces API — 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. 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, retained up to roughly the **last 3 months** (Robinhood is a newer chain, so today the archive holds its complete history; older data ages out as the cap applies); its head lags the chain by minutes. - **`combined`** — archive + realtime union; the safe choice for fixed windows (24h, 7d). For older or bulk history, Bitquery can provide **data exports** — [contact support](https://bitquery.io/forms/api). ### 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 retains up to roughly the last 3 months of calls; for older or bulk data, ask about [exports](https://bitquery.io/forms/api). 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` retains up to roughly the last 3 months of calls (on a newer chain like Robinhood that is currently its complete history), and `realtime` holds a rolling recent window — measure either with the [window probe](#check-the-calls-window). For older or 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/). --- ## Robinhood Chain API: Trades, Pons Launchpad and Real-Time Streams 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, Pons Launchpad and Real-Time Streams **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. 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. :::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 | | 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 | --- ## 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 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 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) | | 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 includes complete history; paid self-service plans are real-time only and add it 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 data - Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Robinhood Chain Data Bitquery provides **Robinhood Chain data dumps** in **Parquet format**, 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 leg 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 leg — 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 Landscape 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 legs | | `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 34 distinct event signatures in the sample. | 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 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-leg 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()) ``` ## Real-Time vs Batch Data Access Cloud data dumps 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 New Pools & Trending Tokens API 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. # Robinhood Chain New Pools & Trending Tokens API 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. 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 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 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 --- ## Robinhood Events API & 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. # Robinhood Events API & 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. 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, retained up to roughly the **last 3 months** (Robinhood is a newer chain, so today the archive holds its complete history; older data ages out as the cap applies); 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? Bitquery can also provide **historical data exports** — [contact support](https://bitquery.io/forms/api). ### 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 Bitquery about [historical data exports](https://bitquery.io/forms/api). --- ## 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` retains up to roughly the last 3 months of events (on a newer chain like Robinhood that is currently its complete history), and `realtime` holds a rolling recent window — measure either with the [window probe](#check-the-events-window). For older or 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/). --- ## Robinhood Liquidity & Slippage API 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. # Robinhood Liquidity & Slippage API 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/). 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). ::: :::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. --- ## 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 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. --- ## Robinhood Meme Coin Launches API 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. # Robinhood Meme Coin Launches API 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. :::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 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 Trades API](/docs/blockchain/robinhood/robinhood-trades). - Inspect holder and wallet flows with [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers). --- ## Robinhood Token Holders API — Rankings & Distribution URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-token-holders-api/ Query Robinhood token holders with Bitquery GraphQL: top-holder rankings, holder counts, distribution stats, whale floors and dormancy screens. # Robinhood Token Holders API — Rankings & Distribution Query **token holders on Robinhood** with Bitquery's dedicated `EVM.Holders` cube — the token-centric view: who holds a token, ranked by balance, with per-holder change history (`FirstChangeTime`, `LastChangeTime`, `UpdateCount`) built in. One query replaces the transfer-indexing pipeline you would otherwise need, and it powers holder leaderboards, holder counts, distribution stats, whale floors, dormancy screens, and airdrop snapshots. This is the API equivalent of the block explorer's token-holders tab (Blockscout's holders endpoint) with rankings, counts, distribution stats and history that you can query in bulk or stream. For the wallet-centric view — one address's full portfolio — use the [Robinhood Balances API](/docs/blockchain/robinhood/robinhood-balances-api/) instead. Every query on this page 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 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 Balances API](/docs/blockchain/robinhood/robinhood-balances-api/) - [Robinhood Token Supply API](/docs/blockchain/robinhood/robinhood-token-supply/) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) (live movement between holders) - [Robinhood Trades](/docs/blockchain/robinhood/robinhood-trades/) (prices to value holdings) - [Pons Launchpad API on Robinhood Chain](/docs/blockchain/robinhood/pons-api) (holder distribution on a bonding-curve launchpad) ::: **On this page:** [Concepts](#cube-concepts) · [Top holders](#top-holders-of-a-token) · [Holder count](#holder-count-of-a-token) · [Whale floors](#holders-above-a-balance-floor) · [Distribution](#holder-distribution-statistics) · [Dormant holders](#dormant-holders-diamond-hands) · [Stock tokens](#tokenized-stock-holders-nvda) · [ETH rich list](#native-eth-rich-list) · [Pagination](#paginating-full-holder-snapshots) · [FAQ](#faq) --- ## Cube concepts - **Rows are (holder, token) pairs**: `Holder.Address` plus a `Balance` with `Amount`, `FirstChangeTime`, `LastChangeTime`, and `UpdateCount`. Select `Currency` fields when you query across tokens. - Use **`dataset: archive`** — holder tables are computed from full history. - **No USD field on this cube** — threshold and rank by token `Amount` (USDG ≈ dollars); join prices from the [Trades API](/docs/blockchain/robinhood/robinhood-trades/) to value holdings. - **`Balance.LastChangeTime.till` filters by inactivity, not history**: a **future** date includes every holder (the current snapshot); a **past** date returns only wallets whose balance hasn't changed since then — with their frozen balances — which makes it a dormancy screen, not time travel. - A plain `count` includes **everyone who ever held** (including now-zero balances). Add `Balance: { Amount: { gt: "0" } }` for **current** holders — the two numbers differ a lot on active tokens. - The cube also accepts `Holder.Address` filters for wallet-side lookups, but portfolios are better served by the [Balances API](/docs/blockchain/robinhood/robinhood-balances-api/). --- ## Top holders of a token The holder leaderboard — ranked by balance, with each holder's history stats. Example: USDG. A far-future `LastChangeTime.till` (here 2099) explicitly includes all holders (see [concepts](#cube-concepts)); tighten it to screen for dormancy. ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Balance: { LastChangeTime: { till: "2099-12-31T23:59:59Z" } } } limit: { count: 100 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Holder count of a token One number per question: how many wallets **currently** hold the token (with the `gt: "0"` filter), or how many **ever** held it (without). ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Balance: { Amount: { gt: "0" } } } ) { holders: count } } } ``` Drop the `Balance` filter to count all-time holders instead. --- ## Holders above a balance floor **Whale lists and eligibility checks:** a regular `where` filter on `Balance.Amount` keeps only holders above a threshold — for USDG, the floor is effectively in dollars. ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Balance: { Amount: { ge: "100000" } } } limit: { count: 10 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount } } } } ``` --- ## Holder distribution statistics Concentration analysis in one aggregate call: current holder count, total held, and the mean / median / 99th-percentile holder size. Expect a long tail — the median holder is typically far below the mean. ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Balance: { Amount: { gt: "0" } } } ) { holders: count total: sum(of: Balance_Amount) avg: average(of: Balance_Amount) med: median(of: Balance_Amount) p99: quantile(of: Balance_Amount, level: 0.99) } } } ``` `standard_deviation` and other `quantile` levels are available for deeper concentration metrics (top-N share is easiest computed client-side from the [top holders](#top-holders-of-a-token) list against `total`). --- ## Dormant holders (diamond hands) Set `LastChangeTime.till` to a **past** date to keep only wallets whose balance hasn't moved since then — their `Amount` is the balance frozen at their last change. Combine with `FirstChangeTime` and `UpdateCount` to separate long-term holders from one-touch airdrop recipients. ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Balance: { LastChangeTime: { till: "2026-07-01T00:00:00Z" }, Amount: { gt: "0" } } } limit: { count: 10 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Tokenized stock holders (NVDA) Robinhood's tokenized equities are ordinary ERC-20s, so holder analytics work unchanged — `Amount` reads as the tokenized share count. Example: NVIDIA; swap in AAPL (`0xaf3d76f1834a1d425780943c99ea8a608f8a93f9`) or any other stock token. ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec" } } } limit: { count: 10 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount FirstChangeTime LastChangeTime UpdateCount } } } } ``` --- ## Native ETH rich list Filter `Currency.Native: true` for the chain's largest ETH holders. **Contracts appear as holders** — the WETH contract naturally tops the list since it custodies wrapped ETH; filter or label known contracts for a people-only ranking. ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { Native: true } } limit: { count: 10 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount } } } } ``` --- ## Paginating full holder snapshots **Airdrop snapshots and exports:** page through the complete holder set with `limit.offset`, keeping the same `orderBy` so pages don't overlap. ```graphql { EVM(dataset: archive, network: robinhood) { Holders( where: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } } limit: { count: 5, offset: 5 } orderBy: { descending: Balance_Amount } ) { Holder { Address } Balance { Amount } } } } ``` For very large one-off snapshots, Bitquery can also provide [data exports](https://bitquery.io/forms/api). --- ## Use-case patterns | Goal | Approach | | --- | --- | | Holder leaderboard page | [Top holders](#top-holders-of-a-token), refreshed on your interval | | Distribution / concentration dashboards | [Holder count](#holder-count-of-a-token) + [distribution stats](#holder-distribution-statistics); top-N share client-side | | Airdrop eligibility & snapshots | [Balance floors](#holders-above-a-balance-floor) + [offset pagination](#paginating-full-holder-snapshots) | | Diamond-hands / dormancy analysis | [`LastChangeTime` screens](#dormant-holders-diamond-hands) with `FirstChangeTime` / `UpdateCount` | | Stock-token cap tables | [Tokenized stock holders](#tokenized-stock-holders-nvda) | | Live movement between holders | Stream the token on the [Transfers API](/docs/blockchain/robinhood/robinhood-transfers/) | --- ## Tips 1. Use `dataset: archive` and always keep a `limit` — popular tokens have very large holder sets. 2. Add `Balance: { Amount: { gt: "0" } }` whenever you mean **current** holders; plain counts include every wallet that ever held. 3. There is no USD field on this cube — rank and threshold in token units (USDG ≈ dollars) and join prices from the [Trades API](/docs/blockchain/robinhood/robinhood-trades/) for valuations. 4. `LastChangeTime.till` in the future = full current snapshot; in the past = dormancy screen with frozen balances. It is not an as-of-date balance calculator — for historical *balances* use the [Balances API's date filter](/docs/blockchain/robinhood/robinhood-balances-api/). 5. Contracts are holders too (WETH tops native rankings by design) — maintain a label list to exclude them from people-only rankings. 6. `UpdateCount` separates active traders (high) from set-and-forget holders (low) at a glance. --- ## FAQ ### How do I get the top holders of a Robinhood token? Query `EVM.Holders` on `dataset: archive`, filter `Currency.SmartContract`, and order by `Balance_Amount` descending — see [Top holders](#top-holders-of-a-token). Each row includes the holder's first/last change time and update count. ### How do I get a token's holder count? Run the [holder-count query](#holder-count-of-a-token) with `Balance: { Amount: { gt: "0" } }` for current holders, or without it for all-time holders. ### Can I take an airdrop snapshot of all holders? Yes — page through the full holder set with `limit: { count, offset }` under a stable `orderBy`, optionally with a [balance floor](#holders-above-a-balance-floor) for eligibility. For very large snapshots, ask about data exports. ### How do I find dormant or diamond-hand holders? Set `Balance.LastChangeTime.till` to a past date — only wallets untouched since then return, with their frozen balances. See [Dormant holders](#dormant-holders-diamond-hands). ### Why is there no USD value on holder rows? The Holders cube reports token amounts only. Use token-unit thresholds (USDG ≈ dollars), or multiply amounts by a price from the [Trades API](/docs/blockchain/robinhood/robinhood-trades/). ### Should I use Holders or Balances? `Holders` is token-centric (one token → many wallets): rankings, counts, distribution. [`Balances`](/docs/blockchain/robinhood/robinhood-balances-api/) is wallet-centric (one wallet → many tokens): portfolios, multi-address batches, and as-of-date balance history. --- ## Robinhood Token Supply API URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-token-supply/ Robinhood Token Supply API: query and stream token total supply with Bitquery's EVM TransactionBalances API — single tokens, watchlists, and all active tokens. # Robinhood Token Supply API Get **token total supply** on the **Robinhood** network with Bitquery's `EVM.TransactionBalances` API. This guide covers the **latest supply of a token**, a **real-time supply stream**, and the **supply of all active 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 Chain API overview](/docs/blockchain/robinhood/) — every Robinhood Chain API, launchpad guide and stream in one place - [Robinhood Trades API](/docs/blockchain/robinhood/robinhood-trades) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers) - [Robinhood Liquidity & Slippage API](/docs/blockchain/robinhood/robinhood-liquidity/) - [Flap.sh API on Robinhood](/docs/blockchain/robinhood/flap-sh-api) - [WebSocket subscriptions](/docs/subscriptions/websockets/) ::: :::caution `TransactionBalances` is realtime-only on Robinhood This cube has no archive table on Robinhood: it holds only the most recent days, so a token with no transaction in that window returns no row, and `dataset: archive` errors. Keep queries bounded with a `Block.Time` filter and a `limit`. ::: :::note Supply is decimal-normalized `TokenBalance.TotalSupply` is already adjusted for the token's decimals, so it returns whole-token values (e.g. `100000000.000000000000000000`) — not the raw on-chain integer. ::: --- ▶️ [Token lookup by contract address - Run in IDE](https://ide.bitquery.io/token-lookup-by-address-robinhood-chain) ## Latest Supply of a Token Get the most recent total supply for a single token by filtering on its contract address and taking the newest balance record. ```graphql { EVM(network: robinhood) { TransactionBalances( limit: {count: 1} orderBy: {descending: Block_Time} where: {TokenBalance: {Currency: {SmartContract: {is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73"}}}} ) { TokenBalance { Currency { Symbol HasURI SmartContract } TotalSupply } } } } ```
Sample response ```json { "EVM": { "TransactionBalances": [ { "TokenBalance": { "Currency": { "Symbol": "WETH", "HasURI": false, "SmartContract": "0x0bd7d308f8e1639fab988df18a8011f41eacad73" }, "TotalSupply": "18584.722713864831985195" } } ] } } ```
--- ## Real-Time Supply Stream for Tokens on Robinhood Subscribe to live total-supply updates across Robinhood tokens. The `SmartContract: {not: "0x"}` filter excludes the native coin so only token supply changes stream through. ```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 in a single query. `limitBy` collapses results to the newest record per token contract, so each token appears once with its current supply. 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 } } } } ```
Sample response ```json { "EVM": { "TransactionBalances": [ { "TokenBalance": { "Currency": { "Symbol": "HEIST", "HasURI": false, "SmartContract": "0xfbb3171fc52fca9f8ff10b2494a6055a51f68717" }, "TotalSupply": "100000000.000000000000000000" } }, { "TokenBalance": { "Currency": { "Symbol": "ROBINHOOD", "HasURI": false, "SmartContract": "0x217b7013e00c13ce4f3bc968238e0b13ce297382" }, "TotalSupply": "100000000000.000000000000000000" } }, { "TokenBalance": { "Currency": { "Symbol": "BabyJugger", "HasURI": false, "SmartContract": "0xd8e25ced04f51efa18fa94b460f6e924c3aa23ae" }, "TotalSupply": "1000000000.000000000000000000" } } ] } } ```
--- ## Tokenized Stock Supply (NVDA) Robinhood's tokenized equities are ordinary ERC-20s, so the same query returns the on-chain supply of a stock token — `TotalSupply` reads as the tokenized share count. Example: NVIDIA (`NVDA`); swap in AAPL (`0xaf3d76f1834a1d425780943c99ea8a608f8a93f9`) or any other stock token. ```graphql { EVM(network: robinhood) { TransactionBalances( limit: {count: 1} orderBy: {descending: Block_Time} where: {TokenBalance: {Currency: {SmartContract: {is: "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec"}}}} ) { TokenBalance { Currency { Symbol Name SmartContract } TotalSupply } } } } ``` --- ## Supply Watchlist: Multiple Tokens at Once One latest supply row per token for a fixed list — `SmartContract.in` plus `limitBy` per contract, bounded to the last six hours so the `limitBy` scan stays fast (widen the bound for tokens that transact rarely). Example list: WETH, USDG, AAPL, NVDA. ```graphql { EVM(network: robinhood) { TransactionBalances( limitBy: {by: TokenBalance_Currency_SmartContract, count: 1} limit: {count: 10} orderBy: {descending: Block_Time} where: {Block: {Time: {since_relative: {hours_ago: 6}}}, TokenBalance: {Currency: {SmartContract: {in: [ "0x0bd7d308f8e1639fab988df18a8011f41eacad73", "0x5fc5360d0400a0fd4f2af552add042d716f1d168", "0xaf3d76f1834a1d425780943c99ea8a608f8a93f9", "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec" ]}}}} ) { TokenBalance { Currency { Symbol SmartContract } TotalSupply } } } } ``` --- ## FAQ ### How do I get the current total supply of a Robinhood token? Query `EVM.TransactionBalances` filtered by the token's `Currency.SmartContract`, ordered by `descending: Block_Time` with `limit: 1`. The newest record holds the latest `TotalSupply`. ### How do I stream supply changes in real time? Run the `subscription` on `TransactionBalances` with `Currency.SmartContract: {not: "0x"}`. Each supply change on a token is pushed to your client as it is indexed. ### How do I list supply for all active tokens at once? Use `limitBy: {by: TokenBalance_Currency_SmartContract, count: 1}` with `orderBy: {descending: Block_Time}`. This returns one row — the latest supply — per token contract. ### Can I get supply for several tokens in one query? Yes — filter `Currency.SmartContract` with `in: [...]` and add `limitBy: {by: TokenBalance_Currency_SmartContract, count: 1}` so each token returns its newest supply once. See [the watchlist example](#supply-watchlist-multiple-tokens-at-once). ### Is `TotalSupply` raw or decimal-adjusted? It is decimal-normalized (whole tokens), already divided by the token's decimals. Use it directly for market-cap math without further scaling. --- ## Next steps - Combine supply with price from the [Robinhood Trades API](/docs/blockchain/robinhood/robinhood-trades) for market-cap and FDV calculations. - Track newly launched tokens with the [Robinhood Meme Coin Launches API](/docs/blockchain/robinhood/robinhood-meme-coin-launches) and [Flap.sh API](/docs/blockchain/robinhood/flap-sh-api). - Inspect holder and wallet flows with [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers). --- ## Robinhood Trades API & Streams URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-trades/ Robinhood Trades API: live trades, USD prices, OHLCV candles, market cap, whale trades, buy/sell pressure, and top traders via Bitquery GraphQL & WebSockets. # Robinhood Trades API & 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. ## 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). --- ## Robinhood Transactions & Receipts API URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-transactions-receipts-api/ Query Robinhood transactions and receipts with Bitquery GraphQL: block receipts, single-tx receipts, status, gas and fees. No node required. # Robinhood Transactions & Receipts API Query **transactions and their receipts on Robinhood** with Bitquery GraphQL. The `EVM.Transactions` cube returns one row per transaction with its **receipt** (status, gas used, cumulative gas, contract address, logs bloom), **fee breakdown** (effective gas price, burnt, miner reward), and header fields — a no-node replacement for the JSON-RPC receipt methods that also streams live over WebSocket. This page is organized around the **RPC methods people migrate from** — `eth_getBlockReceipts`, `eth_getTransactionReceipt`, `eth_getTransactionByHash` — with the Bitquery equivalent for each. Every query was executed against the production endpoint before publishing, and the stream was verified live over 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/) ::: :::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/) (logs — receipts don't nest them here) - [Robinhood Calls & Traces API](/docs/blockchain/robinhood/robinhood-calls-api/) - [Robinhood Transfers](/docs/blockchain/robinhood/robinhood-transfers/) - [WebSocket authentication](/docs/authorization/websocket/) ::: **On this page:** [RPC mapping](#rpc-method-mapping) · [Dataset caveat](#dataset-realtime-only) · [Block receipts](#eth_getblockreceipts-equivalent) · [Single receipt](#eth_gettransactionreceipt-equivalent) · [Transaction by hash](#eth_gettransactionbyhash-equivalent) · [Getting logs](#getting-the-logs-for-a-receipt) · [Latest & stream](#latest-transactions-and-live-stream) · [Failed txs](#failed-transactions) · [Account history](#transactions-for-an-account) · [Receipt fields](#receipt-field-reference) · [FAQ](#faq) --- ## RPC method mapping | JSON-RPC method | Bitquery equivalent | | --- | --- | | `eth_getBlockReceipts` | `Transactions` filtered by `Block.Number` (or `Block.Hash`) — [below](#eth_getblockreceipts-equivalent) | | `eth_getTransactionReceipt` | `Transactions` filtered by `Transaction.Hash` — [below](#eth_gettransactionreceipt-equivalent) | | `eth_getTransactionByHash` | Same filter, selecting header fields incl. `Transaction.Data` — [below](#eth_gettransactionbyhash-equivalent) | | `eth_getTransactionReceipt().logs` | `Events` cube, same block or tx filter — [below](#getting-the-logs-for-a-receipt) | | `eth_getBlockTransactionCountByNumber` | `Transactions` + `count` on a block — [below](#block-transaction-stats) | | `eth_subscribe("newHeads"/txs)` | `subscription { Transactions }` — [below](#latest-transactions-and-live-stream) | --- ## Dataset: realtime only :::warning Use `dataset: realtime` for transactions and receipts Unlike the [Events](/docs/blockchain/robinhood/robinhood-events-api/) and [Calls](/docs/blockchain/robinhood/robinhood-calls-api/) cubes, the **`Transactions` cube has no archive table on Robinhood**. `dataset: archive` errors (*"no table can query Transaction"*), and `combined` only serves blocks still inside the realtime window. So receipt queries work for **recent blocks** — the realtime window is a rolling span of recent days; measure it with the [window probe](#window-probe). Blocks older than the window need a [data export](https://bitquery.io/forms/api). ::: The block and transaction identifiers in the examples are **illustrative recent values** — they roll out of the realtime window over time. Get a current block number from the [latest-transactions query](#latest-transactions-and-live-stream) and substitute it. ### Window probe ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions { count earliest: Block { Time(minimum: Block_Time) } latest: Block { Time(maximum: Block_Time) } } } } ``` --- ## `eth_getBlockReceipts` equivalent Every transaction receipt in one block: filter `Block.Number` and order by `Transaction.Index` — each row is one receipt. Substitute a recent block number. ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions( where: { Block: { Number: { eq: "18038003" } } } orderBy: { ascending: Transaction_Index } limit: { count: 1000 } ) { Block { Number Hash Time } Transaction { Hash Index From To Type Nonce Value } Receipt { Status Type CumulativeGasUsed GasUsed ContractAddress Bloom PostState } Fee { EffectiveGasPrice } TransactionStatus { Success } } } } ``` To target the block **by hash** (the other form `eth_getBlockReceipts` accepts), swap the filter: ```graphql where: { Block: { Hash: { is: "0x69ab18694427b809459cad7a44b1ae369095897b2d86571410a1430902a9fb1d" } } } ``` :::note Robinhood is an Arbitrum-Orbit chain Blocks include system/sequencer transactions (e.g. `Receipt.Type: 106` from the sequencer address `0x…000a4b05`) alongside user transactions — exactly what a node returns for the block. Filter them out by `Transaction.Type` or sender if you only want user activity. ::: --- ## `eth_getTransactionReceipt` equivalent One transaction's receipt — filter `Transaction.Hash`. ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions( where: { Transaction: { Hash: { is: "0x01f956f16e7200e1a2054e3a701bf6b2496972a23544b4d2f122f0894a0f0835" } } } ) { Block { Number Hash Time } Transaction { Hash Index From To Type Nonce Value Gas GasPrice } Receipt { Status Type CumulativeGasUsed GasUsed ContractAddress Bloom } Fee { EffectiveGasPrice Burnt MinerReward } TransactionStatus { Success EndError } } } } ``` `Receipt.Status` is the RPC-style `"1"`/`"0"`; `TransactionStatus.Success` is the same as a boolean, with `EndError` / `FaultError` carrying the revert reason when it failed. --- ## `eth_getTransactionByHash` equivalent The same filter, selecting the transaction header — including `Transaction.Data` (the input calldata) and the fee-cap fields. ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions( where: { Transaction: { Hash: { is: "0x01f956f16e7200e1a2054e3a701bf6b2496972a23544b4d2f122f0894a0f0835" } } } ) { Block { Number Time } Transaction { Hash Index From To Nonce Value Gas GasPrice GasFeeCap GasTipCap Type Data } } } } ``` For the decoded function call and internal calls of a transaction, use the [Calls & Traces API](/docs/blockchain/robinhood/robinhood-calls-api/#full-call-tree-of-a-transaction) instead of raw `Data`. --- ## Getting the logs for a receipt `eth_getTransactionReceipt` embeds a `logs` array; here logs live in the **[Events cube](/docs/blockchain/robinhood/robinhood-events-api/)**, decoded. Query them for the same transaction (or the whole block) and order by `Log.Index`: ```graphql { EVM(network: robinhood, dataset: realtime) { Events( where: { Transaction: { Hash: { is: "0x01f956f16e7200e1a2054e3a701bf6b2496972a23544b4d2f122f0894a0f0835" } } } orderBy: { ascending: Log_Index } ) { Log { Index SmartContract Signature { Name SignatureHash } } Arguments { Name Type Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } } } } } } ``` Swap the filter to `Block: { Number: { eq: "…" } }` for every log in a block (the `eth_getBlockReceipts` logs, flattened). --- ## Latest transactions and live stream ▶️ Runnable IDE examples: [daily transaction count](https://ide.bitquery.io/robinhood-chain-daily-transactions), [daily active wallets](https://ide.bitquery.io/robinhood-chain-active-wallets), [gas usage and price](https://ide.bitquery.io/robinhood-chain-gas-fees), [blocks per day](https://ide.bitquery.io/robinhood-chain-block-time) The newest transactions with their receipts — and the block numbers to plug into the examples above. ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions(limit: { count: 10 }, orderBy: { descending: Block_Time }) { Block { Number Time } Transaction { Hash From To Value Type } Receipt { Status GasUsed } TransactionStatus { Success } } } } ``` Stream every transaction as it is mined — the push-based counterpart, verified live over WebSocket: ```graphql subscription { EVM(network: robinhood) { Transactions { Block { Number Time } Transaction { Hash From To Value } Receipt { Status GasUsed } TransactionStatus { Success } } } } ``` :::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 every transaction continuously? Bitquery also delivers Robinhood data as **Kafka streams** (protobuf topic `robinhood.transactions.proto`) with consumer-group scaling and replay. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). ::: --- ## Failed transactions Filter `TransactionStatus.Success: false` for reverted transactions with their error text — an error monitor across the chain. ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions( limit: { count: 10 } orderBy: { descending: Block_Time } where: { TransactionStatus: { Success: false } } ) { Block { Time } Transaction { Hash From To } TransactionStatus { Success EndError FaultError } Receipt { Status GasUsed } } } } ``` --- ## Transactions for an account Every top-level transaction sent by an address (`Transaction.From`), with receipts — an account history / nonce tracker. Swap in an active sender. ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Transaction: { From: { is: "0xcc1120e4af58abbecae0c0e3c4b2d343c1283695" } } } ) { Block { Time } Transaction { Hash To Value Nonce } Receipt { Status GasUsed } } } } ``` `Transaction.From` is the top-level sender (EOA). For a contract's inbound calls including internal ones, use the [Calls API](/docs/blockchain/robinhood/robinhood-calls-api/#stream-calls-to-one-contract). --- ## Block transaction stats The count and gas of one block in a single aggregate — the `eth_getBlockTransactionCountByNumber` answer, plus success rate and total gas. ```graphql { EVM(network: robinhood, dataset: realtime) { Transactions(where: { Block: { Number: { eq: "18038003" } } }) { txns: count success: count(if: { TransactionStatus: { Success: true } }) gas: sum(of: Receipt_GasUsed) } } } ``` --- ## Receipt field reference | JSON-RPC receipt field | Bitquery field | | --- | --- | | `blockNumber` / `blockHash` | `Block.Number` / `Block.Hash` | | `transactionHash` / `transactionIndex` | `Transaction.Hash` / `Transaction.Index` | | `from` / `to` | `Transaction.From` / `Transaction.To` | | `status` | `Receipt.Status` (`"1"`/`"0"`) or `TransactionStatus.Success` (bool) | | `cumulativeGasUsed` | `Receipt.CumulativeGasUsed` | | `gasUsed` | `Receipt.GasUsed` | | `contractAddress` | `Receipt.ContractAddress` | | `logsBloom` | `Receipt.Bloom` | | `effectiveGasPrice` | `Fee.EffectiveGasPrice` | | `type` | `Receipt.Type` (or `Transaction.Type`) | | `root` (pre-Byzantium) | `Receipt.PostState` | | `logs` | [`Events` cube](#getting-the-logs-for-a-receipt) (separate, decoded) | Also on `Fee`: `Burnt`, `MinerReward`, `PriorityFeePerGas`, `GasRefund`, `Savings` (plus `*InUSD` variants). On `Transaction`: `GasFeeCap`, `GasTipCap`, `Data`, `Nonce`, `CallCount`, `Protected`. --- ## Tips 1. Use **`dataset: realtime`** — the `Transactions` cube has no archive on Robinhood; older blocks need a [data export](https://bitquery.io/forms/api). 2. `Receipt.Status` is RPC-style `"1"`/`"0"`; `TransactionStatus.Success` is the boolean form and carries `EndError` / `FaultError` on failure. 3. Receipts don't nest logs here — pull them from the [Events cube](#getting-the-logs-for-a-receipt) by block or tx hash. 4. Block/tx identifiers in queries roll out of the realtime window over time; fetch current ones from the [latest-transactions query](#latest-transactions-and-live-stream). 5. Sequencer/system transactions (`Type: 106`) appear in blocks — filter by `Transaction.Type` or sender for user-only views. 6. For decoded function inputs and internal calls, use the [Calls API](/docs/blockchain/robinhood/robinhood-calls-api/); for token movement, use [Transfers](/docs/blockchain/robinhood/robinhood-transfers/). --- ## FAQ ### What is the eth_getBlockReceipts equivalent on Robinhood? Query the `EVM.Transactions` cube filtered by `Block.Number` (or `Block.Hash`), ordered by `Transaction.Index`, selecting `Receipt`, `Fee`, and `TransactionStatus` — one row per receipt. See [the query](#eth_getblockreceipts-equivalent). Use `dataset: realtime`. ### How do I get a single transaction's receipt? Filter `Transaction.Hash` on the same cube — the [`eth_getTransactionReceipt` equivalent](#eth_gettransactionreceipt-equivalent). Add `Transaction.Data` and fee-cap fields for the [`eth_getTransactionByHash`](#eth_gettransactionbyhash-equivalent) view. ### Where are the receipt logs? Logs are a separate, decoded cube — [Events](/docs/blockchain/robinhood/robinhood-events-api/). Filter it by the same `Transaction.Hash` or `Block.Number` and order by `Log.Index`. See [Getting the logs](#getting-the-logs-for-a-receipt). ### Why does dataset archive fail for transactions? The `Transactions` cube is realtime-only on Robinhood — there is no archive table, so `archive` errors and `combined` only covers the realtime window. Recent blocks work; for older history request a [data export](https://bitquery.io/forms/api). ### How do I check whether a transaction succeeded or reverted? Read `TransactionStatus.Success` (boolean) with `EndError` / `FaultError` for the reason, or `Receipt.Status` for the `"1"`/`"0"` form. Filter `Success: false` to list [failed transactions](#failed-transactions). --- ## Robinhood Transfers API & Streams URL: https://docs.bitquery.io/docs/blockchain/robinhood/robinhood-transfers/ Query & stream Robinhood transfers with Bitquery GraphQL: ETH, USDG, tokenized stocks (AAPL, NVDA), whale alerts, wallet ledgers, and compliance monitors. # Robinhood Transfers API & Streams Use the **Robinhood Transfers API** to query and stream on-chain transfers on Robinhood with Bitquery GraphQL (`network: robinhood` on `EVM`). This is the shared **EVM Transfers** cube scoped to Robinhood — not a separate schema. Track native ETH, WETH, stablecoins such as USDG, **tokenized stocks (AAPL, NVDA, GOOGL, GME)**, and meme-token movements in real time or across historical windows. Build whale alerts, address ledgers, transfer-volume dashboards, and compliance monitors from the same cube. Every query on this page was executed against the production endpoint before publishing, and each subscription was verified live over WebSocket. | Use case | What you can build | | --- | --- | | **Trading / desks** | Whale alerts, large ETH moves, hourly volume, liquidity-hub flows | | **DeFi / bots** | Token transfer feeds, WETH wrap/unwrap, router counterparties | | **Accounting / portfolio** | Inbound vs outbound, sent/received volume by token, date-range ledgers | | **Compliance / forensics** | Address timelines, top counterparties, failed transfers, address-pair flows | | **Token analytics** | Most-transferred tokens, transfer size stats, daily volume, unique senders/receivers | **On this page:** [Stream](#stream-real-time-transfers) · [Latest](#latest-transfers) · [By token](#transfers-for-a-specific-token) · [Token pulse](#latest-transfer-per-token-activity-pulse) · [USDG](#usdg-stablecoin-transfers) · [Tokenized stocks](#tokenized-stock-transfers-aapl-nvda) · [By address](#transfers-for-an-address) · [Whales](#whale-transfers-by-usd-value) · [Top tokens](#most-transferred-tokens-24h) · [Size stats](#eth-transfer-size-statistics-24h) · [Daily volume](#daily-transfer-volume-7-days) · [Historical](#historical-transfers-by-date) · [FAQ](#faq) :::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 Trades](/docs/blockchain/robinhood/robinhood-trades/) - [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/) - [EVM Transfers schema](/docs/schema/evm/transfers/) - [ERC20 Token Transfers API (Ethereum)](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api/) - [Transfers vs Events vs Calls](/docs/start/mental-model-transfers-events-calls/) ::: --- ## Network and useful contracts | Item | Value | | --- | --- | | GraphQL network | `network: robinhood` on `EVM` | | Native currency | ETH (`Currency.Native: true`, `SmartContract: "0x"`) | | WETH | `0x0bd7d308f8e1639fab988df18a8011f41eacad73` | | USDG (Global Dollar) | `0x5fc5360d0400a0fd4f2af552add042d716f1d168` | | AAPL (Apple · Robinhood Token) | `0xaf3d76f1834a1d425780943c99ea8a608f8a93f9` | | NVDA (NVIDIA · Robinhood Token) | `0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec` | | FREN (example meme token) | `0xd387e5bba711457faf4d013d20e02e8c91f07fa4` | | Zero address (wrap/unwrap, mint/burn) | `0x0000000000000000000000000000000000000000` | | Example address used below | `0xcaf681a66d020601342297493863e78c959e5cb2` | :::note Example addresses `0xcaf681a6…` is a **high-activity address** on Robinhood (often involved in routing/liquidity flows). Treat it as a sample — replace it with any wallet or contract you want to track. FREN is an illustrative meme token and may change over time. ::: `Transfer.Type` commonly returns `token` (ERC-20 log), `call` (internal value move), or `transaction` (top-level ETH value). :::tip AmountInUSD on Robinhood transfers In practice **only native ETH carries a populated `AmountInUSD`** on this cube — WETH and USDG rows return `0` too, not just long-tail tokens. Consequences: - USD thresholds and USD rankings effectively select **ETH flows only**. - For USDG, treat `Transfer.Amount` as ≈ USD (it is a dollar stablecoin). - For every other token (including tokenized stocks), filter and rank by `Transfer.Amount` in token units. ::: :::tip Choosing a dataset - **`realtime`** — a rolling window of recent blocks. Its depth **varies** from hours to days — don't assume a fixed depth; measure it with the query below. - **`combined`** — archive + realtime union. The safe choice for any fixed window (24h, 48h, 7d). - **`archive`** — full history; its head lags the chain by minutes. Unlike the [liquidity cubes](/docs/blockchain/robinhood/robinhood-liquidity/), Transfers **does** support archive. ::: ### Check the dataset window Don't guess the realtime depth — measure it. `Time(minimum: …)` / `Time(maximum: …)` return the bounds of whatever the dataset currently holds (swap in `archive` to see the archive head). ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers { count earliest: Block { Time(minimum: Block_Time) } latest: Block { Time(maximum: Block_Time) } } } } ``` --- ## Stream real-time transfers Stream live transfers for dashboards, bots, and alerting. :::warning Filter live streams Robinhood transfer volume is very high. Prefer a `where` filter (token, address, or `AmountInUSD`) in production. An unfiltered subscription is fine for exploration, but it can overwhelm clients and burn stream quota. ::: ▶️ [Run in IDE](https://ide.bitquery.io/real-time-transfers-on-robinhood) ```graphql subscription { EVM(network: robinhood) { Transfers { Transfer { Amount AmountInUSD Sender Receiver Type Success Currency { Name Symbol SmartContract Native } } Transaction { Hash From To } Block { Number Time } } } } ``` :::tip WebSocket connection Connect to `wss://streaming.bitquery.io/graphql?token=YOUR_TOKEN` with the `graphql-transport-ws` subprotocol (`connection_init` → `connection_ack` → `subscribe`). Events arrive in per-block batches. See [WebSocket authentication](/docs/authorization/websocket/). ::: :::tip Prefer Kafka for the firehose Consuming all Robinhood transfers continuously? Bitquery also delivers this data as **Kafka streams** (protobuf topic `robinhood.tokens.proto`) with consumer-group scaling and replay. See [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). ::: ### Stream whale transfers (USD threshold) Alert when a successful transfer exceeds a USD size. Exclude the zero address to skip wrap/unwrap and mint/burn noise. Because USD is populated for native ETH, this is effectively a **large ETH move alert**. ```graphql subscription { EVM(network: robinhood) { Transfers( where: { Transfer: { AmountInUSD: { gt: "10000" } Success: true Sender: { not: "0x0000000000000000000000000000000000000000" } Receiver: { not: "0x0000000000000000000000000000000000000000" } } } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol Native SmartContract } } Transaction { Hash From To } Block { Number Time } } } } ``` ### Stream transfers for an address (wallet tracker) Watch one wallet's inbound and outbound transfers live — the core of a wallet tracker or deposit monitor. Replace the sample address with yours. ```graphql subscription { EVM(network: robinhood) { Transfers( where: { any: [ { Transfer: { Sender: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } { Transfer: { Receiver: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } ] Transfer: { Success: true } } ) { Transfer { Amount AmountInUSD Sender Receiver Type Currency { Symbol SmartContract Native } } Transaction { Hash } Block { Time Number } } } } ``` --- ## Latest transfers Query the most recent transfers with amount, USD value, token metadata, sender, receiver, time, and transaction hash. ▶️ [Run in IDE](https://ide.bitquery.io/latest-transfers-on-robinhood) ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Type Success Currency { Name Symbol SmartContract Native } } Transaction { Hash From To } Block { Time Number } } } } ``` Example response shape: ```json { "EVM": { "Transfers": [ { "Block": { "Number": "17306406", "Time": "2026-07-23T13:00:09Z" }, "Transaction": { "From": "0x8c72ce85b70972de417919a8f999145e6d9bd303", "Hash": "0x1a60e55cddedbd7534eea1e721a59a6abd8ce1e68c06313272621eaf9958488b", "To": "0xcaf681a66d020601342297493863e78c959e5cb2" }, "Transfer": { "Amount": "0.020000000000000000", "AmountInUSD": "38.05729248046875", "Currency": { "Name": "Ethereum", "Native": true, "SmartContract": "0x", "Symbol": "ETH" }, "Receiver": "0x0bd7d308f8e1639fab988df18a8011f41eacad73", "Sender": "0xcaf681a66d020601342297493863e78c959e5cb2", "Success": true, "Type": "call" } } ] } } ``` --- ## Native ETH transfers Useful for gas/treasury monitoring and large native ETH value moves (`Type` is often `call` or `transaction`). ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { Native: true } Success: true } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Type Currency { Symbol Native } } Transaction { Hash From To } Block { Time } } } } ``` --- ## Token transfers (exclude native ETH) Track ERC-20 style movements — WETH, USDG, tokenized stocks, meme tokens — without native ETH noise. ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { Native: false } Success: true } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Type Currency { Name Symbol SmartContract } } Transaction { Hash } Block { Time } } } } ``` --- ## Transfers for a specific token ▶️ [Whale WETH transfers - Run in IDE](https://ide.bitquery.io/whale-transfers-robinhood-chain) Filter with `Transfer.Currency.SmartContract`. Example: WETH on Robinhood. ▶️ [Run in IDE](https://ide.bitquery.io/Transfers-for-a-token-on-robinhood) ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } } Success: true } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract } } Transaction { Hash } Block { Time } } } } ``` ### Multiple tokens in one query Monitor a watchlist (WETH + a meme token) with `SmartContract.in`. ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { SmartContract: { in: [ "0x0bd7d308f8e1639fab988df18a8011f41eacad73" "0xd387e5bba711457faf4d013d20e02e8c91f07fa4" ] } } Success: true } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Transfer { Amount Sender Receiver Currency { Symbol SmartContract } } Transaction { Hash } Block { Time } } } } ``` --- ## Latest transfer per token (activity pulse) One call, one **latest** transfer per token: `limitBy` on the currency contract turns the firehose into a network-wide "which tokens are moving right now" pulse — useful for screeners and discovery dashboards. ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Success: true, Currency: { Native: false } } } limitBy: { by: Transfer_Currency_SmartContract, count: 1 } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Block { Time } Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol SmartContract } } } } } ``` --- ## USDG stablecoin transfers **Accounting / payments / compliance:** track Global Dollar (USDG) flows. USDG rows report `AmountInUSD: 0`, but since USDG is a dollar stablecoin, `Transfer.Amount` **is** the dollar size — filter on it directly. ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Amount: { gt: "1000" } Success: true Sender: { not: "0x0000000000000000000000000000000000000000" } Receiver: { not: "0x0000000000000000000000000000000000000000" } } } limit: { count: 10 } orderBy: { descending: Transfer_Amount } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract } } Transaction { Hash } Block { Time } } } } ``` ### USDG 24h activity summary Use `dataset: combined` so the full 24h window is covered regardless of the current realtime depth. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Currency: { SmartContract: { is: "0x5fc5360d0400a0fd4f2af552add042d716f1d168" } } Success: true } } ) { count amount: sum(of: Transfer_Amount) receivers: uniq(of: Transfer_Receiver) senders: uniq(of: Transfer_Sender) } } } ``` --- ## Tokenized stock transfers (AAPL, NVDA) **Trading / custody:** monitor tokenized equity movements. Robinhood's stock tokens are ordinary ERC-20s here — AAPL below; swap in NVDA (`0xd0601ce1…`) or any other. Other stock tokens (GOOGL, GME, INTC, SNDK) follow the same pattern. `AmountInUSD` is `0` for these, so read `Transfer.Amount` as the **share count**. ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xaf3d76f1834a1d425780943c99ea8a608f8a93f9" } } Success: true } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract } } Transaction { Hash From To } Block { Time Number } } } } ``` :::warning Ticker symbols are not unique Multiple contracts can share one ticker — Robinhood has **two different contracts both using the GME symbol** (`0x1b0e319c6a659f002271b69db8a7df2f911c153e` and `0xc2362aff2a2a4cc1f48cf3dab2c4e2605eb94ba3`). Always resolve and pin the `SmartContract` address (the canonical Robinhood stock tokens are named like `NVIDIA • Robinhood Token`) instead of trusting a ticker. ::: --- ## Transfers for an address Filter where the address is either `Transfer.Sender` or `Transfer.Receiver` to build a full transfer history. Replace the sample address with your wallet or contract. ▶️ [Run in IDE](https://ide.bitquery.io/transfers-for-a-wallet-on-Robinhood) ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { any: [ { Transfer: { Sender: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } { Transfer: { Receiver: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } ] Transfer: { Success: true } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract Native } } Transaction { Hash From To } Block { Time Number } } } } ``` ### Inbound only (deposits) ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Receiver: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } Success: true } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol Native SmartContract } } Transaction { Hash From To } Block { Time Number } } } } ``` ### Outbound only (withdrawals) ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Sender: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } Success: true } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol Native SmartContract } } Transaction { Hash } Block { Time } } } } ``` --- ## Whale transfers by USD value **Trading / compliance:** find the largest successful transfers by `AmountInUSD`, excluding zero-address wrap/unwrap and mint/burn rows. Since only native ETH carries USD, this surfaces **large ETH moves**. For token whales, use raw-amount thresholds like the [meme-token example](#large-meme-token-transfers-by-token-amount). ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { AmountInUSD: { gt: "10000" } Success: true Sender: { not: "0x0000000000000000000000000000000000000000" } Receiver: { not: "0x0000000000000000000000000000000000000000" } } } limit: { count: 20 } orderBy: { descending: Transfer_AmountInUSD } ) { Transfer { Amount AmountInUSD Sender Receiver Type Currency { Symbol Native SmartContract } } Transaction { Hash From To } Block { Time Number } } } } ``` ### Large top-level ETH value transfers `Transfer.Type: transaction` focuses on ETH moved as the transaction value (typical for large treasury moves). ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Type: { is: transaction } Success: true AmountInUSD: { gt: "100" } } } limit: { count: 10 } orderBy: { descending: Transfer_AmountInUSD } ) { Transfer { Amount AmountInUSD Type Sender Receiver Currency { Symbol Native } } Transaction { Hash From To } Block { Time } } } } ``` --- ## Large meme-token transfers (by token amount) When `AmountInUSD` is `0`, rank by raw `Transfer.Amount`. Example uses FREN (`0xd387e5bba711457faf4d013d20e02e8c91f07fa4`). ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xd387e5bba711457faf4d013d20e02e8c91f07fa4" } } Amount: { gt: "1000000" } Success: true } } limit: { count: 20 } orderBy: { descending: Transfer_Amount } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol SmartContract } } Transaction { Hash } Block { Time } } } } ``` --- ## WETH wrap/unwrap and mint/burn (zero address) **DeFi / supply:** on Robinhood, transfers from or to the zero address are most often **WETH wrap/unwrap**. For other tokens they can also represent mints or burns. Filter by `Currency.SmartContract` when you care about one asset. ### From zero (wrap-in / mint) ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Sender: { is: "0x0000000000000000000000000000000000000000" } Currency: { Native: false } Success: true } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Name Symbol SmartContract } } Transaction { Hash } Block { Time } } } } ``` ### To zero (unwrap / burn) ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Receiver: { is: "0x0000000000000000000000000000000000000000" } Currency: { Native: false } Success: true } } limit: { count: 10 } orderBy: { descending: Block_Time } ) { Transfer { Amount Sender Receiver Currency { Name Symbol SmartContract } } Transaction { Hash } Block { Time } } } } ``` --- ## Transfers between two addresses **Compliance / accounting:** activity between two addresses (example: high-activity sample address ↔ WETH). Replace either side with the pair you care about. ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { any: [ { Transfer: { Sender: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } Receiver: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } } } { Transfer: { Sender: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } Receiver: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } } } ] Transfer: { Success: true } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol Native } } Transaction { Hash } Block { Time } } } } ``` --- ## Address volume: sent vs received **Accounting / tax / portfolio:** aggregate transfer counts and volumes for an address over the last 24 hours. Results group by currency. Use `combined` so the full day is covered regardless of realtime depth. Replace the sample address with yours. ```graphql { EVM(network: robinhood, dataset: combined) { sent: Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Sender: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } Success: true } } limit: { count: 50 } orderBy: { descendingByField: "usd" } ) { Transfer { Currency { Symbol SmartContract Native } } count usd: sum(of: Transfer_AmountInUSD) amount: sum(of: Transfer_Amount) } received: Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Receiver: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } Success: true } } limit: { count: 50 } orderBy: { descendingByField: "usd" } ) { Transfer { Currency { Symbol SmartContract Native } } count usd: sum(of: Transfer_AmountInUSD) amount: sum(of: Transfer_Amount) } } } ``` --- ## Top counterparties for an address **Compliance / AML:** who received the most USD volume from an address in the last 24 hours. The `AmountInUSD > 0` filter limits this to native ETH flows; drop it and rank `count` (or per-token `amount`) to include token counterparties. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Sender: { is: "0xcaf681a66d020601342297493863e78c959e5cb2" } Success: true AmountInUSD: { gt: "0" } } } limit: { count: 20 } orderBy: { descendingByField: "usd" } ) { Transfer { Receiver Currency { Symbol Native } } count usd: sum(of: Transfer_AmountInUSD) } } } ``` --- ## Most transferred tokens (24h) **Trading / market structure:** rank currencies by **transfer count**. Ranking by summed USD only works for native ETH (every other token sums to `0`), so activity count is the meaningful network-wide leaderboard; USD volume is kept as a secondary column. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Success: true } } limit: { count: 20 } orderBy: { descendingByField: "transfers" } ) { Transfer { Currency { Name Symbol SmartContract Native } } transfers: count usd_volume: sum(of: Transfer_AmountInUSD) senders: uniq(of: Transfer_Sender) } } } ``` --- ## Top receivers by ETH inflow (liquidity hubs) **DeFi / trading:** addresses receiving the most native ETH (USD) in 24 hours — often routers, pools, or bridges. Use `combined` for the full 24h window. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Success: true Currency: { Native: true } AmountInUSD: { gt: "0" } } } limit: { count: 20 } orderBy: { descendingByField: "usd_in" } ) { Transfer { Receiver } count usd_in: sum(of: Transfer_AmountInUSD) } } } ``` --- ## Token accumulation: top receivers of a meme token **Trading / analytics:** who accumulated the most units of a token over a window (exclude zero address). Use `combined` for a 48h window. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 48 } } } Transfer: { Currency: { SmartContract: { is: "0xd387e5bba711457faf4d013d20e02e8c91f07fa4" } } Success: true Receiver: { not: "0x0000000000000000000000000000000000000000" } } } limit: { count: 20 } orderBy: { descendingByField: "amount" } ) { Transfer { Receiver Currency { Symbol SmartContract } } count amount: sum(of: Transfer_Amount) } } } ``` --- ## Unique senders and receivers for a token **Distribution / compliance:** count distinct participants for WETH over 24 hours. Note `usd` comes back `0` here — WETH carries no USD enrichment (see [the USD note](#network-and-useful-contracts)). ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Currency: { SmartContract: { is: "0x0bd7d308f8e1639fab988df18a8011f41eacad73" } } Success: true } } ) { count receivers: uniq(of: Transfer_Receiver) senders: uniq(of: Transfer_Sender) usd: sum(of: Transfer_AmountInUSD) } } } ``` --- ## ETH transfer size statistics (24h) **Market microstructure:** distribution stats for native ETH transfer sizes — average, median, and 90th percentile in one aggregate call. Expect a long-tail distribution: the average typically sits far above the median. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 24 } } } Transfer: { Currency: { Native: true } Success: true AmountInUSD: { gt: "0" } } } ) { count total_usd: sum(of: Transfer_AmountInUSD) avg_usd: average(of: Transfer_AmountInUSD) median_usd: median(of: Transfer_AmountInUSD) p90_usd: quantile(of: Transfer_AmountInUSD, level: 0.9) senders: uniq(of: Transfer_Sender) } } } ``` Also available: `standard_deviation`, other `quantile` levels, and `count(distinct: …)` for exact distinct counts (`uniq` is approximate). --- ## Hourly ETH transfer volume **Trading / ops:** time series of native ETH transfer count and USD volume (12 hours). Use `combined` so the whole window is covered. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 12 } } } Transfer: { Currency: { Native: true } Success: true AmountInUSD: { gt: "0" } } } orderBy: { ascendingByField: "Block_Time" } limit: { count: 12 } ) { Block { Time(interval: { in: hours, count: 1 }) } count usd: sum(of: Transfer_AmountInUSD) eth: sum(of: Transfer_Amount) } } } ``` --- ## Daily transfer volume (7 days) **Dashboards:** one row per day — total transfers, ETH-denominated USD volume, and how many distinct tokens moved. ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Time: { since_relative: { days_ago: 7 } } } Transfer: { Success: true } } limit: { count: 7 } orderBy: { descendingByField: "Block_Time" } ) { Block { Time(interval: { in: days, count: 1 }) } count usd: sum(of: Transfer_AmountInUSD) tokens: uniq(of: Transfer_Currency_SmartContract) } } } ``` Remember the USD column reflects native ETH only; token flows are counted but not USD-valued. --- ## Transfer types breakdown Understand how transfers are classified on Robinhood (`token`, `call`, `transaction`). ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Block: { Time: { since_relative: { hours_ago: 6 } } } Transfer: { Success: true } } limit: { count: 10 } orderBy: { descendingByField: "count" } ) { Transfer { Type } count } } } ``` --- ## Failed transfers **Ops / compliance:** transfers marked `Transfer.Success: false` (often tied to reverted execution). Include `Call` fields for context. :::note Transfer Success vs Call Success `Transfer.Success` and `Call.Success` are independent. You can see `Transfer.Success: false` with `Call.Success: true` and `Call.Reverted: true` (or other combinations). For forensics, return both. ::: ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Success: false } } limit: { count: 20 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Success Type Sender Receiver Currency { Name Symbol SmartContract } } Call { Error Reverted Success Signature { Name } } Transaction { Hash From To } Block { Time } } } } ``` --- ## Historical transfers by date Use `dataset: combined` (or `archive`) with `Block.Date` for ledgers and backfills. Example: large USD transfers between two calendar dates. :::note after/before are exclusive `Date.after: "2026-07-20"` with `Date.before: "2026-07-22"` returns **only 2026-07-21** (both bounds excluded). Use `since` / `till` when you want inclusive bounds. ::: ```graphql { EVM(network: robinhood, dataset: combined) { Transfers( where: { Block: { Date: { after: "2026-07-20" before: "2026-07-22" } } Transfer: { AmountInUSD: { gt: "10000" } Success: true } } limit: { count: 20 } orderBy: { descending: Transfer_AmountInUSD } ) { Transfer { Amount AmountInUSD Sender Receiver Currency { Symbol Native SmartContract } } Transaction { Hash } Block { Time Date Number } } } } ``` --- ## Full transfer context (log, call, receipt) **Forensics / indexers:** join transfer value with log signature, call path, receipt status, and gas. ```graphql { EVM(network: robinhood, dataset: realtime) { Transfers( where: { Transfer: { Currency: { Native: false } Type: { is: token } Success: true } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Transfer { Amount AmountInUSD Sender Receiver Type Index Id Success Currency { Name Symbol SmartContract Native } } Log { Index SmartContract Signature { Name Signature SignatureHash } } Call { From To Success Reverted Signature { Name } } Receipt { Status GasUsed } Transaction { Hash From To CostInUSD ValueInUSD Gas GasPrice } Block { Number Time Hash } } } } ``` --- ## Response fields (quick reference) | Group | Useful fields | | --- | --- | | **Transfer** | `Amount`, `AmountInUSD`, `Sender`, `Receiver`, `Type`, `Success`, `Index`, `Id`, `Currency.*` | | **Currency** | `Name`, `Symbol`, `SmartContract`, `Native` | | **Transaction** | `Hash`, `From`, `To`, `Value`, `ValueInUSD`, `Cost`, `CostInUSD`, `Gas`, `GasPrice` | | **Block** | `Number`, `Time`, `Date`, `Hash` | | **Log / Call / Receipt** | Event signature, call path, revert/error, receipt status | Aggregations: `count` (with `distinct:`/`if:`), `sum`, `average`, `median`, `quantile`, `standard_deviation`, `uniq`, plus argmin/argmax via `Field(minimum: Other_Field)` / `Field(maximum: Other_Field)` (used above to read dataset window bounds). For the full cube shape, see [EVM Transfers](/docs/schema/evm/transfers/). --- ## Tips for fast, useful queries 1. Always scope with `network: robinhood` and prefer a time window (`Block.Time` / `Block.Date`) on aggregates. 2. Realtime depth **varies** (anywhere from hours to days) — never assume it; use `combined` for any fixed window (24h/48h/7d) and `archive` for full history. Measure the current window with the [dataset window query](#check-the-dataset-window). 3. Filter WebSocket subscriptions in production — unfiltered Robinhood transfer streams are very noisy. Connect with the `graphql-transport-ws` subprotocol and the token in the URL ([WebSocket auth](/docs/authorization/websocket/)). 4. Use `Transfer.Success: true` unless you specifically want failed flows; check `Call.Success` / `Call.Reverted` separately when debugging. 5. `AmountInUSD` is effectively **native-ETH-only** on Robinhood transfers — use it for ETH whales; use `Amount` for USDG (≈ dollars), tokenized stocks (shares), and meme tokens. 6. Exclude the zero address when you want address-to-address or whale alerts without wrap/unwrap noise. 7. Ticker symbols collide (two GME contracts observed) — resolve and pin `Currency.SmartContract` in production. 8. Keep `limit` tight on fact queries; use `sum` / `count` / `uniq` / `median` / `quantile` for analytics instead of pulling millions of rows. 9. For live products, start from the whale, wallet-tracker, or token subscription patterns above, then backfill with `combined` / `archive` date windows. --- ## FAQ ### How do I query Robinhood transfers with GraphQL? Use the `EVM` root with `network: robinhood` and the `Transfers` cube (same EVM Transfers API, Robinhood network). Add `dataset: realtime` for recent data, or `combined` / `archive` for longer history. ### How do I stream Robinhood transfers in real time? Use a GraphQL `subscription` on `EVM(network: robinhood) { Transfers { ... } }` over WebSocket (`graphql-transport-ws` subprotocol). Filter by token, address, or `AmountInUSD` for whale alerts — avoid unfiltered production streams. ### How do I get whale transfers on Robinhood? Filter `Transfer.AmountInUSD` with `gt`, set `Success: true`, and exclude the zero address — this captures large native ETH moves. For USDG and tokens (where `AmountInUSD` is `0`), filter by `Transfer.Amount` instead. ### How do I get all transfers for an address? Use `where.any` with `Transfer.Sender` and `Transfer.Receiver` set to the same address. Split into inbound-only or outbound-only filters when you need deposits vs withdrawals, or use the [wallet-tracker subscription](#stream-transfers-for-an-address-wallet-tracker) for live updates. ### How far back does the realtime dataset go? It varies — realtime is a rolling window of recent blocks; its depth changes over time. Measure it with the [dataset window query](#check-the-dataset-window), and switch to `combined` whenever your window must be complete. ### Why is AmountInUSD 0 for WETH, USDG, or stock tokens? USD enrichment on the Robinhood Transfers cube effectively covers native ETH only — WETH and USDG rows return `$0` as well. Use `Transfer.Amount` (USDG ≈ dollars, stock tokens ≈ shares) or join prices from the [Trades API](/docs/blockchain/robinhood/robinhood-trades/). ### How do I get hourly or daily transfer volume? Group with `Block { Time(interval: { in: hours, count: 1 }) }` (or `in: days`) plus `count` / `sum` aggregates on `dataset: combined` — see the [hourly](#hourly-eth-transfer-volume) and [daily](#daily-transfer-volume-7-days) examples. --- ## 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/). ::: --- ## 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! ::: --- ## Slippage Faq Using Dexpool Stream URL: https://docs.bitquery.io/docs/API-Blog/slippage-faq-using-dexpool-stream/ Slippage Faq Using Dexpool Stream: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 --- ## Smart Contract Creation URL: https://docs.bitquery.io/docs/blockchain/Ethereum/calls/contract-creation/ Smart Contract Creation: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # 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 } } } } } ``` --- ## SmartContract Calls API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/calls/smartcontract/ SmartContract Calls API: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. Scale further with Kafka or gRPC streams. # SmartContract 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 } } } } ``` --- ## Solana API - DEX Trades, Token Data, Real-Time Streams URL: https://docs.bitquery.io/docs/blockchain/Solana/ Solana API - DEX Trades, Token Data, Real-Time Streams: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. # Solana 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 **9 chains in one API**. For **historical Solana data older than ~30 days**, use the chain-level `DEXTrades` / `DEXTradeByTokens` APIs documented below. ::: 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 DYN 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) - [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/) ## Other Solana APIs - [Solana Balance Updates](/docs/blockchain/Solana/solana-balance-updates) - [Token Supply Cube](/docs/blockchain/Solana/token-supply-cube) - [Solana Instructions](/docs/blockchain/Solana/solana-instructions) - [Solana Transactions](/docs/blockchain/Solana/solana-transactions) - [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) - [BonkSwap API](/docs/blockchain/Solana/letsbonk-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 Aldrinamm API URL: https://docs.bitquery.io/docs/blockchain/Solana/Solana-AldrinAmm-api/ Solana Aldrinamm API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Run it in the IDE, then ship in your app. # 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 **9 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 The below query gets real-time information whenever there's a new trade on the AldrinAmm DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. You can run the query [here](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 You can use the following query to get the latest price of a token on AldrinAmm on Solana. You can run this query using this [link](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 The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on AldrinAmm. 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-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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on AldrinAmm DEX. Try out the API [here](https://ide.bitquery.io/trade_volume_aldrinAmm). ```graphql query MyQuery { Solana(dataset: combined) { 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: "AldrinAmm"}}}} ) { 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 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. [Here](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-AldrinAmm-Dex-on-Solana_1) is the query to get the volatility for a selected pair in 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 & Balance Updates API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-balance-updates/ Solana Balance & Balance Updates API: fetch current and historical Solana balances with Bitquery GraphQL balance queries. # Solana Balance & 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](https://ide.bitquery.io/top-100-holders-of-USDC-token-on-Solana) returns all token holders of a particular token after a given time. ```graphql query MyQuery { Solana { BalanceUpdates( orderBy: {descendingByField: "BalanceUpdate_Holding_maximum"} where: {BalanceUpdate: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, }, Transaction: {Result: {Success: true}}} ) { BalanceUpdate { Currency { Name MintAddress Symbol } Account { Address } Holding: PostBalance(maximum: Block_Slot selectWhere:{gt:"0"}) } } } } ``` ## 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 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 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/ Solana Boop Fun API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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 **9 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 Builder Terms Explaination: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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 Builder Terms Explanation: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. # 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/ Solana Bullx API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Covers archive history and realtime data. # 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 **9 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 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 BullX 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 BullX 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/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 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?_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 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 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#). ```graphql query MyQuery { Solana(dataset: combined) { DEXTradeByTokens( where: {Block: {Time: {since: "2025-02-10T07:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "token mint address"}}, 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}}}}) } } } ``` --- ## Solana Byreal API URL: https://docs.bitquery.io/docs/blockchain/Solana/byreal-api/ Solana Byreal API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Covers archive history and realtime data. # 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 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 API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Scale further with Kafka or gRPC streams. # 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 **9 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 Need real-time Solana DEX pool 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 pool swaps with **USD price, market cap, and supply on every row** across **9 chains in one API**. Use this page when you need **historical Solana DEX pool data older than ~30 days**, raw per-swap detail, or call / event context. Pool and liquidity data ships with the [Solana DEX API](https://bitquery.io/products/solana-dex-api) — the product page 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 Price PriceInUSD } Quote { ChangeAmount PostAmount Price PriceInUSD } 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 Price PriceInUSD } 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) } } } } } { "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 Liqudity [This](https://ide.bitquery.io/latest-price-based-on-liquidity_2) subscription given below returns the latest and real-time price and other info related to the token, DEX and market for the following token `LMFzmYL6y1FX8HsEmZ6yNKNzercBmtmpg2ZoLwuUboU`.
Click to expand GraphQL query ```graphql subscription { Solana { DEXPools( where: { Pool: { Market: { BaseCurrency: { MintAddress: { is: "So11111111111111111111111111111111111111112" } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Pool { Base { ChangeAmount PostAmount Price PriceInUSD } Dex { ProgramAddress ProtocolFamily } Market { BaseCurrency { MintAddress Name Symbol } MarketAddress } } } } } ```
## 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 PriceInUSD } 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 Price PriceInUSD } Quote { ChangeAmount ChangeAmountInUSD PostAmount PostAmountInUSD Price PriceInUSD } 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 Price PriceInUSD } Quote { ChangeAmount ChangeAmountInUSD PostAmount PostAmountInUSD Price PriceInUSD } 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 PriceInUSD 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 PriceInUSD 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 PriceInUSD 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 PriceInUSD 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 PriceInUSD 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 PriceInUSD PostAmountInUSD } Base { ChangeAmount PostAmount } } } } } ```
--- ## 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 **9 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 `dataset: combined` currently fails on Solana Every `Solana(dataset: combined)` query tested returns a ClickHouse 500 on the `/graphql` endpoint. Use `dataset: archive` for history and realtime for recent data. Several queries further down this page still use `combined` and will error until that is resolved — swap `combined` for `archive` to run them. 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 fills are not in this cube Off-chain-quoted trades (Jupiter Z, Jupiter Limit Order v2, Mayan Swift, HumidiFi, Tessera V, ZeroFi) settle without a pool, so they produce no `Trade` object and return zero rows here. Query them through the [Solana RFQ API](/docs/blockchain/Solana/solana-rfq-api/) instead. ::: 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/) ::: ## 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/). You can find the query [here](https://ide.bitquery.io/solana-trades-subscription_3)
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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. You can find the query [here](https://ide.bitquery.io/Latest-Trades-of-Trump-COin)
Click to expand GraphQL query ```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) Check data here 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)
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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).
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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.
Click to expand GraphQL query ```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 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 } } } } } } ```
## 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)
Click to expand GraphQL query ```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: combined) { 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.
Click to expand GraphQL query ```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. You can find the query [here](https://ide.bitquery.io/DEX-Markets-for-a-token)
Click to expand GraphQL query ```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) Check data here 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)
Click to expand GraphQL query ```graphql { Solana(dataset: combined) { 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)
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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. You can find the query [here](https://ide.bitquery.io/Top-Bought-Solana-Tokens)
Click to expand GraphQL query ```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}}}}) } } } ```
Arranged in the descending order of `bought - sold` on [DEXrabbit](https://dexrabbit.bitquery.io/solana). ![image](https://github.com/user-attachments/assets/20872a56-f02a-4323-889a-605ff7947a13) Check data here on [DEXrabbit](https://dexrabbit.bitquery.io/solana). ## Get Top Sold Tokens on Solana This query will give you most sold Solana Tokens on Raydium. You can find the query [here](https://ide.bitquery.io/Top-sold-Solana-Tokens)
Click to expand GraphQL query ```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}}}}) } } } ```
Arranged in the descending order of `sold - bought` on [DEXrabbit](https://dexrabbit.bitquery.io/solana). ![image](https://github.com/user-attachments/assets/216bfb28-d365-4a9e-b280-ae19562d7600) Check data here on [DEXrabbit](https://dexrabbit.bitquery.io/solana). ## Get Top Traded Pairs in terms of volume This query will give you top traded pairs data. You can find the query [here](https://ide.bitquery.io/top-trading-pairs)
Click to expand GraphQL query ```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) Check data here on [DEXrabbit](https://dexrabbit.bitquery.io/solana/pair). ## Get Top DEXs information This query will give you top DEXs info. You can find the query [here](https://ide.bitquery.io/top-dexs)
Click to expand GraphQL query ```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) Check data here 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`. You can find the query [here](https://ide.bitquery.io/traded-pairs-of-a-token)
Click to expand GraphQL query ```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) Check data here 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)
Click to expand GraphQL query ```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#).
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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).
Click to expand GraphQL query ```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).
Click to expand GraphQL query ```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).
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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#).
Click to expand GraphQL query ```graphql query MyQuery { Solana(dataset: combined) { 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)
Click to expand GraphQL query ```graphql { Solana(dataset: combined) { 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)
Click to expand GraphQL query ```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. :::
Click to expand GraphQL query ```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) Check data here on [DEXrabbit](https://dexrabbit.bitquery.io/solana/pair/9Fv7n7HuA5EzjCRSvprBMx2Qhd1VL3hPEXKhTUKPm1Qh/So11111111111111111111111111111111111111112). ## 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.
Click to expand GraphQL query ```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.
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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)
Click to expand GraphQL query ```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#).
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 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 Data - Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Solana Data Bitquery provides **Solana blockchain data dumps** in **Parquet format**, 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 ``` ## Real-Time vs Batch Data Access Cloud data dumps 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/) - **GraphQL subscriptions** --- ## 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 [PumpFun 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 Goonfi API URL: https://docs.bitquery.io/docs/blockchain/Solana/goonfi-api/ Solana Goonfi API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Covers archive history and realtime data. # GoonFi API :::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 **9 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 The below query gets real-time information whenever there's a new trade on the GoonFi DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. You can run the query [here](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. Run the query [in the Bitquery IDE](https://ide.bitquery.io/specific-goonfi-v2-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: { Program: { is: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE" } } } ) { 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 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 You can use the following query to get the latest price of a token on GoonFi on Solana. You can run this query using this [link](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 You can use the following query to get the latest price of a token on GoonFi on Solana. You can run this query using this [link](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 If you want to get OHLC data for any specific currency pair on GoonFi, you can use this api. Only use [this API](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 The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on GoonFi. 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/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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`. Try out the API [here](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token-on-GoonFi-DEX_1). ```graphql query MyQuery { Solana(dataset: combined) { 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: "goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE"}}}} ) { 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 Heaven DEX API URL: https://docs.bitquery.io/docs/blockchain/Solana/heaven-dex-api/ Solana Heaven DEX API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Includes filters and field selection tips. # 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 **9 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 You can use the following query to get the latest price of a token on Heaven DEX on Solana. 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 The below query gets the Top Traders of the specified Token `G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777` on Heaven 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/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 query fetches you the traded volume, buy volume and sell volume of a token `G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777`. Try out the API [here](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-heaven-dex-token).
Click to expand GraphQL query ```graphql query MyQuery { Solana(dataset: combined) { DEXTradeByTokens( where: {Block: {Time: {since_relative: {hours_ago: 1}}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "G9z2bN7rqxdoN526H4XzdLNWt8Wy8GdbqwNFSrpMv777"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProgramAddress: {is: "HEAVENoP2qxoeuF8Dj2oT1GHEnu49U5mJYkdeC8BAX2o"}}}} ) { 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}}}} ) } } } ```
## 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. 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 through [cloud datasets](/docs/cloud/solana). Every query on this page runs as written in the [Bitquery IDE](https://ide.bitquery.io) on a free account. The trial includes complete history; paid self-service plans add Solana history through the archive packs on the [pricing page](https://bitquery.io/pricing). | 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 | | 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 | Cloud datasets as Parquet on S3, GCS, Snowflake or BigQuery | Full history per dataset | Backtesting and warehouses | Retention per cube is on the [data coverage and retention](/docs/graphql/data-coverage-retention) page. :::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** | — | | `Trade.Side.AmountInUSD`, `Trade.AmountInUSD` | **error** | works — `sum(of: Trade_Side_AmountInUSD)` | | `Trade.PriceInUSD` | **error** | works — `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/).** [This](https://ide.bitquery.io/historical-Solana-trades_1) example showcase how trades for the duration of upto past 30 days could be recieved via 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/eap", 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, [cloud datasets](/docs/cloud/solana) 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: combined) { 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: combined) { 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: combined) { 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: combined) { 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: combined) { 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: combined) { 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: combined) { 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: combined) { 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: combined) { 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. For **SPL transfers and older history**, use the **[V1 Solana examples](https://docs.bitquery.io/v1/docs/Examples/Solana/transfers)**. All other chains have complete historical data. ## What fields are available in Solana DEXTradeByTokens with dataset: combined? **`Solana(dataset: combined)`** (and **`archive`**) **`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; the trial includes complete history | ## 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 cloud datasets](/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 API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Great for bots, dashboards, and alerts. # 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/ Solana Jito Bundle API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Built for traders and analytics teams. # 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 **9 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 **9 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 and Jupiter Limit Order v2, neither of which appears in DEX trade 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/) ::: --- ### 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 Monitor real-time Jupiter limit order creation with comprehensive details including input/output tokens, maker addresses, and order parameters. We track Jupiter's Limit Order program address `jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu` for `initializeOrder` instructions. 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 Monitor real-time Jupiter limit order cancellations with detailed transaction information including maker addresses, token details, and cancellation parameters. We track Jupiter's Limit Order program address `jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu` for `cancelOrder` instructions. 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 Monitor real-time Jupiter expired limit order cancellations with comprehensive transaction details and account information. We track Jupiter's Limit Order program address `jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu` for `cancelExpiredOrder` instructions. 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 Create Limit Order, Cancel Limit Order and Cancel Expired Limit Order Transactions on Jupiter --- ## 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 **9 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. Access real-time data for Jupiter Studio token launches, trading activity, migration events, and Meteora Dynamic Bonding Curve insights through our Jupiter Studio API. 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 Jupiter studio tokens are launched and traded on Meteora DBC. So a Jup Studio token follows a lifecycle of a Meteora DBC Token. ::: :::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 Real-Time Jupiter Studio Token Trades ➤](#track-real-time-jupiter-studio-token-trades) - [Get Latest Price of Jupiter Studio Token ➤](#get-latest-price-of-jupiter-studio-token) - [Jupiter Studio Token OHLC Data ➤](#jupiter-studio-token-ohlc-data) - [Get Trading Volume & Analytics ➤](#get-trading-volume--analytics) ### 2. Jupiter Studio Token Launches & Migration - [Track Latest Jupiter Studio Token Launches ➤](#track-latest-jupiter-studio-token-launches-on-meteora-dbc) - [Monitor Jupiter Studio Token Migrations ➤](#monitor-jupiter-studio-token-migrations) - [Check Token Migration Status ➤](#check-token-migration-status) ### 3. Jupiter Studio Trader Insights - [Get Top Traders of Jupiter Studio Token ➤](#get-top-traders-of-jupiter-studio-token) ## Jupiter Studio Trading & Market Data ### Track Real-Time Jupiter Studio Token Trades Get real-time Jupiter Studio token trades on Meteora Dynamic Bonding Curve with comprehensive trade details including buy/sell information, account addresses, and transaction specifics. We monitor Jupiter Studio tokens (ending with "jups") trading on Meteora DBC program address `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN`. The query returns detailed trade information including currency details, amounts, prices, and account addresses. [Jupiter Studio Token Trades — Stream ➤](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 Latest Jupiter Studio Token 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. [Jupiter Studio Token Launches — Stream ➤](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 } } } } ```
## Jupiter Studio Token Launches & Migration ### Monitor Jupiter Studio Token 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. [Jupiter Studio Token Migrations — Stream ➤](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 Token Migration Status Check if specific Jupiter Studio tokens have migrated from Meteora DBC to Meteora DEX with detailed migration history and transaction information. [Jupiter Studio Migration Status Check — Query ➤](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 Latest Price of Jupiter Studio Token Get the most recent price data for a specific Jupiter Studio token trading on Meteora Dynamic Bonding Curve with comprehensive price information. [Jupiter Studio Token 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 } } } } } ```
### Jupiter Studio Token OHLC Data 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. ::: [Jupiter Studio Token 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 Get comprehensive trading volume analytics for Jupiter Studio tokens including total volume, buy volume, sell volume, and USD value analysis. [Jupiter Studio Trading 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: combined) { 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 Top Traders of Jupiter Studio Token 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. ::: [Jupiter Studio 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 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 **9 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 The below query gets real-time information whenever there's a new trade on the Lifinity DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. 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 You can use the following query to get the latest price of a token on Lifinity on Solana. You can run this query using this [link](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 The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on Lifinity. 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-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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on Lifinity DEX. Try out the API [here](https://ide.bitquery.io/trade_volume_lifinity). ```graphql query MyQuery { Solana(dataset: combined) { 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. [Here](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-Lifinity-Dex-on-Solana) is the query to get the volatility for a selected pair in 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 Logs API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-logs/ Solana Logs: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Covers archive history and realtime data. # 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 Meteora Damm V2 API URL: https://docs.bitquery.io/docs/blockchain/Solana/Meteora-DAMM-v2-API/ Solana Meteora Damm V2 API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Keep queries fast with indexed filters. # Meteora DAMM v2 API :::tip Need real-time Meteora DAMM v2 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 Meteora DAMM v2 swaps with **USD price, market cap, and supply on every row** across **9 chains in one API**. Use this page when you need **historical Meteora DAMM v2 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 from Meteora's Dynamic Automated Market Maker (DAMM) v2. ## Meteora DAMM v2 API Guide In this section we will see how to get data on Meteora DAMM v2 trades in real-time. According to the official Meteora documentation, DAMM v2 is a Dynamic Automated Market Maker that provides efficient price discovery and liquidity provision for token pairs on Solana. :::note `Trade Side Account` field will not be available as aggregates in Archive and Combined Datasets ::: ## Subscribe to Realtime DAMM v2 Trades This query subscribes to real-time trades on the Meteora DAMM v2 (Dynamic Automated Market Maker) on the Solana blockchain by filtering using the program address `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG`. You can run the query [here](https://ide.bitquery.io/Real-time-trades-on-MeteoraDAMMv2-DEX-on-Solana) ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG" } } } } ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Currency { Name Symbol MintAddress Decimals Fungible Uri } Amount Account { Address } PriceAgainstSellCurrency: Price } Sell { Account { Address } Amount Currency { Name Symbol MintAddress Decimals Fungible Uri } PriceAgainstBuyCurrency: Price } } Block { Time } Transaction { Signature } } } } ``` ## Latest Pool Creation on Meteora DAMM v2 The below query tracks latest pool creation on Meteora DAMM v2. The `"Program": {"AccountNames"}` includes the order in which account addresses are mentioned in `Accounts` list. This includes pool creator, token vaults and token mints for the tokens being used in the pool. The mint addresses for the tokens being used in the pool are listed, indicating which tokens the DAMM v2 pool will support. You can test the query [here](https://ide.bitquery.io/Track-Latest-created-pools-on-Meteora-DAMM-v2) ```graphql subscription MyQuery { Solana { Instructions( where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Method: {is: "EvtInitializePool"}, Address: {is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}}}} ) { 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 } } } } ``` ## Latest Price of a Token on Meteora DAMM v2 You can use the following query to get the latest price of a token on Meteora DAMM v2 on Solana. This query fetches the most recent trade data for a specific token pair. You can run this query using this [link](https://ide.bitquery.io/latest-price-of-a-token-on-Damm-v2). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Realtime Price Feed of a Token on Meteora DAMM v2 You can use the following subscription to get real-time price updates of a token on Meteora DAMM v2 on Solana. This provides live price data as new trades occur. You can run this query using this [link](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-Meteora-DAMM-v2). ```graphql subscription{ Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProgramAddress: {is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Meteora DAMM v2 OHLC API If you want to get OHLC (Open, High, Low, Close) data for any specific currency pair on Meteora DAMM v2, you can use this API. This provides technical analysis data for charting and trading strategies. :::note Only use this API as a query and not as a subscription websocket, as Aggregates and Time Intervals don't work well with subscriptions. ::: You can run this query [here](https://ide.bitquery.io/Meteora-DAMM-v2-OHLC-API). ```graphql { Solana { DEXTradeByTokens( orderBy: {descendingByField: "Block_Timefield"} where: {Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, Dex: {ProgramAddress: {is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}}, 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 Meteora DAMM v2 DEX The below query gets the Top Traders of the specified Token on Meteora DAMM v2. This provides insights into the most active traders and their trading patterns. :::note 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/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DAMM-v2-DEX_1) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProgramAddress: {is: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}}}, 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 query fetches the traded volume, buy volume and sell volume of a specific token on Meteora DAMM v2. This provides comprehensive volume analytics for trading insights and market analysis. Try out the API [here](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token_2). ```graphql query MyQuery { Solana(dataset: combined) { 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: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"}}}} ) { 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}}}} ) } } } ``` ## Related Documentation - [Meteora DLMM API](/docs/blockchain/Solana/Meteora-DLMM-API/) - [Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/) - [Solana Token Holders API](/docs/blockchain/Solana/solana-token-holders/) - [Real-time Solana Data Streams](/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/) --- ## Solana Meteora Dyn API URL: https://docs.bitquery.io/docs/blockchain/Solana/Meteora-DYN-API/ Solana Meteora Dyn API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Keep queries fast with indexed filters. # Meteora API - DYN :::tip Need real-time Meteora DYN 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 Meteora DYN swaps with **USD price, market cap, and supply on every row** across **9 chains in one API**. Use this page when you need **historical Meteora DYN data older than ~30 days**, raw per-swap detail, or call / event context. ::: ## Track Latest created pools on Meteora DYN Below query will give you the latest created Meteora DYN pools in realtime. You can test the query [here](https://ide.bitquery.io/Track-Latest-created-pools-on-MeteoraDYN) ```graphql subscription MyQuery { Solana { Instructions( where: {Transaction: {Result: {Success: true}}, Instruction: {Program: {Method: {is: "initializePermissionlessConstantProductPoolWithConfig2"}, Address: {is: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB"}}}} ) { 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 } } } } ``` ## Meteora DYN Trades in Real-Time The below query gets real-time information whenever there's a new trade on the Meteora DYN DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. You can run the query [here](https://ide.bitquery.io/Real-time-trades-on-MeteoraDYN-DEX-on-Solana#) ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProgramAddress: { is: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB" } } } } ) { 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 Meteora DYN You can use the following query to get the latest price of a token on Meteora DYN on Solana. You can run this query using this [link](https://ide.bitquery.io/latest-price-of-a-token-on-DYN#). ```graphql { Solana { DEXTradeByTokens( limit: {count: 1} orderBy: {descending: Block_Time} where: {Trade: {Dex: {ProgramAddress: {is: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Realtime Price feed of a Token on Meteora DYN You can use the following query to get the latest price of a token on Meteora DYN on Solana. You can run this query using this [link](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-Meteora-DYN#). ```graphql subscription{ Solana { DEXTradeByTokens( where: {Trade: {Dex: {ProgramAddress: {is: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB"}}, Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Block { Time } Trade { Price PriceInUSD } } } } ``` ## Meteora DYN OHLC API If you want to get OHLC data for any specific currency pair on Meteora DYN, you can use this api. Only use [this API](https://ide.bitquery.io/Meteora-DYN-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: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB"}}, 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 Meteora DYN DEX The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on Meteora DYN. 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/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DYN-DEX#) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volumeUsd"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}, Dex: {ProgramAddress: {is: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB"}}}, 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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`. Try out the API [here](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token_4#). ```graphql query MyQuery { Solana(dataset: combined) { 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: "Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB"}}}} ) { 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 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 **9 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 here](/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 **9 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 The below query gets real-time information whenever there's a new trade on the OpenBook DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. You can run the query [here](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 [Here](https://ide.bitquery.io/Average-Price-for-24-hours-of-a-token-on-OpenBook-DEX-on-Solana_1) is the query to get average price of a selected pair on a selected 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 To get all the Instructions associated with OpenBook v2, we will utilize the Solana instructions API. You can run this query using this [link](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 We will use this subscription to listen to transactions that are placing orders on OpenBook v2. We will utilize the Solana instructions API. You can also watch a Youtube Tutorial for a better understand [here](https://www.youtube.com/watch?v=B-3w1t-tnwE). You can run this query using this [link](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 We will use this subscription to listen to `consumeEvents` transactions on OpenBook v2. This instruction processes trade events and other activities such as order cancellations. It updates the order book and ensures that all relevant trade activities are accounted for and settled. We will utilize the Solana instructions API. You can also watch a Youtube TUtorial for a better understand [here](https://www.youtube.com/watch?v=B-3w1t-tnwE). You can run this query using this [link](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 You can use the following query to get the latest price of a token on OpenBook on Solana. You can run this query using this [link](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 The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on OpenBook. 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-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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on OpenBook DEX. Try out the API [here](https://ide.bitquery.io/trade_volume_openbook). ```graphql query MyQuery { Solana(dataset: combined) { DEXTradeByTokens( where: {Block: {Time: {since: "2025-03-10T07:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, Dex: {ProtocolFamily: {is: "OpenBook"}}}} ) { 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 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. [Here](https://ide.bitquery.io/Volatility-of-USDC-on-OpenBook-Dex-on-Solana) is the query to get the volatility for a selected token in 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/ Solana Orbic API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Includes filters and field selection tips. # 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 **9 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 The below query gets real-time information whenever there's a new trade on the Orbic DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. 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 You can use the following query to get the latest price of a token on Orbic on Solana. You can run this query using this [link](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 You can use the following query to get the latest price of a token on Orbic on Solana. You can run this query using this [link](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 The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on Orbic. 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/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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`. Try out the API [here](https://ide.bitquery.io/Get-trading-volume-buy-volume-sell-volume-of-a-token_5#). ```graphql query MyQuery { Solana(dataset: combined) { 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 **9 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 The below query gets real-time information whenever there's a new trade on the Phoenix DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. You can run the query [here](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 You can use the following query to get the latest price of a token on Phoenix on Solana. You can run this query using this [link](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 You can use the following query to get the latest price of a token on Phoenix on Solana. You can run this query using this [link](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 If you want to get OHLC data for any specific currency pair on Phoenix, you can use this api. Only use [this API](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 The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on Phoenix. 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-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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`. Try out the API [here](https://ide.bitquery.io/trade_volume_phoenix). ```graphql query MyQuery { Solana(dataset: combined) { 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: "Phoenix"}}}} ) { 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 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. [Here](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-phoenix-Dex-on-Solana_1) is the query to get the volatility for a selected pair in 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 **9 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 legs at once. Which means the data lands somewhere most people are not looking. :::danger RFQ fills do not appear in DEX trade data `DEXTrades` and `DEXTradeByTokens` return zero rows for Jupiter Z, Jupiter Limit Order v2, Mayan Swift, HumidiFi, Tessera V and ZeroFi. There is no pool and no swap event, so no `Trade` object is ever created. A fill leaves one `Instructions` row and two `Transfers` rows. If you compute Solana volume, price or venue market share from trade tables alone, you are missing this flow, including some assets that trade nowhere else. ::: Everything here uses 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 | |---|---|---|---| | Jupiter Z (JupiterZ) | `61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH` | `order_engine` → `fill` | Same-chain RFQ. The maker signs and pays gas, the taker pays nothing. | | Jupiter Z (2nd deployment) | `2En5Y11SEAGLNmEezTuRUCwTyzyNReHaMbSnS5gjGsL1` | `order_engine` → `fill` | Same IDL and same maker set, but the taker or a relayer pays gas. | | Jupiter Limit Order v2 | `j1o2qRpjcyUwEvwtcfhEQefh773ZgjxcVRry7LDqg5X` | `limit_order_2` → `fill_order` | Resting maker orders filled by a keeper. | | Mayan Swift | `mayan34VedncxdK2XobtvWFDXQASUTBXhUVzt2kKgny` | `swift` → `init_order` / `fulfill` / `settle` | Cross-chain intent auction with competing drivers (solvers). | | 1inch Fusion | `HNarfxC3kYMMhFkxUFeYb8wHVdPzY5t9pupqW5fL2meM` | `fusion_swap` → `fill` | Dutch-auction intents. Deployed, but barely used on Solana. | ### 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 | | HumidiFi | `9H6tua7jkLhdm3w8BvgpTn5LZNU7g4ZynDmCiNN3q6Rp` | No | | Tessera V | `TessVdML9pBGgG9yGks7o4HewRaXVAMuoVj4x83GLQH` | No | | ZeroFi | `ZERor4xhbUycZ6gb9ntrhqscUcZmAbQDjEAtCf4hbZY` | No | --- ## 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 legs behave differently `Currency: { Native: false }` keeps the SPL token legs 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 leg 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 legs 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 either leg. ```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 [asset reference](#assets-that-trade-only-on-rfq). 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. --- ## Assets that trade only on RFQ Tokenized equities on Solana settle almost entirely through the RFQ order engine. Two issuers are active, xStocks from Backed (symbols ending `x`) and Ondo Global Markets (ending `on`), and a large share of their mints have no DEX trades at all. For those, the `fill` instruction is the only on-chain price print in existence. There is a structural reason. You cannot run an AMM for an asset whose underlying is closed 16 hours a day and settles in the traditional system. A broker quotes it, or it does not trade. ```graphql query TokenizedEquityRFQPrints { Solana { Instructions( limit: { count: 50 } orderBy: { descending: Block_Time } where: { Transaction: { Result: { Success: true } } Instruction: { Program: { Address: { is: "61DFfeTKM7trxYcPQCM78bJ794ddZprZpAwAnLiwTpYH" } Method: { is: "fill" } } Accounts: { includes: { Address: { in: [ "XsoCS1TfEyfFhfvj8EtZ528L3CaKBDBRqRapnBbDF2W" "Xs8S1uUs1zvS2p7iwtsG3b6fkhpvmwz4GYU3gWAmWHZ" "XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB" "Xsc9qvGR1efVDFGLrVsmkzv3qi45LTBjeUKSPmx9qEh" "XsCPL9dNWBMvFtTmwcCA5v3xWPSMEBCszbQdiLLq6aN" "Xsa62P5mvPszXL1krVUnU5ar38bBSVcWAB6fmPCo5Zu" ] } } } } } ) { Block { Time } Transaction { Signature Signer } Instruction { Accounts { Address Token { Mint Owner } } Program { Arguments { Name Value { ... on Solana_ABI_BigInt_Value_Arg { bigInteger } } } } } } } } ``` ### 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 single maker to be quoting an entire issuer's range, with the second issuer covered by one or two others. Resolve the current set from account index 1 rather than hard-coding addresses, because that is exactly the kind of thing that rotates. If the maker for a ticker stops quoting, the ticker stops trading, which makes a per-issuer maker heartbeat 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 legs 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, Aquifer and BisonFi work this way, 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 No IDL for these programs Bitquery has no IDL for HumidiFi, Tessera V or ZeroFi, so `Program.Method` and `Program.Name` come back empty and the payload arrives as raw `Instruction.Data`. You get timing, frequency, signer and account set, but not decoded quote levels. ::: --- ## 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 stable leg.** For notional, take the stablecoin side at $1 where one exists and fall back to the SOL leg 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 leg - [Solana Transfers API](/docs/blockchain/Solana/solana-transfers) - [Solana Jupiter API](/docs/blockchain/Solana/solana-jupiter-api), the aggregator and routing side - [xStocks API](/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 Raydium Clmm API URL: https://docs.bitquery.io/docs/blockchain/Solana/raydium-clmm-API/ Solana Raydium Clmm API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Keep queries fast with indexed filters. # 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 **9 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 } } } } ``` --- ## Solana Raydium Cpmm API URL: https://docs.bitquery.io/docs/blockchain/Solana/raydium-cpmm-API/ Solana Raydium Cpmm API: real-time Solana memecoin and DEX data via Bitquery GraphQL APIs and Kafka streams. Works with WebSocket live subscriptions. # 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 **9 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 } } } } ``` --- ## 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 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`) #### 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/ Solana Solfi API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Keep queries fast with indexed filters. # 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 **9 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 The below query gets real-time information whenever there's a new trade on the SolFi DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. You can run the query [here](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 You can use the following query to get the latest price of a token on SolFi on Solana. You can run this query using this [link](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 You can use the following query to get the latest price of a token on SolFi on Solana. You can run this query using this [link](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 The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on SolFi. 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-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 query fetches you the traded volume, buy volume and sell volume of a token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`. Try out the API [here](https://ide.bitquery.io/trade_volume-Solfi). ```graphql query MyQuery { Solana(dataset: combined) { 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: "Solfi"}}}} ) { 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 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 Rewards: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Scale further with Kafka or gRPC streams. # 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 API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Scale further with Kafka or gRPC streams. # 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 V1 holder queries sorted by net balance to list the largest wallets, or V2 `BalanceUpdates` ordered by `PostBalance` for fresh launches. Filter minimum `PostBalance` 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 ~8 hours of balance updates | | **Best for** | Any token, any age | Newly launched tokens (< 8 hours old) | | **Data freshness** | Lags a few minutes behind real-time | Real-time | | **Method** | Calculates holders from cumulative transfers (sum of inflows − outflows) | Reads latest balance snapshot directly | | **Query complexity** | Requires aggregation (sum, expression) | Simple — just read `PostBalance` | | **Ideal use cases** | Tokens older than 8 hours, historical holder analysis, whale tracking | Tokens launched within the last 8 hours, Pump.fun launches, fast holder snapshots | :::tip When to use which? - **Token launched more than 8 hours ago** → Use **V1 API** (complete history) - **Token launched within the last 8 hours** → Use **V2 API** (faster, simpler) - **Need both speed and history** → Combine both: V2 for the latest snapshot, V1 for historical trends ::: ## V1 API — Historical Token Holders via Transfers The V1 API calculates token holders by summing all incoming and outgoing transfers for each wallet address. This gives you **complete, accurate holder data** for any token regardless of when it was launched. **Strengths:** - Full historical coverage from token genesis - Works for any SPL token, any age - Accurate holder balances computed from on-chain transfer history **Limitation:** - Data may lag a few minutes behind real-time 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 { solana(network: solana) { transfers( date: { since: "2026-02-19" } currency: { is: "943YczGfS95e1ZnUSMd5DPQrGXaKBS2zGR76htycpump" } options: { limit: 10000, desc: "balance" } ) { sum_in: amount(calculate: sum) sum_out: amount(calculate: sum) balance: expression(get: "sum_in - sum_out") count_in: countBigInt count_out: countBigInt currency { address symbol tokenType } receiver { address } } } } ``` ### How This Query Works 1. **Fetches all transfers** for the specified token since the given date 2. **Groups by receiver address** — each row represents a unique wallet 3. **`sum_in`** — total tokens received by that wallet 4. **`sum_out`** — total tokens sent out by that wallet 5. **`balance`** — net balance calculated as `sum_in - sum_out` 6. **Results sorted** by balance in descending order — top holders first ### Customization Options **Filter by date range** — Narrow down to a specific period: ```graphql date: { since: "2026-01-01", till: "2026-02-19" } ``` **Increase result limit** — Get more holders (up to the API limit): ```graphql options: { limit: 25000, desc: "balance" } ``` **Filter out zero balances** — Only show current holders: Add a filter to exclude wallets where balance equals zero by checking `sum_in - sum_out > 0` in your application logic after receiving the results. ## V2 API — Real-Time Token Holders via Balance Updates The V2 API reads the latest balance snapshot directly from Solana's balance update records. This is **faster and simpler** but only covers the last ~8 hours of data. **Strengths:** - Real-time data with minimal delay - Simpler query — reads balance directly instead of calculating from transfers - Great for newly launched tokens and fast-moving markets **Limitation:** - Only covers the last ~8 hours of balance updates - Best suited for tokens launched within that window ### Top Token Holders Get the top 50 holders for a recently launched token using balance updates. **Try it live:** [Solana Token Holders V2](https://ide.bitquery.io/) ```graphql { Solana { BalanceUpdates( orderBy: { descendingByField: "BalanceUpdate_balance_maximum" } limit: { count: 50 } where: { BalanceUpdate: { PostBalance: { gt: "0" } Currency: { MintAddress: { is: "943YczGfS95e1ZnUSMd5DPQrGXaKBS2zGR76htycpump" } } } } ) { BalanceUpdate { Account { Owner } balance: PostBalance(maximum: Block_Slot) } } } } ``` ### How This Query Works 1. **Fetches balance update records** for the specified token mint address 2. **Filters out zero balances** — `PostBalance: { gt: "0" }` ensures only current holders are shown 3. **`PostBalance(maximum: Block_Slot)`** — gets the most recent balance by taking the value at the highest block slot 4. **Sorted by balance** in descending order — top holders first 5. **`Account.Owner`** — returns the wallet owner address ### Customization Options **Get more holders** — Increase the limit: ```graphql limit: { count: 200 } ``` **Filter by minimum balance** — Only show significant holders: ```graphql PostBalance: { gt: "1000000" } ``` ## 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 8 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 **9 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 Search API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-search-tokens/ Solana Token Search API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # 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. 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 - **[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 - **[Video Tutorials](#video-tutorials)** - Step-by-step guides ## 🔗 Related Solana APIs - **[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 } } } } ``` --- ## Token Creation Tracking ### Get newly created Pump Fun tokens, Creation Time, Dev Address, Metadata Now you can track the newly created Pump Fun Tokens along with their dev address, metadata and supply. `PostBalance` will give you the current supply for the token. Check the query [here](https://ide.bitquery.io/newly-created-PF-token-dev-address-metadata) ```graphql subscription { Solana { TokenSupplyUpdates( where: { Instruction: { Program: { Address: { is: "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" } Method: { is: "create" } } } } ) { 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 } } } } ``` ### Get newly created Moonshot tokens and their Metadata Now you can track the newly created Moonshot 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 } } } } ``` --- ## Market Cap Analysis ### Top 10 Solana tokens with the highest marketcap increase in last 1hr Use below query to get top 10 marketcap jump tokens in last 1hr. Test the query [here](https://ide.bitquery.io/top-10-marketcap-jump-tokens-in-last-1hr#) ```graphql query MyQuery { Solana { TokenSupplyUpdates( limit: {count: 10} orderBy: {descendingByField: "marketcapJump"} where: {Transaction: {Result: {Success: true}}, Block: {Time: {since_relative: {minutes_ago: 60}}}} ) { TokenSupplyUpdate { AmountInUSD pre: PreBalanceInUSD post: PostBalanceInUSD Currency { MintAddress Name Symbol Decimals } } marketcapJump: calculate( expression: "(($TokenSupplyUpdate_post - $TokenSupplyUpdate_pre) / $TokenSupplyUpdate_pre) * 100" ) } } } ``` ## Marketcap of a Token We use `PostBalanceInUSD` field to get the marketcap. Since it is built on real-time data, you will get the Marketcap if the token was active in the past 8 hours or is being transacted in real-time. [This](https://ide.bitquery.io/market-cap-of-token_1) query returns latest marketcap of a particular token. ```graphql query MyQuery { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { Currency: { MintAddress: { is: "token mint address" } } } } limit: { count: 1 } orderBy: { descending: Block_Time } ) { TokenSupplyUpdate { PostBalanceInUSD } } } } ``` In case PostAmountInUSD is 0 then, you need to pull price from our Crypto price API. Here is an example which gets both supply and Price. [Run query](https://ide.bitquery.io/marketcap-query) ```graphql { Solana { TokenSupplyUpdates( where: {TokenSupplyUpdate: {Currency: {MintAddress: {is: "4iBhvT6bpCf92u12P1kpbejYrHDS6N3hJCNtAq6wpump"}}}} limit: {count: 1} orderBy: {descending: Block_Time} ) { TokenSupplyUpdate { Currency { Name Symbol MintAddress Decimals } PostBalance PostBalanceInUSD } } } Trading { Tokens( limit: {count: 1} where: {Price: {IsQuotedInUsd: true}, Interval: {Time: {Duration: {eq: 1}}}, Token: {Address: {is: "4iBhvT6bpCf92u12P1kpbejYrHDS6N3hJCNtAq6wpump"}}} ) { Block { Time(maximum: Block_Time) } Price { Average { Mean } } } } } ``` ## Monitor Market Cap Metric for a Pump Fun Token The subscription given [below](https://ide.bitquery.io/pump-fun-token-mcap-monitoring) could be used to setup a [websocket](/docs/subscriptions/websockets/) like solution that monitors market cap of a Pump Fun token in real time, where the `PostBalanceInUSD` is essentially the marketcap of the token. ```graphql subscription { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { Currency: { MintAddress: { is: "token mint address" } } } } limitBy: { by: TokenSupplyUpdate_Currency_MintAddress, count: 1 } ) { TokenSupplyUpdate { PostBalanceInUSD } } } } ``` ## Top Solana Tokens By MarketCap [This](https://ide.bitquery.io/top-Solana-tokens-based-on-market-cap) query returns the top Solana tokens based on the latest MarketCap. ```graphql query MyQuery { Solana { TokenSupplyUpdates( orderBy: { descending: Block_Time descendingByField: "TokenSupplyUpdate_Marketcap" } limitBy: { by: TokenSupplyUpdate_Currency_MintAddress, count: 1 } ) { TokenSupplyUpdate { Marketcap: PostBalanceInUSD Currency { Name Symbol MintAddress Fungible Decimals } } } } } ``` ## Top 100 Pump Fun Tokens By MarketCap [This](https://ide.bitquery.io/top-pump-fun-tokens-based-on-market-cap_1) query returns the top Solana tokens based on the latest MarketCap. ```graphql query MyQuery { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { Currency: { MintAddress: { includes: "pump" } } } } orderBy: { descending: Block_Time descendingByField: "TokenSupplyUpdate_Marketcap" } limitBy: { by: TokenSupplyUpdate_Currency_MintAddress, count: 1 } limit: { count: 100 } ) { TokenSupplyUpdate { Marketcap: PostBalanceInUSD Currency { Name Symbol MintAddress Fungible Decimals Uri } } } } } ``` ## Get Solana Tokens With a Specific MarketCap Lets say we need to get the tokens whose marketcap has crossed the `1M USD` mark but is less than `2M USD` for various reasons like automated trading. We can get the token details that have crossed a particular marketcap using [this](https://ide.bitquery.io/tokens-with-market-cap-range) query. ```graphql query MyQuery { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { PostBalanceInUSD: { ge: "1000000", le: "2000000" } } } orderBy: { descending: Block_Time } limitBy: { by: TokenSupplyUpdate_Currency_MintAddress, count: 1 } ) { TokenSupplyUpdate { Marketcap: PostBalanceInUSD Currency { Name Symbol MintAddress Decimals Uri } } } } } ``` --- ## Token Burn Events ### Get Latest Token Burn Events on Solana We will be using the token supply API to query recent token liquidity removals (token burn). You can modify this query to track burn events of a specific token using `Currency` filter in real time or query it. You can run the query [here](https://ide.bitquery.io/burn-token-supply-updates) ```graphql query MyQuery { Solana(network: solana) { TokenSupplyUpdates( where: { Instruction: { Program: { Method: { in: ["Burn"] } } } TokenSupplyUpdate: {} } limit: { count: 100 } orderBy: { descending: Block_Time } ) { TokenSupplyUpdate { PostBalanceInUSD PostBalance Amount Currency { Name MintAddress } } Instruction { Program { Name Method } } } } } ``` --- ## Video Tutorials ### Video Tutorial on Streaming and Getting Total Supply of a Solana Token ### Video Tutorial on Getting New Pump Fun Token Metadata ### Video Tutorial | How to get Newly Created Pump Fun Tokens, Dev Address, Creation Time, Metadata ### Video Tutorial | How to get Top Solana tokens by Marketcap increase in last 1 hr --- ## Solana Trader API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-trader-API/ Solana Trader API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Includes filters and field selection tips. # Solana Trader API :::tip Need real-time Solana trader data or anything from the last ~30 days? For **real-time trader and wallet data over the last ~30 days** across **9 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 Solana trader data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section we will see how to get Solana trader information using our API. More queries on DEX trades including latest trades, OHLC, and other data points can be found in the [Solana DEX Trades API page](/docs/blockchain/Solana/solana-dextrades/). :::note `Trade Side Account` field will not be available for aggregate queries in Archive and Combined Datasets ::: ## Top Traders of a token This query returns the top traders for a specific token by USD volume over a date range. It uses the **combined** dataset and filters by token mint, quote currency (e.g. SOL), and optional date range. For each trader you get buy/sell counts, buy/sell volume, total volume, and trade count. [Run query](https://ide.bitquery.io/top-traders-for-a-specific-token) ```graphql { Solana(dataset: combined) { 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 } } } ``` Change the token mint (`Trade.Currency.MintAddress`), quote currency (`Trade.Side.Currency.MintAddress`), and `Block.Date.since` / `till` to match your token and time window. ## Trades of Wallets in Realtime Below query will give you the trades of the wallets present in `addressList` in realtime. Try the query [here](https://ide.bitquery.io/Trades-of-wallets-in-realtime_1). ```graphql subscription MyQuery($addressList: [String!]) { Solana { DEXTrades( where: {Transaction: {Result: {Success: true}}, any: [{Trade: {Buy: {Account: {Address: {in: $addressList}}}}}, {Trade: {Buy: {Account: {Token: {Owner: {in: $addressList}}}}}}, {Trade: {Sell: {Account: {Address: {in: $addressList}}}}}, {Trade: {Sell: {Account: {Token: {Owner: {in: $addressList}}}}}}]} ) { Instruction { Program { Method } } Block { Time } Trade { Buy { Amount Account { Address } Currency { Name Symbol MintAddress Decimals } AmountInUSD } Sell { Amount Account { Address } Currency { Name Symbol MintAddress Decimals } AmountInUSD } } Transaction { Signature Signer } } } } { "addressList": ["7eWHXZefGY98o9grrrt1Z3j7DcPDEhA4UviQ1pVNhTXX", "6LNdbvyb11JH8qxAsJoPSfkwK4zJDQKQ6LNp4mxt8VpR"] } ``` ## Trades of Wallets with PreBalance, PostBalance Below query will give you the trades of the wallets present in `addressList` along with the balance updates happened in those trades.. Try the query [here](https://ide.bitquery.io/Trades-of-wallets-with-balance-Updates-in-that-trades). ```graphql query MyQuery($addressList: [String!]) { Solana { DEXTrades( limit: {count: 10} orderBy: {descending: Block_Time} where: {Transaction: {Result: {Success: true}}, any: [{Trade: {Buy: {Account: {Address: {in: $addressList}}}}}, {Trade: {Buy: {Account: {Token: {Owner: {in: $addressList}}}}}}, {Trade: {Sell: {Account: {Address: {in: $addressList}}}}}, {Trade: {Sell: {Account: {Token: {Owner: {in: $addressList}}}}}}]} ) { Instruction { Program { Method } } Block { Time } Trade { Buy { Amount Account { Address } Currency { Name Symbol MintAddress Decimals } AmountInUSD } Sell { Amount Account { Address } Currency { Name Symbol MintAddress Decimals } AmountInUSD } } Transaction { Signature Signer } joinBalanceUpdates(join: left, Transaction_Signature: Transaction_Signature) { Block{ Time } BalanceUpdate { PreBalance PostBalance Account { Address Token { Owner } } } } } } } { "addressList": ["HevtGooXxDjLfvLM1vUY2y7b9gyu59whR4ycnQj3UjUT"] } ``` ## Get count of Buys and Sells of a Trader To get the count of Buys and Sells of a specific trader after a certain `timestamp`, use the following query. Find the query [here](https://ide.bitquery.io/buys-and-sells-of-a-traders) ```graphql query MyQuery($timestamp: DateTime, $trader: String) { Solana(dataset: combined) { DEXTradeByTokens( where: {Block: {Time: {since: $timestamp}}, Trade: {Side: {Currency: {MintAddress: {in: ["So11111111111111111111111111111111111111112", "11111111111111111111111111111111"]}}}}, any: [{Trade: {Account: {Address: {is: $trader}}}}, {Trade: {Account: {Token: {Owner: {is: $trader}}}}}]} ) { buys: count(if: {Trade: {Side: {Type: {is: buy}}}}) sells: count(if: {Trade: {Side: {Type: {is: sell}}}}) } } } { "timestamp" : "2024-06-25T06:19:00Z", "trader" : "FeWbDQ9SpgWS8grNrpFesVquJfxVkRu1WNZerKsrkcbY" } ``` ## 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) ```graphql query MyQuery ($trader:String, $token:String){ Solana(dataset: realtime) { DEXTradeByTokens( where: { Trade: {Currency:{MintAddress:{is:$token}} Side: {Currency: {MintAddress: {in: ["So11111111111111111111111111111111111111112", "11111111111111111111111111111111"]}}}}, any: [{Trade: {Account: {Address: {is: $trader}}}}, {Trade: {Account: {Token: {Owner: {is: $trader}}}}}]} ) { Block{ last_active_time:Time(maximum:Block_Time) } total_buy: sum(of:Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: buy}}}}) total_sell: sum(of:Trade_Side_AmountInUSD if: {Trade: {Side: {Type: {is: sell}}}}) avg_sell_price: average(of:Trade_PriceInUSD if: {Trade: {Side: {Type: {is: sell}}}}) } } } ``` ```json { "token":"FSJYiGZhJ1wDPNhHbSHm49yJkzbFp7FykNB2SZFipump", "trader": "CECN4BW4DKnbyddkd9FhWVR5dotzKhQr5p7DUPhQ55Du" } ``` ## Subscribe to a Trader in Real-time The below subscription query will fetch in real-time the trades done by a wallet. You can use websockets to build applications on this data. Read more [here](/docs/subscriptions/websockets/) To filter trades by a wallet we will use the condition `Account: {Address: {is}}`. Run the subscription query [here](https://ide.bitquery.io/trades-of-a-wallet_2) You can convert this subscription to a `query` to get past trades of the wallet. ```graphql subscription { Solana { buy: DEXTrades( where: {Trade: {Buy: {Account: {Address: {is: "CP1d7VVnCMy321G6Q1924Bibp528rqibTX8x9UL6wUCe"}}}}} ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Amount Account { Address } Currency { MetadataAddress Key IsMutable EditionNonce Decimals CollectionAddress Fungible Symbol Native Name } Order { LimitPrice LimitAmount OrderId } Price } Market { MarketAddress } Sell { Account { Address } Currency { IsMutable Decimals CollectionAddress Fungible Symbol Native Name } Price } } } sell: DEXTrades( where: {Trade: {Sell: {Account: {Address: {is: "CP1d7VVnCMy321G6Q1924Bibp528rqibTX8x9UL6wUCe"}}}}} ) { Trade { Dex { ProgramAddress ProtocolFamily ProtocolName } Buy { Amount Account { Address } Currency { MetadataAddress Key IsMutable EditionNonce Decimals CollectionAddress Fungible Symbol Native Name } Order { LimitPrice LimitAmount OrderId } Price } Market { MarketAddress } Sell { Account { Address } Currency { IsMutable Decimals CollectionAddress Fungible Symbol Native Name } Price } } } } } ``` ## Get the First 100 buyers of a Token The below query retrieves the first 100 buyers of a specified token. You can run the query [here](https://ide.bitquery.io/get-first-100-buyers-of-a-token_1) ```graphql query MyQuery { Solana { DEXTrades( where: { Trade: { Buy: { Currency: { MintAddress: { is: "2Z4FzKBcw48KBD2PaR4wtxo4sYGbS7QqTQCLoQnUpump" } } } } } limit: { count: 100 } orderBy: { ascending: Block_Time } ) { Trade { Buy { Amount Account { Token { Owner } } } } } } } ``` --- ## Solana Transactions - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/transactions/ Solana Transactions - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana Transactions gRPC Stream The `transactions` gRPC Stream provides real-time transaction data across the Solana blockchain. --- ## Overview Subscribe to live Solana transactions with filtering by program or signer. Each event includes parsed instructions (IDL), balance updates, program logs, and execution status. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. ## Configuration To subscribe to transactions, configure your stream as follows: ```yaml stream: type: "transactions" ``` ## Available Data The transactions stream provides comprehensive transaction information including: - **Transaction details**: Slot, signature, status, fees (in native and USD) - **Account information**: Signers, accounts, program IDs - **Balance updates**: Pre/post balances for all accounts - **Parsed instructions**: IDL-parsed program calls with arguments and logs - **Program execution**: Success/failure status and error messages ## Sample Data Structure Here's an example of the data structure you'll receive: ```json { "Block": { "Slot": 370030401 }, "Transaction": { "Index": 455, "Signature": "2gyW9NtqCRwsGGWoeJkGGQNPrQfcDT2dBQxUKXXVcC7QQbNBey9DtQLNkCRn7yU5N1H8YcFQESTC6KbQ7n1HyTwj", "Status": { "Success": true, "ErrorMessage": "" }, "Header": { ... ], "Accounts": [ ... ] }, "FeeInUsd": 0.00075, "TotalBalanceUpdates": [ { "PreBalance": 82844277367, "PostBalance": 82844272367, "AccountIndex": 0 }, ... ], "ParsedIdlInstructions": [ { "Index": 0, "Depth": 0, "CallerIndex": -1, "ExternalSeqNumber": 1, "InternalSeqNumber": 0, "Program": { "Address": "Vote111111111111111111111111111111111111111", "Parsed": true, "Name": "vote", "Method": "TowerSync", ... }, "Accounts": [ { "Address": "C616NHpqpaiYpqVAv619QL73vEqKJs1mjsJLtAuCzMX6", "IsSigner": false, "IsWritable": true }, { "Address": "ETcW7iuVraMKLMJayNCCsr9bLvKrJPDczy1CMVMPmXTc", "IsSigner": true, "IsWritable": true } ], "Logs": [ "Program Vote111111111111111111111111111111111111111 invoke [1]", "Program Vote111111111111111111111111111111111111111 success" ], "Data": ... } ] } } ``` ## Key Points - **Parsed instructions**: IDL-parsed program calls with structured arguments and account names - **Balance tracking**: Complete pre/post balance changes for all accounts - **Program logs**: Execution logs showing program invocation and success/failure - **All programs**: Captures transactions from all Solana programs, not just DEX ## Filtering Options The filter options are defined in the `request.proto` file. You can filter transactions using the following filters: ```protobuf message SubscribeTransactionsRequest { AddressFilter program; AddressFilter signer; } ``` Available filters: - **program**: Filter by program address (e.g., Vote, Token, System) - **signer**: Filter by signer's address ## Schema Reference - **Protobuf Schema**: [transaction_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/parsed_idl_block_message.proto) - **Sample Data**: [solana_transaction.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_tx.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 - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana Transactions API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-transactions/ Solana Transactions API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # Solana Transactions API In this section we'll have a look at some examples using the Solana Transactions API. ## Subscribe to Recent Transactions The subscription query below fetches the most recent transactions on the Solana blockchain You can find the query [here](https://ide.bitquery.io/Realtime-Solana-Transactions) ```graphql subscription { Solana { Transactions(limit: {count: 10}) { Block { Time Hash } Transaction { BalanceUpdatesCount Accounts { Address IsWritable } Signer Signature Result { Success ErrorMessage } Index Fee TokenBalanceUpdatesCount InstructionsCount } } } } ``` ## Filtering Solana Transactions Based on Dynamic Criteria In this subscription query we will see how to set dynamic filters for the transactions to be retrieved based on various transaction properties. Developers can monitor specific types of transactions on the Solana network, such as high-volume or high-fee transactions. You can run the query [here](https://ide.bitquery.io/Solana-tx-dynamic-filter) #### Variables - **`$network`**: Specifies the Solana network. - **`$tx_filter`**: A filter object used to specify the criteria for transactions to retrieve. ```graphql subscription( $network: solana_network $tx_filter: Solana_Transaction_Filter ) { Solana(network: $network) { Transactions(where:$tx_filter) { Block { Time Hash } Transaction { BalanceUpdatesCount Accounts { Address IsWritable } Signer Signature Result { Success ErrorMessage } Index Fee TokenBalanceUpdatesCount InstructionsCount } } } } { "network": "solana", "tx_filter":{"Transaction": {"TokenBalanceUpdatesCount": {"gt": 10}, "FeeInUSD": {"ge": "0.0010"}}} } ``` --- ## Solana Transfers - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/transfer/ Solana Transfers - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana Transfers gRPC Stream The `transfers` gRPC Stream provides real-time token and SOL transfer data across the Solana blockchain. --- ## Overview Subscribe to live token and SOL transfers with filtering by sender, receiver, or token mint. Each event includes transaction details, sender/receiver accounts, amounts, and balance updates. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. ## Configuration To subscribe to transfers, configure your stream as follows: ```yaml stream: type: "transfers" ``` ## Available Data The transfers stream provides comprehensive transfer 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 - **Transfer specifics**: Amounts, sender/receiver addresses, authority information - **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": 370428239 }, "Transaction": { "Index": 776, "Signature": "2knhEScuNwtKYXw86X59iY1UDnETUGXpB4r54i26T9Th1k3zCZC9ZXeBfvXCfBHAxyG7PZg3GTdxQSzzXP8Rzyyo", ... }, "Transfer": { "InstructionIndex": 10, "Amount": 45212952, "Sender": { "Address": "CjUfYX9UYiJAmvguVWXZusqQdPDSMPRfhmQRMnH6cYJC", "IsSigner": false, "IsWritable": true, "Token": { "Mint": "So11111111111111111111111111111111111111112", "Owner": "B4YMuvqf5o5uSxBXLZozC4BQKrpo2aHk5DXSquyHZ2fb", "Decimals": 9, "ProgramId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" } }, "Receiver": { "Address": "866SWVmbZDQjQFwe8RS1zRrwQKo2RBS7WZfxSGc18Guo", "IsSigner": false, "IsWritable": true, "Token": { "Mint": "So11111111111111111111111111111111111111112", "Owner": "CAVE3Fc6dH3zwEreMvXuBiEMjvPXeqkJfyT2VFHngxyQ", "Decimals": 9, "ProgramId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" } }, "Authority": { "Address": "B4YMuvqf5o5uSxBXLZozC4BQKrpo2aHk5DXSquyHZ2fb", "IsSigner": true, "IsWritable": true }, "Currency": { "Name": "Wrapped Solana", "Decimals": 9, "Symbol": "WSOL", "MintAddress": "So11111111111111111111111111111111111111112" }, "Instruction": { "Index": 10, "Program": { "Address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "Name": "spl_token_2022", "Method": "transferChecked" }, "Arguments": [ { "Name": "amount", "Type": "u64", "UInt": 45212952 }, { "Name": "decimals", "Type": "u8", "UInt": 9 } ], "AccountNames": [ "source", "mint", "destination", "authority" ] }, "BalanceUpdates": [ { "PreBalance": 47252232, "PostBalance": 2039280, "AccountIndex": 1 }, { "PreBalance": 148077284154, "PostBalance": 148122497106, "AccountIndex": 3 } ], "TokenBalanceUpdates": [ { "PreBalance": 148075244874, "PostBalance": 148120457826, "AccountIndex": 3 } ] } } ``` ## Filtering Options The filter options are defined in the `request.proto` file. You can filter transfers using the following filters: ```protobuf message SubscribeTransfersRequest { AddressFilter sender; AddressFilter receiver; AddressFilter token; } ``` Available filters: - **sender**: Filter by sender's address - **receiver**: Filter by receiver's address - **token**: Filter by token mint address (e.g., WSOL, USDC) ## Transfer Types The transfers stream captures various transfer-related events: - **SPL Token transfers**: Standard token transfers using SPL Token program - **SPL Token 2022 transfers**: Enhanced token transfers with additional features - **SOL transfers**: Native Solana transfers - **Authority transfers**: Transfers authorized by token authorities ## Transfer Data Fields - **Amount**: The amount being transferred (in smallest unit) - **Sender**: The source account/token account - **Receiver**: The destination account/token account - **Authority**: The account that authorized the transfer - **Currency**: Token information including mint address and decimals - **InstructionIndex**: The position of the transfer instruction in the transaction ## Schema Reference - **Protobuf Schema**: [dex_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/dex_block_message.proto) - **Sample Data**: [solana_transfer.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_transfer.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 - [Solana Transfers (GraphQL)](/docs/blockchain/Solana/solana-transfers/) — WebSocket subscriptions - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana Transfers API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-transfers/ Solana Transfers API: monitor Solana native and token transfers in real time with Bitquery GraphQL APIs. Scale further with Kafka or gRPC streams. # Solana Transfers API > **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. In this section we'll have a look at some examples using the Solana Transfers API. ## 🔗 Related Solana APIs - **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)** - Monitor balance changes from transfers - **[Solana Instructions API](/docs/blockchain/Solana/solana-instructions/)** - Track transfer instructions and events - **[Solana DEX Trades API](/docs/blockchain/Solana/solana-dextrades/)** - Monitor trading transfers and swaps - **[Solana Fees API](/docs/blockchain/Solana/solana_fees_api/)** - Analyze transfer fees and transaction costs - **[Solana Token Supply API](/docs/blockchain/Solana/token-supply-cube/)** - Track supply changes from transfers - **[Historical Transfers API](https://docs.bitquery.io/v1/docs/Examples/Solana/transfers)** ## Subscribe to all transfers on Solana This includes all types of transactions; transfers, swaps, and other types of transactions on Solana For monitoring the balance changes that result from these transfers, see our **[Solana Balance Updates API](/docs/blockchain/Solana/solana-balance-updates/)**. [Run Stream >](https://ide.bitquery.io/Subscribe-to-the-all-transfers-on-Solana) ```graphql subscription { Solana(network: solana) { Transfers { Transfer { Amount AmountInUSD Currency { Name MintAddress Fungible Symbol Uri } Receiver { Address } Sender { Address } } Transaction { Signature } } } } ``` ## Subscribe to the latest NFT token transfers on Solana Let's see an example of NFT token transfers using GraphQL Subscription (Webhook). In the following API, we will be subscribing to all NFT token transfers. You can run the query [here](https://ide.bitquery.io/Subscribe-to-the-latest-NFT-transfers-on-Solana) ```graphql subscription { Solana { Transfers(where: {Transfer: {Currency: {Fungible: false}}}) { Transfer { Amount AmountInUSD Currency { Name MintAddress Fungible Symbol Uri } Receiver { Address } Sender { Address } } Transaction { Signature } } } } ``` ## SPL Token Transfers API | Token transfers of a particular token on Solana One of the most common types of transfers on Solana are SPL token transfers. Let's see an example to get the latest SPL token transfers using our API. Today we are taking an example of JUPITER token transfers. The contract address for the JUPITER token is `JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN`. You can find the query [here](https://ide.bitquery.io/SPL-transfers-websocket_1) ```graphql subscription { Solana { Transfers( where: {Transfer: {Currency: {MintAddress: {is: "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"}}}} ) { Transfer { Currency { MintAddress Symbol Name Fungible Native } Receiver { Address } Sender { Address } Amount AmountInUSD } } } } ``` ## Get transfers in a Transaction Signature This query will help you fetch transfers for a particular transaction signature `3x3fbg3zfTvcfwEiDee5Z5NnQP2Hr7cgZZ9bMxNYtYKi6fMN9gT6xpdUzRb2FjfCkGXMPvhkt3bW61CHCNaWwdQi`. Check the query [here](https://ide.bitquery.io/Query-transfer-by-sig) ```graphql { Solana(dataset: realtime) { Transfers( limit: {count: 10} orderBy: {descending: Block_Slot} where: {Transaction: {Signature: {is: "3x3fbg3zfTvcfwEiDee5Z5NnQP2Hr7cgZZ9bMxNYtYKi6fMN9gT6xpdUzRb2FjfCkGXMPvhkt3bW61CHCNaWwdQi"}}} ) { Transaction { Signature } Block { Slot } count Transfer { Amount AmountInUSD Currency { MintAddress Name Symbol } Receiver { Address } Index Sender { Address } } } } } ``` ## Transfers sent by specific address This websocket retrieves transfers where the sender is a particular address `2g9NLWUM6bPm9xq2FBsb3MT3F3G5HDraGqZQEVzcCWTc`. For this subscription query we use `where` keyword and in that we specify `{Transfer: {Sender: {Address: {is: "2g9NLWUM6bPm9xq2FBsb3MT3F3G5HDraGqZQEVzcCWTc"}}}}` to get the desired data. You can find the query [here](https://ide.bitquery.io/transfers-where-sender-is-the-specified-address_1) ```graphql subscription { Solana { Transfers( where: {Transfer: {Sender: {Address: {is: "2g9NLWUM6bPm9xq2FBsb3MT3F3G5HDraGqZQEVzcCWTc"}}}} ) { Transaction { Signature } Transfer { Amount AmountInUSD Sender { Address } Receiver { Address } Currency { Name Symbol MintAddress } } } } } ``` ## Monitor multiple solana wallets transfers in real time using Websocket You can also monitor multiple wallet addresses using Bitquery's GraphQL subscription via WebSocket. The following query listens to real-time transfers sent or received by the specified wallet addresses. You can include around 100 addresses in a single subscription, potentially more, as we typically do not throttle this on our end. However, if you need to track thousands of addresses, you can subscribe to all transfers and filter them on your side. Websockets are priced based on their running time, not the amount of data delivered. Run query using [this link](https://ide.bitquery.io/Solana-Websocket---Subscribe-to-all-transfers-of-specific-addresses-in-realtime) ```graphql subscription { Solana { Transfers( where: { any: [ { Transfer: { Sender: { Address: { in: [ "7Ppgch9d4XRAygVNJP4bDkc7V6htYXGfghX4zzG9r4cH" "G6xptnrkj4bxg9H9ZyPzmAnNsGghSxZ7oBCL1KNKJUza" ] } } } } { Transfer: { Receiver: { Address: { in: [ "7Ppgch9d4XRAygVNJP4bDkc7V6htYXGfghX4zzG9r4cH" "G6xptnrkj4bxg9H9ZyPzmAnNsGghSxZ7oBCL1KNKJUza" ] } } } } ] } ) { Transfer { Amount AmountInUSD Authority { Address } Currency { Decimals CollectionAddress Fungible MetadataAddress MintAddress Name Native Symbol } Receiver { Address } Sender { Address } } } } } ``` ## Transfers of a wallet address This query fetches you the recent 10 transfers of a specific wallet address `9nnLbotNTcUhvbrsA6Mdkx45Sm82G35zo28AqUvjExn8`. Try the query [here](https://ide.bitquery.io/Transfers-of-a-wallet_1). ```graphql { Solana { Transfers( limit: {count: 10} orderBy: {descending: Block_Time} where: {any: [{Transfer: {Sender: {Address: {is: "9nnLbotNTcUhvbrsA6Mdkx45Sm82G35zo28AqUvjExn8"}}}}, {Transfer: {Receiver: {Address:{is: "9nnLbotNTcUhvbrsA6Mdkx45Sm82G35zo28AqUvjExn8"}} }}]} ) { Transaction { Signature } Transfer { Amount AmountInUSD Sender{ Address } Receiver{ Address } } } } } ``` ## Video Tutorial on Solana Transfers API | How to get NFT, SPL Transfers data on Solana in Realtime --- ## Solana Wash Trading Dashboard URL: https://docs.bitquery.io/docs/usecases/wash-trading-detector/app/ Build Solana Wash Trading Dashboard: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Solana Wash Trading Dashboard This script runs an interactive Streamlit web application that: - Loads fresh Solana DEX trade data from Bitquery. - Applies a trained XGBoost model to detect wash trading. - Calculates various risk metrics. - Displays dynamic, real-time visualizations. ## Code Braakdown ### Imports Refer to the [file structure](../overview/#project-structure) to make sure that the imports are correct. ```py from sklearn.preprocessing import LabelEncoder from get_data import get_trades ``` ### Load Model and Features The code given below loads your pre-trained XGBoost model and the feature list used during training to ensure correct column alignment. ```py model = pickle.load(open("xgb_wash_model.pkl", "rb")) with open("model_features.json", "r") as f: feature_cols = json.load(f) ``` ### Fetch and Prepare Data This code fetch the latest Solana DEX trades using Bitquery API, flattens nested JSON into a usable DataFrame, encode categorical features and align the data with training features. ```py trade_data = get_trades() df = pd.json_normalize(trade_data) X = df.copy() for col in X.select_dtypes(include="object").columns: X[col] = LabelEncoder().fit_transform(X[col].astype(str)) for col in feature_cols: if col not in X.columns: X[col] = 0 X = X[feature_cols] ``` ### Run Predictions and Compute Risk Score This code adds a new column prediction indicating suspected wash trades and computes an overall risk score (0–100). ```py df["prediction"] = model.predict(X) wash_count = int(df["prediction"].sum()) total_trades = len(df) risk_score = min(100, int((wash_count / total_trades) * 100)) if total_trades else 0 ``` ### Compute Key Metrics The code given below returns: 1. Cleaned timestamp for resampling. 2. Buy volume in USD 3. Suspicious volume based on model prediction 4. Top 10 wallets' volume share 5. Most active wallet’s trade contribution 6. % of volume flagged as suspicious ```py df["timestamp"] = pd.to_datetime(df["Block.Time"], errors="coerce") df["volume"] = pd.to_numeric(df["Trade.Buy.AmountInUSD"], errors="coerce").fillna(0) df["suspiciousVolume"] = df.apply( lambda row: row["volume"] if row["prediction"] == 1 else 0, axis=1 ) top_wallets = df.groupby("Trade.Buy.Account.Address")["volume"].sum().sort_values(ascending=False) total_volume = top_wallets.sum() top_10_volume = top_wallets.head(10).sum() volume_concentration = round(100 * top_10_volume / total_volume, 2) top_wallet_trade_count = df["Trade.Buy.Account.Address"].value_counts().iloc[0] wallet_contribution = round(100 * top_wallet_trade_count / len(df), 2) wash_volume_pct = round(100 * df["suspiciousVolume"].sum() / df["volume"].sum(), 2) ``` ### Streamlit App Setup This code initializes the Streamlit app with a title and a button. ```py st.set_page_config(page_title="Solana Wash Trade Risk Dashboard", layout="wide") st.title("🚨 Solana Wash Trading Risk Assessment") st.button("🔍 Analyze Wash Trading Risk for Solana") ``` ### Show Risk Metrics The below code renders `Risk Score` and `Trading Metrics` on the Streamlit app. ```py st.subheader("Risk Assessment") st.markdown(f"**Risk Score: `{risk_score}`** – {'High' if risk_score > 70 else 'Medium' if risk_score > 40 else 'Low'} Risk") st.progress(risk_score / 100) col1, col2, col3, col4 = st.columns(4) col1.metric("Volume Concentration", f"{volume_concentration}%") col2.metric("Most Active Trader", f"{wallet_contribution}%") col3.metric("Suspicious Trades", f"{wash_count}") col4.metric("Wash Trade Volume", f"{wash_volume_pct}%") ``` ### Plot Volume Chart (Total vs Suspicious) The below code renders a bar chart of total trade volume v/s the suspicious volume for a timeframe of `1s`. ```py df.set_index("timestamp", inplace=True) agg = df.resample("1s").agg({ "volume": "sum", "suspiciousVolume": "sum" }).fillna(0).reset_index() fig = go.Figure() # Blue bars = total volume fig.add_trace(go.Bar( x=agg["timestamp"], y=agg["volume"], name="Total Volume", marker_color="blue", width=500 )) # Red bars = suspicious volume fig.add_trace(go.Bar( x=agg["timestamp"], y=agg["suspiciousVolume"], name="Suspicious Volume", marker_color="red", width=500 )) fig.update_layout( barmode="group", title="Grouped Bar Chart: Volume vs Suspicious Volume", xaxis_title="Time(UTC+00:00:00)", yaxis_title="Volume (USD)", xaxis_tickformat="%H:%M:%S", legend=dict(x=0.8, y=1.1), bargap=0.4, bargroupgap=0.1, height=400, ) st.plotly_chart(fig, use_container_width=True) ``` ### Raw Data Toggle The below code allows to optionally show the full processed dataset (including predictions and timestamps). ```py if st.checkbox("Show Raw Trade Data"): st.dataframe(df) ``` ## Deployment via Streamlit You can deploy this dashboard to Streamlit Cloud in a few easy steps just as this [Live Demo](https://washtrade.streamlit.app). ### Add `requirements.txt` In the project repository add the following `requirements.txt` file. ```txt streamlit pandas scikit-learn xgboost matplotlib plotly ``` ### Deploy on Streamlit Cloud 1. Go to [Streamlit Cloud](https://streamlit.io/cloud). 2. Click "New App". 3. Connect your GitHub repo. 4. Set app.py as the entry point. 5. Add your [access token](https://account.bitquery.io/user/api_v2/access_tokens) in Secrets. 6. Click Deploy. ## Final Product The final product looks like the image given below. ![Solana Wash Trading Dashboard](/img/wash_dashboard.png) --- ## Solana Wash Trading Detector URL: https://docs.bitquery.io/docs/usecases/wash-trading-detector/overview/ Detect Solana wash trades using Bitquery DEX data, rule-based labels, XGBoost scoring, and a Streamlit investigation UI. # Solana Wash Trades Detector This project fetches on-chain Solana DEX trades data from Bitquery, labels potential wash-trades based on a set of defined rules, trains an XGBoost model, and deploys an interactive Streamlit dashboard to visualize suspicious trades and compute risk metrics. ## How It Works 1. `Data Collection`: Live Solana DEX trades are fetched from Bitquery using GraphQL APIs. 2. `Trade Labeling`: A set of defined rules (e.g., self-trading, repeated trading loops, price spoofing) is applied to label trades as potentially suspicious (wash trades). 3. `Model Training`: A machine learning model (XGBoost) is trained on the labeled data to learn patterns indicative of wash trading. 4. `Visualization`: A clean and interactive dashboard built with Streamlit displays incoming trades, volume metrics, risk concentration, and predicted suspicious activity in real time. ## Project Structure ```bash ├── get_data.py # Fetches trades from Bitquery ├── label.py # Rule-based labeling functions ├── main.py # Preprocesses data, trains XGBoost, saves model + features ├── app.py # Streamlit app for live inference & visualization ├── requirements.txt # List of pip packages required for the project ├── model_features.json # Saved feature list used during training ├── xgb_wash_model.pkl # Trained XGBoost model └── .streamlit/secrets.toml # To store secret keys such as Bitquery Access Token ``` You can checkout the entire codebase of the project [here](https://github.com/Kshitij0O7/wash-trading-detector). --- ## Solana Xstocks API URL: https://docs.bitquery.io/docs/blockchain/Solana/xstocks-api/ Solana Xstocks API: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. Works with WebSocket live subscriptions. # xStocks API :::tip Need real-time xStocks 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 xStocks swaps with **USD price, market cap, and supply on every row** across **9 chains in one API**. Use this page when you need **historical xStocks data older than ~30 days**, raw per-swap detail, or call / event context. ::: :::note Some tickers only trade via RFQ Several tokenized equities settle through Jupiter's RFQ order engine rather than a pool, which means they have no DEX trades at all and no price here. The [Solana RFQ API](/docs/blockchain/Solana/solana-rfq-api/) shows how to read their executed prices from the `fill` instruction. ::: ## Tesla xStock Trades in Real-Time Below query will give you realtime trades of Tesla xStock (TESLAx). You can run the query [here](https://ide.bitquery.io/Latest-Trades-of-TESLA-onchain-xStock_1) ```graphql subscription LatestTrades { Solana { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB" } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signature } Trade { Market { MarketAddress } Dex { ProtocolName ProtocolFamily } AmountInUSD PriceInUSD Amount Currency { Name Symbol MintAddress } Side { Type Currency { Symbol MintAddress Name } AmountInUSD Amount } } } } } ``` ## Latest Price of xStocks using Crypto Price api You can get latest price of xStocks tokens prices using our [Crypto price api](/docs/trading/crypto-price-api/). You can run the query [here](https://ide.bitquery.io/xStocks-prices) ```graphql subscription { Trading { Tokens( where: {Token: {Name: {includes: "xStock"}}, Interval: {Time: {Duration: {eq: 1}}}} ) { 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 } } } } } ``` ## Latest Price of the Apple xstock You can use the following query to get the latest price of a Apple xStock on Solana. You can run this query using this [link](https://ide.bitquery.io/Get-Latest-Price-of-Apple-xStock-in--USD-Real-time). ```graphql query { Solana { DEXTradeByTokens( limit:{count:1} orderBy:{descending:Block_Time} where: {Trade: {Currency: {MintAddress: {is: "XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp"}}}} ) { Transaction { Signature } Trade { AmountInUSD Amount Currency { MintAddress Name } Dex { ProgramAddress ProtocolName } Price PriceInUSD Side { Account { Address } AmountInUSD Amount Currency { Name MintAddress } } } } } } ``` ## Realtime Price feed of Apple xstock You can use the following query to get the latest price of a Apple xStock on Solana. You can run this query using this [link](https://ide.bitquery.io/Get-realtime-Price-of-Apple-xStock-in--USD-Real-time). ```graphql subscription { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp"}}}} ) { Transaction { Signature } Trade { AmountInUSD Amount Currency { MintAddress Name } Dex { ProgramAddress ProtocolName } Price PriceInUSD Side { Account { Address } AmountInUSD Amount Currency { Name MintAddress } } } } } } ``` ## Tesla xStock OHLC API If you want to get OHLC data for any xStock, you can use this api. Only use [this API](https://ide.bitquery.io/Tesla-xStock-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: "XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB"}}, Side: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}}, PriceAsymmetry: {lt: 0.1}}} limit: {count: 10} ) { Block { Timefield: Time(interval: {in: minutes, count: 1}) } volume: sum(of: Trade_Side_AmountInUSD) Trade { high: PriceInUSD(maximum: Trade_Price) low: PriceInUSD(minimum: Trade_Price) open: PriceInUSD(minimum: Block_Slot) close: PriceInUSD(maximum: Block_Slot) } count } } } ``` ## Get the Top Traders of the Apple xStock The below query gets the Top Traders of the Apple xStock `XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp`. 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-of-the-Apple-xStock_1) ```graphql query TopTraders($token: String) { Solana { DEXTradeByTokens( orderBy: {descendingByField: "volume"} limit: {count: 100} where: {Trade: {Currency: {MintAddress: {is: $token}}}, Transaction: {Result: {Success: true}}} ) { Trade { Account { Owner } Currency{ Name Symbol MintAddress } Side { Account { Address } Type } } buyVolume: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: buy}}}}) sellVolume: sum(of: Trade_Side_AmountInUSD, if: {Trade: {Side: {Type: {is: sell}}}}) volume: sum(of: Trade_Side_AmountInUSD) } } } { "token": "XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp" } ``` ## Get trading volume, buy volume, sell volume of the Meta xStock This query fetches you the traded volume, buy volume and sell volume of a Meta xStock `Xsa62P5mvPszXL1krVUnU5ar38bBSVcWAB6fmPCo5Zu`. Try out the API [here](https://ide.bitquery.io/trade_volume-META-xStock). ```graphql query MyQuery { Solana(dataset: combined) { DEXTradeByTokens( orderBy: {descendingByField: "traded_volume"} where: {Block: {Time: {since: "2025-06-20T01:00:00Z"}}, Transaction: {Result: {Success: true}}, Trade: {Currency: {MintAddress: {is: "Xsa62P5mvPszXL1krVUnU5ar38bBSVcWAB6fmPCo5Zu"}}, Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}}} ) { Trade { Currency { Name MintAddress Symbol } Side { Currency { Name Symbol MintAddress } } } traded_volume_USD: sum(of:Trade_Side_AmountInUSD) traded_volume: sum(of: Trade_Amount) buy_volume: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: buy}}}}) sell_volume: sum(of: Trade_Amount, if: {Trade: {Side: {Type: {is: sell}}}}) } } } ``` ## Video Tutorial | How to Monitor Tokenized Stocks (Tesla, Apple, Meta, etc) on Solana --- ## Solana Zeta Markets API URL: https://docs.bitquery.io/docs/blockchain/Solana/solana-zeta/ Solana Zeta: query and stream Solana on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # ZETA DEX API :::tip Need real-time Zeta 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 Zeta swaps with **USD price, market cap, and supply on every row** across **9 chains in one API**. Use this page when you need **historical Zeta data older than ~30 days**, raw per-swap detail, or call / event context. ::: In this section, we'll show you how to access information about Zeta DEX data using Bitquery APIs. ## Track Order placed on Zeta in Realtime To retrieve the latest orders placed on Zeta DEX, we will utilize the Solana instructions API/Websocket. We will specifically look for the latest instructions from Zeta's program, identified by the program ID `ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD`, [using this query](https://ide.bitquery.io/Get-all-the-Zeta-Program-methods#). And then we can see in the response that the method with the largest count is an empty string which should be the method to place orders. We will filter for this method to get the orders placed on Zeta in realtime. You can run this query using this [link](https://ide.bitquery.io/Track-orders-placed-on-Zeta-in-realtime#). ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD" } Method: { is: "" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Accounts { Address IsWritable Token { Owner Mint ProgramId } } 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_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } } } Name Method } } Transaction { Signature } } } } ``` ## Track Liquidations happening on Zeta in Realtime To track the latest Liquidations on Zeta DEX, we will utilize the Solana instructions API/Websocket. We will specifically look for the latest instructions from Zeta's program, identified by the program ID `ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD`, [using this query](https://ide.bitquery.io/Get-all-the-Zeta-Program-methods#). And then we can see in the response `liquidateV2` method which is called to initialize a liquidation. We will filter for this method to get the liquidations on Zeta in realtime. You can run this query using this [link](https://ide.bitquery.io/Track-Liquidations-on-Zeta-in-realtime). ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD" } Method: { is: "liquidateV2" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Accounts { Address IsWritable Token { Owner Mint ProgramId } } 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_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } } } Name Method } } Transaction { Signature } } } } ``` ## Track Settling of Funds on Zeta in Realtime To retrieve the latest settling of funds transactions on Zeta DEX, we will utilize the Solana instructions API/Websocket. We will specifically look for the latest instructions from Zeta's program, identified by the program ID `ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD`, [using this query](https://ide.bitquery.io/Get-all-the-Zeta-Program-methods#). And then we can see in the response `settleDEXFunds` method which is called to initialize a settlement. We will filter for this method to track the settlements on Zeta in realtime. You can run this query using this [link](https://ide.bitquery.io/Track-settling-of-funds-on-Zeta-in-realtime). ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD" } Method: { is: "settleDexFunds" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Accounts { Address IsWritable Token { Owner Mint ProgramId } } 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_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } } } Name Method } } Transaction { Signature } } } } ``` ## Track Cancelling of orders on Zeta in Realtime To retrieve the latest cancelling of orders on Zeta DEX, we will utilize the Solana instructions API/Websocket. We will specifically look for the latest instructions from Zeta's program, identified by the program ID `ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD`, [using this query](https://ide.bitquery.io/Get-all-the-Zeta-Program-methods#). And then we can see in the response `cancelOrder` method which is called to initialize a cancellation. You can run this query using this [link](https://ide.bitquery.io/Track-cancelling-of-Orders-on-Zeta-in-realtime). ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD" } Method: { is: "cancelOrder" } } } Transaction: { Result: { Success: true } } } ) { Instruction { Accounts { Address IsWritable Token { Owner Mint ProgramId } } 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_Boolean_Value_Arg { bool } ... on Solana_ABI_Bytes_Value_Arg { hex } ... on Solana_ABI_Json_Value_Arg { json } ... on Solana_ABI_Float_Value_Arg { float } } } Name Method } } Transaction { Signature } } } } ``` ## Video Tutorial | How to Track Zeta Placed Orders, Liquidations and Settling of Funds --- ## Solana gRPC Authentication - CoreCast API Token URL: https://docs.bitquery.io/docs/grpc/solana/authorization/ Solana gRPC Authentication - CoreCast API Token for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Authentication To access Bitquery's Solana gRPC streams (CoreCast), you must authenticate every stream using an **[authorization token](https://account.bitquery.io/user/api_v2/access_tokens)**. This token is provided in your configuration file and automatically added to the gRPC metadata before starting a stream. Check the [documentation](/docs/authorization/how-to-generate/) to create a new token. --- ## Overview 1. Generate an API token at [account.bitquery.io](https://account.bitquery.io/user/api_v2/access_tokens) 2. Add it to your config or environment 3. Inject it into gRPC metadata as `Authorization` header before each stream call --- ## Quick Example Minimal Node.js snippet: create metadata and start a stream. Use your token from `config.yaml` or `process.env`. ```javascript const grpc = require('@grpc/grpc-js'); const metadata = new grpc.Metadata(); metadata.add('authorization', process.env.BITQUERY_TOKEN || config.server.authorization); // Use with any CoreCast stream (DexTrades, Transfers, etc.) const stream = client.DexTrades(request, metadata); stream.on('data', (msg) => console.log(msg)); stream.on('error', (err) => console.error(err)); ``` :::tip No extra headers Only the `authorization` header is required. No API keys or other credentials. ::: --- ## Configuration The token is defined under the server in the `config.yaml` file: ```yaml server: address: "corecast.bitquery.io" authorization: "" insecure: false ``` | Field | Description | | ----- | ----------- | | **address** | gRPC server host: `corecast.bitquery.io` | | **authorization** | Your API token (usually starts with `ory_at_...`) | | **insecure** | Set `true` for unencrypted; prefer `false` (TLS) | --- ## How it works At runtime, the token from `config.server.authorization` is injected into gRPC metadata: ```js const metadata = new grpc.Metadata(); metadata.add('authorization', config.server.authorization); // Example stream const stream = client.DexTrades(request, metadata); ``` This adds an `authorization` header to the gRPC call. No other headers or credentials are required. --- ## Security * Always keep your token secret — do not hardcode it in your codebase. * Store it in `config.yaml`, an environment variable, or a secret manager. * If `insecure: true`, traffic will not be encrypted. Prefer TLS (`insecure: false`). --- ## Common Issues When authentication fails, you'll see gRPC error **code `16`** with HTTP status **`401 Unauthorized`**: ```json { "code": 16, "details": "Received HTTP status code 401" } ``` ### Causes * **Incorrect token** → Typo in `config.yaml` or copied wrong value. * **Missing token** → No `authorization` field in `config.yaml`. * **Expired token** → Token is no longer valid. ### Debugging Methods 1. **Verify token in `config.yaml`** Ensure it looks like: ```yaml server: authorization: "ory_at_xxx..." ``` and not empty. 2. **Check for quotes/whitespace** Tokens should be a single continuous string. No extra spaces or line breaks. 3. **Confirm token is active** If the token expired or was revoked, generate a new one from your Bitquery account. --- ## Solana gRPC Errors URL: https://docs.bitquery.io/docs/grpc/solana/errors/ Errors for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. Run it in the IDE, then ship in your app. # Error Handling When working with gRPC streams for Solana CoreCast, you may encounter errors. This page documents common error types, their causes, and how to debug them. ## Unauthorized **Code:** `16 (UNAUTHENTICATED)` **HTTP Status:** `401 Unauthorized` ### Causes * Access token is **missing** from `config.yaml`. * Access token is **incorrect** (typo, bad copy-paste). * Access token is **expired** or revoked. ### Example Output ```json { "code": 16, "details": "Received HTTP status code 401" } ``` ### How to Fix * Ensure `config.yaml` includes a valid token: ```yaml server: address: "corecast.bitquery.io" authorization: "ory_at_" insecure: false ``` * Check for trailing spaces or missing quotes. * [Generate](/docs/authorization/how-to-generate/) a new token if expired. --- ## Unsupported Stream Type **Details:** Error message will mention unsupported stream type. ### Cause The `config.stream.type` in `config.yaml` refers to a stream that isn’t available with Bitquery gRPC streams. ### Example Config ```yaml stream: type: "dex_trades" # ✅ supported ``` ### Supported Stream Types * [`dex_trades`](/docs/grpc/solana/topics/dextrades/) * [`transactions`](/docs/grpc/solana/topics/transactions/) * [`balances`](/docs/grpc/solana/topics/balance/) ### How to Fix * Double-check spelling of the stream type. * Only use supported values listed above. * Update your config if the API evolves. ## Runtime Errors Runtime errors can occur for many reasons, including: * Network connectivity issues. * Server-side failures (temporary outage, overload). * Incorrect filters in your request object. * Message parsing or serialization errors. ### Debugging Method To properly investigate runtime errors, add an error handler to your stream: ```js stream.on('error', (error) => { flushLogs(); console.error('Stream error:', error); console.error('Error details:', error.details); console.error('Error code:', error.code); console.error('Request sent:', JSON.stringify(request, null, 2)); }); ``` This will log the full error object, its details, the numeric error code, and the request you sent. With this context, you can narrow down whether the issue is related to authentication, filters, or transient server/network conditions. ## Best Practices * Always log `error.code` and `error.details`. * Use retries with exponential backoff for network issues. * Validate stream type and filters before starting. * Rotate tokens regularly and handle token expiry gracefully. --- ## Solana gRPC Introduction URL: https://docs.bitquery.io/docs/grpc/solana/introduction/ Introduction for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. See examples in the Bitquery IDE. # CoreCast - Smart Solana gRPC Streams ## What is Bitquery gRPC for Solana and how is it different from RPC? {#what-is-bitquery-grpc-for-solana-and-how-is-it-different-from-rpc} **Bitquery gRPC for Solana** is **CoreCast** (Smart gRPC Streams): a managed feed of **indexed, decoded** Solana activity delivered as **Protobuf** over gRPC to `corecast.bitquery.io`. You subscribe by **topic** (for example `dex_trades`, `transfers`, `transactions`) with **server-side filters** (addresses, mints, programs, thresholds), so you receive structured events not raw ledger blobs. **Solana RPC** (JSON-RPC from a validator or provider) is the chain’s **low-level API**: `getTransaction`, `getAccountInfo`, `getBlock`, simulation, and base64 logs. You typically **poll or subscribe** per method, **decode instructions and layouts yourself**, and stitch together DEX or token context. CoreCast is optimized for **low-latency, filtered market data**; RPC is for **generic chain access** and tooling that already expects JSON-RPC. For GraphQL + WebSocket on the same indexed data, see [real-time subscriptions](/docs/subscriptions/websockets/) and the [streaming overview](/docs/streams/). ### What are Smart gRPC Streams? Bitquery Smart gRPC Streams provide low-latency, context-aware, topic-wise event delivery from the Solana blockchain. Unlike raw gRPC streams, Smart Streams enrich and filter events so your application receives only the data it needs (trades,balances, token context, program metadata). The data is sent in the **protobuf format**, the schema is publicly available as packages for easy parsing. ### Why gRPC - **Low latency**: stream RPCs for near real-time delivery. - **Strong typing**: Protobuf contracts for stable schemas and efficient encoding. ### Topics Bitquery exposes multiple topics so you subscribe only to what you need: - **[transactions](/docs/grpc/solana/topics/transactions)**: Finalized transactions with instructions, logs, and status. - **transfers**: All token transfers with token context. - **[dex_trades](/docs/grpc/solana/topics/dextrades)**: DEX trade/swaps across supported protocols. - **dex_orders**: Order lifecycle updates where applicable. - **dex_pools**: Pool creation/updates and liquidity changes. - **[balances](/docs/grpc/solana/topics/balance)**: Balance updates for tracked accounts and mints. Each topic supports context-aware filters and consistent identifiers for easy correlation across streams. ### Context-aware filtering Filters are required to use Smart gRPC Streams. You must specify at least one filter per subscription; empty filter sets are rejected. Select exactly what to stream by combining filters. Common options include: - **addresses**: `senders`, `receivers`, `owners`, `program_ids` - **tokens**: Mint addresses (e.g., WSOL, USDC) and token standards - **value thresholds**: Minimal amounts in native or token units - **markets/pools**: By protocol, pool, or market identifiers (for DEX topics) Filters are applied server-side to reduce bandwidth and speed up downstream processing. ## Quick Start Examples - [JS Example](https://github.com/bitquery/grpc-code-samples/tree/main/js-demo) - [Python Example](https://github.com/bitquery/grpc-code-samples/tree/main/python-demo) - [Go Sample](https://github.com/bitquery/grpc-code-samples/tree/main/go-demo) ### Quickstart (YAML config example) Use a minimal configuration to subscribe to Solana transfers for specific addresses and tokens. Note: at least one filter is mandatory. ```yaml server: address: "corecast.bitquery.io" authorization: "" insecure: false stream: type: "transfers" # one of: transactions, transfers, dex_trades, dex_orders, dex_pools, balances filters: signers: - "7epLWkFd7xo18k4a4ySmN2UiiAFELDTV2ZNYAedCNh" # example address ``` **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) ## Schema for the Data - If you are a first time Bitquery user, schema is available in below mentioned files - [Solana](https://github.com/bitquery/streaming_protobuf/tree/main/solana) - [corecast](https://github.com/bitquery/streaming_protobuf/tree/main/solana/corecast) - If you are a Kafka user, the schema is the same as the Kafka schema, you only need the corecast schema The schema need not be downloaded, we have it as packages for install in NPM and PYPI. - Python `pip install bitquery-corecast-proto` - Node `npm install bitquery-corecast-proto` ## Is Solana gRPC (CoreCast) streaming included on the free plan? {#is-solana-grpc-corecast-streaming-included-on-the-free-plan} CoreCast uses the same **V2 API tokens** as the GraphQL IDE ([create a token](https://account.bitquery.io/user/api_v2/access_tokens); see [authentication](/docs/grpc/solana/authorization/)). Whether **Solana gRPC streaming** is enabled for your workspace, and how it relates to the Developer (free) tier or points, depends on your **plan and account entitlements**—it is not guaranteed to be unlimited or identical to self-serve GraphQL limits. Check [pricing](https://bitquery.io/pricing) and [Points](/docs/ide/points/); if you need access or a trial, use [Account → Billing](https://account.bitquery.io/user/billing) or contact [sales@bitquery.io](mailto:sales@bitquery.io). ## Does Bitquery support gRPC for chains other than Solana? {#does-bitquery-support-grpc-for-chains-other-than-solana} At present, Bitquery provides gRPC streaming exclusively for Solana. However, the platform is architected to support gRPC on other blockchains as well. If you require gRPC streaming for a blockchain outside of Solana, please reach out to the Bitquery sales team at sales@bitquery.io to explore custom solutions. --- ## Solana gRPC Stream Topics: Trades, Transfers, Balances, Pools URL: https://docs.bitquery.io/docs/category/topics/ The six CoreCast gRPC topics for Solana, what each message carries, the filters every stream needs, and which topic answers which question. # Solana gRPC Stream Topics: Trades, Transfers, Balances, Pools CoreCast, the Bitquery gRPC service for Solana at `corecast.bitquery.io`, delivers decoded chain activity as protobuf over six topics: `transactions`, `transfers`, `dex_trades`, `dex_orders`, `dex_pools` and `balances`. You subscribe to one topic per stream and must pass at least one filter (addresses, mints, value thresholds, or markets and pools), which the server applies before sending, so a stream carries only the rows you asked for. Authentication uses the same access token as the GraphQL API, sent as an `Authorization` header on each stream. This page says what each topic carries and which one answers which question; each topic page has the message schema and a runnable client. ## The six topics | Topic | Each message is | Typical filters | Guide | |---|---|---|---| | `dex_trades` | One DEX trade or swap across supported protocols (Pump.fun, Raydium, Orca, Jupiter and more), with both sides, amounts and the trader | program, market, mint, trader | [DEX trades](/docs/grpc/solana/topics/dextrades) | | `dex_orders` | An order placed, filled or cancelled on protocols that expose orders | program, market, owner | [DEX orders](/docs/grpc/solana/topics/dexorder) | | `dex_pools` | A pool created or its liquidity changed | program, pool, mint | [DEX pools](/docs/grpc/solana/topics/dexpools) | | `transfers` | One SOL or token transfer with sender, receiver and mint | senders, receivers, mints, minimum amount | [Transfers](/docs/grpc/solana/topics/transfer) | | `balances` | A balance change on an account or token account | owners, accounts, mints | [Balance updates](/docs/grpc/solana/topics/balance) | | `transactions` | A finalized transaction with instructions, logs and status | signers, program ids | [Transactions](/docs/grpc/solana/topics/transactions) | ## Which topic answers which question | Question | Topic | |---|---| | Every trade on one token or one pool, as it lands | `dex_trades` with a mint or market filter | | New pools and liquidity moves for a launchpad or DEX | `dex_pools` with a program filter | | Wallet in, wallet out, whale alerts | `transfers` with senders, receivers and a minimum amount | | Portfolio changes for a set of wallets | `balances` with owners | | Everything a program did, including failed calls and logs | `transactions` with a program id | | Limit-order style venues (placement and fills) | `dex_orders` | Two habits save time. Filter as tightly as the question allows, because an empty filter set is rejected and a loose one costs bandwidth on both ends. And correlate across topics by transaction signature: a `dex_trades` row and the `transfers` rows behind it share it. ## Try the same rows in the IDE first Every topic has a GraphQL subscription with the same data, so you can see the shape of a message in the [Bitquery IDE](https://ide.bitquery.io) on a free account before you write a gRPC client. This is the WebSocket twin of `dex_trades` filtered to Raydium: ```graphql subscription { Solana { DEXTrades( where: { Trade: { Dex: { ProtocolFamily: { is: "Raydium" } } }, Transaction: { Result: { Success: true } } } ) { Block { Time } Trade { Dex { ProtocolName } Buy { Amount Currency { Symbol } } Sell { Amount Currency { Symbol } } } Transaction { Signature } } } } ``` When you move to gRPC, the [introduction](/docs/grpc/solana/introduction) has a YAML quickstart, [authentication](/docs/grpc/solana/authorization) covers the token header, and [best practices](/docs/grpc/solana/best_practices) covers reconnects, error handling and filter design. Worked clients live in [Pump.fun gRPC streams](/docs/grpc/solana/examples/pump-fun-grpc-streams), [LetsBonk gRPC streams](/docs/grpc/solana/examples/letsbonk-grpc-streams) and the [copy-trading bot](/docs/grpc/solana/examples/grpc-copy-trading-bot). ## Related pages - [Solana gRPC introduction (CoreCast)](/docs/grpc/solana/introduction) - [Kafka streams](/docs/category/kafka-streams) - [Real-time streaming compared: WebSocket, Kafka and gRPC](/docs/streams/) - [Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades) --- ## Sorting Results in Bitquery GraphQL URL: https://docs.bitquery.io/docs/graphql/sorting/ Sorting Results in Bitquery GraphQL in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Sorting Ordering can be applied to the results of the query, sorting the results in a way you define. Use attribute `orderBy` to define the ascending / descending way the results to be sorted. ``` Transactions( orderBy: { descending: Transaction_Value }) ``` ## Multiple Conditions If multiple sorting conditions are used, they applied in the order you define them: ``` orderBy: { descending: Transaction_Value ascending: Block_Number } ``` First results will be sorted by Transaction_Value and after that by Block_Number. Another way to sort on multiple condition is following ```graphql { EVM { Events( orderBy: [{ascending: Transaction_Index}, {ascending: Call_Index}, {ascending: Log_Index}] ) { Transaction { Index } Call { Index } Log { Index Signature { Signature } } } } } ``` :::note this is not the same as: ``` orderBy: { ascending: Block_Number descending: Transaction_Value } ``` ::: The example below shows how to sort transfers by their index within a block in ascending order, ```graphql { EVM(dataset: archive) { Transfers( limit: {count: 20} where: {Transfer: {Success: true, Sender: {is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549"}}} orderBy: {ascendingByField: "Transaction_Index", descending: Block_Time} ) { amount: sum(of: Transfer_Amount) Block { Time } Transfer { Receiver Sender } Transaction { Hash Index Value } } } } ``` `orderBy: {ascendingByField: "Transaction_Index", descending: "Block_Time"}` sorts the results first by the transaction index within a block in ascending order, ensuring that transactions are listed in the order they were executed. Secondly, it sorts by block time in descending order, prioritizing newer blocks. ## Sort by Metrics If you use [metrics](/docs/graphql/metrics/) or [calculations](/docs/graphql/calculations) in the query, you can sort by them using `descendingByField` and `ascendingByField` attributes. You must write the name of the **metric** (`count`) or **alias** of the metric (`txCount`) as shown on this example: ```graphql { EVM { Transactions( orderBy: { descendingByField: "txCount" } limit: { count: 10 } ) { Block { Number } txCount: count } } } ``` ## How do I get the most recent entry only from a Bitquery query? To fetch only the most recent entry (such as the latest trade, event, or transaction), use the `orderBy` argument to sort results by `Block_Time` in descending order (`{descending: Block_Time}`). To guarantee correct chronological ordering and resolve ties between events occurring in the same block, add secondary sort fields such as `Transaction_Index` or even lower levels like `Instruction_Index` and `Trade_Index` if available. This approach ensures your query will always return the latest entry—even in high-throughput chains or when multiple events share the same block time. Recommended ordering for the latest record: - First, sort by `Block_Time`—`{descending: Block_Time}`—to prioritize the newest blocks first. - Next, add `Transaction_Index`—`{descending: Transaction_Index}`—for precise ordering within a block. - Then, add `Instruction_Index` and/or `Trade_Index`—`{descending: Instruction_Index}`, `{descending: Trade_Index}`—to resolve ordering among instructions or trades that occur within the same transaction. This multi-level ordering creates a stable, deterministic way to get the most recent record, or to paginate results with full reliability. **Example: Get the latest trade on Solana (DEXTradeByTokens cube)** ```graphql { Solana { DEXTradeByTokens( orderBy: [ {descending: Block_Time}, {descending: Transaction_Index}, {descending: Instruction_Index}, {descending: Trade_Index} ] limit: {count: 1} ) { Transaction { Signature } } } } ``` In this example, the query returns exactly one result (the most recent trade), sorted by block time, transaction index, instruction index, and trade index—all in descending order to ensure true "latest" ordering. ## What does the desc option do in a Bitquery query? **API V2** uses **`orderBy: { descending: … }`** or **`ascending`**, not a standalone **`desc`** option on the root query. **API V1** examples often used **`options: { desc: [ ... ], limit, offset }`**. For migration and side‑by‑side examples, see [Migrate Bitquery API V1 to V2](/docs/API-Blog/migrate-v1-v2/). --- ## Stablecoin Balance API URL: https://docs.bitquery.io/docs/stablecoin-APIs/stablecoin-balance-api/ Stablecoin Balance API using Bitquery stablecoin APIs for prices, transfers, payments, and cross-chain monitoring workflows. # Stablecoin Balance API :::danger `BalanceUpdates` sunsets 10 August 2026 Queries on this page that use **`BalanceUpdates`** will stop working on **10 August 2026**. Migrate to the **`Balances`** and **`Holders`** cubes, which return the current balance directly instead of summing deltas. See the [migration mapping](/docs/cubes/balances-cube/#migrating-from-balanceupdates) for the query-by-query translation. ::: The Stablecoin API by Bitquery provides you the comprehensive set of APIs which can provide you realtime transfers, realtime trades, realtime price, holder distribution of stablecoins across chains with a single API call. We are going to particularly deep-dive into how to get Stablecoin Balance data in this section. ## Stablecoin Balance of an Address ### Solana Below stream will give you balance of `9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM` for `FDUSD` on Solana. Test the query [here](https://ide.bitquery.io/FDUSD-balance-of-an-address). ```graphql query MyQuery { Solana { BalanceUpdates( where: {BalanceUpdate: {Account: {Owner: {is: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"}}, Currency: {MintAddress: {is: "9zNQRsGLjNKwCUU5Gq5LR8beUCPzQMVMqKAi3SSZh54u"}}}} orderBy: {descendingByField: "BalanceUpdate_Balance_maximum"} ) { BalanceUpdate { Balance: PostBalance(maximum: Block_Slot) Currency { Name Symbol } } } } } ``` ### Ethereum [Run Query](https://ide.bitquery.io/ethereum-stablecoin-balances-address) ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0xcf1DC766Fc2c62bef0b67A8De666c8e67aCf35f6" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD } } } } ``` ### Tron Below query will give you **USDT** balance for address `TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ` on Tron. Test the query [here](https://ide.bitquery.io/Stablecoin-Balance-of-an-Address). **Migrated query** — use this. `BalanceUpdates` sunsets 10 August 2026. ```graphql query MyQuery { Tron(dataset: combined) { Balances( where: {Balance: {Address: {is: "TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ"}}, Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}} orderBy: { descending: Balance_Amount } ) { Currency { Name } Balance { Amount(selectWhere: {gt: "0"}) } Balance { Address } } } } ```
Old BalanceUpdates version (stops working 10 August 2026) ```graphql query MyQuery { Tron(dataset: combined) { BalanceUpdates( where: {BalanceUpdate: {Address: {is: "TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ"}}, Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}} orderBy: {descendingByField: "balance"} ) { Currency { Name } balance: sum(of: BalanceUpdate_Amount, selectWhere: {gt: "0"}) BalanceUpdate { Address } } } } ```
More examples on balance and balance updates on EVM chains can be found [here](/docs/blockchain/Ethereum/balances/balance-api/) Token holder API examples can be found [here](/docs/blockchain/Ethereum/token-holders/token-holder-api/) ## Get Top 100 Holders of a Particular Stablecoin [This query](https://ide.bitquery.io/top-100-holders-of-USDC-token-on-Solana) returns the top 100 holders of a particular Stablecoin. ```graphql query MyQuery { Solana { BalanceUpdates( orderBy: {descendingByField: "BalanceUpdate_Holding_maximum"} where: {BalanceUpdate: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}, }, Transaction: {Result: {Success: true}}} ) { BalanceUpdate { Currency { Name MintAddress Symbol } Account { Address } Holding: PostBalance(maximum: Block_Slot selectWhere:{gt:"0"}) } } } } ``` --- ## Stablecoin Payments API URL: https://docs.bitquery.io/docs/stablecoin-APIs/stablecoin-payments-api/ Stablecoin Payments API using Bitquery stablecoin APIs for prices, transfers, payments, and cross-chain monitoring workflows. # Stablecoin Payments API Bitquery's Stablecoin Payments API exposes real-time and historical payment flows for USDT, USDC, FDUSD, EURC, DAI, TUSD, USDS, USD1, USDD and other major stablecoins across Solana, Ethereum, Tron, BSC, Base, Arbitrum, Polygon and more — through a single GraphQL endpoint. This page focuses on payment-oriented use cases (incoming/outgoing transfers, merchant detection, address monitoring, AML/compliance). For related capabilities, see the [Stablecoin Transfers API](/docs/stablecoin-APIs/stablecoin-transfers-api), [Stablecoin Balance API](/docs/stablecoin-APIs/stablecoin-balance-api), [Stablecoin Trades API](/docs/stablecoin-APIs/stablecoin-trades-api), [Stablecoin Reserve API](/docs/stablecoin-APIs/stablecoin-reserve-api) and [Stablecoin Price API](/docs/stablecoin-APIs/stablecoin-price-api). All examples below are runnable in the [Bitquery IDE](https://ide.bitquery.io). Streams are delivered over WebSocket / Kafka subscriptions; historical queries use the same schema over HTTP. For pre-built stablecoin dashboards (top tokens, flows, market activity), browse the [DEXrabbit Stablecoins dashboard](https://dexrabbit.bitquery.io/categories/stablecoins). ## Stablecoin Payment API Examples ### 1. Listening to All USDT and USDC Payments on Solana This GraphQL stream provides **live USDT and USDC stablecoin transfers** on Solana. 🔗 [Stream Example](https://ide.bitquery.io/USDT-and-USDC-token-Transfers-stream-on-solana) 🔗 [API Example](https://ide.bitquery.io/USDT-and-USDC-token-Transfers-api-on-solana) ```graphql subscription { Solana { Transfers( where: { Transfer: { Currency: { MintAddress: { in: [ "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" ] } } } } ) { Transfer { Amount AmountInUSD Sender { Address Owner } Receiver { Address Owner } Currency { Symbol Name MintAddress } } Instruction { Program { Method } } Block { Time Height Slot } Transaction { Signature Signer Fee FeeInUSD FeePayer } } } } ``` ### 2. Multi-Chain Stablecoin Payments Listen to **stablecoin payments across all major blockchains**. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. | Blockchain | API | Stream | Mempool | |------------|-----|--------|---------| | **Tron** | [API](https://ide.bitquery.io/Latest-Tron-USDT-Transfers) | [Stream](https://ide.bitquery.io/Latest-Tron-USDT-Transfers-stream) | [Mempool](https://ide.bitquery.io/Latest-Tron-USDT-Transfers-stream-in-Mempool) | | **Ethereum** | [API](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-api-on-ethereum) | [Stream](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-stream-on-ethereum) | [Mempool](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-stream-on-ethereum-in-Mempool) | | **BSC** | [API](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-api-on-BSC_2) | [Stream](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-Stream-on-BSC) | [Mempool](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-Stream-on-BSC-on-Mempool) | | **Base** | [API](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-api-on-base) | [Stream](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-stream-on-base) | Not Available | Mempool feeds are produced by simulating transactions on top of the current block. ### 3. Listening to USDT Payments on Tron (stream) This subscription streams **USDT** (`TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`) transfers on **Tron** — the highest-volume stablecoin payments network globally. 🔗 [Stream Example](https://ide.bitquery.io/Listening-to-All-USDT-and-USDC-Payments-on-Solana---stream) ```graphql subscription { Tron(network: tron) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}}} ) { Transaction { Hash } Transfer { Amount Currency { Name Symbol } Receiver Sender } } } } ``` ### 4. Stablecoin Payments For a Specific Address (Tron) Listen to **USDT** sent or received by address `TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ`. This is the canonical "merchant/treasury wallet monitor" pattern — fan-out one subscription per wallet and route hits to your payments backend. 🔗 [Stream Example](https://ide.bitquery.io/Listening-to-stablecoin-Transfers-for-Specific-Addresse-on-tron) ```graphql subscription { Tron { Transfers( where: {any: [{Transfer: {Sender: {is: "TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ"}}}, {Transfer: {Receiver: {is: "TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ"}}}], Transfer: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}}} ) { Transaction { Hash } Transfer { Amount AmountInUSD Sender Receiver } } } } ``` For the equivalent on Solana, see the [Stablecoin Transfers API → Stablecoin received and sent by an address](/docs/stablecoin-APIs/stablecoin-transfers-api#stablecoin-recieved-and-sent-by-an-address). ### 5. Stablecoin Payments For a Specific Address (BSC) Filter incoming **USDT and USDC** payments to a single BSC receiver across both stablecoin contracts in one subscription. 🔗 [Example Query](https://ide.bitquery.io/USDT-and-USDC-transfers-on-bnb-chain) ```graphql subscription { EVM(network: bsc) { Transfers( where: { Transfer: { Receiver: { in: ["0x443fa7bbf35c09ee0ebb5e15f1ea3f0704b89d04"] } Currency: { SmartContract: { in: [ "0x55d398326f99059ff775485246999027b3197955" "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d" ] } } } } ) { Block { Time Number } Transfer { Sender Receiver Amount AmountInUSD Currency { Name Symbol SmartContract } } Transaction { Hash From To } } } } ``` ### 6. Stablecoin Payments Stream on Ethereum A single-contract USDC payments stream on Ethereum mainnet. Swap the `SmartContract` for `0xdAC17F958D2ee523a2206206994597C13D831ec7` to get USDT, or extend with an `in: [...]` list to multiplex stablecoins. 🔗 [Stream Example](https://ide.bitquery.io/Stablecoin-Realtime-Payments-Stream-on-Eth-Mainnet) ```graphql subscription { EVM(network: eth) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"}}}} ) { Transaction { Hash } Transfer { Amount Currency { Name Symbol } Receiver Sender Type } } } } ``` For the full transfer schema (mint/burn detection, `Type`, dataset selection), see the [Stablecoin Transfers API](/docs/stablecoin-APIs/stablecoin-transfers-api). ## Compliance & Risk Checks For **AML/KYC and risk monitoring**, you can analyze a payment counterparty's lifecycle on the asset — first and last activity dates, total change count, and current balance — in a single query. The `Holders` cube does not break activity down by direction. For separate inbound and outbound counts or amounts, aggregate the [Transfers cube](/docs/cubes/transfers-cube) by `Transfer.Sender` / `Transfer.Receiver` instead. 🔗 [Example API](https://ide.bitquery.io/stats-for-an-adddress) ```graphql { EVM(dataset: archive, network: eth) { Holders( date: "2025-08-25" where: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } }, Holder: { Address: { is: "0x72187db55473b693ded367983212fe2db3768829" } } } ) { Holder { Address } Balance { UpdateCount FirstChangeTime LastChangeTime Amount } } } } ``` To verify the live balance of a payer/payee on any chain, see the [Stablecoin Balance API](/docs/stablecoin-APIs/stablecoin-balance-api) (Solana, Ethereum and Tron examples included). ### Confirming the Sender's Solvency Before Settlement Before releasing goods or off-ramping a stablecoin payment, you may want to verify the sender actually held the asset at the moment of transfer. Use the [Stablecoin Balance API](/docs/stablecoin-APIs/stablecoin-balance-api#stablecoin-balance-of-an-address) to fetch a wallet's current stablecoin balance per chain. For supply-side checks (e.g. confirming an issuer mint backed an inbound payment), use the [Stablecoin Reserve API](/docs/stablecoin-APIs/stablecoin-reserve-api). ## Payment Analytics ### 1. First-Time Stablecoin Receivers Identify addresses receiving stablecoins for the **first time** on a given date — useful for new-customer attribution and onboarding analytics. 🔗 [Query Example](https://ide.bitquery.io/first-time-UDST-received-by-addresses-on-a-given-date) ```graphql { EVM(dataset: archive, network: eth) { Holders( limit: { count: 1000 } date: "2025-08-25" where: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } }, BalanceUpdate: { FirstDate: { is: "2025-08-25" } } } ) { Holder { Address } } } } ``` ### 2. Last-Time Stablecoin Receivers Identify addresses that **last received USDT** on a specific date — useful for churn detection and dormant-wallet analysis. 🔗 [Query Example](https://ide.bitquery.io/Address-which-received-USDT-on-a-given-date-last-time) ```graphql { EVM(dataset: archive, network: eth) { Holders( orderBy: { descending: Balance_Amount } limit: { count: 1000 } date: "2025-08-25" where: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } }, BalanceUpdate: { LastDate: { is: "2021-01-01" } } } ) { Holder { Address } Balance { FirstChangeTime LastChangeTime Amount } } } } ``` ### 3. Top Stablecoin Holders Find **top holders of USDT on Ethereum**, with current balance and activity history (first change, last change, total change count). For directional inflow/outflow totals, aggregate the [Transfers cube](/docs/cubes/transfers-cube) by sender and receiver. The [Stablecoin Balance API](/docs/stablecoin-APIs/stablecoin-balance-api#get-top-100-holders-of-a-particular-stablecoin) covers the same pattern on Solana. 🔗 [Query Example](https://ide.bitquery.io/Top-holders-of-usdt-on-specific-date) ```graphql { EVM(dataset: archive, network: eth) { Holders( orderBy: [{ descending: Balance_Amount }] limit: { count: 100 } date: "2025-08-25", where: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } ) { Holder { Address } Balance { UpdateCount FirstChangeTime LastChangeTime Amount } } } } ``` ## Pricing Stablecoin Payments Accurately For high-value or cross-border payments, even a 20–50 bps deviation from the peg materially changes settlement value. Use the [Stablecoin Price API](/docs/stablecoin-APIs/stablecoin-price-api) to: - [Stream the latest price](/docs/stablecoin-APIs/stablecoin-price-api#stream-latest-stablecoin-price) of USDT/USDC/DAI/USDS at 1-second intervals. - [Compare prices across chains](/docs/stablecoin-APIs/stablecoin-price-api#check-arbitrage-of-a-stablecoin-across-chains) to mark the payment to its true on-chain rate. - [Monitor peg health per DEX/market](/docs/stablecoin-APIs/stablecoin-price-api#stablecoin-peg-health-api) to catch a depeg before it hits your treasury. For depeg detection at the trade level (alerting when any trade prints outside `0.95–1.05`), see the [Stablecoin Trades API → Depeg tracking streams](/docs/stablecoin-APIs/stablecoin-trades-api#stablecoin-depeg-tracking-stream-for-evm). ## Asset-Specific Guides For deep-dives on a single asset (price + payments + trades + reserves + balances curated together), see [USDT API](/docs/stablecoin-APIs/usdt-api). ## Why Use Bitquery for Stablecoin Payments? - **Real-time streams (WebSocket & Kafka)** for instant detection. - **Mempool visibility** on Tron, Ethereum and BSC for pre-confirmation UX. - **Webhook support** to integrate with your payment systems. - **Compliance-focused APIs** for AML/KYC and risk analysis. - **Multi-chain coverage** across Solana, Ethereum, Tron, BSC, Base, Arbitrum, Polygon and more. Bitquery enables **faster, compliant, and scalable stablecoin payment solutions** for businesses, fintechs, and governments. --- ## Stablecoin Price API URL: https://docs.bitquery.io/docs/stablecoin-APIs/stablecoin-price-api/ Stablecoin Price API using Bitquery stablecoin APIs for prices, transfers, payments, and cross-chain monitoring workflows. # Stablecoin Price API While stablecoins are designed to maintain a stable value (typically pegged to USD, EUR, or other assets), they can deviate slightly from their target price (e.g., $0.998 or $1.02 for USD-pegged stablecoins). For developers, traders, and businesses processing large volumes of stablecoin payments, even these small deviations can translate to significant financial impact at scale. Bitquery's Stablecoin API provides comprehensive real-time data including transfers, trades, prices, and holder distribution across multiple blockchain networks—all accessible through a single API call. Track minute price changes, fetch blended average prices, and identify arbitrage opportunities across different platforms with precision and ease. This is built on the extensive [Crypto Price APIs](/docs/trading/crypto-price-api/) Need help implementing stablecoin price APIs? Contact our support team or join our community discussion on [@Bloxy_info](https://t.me/bloxy_info). ## Stream Latest Stablecoin Price [Run Stream](https://ide.bitquery.io/stablecoin-1-second-price-stream) ```graphql subscription { Trading { Tokens( where: {Interval: {Time: {Duration: {eq: 1}}}, Currency: {Id: {in: ["usdt", "usdc", "tusd", "usdd", "usds", "usd₮0", "usd1", "dai"]}}} ) { 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 } } } } } ``` ## 5 Minute Price Change Stablecoin API [Run Query](https://ide.bitquery.io/5-minute-price-change-stablecoin-API) ```graphql { Trading { Tokens( limit: {count: 10} limitBy: {count: 1, by: Token_Id} orderBy: [{descending: Block_Time}, {descendingByField: "change"}] where: {Currency: {Id: {in: ["usdt", "usdc", "tusd", "usdd", "usds", "usd₮0", "usd1", "dai"]}}, 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 Quote Usd } 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") } } } ``` ## Check Arbitrage of a Stablecoin Across Chains This query compares USDT prices across different blockchain networks in real-time. It fetches the latest price data for USDT from different networks, showing you where the same stablecoin trades at different prices. **What this tells traders:** - **Price discrepancies**: See which networks have USDT trading above or below $1.00 - **Volume context**: Understand trading volume on each network to assess liquidity - **Timing**: Get 1-second interval data to catch fleeting arbitrage windows - **Network comparison**: Compare prices across Ethereum, BSC, Polygon, and other major networks [Run Query](https://ide.bitquery.io/usdt-latest-price-arbitrage) ```graphql { Trading { Tokens( where: {Interval: {Time: {Duration: {eq: 1}}}, Currency: {Id: {is: "usdt"}}} limit: {count: 100} limitBy: {by: Token_Network, count: 1} ) { 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 } } } } } ``` ## Stablecoin Peg Health API Monitor stablecoin peg health by getting the **latest price per DEX/market** for a stablecoin. This helps identify which exchanges or markets have the stablecoin trading closest to its peg (e.g., $1.00 for USD-pegged stablecoins) and detect de-pegging events across different trading venues. Browse live multi-chain stablecoin DEX prices on [DEXrabbit's Stablecoins category](https://dexrabbit.bitquery.io/categories/stablecoins). ### Solana Peg Health Get the latest price of a stablecoin across all Solana DEXs/markets. Returns one row per market with the most recent trade price. [Run in Bitquery IDE](https://ide.bitquery.io/Latest-Price-of-a-Token-on-all-exchanges_1) ```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 } } } } } ``` ### Ethereum / BSC Peg Health Get the latest price of a stablecoin across all EVM DEXs. Returns one row per DEX protocol with the most recent trade price. Works on Ethereum, BSC, and other EVM chains. [Run in Bitquery IDE](https://ide.bitquery.io/evm-peg-health_1) ```graphql { EVM(network: eth) { DEXTradeByTokens( orderBy: { descending: Block_Time } limitBy: { count: 1, by: Trade_Dex_SmartContract } where: { Trade: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } ) { 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 } } } } } ``` ### Tron Peg Health Get the latest price of a stablecoin across all Tron DEXs. Returns one row per DEX protocol with the most recent trade price. [Run in Bitquery IDE](https://ide.bitquery.io/peg-health-tron) ```graphql { Tron { DEXTradeByTokens( orderBy: { descending: Block_Time } limitBy: { count: 1, by: Trade_Dex_SmartContract } where: { Trade: { Currency: { SmartContract: { is: "TXL6rJbvmjD46zeN1JssfgxvSo99qC8MRT" } } } } ) { 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 } } } } } ``` --- ## Stablecoin Reserve API URL: https://docs.bitquery.io/docs/stablecoin-APIs/stablecoin-reserve-api/ Stablecoin Reserve API using Bitquery stablecoin APIs for prices, transfers, payments, and cross-chain monitoring workflows. # Stablecoin Reserve API The Stablecoin API by Bitquery provides you the comprehensive set of APIs which can provide you realtime reserves data, realtime transfers, realtime trades, realtime price, holder distribution of stablecoins across chains with a single API call. We are going to particularly deep-dive into how to get Stablecoin Transfers data in this section. ## Ethereum ### USDT Stablecoin reserves on Ethereum Below API query will give you realtime reserves data of `USDT` on Ethereum. Test the API [here](https://ide.bitquery.io/USDT-Stablecoin-reserves-on-Ethereum). ```graphql query MyQuery { EVM(network: eth, dataset: combined) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xdAC17F958D2ee523a2206206994597C13D831ec7"}}, Success: true}} ) { minted: sum( of: Transfer_Amount if: {Transfer: {Sender: {is: "0x0000000000000000000000000000000000000000"}}} ) burned: sum( of: Transfer_Amount if: {Transfer: {Receiver: {is: "0x0000000000000000000000000000000000000000"}}} ) } } } ``` ## Solana ### USDC Stablecoin reserves on Solana Below API query will give you realtime reserves data of `USDC` on Solana. Test the API [here](https://ide.bitquery.io/USDC-Stablecoin-reserves-on-Solana). ```graphql { Solana { TokenSupplyUpdates( limit:{count:1} orderBy:{descending:Block_Time} where: {TokenSupplyUpdate: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { TokenSupplyUpdate { Amount Currency { MintAddress Name } PreBalance PostBalance } } } } ``` ## Tron ### USDT Stablecoin reserves on Tron Below API query will give you realtime reserves data of `USDT` on Tron. Test the API [here](https://ide.bitquery.io/USDT-Stablecoin-reserves-on-Tron). ```graphql query MyQuery { Tron(dataset: combined) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}, Success: true}} ) { minted: sum( of: Transfer_Amount if: {Transfer: {Sender: {is: "THPvaUhoh2Qn2y9THCZML3H815hhFhn5YC"}}} ) burned: sum( of: Transfer_Amount if: {Transfer: {Receiver: {is: "THPvaUhoh2Qn2y9THCZML3H815hhFhn5YC"}}} ) } } } ``` --- ## Stablecoin Trades API: USDT and USDC DEX Trades, Depeg Checks and Wallet Flows URL: https://docs.bitquery.io/docs/stablecoin-APIs/stablecoin-trades-api/ Stablecoin DEX trades on Ethereum, Solana and Tron via Bitquery GraphQL: live USDT streams, off-peg trade checks with a USD floor, a wallet's stablecoin flows. # Stablecoin Trades API: USDT and USDC DEX Trades, Depeg Checks and Wallet Flows Stablecoins are the quote side of most DEX volume, so a stablecoin trade feed is close to a feed of everything. This page filters Bitquery's trade cubes down to one stablecoin at a time on Ethereum, Solana and Tron: the live trades, the trades that printed away from one dollar, and what one wallet did with its USDC. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. Solana queries go to the `eap` endpoint, Ethereum and Tron to `graphql`. The [Trading cube](/docs/trading/crypto-trades-api/trades-api) gives the same trades across nine chains with USD on every row for the last month, which is the first section; the chain cubes below add history and per-pool detail. ## Live USDT trades across all chains One subscription, every chain, filtered on the symbol. ```graphql subscription { Trading { Trades(where: { Pair: { Currency: { Symbol: { is: "USDT" } } } }) { Block { Time } Price PriceInUsd AmountsInUsd { Base Quote } Pair { Currency { Id Symbol } Token { Symbol Network } QuoteToken { Symbol } Market { Network Protocol } } } } } ``` For ready-made stablecoin dashboards, browse [DEXrabbit's Stablecoins category](https://dexrabbit.bitquery.io/categories/stablecoins). ## Ethereum ### USDT trades on Ethereum, live `DEXTradeByTokens` gives one row per trade with USDT under `Trade.Currency`, whichever side it was on. Saved stream [here](https://ide.bitquery.io/Stablecoin-trades-for-etheruem). ```graphql subscription { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } } ) { Block { Time } Transaction { Hash From } Trade { Amount AmountInUSD Price PriceInUSD Side { Type Amount AmountInUSD Currency { Symbol SmartContract } } Dex { ProtocolName SmartContract } } } } } ``` ### USDT trades away from the peg on Ethereum {#stablecoin-depeg-tracking-stream-for-evm} A depeg check has to ignore dust and thin pairs, or it fires all day. This query keeps trades against WETH or USDC worth over a thousand dollars whose USDT price printed more than half a percent from one dollar, over the last day. Two ranges on one field need `any`; a single `PriceInUSD: {lt, gt}` block is an AND and matches nothing. Widen the band or shorten the window for alerts, or run it as a subscription without the `Block` filter. Saved query [here](https://ide.bitquery.io/Stablecoin-Depeg-tracking-Stream-for-evm). ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } Side: { AmountInUSD: { gt: "1000" } Currency: { SmartContract: { in: [ "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" ] } } } } any: [ { Trade: { PriceInUSD: { lt: 0.995 } } } { Trade: { PriceInUSD: { gt: 1.005 } } } ] Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 50 } orderBy: { descending: Block_Time } ) { Block { Time } Transaction { Hash } Trade { PriceInUSD Amount AmountInUSD Side { Currency { Symbol } AmountInUSD } Dex { ProtocolName SmartContract } } } } } ``` ## Solana ### USDT trades on Solana, live Both sides of each swap, with the accounts and the market. Saved stream [here](https://ide.bitquery.io/solana-trades-subscription_10_1). ```graphql subscription { Solana { DEXTrades( where: { any: [ { Trade: { Buy: { Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } } } } { Trade: { Sell: { Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } } } } ] Transaction: { Result: { Success: true } } } ) { Block { Time Slot } Transaction { Signature Signer } Trade { Dex { ProgramAddress ProtocolName } Market { MarketAddress } Buy { Amount AmountInUSD Price PriceInUSD Currency { Symbol MintAddress } Account { Address } } Sell { Amount AmountInUSD Currency { Symbol MintAddress } Account { Address } } } } } } ``` ### One wallet's stablecoin flows on Solana Filter the transaction signer and the stablecoin mints. The example wallet swaps USDC around the clock at the time of writing; the totals split what it bought from what it sold. Saved query [here](https://ide.bitquery.io/real-time-stablecoin-portfolio_2). ```graphql { Solana { DEXTradeByTokens( where: { Transaction: { Signer: { is: "3i51cKbLbaKAqvRJdCUaq9hsnvf9kqCfMujNgFj7nRKt" } Result: { Success: true } } Trade: { Currency: { MintAddress: { in: [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" ] } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } ) { Trade { Currency { Symbol MintAddress } } trades: count bought: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: sell } } } }) sold: sum(of: Trade_Amount, if: { Trade: { Side: { Type: { is: buy } } } }) } } } ``` Drop the aggregates and the `Block` filter and subscribe to the same `where` for each swap as it happens: ```graphql subscription { Solana { DEXTradeByTokens( where: { Transaction: { Signer: { is: "3i51cKbLbaKAqvRJdCUaq9hsnvf9kqCfMujNgFj7nRKt" } Result: { Success: true } } Trade: { Currency: { MintAddress: { in: [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" ] } } } } ) { Block { Time } Trade { Currency { Symbol } Amount AmountInUSD Side { Type Amount Currency { Symbol } } } Transaction { Signature } } } } ``` ### USDT trades away from the peg on Solana Same band and floor as the Ethereum check, against USDC or WSOL so that thin memecoin pairs do not set off the alarm. Saved query [here](https://ide.bitquery.io/stablecoin-depeg-tracking-stream-for-USDC). ```graphql { Solana { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" } } Side: { AmountInUSD: { gt: "1000" } Currency: { MintAddress: { in: [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" "So11111111111111111111111111111111111111112" ] } } } } any: [ { Trade: { PriceInUSD: { lt: 0.995 } } } { Trade: { PriceInUSD: { gt: 1.005 } } } ] Transaction: { Result: { Success: true } } Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 50 } orderBy: { descending: Block_Time } ) { Block { Time } Transaction { Signature } Trade { PriceInUSD Amount AmountInUSD Side { Currency { Symbol } AmountInUSD } Dex { ProtocolName } Market { MarketAddress } } } } } ``` ## Tron ### USDT trades on Tron, live Most Tron DEX volume is USDT against TRX on SunSwap. Streams on Tron match currencies by symbol; use the contract address, `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`, in queries. Saved stream [here](https://ide.bitquery.io/Stablecoin-trades-for-tron). ```graphql subscription { Tron { DEXTradeByTokens(where: { Trade: { Currency: { Symbol: { is: "USDT" } } } }) { Block { Time } Transaction { Hash } Trade { Amount AmountInUSD PriceInUSD Side { Type Amount Currency { Symbol } } Dex { ProtocolName } } } } } ``` ### USDT trades away from the peg on Tron The band check for Tron, with the USD floor and no counter-token list, since almost everything on Tron is quoted in TRX. Saved query [here](https://ide.bitquery.io/Stablecoin-Depeg-tracking-Stream-for-tron). ```graphql { Tron { DEXTradeByTokens( where: { Trade: { Currency: { SmartContract: { is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" } } Side: { AmountInUSD: { gt: "1000" } } } any: [ { Trade: { PriceInUSD: { lt: 0.995 } } } { Trade: { PriceInUSD: { gt: 1.005 } } } ] Block: { Time: { since_relative: { hours_ago: 24 } } } } limit: { count: 50 } orderBy: { descending: Block_Time } ) { Block { Time } Transaction { Hash } Trade { PriceInUSD Amount AmountInUSD Side { Currency { Symbol } AmountInUSD } Dex { ProtocolName } } } } } ``` ## Related pages - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) - [Ethereum DEX trades API](/docs/blockchain/Ethereum/dextrades/dex-api) - [Solana DEX trades API](/docs/blockchain/Solana/solana-dextrades) - [Tron DEX trades API](/docs/blockchain/Tron/tron-dextrades) --- ## Stablecoin Transfers API URL: https://docs.bitquery.io/docs/stablecoin-APIs/stablecoin-transfers-api/ Stablecoin Transfers API using Bitquery stablecoin APIs for prices, transfers, payments, and cross-chain monitoring workflows. # Stablecoin Transfers API The Stablecoin API by Bitquery provides you the comprehensive set of APIs which can provide you realtime transfers, realtime trades, realtime price, holder distribution of stablecoins across chains with a single API call. We are going to particularly deep-dive into how to get Stablecoin Transfers data in this section. ## Ethereum ### Stablecoin Realtime Transfers Stream on Eth Mainnet Below stream will give you realtime transfers of `USDC` on Eth mainnet. Test the stream [here](https://ide.bitquery.io/Stablecoin-Realtime-Payments-Stream-on-Eth-Mainnet). ```graphql subscription { EVM(network: eth) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"}}}} ) { Transaction { Hash } Transfer { Amount Currency { Name Symbol } Receiver Sender Type } } } } ``` ### Stablecoin mint/burn on Ethereum Below API query will give you mint/burn data of `USDT` on Ethereum. Test the API [here](https://ide.bitquery.io/USDT-Stablecoin-reserves-on-Ethereum). ```graphql query MyQuery { EVM(network: eth, dataset: combined) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "0xdAC17F958D2ee523a2206206994597C13D831ec7"}}, Success: true}} ) { minted: sum( of: Transfer_Amount if: {Transfer: {Sender: {is: "0x0000000000000000000000000000000000000000"}}} ) burned: sum( of: Transfer_Amount if: {Transfer: {Receiver: {is: "0x0000000000000000000000000000000000000000"}}} ) } } } ``` ## Solana ### Stablecoin Realtime Transfers Stream Below stream will give you realtime transfers of `USDC` on Solana. Test the stream [here](https://ide.bitquery.io/stablecoin-transfers-websocket). ```graphql subscription { Solana { Transfers( where: {Transfer: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}} ) { Transfer { Currency { MintAddress Symbol Name Fungible Native } Receiver { Address } Sender { Address } Amount AmountInUSD } Transaction{ Signature } } } } ``` ### Stablecoin recieved and sent by an address Below query will give you `EURC` transfers from/to `cHxJ2uC6vgcCfoFSfupkfCWbKHAkekrGfG39DXRamXT` on Solana. Test the query [here](https://ide.bitquery.io/stablecoin-Transfers-fromto-an-address). ```graphql { Solana { Transfers( limit: {count: 10} orderBy: {descending: Block_Time} where: {any: [{Transfer: {Sender: {Address: {is: "cHxJ2uC6vgcCfoFSfupkfCWbKHAkekrGfG39DXRamXT"}}}}, {Transfer: {Receiver: {Address: {is: "cHxJ2uC6vgcCfoFSfupkfCWbKHAkekrGfG39DXRamXT"}}}}], Transfer: {Currency: {MintAddress: {is: "HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr"}}}} ) { Transaction { Signature } Transfer { Amount AmountInUSD Sender { Address } Receiver { Address } } } } } ``` ## Tron ### Stablecoin Realtime Transfers Stream on Tron Below stream will give you realtime transfers of `USDT` on Tron. Test the stream [here](https://ide.bitquery.io/Stablecoin-Realtime-Transfers-Stream-on-tron). ```graphql subscription { Tron(network: tron) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}}} ) { Transaction { Hash } Transfer { Amount Currency { Name Symbol } Receiver Sender } } } } ``` ### Stablecoin recieved and sent by an address Below query will give you `USDT` transfers from/to `TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ` on Tron. Test the query [here](https://ide.bitquery.io/Stablecoin-recieved-and-sent-by-an-address). ```graphql { Tron(dataset: combined) { Transfers( limit: {count: 10} orderBy: {descending: Block_Time} where: {any: [{Transfer: {Sender: {is: "TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ"}}}, {Transfer: {Receiver: {is: "TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ"}}}], Transfer: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}}} ) { Transaction { Hash } Transfer { Amount AmountInUSD Sender Receiver } } } } ``` --- ## Starter Queries - Bitquery API Examples by Chain URL: https://docs.bitquery.io/docs/start/starter-queries/ Curated, tested Bitquery API queries organised by chain and data type — trades, transfers, balances, holders, prices, liquidity, events and mempool. # Starter Queries Every query below is saved in the [Bitquery IDE](https://ide.bitquery.io) and was executed against the live API before publishing. Pick a chain, then a data type. Queries marked as needing history use the `archive` or `combined` dataset — the comment at the top of each of those queries shows the single line to change. ## Table of Contents - [Bitcoin](#bitcoin) - [Solana](#solana) - [Robinhood Chain](#robinhood-chain) - [Polymarket](#polymarket) - [Perpetuals](#perpetuals) - [TRON](#tron) - [Cross-Chain](#cross-chain) - [Ethereum](#ethereum) - [BSC](#bsc) - [Base](#base) - [Arbitrum](#arbitrum) - [Optimism](#optimism) - [Polygon](#polygon) - [Avalanche](#avalanche) - [Celo](#celo) - [Cronos](#cronos) - [Klaytn](#klaytn) - [Litecoin](#litecoin) - [Bitcoin Cash](#bitcoin-cash) - [Dogecoin](#dogecoin) - [Dash](#dash) - [Zcash](#zcash) - [Cardano](#cardano) - [Ripple](#ripple) - [Stellar](#stellar) - [Algorand](#algorand) - [Filecoin](#filecoin) - [Trading API](#trading-api) - [Stablecoins](#stablecoins) - [NFTs](#nfts) - [Futures DEXs](#futures-dexs) - [x402](#x402) ## Bitcoin ### Transfers #### Inflows and Outflows of a wallet This API returns all incoming and outgoing transactions for a specific Bitcoin wallet address. ▶️ [Inflows and Outflows of a wallet](https://ide.bitquery.io/Inflows-and-Outflow-of-a-bitcoin-wallet) ### Balances & Holders #### Balance of an address at a past date What one Bitcoin address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Bitcoin-Balance-of-an-address-at-a-past-date) #### Bitcoin Balance for multiple addresses This query calculates the combined balance of multiple Bitcoin wallet addresses by summing their total inflows and outflows: Balance = Total Output - Total Input. You can also set a date to get balances as of a specific point in time. ▶️ [Bitcoin Balance for multiple addresses](https://ide.bitquery.io/BTC-balance-api-for-multiple-addresses) #### BTC balance api for multiple addresses 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. ▶️ [BTC balance api for multiple addresses](https://ide.bitquery.io/BTC-balance-API-for-multiple-addresses) #### Bitcoin balance 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. ▶️ [Bitcoin balance](https://ide.bitquery.io/Bitcoin-balance_5) #### Bitcoin balance at a given 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. ▶️ [Bitcoin balance at a given height](https://ide.bitquery.io/bitcoin-balance-at-a-given-height) #### Bitcoin balance on a given 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. ▶️ [Bitcoin balance on a given block height](https://ide.bitquery.io/bitcoin-balance-on-a-given-block-height) ### Price & OHLC #### Btc price in 2016 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. ▶️ [Btc price in 2016](https://ide.bitquery.io/btc-price-in-2016) ### Transactions #### Details of Bitcoin Transaction This API provides comprehensive details of a specific Bitcoin transaction in a single query. ▶️ [Details of Bitcoin Transaction](https://ide.bitquery.io/Details-of-Bitcoin-Transaction) ### Blocks & Validators #### Bitcoin miners rewards Mining rewards live in coinbase outputs (the first transaction in every block, `txIndex: 0`) with `outputDirection: mining`. ▶️ [Bitcoin miners rewards](https://ide.bitquery.io/bitcoin-miners-rewards) #### Get miners activity in a specific timeframe Pulls the activity count per miner address inside a date range. Drop or extend the date window to size the cohort however you need. ▶️ [Get miners activity in a specific timeframe](https://ide.bitquery.io/get-miners-activity-in-a-specific-timeframe) #### Get miners first 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. ▶️ [Get miners first activity](https://ide.bitquery.io/get-miners-first-activity) ## Solana ### Trades #### Get Swaps by Pair Address Get all trades related transactions for a specific pair address. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Get Swaps by Pair Address](https://ide.bitquery.io/swaps-for-a-market-address-on-Solana) #### Get Trades by Wallet Address Get all trades related transactions (buy, sell) for a specific wallet address. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Get Trades by Wallet Address](https://ide.bitquery.io/Solana-dextrades-by-a-trader_2) #### Get Volume Stats for Solana Chain Traded volume, trade count and active wallets for Solana over a stated window, from `DEXTradeByTokens`. Two things this query has to work around. `Solana.DEXTrades` keeps about 12 hours and has no archive, so it cannot answer this at all. And a `uniq` in the same selection as `sum` and `count` corrupts those aggregates and freezes the time filter with them - asking for 1, 3 or 6 days then returns the same totals - so active wallets is computed in its own aliased call. The volume sum also excludes single trades above $1M, which are mispriced rows; without that guard the total reads about $32 quadrillion a day instead of about $16 billion. ▶️ [Get Volume Stats for Solana Chain](https://ide.bitquery.io/Chain-stats-like-total-volume-traded-total-transactions-active-wallets_1) #### Get Multiple Token Analytics — historical (beyond 30 days) Returns analytics data for multiple token addresses. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Multiple Token Analytics — historical (beyond 30 days)](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-multiple-solana-tokens) #### Get Token Metadata — historical (beyond 30 days) Get the token metadata for contract (mint, standard, name, symbol). Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Token Metadata — historical (beyond 30 days)](https://ide.bitquery.io/Solana-currency-details) #### Get Token Pair Stats — historical (beyond 30 days) Get the pair stats by using pair address. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Token Pair Stats — historical (beyond 30 days)](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair) #### Get Token Pairs by Address — historical (beyond 30 days) Get the supported pairs for a specific token address. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Token Pairs by Address — historical (beyond 30 days)](https://ide.bitquery.io/traded-pairs-of-a-token_2) #### Realised PnL, avg buy price, buy volume, sell volume of a Trader for specific token — historical (beyond 30 days) Get realised PnL, average buy price, buy volume, and sell volume for a token on Solana of a trader for over a time window. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Realised PnL, avg buy price, buy volume, sell volume of a Trader for specific token — historical (beyond 30 days)](https://ide.bitquery.io/Realised-Pnl-avg-buy-price-Buy-volume-Sell-Volume-Solana_2) #### Search tokens by name, symbol, mint address — historical (beyond 30 days) Search for tokens based on contract address, token name or token symbol. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Search tokens by name, symbol, mint address — historical (beyond 30 days)](https://ide.bitquery.io/Token-Search-API---trump-symbol) #### Buys Sells BuyVolume SellVolume Makers TotalTradedVolume PriceinUSD for solana token pair — historical (beyond 30 days) Returns 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Buys Sells BuyVolume SellVolume Makers TotalTradedVolume PriceinUSD for solana token pair — historical (beyond 30 days)](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-solana-token-pair00_2) ### Transfers #### Simple SOL transfers (Transactions not trades) This API returns simple SOL transfers; in other words, it contains transactions that are simple token transfers, not trades. ▶️ [Simple SOL transfers (Transactions not trades)](https://ide.bitquery.io/Simple-SOL-transfers-Transactions-not-trades) #### Solana Token Transfers for a Specific Address This API retrieves the history of token transfers (both sent and received) for a specific Solana address within a defined time period. ▶️ [Solana Token Transfers for a Specific Address](https://ide.bitquery.io/Solana-historical-token-transfers-of-an-address-between-a-time) #### Solana Transfers This query gets the latest 10 transfers on Solana. You can increase the limit to get more transfers. This query only uses real-time data. ▶️ [Solana Transfers](https://ide.bitquery.io/Solana-transfers0_5) #### Solana Historical Transfers Solana Historical Transfers. ▶️ [Solana Historical Transfers](https://ide.bitquery.io/solana-historical-transfers_1) #### Currency with elon inclusion You can search tokens on Solana using names or symbols case insensitively also using our APIs and get prices and other details. ▶️ [Currency with elon inclusion](https://ide.bitquery.io/Currency-with-elon-inclusion) #### Solana token transfers of Bags fm tokens Track all transfers of Bags FM tokens across wallets. This Bags FM token transfers endpoint provides complete transfer history. 🔗. ▶️ [Solana token transfers of Bags fm tokens](https://ide.bitquery.io/Solana-token-transfers-of-Bags-fm-tokens) #### Total txn fees paid by the Account Get the total fees (in SOL and USD) paid by a specific Solana account across all transfers. ▶️ [Total txn fees paid by the Account](https://ide.bitquery.io/total-txn-fees-paid-by-the-Account) #### Transaction fees paid by Account aggregated by currency Get total fees paid by a Solana account for transferring each type of token. ▶️ [Transaction fees paid by Account aggregated by currency](https://ide.bitquery.io/Transaction-fees-paid-by-Account-aggregated-by-currency) #### Transfers of a wallet Fetches the recent 10 transfers of a specific wallet address `9nnLbotNTcUhvbrsA6Mdkx45Sm82G35zo28AqUvjExn8`. ▶️ [Transfers of a wallet](https://ide.bitquery.io/Transfers-of-a-wallet_1) #### Wallet transfers with transaction fees paid Track wallet token transfers and get the fees paid for each by the address. ▶️ [Wallet transfers with transaction fees paid](https://ide.bitquery.io/wallet-transfers-with-transaction-fees-paid) ### Balances & Holders #### Solana Instruction Balance Updates This query returns Solana balance update info for any balance update event, including the address, amount, currency details, and the details of the program responsible for this update. ▶️ [Solana Instruction Balance Updates](https://ide.bitquery.io/Solana-InstructionBalanceUpdates) #### Balance updates Returns balance update associated with a instruction invocation. ▶️ [Balance updates](https://ide.bitquery.io/balance-updates) #### Solana balance updates executing burn instruction The query below uses the InstructionBalanceUpdates API to fetch balance updates that occur when token burn instructions execute. ▶️ [Solana balance updates executing burn instruction](https://ide.bitquery.io/solana-balance-updates-executing-burn-instruction) #### Trades of wallets with balance Updates in that trades Trades made by the wallets in `addressList`, with the balance updates from those same transactions joined on. Uses `DEXTradeByTokens` rather than `Solana.DEXTrades`: DEXTrades keeps only about 12 hours on Solana and has no archive, so the previous version returned no rows whenever the wallet had not traded in the last half day. DEXTradeByTokens keeps about 7 days and supports `archive` for older windows. ▶️ [Trades of wallets with balance Updates in that trades](https://ide.bitquery.io/Trades-of-wallets-with-balance-Updates-in-that-trades) ### Price & OHLC #### Token price from top market (rank 1) Prices SOL from its single top market rather than blending every pool — the recommended way to price one specific token. Replace `token` in the Variables pane, lowercase. ▶️ [Token price from top market (rank 1)](https://ide.bitquery.io/Solana-Token-price-from-top-market-rank-1) #### Get OHLCV by Pair Address You can get charting data easily with this query. Adjust the intervals as necessary. This query supports historical data. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Get OHLCV by Pair Address](https://ide.bitquery.io/OHLC-for-a-token_8) #### Get Latest Price of a Token in USD Get Latest Price of a Token in USD. Uses the `Pairs` cube. Replace the address in the `where` clause to use it. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Get Latest Price of a Token in USD](https://ide.bitquery.io/Pumpfun-token-latest-price-USD) #### Historical Price and Volume Data (Volume & Price, Last 24h using Trading API) Use this API to get historical price and volume for a specific token over the past 24 hours. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Historical Price and Volume Data (Volume & Price, Last 24h using Trading API)](https://ide.bitquery.io/24h-historical-price-and-historical-volume-on-Solana) #### Get Token Prices on Solana — historical (beyond 30 days) Returns price information for multiple Solana tokens in a single request. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Token Prices on Solana — historical (beyond 30 days)](https://ide.bitquery.io/Get-multiple-Token-Prices) #### Price change 5min, 1hr, 6hr precentage of a specific token — historical (beyond 30 days) With this, you can get the price change 5min, 1hr, 6hr precentage of a specific token. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Price change 5min, 1hr, 6hr precentage of a specific token — historical (beyond 30 days)](https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_5) #### Top 10 solana tokens by price change in last 1 hr — historical (beyond 30 days) With this, you can get top 10 solana tokens by price change in last 1 hr. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top 10 solana tokens by price change in last 1 hr — historical (beyond 30 days)](https://ide.bitquery.io/Top-10-solana-tokens-by-price-change-in-last-1-hr_4) #### ATH of multiple tokens quantile Solana — historical (beyond 30 days) ATH of multiple tokens quantile Solana. Uses the `DEXTradeByTokens` cube. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [ATH of multiple tokens quantile Solana — historical (beyond 30 days)](https://ide.bitquery.io/ATH-of-multiple-tokens-quantile-Solana) #### ATH with price delta Solana — historical (beyond 30 days) 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [ATH with price delta Solana — historical (beyond 30 days)](https://ide.bitquery.io/ATH-with-price-delta-Solana) #### AldrinAmm OHLC for specific pair — historical (beyond 30 days) If you want to get OHLC data for any specific currency pair on AldrinAmm, you can use this api. Only use. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [AldrinAmm OHLC for specific pair — historical (beyond 30 days)](https://ide.bitquery.io/AldrinAmm-OHLC-for-specific-pair) #### Get Latest Price of Apple xStock in USD Real-time — historical (beyond 30 days) You can use the following query to get the latest price of a Apple xStock on Solana. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Latest Price of Apple xStock in USD Real-time — historical (beyond 30 days)](https://ide.bitquery.io/Get-Latest-Price-of-Apple-xStock-in--USD-Real-time) ### Supply & Market Cap #### Sandisk - Backpack Securities MCAP See the Pairs cube for full field reference. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Sandisk - Backpack Securities MCAP](https://ide.bitquery.io/Sandisk---Backpack-Securities-MCAP) #### Top Tokens by Market Cap on solana 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. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Top Tokens by Market Cap on solana](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-solana) #### Bags.fm token creation using Solana token supply updates Bags.fm token creation using Solana token supply updates. Uses the `TokenSupplyUpdates` cube. Replace the address in the `where` clause to use it. ▶️ [Bags.fm token creation using Solana token supply updates](https://ide.bitquery.io/Bagsfm-token-creation-using-Solana-token-supply-updates) #### Market cap of token You can fetch Marketcap of a token using below query. ▶️ [Market cap of token](https://ide.bitquery.io/market-cap-of-token_1) #### Token burn example solana You can also track real-time token burn using the TokenSupplyUpdates API. Check out the. ▶️ [Token burn example solana](https://ide.bitquery.io/token-burn-example-solana) #### Token supply 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. ▶️ [Token supply](https://ide.bitquery.io/token-supply_2) #### Tokens with market cap range Lets say we need to get the tokens whose marketcap has crossed the `1M USD` mark but is less than `2M USD` for various reasons like automated trading. We can get the token details that have crossed a particular marketcap using. ▶️ [Tokens with market cap range](https://ide.bitquery.io/tokens-with-market-cap-range) #### Top 10 marketcap jump tokens in last 1hr Use below query to get top 10 marketcap jump tokens in last 1hr. ▶️ [Top 10 marketcap jump tokens in last 1hr](https://ide.bitquery.io/top-10-marketcap-jump-tokens-in-last-1hr) #### Top Solana tokens based on market cap Top Solana tokens based on market cap. Uses the `TokenSupplyUpdates` cube. ▶️ [Top Solana tokens based on market cap](https://ide.bitquery.io/top-Solana-tokens-based-on-market-cap) #### Marketcap of tokens — historical (beyond 30 days) 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Marketcap of tokens — historical (beyond 30 days)](https://ide.bitquery.io/Marketcap-of-tokens) ### Liquidity & Pools #### All Token Pairs Across DEXs with Current Liquidity This query retrieves all instances of a specific token pair across decentralized exchanges (DEXs) on Solana, along with their current liquidity. ▶️ [All Token Pairs Across DEXs with Current Liquidity](https://ide.bitquery.io/All-Liquidity-pairs-of-a-token-and-current-liquidity-on-solana) #### Latest Pools Created on Launchpad This query returns the latest created pools on Raydium launchpad. You can set the limit here also. ▶️ [Latest Pools Created on Launchpad](https://ide.bitquery.io/Launchpad-latest-pool-created) #### Liquidity of All Pools of a Token on Solana Get latest liquidity snapshots for all pools where a token is either base or quote currency. ▶️ [Liquidity of All Pools of a Token on Solana](https://ide.bitquery.io/liqidity-of-all-pools-of-a-token) #### Solana Pool Liquidity Changes This query retrieves the latest changes to liquidity pools on Solana, including the change amount and the price at which the change happened. This query also uses only the real-time data set. ▶️ [Solana Pool Liquidity Changes](https://ide.bitquery.io/Solana-DEXPools) #### All liquidity add instructions track on Solana Tracks liquidity addition events on Solana DEX pools by monitoring specific instructions. ▶️ [All liquidity add instructions track on Solana](https://ide.bitquery.io/All-liquidity-add-instructions-track-on-Solana) #### CPMM pools created 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. ▶️ [CPMM pools created](https://ide.bitquery.io/CPMM-pools-created_1) #### Get LP Latest liqudity on Solana Get LP Latest liqudity on Solana. Uses the `DEXPools` cube. Replace the address in the `where` clause to use it. ▶️ [Get LP Latest liqudity on Solana](https://ide.bitquery.io/Get-LP-Latest-liqudity-on-Solana) #### Get all the liquidity pools info for a particular token Will give the information on all the liquidity pools of a particular token `EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm`. ▶️ [Get all the liquidity pools info for a particular token](https://ide.bitquery.io/get-all-the-liquidity-pools-info-for-a-particular-token_1) #### Liquidity change in recent month Liquidity change in recent month. Uses the `DEXTradeByTokens` cube. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Liquidity change in recent month](https://ide.bitquery.io/liquidity-change-in-recent-month) #### Liquidity lock using instructions balance update Using the below query, you can retrieve latest liquidity locks made using streamflow. ▶️ [Liquidity lock using instructions balance update](https://ide.bitquery.io/Liquidity-lock-using-instructions-balance-update) ### Events & Calls #### Not Anchor Error Solana Logs To exclude instructions containing specific log phrases such as 'AnchorError' you can use the `notLike` filter. ▶️ [Not Anchor Error Solana Logs](https://ide.bitquery.io/Not-Anchor-Error-Solana-Logs) #### Solana Zeta Market logs If you need to filter out the instructions from Solana logs that involve a particular exchange but you don’t have any information, like address and protocol, then you can use the “includes” keyword on Logs. ▶️ [Solana Zeta Market logs](https://ide.bitquery.io/Solana-Zeta-Market-logs) ### Pump.fun #### First buyers of a token (sniper detection) The earliest buyers of a token, in time order - snipers are the first rows, buying within seconds of launch at the lowest price. Replace `token` in the Variables pane. ▶️ [First buyers of a token (sniper detection)](https://ide.bitquery.io/Solana---First-buyers-of-a-Pumpfun-token-sniper-detection) #### Top 10 pump fun tokens by Marketcap change in last 5mins This query returns the top 10 pump fun tokens by Marketcap change in last 5mins. You can increase the limit to get more tokens. ▶️ [Top 10 pump fun tokens by Marketcap change in last 5mins](https://ide.bitquery.io/Top-10-pump-fun-tokens-by-Marketcap-change-in-last-5mins_1) #### Top PumpFun Tokens by Marketcap Top Pump.fun and PumpSwap tokens on Solana over the last hour, ranked by USD volume. Ranked by volume rather than market cap on purpose: Solana market caps in the cube saturate against whatever ceiling you filter on, so sorting by them surfaces tokens with broken supply figures. `Supply.MarketCap` is still returned for reference. The previous version sorted `Solana.DEXTrades` by raw buy price over a window 18 months outside that cube's ~12 hour retention and returned USDC as the top Pump.fun token. ▶️ [Top PumpFun Tokens by Marketcap](https://ide.bitquery.io/top-tokens-by-mktcap-on-pump-fun-in-last-15-min) #### Get Bonding Curve Progress of a Token on Pump Fun Returns Bonding Curve Percentage of a Token on the Pump Fun. ▶️ [Get Bonding Curve Progress of a Token on Pump Fun](https://ide.bitquery.io/get-the-bonding-curve-progress-percentage_1) #### ATH Market Cap of Pump Fun Tokens in a Specific Timeframe Use Bitquery's `DEXTradeByTokens` with `dataset: combined`, `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). ▶️ [ATH Market Cap of Pump Fun Tokens in a Specific Timeframe](https://ide.bitquery.io/ATH-Market-Cap-of-Pump-Fun-Tokens-in-a-Specific-Timeframe) #### All tokens traded on Pump.fun in the last 1 hour To get all tokens traded on Pump.fun in the last 1 hour, use a query that filters trades by the Pump.fun protocol and a block time within the past hour. ▶️ [All tokens traded on Pump.fun in the last 1 hour](https://ide.bitquery.io/all-tokens-traded-on-Pumpfun-in-the-last-1-hour_1) #### How do I get tokens that reached a specific market cap on Pump.fun? To find tokens on Pump.fun that have reached a specific market capitalization threshold, you can use the following Bitquery GraphQL example. ▶️ [How do I get tokens that reached a specific market cap on Pump.fun?](https://ide.bitquery.io/How-do-I-get-tokens-that-reached-a-specific-market-cap-on-Pumpfun) #### Latest creator fee transfers on pumpfun amm Latest creator fee transfers on pumpfun amm. Uses the `InstructionBalanceUpdates` cube. Replace the address in the `where` clause to use it. ▶️ [Latest creator fee transfers on pumpfun amm](https://ide.bitquery.io/latest-creator-fee-transfers-on-pumpfun-amm) #### Pumpfun transfers type v1 to pumpfun migrations Retrieve Pump.fun token migrations on a specific date. The API returns transfers to the PumpSwap migration receiver address for the given date. ▶️ [Pumpfun transfers type v1 to pumpfun migrations](https://ide.bitquery.io/pumpfun-transfers-type-v1-to-pumpfun-migrations_1) #### Pumpswap latest Trades API Latest PumpSwap trades from the Trading cube, with USD price and trade size on every row. The Trading cube reaches back about 30 days on Solana; `Solana.DEXTrades` keeps only about 12 hours. ▶️ [Pumpswap latest Trades API](https://ide.bitquery.io/Pumpswap-latest-Trades-API) #### Top 10 pump fun tokens by Price change in last 5min Use the below query to get top 10 Pump.fun tokens by price change in the last 5 minutes. ▶️ [Top 10 pump fun tokens by Price change in last 5min](https://ide.bitquery.io/Top-10-pump-fun-tokens-by-Price-change-in-last-5min_1) #### Top 100 graduating pump fun tokens in last 5 minutes We can use below query to get top 100 About to Graduate Pump Fun Tokens. You can run and test the saved query. ▶️ [Top 100 graduating pump fun tokens in last 5 minutes](https://ide.bitquery.io/Top-100-graduating-pump-fun-tokens-in-last-5-minutes_2) #### Top traders 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. ▶️ [Top traders on pumpswap](https://ide.bitquery.io/top-traders-on-pumpswap_2) #### All Pump fun tokens created by an address All Pump fun tokens created by an address. Uses the `TokenSupplyUpdates` cube. Replace the address in the `where` clause to use it. ▶️ [All Pump fun tokens created by an address](https://ide.bitquery.io/all-Pump-fun-tokens-created-by-an-address_3) #### First transfers of a pump fun token Retrieves the first transfer of a token to each address, providing the timestamp when each address first received the token. ▶️ [First transfers of a pump fun token](https://ide.bitquery.io/first-transfers-of-a-pump-fun-token_1) ### Meteora #### Get the Top Traders of a specific Token on Meteora DAMM v2 DEX The below query gets the Top Traders of the specified Token on Meteora DAMM v2. This provides insights into the most active traders and their trading patterns. ▶️ [Get the Top Traders of a specific Token on Meteora DAMM v2 DEX](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DAMM-v2-DEX_1) #### Get the Top Traders of a specific Token on Meteora DLMM DEX The below query gets the Top Traders of the specified Token on Meteora DLMM. This provides insights into the most active traders and their trading patterns. ▶️ [Get the Top Traders of a specific Token on Meteora DLMM DEX](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DLMM-DEX) #### Get the Top Traders of a specific Token on Meteora DYN DEX The below query gets the Top Traders of the specified Token `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` on Meteora DYN. ▶️ [Get the Top Traders of a specific Token on Meteora DYN DEX](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DYN-DEX) #### Meteora DAMM v2 OHLC API If you want to get OHLC (Open, High, Low, Close) data for any specific currency pair on Meteora DAMM v2, you can use this API. This provides technical analysis data for charting and trading strategies. ▶️ [Meteora DAMM v2 OHLC API](https://ide.bitquery.io/Meteora-DAMM-v2-OHLC-API) #### Meteora DLMM OHLC API If you want to get OHLC (Open, High, Low, Close) data for any specific currency pair on Meteora DLMM, you can use this API. This provides technical analysis data for charting and trading strategies. ▶️ [Meteora DLMM OHLC API](https://ide.bitquery.io/Meteora-DLMM-OHLC-API) #### Meteora DYN OHLC API If you want to get OHLC data for any specific currency pair on Meteora DYN, you can use this api. Only use. ▶️ [Meteora DYN OHLC API](https://ide.bitquery.io/Meteora-DYN-OHLC-API) #### Volatility of WSOL USDC Pair on AldrinAmm Dex on Solana Standard deviation of the WSOL/USDC price on AldrinAmm over the last five days. Uses `DEXTradeByTokens`, which keeps about 7 days, rather than `Solana.DEXTrades`, which keeps about 12 hours and has no archive. `trades` is returned alongside the volatility so an empty window reads as 0 trades instead of passing for zero volatility. ▶️ [Volatility of WSOL USDC Pair on AldrinAmm Dex on Solana](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-AldrinAmm-Dex-on-Solana_1) #### Volatility of WSOL USDC Pair on Lifinity Dex on Solana Standard deviation of the WSOL/USDC price on Lifinity over the last five days. This pair is currently inactive on Lifinity, so the query returns 0 trades - change the `ProtocolFamily` to a busier venue such as Raydium or Meteora to see a live figure. Uses `DEXTradeByTokens` rather than `Solana.DEXTrades`, which keeps about 12 hours and has no archive. ▶️ [Volatility of WSOL USDC Pair on Lifinity Dex on Solana](https://ide.bitquery.io/Volatility-of-WSOL-USDC-Pair-on-Lifinity-Dex-on-Solana) #### Volatility of a Pair on Meteora Dynamic Standard deviation of the WSOL/USDC price on Meteora over the last five days. The previous version asked `Solana.DEXTrades` for a two-hour window more than a year old and reported a volatility of 0, which meant no data rather than no movement. `trades` is returned alongside so an empty window is visible. ▶️ [Volatility of a Pair on Meteora Dynamic](https://ide.bitquery.io/Volatility-of-a-Pair-on-Meteora-Dynamic) #### Get the Top Traders of a specific Token on Meteora DBC The below query gets the Top Traders of the specified Token `4kJkgxzuk1gcjsgRSVhdeSiC15ibQLRDKTuqtf2i16Dm` on Meteora DBC. ▶️ [Get the Top Traders of a specific Token on Meteora DBC](https://ide.bitquery.io/Get-the-Top-Traders-of-a-specific-Token-on-Meteora-DBC) ### Raydium #### Top 100 About to Graduate Raydium Launchpad Tokens Returns top 100 About to Graduate Raydium Launchpadn Tokens. ▶️ [Top 100 About to Graduate Raydium Launchpad Tokens](https://ide.bitquery.io/Top-100-graduating-raydium-launchlab-tokens-in-last-5-minutes) #### Historical PumpFun Migrated Token on Raydium and Pumpswap. Historical PumpFun Migrated Token on Raydium and Pumpswap. Uses the `DEXTradeByTokens` cube. Adjust the date range in the `where` clause. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Historical PumpFun Migrated Token on Raydium and Pumpswap.](https://ide.bitquery.io/all-pumpfun-migrated-token-query_4) #### Get Bonding Curve Progress of a Raydium Launchpad Token Returns Bonding Curve Percentage of a Raydium Launchpad Token. ▶️ [Get Bonding Curve Progress of a Raydium Launchpad Token](https://ide.bitquery.io/bonding-curve-progress-percentage-of-a-letsbonkfun-token) #### Latest Price of a Token on Raydium Launchpad This query returns the latest price of a token on the Raydium launchpad. ▶️ [Latest Price of a Token on Raydium Launchpad](https://ide.bitquery.io/Latest-Price-of-a-Token-on-Launchpad) #### Latest Trades for a specific currency on Raydium This query returns the latest trades for a token on Raydium. You can set the limit here also. ▶️ [Latest Trades for a specific currency on Raydium](https://ide.bitquery.io/Trades-for-a-token-on-Raydium-on-Solana) #### DecreaseLiquidityV2 latest raydium clmm DecreaseLiquidityV2 latest raydium clmm. Uses the `Instructions` cube. Replace the address in the `where` clause to use it. ▶️ [DecreaseLiquidityV2 latest raydium clmm](https://ide.bitquery.io/decreaseLiquidityV2-latest-raydium-clmm_1) #### IncreaseLiquidityV2 latest raydium clmm IncreaseLiquidityV2 latest raydium clmm. Uses the `Instructions` cube. Replace the address in the `where` clause to use it. ▶️ [IncreaseLiquidityV2 latest raydium clmm](https://ide.bitquery.io/increaseLiquidityV2-latest-raydium-clmm) #### Live price of token on raydium - updated You can use the following query to get the latest price of a token on Raydium DEX on Solana. ▶️ [Live price of token on raydium - updated](https://ide.bitquery.io/live-price-of-token-on-raydium---updated) #### Raydium CLMM Pool Creation 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. ▶️ [Raydium CLMM Pool Creation](https://ide.bitquery.io/Raydium-CLMM-Pool-Creation) #### Raydium OHLC for specific pair If you want to get OHLC data for any specific currency pair on Raydium DEX, you can use. ▶️ [Raydium OHLC for specific pair](https://ide.bitquery.io/Raydium-OHLC-for-specific-pair_5) #### Top Bought Solana Tokens Will give most bought Solana Tokens on Raydium. ▶️ [Top Bought Solana Tokens](https://ide.bitquery.io/Top-Bought-Solana-Tokens) #### Top sold Solana Tokens Will give most sold Solana Tokens on Raydium. ▶️ [Top sold Solana Tokens](https://ide.bitquery.io/Top-sold-Solana-Tokens) ### LetsBonk.fun #### Latest Price of a LetsBonk.fun Token on Launchpad 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. ▶️ [Latest Price of a LetsBonk.fun Token on Launchpad](https://ide.bitquery.io/Latest-Price-of-a-LetsBonkfun-Token-on-Launchpad) #### Latest Trades of a letsbonk.fun token on Launchpad Fetches the most recent trades of a LetsBonk.fun Token `token Mint Address` on the Raydium Launchpad. Run the query. ▶️ [Latest Trades of a letsbonk.fun token on Launchpad](https://ide.bitquery.io/Latest-Trades-of-a-letsbonkfun-token-on-Launchpad) #### Liquidity for a Letsbonk.fun token pair Liquidity for a Letsbonk.fun token pair. Uses the `DEXPools` cube. Replace the address in the `where` clause to use it. ▶️ [Liquidity for a Letsbonk.fun token pair](https://ide.bitquery.io/liquidity-for-a-Letsbonkfun-token-pair_2) #### Ohlc for letsbonk.fun token Ohlc for letsbonk.fun token. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Ohlc for letsbonk.fun token](https://ide.bitquery.io/ohlc-for-letsbonkfun-token) #### Pool address for letsbonk.fun token Pool address for letsbonk.fun token. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Pool address for letsbonk.fun token](https://ide.bitquery.io/pool-address-for-letsbonkfun-token_1) #### Top buyers of a letsbonk.fun token on launchpad Top buyers of a letsbonk.fun token on launchpad. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Top buyers of a letsbonk.fun token on launchpad](https://ide.bitquery.io/top-buyers-of-a-letsbonkfun-token-on-launchpad) #### Top sellers of a letsbonk.fun token on launchpad Top sellers of a letsbonk.fun token on launchpad. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Top sellers of a letsbonk.fun token on launchpad](https://ide.bitquery.io/top-sellers-of-a-letsbonkfun-token-on-launchpad_1) ## Robinhood Chain ### Trades #### Largest Trades on Robinhood Chain (24h, USD) Largest Trades on Robinhood Chain (24h, USD). Uses the `Trades` cube. ▶️ [Largest Trades on Robinhood Chain (24h, USD)](https://ide.bitquery.io/largest-swaps-robinhood-chain) #### Pools trade Latest trades for a token 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. ▶️ [Pools trade Latest trades for a token](https://ide.bitquery.io/Pools-trade-Latest-trades-for-a-token) #### Pools trade Top tokens by volume The two-step pattern: pass a token set harvested from `TokenCreated` into the `Trading` cube. ▶️ [Pools trade Top tokens by volume](https://ide.bitquery.io/Pools-trade-Top-tokens-by-volume) #### Pools trade Crowd Launch bids 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. ▶️ [Pools trade Crowd Launch bids](https://ide.bitquery.io/Pools-trade-Crowd-Launch-bids) #### Pools trade Latest launches The decoded `TokenCreated` event on the two entry contracts is the cleanest launch feed — one row per launch. ▶️ [Pools trade Latest launches](https://ide.bitquery.io/Pools-trade-Latest-launches) #### Pools trade Launches per day Grouping by `LogHeader.Address` too shows the split between the two entry contracts. ▶️ [Pools trade Launches per day](https://ide.bitquery.io/Pools-trade-Launches-per-day) #### Pools trade Most active token creators Useful for spotting spam-bot deployers — a single wallet can mint hundreds of tokens a day. ▶️ [Pools trade Most active token creators](https://ide.bitquery.io/Pools-trade-Most-active-token-creators) #### Pools trade PoolKey from TokenLaunched Pools trade PoolKey from TokenLaunched. Uses the `Events` cube. ▶️ [Pools trade PoolKey from TokenLaunched](https://ide.bitquery.io/Pools-trade-PoolKey-from-TokenLaunched) #### Pools trade Token description and image The filter below pins the factory by address because the entry contract emits a *different* `TokenCreated` under the same name (see Reading decoded arguments). ▶️ [Pools trade Token description and image](https://ide.bitquery.io/Pools-trade-Token-description-and-image) #### Pools trade TokenDistributed decoded event 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. ▶️ [Pools trade TokenDistributed decoded event](https://ide.bitquery.io/Pools-trade-raw-event-by-topic0) ### Transfers #### Ape.store Newly created tokens Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Ape.store Newly created tokens](https://ide.bitquery.io/Apestore-Newly-created-tokens) #### Bags.fm Newly created tokens Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Bags.fm Newly created tokens](https://ide.bitquery.io/Bagsfm-Newly-created-tokens) #### Bankr Bot Newly created tokens Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Bankr Bot Newly created tokens](https://ide.bitquery.io/Bankr-Bot-Newly-created-tokens) #### 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. ▶️ [Flap.sh Newly created tokens using transfer data](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-transfer-data) #### Klik Finance Newly created tokens using transfers Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Klik Finance Newly created tokens using transfers](https://ide.bitquery.io/Klik-Finance-Newly-created-tokens-using-transfers) #### Robinhood Chain API - Latest Token Transfers Robinhood Chain API - Latest Token Transfers. Uses the `Transfers` cube. ▶️ [Robinhood Chain API - Latest Token Transfers](https://ide.bitquery.io/latest-transfers-on-robinhood) #### Robinhood Chain Token Lookup by Contract Address 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. ▶️ [Robinhood Chain Token Lookup by Contract Address](https://ide.bitquery.io/Pools-trade-Token-name-symbol-decimals) #### Token Lookup by Contract Address - Robinhood Chain Follow the steps here: How to generate Bitquery API token ➤. ▶️ [Token Lookup by Contract Address - Robinhood Chain](https://ide.bitquery.io/token-lookup-by-address-robinhood-chain) #### Transfers for a token on robinhood Filter with `Transfer.Currency.SmartContract`. Example: WETH on Robinhood. ▶️ [Transfers for a token on robinhood](https://ide.bitquery.io/Transfers-for-a-token-on-robinhood) #### Transfers for a wallet on Robinhood Filter where the address is either `Transfer.Sender` or `Transfer.Receiver` to build a full transfer history. Replace the sample address with your wallet or contract. ▶️ [Transfers for a wallet on Robinhood](https://ide.bitquery.io/transfers-for-a-wallet-on-Robinhood) ### Balances & Holders #### Pools trade Per-transaction balance changes A stream of this filtered to `SlippageBasisPoints: {gt: 100}` is a ready-made "toxic fill" alert for a token's pool. ▶️ [Pools trade Per-transaction balance changes](https://ide.bitquery.io/Pools-trade-Per-transaction-balance-changes) #### Wallet Token Balances on Robinhood Chain Wallet Token Balances on Robinhood Chain. Uses the `Balances` cube. Replace the address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Wallet Token Balances on Robinhood Chain](https://ide.bitquery.io/wallet-token-balances-robinhood-chain) ### Price & OHLC #### Latest price of a token on a pool This API endpoint retrieves the latest price of a token for a particular token pair or liquidity pool using the `Trading.Pairs` cube. ▶️ [Latest price of a token on a pool](https://ide.bitquery.io/latest-price-of-a-token-on-a-pool) #### Latest price of a token 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. ▶️ [Latest price of a token](https://ide.bitquery.io/latest-price-of-a-token_10) #### Pools trade OHLCV price candles Deduplicate on `(TransactionHeader.Hash, Block.Time, Side, Amounts.Base, Pair.QuoteToken.Symbol, Trader.Address)` before aggregating. ▶️ [Pools trade OHLCV price candles](https://ide.bitquery.io/Pools-trade-OHLCV-price-candles) ### Supply & Market Cap #### Pools trade Token holders and supply Pools trade Token holders and supply. Uses the `Holders` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Pools trade Token holders and supply](https://ide.bitquery.io/Pools-trade-Token-holders-and-supply) ### Liquidity & Pools #### Pools trade Per-swap slippage Pools trade Per-swap slippage. ▶️ [Pools trade Per-swap slippage](https://ide.bitquery.io/Pools-trade-Per-swap-slippage) #### Pools trade 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. ▶️ [Pools trade Pool creation Initialize](https://ide.bitquery.io/Pools-trade-Pool-creation-Initialize) ### Transactions #### Daily Active Wallets on Robinhood Chain Daily Active Wallets on Robinhood Chain. Uses the `Transactions` cube. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Daily Active Wallets on Robinhood Chain](https://ide.bitquery.io/robinhood-chain-active-wallets) #### Robinhood Chain Daily Transaction Count Robinhood Chain Daily Transaction Count. Uses the `Transactions` cube. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Robinhood Chain Daily Transaction Count](https://ide.bitquery.io/robinhood-chain-daily-transactions) #### Robinhood Chain Gas Usage and Gas Price Robinhood Chain Gas Usage and Gas Price. Uses the `Transactions` cube. ▶️ [Robinhood Chain Gas Usage and Gas Price](https://ide.bitquery.io/robinhood-chain-gas-fees) ### Events & Calls #### All events from Flap.sh Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [All events from Flap.sh](https://ide.bitquery.io/All-events-from-Flapsh) #### Flap.sh Newly created tokens using logs TokenCreated Filter Flap.sh `TokenCreated` events and decode argument values (token address, metadata fields, and related parameters). ▶️ [Flap.sh Newly created tokens using logs TokenCreated](https://ide.bitquery.io/Flapsh-Newly-created-tokens-using-logs-TokenCreated) #### New Contracts Deployed on Robinhood Chain To pin one exact ABI variant — or to match an undecoded method — filter the 4-byte selector instead (uppercase hex, no `0x`) ▶️ [New Contracts Deployed on Robinhood Chain](https://ide.bitquery.io/new-contracts-deployed-robinhood-chain) ### Blocks & Validators #### Robinhood Chain Blocks per Day and Block Time Robinhood Chain Blocks per Day and Block Time. Uses the `Blocks` cube. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Robinhood Chain Blocks per Day and Block Time](https://ide.bitquery.io/robinhood-chain-block-time) ### Uniswap #### Uniswap v4 Pools on Robinhood Chain New Uniswap v4 pools: decoded Initialize events on the PoolManager with currencies, fee tier, tick spacing and hooks. ▶️ [Uniswap v4 Pools on Robinhood Chain](https://ide.bitquery.io/uniswap-v4-pools-on-robinhood-chain) #### Uniswap v4 Hooks in Use on Robinhood Chain Uniswap v4 Hooks in Use on Robinhood Chain. Uses the `Events` cube. Replace the address in the `where` clause to use it. ▶️ [Uniswap v4 Hooks in Use on Robinhood Chain](https://ide.bitquery.io/uniswap-v4-hooks-robinhood-chain) #### Uniswap v4 Pool Liquidity on Robinhood Chain (pools.trade) 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. ▶️ [Uniswap v4 Pool Liquidity on Robinhood Chain (pools.trade)](https://ide.bitquery.io/Pools-trade-Live-pool-liquidity) ## Polymarket ### Trades #### Latest Trades Fetch the most recent prediction market trades with full details, ordered by block time. ▶️ [Latest Trades](https://ide.bitquery.io/latest-prediction-market-trades_8) #### 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 (e.g. Yes/No). Pass the market's outcome token AssetIds in `$marketAssets`. ▶️ [Total Volume and Yes/No Volume for a Market](https://ide.bitquery.io/total-volume-outcome-1-volume-outcome-2-volume-of-a-market_1) #### 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. ▶️ [Trades for a Specific Trader](https://ide.bitquery.io/Trades-for-a-specific-trader_1) #### 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. ▶️ [How do I count trades for a specific Polymarket trader?](https://ide.bitquery.io/How-do-I-count-trades-for-a-specific-Polymarket-trader) #### 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. ▶️ [How do I get top buyers and sellers on Polymarket by volume?](https://ide.bitquery.io/How-do-I-get-top-buyers-and-sellers-on-Polymarket-by-volume) #### Latest prediction market trades Fetch the most recent prediction market trades with full details, ordered by block time. ▶️ [Latest prediction market trades](https://ide.bitquery.io/latest-prediction-market-trades) #### Prediction_trades Prediction_trades. ▶️ [Prediction_trades](https://ide.bitquery.io/prediction_trades) #### Top 100 markets by volumein last24 hrs 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. ▶️ [Top 100 markets by volumein last24 hrs](https://ide.bitquery.io/top-100-markets-by-volumein-last24-hrs_1) #### Top AI markets by volume Polymarket 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. ▶️ [Top AI markets by volume Polymarket](https://ide.bitquery.io/Top-AI-markets-by-volume-Polymarket) #### Top Buyers/Sellers of Bitcoin up down market 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). ▶️ [Top Buyers/Sellers of Bitcoin up down market](https://ide.bitquery.io/Top-BuyersSellers-of-Bitcoin-up-down-market) ### Markets #### Created vs Resolved Count (Last 24 Hours) Count how many Created and Resolved events occurred in the last 24 hours. ▶️ [Created vs Resolved Count (Last 24 Hours)](https://ide.bitquery.io/last-24-hr-resolution-and-ceated-count_1) #### Latest Creations + Resolutions Fetch the most recent creation and resolution events with full details, ordered by block time. ▶️ [Latest Creations + Resolutions](https://ide.bitquery.io/latest-Prediction-managements-resolutions-creations_1) #### Latest Market Creations Fetch the most recent Created events (new markets). All possible outcomes per market are in Prediction.Condition.Outcomes. ▶️ [Latest Market Creations](https://ide.bitquery.io/latest-polymarket-creations_1) #### Latest Market Resolutions Query that returns the 10 most recent Resolved events. Winning outcome is in Prediction.Outcome; Prediction.OutcomeToken holds the asset ID and contract details. ▶️ [Latest Market Resolutions](https://ide.bitquery.io/latest-polymarket-resolutions_2) #### Latest Prediction managements (resolutions, creations) Fetch the most recent creation and resolution events with full details, ordered by block time. ▶️ [Latest Prediction managements (resolutions, creations)](https://ide.bitquery.io/latest-Prediction-managements-resolutions-creations) #### Latest polymarket creations Fetch the most recent Created events. For each market, all possible outcomes are listed under Prediction.Condition.Outcomes. ▶️ [Latest polymarket creations](https://ide.bitquery.io/latest-polymarket-creations) #### Latest polymarket resolutions Latest polymarket resolutions. ▶️ [Latest polymarket resolutions](https://ide.bitquery.io/latest-polymarket-resolutions_1) #### Latest resolved crudeoil markets Returns the 10 most recent Resolved events for Polymarket Crude Oil markets. ▶️ [Latest resolved crudeoil markets](https://ide.bitquery.io/latest-resolved-crudeoil-markets) #### Latest resolved sports markets 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. ▶️ [Latest resolved sports markets](https://ide.bitquery.io/Latest-resolved-sports-markets) #### Query latest created resolved prediction markets for Bitcoin Query latest created resolved prediction markets for Bitcoin. ▶️ [Query latest created resolved prediction markets for Bitcoin](https://ide.bitquery.io/Query-latest-created-resolved-prediction-markets-for-Bitcoin) ### Settlements #### Latest Settlements Fetch the most recent settlements with full details, ordered by block time. ▶️ [Latest Settlements](https://ide.bitquery.io/latest-prediction-market-settlements_3) #### Latest Whale Settlements Find the most recent high-value redemptions (e.g. amount ≥ 10,000 in outcome token units). Useful for tracking large payouts and whale activity. ▶️ [Latest Whale Settlements](https://ide.bitquery.io/latest-whale-settlements-on-prediction-market_3) #### Redemption / Merge / Split Count (Last 1 Hour) Count how many settlement events occurred in the last hour, grouped by event signature (Split, Merge, Redemption). ▶️ [Redemption / Merge / Split Count (Last 1 Hour)](https://ide.bitquery.io/redemptions-merge-split-count-in-last-1-hour_1) #### Top 10 Market Questions by Redeemed Amount (Last 1 Hour) Aggregate redemptions by market question and sort by total redeemed amount. See which markets had the most payout activity recently. ▶️ [Top 10 Market Questions by Redeemed Amount (Last 1 Hour)](https://ide.bitquery.io/top-10-market-questions-in-last-1-hour_3) #### 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. ▶️ [Top 10 Redeemers (Last 1 Hour)](https://ide.bitquery.io/top-10-redeemers_1) #### Top 10 Winners of a Specific Market Question Rank holders by total redeemed amount for one market (filter by question title). ▶️ [Top 10 Winners of a Specific Market Question](https://ide.bitquery.io/top-10-winners-of-a-market-question_2) #### Latest prediction market settlements Fetch the most recent settlements with full details, ordered by block time. ▶️ [Latest prediction market settlements](https://ide.bitquery.io/latest-prediction-market-settlements_2) #### Latest whale settlements on prediction market Find the most recent high-value redemptions (e.g. amount ≥ 10,000 USD). Useful for tracking large payouts and whale activity. ▶️ [Latest whale settlements on prediction market](https://ide.bitquery.io/latest-whale-settlements-on-prediction-market_2) #### Redemptions, merge, split count in last 1 hour Count how many settlement events occurred in the last hour, grouped by event signature (Split, Merge, Redemption). ▶️ [Redemptions, merge, split count in last 1 hour](https://ide.bitquery.io/redemptions-merge-split-count-in-last-1-hour) #### Top 10 redeemers Rank addresses by total amount redeemed in the last hour across all markets. Useful for leaderboards and whale tracking. ▶️ [Top 10 redeemers](https://ide.bitquery.io/top-10-redeemers) ### Transfers #### Freshwallet check for polymarket 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. ▶️ [Freshwallet check for polymarket](https://ide.bitquery.io/freshwallet-check-for-polymarket) #### FundingSource for poylmarket FundingSource for poylmarket. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [FundingSource for poylmarket](https://ide.bitquery.io/FundingSource-for-poylmarket) #### SiblingWallets for polymarket 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. ▶️ [SiblingWallets for polymarket](https://ide.bitquery.io/SiblingWallets-for-polymarket) ### Balances & Holders #### Polymarket TVL Summarize USDC.e (`0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174`) held by Conditional Tokens and neg-risk wrapped collateral contracts. Extend the `Address` list if you track additional custodians. ▶️ [Polymarket TVL](https://ide.bitquery.io/Polymarket-TVL) ### Price & OHLC #### Current Price per Outcome (Latest Trade) Get the latest trade price for each outcome in a market. Uses `limitBy` for one row per outcome, with Price and PriceInUSD at the most recent block time. ▶️ [Current Price per Outcome (Latest Trade)](https://ide.bitquery.io/Current-price-inside-the-market-for-all-options-based-on-latest-trade_1) #### Current price inside the market for all options based on 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). ▶️ [Current price inside the market for all options based on latest trade](https://ide.bitquery.io/Current-price-inside-the-market-for-all-options-based-on-latest-trade) #### 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 or from the creation/resolution queries above. ▶️ [Latest price of outcomes of a crude oil market](https://ide.bitquery.io/latest-price-of-outcomes-of-a-crude-oil-market) #### OHLC of a 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"`). ▶️ [OHLC of a outcome of a gold market](https://ide.bitquery.io/OHLC-of-a-outcome-of-a-gold-market) #### Polymarket AI odds movement OHLC 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 `""` ▶️ [Polymarket AI odds movement OHLC](https://ide.bitquery.io/Polymarket-AI-odds-movement-OHLC) #### Polymarket sports odds movement OHLC 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. ▶️ [Polymarket sports odds movement OHLC](https://ide.bitquery.io/Polymarket-sports-odds-movement-OHLC) ### Liquidity & Pools #### Top cricket Markets by Liquidity Returns the top 100 cricket related polymarkets sorted by liquidity position in the past 24 hours. ▶️ [Top cricket Markets by Liquidity](https://ide.bitquery.io/Top-cricket-Markets-by-Liquidity) #### 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. ▶️ [Top FIFA World Cup Markets by Liquidity](https://ide.bitquery.io/Top-FIFA-World-Cup-Markets-by-Liquidity) ## Perpetuals ### Hyperliquid #### Hyperliquid BTC Perp Trades Hyperliquid BTC Perp Trades. Uses the `Trades` cube. ▶️ [Hyperliquid BTC Perp Trades](https://ide.bitquery.io/hyperliquid-btc-perp-trades) #### Hyperliquid Latest Trades (Perps + Spot + HIP-3) Each fill carries the execution (price, size, side, aggressor flag), the position it changed (leverage, margin mode, size before, realized PnL) and fees. `Direction` is one of `Open Long`, `Open Short`, `Close Long`, `Close Short`. ▶️ [Hyperliquid Latest Trades (Perps + Spot + HIP-3)](https://ide.bitquery.io/hyperliquid-latest-trades) #### Hyperliquid Trader Leverage Updates Hyperliquid Trader Leverage Updates. ▶️ [Hyperliquid Trader Leverage Updates](https://ide.bitquery.io/hyperliquid-leverage-updates) #### Hyperliquid BTC OHLCV Candles (1 minute) The `Candles` cube provides OHLCV per market and interval. `Interval.Time.Duration` is the candle length in seconds (e.g. `60` for one minute), `Start` the interval open time. OHLCV values are floats. ▶️ [Hyperliquid BTC OHLCV Candles (1 minute)](https://ide.bitquery.io/hyperliquid-btc-ohlcv-candles) #### Hyperliquid Mark Prices (All Markets) Follow the steps here: How to generate Bitquery API token ➤. ▶️ [Hyperliquid Mark Prices (All Markets)](https://ide.bitquery.io/hyperliquid-mark-prices) ### Phoenix #### Phoenix Perps Fills by Trader Wallet - Solana Stream every stop-loss and take-profit placement as it happens. ▶️ [Phoenix Perps Fills by Trader Wallet - Solana](https://ide.bitquery.io/sol_perps_filled_orders_by_signer) #### Trader Realized PnL on Solana Perps Rows with `Size: 0` are markets they've fully closed — drop them and the rest is the live book, with entry prices. ▶️ [Trader Realized PnL on Solana Perps](https://ide.bitquery.io/solana-perps-trader-pnl) #### Whale Trades on Solana Perps (Phoenix) Positive = received, negative = paid. Replace the field list with `total: sum(of: Position_Funding)` for the net carry cost of holding their positions. ▶️ [Whale Trades on Solana Perps (Phoenix)](https://ide.bitquery.io/solana-perps-whale-trades) #### Solana Perps OHLC Candles from Mark Price As a `query`, add `orderBy: { descending: Block_Time }` and a `limit` for the recent whale prints. ▶️ [Solana Perps OHLC Candles from Mark Price](https://ide.bitquery.io/solana-perps-ohlc-candles) #### Collateral deposits and withdrawals Deposits and withdrawals of collateral on Phoenix perpetuals, newest first, with trader, signer and fee. Filter by Type for one side only. ▶️ [Collateral deposits and withdrawals](https://ide.bitquery.io/Solana---Phoenix-collateral-deposits-and-withdrawals) ## TRON ### Trades #### Historical Tron Token Trades within 30 Days This query returns the historical trades on the TRON network for a token with the time window of past 30 days. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Historical Tron Token Trades within 30 Days](https://ide.bitquery.io/Historical-Tron-trades-for-a-token-within-30-days) #### Tron DEX Trades This query returns the latest trades on the TRON network from a trader perspective. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Tron DEX Trades](https://ide.bitquery.io/Tron-Trades) #### Tron Dex Trade By Tokens This query returns the latest token trades on the TRON network. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Tron Dex Trade By Tokens](https://ide.bitquery.io/Tron-trades-for-a-token) #### Sunmpump launchtoDEX This query allows you to track when tokens are launched on SunSwap using the `launchToDEX` function. It returns the most recent 10 token launches, displaying details such as the token address, transaction hash, block timestamp, and the method call signature. ▶️ [Sunmpump launchtoDEX](https://ide.bitquery.io/sunmpump-launchtoDEX_1) #### Sunswap v2 latest Trades — historical (beyond 30 days) Retrieves details about each trade, including the amounts and prices of tokens bought and sold, as well as information about the trading pair. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Sunswap v2 latest Trades — historical (beyond 30 days)](https://ide.bitquery.io/sunswap-v2-latest-Trades) #### Historical Tron Token Trades beyond 30 Days — historical (beyond 30 days) This query returns the historical token trades on the TRON network for time window beyond 30 days. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Historical Tron Token Trades beyond 30 Days — historical (beyond 30 days)](https://ide.bitquery.io/Historical-tron-token-trades-beyond-30-days) #### All dexs info — historical (beyond 30 days) Fetches all the DEXs information on Tron network such as unique sellers, unique buyers etc. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [All dexs info — historical (beyond 30 days)](https://ide.bitquery.io/all-dexs-info) #### DEX Markets for a token — historical (beyond 30 days) Fetches the DEXs where a specific token is being traded on Tron network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [DEX Markets for a token — historical (beyond 30 days)](https://ide.bitquery.io/DEX-Markets-for-a-token_1) #### First 100 buyers tron token — historical (beyond 30 days) Find the earliest buyers of any Tron token by using Tron `DEXTradeByTokens` API. This is widely used for memecoin sniper detection, early-holder analysis, and alpha groups monitoring SunPump / SunSwap launches. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [First 100 buyers tron token — historical (beyond 30 days)](https://ide.bitquery.io/first-100-buyers-tron-token) #### Peg health tron — historical (beyond 30 days) Browse multi-chain stablecoin DEX prices on DEXrabbit's Stablecoins category. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Peg health tron — historical (beyond 30 days)](https://ide.bitquery.io/peg-health-tron) ### Transfers #### Historical TRON Transfers for a Wallet This query returns the historical transfers for a wallet in a given time window on the TRON network and includes details such as token amount transferred, sender, receiver, and token info. ▶️ [Historical TRON Transfers for a Wallet](https://ide.bitquery.io/Historical-Tron-transfers-for-a-wallet) #### Latest TRON Transfers This query returns the most recent transfers on the TRON network and includes details such as token amount transferred, sender, receiver, and token info. ▶️ [Latest TRON Transfers](https://ide.bitquery.io/Tron-transfer_10_1) #### Daily transfer volume tron Aggregate daily transfer volume in USD for any TRC20 token for analytics dashboards, weekly newsletters, and on-chain reports for stablecoins, governance tokens, and memecoins on Tron. ▶️ [Daily transfer volume tron](https://ide.bitquery.io/daily-transfer-volume-tron) #### Top transfers of a token Retrieves the top 10 transfers by amount of the token `TXL6rJbvmjD46zeN1JssfgxvSo99qC8MRT`. ▶️ [Top transfers of a token](https://ide.bitquery.io/top-transfers-of-a-token_2) #### Tron total txn fees paid by the Account Get the total fees (in SOL and USD) paid by a specific Tron account across all transfers. ▶️ [Tron total txn fees paid by the Account](https://ide.bitquery.io/Tron-total-txn-fees-paid-by-the-Account) #### Transfers of a wallet API Fetches the recent 10 transfers of a specific wallet address `TFXttAWURRrXrd9JvFPVLEh1esJK8NHxn7`. ▶️ [Transfers of a wallet API](https://ide.bitquery.io/Transfers-of-a-wallet-API) #### Tron Transaction fees paid by Account aggregated by currency Get total fees paid by a Tron account for transferring each type of token. ▶️ [Tron Transaction fees paid by Account aggregated by currency](https://ide.bitquery.io/Tron-Transaction-fees-paid-by-Account-aggregated-by-currency) #### Tron wallet transfers with transaction fees paid Track wallet token transfers and get the fees paid for each by the address. ▶️ [Tron wallet transfers with transaction fees paid](https://ide.bitquery.io/tron-wallet-transfers-with-transaction-fees-paid) ### Balances & Holders #### Historical Balance of a Wallet for a Currency This query returns the current balance of a wallet for all currencies on the TRON network. ▶️ [Historical Balance of a Wallet for a Currency](https://ide.bitquery.io/Historical-Tron-Wallet-Balance-for-a-currency) #### Top token holders of a token Returns the top holders of a token ranked by current balance. Use the Holders API with `orderBy` and `limit`. ▶️ [Top token holders of a token](https://ide.bitquery.io/top-token-holders-of-a-token) #### Tron Balances for Native currency Returns the native TRX balance for a wallet (not TRC10 or TRC20 tokens). Filter with `Currency: { Native: true }` instead of a token contract address. ▶️ [Tron Balances for Native currency](https://ide.bitquery.io/Tron-Balances-for-Native-currency) #### Tron USDT Balance At Date (Balances Cube) Unlike summing Transfers, this includes mints, burns, and genesis supply. ▶️ [Tron USDT Balance At Date (Balances Cube)](https://ide.bitquery.io/tron-usdt-balance-at-date) #### Tron balances 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. ▶️ [Tron balances by date](https://ide.bitquery.io/tron-balances-by-date) #### Tron token balance Add a `Currency.SmartContract` filter. Always use the contract address, not the token name. ▶️ [Tron token balance](https://ide.bitquery.io/tron-token-balance) #### TronWalletPortfolio Tron Returns balances for all the currecies owned by a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances and `dataset: combined` for the latest balances. ▶️ [TronWalletPortfolio Tron](https://ide.bitquery.io/TronWalletPortfolio-Tron) #### SunPump Bonding Curve TRX Balance TRX balance in bonding curve based on dex trades. Calculated as `balance = in_sum - out_sum` ▶️ [SunPump Bonding Curve TRX Balance](https://ide.bitquery.io/SunPump-Bonding-Curve-TRX-Balance) #### SunPump Historical Bonding Curve TRX Balance Calculated as `balance = in_sum - out_sum` ▶️ [SunPump Historical Bonding Curve TRX Balance](https://ide.bitquery.io/SunPump-Historical-Bonding-Curve-TRX-Balance) ### Liquidity & Pools #### Sun Pump Virtual Liquidity Pools Sun Pump does not use a dedicated pool for each pair; instead, all liquidity is managed within a single contract. You can query the virtual liquidity pools directly by running the following query. ▶️ [Sun Pump Virtual Liquidity Pools](https://ide.bitquery.io/Sun-Pump-Virtual-Liquidity-Pools_1) ### Events & Calls #### Latest created Sunpump tokens If you remove `subscription` from the below GraphQL query it will become API, for example check. ▶️ [Latest created Sunpump tokens](https://ide.bitquery.io/latest-created-Sunpump-tokens) #### Latest tokens created on Sunpump The `Arguments` include the token address, creator, and token index. You can run it. ▶️ [Latest tokens created on Sunpump](https://ide.bitquery.io/Latest-tokens-created-on-Sunpump_2) #### TokenPurchased on Sunpump This query allows you to track `TokenPurchased` events on SunPump. It retrieves the 10 most recent token purchase events, showing important details such as the token address, buyer information, transaction hash, and token amount involved. ▶️ [TokenPurchased on Sunpump](https://ide.bitquery.io/TokenPurchased-on-Sunpump) ## Cross-Chain ### Trades #### 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. Returns volume for 1h, 4h, and 24h periods, plus price change percentages. > **Note:** For EVM chains (Ethereum, BSC, etc.) in the Trading API, use **all lowercase… ▶️ [Volume of Multiple Tokens Across Different Chains](https://ide.bitquery.io/volume-of-a-token_2) ### Price & OHLC #### SMA and Volume Data (for past 28, 14 and 7 Days Time) Use this API to get SMA and volume over the past 28 days, with 14 days, and 7 days breakdowns. Note that the oldest possible data it could return is 30 days ago. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [SMA and Volume Data (for past 28, 14 and 7 Days Time)](https://ide.bitquery.io/multiple-tokens-volume-and-SMA) #### Historical OHLC of a Token Pair Across Chains This query fetches historical OHLC (Open, High, Low, Close) price data for a token pair across different blockchains for as long back as 30 days. For **native tokens**, you only need to specify their ID (e.g., `bid:eth` for ETH). Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Historical OHLC of a Token Pair Across Chains](https://ide.bitquery.io/Historical-Token-OHLC-Multi-Chains_1) #### Latest Price of Any Token This query gives you bitcoin currency 1-sec OHLC across different blockchains. You can adjust duration in `Duration: {eq: 1}` filter. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Latest Price of Any Token](https://ide.bitquery.io/Latest-bitcoin-price-on-across-chains_5) #### OHLC of a currency on multiple blockchains This query retrieves the OHLC (Open, High, Low, Close) prices of a currency(in this eg Bitcoin; it will include all sorts of currencies whose underlying asset is Bitcoin like cbBTC, WBTC, etc) across all supported blockchains, aggregated into a given time interval (e.g., 60 seconds in this example). Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [OHLC of a currency on multiple blockchains](https://ide.bitquery.io/OHLC-of-a-currency-on-multiple-blockchains_2) #### Historical Price and Volume Data for a Token Pair beyond 30 days Use this API to get historical price and volume for a specific token pair address on a specific network for the time window beyond the 30 days. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Historical Price and Volume Data for a Token Pair beyond 30 days](https://ide.bitquery.io/historical-price-and-historical-volume) #### All time High Trade Price for a Token — historical (beyond 30 days) Retrieves the all-time high (ATH) price in USD for a specified token contract. All time high price could lie beyond the 30 days window provided by Trading API, hence we use these network specific APIs to get the ATH for a token. While this provides the option to go beyond the 30 days time…. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [All time High Trade Price for a Token — historical (beyond 30 days)](https://ide.bitquery.io/ATH-of-eth-token_1) ## Ethereum ### Trades #### Latest DEX trades for a token Most recent swaps for one token across every Ethereum DEX. Change the token address in the `Currency: {SmartContract:}` filter. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Latest DEX trades for a token](https://ide.bitquery.io/Ethereum-Trades-of-a-Token_1) #### Trades by a wallet Every buy and sell made by one address. Replace the wallet in `Transaction: {From:}`. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Trades by a wallet](https://ide.bitquery.io/Ethereum-Trades-of-a-Trader_1) #### All events on fluid DEX VaultFactory 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. ▶️ [All events on fluid DEX VaultFactory](https://ide.bitquery.io/all-events-on-fluid-DEX-VaultFactory) #### Address is Buyer or Seller V2 — historical (beyond 30 days) Returns 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Address is Buyer or Seller V2 — historical (beyond 30 days)](https://ide.bitquery.io/Address-is-Buyer-or-Seller-V2) #### First 500 buyers of a token — historical (beyond 30 days) Earliest buyers of a token in order, useful for launch and insider analysis. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [First 500 buyers of a token — historical (beyond 30 days)](https://ide.bitquery.io/first-500-buyers-of-a-ERC20-token_1) #### Realised PnL, buy and sell volume — historical (beyond 30 days) Profit and loss for a wallet on one token, from its own trade history. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Realised PnL, buy and sell volume — historical (beyond 30 days)](https://ide.bitquery.io/Realised-Pnl-Buy-volume-Sell-Volume-Ethereum_1) #### Buys, Sells, BuyVolume, SellVolume, Makers, TotalTradedVolume, PriceinUSD for a eth pair — historical (beyond 30 days) Will fetch 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Buys, Sells, BuyVolume, SellVolume, Makers, TotalTradedVolume, PriceinUSD for a eth pair — historical (beyond 30 days)](https://ide.bitquery.io/Buys-Sells-BuyVolume-SellVolume-Makers-TotalTradedVolume-PriceinUSD-for-a-eth-pair) #### Coin ticker api — historical (beyond 30 days) Coin ticker api. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Coin ticker api — historical (beyond 30 days)](https://ide.bitquery.io/Coin-ticker-api_4) #### Dex info — historical (beyond 30 days) Will fetch a specific DEX stats for the selected network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Dex info — historical (beyond 30 days)](https://ide.bitquery.io/dex-info) #### Dex markets — historical (beyond 30 days) Will fetch all the DEXs info for the selected network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Dex markets — historical (beyond 30 days)](https://ide.bitquery.io/dex-markets) ### Transfers #### ERC-20 transfers by wallet Recent token transfers in and out of one address. Replace the address in the `where` clause. ▶️ [ERC-20 transfers by wallet](https://ide.bitquery.io/Get-ERC20-token-transfers-by-wallet_7) #### ERC-20 transfers over a past period Token transfers for a wallet between two dates. Change `since` and `till`. Needs the historical data add-on — see the comment at the top of the query. ▶️ [ERC-20 transfers over a past period](https://ide.bitquery.io/Get-historical-ERC20-token-transfers-by-wallet_1) #### Array_intersect example for 2 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. ▶️ [Array_intersect example for 2 addresses](https://ide.bitquery.io/array_intersect-example-for-2-addresses_2) #### Binance:hot wallet transfers with transaction fees 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. ▶️ [Binance:hot wallet transfers with transaction fees](https://ide.bitquery.io/binancehot-wallet-transfers-with-transaction-fees) #### Find earliest transfer to an account Find the first transfer ever received by a specific wallet address. This is useful for wallet age analysis, first transaction tracking, and onboarding analytics. ▶️ [Find earliest transfer to an account](https://ide.bitquery.io/Copy-of-find-earliest-transfer-to-an-account) #### Get Contract Type in v2 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. ▶️ [Get Contract Type in v2](https://ide.bitquery.io/Get-Contract-Type-in-v2) #### Get Minted Address of the ICO Token In most of the ICOs, the token is minted to a smart contract that contains various methods for distributing the token whenever the conditions set by project owners are satisfied. ▶️ [Get Minted Address of the ICO Token](https://ide.bitquery.io/Get-Minted-Address-of-the-ICO-Token) #### Number of Purchasers in ICO Number of Purchasers in ICO. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Number of Purchasers in ICO](https://ide.bitquery.io/Number-of-Purchasers-in-ICO) #### Transfers sent OR received by an address Both sides of an address's transfer history in one result, using an OR filter. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Transfers sent OR received by an address](https://ide.bitquery.io/Sender-OR-Receiver-Transfer-on-Ethereum) #### Total txn fees paid by binance hot wallet in a day 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. ▶️ [Total txn fees paid by binance hot wallet in a day](https://ide.bitquery.io/total-txn-fees-paid-by-binance-hot-wallet-in-a-day) ### Balances & Holders #### Current balance of an address Every token balance held by one wallet, with USD value. Balances are cumulative, so this reads the full history. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Current balance of an address](https://ide.bitquery.io/Ethereum-Balance-of-an-Address_2) #### Token holder count How many addresses hold a token right now. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Token holder count](https://ide.bitquery.io/Copy-of-token-holders-count-eth) #### Balance of an address at a past date What a wallet held on a given day. Change the `date` argument. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Historical-Balance-of-an-Address_1) #### Token holders on a specific date A holder snapshot for any past day, with per-holder stats. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Token holders on a specific date](https://ide.bitquery.io/tokens-holders-of-a-token_10) #### Token Holders of Multiple Tokens until last month This API provides a list of top holders along with relevant statistics for a given token liston a specific date using BalanceUpdates API. ▶️ [Token Holders of Multiple Tokens until last month](https://ide.bitquery.io/Top-10-historical-holders-of-multiple-tokens-on-ETH) #### Average Tip in terms of avg gas Fee Compares average user tip to average total gas fee per block across the last 10 blocks. ▶️ [Average Tip in terms of avg gas Fee](https://ide.bitquery.io/Average-Tip-in-terms-of-avg-gas-Fee_4) #### Balance Updates for multiple addresses transfer in last 24 hours Balance Updates for multiple addresses transfer in last 24 hours. Uses the `TransactionBalances` cube. ▶️ [Balance Updates for multiple addresses transfer in last 24 hours](https://ide.bitquery.io/Balance-Updates-for-multiple-addresses-transfer-in-last-24-hours) #### Balance Updates for transfer in last 24 hours Balance Updates for transfer in last 24 hours. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance Updates for transfer in last 24 hours](https://ide.bitquery.io/Balance-Updates-for-transfer-in-last-24-hours) #### Balance update after transfer received from multiple addresses Balance update after transfer received from multiple addresses. Uses the `TransactionBalances` cube. ▶️ [Balance update after transfer received from multiple addresses](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses_2) #### Balance update after transfer sent from multiple addresses Balance update after transfer sent from multiple addresses. Uses the `TransactionBalances` cube. ▶️ [Balance update after transfer sent from multiple addresses](https://ide.bitquery.io/Balance-update-after-transfer-sent-from-multiple-addresses) ### Price & OHLC #### Token price from top market (rank 1) Prices WETH from its single top market rather than blending every pool — the recommended way to price one specific token. Replace `token` in the Variables pane, lowercase. ▶️ [Token price from top market (rank 1)](https://ide.bitquery.io/Ethereum-Token-price-from-top-market-rank-1) #### Ohlc of a token pair 1 hour interval 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). Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Ohlc of a token pair 1 hour interval](https://ide.bitquery.io/ohlc-of-a-token-pair-1-hour-interval) #### Historical Price and Volume Data for a Token Pair beyond 30 days Use this API to get historical price and volume for a specific token pair address on a specific network for the time window beyond the 30 days. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Historical Price and Volume Data for a Token Pair beyond 30 days](https://ide.bitquery.io/historical-price-and-historical-volume) #### Pepe historical ohlcv 30days Fetch hourly OHLCV candles for the past 30 days. Change `Duration` for different intervals, such as 60 (1 minute) or 300 (5 minutes). Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Pepe historical ohlcv 30days](https://ide.bitquery.io/pepe-historical-ohlcv-30days) #### Prices for multiple tokens at once — historical (beyond 30 days) Latest USD price for a list of tokens in a single request. Add addresses to the `in` filter. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Prices for multiple tokens at once — historical (beyond 30 days)](https://ide.bitquery.io/Price-of-multiple-tokens-in-realtime) #### Price of a token in realtime — historical (beyond 30 days) Will give 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Price of a token in realtime — historical (beyond 30 days)](https://ide.bitquery.io/Price-of-a-token-in-realtime) #### All-time high price of a token — historical (beyond 30 days) Highest price a token has ever traded at, with the date it happened. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [All-time high price of a token — historical (beyond 30 days)](https://ide.bitquery.io/ATH-of-eth-token) #### OHLCV by pair address — historical (beyond 30 days) Open, high, low, close and volume candles for one pair. Change the interval to re-bucket the candles. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [OHLCV by pair address — historical (beyond 30 days)](https://ide.bitquery.io/OHLC0_8) #### Price change over 5m, 1h, 6h and 24h — historical (beyond 30 days) Percentage moves across four windows for one token in one query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Price change over 5m, 1h, 6h and 24h — historical (beyond 30 days)](https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_4) #### Top 10 tokens by price change, last hour — historical (beyond 30 days) Biggest movers on Ethereum over the past hour, ranked. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top 10 tokens by price change, last hour — historical (beyond 30 days)](https://ide.bitquery.io/Top-10-eth-tokens-by-price-change-in-last-1-hr_2) #### Price change 5min, 1hr, 6hr precentage of a specific token — historical (beyond 30 days) Price change 5min, 1hr, 6hr precentage of a specific token. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Price change 5min, 1hr, 6hr precentage of a specific token — historical (beyond 30 days)](https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_1) ### Supply & Market Cap #### Pepe volume marketcap Provides the latest trade volume for the past one hour along with the latest market cap. ▶️ [Pepe volume marketcap](https://ide.bitquery.io/pepe-volume-marketcap) #### Top tokens by market cap Ethereum tokens ranked by market capitalisation. ▶️ [Top tokens by market cap](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Ethereum) #### Total supply and market cap of a token Current circulating supply and market cap for one token. ▶️ [Total supply and market cap of a token](https://ide.bitquery.io/Get-Token-Total-Supply-and-Market-Cap_4) #### Latest supply of USDT and USDC Live supply for the two largest stablecoins; swap the addresses for any other tokens. ▶️ [Latest supply of USDT and USDC](https://ide.bitquery.io/latest-token-supply-on-USDT-and-USDC-on-ethereum-chain_1) #### Get Token Total Supply and Market Cap Retrieve the total supply and market capitalization of a specific ERC-20 token. This query provides on-chain market cap data. ▶️ [Get Token Total Supply and Market Cap](https://ide.bitquery.io/Get-Token-Total-Supply-and-Market-Cap) #### Latest token supply on USDT and USDC on ethereum chain 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. ▶️ [Latest token supply on USDT and USDC on ethereum chain](https://ide.bitquery.io/latest-token-supply-on-USDT-and-USDC-on-ethereum-chain) #### Total Supply and onchain Marketcap of a specific token 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. ▶️ [Total Supply and onchain Marketcap of a specific token](https://ide.bitquery.io/Total-Supply-and-onchain-Marketcap-of-a-specific-token) ### Liquidity & Pools #### Latest liquidity of a pool Current reserves on both sides of one pool. Replace the pool address. ▶️ [Latest liquidity of a pool](https://ide.bitquery.io/latest-liquidity-of-a-EVM-pool_1) #### Liquidity across all pools of a token Total liquidity for a token summed across every pool it trades in. ▶️ [Liquidity across all pools of a token](https://ide.bitquery.io/liquidiy-of-all-token-pools_2) #### Top liquidity pools for a token The deepest pools holding a token, ranked by liquidity. ▶️ [Top liquidity pools for a token](https://ide.bitquery.io/top-liquidity-pools-of-atoken-on-ethereum_1) #### Decoded arguments of a specific function call Every call to one function with its arguments decoded. Change the method name to track a different function. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Decoded arguments of a specific function call](https://ide.bitquery.io/addLiquidityETH_function) #### BlackRock USD Institutional Digital Liquidity Fund Latest Issuance You can use the same as a `subscription` to monitor issuances in real-time. ▶️ [BlackRock USD Institutional Digital Liquidity Fund Latest Issuance](https://ide.bitquery.io/BlackRock-USD-Institutional-Digital-Liquidity-Fund-Latest-Issuance) #### Liquidiy of all token pools 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. ▶️ [Liquidiy of all token pools](https://ide.bitquery.io/liquidiy-of-all-token-pools_1) #### Top liquidity pools of atoken on ethereum 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. ▶️ [Top liquidity pools of atoken on ethereum](https://ide.bitquery.io/top-liquidity-pools-of-atoken-on-ethereum) #### Top liquidity pools on Ethereum You can run and modify this query in the. ▶️ [Top liquidity pools on Ethereum](https://ide.bitquery.io/top-liquidity-pools-on-Ethereum) #### Latest Liquidity Changes of a Specific Pool 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. ▶️ [Latest Liquidity Changes of a Specific Pool](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_5) ### Transactions #### Transactions by wallet Recent transactions sent from or to an address. ▶️ [Transactions by wallet](https://ide.bitquery.io/Get-transactions-by-wallet_7) #### Look up a transaction by hash Full detail for a single transaction. Paste the hash into the `where` clause. ▶️ [Look up a transaction by hash](https://ide.bitquery.io/Get-a-transaction-by-hash) #### Transaction value in USD Converts transaction value to USD at the time it was mined. ▶️ [Transaction value in USD](https://ide.bitquery.io/Transaction-value-in-USD) #### Debug traceTransaction To trace a transaction using the debug_traceTransaction we need the `transaction hash`. We are using. ▶️ [Debug traceTransaction](https://ide.bitquery.io/debug_traceTransaction) #### Eth getBlockReceipt In this section we will build an API that serves as an alternative to the eth_getBlockReceipts JSON RPC method that takes `Block Number` as an input and returns all transaction receipts for the given block. ▶️ [Eth getBlockReceipt](https://ide.bitquery.io/eth_getBlockReceipt) #### Eth getTransactionByHash Eth getTransactionByHash. Uses the `Transactions` cube. ▶️ [Eth getTransactionByHash](https://ide.bitquery.io/eth_getTransactionByHash_1) #### Eth getTransactionReceipt In this section, we will build an alternative to the eth_getTransactionReceipt JSON RPC method using the Bitquery APIs. The method is used to provide the receipt of a transaction given `transaction hash`. ▶️ [Eth getTransactionReceipt](https://ide.bitquery.io/eth_getTransactionReceipt_1) #### Internal transactions of a transaction The internal calls a transaction produced — what a block explorer shows as internal txns. ▶️ [Internal transactions of a transaction](https://ide.bitquery.io/internal-transactions-for-a-particular-tx) ### Events & Calls #### Latest smart contract calls Decoded contract calls with their arguments. ▶️ [Latest smart contract calls](https://ide.bitquery.io/Recent-Calls-on-Ethereum_2) #### Latest events and logs Decoded event logs as they land. Filter by contract or by event name. ▶️ [Latest events and logs](https://ide.bitquery.io/Recents-Events-and-Logs-on-Ethereum_3) #### All aave v3 events latest 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. ▶️ [All aave v3 events latest](https://ide.bitquery.io/All-aave-v3-events-latest) #### ByteCode of A Token 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. ▶️ [ByteCode of A Token](https://ide.bitquery.io/ByteCode-of-A-Token) #### Find the deployer of a contract Returns which address created a given contract, and when. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Find the deployer of a contract](https://ide.bitquery.io/creator--deployer-of-an-address_1) #### Debug_traceCall In this section, we will discuss how we can use Bitquery APIs as an alternative to the debug_traceCall JSON RPC method, which runs an eth_call within the context of the given block execution using the final state of parent block as the base. ▶️ [Debug_traceCall](https://ide.bitquery.io/debug_traceCall) #### ETH/BSC SC creates count over 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. ▶️ [ETH/BSC SC creates count over date](https://ide.bitquery.io/ETHBSC-SC-creates-count-over-date) #### Eth getLogs with filters Now, just like the orignal eth_getLogs method, Bitquery APIs provides the option to filter out the `Logs` based on the following parameeters. ▶️ [Eth getLogs with filters](https://ide.bitquery.io/eth_getLogs-with-filters) ### Mempool #### Get next available nonce The following query helps you determine the next available nonce for an Ethereum account by getting the latest transaction in the mempool (broadcasted transactions). The returned nonce is the highest nonce used by the account in the mempool. ▶️ [Get next available nonce](https://ide.bitquery.io/get-next-available-nonce) #### Simulating Pending Transactions 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. ▶️ [Simulating Pending Transactions](https://ide.bitquery.io/Simulating-Pending-Transactions_1) ### Blocks & Validators #### Aggregate Self-Destruct Statistics Calculate total ETH destroyed or received from self-destructs using aggregation functions. ▶️ [Aggregate Self-Destruct Statistics](https://ide.bitquery.io/Aggregate-Self-Destruct-Statistics) #### QuasarBuilder MEV Payout Transaction Balance 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. ▶️ [QuasarBuilder MEV Payout Transaction Balance](https://ide.bitquery.io/QuasarBuilder-MEV-Payout-Transaction-Balance) #### Self-Destruct Balance Decrease API Monitor contract balance decrease when contracts are self-destructing. ▶️ [Self-Destruct Balance Decrease API](https://ide.bitquery.io/Self-Destruct-Balance-Decrease-API) #### Self-Destruct Balance Increase API Monitor contract balance increase when contracts are self-destructing. ▶️ [Self-Destruct Balance Increase API](https://ide.bitquery.io/Self-Destruct-Balance-Increase-API) #### Top validators by total tips in last 24 hrs Ranks validators by cumulative priority fees (reason code 5) received in the last 24 hours. ▶️ [Top validators by total tips in last 24 hrs](https://ide.bitquery.io/top-validators-by-total-tips-in-last-24-hrs) #### Total tips received 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. ▶️ [Total tips received by a validator in last 24 hrs](https://ide.bitquery.io/total-tips-received-by-a-validator-in-last-24-hrs) ### Uniswap #### Latest slippage on a Uniswap v3 pool Per-trade slippage for one v3 pool, to size orders before sending them. ▶️ [Latest slippage on a Uniswap v3 pool](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Uniswap-v3-Ethereum_1) #### All Pool_Ids for currency These swaps use the chain-specific DEXTrades cube via `EVM { DEXTrades }`: `Trade.PoolId`, pool-relative Buy/Sell (DEXTrades cube). USD can be thin on small pools—use live swaps above when you want the Trading row shape. ▶️ [All Pool_Ids for currency](https://ide.bitquery.io/All-Pool_Ids-for-currency) #### Fee collection on Uniswap v3 Positions It returns decoded arguments—including the Uniswap position `tokenId`, the `recipient` address, and the collected `amount0` and `amount1` values (raw integer amounts). ▶️ [Fee collection on Uniswap v3 Positions](https://ide.bitquery.io/Fee-collection-on-Uniswap-v3-Positions) #### Latest ModifyLiquidity Events on Uniswap v4 Track the most recent liquidity modifications on Uniswap V4 by querying `ModifyLiquidity` events from the PoolManager contract. ▶️ [Latest ModifyLiquidity Events on Uniswap v4](https://ide.bitquery.io/Latest-ModifyLiquidity-Events-on-Uniswap-v4) #### Latest trades of a Uniswap pair Trades for one Uniswap pair. Replace the pair address. ▶️ [Latest trades of a Uniswap pair](https://ide.bitquery.io/Latest-Trades-of-a-Pair-on-Uniswap) #### Latest liquidity for a currency pair across all v4 pools This API endpoint provides latest liquidity event for every Uniswap V4 pool for a given currency pair. This info includes the Price of currencies in terms of other, Price of currencies in USD, Currency Details and `PoolIDs`. ▶️ [Latest liquidity for a currency pair across all v4 pools](https://ide.bitquery.io/latest-liquidity-for-a-currency-pair-across-all-v4-pools_1) #### Latest liquidity for an individual pool on uniswap v4 Returns the most recent liquidity event for a single Uniswap v4 pool. Replace `$poolId` with your target `PoolId` (from trades UI, subgraph, or a prior `DEXTradeByTokens` / `DEXPoolEvents` discovery query). ▶️ [Latest liquidity for an individual pool on uniswap v4](https://ide.bitquery.io/latest-liquidity-for-an-individual-pool-on-uniswap-v4) #### Latest slippage of a pool on Uniswap v3 Ethereum 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. ▶️ [Latest slippage of a pool on Uniswap v3 Ethereum](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Uniswap-v3-Ethereum) #### Latest trade price of uniswap pair Here's an example of tracking Uniswap token pair trading price. ▶️ [Latest trade price of uniswap pair](https://ide.bitquery.io/latest-trade-price-of-uniswap-pair) #### Latest trades for a Pool Id on uniswap v4 Latest trades for a Pool Id on uniswap v4. Uses the `DEXTrades` cube. ▶️ [Latest trades for a Pool Id on uniswap v4](https://ide.bitquery.io/Latest-trades-for-a-Pool-Id-on-uniswap-v4) ### PancakeSwap #### Latest Trades on PancakeSwap V3 ETH The PancakSwap DEX Data is also available for view as a dashboard at DEXRABBIT. ▶️ [Latest Trades on PancakeSwap V3 ETH](https://ide.bitquery.io/Latest-Trades-on-PancakeSwap-V3-ETH) #### Top Traders of a token on PancakeSwap on ETH Top Traders of a token on PancakeSwap on ETH. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Top Traders of a token on PancakeSwap on ETH](https://ide.bitquery.io/Top-Traders-of-a-token-on-PancakeSwap-on-ETH) #### Top token pairs on PancakeSwap v3 Top token pairs on PancakeSwap v3. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Top token pairs on PancakeSwap v3](https://ide.bitquery.io/Top-token-pairs-on-PancakeSwap-v3) ## BSC ### Trades #### BSC DEX Trades This query returns the latest trades on the BSC network from a trader perspective and returns useful metrics such as marketcap and pool ranking. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [BSC DEX Trades](https://ide.bitquery.io/BSC-dextrades_9) #### BSC Dex Trade By Tokens This query returns the latest trades on the BSC network. This is useful when looking for trades of a token. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [BSC Dex Trade By Tokens](https://ide.bitquery.io/BSC-dextrades-for-a-token) #### Get Trades by a Trader Get all trades by a particular trader. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Get Trades by a Trader](https://ide.bitquery.io/BSC-dextrades-by-a-trader) #### First 500 buyers of a specific BSC chain token — historical (beyond 30 days) Below API gets you the first 500 buyers of a specific BSC token, here as example we have taken this token `0x031b41e504677879370e9DBcF937283A8691Fa7f`. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [First 500 buyers of a specific BSC chain token — historical (beyond 30 days)](https://ide.bitquery.io/first-500-buyers-of-a-specific-BSC-chain-token_2) #### Get all the DEXs on BSC network — historical (beyond 30 days) Retrieves all the DEXes operating on BSC network and gives info such as `ProtocolName` , `ProtocolVersion` and `ProtocolFamily`. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get all the DEXs on BSC network — historical (beyond 30 days)](https://ide.bitquery.io/Get-all-the-DEXs-on-BSC-network) #### Latest Flap.sh trades using DEXTrades API — historical (beyond 30 days) Monitor all recent trades across Flap.sh tokens using the DEXTrades API. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latest Flap.sh trades using DEXTrades API — historical (beyond 30 days)](https://ide.bitquery.io/Latest-Flapsh-trades-using-DEXTrades-API) #### Top Gainers on BSC — historical (beyond 30 days) Get Top Gainers for the BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top Gainers on BSC — historical (beyond 30 days)](https://ide.bitquery.io/bsc-top-gainers) #### All dexs info on bsc — historical (beyond 30 days) Will fetch all the DEXs info for the BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [All dexs info on bsc — historical (beyond 30 days)](https://ide.bitquery.io/all-dexs-info-on-bsc) #### Get all dex markets for a token — historical (beyond 30 days) Will fetch all the DEXs where a token is listed for the BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get all dex markets for a token — historical (beyond 30 days)](https://ide.bitquery.io/get-all-dex-markets-for-a-token) #### Latest Flap.sh trades for a specific token — historical (beyond 30 days) Get trading activity for a specific Flap.sh token using DEXTradeByTokens API. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latest Flap.sh trades for a specific token — historical (beyond 30 days)](https://ide.bitquery.io/Latest-Flapsh-trades-for-a-specific-token) ### Settlements #### Gra fun redeem transactions Gra fun redeem transactions. Uses the `Events` cube. Replace the address in the `where` clause to use it. ▶️ [Gra fun redeem transactions](https://ide.bitquery.io/Gra-fun-redeem-transactions) ### Transfers #### Get Historical ERC20 token transfers by wallet Get ERC20 token transfers for an address in a given historical time window ▶️ [Get Historical ERC20 token transfers by wallet](https://ide.bitquery.io/Get-historical-ERC20-token-transfers-by-wallet-bsc) #### Get token transfers by wallet Get token transactions ordered by block number in descending order. ▶️ [Get token transfers by wallet](https://ide.bitquery.io/Get-ERC20-token-transfers-by-wallet-bsc) #### Check if an address interacted with predict.fun ever 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. ▶️ [Check if an address interacted with predict.fun ever](https://ide.bitquery.io/check-if-an-address-interacted-with-predictfun-ever) #### Check who created this 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. ▶️ [Check who created this meme rush token](https://ide.bitquery.io/check-who-created-this-meme-rush-token) #### Check who created this 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. ▶️ [Check who created this token](https://ide.bitquery.io/check-who-created-this-token) #### First transfers of a token Retrieves the first transfer of a token to each address, providing the timestamp when each address first received the token. ▶️ [First transfers of a token](https://ide.bitquery.io/first-transfers-of-a-token_5) #### Meme rush tokens created by 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`. ▶️ [Meme rush tokens created by specific dev](https://ide.bitquery.io/meme-rush-tokens-created-by-specific-dev) #### 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. ▶️ [New Flap.sh Tokens Created Using Transfers API](https://ide.bitquery.io/New-Flapsh-Tokens-Created-Using-Transfers-API) #### Sender OR Receiver Transfer Example BSC Sender OR Receiver Transfer Example BSC. Uses the `Transfers` cube. Replace the address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Sender OR Receiver Transfer Example BSC](https://ide.bitquery.io/Sender-OR-Receiver-Transfer-Example-BSC) #### Token created by 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`. ▶️ [Token created by specific dev](https://ide.bitquery.io/token-created-by-specific-dev) ### Balances & Holders #### Get latest BNB balance of an wallet Get latest BNB balance of an wallet. ▶️ [Get latest BNB balance of an wallet](https://ide.bitquery.io/Latest-native-balance-of-an-address-bsc) #### Average Tip in terms of avg gas Fee bsc Compares average user tip to average total gas fee per block across the last 10 blocks. ▶️ [Average Tip in terms of avg gas Fee bsc](https://ide.bitquery.io/Average-Tip-in-terms-of-avg-gas-Fee-bsc) #### Latest balance of an address for a specific token bsc This API gives you latest balance of a specific address (here in example `0x238a358808379702088667322f80ac48bad5e6c4`) for a specific token (here we have taken example of USDC `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`). Try it out. ▶️ [Latest balance of an address for a specific token bsc](https://ide.bitquery.io/Latest-balance-of-an-address-for-a-specific-token-bsc) #### Top 10 holders percentage Calculates the percentage of total supply held by the top 10 holders of a specific Four Meme token on BSC. ▶️ [Top 10 holders percentage](https://ide.bitquery.io/top-10-holders-percentage) #### Track recent ephemeral contract patterns bsc Many MEV bots and arbitrage executors create contracts that are destroyed within the same transaction. These short-lived contracts are used for. ▶️ [Track recent ephemeral contract patterns bsc](https://ide.bitquery.io/Track-recent-ephemeral-contract-patterns-bsc) #### Balance Updates for multiple addresses transfer in last 24 hours bsc Balance Updates for multiple addresses transfer in last 24 hours bsc. Uses the `TransactionBalances` cube. ▶️ [Balance Updates for multiple addresses transfer in last 24 hours bsc](https://ide.bitquery.io/Balance-Updates-for-multiple-addresses-transfer-in-last-24-hours-bsc) #### Balance Updates for transfer in last 24 hours bsc Balance Updates for transfer in last 24 hours bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance Updates for transfer in last 24 hours bsc](https://ide.bitquery.io/Balance-Updates-for-transfer-in-last-24-hours-bsc) #### Balance update after transfer received bsc Balance update after transfer received bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update after transfer received bsc](https://ide.bitquery.io/Balance-update-after-transfer-received-bsc) #### Balance update after transfer received from multiple addresses bsc Balance update after transfer received from multiple addresses bsc. Uses the `TransactionBalances` cube. ▶️ [Balance update after transfer received from multiple addresses bsc](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses-bsc) #### Balance update after transfer sent bsc Balance update after transfer sent bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update after transfer sent bsc](https://ide.bitquery.io/Balance-update-after-transfer-sent-bsc) ### Price & OHLC #### Token price from top market (rank 1) Prices WBNB from its single top market rather than blending every pool — the recommended way to price one specific token. Replace `token` in the Variables pane, lowercase. ▶️ [Token price from top market (rank 1)](https://ide.bitquery.io/BSC-Token-price-from-top-market-rank-1) #### OHLCV data for specific Flap.sh token against BNB Get OHLCV data for Flap.sh tokens paired with BNB. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [OHLCV data for specific Flap.sh token against BNB](https://ide.bitquery.io/OHLCV-data-for-specific-Flapsh-token-against-BNB) #### OHLCV data for specific Flap.sh token in USD Get OHLCV (Open, High, Low, Close, Volume) data for Flap.sh tokens quoted in USD. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [OHLCV data for specific Flap.sh token in USD](https://ide.bitquery.io/OHLCV-data-for-specific-Flapsh-token-in-USD) #### BEP-20 Token Price — historical (beyond 30 days) Get the latest price of a BEP-20 token on BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [BEP-20 Token Price — historical (beyond 30 days)](https://ide.bitquery.io/realtime-usd-price-of-a-token) #### Get Price Change 5min, 1h, 6h and 24h of a specific BSC token — historical (beyond 30 days) This query gets you Price Change 5min, 1h, 6h and 24h of a specific token on the BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Price Change 5min, 1h, 6h and 24h of a specific BSC token — historical (beyond 30 days)](https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_3) #### OHLC for a BEP-20 Token — historical (beyond 30 days) Get OHLC statistics for a BEP-20 token on BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [OHLC for a BEP-20 Token — historical (beyond 30 days)](https://ide.bitquery.io/OHLC-for-a-token-on-bsc_1) #### Top 10 BSC Tokens by Price Change in last 1h — historical (beyond 30 days) This query gets you top 10 BSC Tokens by Price Change in last 1h. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top 10 BSC Tokens by Price Change in last 1h — historical (beyond 30 days)](https://ide.bitquery.io/Top-10-bsc-tokens-by-price-change-in-last-1-hr) #### BSC OHLC API For Token Pair — historical (beyond 30 days) Will fetch the OHLC of a token pair for the BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [BSC OHLC API For Token Pair — historical (beyond 30 days)](https://ide.bitquery.io/BSC-OHLC-API-For-Token-Pair) #### Meme rush token ATH price — historical (beyond 30 days) 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). Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Meme rush token ATH price — historical (beyond 30 days)](https://ide.bitquery.io/meme-rush-token-ATH-price) #### Latest price of a token on bsc — historical (beyond 30 days) Will fetch latest trades for a token pair for the BSC network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latest price of a token on bsc — historical (beyond 30 days)](https://ide.bitquery.io/Latest-price-of-a-token-on-bsc) #### Percentage price change for a meme rush token — historical (beyond 30 days) 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Percentage price change for a meme rush token — historical (beyond 30 days)](https://ide.bitquery.io/Percentage-price-change-for-a-meme-rush-token) ### Supply & Market Cap #### Top Tokens by Market Cap on bsc Ranks tokens on BNB Smart Chain by `Supply.MarketCap`, with 24h window, 1s interval, $1,000+ USD volume, `limitBy` per `Token_Id`, up to 50 rows. `Token.Network` is Binance Smart Chain. ▶️ [Top Tokens by Market Cap on bsc](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-bsc) #### Get Total Supply and Marketcap of an ERC20 token Get Total Supply and Marketcap of an ERC20 token. ▶️ [Get Total Supply and Marketcap of an ERC20 token](https://ide.bitquery.io/Total-Supply-and-onchain-Marketcap-of-a-specific-token-bsc_1) #### Total Supply and onchain Marketcap of a specific token bsc This API gives you latest Supply and Marketcap of a token on BSC (here as example we have taken a BEP-20 token `0x55d398326f99059ff775485246999027b3197955`). Try it out. ▶️ [Total Supply and onchain Marketcap of a specific token bsc](https://ide.bitquery.io/Total-Supply-and-onchain-Marketcap-of-a-specific-token-bsc) ### Liquidity & Pools #### 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. ▶️ [Latest Slippage for a Specific Pool](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Pancakeswap) #### Latest Liquidity Changes of a Specific Pool Retrieves the latest liquidity events for a specific DEX pool on BSC. Use this to check current pool reserves, spot prices, and recent liquidity changes for a particular token pair. ▶️ [Latest Liquidity Changes of a Specific Pool](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_2) ### Transactions #### Get transactions by wallet Get transactions ordered by block number in descending order. ▶️ [Get transactions by wallet](https://ide.bitquery.io/Get-transactions-by-wallet_6) #### Gra fun buy transactions Retrieve all buy transactions from GRA.fun using. ▶️ [Gra fun buy transactions](https://ide.bitquery.io/Gra-fun-buy-transactions) #### Gra fun sell transactions Retrieve all sell transactions on GRA fun using. ▶️ [Gra fun sell transactions](https://ide.bitquery.io/Gra-fun-sell-transactions) ### Events & Calls #### Latest Calls on BSC network 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. ▶️ [Latest Calls on BSC network](https://ide.bitquery.io/Latest-Calls-on-BSC-network) #### Latest flap.sh token created using events data Monitor token creation events directly from the Flap.sh portal contract for more detailed information. ▶️ [Latest flap.sh token created using events data](https://ide.bitquery.io/Latest-flapsh-token-created-using-events-data_1) ### Blocks & Validators #### Aggregate Self-Destruct Statistics bsc Calculate total ETH destroyed or received from self-destructs using aggregation functions. ▶️ [Aggregate Self-Destruct Statistics bsc](https://ide.bitquery.io/Aggregate-Self-Destruct-Statistics-bsc) #### Self-Destruct Balance Decrease API bsc Monitor contract balance decrease when contracts are self-destructing. ▶️ [Self-Destruct Balance Decrease API bsc](https://ide.bitquery.io/Self-Destruct-Balance-Decrease-API-bsc) #### Self-Destruct Balance Increase API bsc Monitor contract balance increase when contracts are self-destructing. ▶️ [Self-Destruct Balance Increase API bsc](https://ide.bitquery.io/Self-Destruct-Balance-Increase-API-bsc) #### Top validators by total tips in last 24 hrs bsc Ranks validators by cumulative priority fees (reason code 5) received in the last 24 hours. ▶️ [Top validators by total tips in last 24 hrs bsc](https://ide.bitquery.io/top-validators-by-total-tips-in-last-24-hrs-bsc) #### Historical Miner Balance Data bsc Historical Miner Balance Data bsc. Uses the `TransactionBalances` cube. ▶️ [Historical Miner Balance Data bsc](https://ide.bitquery.io/Historical-Miner-Balance-Data-bsc) #### Total tips received by a validator in last 24 hrs bsc Returns the total priority fees (native and USD) earned by a specific validator over the last 24 hours. ▶️ [Total tips received by a validator in last 24 hrs bsc](https://ide.bitquery.io/total-tips-received-by-a-validator-in-last-24-hrs-bsc) ### PancakeSwap #### OHLC of a Token on PancakeSwap Get the OHLC stats of a token traded on Pancakeswap. ▶️ [OHLC of a Token on PancakeSwap](https://ide.bitquery.io/OHLC-of-a-Token-on-pancake_swap_v3) #### Price of a Token on PancakeSwap Get the latest price of a token traded on Pancakeswap. ▶️ [Price of a Token on PancakeSwap](https://ide.bitquery.io/BSC-PancakeSwap-v3-Price-for-a-token) #### Trades on Pancakeswap Get the latest trades on Pancakeswap. ▶️ [Trades on Pancakeswap](https://ide.bitquery.io/BSC-dextrades-for-pancakeswap) #### All pools of a token on pancake swap All pools of a token on pancake swap. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [All pools of a token on pancake swap](https://ide.bitquery.io/All-pools-of-a-token-on-pancake-swap_2) #### Bsc pancakeswap ohlc using trading api Bsc pancakeswap ohlc using trading api. Uses the `Pairs` cube. ▶️ [Bsc pancakeswap ohlc using trading api](https://ide.bitquery.io/bsc-pancakeswap-ohlc-using-trading-api) #### Get Latest Price of a token on PancakeSwap Infinity Below query will get you Latest Price of a token on PancakeSwap Infinity. ▶️ [Get Latest Price of a token on PancakeSwap Infinity](https://ide.bitquery.io/Get-Latest-Price-of-a-token-on-PancakeSwap-Infinity_1) #### Get metadata for bsc pancakeswap infnity token Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. ▶️ [Get metadata for bsc pancakeswap infnity token](https://ide.bitquery.io/get-metadata-for-bsc-pancakeswap-infnity-token) #### Get metadata pancakeswap Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. ▶️ [Get metadata pancakeswap](https://ide.bitquery.io/get-metadata-pancakeswap) ### Four Meme #### Get Dev and Age of Four Meme Token Below query retrieves the Dev address and time when a Four Meme Token was created. ▶️ [Get Dev and Age of Four Meme Token](https://ide.bitquery.io/get-dev-and-age-of-a-four-meme-token) #### Get Newly Created Tokens on Four Meme This query retrieves newly created tokens on Four Meme by listening to the `TokenCreate` event. The response provides token information including creator address, token contract address, name, symbol, total supply, and launch details. ▶️ [Get Newly Created Tokens on Four Meme](https://ide.bitquery.io/track-Four-meme-token-creation-using-events) #### Liquidity Addition for Four Meme Token Get the liquidity addition events for a specific token on the Four Meme Exchange. ▶️ [Liquidity Addition for Four Meme Token](https://ide.bitquery.io/Liquidity-Added-to-specific-tokens-on-Four-meme) #### Four meme - token ATH price 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). ▶️ [Four meme - token ATH price](https://ide.bitquery.io/four-meme---token-ATH-price) #### Get first buys of an address list of 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. ▶️ [Get first buys of an address list of a specific token](https://ide.bitquery.io/get-first-buys-of-an-address-list-of-a-specific-token_2) #### If meme rush token migrated from four meme 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. ▶️ [If meme rush token migrated from four meme or not](https://ide.bitquery.io/if-meme-rush-token-migrated-from-four-meme-or-not) #### If token migrated from four meme 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. ▶️ [If token migrated from four meme or not](https://ide.bitquery.io/if-token-migrated-from-four-meme-or-not_4) #### Top buyers of a four meme token Top buyers of a four meme token. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Top buyers of a four meme token](https://ide.bitquery.io/Top-buyers-of-a-four-meme-token) #### Top buyers of a meme rush token Top buyers of a meme rush token. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Top buyers of a meme rush token](https://ide.bitquery.io/Top-buyers-of-a-meme-rush-token) #### Top tokens by launch marketcap on fourmeme 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. ▶️ [Top tokens by launch marketcap on fourmeme](https://ide.bitquery.io/top-tokens-by-launch-marketcap-on-fourmeme_1) ### Uniswap #### Trading Pairs on a BSC DEX Get all trading pairs present on a BSC network DEX. ▶️ [Trading Pairs on a BSC DEX](https://ide.bitquery.io/trading-pairs-on-BNB-by-USD-volume) #### Get metadata Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. ▶️ [Get metadata](https://ide.bitquery.io/get-metadata_1) #### Latest Trades for a currency pair on bsc Latest Trades for a currency pair on bsc. Uses the `DEXTrades` cube. ▶️ [Latest Trades for a currency pair on bsc](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-bsc) #### OHLC on BSC Uniswap v3 Retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on Uniswap v3 over a defined time period and interval. ▶️ [OHLC on BSC Uniswap v3](https://ide.bitquery.io/OHLC-on-BSC-Uniswap-v3) #### Top bought tokens on bsc uniswap v3 Will fetch the top bought tokens on uniswap v3. ▶️ [Top bought tokens on bsc uniswap v3](https://ide.bitquery.io/top-bought-tokens-on-bsc-uniswap-v3) #### Top buyers of a currency on uniswap v4 bsc Top buyers of a currency on uniswap v4 bsc. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top buyers of a currency on uniswap v4 bsc](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-bsc) #### Top sellers of a token on uniswap v4 pool bsc Top sellers of a token on uniswap v4 pool bsc. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top sellers of a token on uniswap v4 pool bsc](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-pool-bsc) #### Top sold tokens on bsc uniswap v3 Will fetch the top bought tokens on uniswap v3. ▶️ [Top sold tokens on bsc uniswap v3](https://ide.bitquery.io/top-sold-tokens-on-bsc-uniswap-v3) #### Top traders of a token on uniswapv3 bsc Will fetch top traders of a token for the selected network. ▶️ [Top traders of a token on uniswapv3 bsc](https://ide.bitquery.io/top-traders-of-a-token-on-uniswapv3-bsc) #### Trade stats for a token pair on uniswap v4 bsc Trade stats for a token pair on uniswap v4 bsc. Uses the `DEXTradeByTokens` cube. ▶️ [Trade stats for a token pair on uniswap v4 bsc](https://ide.bitquery.io/trade-stats-for-a-token-pair-on-uniswap-v4-bsc_1) ## Base ### Trades #### Base DEX Trades This query returns the latest trades on the Base network from a trader perspective and returns useful metrics such as marketcap and pool ranking. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Base DEX Trades](https://ide.bitquery.io/base-dextrades_3) #### Base Dex Trade By Tokens This query returns the latest trades on the Base network. This is useful when looking for trades of a token. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Base Dex Trade By Tokens](https://ide.bitquery.io/base-dextrades-for-a-token) #### Get Trades by a Trader Get all trades by a particular trader. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Get Trades by a Trader](https://ide.bitquery.io/base-dextrades-by-a-trader) #### Top Traders by PnL of a specific base pool 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. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Top Traders by PnL of a specific base pool](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-base-pool_1) #### Ape store token trades Ape store token trades. Uses the `Calls` cube. Replace the address in the `where` clause to use it. ▶️ [Ape store token trades](https://ide.bitquery.io/ape-store-token-trades) #### First 500 buyers of a specific base token — historical (beyond 30 days) Below API gets you the first 500 buyers of a specific Base chain token, here as example we have taken this token `0x58538e6A46E07434d7E7375Bc268D3cb839C0133`. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [First 500 buyers of a specific base token — historical (beyond 30 days)](https://ide.bitquery.io/first-500-buyers-of-a-specific-base-token) #### Latest Trades of a Token on Zora Base — historical (beyond 30 days) Latest Trades of a Token on Zora Base. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latest Trades of a Token on Zora Base — historical (beyond 30 days)](https://ide.bitquery.io/Latest-Trades-of-a-Token-on-Zora-Base) #### Latest Zora Trades on Base — historical (beyond 30 days) Fetches the latest DEX trades on the Zora protocol (`zora_v4`) on Base blockchain. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latest Zora Trades on Base — historical (beyond 30 days)](https://ide.bitquery.io/Latest-Zora-Trades-on-Base) #### Most Traded Tokens on Aerodome Last Month — historical (beyond 30 days) 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Most Traded Tokens on Aerodome Last Month — historical (beyond 30 days)](https://ide.bitquery.io/Most-Traded-Tokens-on-Aerodome-Last-Month) ### Transfers #### Get Historical ERC20 token transfers by wallet Get ERC20 token transfers for an address in a given historical time window ▶️ [Get Historical ERC20 token transfers by wallet](https://ide.bitquery.io/Get-historical-ERC20-token-transfers-by-wallet-base_2) #### Get token transfers by wallet Get token transactions ordered by block number in descending order. ▶️ [Get token transfers by wallet](https://ide.bitquery.io/Get-token-transfers-by-wallet-base_1) #### Newly created zora tokens Retrieves the list of newly created tokens on Zora Launchpad by monitoring transfers where new tokens are minted (sender is the zero address) with a specific amount. ▶️ [Newly created zora tokens](https://ide.bitquery.io/Newly-created-zora-tokens) #### Tx from to base address We use the `any` filter [ OR condition] to get transactions from or to a wallet. ▶️ [Tx from to base address](https://ide.bitquery.io/tx-from-to-base-address) ### Balances & Holders #### Current balance of an address Every token balance held by one Base address. Balances are cumulative, so this reads the whole history — replace the address to use it. ▶️ [Current balance of an address](https://ide.bitquery.io/Base-Current-balance-of-an-address) #### Real-Time Holders of Multiple Tokens This API leverages the balanceUpdate endpoint to deliver real-time holder data for multiple tokens. ▶️ [Real-Time Holders of Multiple Tokens](https://ide.bitquery.io/Top-10-holders-of-multiple-tokens-on-Base_2) #### Token Holder Count on a Specific Date This API returns the total number of holders for a specific token on a given date. ▶️ [Token Holder Count on a Specific Date](https://ide.bitquery.io/token-holders-count-base) #### Token Holders and Stats on a Specific Date - TokenHolders API This API provides a list of all holders along with relevant statistics for a given token on a specific date. ▶️ [Token Holders and Stats on a Specific Date - TokenHolders API](https://ide.bitquery.io/tokens-holders-of-a-token-base) #### Token Holders of Multiple Tokens on a speicifc date This API provides a list of top holders along with relevant statistics for a given token liston a specific date using Holders API. ▶️ [Token Holders of Multiple Tokens on a speicifc date](https://ide.bitquery.io/Top-10-holders-of-multiple-tokens-on-Base-at-a-specific-time-holder-api) #### Get All Token Balances for an Address Retrieve all token balances held by a specific address. This query returns balances for all tokens the address holds. ▶️ [Get All Token Balances for an Address](https://ide.bitquery.io/Get-All-Token-Balances-for-an-Address_4) #### Get latest token balance of a wallet Get latest token balance of a wallet. ▶️ [Get latest token balance of a wallet](https://ide.bitquery.io/Get-Latest-Token-Balance-for-an-Address_4) #### Base balances address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. ▶️ [Base balances address](https://ide.bitquery.io/base-balances-address) #### Base native balances address 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. ▶️ [Base native balances address](https://ide.bitquery.io/base-native-balances-address) #### Latest balance of an address for a specific token base This API gives you latest balance of a specific address (here in example `0x238a358808379702088667322f80ac48bad5e6c4`) for a specific token (here we have taken example of USDC `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`). Try it out. ▶️ [Latest balance of an address for a specific token base](https://ide.bitquery.io/Latest-balance-of-an-address-for-a-specific-token-base) #### Token holder snapshot base 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. ▶️ [Token holder snapshot base](https://ide.bitquery.io/token-holder-snapshot-base) ### Price & OHLC #### Token price from top market (rank 1) Prices WETH from its single top market rather than blending every pool — the recommended way to price one specific token. Replace `token` in the Variables pane, lowercase. ▶️ [Token price from top market (rank 1)](https://ide.bitquery.io/Base-Token-price-from-top-market-rank-1) #### Get Multiple Token Prices — historical (beyond 30 days) Returns an array of token prices denominated in the blockchain's native token and USD for a given token contract address. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Multiple Token Prices — historical (beyond 30 days)](https://ide.bitquery.io/Price-of-multiple-tokens-in-realtime_1) #### Get ATH Price of a token — historical (beyond 30 days) Retrieves the all-time high (ATH) price in USD for a specified token contract. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get ATH Price of a token — historical (beyond 30 days)](https://ide.bitquery.io/ATH-of-base-token) #### Get OHLCV by Pair Address — historical (beyond 30 days) Get the OHLCV candle stick by using pair address. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get OHLCV by Pair Address — historical (beyond 30 days)](https://ide.bitquery.io/OHLC--base) #### Get Price Change 5min, 1h, 6h and 24h of a specific token — historical (beyond 30 days) This query gets you Price Change 5min, 1h, 6h and 24h of a specific token on the Base network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get Price Change 5min, 1h, 6h and 24h of a specific token — historical (beyond 30 days)](https://ide.bitquery.io/Price-change-5min-1hr-6hr-precentage-of-a-specific-token_6) #### Top 10 Base Tokens by Price Change in last 1h — historical (beyond 30 days) This query gets you top 10 Base Tokens by Price Change in last 1h. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top 10 Base Tokens by Price Change in last 1h — historical (beyond 30 days)](https://ide.bitquery.io/Top-10-base-tokens-by-price-change-in-last-1-hr_1) #### OHLC-of-AERO-Coin — historical (beyond 30 days) OHLC-of-AERO-Coin. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [OHLC-of-AERO-Coin — historical (beyond 30 days)](https://ide.bitquery.io/OHLC-of-AERO-Coin_1) #### Price change 5min, 1hr, 6hr, 24h precentage of a specific token — historical (beyond 30 days) Price change 5min, 1hr, 6hr, 24h precentage of a specific token. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Price change 5min, 1hr, 6hr, 24h precentage of a specific token — historical (beyond 30 days)](https://ide.bitquery.io/Price-change-5min-1hr-6hr-24h-precentage-of-a-specific-token) #### Top 10 base tokens by price change in last 1 hr — historical (beyond 30 days) Top 10 base tokens by price change in last 1 hr. Uses the `DEXTradeByTokens` cube. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top 10 base tokens by price change in last 1 hr — historical (beyond 30 days)](https://ide.bitquery.io/Top-10-base-tokens-by-price-change-in-last-1-hr) ### Supply & Market Cap #### Top Tokens by Market Cap on Base This query ranks Base 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. ▶️ [Top Tokens by Market Cap on Base](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Base) #### Bankr token latest marketcap OHLC Bankr token latest marketcap OHLC. Uses the `Tokens` cube. ▶️ [Bankr token latest marketcap OHLC](https://ide.bitquery.io/Bankr-token-latest-marketcap-OHLC) #### Get Token Total Supply and Market Cap Retrieve the total supply and market capitalization of a specific token. This query provides on-chain market cap data. ▶️ [Get Token Total Supply and Market Cap](https://ide.bitquery.io/Get-Token-Total-Supply-and-Market-Cap_5) #### Total supply of a AERO on Base Total supply of a AERO on Base. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Total supply of a AERO on Base](https://ide.bitquery.io/Total-supply-of-a-AERO-on-Base) #### Total Supply and onchain Marketcap of a specific token base This API gives you latest Supply and Marketcap of a token on Base. Try it out. ▶️ [Total Supply and onchain Marketcap of a specific token base](https://ide.bitquery.io/Total-Supply-and-onchain-Marketcap-of-a-specific-token-base) ### Liquidity & Pools #### Latest Liquidity of Base Pool Get the latest liquidity of an Base DEX pool (e.g., Uniswap v3 pool). ▶️ [Latest Liquidity of Base Pool](https://ide.bitquery.io/latest-liquidity-of-a-Base-pool_2) #### 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. ▶️ [Latest Slippage for a Specific Pool](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_7) #### Latest Liquidity Changes of a Specific Pool Retrieves the latest liquidity events for a specific DEX pool on Base. Use this to check current pool reserves, spot prices, and recent liquidity changes for a particular token pair. ▶️ [Latest Liquidity Changes of a Specific Pool](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_4) #### Latest Liquidity Pools on Aerodome Track newly created liquidity pools on Aerodrome Finance in real-time. Discover fresh trading pairs and potential liquidity provision opportunities as pools are created. ▶️ [Latest Liquidity Pools on Aerodome](https://ide.bitquery.io/Latest-Liquidity-Pools-on-Aerodome) #### Top liquidity pools of cbBTC This query separates results by whether cbBTC 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. ▶️ [Top liquidity pools of cbBTC](https://ide.bitquery.io/top-liquidity-pools-of-cbBTC) ### Transactions #### Get transactions by wallet Get transactions ordered by block number in descending order. ▶️ [Get transactions by wallet](https://ide.bitquery.io/Get-transactions-by-wallet_8) #### Latest gauge vaults claimRewards transactions 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 gauge vaults claimRewards transactions](https://ide.bitquery.io/latest-gauge-vaults-claimRewards-transactions) #### Latest gauge vaults deposits transactions 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. ▶️ [Latest gauge vaults deposits transactions](https://ide.bitquery.io/latest-gauge-vaults-deposits-transactions) #### Latest gauge vaults withdraw transactions 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 gauge vaults withdraw transactions](https://ide.bitquery.io/latest-gauge-vaults-withdraw-transactions_1) ### Events & Calls #### Get Latest Calls Get Latest Calls. Uses the `Calls` cube. ▶️ [Get Latest Calls](https://ide.bitquery.io/Recent-Calls-on-base_1) #### Get Latest Events Get Latest Events. Uses the `Events` cube. ▶️ [Get Latest Events](https://ide.bitquery.io/Recents-Events-and-Logs-on-Base) #### Latest Bankr launches Doppler Airlock Base 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. ▶️ [Latest Bankr launches Doppler Airlock Base](https://ide.bitquery.io/Latest-Bankr-launches-Doppler-Airlock-Base) #### All bankers 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. ▶️ [All bankers tokens created by a deployer](https://ide.bitquery.io/All-bankers-tokens-created-by-a-deployer) #### Ape store buys from a wallet Ape store buys from a wallet. Uses the `Calls` cube. Replace the address in the `where` clause to use it. ▶️ [Ape store buys from a wallet](https://ide.bitquery.io/ape-store-buys-from-a-wallet) #### Ape store token event Firstly, we can find the smart contract address of the APE Store using. ▶️ [Ape store token event](https://ide.bitquery.io/ape-store-token-event_1) #### Ape-store-buys Ape-store-buys. Uses the `Calls` cube. Replace the address in the `where` clause to use it. ▶️ [Ape-store-buys](https://ide.bitquery.io/ape-store-buys_1) #### Base jump token event Firstly, we can find the smart contract address of the Base Jump using. ▶️ [Base jump token event](https://ide.bitquery.io/base-jump-token-event) #### Base-jump-buys Base-jump-buys. Uses the `Calls` cube. Replace the address in the `where` clause to use it. ▶️ [Base-jump-buys](https://ide.bitquery.io/base-jump-buys) #### Latest Coin on Base Coin 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 Coin on Base Coin](https://ide.bitquery.io/Latest-Coin-on-Base-Coin_3) ### Blocks & Validators #### Aggregate Self Destruct Statistics base Calculate total ETH destroyed or received from self-destructs using aggregation functions. ▶️ [Aggregate Self Destruct Statistics base](https://ide.bitquery.io/Aggregate-Self-Destruct-Statistics-base) #### Self Destruct Balance Decrease API base Monitor contract balance decrease when contracts are self-destructing. ▶️ [Self Destruct Balance Decrease API base](https://ide.bitquery.io/Self-Destruct-Balance-Decrease-API-base) #### Self Destruct Balance Increase API base Monitor contract balance increase when contracts are self-destructing. ▶️ [Self Destruct Balance Increase API base](https://ide.bitquery.io/Self-Destruct-Balance-Increase-API-base) ### Uniswap #### Uniswap Trades Stream This subscription returns the real-time trades happening on Uniswap. You can modify the stream to get real-time trades for a particular token, a particular token pair and even a particular trader. ▶️ [Uniswap Trades Stream](https://ide.bitquery.io/Realtime-Uniswap-v1-Uniswap-v2-Uniswap-V3-Trades_1) #### Get metadata for base uniswap token Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. ▶️ [Get metadata for base uniswap token](https://ide.bitquery.io/get-metadata-for-base-uniswap-token) #### Latest slippage of a pool on Uniswap v3 Latest slippage of a pool on Uniswap v3. Change the token address in the `where` clause to use it. ▶️ [Latest slippage of a pool on Uniswap v3](https://ide.bitquery.io/Latest-slippage-of-a-pool-on-Uniswap-v3) #### OHLC on BASE Uniswap v3 Retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on Uniswap v3 over a defined time period and interval. ▶️ [OHLC on BASE Uniswap v3](https://ide.bitquery.io/OHLC-on-BASE-Uniswap-v3) #### Top bought tokens on uniswap v3 Will fetch the top bought tokens on uniswap v3. ▶️ [Top bought tokens on uniswap v3](https://ide.bitquery.io/top-bought-tokens-on-uniswap-v3) #### Top sold tokens on uniswap v3 Will fetch the top bought tokens on uniswap v3. ▶️ [Top sold tokens on uniswap v3](https://ide.bitquery.io/top-sold-tokens-on-uniswap-v3) #### Top traders of a token on uniswapv3 Will fetch top traders of a token for the selected network. ▶️ [Top traders of a token on uniswapv3](https://ide.bitquery.io/top-traders-of-a-token-on-uniswapv3_4) #### Trade volume base uniswapv3 Fetches the traded volume, buy volume and sell volume of a token `0x22af33fe49fd1fa80c7149773dde5890d3c76f3b`. ▶️ [Trade volume base uniswapv3](https://ide.bitquery.io/trade_volume_base_uniswapv3) #### Uniswap v3 trades Below query will subscribe you to the latest DEX Trades on Uniswap v3. ▶️ [Uniswap v3 trades](https://ide.bitquery.io/uniswap-v3-trades_2) #### Virtual pool addresses for a token on uniswap v4 base Virtual pool addresses for a token on uniswap v4 base. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Virtual pool addresses for a token on uniswap v4 base](https://ide.bitquery.io/virtual-pool-addresses-for-a-token-on-uniswap-v4-base) ### PancakeSwap #### Get Latest Price of a token on PancakeSwap Infinity Below query will get you Latest Price of a token on PancakeSwap Infinity. ▶️ [Get Latest Price of a token on PancakeSwap Infinity](https://ide.bitquery.io/Get-Latest-Price-of-a-token-on-PancakeSwap-Infinity) #### Pancakeswap infinity trades Below query will subscribe you to the latest DEX Trades on PancakeSwap Infinity. ▶️ [Pancakeswap infinity trades](https://ide.bitquery.io/pancakeswap-infinity-trades) #### Top bought tokens on pancakeswap_infinity Will fetch the top bought tokens on PancakeSwap Infinity. ▶️ [Top bought tokens on pancakeswap_infinity](https://ide.bitquery.io/top-bought-tokens-on-pancakeswap_infinity) #### Top sold tokens on pancake infinty Will fetch the top bought tokens on PancakeSwap Infinity. ▶️ [Top sold tokens on pancake infinty](https://ide.bitquery.io/top-sold-tokens-on-pancake-infinty) #### Get metadata for base pancakeswap infnity token Use the below query to get Token's metadata like `Name`, `symbol`, `SmartContract Address`, `Decimals`. ▶️ [Get metadata for base pancakeswap infnity token](https://ide.bitquery.io/get-metadata-for-base-pancakeswap-infnity-token) #### OHLC on BASE pancakeswap infinity Retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on PancakeSwap Infinity over a defined time period and interval. ▶️ [OHLC on BASE pancakeswap infinity](https://ide.bitquery.io/OHLC-on-BASE-pancakeswap-infinity) #### Top traders of a token on pancakeswap Will fetch top traders of a token on PancakeSwap Infinity for the selected network. ▶️ [Top traders of a token on pancakeswap](https://ide.bitquery.io/top-traders-of-a-token-on-pancakeswap) #### Trade volume base pancakeswap infinity Fetches the traded volume, buy volume and sell volume of a token `0x22af33fe49fd1fa80c7149773dde5890d3c76f3b` on PancakeSwap Infinity. ▶️ [Trade volume base pancakeswap infinity](https://ide.bitquery.io/trade_volume_base_pancakeswap_infinity) ### Aerodrome #### Latest Aerodrome Finance: CL100-WETH/VVV Pool Gauge claimRewards Transactions 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. ▶️ [Latest Aerodrome Finance: CL100-WETH/VVV Pool Gauge claimRewards Transactions](https://ide.bitquery.io/latest-Aerodrome-Finance-CL100-WETHVVV-Pool-Gauge-claimRewards-Transactions) #### Latest Aerodrome Finance: CL100-WETH/VVV Pool Gauge deposits 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. ▶️ [Latest Aerodrome Finance: CL100-WETH/VVV Pool Gauge deposits](https://ide.bitquery.io/latest-Aerodrome-Finance-CL100-WETHVVV-Pool-Gauge-deposits) #### Latest Aerodrome Finance: CL100-WETH/VVV Pool Gauge withdraw transactions 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. ▶️ [Latest Aerodrome Finance: CL100-WETH/VVV Pool Gauge withdraw transactions](https://ide.bitquery.io/latest-Aerodrome-Finance-CL100-WETHVVV-Pool-Gauge-withdraw-transactions_1) ## Arbitrum ### Trades #### Swap Events Arbitrum Returns the 10 most recent `swap` events on the Arbitrum network. We get this by using the signature hash `c42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67` for the swap event. ▶️ [Swap Events Arbitrum](https://ide.bitquery.io/Swap-Events-Arbitrum) #### Pair last trades 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Pair last trades](https://ide.bitquery.io/Pair-last-trades_2) #### Top Sold Tokens on Arbitrum Top Sold Tokens on Arbitrum. Uses the `DEXTradeByTokens` cube. Adjust the date range in the `where` clause. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top Sold Tokens on Arbitrum](https://ide.bitquery.io/Top-Sold-Tokens-on-Arbitrum) #### Top bought tokens on Arbitrum Top bought tokens on Arbitrum. Uses the `DEXTradeByTokens` cube. Adjust the date range in the `where` clause. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top bought tokens on Arbitrum](https://ide.bitquery.io/top-bought-tokens-on-Arbitrum) #### Top traders for a token on Arbitrum Top traders for a token on Arbitrum. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top traders for a token on Arbitrum](https://ide.bitquery.io/top-traders-for-a-token-on-Arbitrum_3) #### Trending token pairs on Arbitrum Crypto Trades API: one row per swap, with USD and supply. Filter `Pair.Market.Network: Arbitrum`. When to use this vs chain DEX APIs. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Trending token pairs on Arbitrum](https://ide.bitquery.io/trending-token-pairs-on-Arbitrum) ### Balances & Holders #### Current balance of an address Every token balance held by one Arbitrum address. Balances are cumulative, so this reads the whole history — replace the address to use it. ▶️ [Current balance of an address](https://ide.bitquery.io/Arbitrum-Current-balance-of-an-address) #### Arbitrum Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. ▶️ [Arbitrum Balance of an Address](https://ide.bitquery.io/Arbitrum-Balance-of-an-Address) #### Arbitrum balances by date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. ▶️ [Arbitrum balances by date](https://ide.bitquery.io/arbitrum-balances-by-date) #### Arbitrum balances history 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. ▶️ [Arbitrum balances history](https://ide.bitquery.io/arbitrum-balances-history) #### Arbitrum balances 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. ▶️ [Arbitrum balances specific token](https://ide.bitquery.io/arbitrum-balances-specific-token) #### Arbitrum native balances address 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. ▶️ [Arbitrum native balances address](https://ide.bitquery.io/arbitrum-native-balances-address) #### Token holder snapshot arbitrum 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. ▶️ [Token holder snapshot arbitrum](https://ide.bitquery.io/token-holder-snapshot-arbitrum) ### Price & OHLC #### Token price from top market (rank 1) Prices WETH from its single top market rather than blending every pool — the recommended way to price one specific token. Replace `token` in the Variables pane, lowercase. ▶️ [Token price from top market (rank 1)](https://ide.bitquery.io/Arbitrum-Token-price-from-top-market-rank-1) #### Ohlc for a pair on Arbitrum — historical (beyond 30 days) Ohlc for a pair on Arbitrum. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Ohlc for a pair on Arbitrum — historical (beyond 30 days)](https://ide.bitquery.io/ohlc-for-a-pair-on-Arbitrum_1) #### Price change 5min, 1hr, 6hr, 24hr precentage of a specific token — historical (beyond 30 days) Price change 5min, 1hr, 6hr, 24hr precentage of a specific token. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Price change 5min, 1hr, 6hr, 24hr precentage of a specific token — historical (beyond 30 days)](https://ide.bitquery.io/Price-change-5min-1hr-6hr-24hr-precentage-of-a-specific-token_1) #### Top 10 arb tokens by price change in last 1 hr — historical (beyond 30 days) Top 10 arb tokens by price change in last 1 hr. Uses the `DEXTradeByTokens` cube. Needs the historical data add-on — see the comment at the top of the query. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top 10 arb tokens by price change in last 1 hr — historical (beyond 30 days)](https://ide.bitquery.io/Top-10-arb-tokens-by-price-change-in-last-1-hr) ### Supply & Market Cap #### Top Tokens by Market Cap on Arbitrum 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. ▶️ [Top Tokens by Market Cap on Arbitrum](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Arbitrum) ### Liquidity & Pools #### Latest liquidity changes of a specific pool Retrieves the latest liquidity events for a specific DEX pool on Arbitrum. Use this to check current pool reserves, spot prices, and recent liquidity changes for a particular token pair. ▶️ [Latest liquidity changes of a specific pool](https://ide.bitquery.io/latest-liquidity-changes-of-a-specific-pool) ### Transactions #### Latest Transactions Retrieves the latest 10 transactions on the Arbitrum network. ▶️ [Latest Transactions](https://ide.bitquery.io/Latest-Transactions_3) #### Transaction Call Trace Arbitrum 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. ▶️ [Transaction Call Trace Arbitrum](https://ide.bitquery.io/Transaction-Call-Trace-Arbitrum) ### Events & Calls #### Latest GMX Events 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. ▶️ [Latest GMX Events](https://ide.bitquery.io/latest-GMX-Events) #### Latest vGLP Withdraw Events The following query retrieves the latest vGLP withdrawals on the Arbitrum network. ▶️ [Latest vGLP Withdraw Events](https://ide.bitquery.io/latest-vGLP-Withdraw-Events) #### Latest deposits on Across Bridge 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 Bridge](https://ide.bitquery.io/Latest-deposits-on-Across-Bridge) #### Latest vGLP Deposit Events The following query retrieves the latest vGLP deposits on the Arbitrum network. ▶️ [Latest vGLP Deposit Events](https://ide.bitquery.io/latest-vGLP-Deposit-Events) ### Blocks & Validators #### Latest Arbitrum blocks Retrieves the latest 10 blocks on the Arbitrum network. ▶️ [Latest Arbitrum blocks](https://ide.bitquery.io/Latest-Arbitrum-blocks) ### Uniswap #### Get virtual pool address for a token on uniswap v4 arbitrum Get virtual pool address for a token on uniswap v4 arbitrum. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Get virtual pool address for a token on uniswap v4 arbitrum](https://ide.bitquery.io/get-virtual-pool-address-for-a-token-on-uniswap-v4-arbitrum) #### Latest Trades for a currency pair on arbitrum Latest Trades for a currency pair on arbitrum. Uses the `DEXTrades` cube. ▶️ [Latest Trades for a currency pair on arbitrum](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-arbitrum) #### Top buyers of a currency on uniswap v4 arbitrum Top buyers of a currency on uniswap v4 arbitrum. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top buyers of a currency on uniswap v4 arbitrum](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-arbitrum) #### Top sellers of a token on uniswap v4 arbitrum Top sellers of a token on uniswap v4 arbitrum. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top sellers of a token on uniswap v4 arbitrum](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-arbitrum) #### Trade stats for a token pair on uniswap v4 arbitrum Trade stats for a token pair on uniswap v4 arbitrum. Uses the `DEXTradeByTokens` cube. ▶️ [Trade stats for a token pair on uniswap v4 arbitrum](https://ide.bitquery.io/trade-stats-for-a-token-pair-on-uniswap-v4-arbitrum) ## Optimism ### Trades #### Top tokens on optimism Top tokens on optimism. Uses the `DEXTradeByTokens` cube. Adjust the date range in the `where` clause. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top tokens on optimism](https://ide.bitquery.io/top-tokens-on-optimism) #### Top traders for wld usdc pair You can checkout a completed product using this info on DEXRabbit. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top traders for wld usdc pair](https://ide.bitquery.io/top-traders-for-wld-usdc-pair) #### Top traders on optimism Top traders on optimism. Uses the `DEXTradeByTokens` cube. Adjust the date range in the `where` clause. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top traders on optimism](https://ide.bitquery.io/top-traders-on-optimism) ### Balances & Holders #### Current balance of an address Every token balance held by one Optimism address. Balances are cumulative, so this reads the whole history — replace the address to use it. ▶️ [Current balance of an address](https://ide.bitquery.io/Optimism-Current-balance-of-an-address) #### Optimism Balance of an Address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. ▶️ [Optimism Balance of an Address](https://ide.bitquery.io/Optimism-Balance-of-an-Address) #### Optimism balances by date Use `Block.Date.till` for a point-in-time snapshot. Use `dataset: archive` for historical dates and addresses not recently active. ▶️ [Optimism balances by date](https://ide.bitquery.io/optimism-balances-by-date) #### Optimism balances history address 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. ▶️ [Optimism balances history address](https://ide.bitquery.io/optimism-balances-history-address) #### Optimism balances 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. ▶️ [Optimism balances specific token](https://ide.bitquery.io/optimism-balances-specific-token) #### Optimism native balances address 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. ▶️ [Optimism native balances address](https://ide.bitquery.io/optimism-native-balances-address) #### Token holder snapshot optimism 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. ▶️ [Token holder snapshot optimism](https://ide.bitquery.io/token-holder-snapshot-optimism) ### Uniswap #### Latest Trades for a currency pair on optimism Latest Trades for a currency pair on optimism. Uses the `DEXTrades` cube. ▶️ [Latest Trades for a currency pair on optimism](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-optimism) #### Top buyers of a currency on uniswap v4 optimism Top buyers of a currency on uniswap v4 optimism. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top buyers of a currency on uniswap v4 optimism](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-optimism) #### Top sellers of a token on uniswap v4 pool optimism Top sellers of a token on uniswap v4 pool optimism. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top sellers of a token on uniswap v4 pool optimism](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-pool-optimism) #### Trade stats for a token pair on uniswap v4 optimism Trade stats for a token pair on uniswap v4 optimism. Uses the `DEXTradeByTokens` cube. ▶️ [Trade stats for a token pair on uniswap v4 optimism](https://ide.bitquery.io/trade-stats-for-a-token-pair-on-uniswap-v4-optimism) ### Price & OHLC #### Token price from top market (rank 1) Prices WETH from its single top market rather than blending every pool — the recommended way to price one specific token. Replace `token` in the Variables pane, lowercase. ▶️ [Token price from top market (rank 1)](https://ide.bitquery.io/Optimism-Token-price-from-top-market-rank-1) ## Polygon ### Trades #### Top Traders by PnL of a specific polygon pool 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. Trading cube — real-time and roughly the last 30 days. For anything older, use the DEXTradeByTokens entries at the bottom of this section. ▶️ [Top Traders by PnL of a specific polygon pool](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-polygon-pool) #### Top traders of a token on matic — historical (beyond 30 days) 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top traders of a token on matic — historical (beyond 30 days)](https://ide.bitquery.io/top-traders-of-a-token-on-matic_1) ### Transfers #### Check if an address interacted with polymarket ever This is cheaper than scanning all `PredictionTrades` when you only need a yes/no signal. Narrow the pattern (e.g. also filter by counterparties) if you need stronger guarantees. ▶️ [Check if an address interacted with polymarket ever](https://ide.bitquery.io/check-if-an-address-interacted-with-polymarket-ever) ### Balances & Holders #### Current balance of an address Every token balance held by one Polygon address. Balances are cumulative, so this reads the whole history — replace the address to use it. ▶️ [Current balance of an address](https://ide.bitquery.io/Polygon-Current-balance-of-an-address) #### Balance of an address Returns all token balances for a wallet on Polygon using `EVM.Balances` with `network: matic` and `dataset: combined`. See [Polygon Address Balance API](/docs/blockchain/Matic/matic-balance-api/#balance-of-an-address). ▶️ [Balance of an address](https://ide.bitquery.io/matic-balances-address_1) #### Matic historical balances address Returns all token balances for a wallet on Polygon using `EVM.Balances` with `network: matic` and `dataset: combined` until a particular period. For this example we will find the Balnce of the address one month ago. ▶️ [Matic historical balances address](https://ide.bitquery.io/matic-historical-balances-address_1) #### Matic balances address Returns token balances for a wallet address. Use `Amount(selectWhere: { gt: "0" })` to exclude zero balances. ▶️ [Matic balances address](https://ide.bitquery.io/matic-balances-address) #### Matic balances history 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. ▶️ [Matic balances history](https://ide.bitquery.io/matic-balances-history) #### Matic balances 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. ▶️ [Matic balances specific token](https://ide.bitquery.io/matic-balances-specific-token) #### Matic native balances address Returns the native MATIC balance for a wallet (not ERC-20 tokens). Filter with `Currency: { Native: true }` instead of a token contract address. ▶️ [Matic native balances address](https://ide.bitquery.io/matic-native-balances-address) #### Matic wallet balance token at 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`. ▶️ [Matic wallet balance token at date](https://ide.bitquery.io/matic-wallet-balance-token-at-date) #### Token holder snapshot matic 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. ▶️ [Token holder snapshot matic](https://ide.bitquery.io/token-holder-snapshot-matic) ### Supply & Market Cap #### Top Tokens by Market Cap on Polygon 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. ▶️ [Top Tokens by Market Cap on Polygon](https://ide.bitquery.io/Top-Tokens-by-Market-Cap-on-Polygon_1) ### Liquidity & Pools #### Latest Liquidity Changes of a Specific Pool 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. ▶️ [Latest Liquidity Changes of a Specific Pool](https://ide.bitquery.io/Latest-Liquidity-Changes-of-a-Specific-Pool_6) ### Uniswap #### Get virtual pool address for a token on uniswap v4 matic Get virtual pool address for a token on uniswap v4 matic. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Get virtual pool address for a token on uniswap v4 matic](https://ide.bitquery.io/get-virtual-pool-address-for-a-token-on-uniswap-v4-matic) #### OHLCV on MATIC uniswap v3 Retrieves the Open, High, Low, and Close (OHLC) prices in USD for a specific token traded on Uniswap v3 over a defined time period and interval. ▶️ [OHLCV on MATIC uniswap v3](https://ide.bitquery.io/OHLCV-on-MATIC-uniswap-v3) #### Top bought tokens on matic uniswap v3 Will fetch the top bought tokens on uniswap v3. ▶️ [Top bought tokens on matic uniswap v3](https://ide.bitquery.io/top-bought-tokens-on-matic-uniswap-v3_4) #### Top sold tokens on matic uniswap v3 Will fetch the top bought tokens on uniswap v3. ▶️ [Top sold tokens on matic uniswap v3](https://ide.bitquery.io/top-sold-tokens-on-matic-uniswap-v3) #### Top traders of a token on uniswapv3 matic Will fetch top traders of a token for the selected network. ▶️ [Top traders of a token on uniswapv3 matic](https://ide.bitquery.io/top-traders-of-a-token-on-uniswapv3-matic) #### Trade volume matic uniswapv3 Fetches the traded volume, buy volume and sell volume of a token `0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270`. ▶️ [Trade volume matic uniswapv3](https://ide.bitquery.io/trade_volume_matic_uniswapv3) #### Uniswap v3 trades matic Below query will subscribe you to the latest DEX Trades on MATIC Uniswap v3. ▶️ [Uniswap v3 trades matic](https://ide.bitquery.io/uniswap-v3-trades-matic) #### Latest Trades for a currency pair on matic Latest Trades for a currency pair on matic. Uses the `DEXTrades` cube. ▶️ [Latest Trades for a currency pair on matic](https://ide.bitquery.io/Latest-Trades-for-a-currency-pair-on-matic_1) #### Top buyers of a currency on uniswap v4 matic Top buyers of a currency on uniswap v4 matic. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top buyers of a currency on uniswap v4 matic](https://ide.bitquery.io/top-buyers-of-a-currency-on-uniswap-v4-matic) #### Top sellers of a token on uniswap v4 pool matic Top sellers of a token on uniswap v4 pool matic. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. ▶️ [Top sellers of a token on uniswap v4 pool matic](https://ide.bitquery.io/top-sellers-of-a-token-on-uniswap-v4-pool-matic) ## Avalanche ### Trades #### Latest DEX trades The most recent DEX trades on Avalanche, with both sides of the pair, the venue and USD value. Add a `baseCurrency` filter to scope it to one token. ▶️ [Latest DEX trades](https://ide.bitquery.io/Avalanche-Latest-DEX-trades) #### Top DEXs by trade count Ranks the DEXs on Avalanche by number of trades, so you can see which venues actually carry volume. ▶️ [Top DEXs by trade count](https://ide.bitquery.io/Avalanche-Top-DEXs-by-trade-count) ### Transfers #### Latest token transfers Recent token transfers on Avalanche. Add a `currency` filter to follow one token, or a sender/receiver filter to follow one wallet. ▶️ [Latest token transfers](https://ide.bitquery.io/Avalanche-Latest-token-transfers) ### Balances & Holders #### Balance of an address at a past date What one Avalanche address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Avalanche-Balance-of-an-address-at-a-past-date) #### Balances of an address Native and token balances held by one Avalanche address. Replace the address to use it. ▶️ [Balances of an address](https://ide.bitquery.io/Avalanche-Balances-of-an-address) ### Transactions #### Latest transactions Recent Avalanche transactions with value, gas and sender/receiver. Move `since` in the Variables pane to change the window — a wide window on a busy chain will exceed the query memory limit. ▶️ [Latest transactions](https://ide.bitquery.io/Avalanche-Latest-transactions) ### Events & Calls #### Latest smart contract events Decoded event logs on Avalanche. Filter by `smartContractAddress` to watch a single contract. ▶️ [Latest smart contract events](https://ide.bitquery.io/Avalanche-Latest-smart-contract-events) ### Blocks & Validators #### Latest blocks The most recent blocks on Avalanche, with height, time, gas used and transaction count. ▶️ [Latest blocks](https://ide.bitquery.io/Avalanche-Latest-blocks_1) ## Celo ### Transfers #### Latest token transfers Recent token transfers on Celo. Add a `currency` filter to follow one token, or a sender/receiver filter to follow one wallet. ▶️ [Latest token transfers](https://ide.bitquery.io/Celo-Latest-token-transfers) ### Balances & Holders #### Balance of an address at a past date What one Celo address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Celo-Balance-of-an-address-at-a-past-date) #### Balances of an address Native and token balances held by one Celo address. Replace the address to use it. ▶️ [Balances of an address](https://ide.bitquery.io/Celo-Balances-of-an-address) ### Transactions #### Latest transactions Recent Celo transactions with value, gas and sender/receiver. Move `since` in the Variables pane to change the window — a wide window on a busy chain will exceed the query memory limit. ▶️ [Latest transactions](https://ide.bitquery.io/Celo-Latest-transactions) ### Events & Calls #### Latest smart contract events Decoded event logs on Celo. Filter by `smartContractAddress` to watch a single contract. ▶️ [Latest smart contract events](https://ide.bitquery.io/Celo-Latest-smart-contract-events) ### Blocks & Validators #### Latest blocks The most recent blocks on Celo, with height, time, gas used and transaction count. ▶️ [Latest blocks](https://ide.bitquery.io/Celo-Latest-blocks) ## Cronos ### Transfers #### Latest token transfers Recent token transfers on Cronos. Add a `currency` filter to follow one token, or a sender/receiver filter to follow one wallet. ▶️ [Latest token transfers](https://ide.bitquery.io/Cronos-Latest-token-transfers) ### Balances & Holders #### Balance of an address at a past date What one Cronos address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Cronos-Balance-of-an-address-at-a-past-date) #### Balances of an address Native and token balances held by one Cronos address. Replace the address to use it. ▶️ [Balances of an address](https://ide.bitquery.io/Cronos-Balances-of-an-address) ### Transactions #### Latest transactions Recent Cronos transactions with value, gas and sender/receiver. Move `since` in the Variables pane to change the window — a wide window on a busy chain will exceed the query memory limit. ▶️ [Latest transactions](https://ide.bitquery.io/Cronos-Latest-transactions) ### Events & Calls #### Latest smart contract events Decoded event logs on Cronos. Filter by `smartContractAddress` to watch a single contract. ▶️ [Latest smart contract events](https://ide.bitquery.io/Cronos-Latest-smart-contract-events) ### Blocks & Validators #### Latest blocks The most recent Cronos blocks, with gas used and transaction count. Move `since` in the Variables pane. ▶️ [Latest blocks](https://ide.bitquery.io/Cronos-Latest-blocks) ## Klaytn ### Trades #### Latest DEX trades The most recent DEX trades on Klaytn, with both sides of the pair, the venue and USD value. Add a `baseCurrency` filter to scope it to one token. ▶️ [Latest DEX trades](https://ide.bitquery.io/Klaytn-Latest-DEX-trades) #### Top DEXs by trade count Ranks the DEXs on Klaytn by number of trades, so you can see which venues actually carry volume. ▶️ [Top DEXs by trade count](https://ide.bitquery.io/Klaytn-Top-DEXs-by-trade-count) ### Transfers #### Latest token transfers Recent token transfers on Klaytn. Add a `currency` filter to follow one token, or a sender/receiver filter to follow one wallet. ▶️ [Latest token transfers](https://ide.bitquery.io/Klaytn-Latest-token-transfers) ### Balances & Holders #### Balance of an address at a past date What one Klaytn address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Klaytn-Balance-of-an-address-at-a-past-date) #### Balances of an address Native and token balances held by one Klaytn address. Replace the address to use it. ▶️ [Balances of an address](https://ide.bitquery.io/Klaytn-Balances-of-an-address) ### Transactions #### Latest transactions Recent Klaytn transactions with value, gas and sender/receiver. Move `since` in the Variables pane to change the window — a wide window on a busy chain will exceed the query memory limit. ▶️ [Latest transactions](https://ide.bitquery.io/Klaytn-Latest-transactions) ### Events & Calls #### Latest smart contract events Decoded event logs on Klaytn. Filter by `smartContractAddress` to watch a single contract. ▶️ [Latest smart contract events](https://ide.bitquery.io/Klaytn-Latest-smart-contract-events) ### Blocks & Validators #### Latest blocks The most recent blocks on Klaytn, with height, time, gas used and transaction count. ▶️ [Latest blocks](https://ide.bitquery.io/Klaytn-Latest-blocks) ## Litecoin ### Transfers #### Largest transfers in the last 24 hours The biggest Litecoin outputs of the past day, ranked by value — a quick way to spot whale movement. Change the `since` date to widen the window. ▶️ [Largest transfers in the last 24 hours](https://ide.bitquery.io/Litecoin-Largest-transfers-in-the-last-24-hours) ### Balances & Holders #### Balance of an address at a past date What one Litecoin address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Litecoin-Balance-of-an-address-at-a-past-date) #### Total received by an address Sums everything an address has ever received on Litecoin, with a first-and-last-seen window. Replace the address to use it. ▶️ [Total received by an address](https://ide.bitquery.io/Litecoin-Total-received-by-an-address) #### Total sent from an address Sums everything an address has ever spent on Litecoin. Subtract this from total received to get the current balance. ▶️ [Total sent from an address](https://ide.bitquery.io/Litecoin-Total-sent-from-an-address) #### Address activity summary First seen, last seen, and lifetime in/out totals for one Litecoin address in a single request. ▶️ [Address activity summary](https://ide.bitquery.io/Litecoin-Address-activity-summary) ### Transactions #### Latest transactions The most recent transactions on Litecoin, with value, fee and input/output counts. Raise the limit to page further back. ▶️ [Latest transactions](https://ide.bitquery.io/Litecoin-Latest-transactions) ### Blocks & Validators #### Latest blocks The most recent blocks on Litecoin, with height, time, transaction count and size. ▶️ [Latest blocks](https://ide.bitquery.io/Litecoin-Latest-blocks) ## Bitcoin Cash ### Transfers #### Largest transfers in the last 24 hours The biggest Bitcoin Cash outputs of the past day, ranked by value — a quick way to spot whale movement. Change the `since` date to widen the window. ▶️ [Largest transfers in the last 24 hours](https://ide.bitquery.io/Bitcoin-Cash-Largest-transfers-in-the-last-24-hours) ### Balances & Holders #### Balance of an address at a past date What one Bitcoin Cash address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Bitcoin-Cash-Balance-of-an-address-at-a-past-date) #### Total received by an address Sums everything an address has ever received on Bitcoin Cash, with a first-and-last-seen window. Replace the address to use it. ▶️ [Total received by an address](https://ide.bitquery.io/Bitcoin-Cash-Total-received-by-an-address) #### Total sent from an address Sums everything an address has ever spent on Bitcoin Cash. Subtract this from total received to get the current balance. ▶️ [Total sent from an address](https://ide.bitquery.io/Bitcoin-Cash-Total-sent-from-an-address) #### Address activity summary First seen, last seen, and lifetime in/out totals for one Bitcoin Cash address in a single request. ▶️ [Address activity summary](https://ide.bitquery.io/Bitcoin-Cash-Address-activity-summary) ### Transactions #### Latest transactions The most recent transactions on Bitcoin Cash, with value, fee and input/output counts. Raise the limit to page further back. ▶️ [Latest transactions](https://ide.bitquery.io/Bitcoin-Cash-Latest-transactions) ### Blocks & Validators #### Latest blocks The most recent blocks on Bitcoin Cash, with height, time, transaction count and size. ▶️ [Latest blocks](https://ide.bitquery.io/Bitcoin-Cash-Latest-blocks) ## Dogecoin ### Transfers #### Largest transfers in the last 24 hours The biggest Dogecoin outputs of the past day, ranked by value — a quick way to spot whale movement. Change the `since` date to widen the window. ▶️ [Largest transfers in the last 24 hours](https://ide.bitquery.io/Dogecoin-Largest-transfers-in-the-last-24-hours) ### Balances & Holders #### Balance of an address at a past date What one Dogecoin address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Dogecoin-Balance-of-an-address-at-a-past-date) #### Total received by an address Sums everything an address has ever received on Dogecoin, with a first-and-last-seen window. Replace the address to use it. ▶️ [Total received by an address](https://ide.bitquery.io/Dogecoin-Total-received-by-an-address) #### Total sent from an address Sums everything an address has ever spent on Dogecoin. Subtract this from total received to get the current balance. ▶️ [Total sent from an address](https://ide.bitquery.io/Dogecoin-Total-sent-from-an-address) #### Address activity summary First seen, last seen, and lifetime in/out totals for one Dogecoin address in a single request. ▶️ [Address activity summary](https://ide.bitquery.io/Dogecoin-Address-activity-summary) ### Transactions #### Latest transactions The most recent transactions on Dogecoin, with value, fee and input/output counts. Raise the limit to page further back. ▶️ [Latest transactions](https://ide.bitquery.io/Dogecoin-Latest-transactions) ### Blocks & Validators #### Latest blocks The most recent blocks on Dogecoin, with height, time, transaction count and size. ▶️ [Latest blocks](https://ide.bitquery.io/Dogecoin-Latest-blocks) ## Dash ### Transfers #### Largest transfers in the last 24 hours The biggest Dash outputs of the past day, ranked by value — a quick way to spot whale movement. Change the `since` date to widen the window. ▶️ [Largest transfers in the last 24 hours](https://ide.bitquery.io/Dash-Largest-transfers-in-the-last-24-hours) ### Balances & Holders #### Balance of an address at a past date What one Dash address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Dash-Balance-of-an-address-at-a-past-date) #### Total received by an address Sums everything an address has ever received on Dash, with a first-and-last-seen window. Replace the address to use it. ▶️ [Total received by an address](https://ide.bitquery.io/Dash-Total-received-by-an-address) #### Total sent from an address Sums everything an address has ever spent on Dash. Subtract this from total received to get the current balance. ▶️ [Total sent from an address](https://ide.bitquery.io/Dash-Total-sent-from-an-address) #### Address activity summary First seen, last seen, and lifetime in/out totals for one Dash address in a single request. ▶️ [Address activity summary](https://ide.bitquery.io/Dash-Address-activity-summary) ### Transactions #### Latest transactions The most recent transactions on Dash, with value, fee and input/output counts. Raise the limit to page further back. ▶️ [Latest transactions](https://ide.bitquery.io/Dash-Latest-transactions) ### Blocks & Validators #### Latest blocks The most recent blocks on Dash, with height, time, transaction count and size. ▶️ [Latest blocks](https://ide.bitquery.io/Dash-Latest-blocks) ## Zcash ### Transfers #### Largest transfers in the last 24 hours The biggest Zcash outputs of the past day, ranked by value — a quick way to spot whale movement. Change the `since` date to widen the window. ▶️ [Largest transfers in the last 24 hours](https://ide.bitquery.io/Zcash-Largest-transfers-in-the-last-24-hours) ### Balances & Holders #### Balance of an address at a past date What one Zcash address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Zcash-Balance-of-an-address-at-a-past-date) #### Total received by an address Sums everything an address has ever received on Zcash, with a first-and-last-seen window. Replace the address to use it. ▶️ [Total received by an address](https://ide.bitquery.io/Zcash-Total-received-by-an-address) #### Total sent from an address Sums everything an address has ever spent on Zcash. Subtract this from total received to get the current balance. ▶️ [Total sent from an address](https://ide.bitquery.io/Zcash-Total-sent-from-an-address) #### Address activity summary First seen, last seen, and lifetime in/out totals for one Zcash address in a single request. ▶️ [Address activity summary](https://ide.bitquery.io/Zcash-Address-activity-summary) ### Transactions #### Latest transactions The most recent transactions on Zcash, with value, fee and input/output counts. Raise the limit to page further back. ▶️ [Latest transactions](https://ide.bitquery.io/Zcash-Latest-transactions) ### Blocks & Validators #### Latest blocks The most recent blocks on Zcash, with height, time, transaction count and size. ▶️ [Latest blocks](https://ide.bitquery.io/Zcash-Latest-blocks) ## Cardano ### Trades #### Cardano Price This query returns the latest price of Cardano on Cardano Network. ▶️ [Cardano Price](https://ide.bitquery.io/latest-cardano-price) ### Transfers #### Cardano User Transfers This query returns the latest transfers for a useron Cardano network. ▶️ [Cardano User Transfers](https://ide.bitquery.io/cardano-transfers-of-a-wallet) ### Balances & Holders #### Cardano Balance This query returns the current balance of a user on Cardano network. ▶️ [Cardano Balance](https://ide.bitquery.io/cardano-address-balance_1) ## Ripple ### Trades #### Ripple Token DEX Trades This query returns the latest trades of a currency on the Ripple network. ▶️ [Ripple Token DEX Trades](https://ide.bitquery.io/trades-for-CNY-on-ripple) #### Ripple Payments This query returns the latest payments on Ripple network. ▶️ [Ripple Payments](https://ide.bitquery.io/Latest-payments-on-ripple-blockchain) ### Transfers #### Ripple Historical Transfers This query returns all the historical transfers done by a specific address on the Ripple network. ▶️ [Ripple Historical Transfers](https://ide.bitquery.io/All-historical-transfers-of-an-individual-address) ### Balances & Holders #### Ripple Historical Balance This query returns all historical balance of an address on Ripple network. ▶️ [Ripple Historical Balance](https://ide.bitquery.io/historical-balances-of-a-ripple-address) ### Transactions #### Transaction Details using Hash This query uses transaction hash and date range as filter to fetch tx details. ▶️ [Transaction Details using Hash](https://ide.bitquery.io/xrpl-search-tx-details) ## Stellar ### Trades #### Latest DEX trades Trades on the Stellar decentralised exchange, with both sides of the pair and the amounts. ▶️ [Latest DEX trades](https://ide.bitquery.io/Stellar-Latest-DEX-trades) ### Transfers #### Latest payments Stellar payment operations — who paid whom, in which asset, and how much. ▶️ [Latest payments](https://ide.bitquery.io/Stellar-Latest-payments) ### Balances & Holders #### Balance of an address at a past date What one Stellar address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Stellar-Balance-of-an-address-at-a-past-date) #### Balances of an address Every asset balance held by one Stellar account. Replace the address to use it. ▶️ [Balances of an address](https://ide.bitquery.io/Stellar-Balances-of-an-address) ### Liquidity & Pools #### Liquidity pool trades Swaps routed through Stellar liquidity pools, with the pool id and both legs. ▶️ [Liquidity pool trades](https://ide.bitquery.io/Stellar-Liquidity-pool-trades) ### Transactions #### Latest transactions Recent Stellar transactions with sender, fee and success flag. Move `since` in the Variables pane to change the window. ▶️ [Latest transactions](https://ide.bitquery.io/Stellar-Latest-transactions) ### Blocks & Validators #### Latest ledgers The most recent Stellar ledgers with close time, transaction count and fee pool. ▶️ [Latest ledgers](https://ide.bitquery.io/Stellar-Latest-ledgers) ## Algorand ### Transfers #### All the transfers of an asset on Algorand Mainnet in a specific timeframe Returns transfers for asset ID `31566704` between two dates, ordered by block height descending. Swap the `currency` filter for any ASA ID or ALGO. ▶️ [All the transfers of an asset on Algorand Mainnet in a specific timeframe](https://ide.bitquery.io/All-the-transfers-of-an-asset-on-Algorand-Mainnet-in-a-specific-timeframe) #### Traansfers where a currency is sent from or sent to a particular address Uses the `any` filter to match transfers where the address appears as either sender or receiver. ▶️ [Traansfers where a currency is sent from or sent to a particular address](https://ide.bitquery.io/traansfers-where-a-currency-is-sent-from-or-sent-to-a-particular-address) ### Price & OHLC #### Get Count of Smart Contract Calls in Latest Block Returns the count of unique smart contract calls in the most recent block after a given date. ▶️ [Get Count of Smart Contract Calls in Latest Block](https://ide.bitquery.io/Get-Count-of-Smart-Contract-Calls-in-Latest-Block_1) ### Transactions #### All Transactions on Algorand Paginated query for all transactions in a specific window. ▶️ [All Transactions on Algorand](https://ide.bitquery.io/All-Transactions-on-Algorand) #### Daily Transaction Count for last 10 days Returns the number of transactions per day over the last 10 days, ordered by date descending. ▶️ [Daily Transaction Count for last 10 days](https://ide.bitquery.io/Daily-Transaction-Count-for-last-10-days) #### Daily Unique Txn Senders on algorand Counts distinct transaction senders on a specific date. ▶️ [Daily Unique Txn Senders on algorand](https://ide.bitquery.io/Daily-Unique-Txn-Senders-on-algorand) ## Filecoin ### Transfers #### Latest transfers FIL value moving between addresses. Add a sender or receiver filter to follow one account. ▶️ [Latest transfers](https://ide.bitquery.io/Filecoin-Latest-transfers) ### Balances & Holders #### Balance of an address at a past date What one Filecoin address held as of a chosen date. Move the date in the Variables pane. ▶️ [Balance of an address at a past date](https://ide.bitquery.io/Filecoin-Balance-of-an-address-at-a-past-date) #### Balance of an address The FIL balance held by one Filecoin address. Replace the address to use it. ▶️ [Balance of an address](https://ide.bitquery.io/Filecoin-Balance-of-an-address) ### Transactions #### Latest messages Filecoin messages — the chain's transactions — with sender, receiver, value and method. ▶️ [Latest messages](https://ide.bitquery.io/Filecoin-Latest-messages) ### Blocks & Validators #### Latest tipsets The most recent Filecoin tipsets with height and time. ▶️ [Latest tipsets](https://ide.bitquery.io/Filecoin-Latest-tipsets) ## Trading API ### Trades #### Average fee per trade, Total fees, total volume, trades count per DEX program Average fee per trade, Total fees, total volume, trades count per DEX program. Uses the `Trades` cube. ▶️ [Average fee per trade, Total fees, total volume, trades count per DEX program](https://ide.bitquery.io/Average-fee-per-trade-Total-fees-total-volume-trades-count-per-DEX-program) #### Last 10 WSOL USDC Token pair trades Last 10 WSOL USDC Token pair trades. Uses the `Trades` cube. ▶️ [Last 10 WSOL USDC Token pair trades](https://ide.bitquery.io/Last-10-WSOL-USDC-Token-pair-trades) #### Most active market pools by trades Most active market pools by trades. Uses the `Trades` cube. ▶️ [Most active market pools by trades](https://ide.bitquery.io/Most-active-market-pools-by-trades) #### Most active traders by trade count Most active traders by trade count. Uses the `Trades` cube. ▶️ [Most active traders by trade count](https://ide.bitquery.io/Most-active-traders-by-trade-count) #### Most traded token in last 1 hour on solana and it's average trade amount and total volume Most traded token in last 1 hour on solana and it's average trade amount and total volume. Uses the `Trades` cube. ▶️ [Most traded token in last 1 hour on solana and it's average trade amount and total volume](https://ide.bitquery.io/Most-traded-token-in-last-1-hour-on-solana-and-its-average-trade-amount-and-total-volume) #### Net flow (buys - sells) per token symbol Net flow (buys - sells) per token symbol. Uses the `Trades` cube. ▶️ [Net flow (buys - sells) per token symbol](https://ide.bitquery.io/Net-flow-buys---sells-per-token-symbol_2) #### Tokens with highest trade frequency Tokens with highest trade frequency. Uses the `Trades` cube. ▶️ [Tokens with highest trade frequency](https://ide.bitquery.io/Tokens-with-highest-trade-frequency) #### Tokens with most unique buyers Tokens with most unique buyers. Uses the `Trades` cube. ▶️ [Tokens with most unique buyers](https://ide.bitquery.io/Tokens-with-most-unique-buyers) #### Top Traders on Solana Top Traders on Solana. Uses the `Trades` cube. ▶️ [Top Traders on Solana](https://ide.bitquery.io/Top-Traders-on-Solana_2) #### Total SOL fees, Total Volume, Total count trades Total SOL fees, Total Volume, Total count trades. Uses the `Trades` cube. ▶️ [Total SOL fees, Total Volume, Total count trades](https://ide.bitquery.io/Total-SOL-fees-Total-Volume-Total-count-trades) ### Price & OHLC #### Token price from top market (rank 1) The recommended way to price one token: takes the single highest-ranked market for it rather than blending every pool. Prices the token from its single top market rather than blending every pool, which is what you want for one specific token. ▶️ [Token price from top market (rank 1)](https://ide.bitquery.io/Token-price-from-top-market--rank-1_2) #### Multi-token watchlist, top market each Prices a list of tokens, each from its own top market. Add or remove addresses in the `Token.Address.in` filter. ▶️ [Multi-token watchlist, top market each](https://ide.bitquery.io/Multi-token-watchlist--rank-1-per-token) #### Historical Bitcoin OHLC data for the last 7 days Recent Bitcoin OHLC using the Crypto Price API (time range in the query matches what the Price Index supports). ▶️ [Historical Bitcoin OHLC data for the last 7 days](https://ide.bitquery.io/historical-Bitcoin-OHLC-data-for-the-last-7-days) #### OHLC of a currency on multiple blockchains Stream real-time Bitcoin OHLC data aggregated from all supported blockchains (Bitcoin, Ethereum WBTC, Solana, etc.) with 60-second intervals. ▶️ [OHLC of a currency on multiple blockchains](https://ide.bitquery.io/OHLC-of-a-currency-on-multiple-blockchains) ### Supply & Market Cap #### Marketcap of pump token Set token address and read `Supply.MarketCap` from the query below. See the Supply fields reference for related supply fields. You can also stream this in real-time by adding the keyword "subscription" at the top. ▶️ [Marketcap of pump token](https://ide.bitquery.io/marketcap-of-pump-token) #### Tokens ranked by market cap Tokens ranked by market cap. Uses the `Trades` cube. ▶️ [Tokens ranked by market cap](https://ide.bitquery.io/Tokens-ranked-by-market-cap_1) ## Stablecoins ### Trades #### Solana USDT trades query Solana trades quoted in USDT. USDT is the quote side on Solana, so it is filtered with `Pair.QuoteToken`, not `Pair.Token`, which would return nothing. The Trading cube reaches back about 30 days; `Solana.DEXTrades` keeps about 12 hours. ▶️ [Solana USDT trades query](https://ide.bitquery.io/solana-USDT-trades-query) ### Transfers #### Latest Tron USDT Transfers Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest Tron USDT Transfers](https://ide.bitquery.io/Latest-Tron-USDT-Transfers) #### Latest USDT/USDC Transfer api on base Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest USDT/USDC Transfer api on base](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-api-on-base) #### Latest USDT/USDC Transfer api on ethereum Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest USDT/USDC Transfer api on ethereum](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-api-on-ethereum) #### Stablecoin Transfers from/to an address Stablecoin Transfers from/to an address. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. ▶️ [Stablecoin Transfers from/to an address](https://ide.bitquery.io/stablecoin-Transfers-fromto-an-address) #### Stablecoin recieved and sent by an address Stablecoin recieved and sent by an address. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [Stablecoin recieved and sent by an address](https://ide.bitquery.io/Stablecoin-recieved-and-sent-by-an-address) #### USDT Stablecoin reserves on Ethereum USDT Stablecoin reserves on Ethereum. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. Needs the historical data add-on — see the comment at the top of the query. ▶️ [USDT Stablecoin reserves on Ethereum](https://ide.bitquery.io/USDT-Stablecoin-reserves-on-Ethereum) #### USDT and USDC token Transfers api on solana USDT and USDC token Transfers api on solana. Uses the `Transfers` cube. ▶️ [USDT and USDC token Transfers api on solana](https://ide.bitquery.io/USDT-and-USDC-token-Transfers-api-on-solana) #### USDT token Transfers api on solana Track live USDT stablecoin transfers. USDT is ideal for payments, settlements, etc and you can track those in real-time using this API/Stream -. ▶️ [USDT token Transfers api on solana](https://ide.bitquery.io/USDT-token-Transfers-api-on-solana) ### Price & OHLC #### 5 minute price change stablecoin API 5 minute price change stablecoin API. Uses the `Tokens` cube. ▶️ [5 minute price change stablecoin API](https://ide.bitquery.io/5-minute-price-change-stablecoin-API) #### Stablecoin price query of USDT Get real-time and historical USDT prices, OHLCV, and moving averages across supported networks and markets. ▶️ [Stablecoin price query of USDT](https://ide.bitquery.io/stablecoin-price-query-of-USDT_1) #### Usdt latest price arbitrage This query compares USDT prices across different blockchain networks in real-time. It fetches the latest price data for USDT from different networks, showing you where the same stablecoin trades at different prices. ▶️ [Usdt latest price arbitrage](https://ide.bitquery.io/usdt-latest-price-arbitrage) ### Supply & Market Cap #### USDC Stablecoin reserves on Solana USDC Stablecoin reserves on Solana. Uses the `TokenSupplyUpdates` cube. Change the token address in the `where` clause to use it. ▶️ [USDC Stablecoin reserves on Solana](https://ide.bitquery.io/USDC-Stablecoin-reserves-on-Solana) #### USDT Stablecoin reserves on Solana query USDT Stablecoin reserves on Solana query. Uses the `TokenSupplyUpdates` cube. Change the token address in the `where` clause to use it. ▶️ [USDT Stablecoin reserves on Solana query](https://ide.bitquery.io/USDT-Stablecoin-reserves-on-Solana--query) ## NFTs ### Trades #### New Uniswap v3 liquidity positions Position NFTs as they are minted — who is adding liquidity to v3 pools, and to which pair. ▶️ [New Uniswap v3 liquidity positions](https://ide.bitquery.io/recent-uniswap-position-NFTs-mint_1) #### Get NFT trades for a specific NFT contract on specific marketplace Get trades of NFTs for a given contract and marketplace. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get NFT trades for a specific NFT contract on specific marketplace](https://ide.bitquery.io/Get-NFT-trades-by-contract) #### Get NFT trades for a specific NFT contract and token ID Get trades of NFTs for a given contract and token ID. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get NFT trades for a specific NFT contract and token ID](https://ide.bitquery.io/Get-NFT-trades-by-token) #### Get NFT trades by wallet Get trades of NFTs for a given wallet. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Get NFT trades by wallet](https://ide.bitquery.io/Get-trades-of-NFTs-for-a-given-wallet) #### Latest NFT Trades Latest NFT Trades. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latest NFT Trades](https://ide.bitquery.io/Latest-NFT-trades-on-ETH) #### Top Traded NFTs in a Period This query gets the top 10 traded NFTs based on the number of trades within a specified date range. You can change the filters such as the date range and limit. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Top Traded NFTs in a Period](https://ide.bitquery.io/Top-traded-NFT-tokens-in-a-month) #### Latests OpenSea Trades Latests OpenSea Trades. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latests OpenSea Trades](https://ide.bitquery.io/Latests-OpenSea-Trades) #### Latest NFT trades on Ethereum network Latest NFT trades on Ethereum network. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Latest NFT trades on Ethereum network](https://ide.bitquery.io/latest-NFT-trades-on-Ethereum-network) #### Pairs of blur token new dataset Open the above query on GraphQL IDE using this. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [Pairs of blur token new dataset](https://ide.bitquery.io/pairs-of-blur-token-new-dataset_1) #### NFT currencies on Solana by DEX'es 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. Built from raw DEX trades, so it reaches back further than the Trading cube's ~30 days. For live prices prefer the Trading cube entries at the top of this section. ▶️ [NFT currencies on Solana by DEX'es](https://ide.bitquery.io/NFT-currencies-on-Solana-by-DEXes_1) ### Transfers #### Get NFT transfers by wallet Get transfers of NFTs given the wallet. ▶️ [Get NFT transfers by wallet](https://ide.bitquery.io/latest-nft-transfers-by-a-user) #### All transfers of an NFT Retrieves the most recent transfers of a specific non-fungible token (NFT) on the Ethereum network. You can find the GraphQL query. ▶️ [All transfers of an NFT](https://ide.bitquery.io/All-transfers-of-an-NFT) #### NFT Token Transfers By Date NFT Token Transfers By Date. ▶️ [NFT Token Transfers By Date](https://ide.bitquery.io/NFT-Token-Transfers-By-Date) #### Top transfered NFT tokens in network Fetches the most frequently transferred NFTs on the Ethereum Blockchain within the specified date range. ▶️ [Top transfered NFT tokens in network](https://ide.bitquery.io/Top-transfered-NFT-tokens-in-network) #### Array_intersect example for NFT Array_intersect example for NFT. ▶️ [Array_intersect example for NFT](https://ide.bitquery.io/array_intersect-example-for-NFT) #### Get all transfers of a specific nft Will give all the transfers of a particular NFT `0xb68CA010776B4584cf49893E75b66583eb884948`. ▶️ [Get all transfers of a specific nft](https://ide.bitquery.io/get-all-transfers-of-a-specific-nft) ### Balances & Holders #### 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. ▶️ [Get Latest NFT Balance for an Address](https://ide.bitquery.io/Get-Latest-NFT-Balance-for-an-Address) #### 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. ▶️ [Get All NFT Collections for an Address](https://ide.bitquery.io/Get-All-NFT-Collections-for-an-Address_1) #### 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. ▶️ [Get NFT Owner for Specific Token ID](https://ide.bitquery.io/Get-NFT-Owner-for-Specific-Token-ID) #### Get NFT Balances for Multiple Addresses Get NFT balances for multiple addresses in a single query. Useful for portfolio tracking or wallet monitoring applications. ▶️ [Get NFT Balances for Multiple Addresses](https://ide.bitquery.io/Get-NFT-Balances-for-Multiple-Addresses_1) #### 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. ▶️ [Get NFT Ownership History](https://ide.bitquery.io/Get-NFT-Ownership-History_2) ### Price & OHLC #### Smart contract calls to an nft contract Smart contract calls to an nft contract. ▶️ [Smart contract calls to an nft contract](https://ide.bitquery.io/Smart-contract-calls-to-an-nft-contract) ### Events & Calls #### All refinance loans for specific NFT collection To retrieve all refinance loans for a specific NFT collection, we filter Refinance event arguments in. ▶️ [All refinance loans for specific NFT collection](https://ide.bitquery.io/All-refinance-loans-for-specificNFT-collection) #### Auction on blur marketplace The 'StartAuction' event is triggered when an NFT auction starts on the Blur : Blend Contract. The following. ▶️ [Auction on blur marketplace](https://ide.bitquery.io/Auction-on-blur-marketplace) #### Creator_of_an_NFT Creator_of_an_NFT. ▶️ [Creator_of_an_NFT](https://ide.bitquery.io/Creator_of_an_NFT) #### Latest Cancelled offers on Blur NFT marketplace On the BLUR market, the 'OfferCancelled' event initiates when an offer is withdrawn or cancelled. The following. ▶️ [Latest Cancelled offers on Blur NFT marketplace](https://ide.bitquery.io/Latest-Cancelled-offers-on-Blur-NFT-marketplace) #### Latest Loans for a specific borrower on Blur marketplace 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 borrower on Blur marketplace](https://ide.bitquery.io/Latest-Loans-for-a-specificborrower-on-Blur-marketplace) #### Latest Seized NFTs on Blur marketplace When a seizure event happens, control of the NFT shifts to the lender or an enforcing third party. The. ▶️ [Latest Seized NFTs on Blur marketplace](https://ide.bitquery.io/Latest-Seized-NFTs-on-Blur-marketplace) #### Latest loans for specific NFT token Latest loans for specific NFT token. ▶️ [Latest loans for specific NFT token](https://ide.bitquery.io/Latest-loans-for-specific-NFTtoken) #### Loan history for specific NFT ID Loan history for specific NFT ID. ▶️ [Loan history for specific NFT ID](https://ide.bitquery.io/Loan-history-for-specific-NFTID) #### Loan repayment of blur marketplace For loan repayment transactions on the BLUR market, use the. ▶️ [Loan repayment of blur marketplace](https://ide.bitquery.io/Loan-repayment-of-blur-marketplace) #### 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. ▶️ [Loans above a specific amount on the Blur NFT marketplace](https://ide.bitquery.io/Loans-above-a-specific-amount-on-the-Blur-NFT-marketplace) #### Locked NFT bought on Blur marketplace 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. ▶️ [Locked NFT bought on Blur marketplace](https://ide.bitquery.io/Locked-NFT-bought-on-Blur-marketplace) ## Futures DEXs ### Trades #### All events of AsterDEX Monitor all events emitted by the AsterDEX contract to track all platform activities. ▶️ [All events of AsterDEX](https://ide.bitquery.io/All-events-of-AsterDEX) #### AsterDEX - All latest Liquidations When there is a liquidation event on AsterDEX, it emits `ExecuteCloseSuccessful` event with `executionType` 2. ▶️ [AsterDEX - All latest Liquidations](https://ide.bitquery.io/AsterDEX---All-latest-Liquidations) #### AsterDEX - OpenMarketTrade AsterDEX - OpenMarketTrade. Uses the `Events` cube. Replace the address in the `where` clause to use it. ▶️ [AsterDEX - OpenMarketTrade](https://ide.bitquery.io/AsterDEX---OpenMarketTrade) #### Trader's specific event You can look for `Transaction -> From` or in some cases the address might be in arguments, for example. ▶️ [Trader's specific event](https://ide.bitquery.io/Traders-specific-event) #### Traders data - 0x01554d63537d3c62715826a268d4eab645d64b92 You can actually merge these two queries. Here is an example. ▶️ [Traders data - 0x01554d63537d3c62715826a268d4eab645d64b92](https://ide.bitquery.io/Copy-of-Traders-data---0x01554d63537d3c62715826a268d4eab645d64b92) #### Traders data - 0x2b7363708984aa25a90450cfca7bedaf6804115c Using Bitquery's APIs you can follow specific traders on AsterDEX to check all their latest activities. ▶️ [Traders data - 0x2b7363708984aa25a90450cfca7bedaf6804115c](https://ide.bitquery.io/Traders-data---0x2b7363708984aa25a90450cfca7bedaf6804115c) ## x402 ### Trades #### Payment Analytics for x402 Server on Solana Payment Analytics for x402 Server on Solana. Replace the address in the `where` clause to use it. ▶️ [Payment Analytics for x402 Server on Solana](https://ide.bitquery.io/Payment-analytics-related-specific-x402-server-on-Solana) ### Transfers #### Get Latest Payments to x402 Server Get Latest Payments to x402 Server. Uses the `Transfers` cube. ▶️ [Get Latest Payments to x402 Server](https://ide.bitquery.io/Latest-payment-to-specific-x402-server) #### Get Latest Payments to x402 Server on Solana Get Latest Payments to x402 Server on Solana. Uses the `Transfers` cube. Replace the address in the `where` clause to use it. ▶️ [Get Latest Payments to x402 Server on Solana](https://ide.bitquery.io/Latest-Payment-to-specific-x402-server-taking-solana-payments) #### Payment Analytics for x402 Server Comprehensive payment analytics including total volume, unique users, transaction counts, and time-based breakdowns for a specific x402 server. ▶️ [Payment Analytics for x402 Server](https://ide.bitquery.io/Payment-analytics-related-specific-x402-server) --- ## Starter Subscriptions - Bitquery Real-Time Streams by Chain URL: https://docs.bitquery.io/docs/start/starter-subscriptions/ Curated, tested Bitquery GraphQL subscriptions organised by chain and data type — real-time trades, transfers, balances, prices and liquidity streams. # Starter Subscriptions Every subscription below is saved in the [Bitquery IDE](https://ide.bitquery.io) and was opened against the live WebSocket endpoint before publishing. Streams are always real time; for historical data see the [Starter Queries](/docs/start/starter-queries/). ## Table of Contents - [Bitcoin](#bitcoin) - [Solana](#solana) - [Robinhood Chain](#robinhood-chain) - [Polymarket](#polymarket) - [Perpetuals](#perpetuals) - [TRON](#tron) - [Cross-Chain](#cross-chain) - [Ethereum](#ethereum) - [BSC](#bsc) - [Base](#base) - [Arbitrum](#arbitrum) - [Optimism](#optimism) - [Polygon](#polygon) - [Trading API](#trading-api) - [Stablecoins](#stablecoins) - [NFTs](#nfts) - [x402](#x402) ## Bitcoin ### Price & OHLC #### Latest Bitcoin Price You can stream Bitcoin price at 1-second interval using the [Crypto Price APIs](/docs/trading/crypto-price-api/). ▶️ [Latest Bitcoin Price](https://ide.bitquery.io/Stream-Bitcoin-Price-Across-Chains) ## Solana ### Trades #### Graduated Tokens This query gives you tokens which are graduated from Raydium Launchpad to Raydium. ▶️ [Graduated Tokens](https://ide.bitquery.io/Track-Token-Migrations-to-Raydium-DEX-and-Raydium-CPMM-in-realtime) #### Solana Trades Stream This subscription streams real-time Solana trades. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Solana Trades Stream](https://ide.bitquery.io/solana-trades-subscription_3) #### All Trade for Bags.fm tokens Get all trades of Bags FM tokens from Meteora and other DEXs. This Bags FM token trades WebSocket provides comprehensive trading data. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [All Trade for Bags.fm tokens](https://ide.bitquery.io/All-Trade-for-Bagsfm-tokens) #### CPMM trades 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, Raydium v4 docs and Raydium LaunchPad docs too. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [CPMM trades](https://ide.bitquery.io/CPMM-trades) #### Large Token Buys and Sells on Solana DEX Streams Solana trades above $10,000, using the Trading cube's `AmountsInUsd` so the threshold is applied to a real USD value. ▶️ [Large Token Buys and Sells on Solana DEX](https://ide.bitquery.io/big-trades-on-solana) #### Specific Token Trades Stream This subscription stream uses DexTradeByTokens API to stream real-time specific token trades. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Specific Token Trades Stream](https://ide.bitquery.io/token-trades-subscription) #### Get Solana pair trades data Will subscribe to real-time trade transactions for a Solana pair, providing a continuous stream of data as new trades are processed and recorded. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get Solana pair trades data](https://ide.bitquery.io/Get-Solana-pair-trades-data) #### Get Solana pair trades data just like dexcsreener Will subscribe to real-time trade transactions for a Solana pair, providing a continuous stream of data as new trades are processed and recorded. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get Solana pair trades data just like dexcsreener](https://ide.bitquery.io/Get-Solana-pair-trades-data-just-like-dexcsreener) #### Get Solana pair trades data just like geckoTerminal Will subscribe to real-time trade transactions for a Solana pair, providing a continuous stream of data as new trades are processed and recorded. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get Solana pair trades data just like geckoTerminal](https://ide.bitquery.io/Get-Solana-pair-trades-data-just-like-geckoTerminal_1) #### Latest Trades of TESLA onchain xStock Below query will give you realtime trades of Tesla xStock (TESLAx). Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Latest Trades of TESLA onchain xStock](https://ide.bitquery.io/Latest-Trades-of-TESLA-onchain-xStock_1) ### Transfers #### Token Transfers Stream This stream provides all token transfers on the Solana blockchain, including SOL transfers. ▶️ [Token Transfers Stream](https://ide.bitquery.io/Solana-transfers-stream_3) #### SPL transfers websocket One of the most common types of transfers on Solana are SPL token transfers. Let's see an example to get the latest SPL token transfers using our API. Today we are taking an example of JUPITER token transfers. ▶️ [SPL transfers websocket](https://ide.bitquery.io/SPL-transfers-websocket_1) #### Solana Websocket - Subscribe to all transfers of specific addresses in realtime Websockets are priced based on their running time, not the amount of data delivered. ▶️ [Solana Websocket - Subscribe to all transfers of specific addresses in realtime](https://ide.bitquery.io/Solana-Websocket---Subscribe-to-all-transfers-of-specific-addresses-in-realtime) #### Subscribe to the all transfers on Solana For monitoring the balance changes that result from these transfers, see our Solana Balance Updates API. ▶️ [Subscribe to the all transfers on Solana](https://ide.bitquery.io/Subscribe-to-the-all-transfers-on-Solana) #### Transfers of All Tip Payment Accounts on Solana 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… ▶️ [Transfers of All Tip Payment Accounts on Solana](https://ide.bitquery.io/Transfers-of-All-Tip-Payment-Accounts-on-Solana) #### Transfers of Tip Payment Accounts on Solana The subscription that provides you the transfer data of one of these addresses is. ▶️ [Transfers of Tip Payment Accounts on Solana](https://ide.bitquery.io/Transfers-of-Tip-Payment-Accounts-on-Solana_1) #### Transfers where sender is the specified address Transfers where sender is the specified address. Uses the `Transfers` cube. Replace the address in the `where` clause to use it. ▶️ [Transfers where sender is the specified address](https://ide.bitquery.io/transfers-where-sender-is-the-specified-address_1) ### Balances & Holders #### Balance Stream This stream provides all balance updates on the Solana blockchain. ▶️ [Balance Stream](https://ide.bitquery.io/solana-balance-update-stream_3) ### Price & OHLC #### Token price stream from top market (rank 1) Streams a Solana token's price from its top market, one-second intervals, quoted in USD. Prices the token from its single top market rather than blending every pool, which is what you want for one specific token. ▶️ [Token price stream from top market (rank 1)](https://ide.bitquery.io/Token-price-stream-from-top-market--rank-1) #### Real-Time Token Prices in USD on Solana Stream live OHLC (Open, High, Low, Close) price and volume data for all tokens on Solana, quoted directly in USD. Useful for dashboards, analytics, or bots that need stable fiat-based prices. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real-Time Token Prices in USD on Solana](https://ide.bitquery.io/Real-Time-usd-price-on-solana-chain) #### 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. ▶️ [GoonFi Realtime OHLC, Price, Volume API - Crypto Price API](https://ide.bitquery.io/GoonFi-Realtime-OHLC-Price-Volume-API---Crypto-Price-API_1) #### 1-Second OHLC Stream This subscription generates a real-time OHLC (Open, High, Low, Close) K-line chart for Solana in real-time, useful for Tradingview charting in real-time. ▶️ [1-Second OHLC Stream](https://ide.bitquery.io/1-second-OHLC-k-line-Solana) #### Byreal token live prices using trades api Lock onto one token with `Pair.Token.Id` (e.g. `bid:solana:`) and the Byreal program address. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Byreal token live prices using trades api](https://ide.bitquery.io/Byreal-token-live-prices-using-trades-api) #### Latest price for more than 1 markets on solana You can retrieve data from multiple Solana DEX markets using our APIs or streams. The. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Latest price for more than 1 markets on solana](https://ide.bitquery.io/latest-price-for-more-than-1-markets-on-solana_1) #### Latest price for more than 1 markets on solana for specific currencies Latest price for more than 1 markets on solana for specific currencies. Uses the Trading cube. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Latest price for more than 1 markets on solana for specific currencies](https://ide.bitquery.io/latest-price-for-more-than-1-markets-on-solana-for-specific-currencies) #### Real-time Token Prices on Solana This stream delivers real-time token prices on Solana based on the latest trades. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real-time Token Prices on Solana](https://ide.bitquery.io/Real-time-price-stream-for-specific-token-on-solana) #### Get Latest Price of SOL in USD Real-time Get Latest Price of SOL in USD Real-time. Uses the Trading cube. Change the token address in the `where` clause to use it. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get Latest Price of SOL in USD Real-time](https://ide.bitquery.io/Get-Latest-Price-of-SOL-in--USD-Real-time) #### Get realtime Price of Apple xStock in USD Real-time You can use the following query to get the latest price of a Apple xStock on Solana. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get realtime Price of Apple xStock in USD Real-time](https://ide.bitquery.io/Get-realtime-Price-of-Apple-xStock-in--USD-Real-time) #### Price of a Moonshot token Real-time price of a Moonshot token in USD, one row per trade. Moonshot is `token_launchpad` in the Trading cube, not `moonshot`. Change the token address in the `where` clause to use it. ▶️ [Price of a Moonshot token](https://ide.bitquery.io/Price-of-a-Moonshot-token) ### Supply & Market Cap #### Realtime heaven tokens with marketcap 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. ▶️ [Realtime heaven tokens with marketcap 10k](https://ide.bitquery.io/realtime-heaven-tokens-with-marketcap-10k) #### Solana tokens with market cap above $1 million (Trading API) Subscribe when **`Token.Id`** matches Solana and **`Supply.MarketCap`** > 1,000,000 USD. ▶️ [Solana tokens with market cap above $1 million (Trading API)](https://ide.bitquery.io/realtime-stream-solana-tokens-with-marketcap-above-1-million) #### All trades on Solana with Price, Marketcap, supply Stream all Solana DEX trades in real time with USD price, market cap, FDV, circulating supply, and transaction fee data. ▶️ [All trades on Solana with Price, Marketcap, supply](https://ide.bitquery.io/All-trades-on-Solana-with-Price-Marketcap-supply) #### Get All DEX Trades on DBC With Price, Market Cap, and Supply Stream all Meteora DBC DEX trades in real time with USD price, market cap, FDV, circulating supply, and transaction fee data. Filter by `Pair.Market.Protocol: dynamic_bonding_curve` to capture every swap across Meteora DBC in a single subscription. ▶️ [Get All DEX Trades on DBC With Price, Market Cap, and Supply](https://ide.bitquery.io/Get-All-DEX-Trades-on-DBC-With-Price-Market-Cap-and-Supply) #### Bags.fm token creation stream using Solana token supply updates 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. ▶️ [Bags.fm token creation stream using Solana token supply updates](https://ide.bitquery.io/Bagsfm-token-creation-stream-using-Solana-token-supply-updates) #### Get newly created Moonshot tokens with 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. ▶️ [Get newly created Moonshot tokens with metadata](https://ide.bitquery.io/Get-newly-created-Moonshot-tokens-with-metadata) #### Newly created PF token, dev address, metadata Now you can track the newly created Pump Fun Tokens along with their dev address, metadata and supply. `PostBalance` will give you the current supply for the token. ▶️ [Newly created PF token, dev address, metadata](https://ide.bitquery.io/newly-created-PF-token-dev-address-metadata) ### Liquidity & Pools #### DEXPool Liquidity Changes This stream provides real time liquidity details for all pools on Solana. ▶️ [DEXPool Liquidity Changes](https://ide.bitquery.io/Solana-DEXPools-stream_2) #### Latest pools created on trends.fun stream Latest pools created on trends.fun stream. Uses the `Instructions` cube. Replace the address in the `where` clause to use it. ▶️ [Latest pools created on trends.fun stream](https://ide.bitquery.io/latest-pools-created-on-trendsfun-stream) #### Latest price based on liquidity Latest price based on liquidity. Uses the `DEXPools` cube. ▶️ [Latest price based on liquidity](https://ide.bitquery.io/latest-price-based-on-liquidity_2) #### Liquidity for a launchpad token pair stream Liquidity for a launchpad token pair stream. Uses the `DEXPools` cube. Replace the address in the `where` clause to use it. ▶️ [Liquidity for a launchpad token pair stream](https://ide.bitquery.io/liquidity-for-a-launchpad-token-pair-stream) #### Search tokens with liquidity over 1 million You can use the below query to get the tokens which are getting traded and have liquidity over 1 million USD. ▶️ [Search tokens with liquidity over 1 million](https://ide.bitquery.io/Search-tokens-with-liquidity-over-1-million) #### Trends fun tokens between 95 and 100 bonding curve progress Track Trends.fun tokens that are approaching graduation with high bonding curve progress percentages. Run the query. ▶️ [Trends fun tokens between 95 and 100 bonding curve progress](https://ide.bitquery.io/trends-fun-tokens-between-95-and-100-bonding-curve-progress) ### Transactions #### Realtime Solana Transactions The subscription query below fetches the most recent transactions on the Solana blockchain. ▶️ [Realtime Solana Transactions](https://ide.bitquery.io/Realtime-Solana-Transactions) ### Events & Calls #### ConsumeEvents instruction on OpenBook V2 We will use this subscription to listen to `consumeEvents` transactions on OpenBook v2. This instruction processes trade events and other activities such as order cancellations. ▶️ [ConsumeEvents instruction on OpenBook V2](https://ide.bitquery.io/consumeEvents-instruction-on-OpenBook-V2_3) ### Pump.fun #### PumpFun Token Creation This subscription tracks in real-time newly created Pumpfun tokens, including their metadata and associated developer addresses. ▶️ [PumpFun Token Creation](https://ide.bitquery.io/newly-created-PF-token-developer-address-metadata) #### PumpFun Trades Stream This stream returns the real time trades on Pumpfun platform. This stream could be modified to get real time trades for a particular token or trades by a particular trader. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [PumpFun Trades Stream](https://ide.bitquery.io/Pumpfun-DEX-Trades_1) #### Pumpswap Trades Stream This stream returns the real time trades on Pumpswap exchange. This stream could be modified to get real time trades for a particular token or trades by a particular trader. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Pumpswap Trades Stream](https://ide.bitquery.io/pumpswap-trades) #### 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. ▶️ [Get All DEX Trades on Pumpfun With Price, Market Cap, and Supply](https://ide.bitquery.io/Get-All-DEX-Trades-on-Pumpfun-With-Price-Market-Cap-and-Supply) #### Latest Trades for a token on Pumpswap Subscribe to `Trading.Trades` with the PumpSwap protocol (`pump_amm`) and the token address. Each update is a new trade involving that token on PumpSwap—use this to stream per-token activity without polling. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Latest Trades for a token on Pumpswap](https://ide.bitquery.io/Latest-Trades-for-a-token-on-Pumpswap) #### Price of a pump fun token using price index in usd Live stream of token price updates on Pump.fun. ▶️ [Price of a pump fun token using price index in usd](https://ide.bitquery.io/Price-of-a-pump-fun-token-using-price-index-in-usd) #### Pump Fun Tokens between 95% and 100% bonding curve progress 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. ▶️ [Pump Fun Tokens between 95% and 100% bonding curve progress](https://ide.bitquery.io/Pump-Fun-Tokens-between-95-and-100-bonding-curve-progress_3) #### Pump fun token mcap monitoring In case PostAmountInUSD is 0 then, you need to pull price from our Crypto price API. Here is an example which gets both supply and Price. ▶️ [Pump fun token mcap monitoring](https://ide.bitquery.io/pump-fun-token-mcap-monitoring) #### PumpSwap new pools Stream 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. ▶️ [PumpSwap new pools Stream](https://ide.bitquery.io/pumpSwap-new-pools-Stream) #### Pumpfun DEX Trades stream Use a `Trading.Trades` 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. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Pumpfun DEX Trades stream](https://ide.bitquery.io/Pumpfun-DEX-Trades-stream) #### Pumpswap latest Trade for a trader stream Subscribe to `Trading.Trades` with the same `Signer` and PumpSwap `ProgramAddress` filters. New trades for that wallet on PumpSwap stream as they are confirmed. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Pumpswap latest Trade for a trader stream](https://ide.bitquery.io/Pumpswap-latest-Trade-for-a-trader-stream_1) #### Realtime price of a pumpswap token Subscribe to `Trading.Pairs` with the PumpSwap protocol (`pump_amm`) and the token address. Each event includes `Price` and `PriceInUSD` for the latest leg—use it as a live price feed for that token on PumpSwap. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Realtime price of a pumpswap token](https://ide.bitquery.io/realtime-price-of-a-pumpswap-token) #### Realtime stream of "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). Subscribe to Trading `Pairs` with `MarketCap` between 30,000 and 35,000 USD. ▶️ [Realtime stream of "King of the Hill" Pump.fun tokens (30K–35K market cap)](https://ide.bitquery.io/realtime-stream-of-King-of-the-Hill-Pumpfun-tokens-30K35K-market-cap) #### Realtime stream pumpfun tokens with marketcap above 10k marketcap Subscribe to Trading `Pairs` when the token is on Solana, `Market.ProtocolFamily` is Pumpfun, `Supply.MarketCap` > 10,000 (USD), and interval duration > 1 second. ▶️ [Realtime stream pumpfun tokens with marketcap above 10k marketcap](https://ide.bitquery.io/realtime-stream-pumpfun-tokens-with-marketcap-above-10k-marketcap) #### Track creator fee transfers on pumpfun amm 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. ▶️ [Track creator fee transfers on pumpfun amm](https://ide.bitquery.io/track-creator-fee-transfers-on-pumpfun-amm) ### Raydium #### Latest Pools Created on Raydium This query returns the latest created pools on Raydium. You can set the limit here also. ▶️ [Latest Pools Created on Raydium](https://ide.bitquery.io/Latest-Radiyum-V4-pools-created_1) #### Latest Trades on Raydium This stream gives info about the real time trades on Raydium exchange. You can modify this query to monitor trades on Raydium for a particular token or by a particular trader. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Latest Trades on Raydium](https://ide.bitquery.io/Updated-Real-time-trades-on-Raydium-DEX-on-Solana_1) #### New Pool Creation on Raydium CLMM This stream gives info about the real time liquidity pool creation on Raydium CLMM. ▶️ [New Pool Creation on Raydium CLMM](https://ide.bitquery.io/Raydium-CLMM-Pool-Creation-stream) #### New Pool Creation on Raydium CPMM This stream gives info about the real time liquidity pool creation on Raydium CPMM. ▶️ [New Pool Creation on Raydium CPMM](https://ide.bitquery.io/CPMM-pools-creation-stream) #### New Pool Creation on Raydium Launchpad This stream gives info about the real time liquidity pool creation on Raydium Launchpad. ▶️ [New Pool Creation on Raydium Launchpad](https://ide.bitquery.io/Raydium-Launchpad-pool-creations_1) #### New Pool Creation on Raydium v4 This stream gives info about the real time liquidity pool creation on Raydium exchange. ▶️ [New Pool Creation on Raydium v4](https://ide.bitquery.io/Latest-Radiyum-V4-pools-created_5) #### Track Raydium Launchpad tokens above 95% Bonding Curve Progress in realtime Returns Raydium Launchpad tokens which have more than 95% bonding curve progress. ▶️ [Track Raydium Launchpad tokens above 95% Bonding Curve Progress in realtime](https://ide.bitquery.io/LetsBonkfun-Tokens-between-95-and-100-bonding-curve-progress_2) #### Newly launched token 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. ▶️ [Newly launched token on PumpFun, Raydium Launchpad, Meteora DBC, Heaven DEX, Bags , Jupiter studio, Moonit](https://ide.bitquery.io/newly-launched-token-on-PumpFun-Raydium-Launchpad-Meteora-DBC-Heaven-DEX-Bags--Jupiter-studio-Moonit) #### Raydium CLMM Trades Streams Raydium CLMM trades from the Trading cube, with USD price and trade size on every row. The Trading cube has no `AccountNames`; for the pool account list use the Raydium CLMM query on the Queries tab. ▶️ [Raydium CLMM Trades](https://ide.bitquery.io/Raydium-CLMM-DEX-Trades-with-AccountNames) #### Raydium AMM Trades Streams Raydium AMM trades from the Trading cube, with USD price and trade size on every row. Order-book context from OpenBook is not part of the Trading cube. ▶️ [Raydium AMM Trades](https://ide.bitquery.io/Raydium-dextrades-through-OpenBook-order-book) #### Realtime stream raydium launchpad tokens with marketcap above 10k marketcap 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. ▶️ [Realtime stream raydium launchpad tokens with marketcap above 10k marketcap](https://ide.bitquery.io/realtime-stream-raydium-launchpad-tokens-with-marketcap-above-10k-marketcap) #### Track Add Liquidity Transactions on Solana Raydium DEX If you want to track latest liquidity additions in Raydium pools, you can use. ▶️ [Track Add Liquidity Transactions on Solana Raydium DEX](https://ide.bitquery.io/Track-Add-Liquidity-Transactions-on-Solana-Raydium-DEX) ### Meteora #### Jup studio token migrations from Meteora DBC to Meteors DEX We monitor Meteora DBC program address `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` for migration instructions including `migrate_meteora_damm` and `migration_damm_v2`. ▶️ [Jup studio token migrations from Meteora DBC to Meteors DEX](https://ide.bitquery.io/jup-studio-token-migrations-from-Meteora-DBC-to-Meteors-DEX_1) #### Liquidity addition for meteora 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](https://ide.bitquery.io/liquidity-addition-for-meteora_1) #### Liquidity removal for meteora Liquidity removal for meteora. Uses the `DEXPools` cube. ▶️ [Liquidity removal for meteora](https://ide.bitquery.io/liquidity-removal-for-meteora_1) #### Meteora DBC token migrations to Meteors DEX Below query will give you the latest migrated tokens Meteora DBC in realtime. ▶️ [Meteora DBC token migrations to Meteors DEX](https://ide.bitquery.io/meteora-DBC-token-migrations-to-Meteors-DEX) #### Real time trades on Meteora Dynamic Bonding Curve on Solana The below query gets real-time information whenever there's a new trade on the Meteora DBC including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades on Meteora Dynamic Bonding Curve on Solana](https://ide.bitquery.io/Real-time-trades-on-Meteora-Dynamic-Bonding-Curve-on-Solana) #### Real time trades on MeteoraDAMMv2 DEX on Solana This query subscribes to real-time trades on the Meteora DAMM v2 (Dynamic Automated Market Maker) on the Solana blockchain by filtering using the program address `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG`. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades on MeteoraDAMMv2 DEX on Solana](https://ide.bitquery.io/Real-time-trades-on-MeteoraDAMMv2-DEX-on-Solana) #### Real time trades on MeteoraDLMM DEX on Solana This query subscribes to real-time trades on the Meteora DLMM (Dynamic Liquidity Market Maker) on the Solana blockchain by filtering using the program address `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo`. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades on MeteoraDLMM DEX on Solana](https://ide.bitquery.io/Real-time-trades-on-MeteoraDLMM-DEX-on-Solana) #### Real time trades on MeteoraDYN DEX on Solana The below query gets real-time information whenever there's a new trade on the Meteora DYN DEX including detailed information about the trade, including the buy and sell details, the block information, and the transaction specifics. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades on MeteoraDYN DEX on Solana](https://ide.bitquery.io/Real-time-trades-on-MeteoraDYN-DEX-on-Solana) #### Realtime Price feed of a Token on Meteora DAMM v2 You can use the following subscription to get real-time price updates of a token on Meteora DAMM v2 on Solana. This provides live price data as new trades occur. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Realtime Price feed of a Token on Meteora DAMM v2](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-Meteora-DAMM-v2) #### Realtime Price feed of a Token on Meteora DLMM You can use the following subscription to get real-time price updates of a token on Meteora DLMM on Solana. This provides live price data as new trades occur. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Realtime Price feed of a Token on Meteora DLMM](https://ide.bitquery.io/Realtime-Price-feed-of-a-Token-on-Meteora-DLMM) ### Orca #### Latest pool created on Orca - Websocket 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. ▶️ [Latest pool created on Orca - Websocket](https://ide.bitquery.io/Latest-pool-created-on-Orca---Websocket_1) #### Liquidity addition for orca whirlpool 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](https://ide.bitquery.io/liquidity-addition-for-orca-whirlpool_1) #### Liquidity removal for orca whirlpool With Orca’s program and negative base change, stream liquidity removals from Whirlpool markets. ▶️ [Liquidity removal for orca whirlpool](https://ide.bitquery.io/liquidity-removal-for-orca-whirlpool_1) #### Orca DEX Trades Websocket To access a real-time stream of trades for Solana Orca DEX. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Orca DEX Trades Websocket](https://ide.bitquery.io/Orca-DEX-Trades-Websocket) #### Orca DEX Trades for a specific currency Websocket By setting the limit to 1, you will receive the most recent trade, which reflects the latest price of the token. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Orca DEX Trades for a specific currency Websocket](https://ide.bitquery.io/Orca-DEX-Trades-for-a-specific-currency-Websocket) #### Price of a token on Orca 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. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Price of a token on Orca](https://ide.bitquery.io/Price-of-a-token-on-Orca) ### Jupiter #### Latest Cancel Expired Order Transactions on Jupiter in realtime We track Jupiter's Limit Order program address `jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu` for `cancelExpiredOrder` instructions. The query returns transaction signatures, account details, and program arguments for expired order cancellations. ▶️ [Latest Cancel Expired Order Transactions on Jupiter in realtime](https://ide.bitquery.io/Latest-Cancel-Expired-Order-Transactions-on-Jupiter-in-realtime_1) #### Latest Cancel Limit Order Transactions on Jupiter in realtime We track Jupiter's Limit Order program address `jupoNjAxXgZ4rjzxzPMP4oxduvQsQtZzyknqvzYNrNu` for `cancelOrder` instructions. The query returns input mint addresses, maker addresses, reserve addresses, and cancellation details. ▶️ [Latest Cancel Limit Order Transactions on Jupiter in realtime](https://ide.bitquery.io/Latest-Cancel-Limit-Order-Transactions-on-Jupiter-in-realtime) #### Tokens involved in Jupiter swap, source address, destination address, DEX involved 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. ▶️ [Tokens involved in Jupiter swap, source address, destination address, DEX involved](https://ide.bitquery.io/Tokens-involved-in-Jupiter-swap-source-address-destination-address-DEX-involved_2) ## Robinhood Chain ### Trades #### Latest DEX Trades on Robinhood Chain Latest DEX trades on Robinhood Chain (chain id 4663) via the Trading API, with price and USD amounts. ▶️ [Latest DEX Trades on Robinhood Chain](https://ide.bitquery.io/Robinhood-Trades) #### Bags amm trade websocket 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. ▶️ [Bags amm trade websocket](https://ide.bitquery.io/bags-amm-trade-websocket) #### Robinhood Chain API - Trades for a 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. ▶️ [Robinhood Chain API - Trades for a Token](https://ide.bitquery.io/Robinhood-Trades-for-a-token) #### Stream Robinhood Chain Trades in Real Time These are live examples — meme tokens go quiet over time, so swap in any token, pool, or trader you care about. ▶️ [Stream Robinhood Chain Trades in Real Time](https://ide.bitquery.io/stream-robinhood-chain-trades) #### Pools trade Stream new Crowd Launch auctions Every Crowd Launch deploys its auction through the auction factory `0x000000001f26a0044baa66024e7b6599c61963f8`, which emits `AuctionCreated(address,address,uint256,bytes)`. ▶️ [Pools trade Stream new Crowd Launch auctions](https://ide.bitquery.io/Pools-trade-Stream-new-Crowd-Launch-auctions) ### Transfers #### Ape.store Newly created tokens - Websocket Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Ape.store Newly created tokens - Websocket](https://ide.bitquery.io/Apestore-Newly-created-tokens---Websocket) #### Bags.fm Newly created tokens - Websocket Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Bags.fm Newly created tokens - Websocket](https://ide.bitquery.io/Bagsfm-Newly-created-tokens---Websocket) #### Bankr Bot Newly created tokens - Websocket Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Bankr Bot Newly created tokens - Websocket](https://ide.bitquery.io/Bankr-Bot-Newly-created-tokens---Websocket) #### Flap Sh Newly created tokens using transfer data - Websocket Track Flap.sh mints as transfers from the zero address with amount `1000000000` in transactions sent to the Flap.sh contract. ▶️ [Flap Sh Newly created tokens using transfer data - Websocket](https://ide.bitquery.io/Flap-Sh-Newly-created-tokens-using-transfer-data---Websocket) #### Hoodfun newly creaed tokens Websocket Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Hoodfun newly creaed tokens Websocket](https://ide.bitquery.io/hoodfun-newly-creaed-tokens---Websocket) #### Klik Finance Newly created tokens using transfers websocket Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Klik Finance Newly created tokens using transfers websocket](https://ide.bitquery.io/Klik-Finance-Newly-created-tokens-using-transfers-websocket) #### Launchpad newly creaed tokens Websocket Every transfer query on this page is identical except two values: the launchpad address in `Transaction.To` and the launch-mint `Amount`. ▶️ [Launchpad newly creaed tokens Websocket](https://ide.bitquery.io/launchpad-newly-creaed-tokens---Websocket) #### Pools trade Stream launches with token detail 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. ▶️ [Pools trade Stream launches with token detail](https://ide.bitquery.io/Pools-trade-Stream-launches-with-token-detail) #### Real time transfers on robinhood Stream live transfers for dashboards, bots, and alerting. ▶️ [Real time transfers on robinhood](https://ide.bitquery.io/real-time-transfers-on-robinhood) ### Price & OHLC #### Robinhood Chain OHLCV / Candlestick API for a Token Pair 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. ▶️ [Robinhood Chain OHLCV / Candlestick API for a Token Pair](https://ide.bitquery.io/OHLCV-stream-for-a-token-pair-on-robinhood) ### Liquidity & Pools #### Stream New pools.trade Token Launches Websocket subscription streaming every new pools.trade token launch on Robinhood Chain the moment it happens. ▶️ [Stream New pools.trade Token Launches](https://ide.bitquery.io/Pools-trade-Stream-new-launches) ### Events & Calls #### Flap sh Newly created tokens using logs (TokenCreated) - Websocket Filter Flap.sh `TokenCreated` events and decode argument values (token address, metadata fields, and related parameters). ▶️ [Flap sh Newly created tokens using logs (TokenCreated) - Websocket](https://ide.bitquery.io/Flap-sh-Newly-created-tokens-using-logs-TokenCreated---Websocket) #### Stream New Tokens on Robinhood Chain (All Launchpads) Follow the steps here: How to generate Bitquery API token ➤. ▶️ [Stream New Tokens on Robinhood Chain (All Launchpads)](https://ide.bitquery.io/stream-new-tokens-robinhood-chain) ## Polymarket ### Trades #### Real-Time Trades Stream Real-Time Trades Stream. ▶️ [Real-Time Trades Stream](https://ide.bitquery.io/prediction-market-trades-subscription) #### Trades for a Specific Market (Stream) Subscribe to trades for one market only by filtering on Question.MarketId. Replace the market ID in the query with your target market. ▶️ [Trades for a Specific Market (Stream)](https://ide.bitquery.io/subscribe-to-specific-market-trades) #### Bitcoin Up or Down Trades Stream Subscribe to live Polymarket trades for markets whose question title includes "Bitcoin Up or Down". ▶️ [Bitcoin Up or Down Trades Stream](https://ide.bitquery.io/Bitcoin-Up-or-Down-Trades-Stream) #### 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. ▶️ [How do I track high-value or whale trades on Polymarket?](https://ide.bitquery.io/How-do-I-track-high-value-or-whale-trades-on-Polymarket) #### Large trades on polymarket Start by streaming large Polymarket trades. Each event gives you a buyer address to investigate. Change `subscription` to `query` for historical results. ▶️ [Large trades on polymarket](https://ide.bitquery.io/large-trades--on-polymarket) #### Monitoring specific wallets trades in realtime for Ethereum up or down market 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. ▶️ [Monitoring specific wallets trades in realtime for Ethereum up or down market](https://ide.bitquery.io/monitoring-specific-wallets-trades-in-realtime-for-Ethereum-up-or-down-market) #### Monitoring specific wallets trades in realtime for XRP up or down market 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. ▶️ [Monitoring specific wallets trades in realtime for XRP up or down market](https://ide.bitquery.io/monitoring-specific-wallets-trades-in-realtime-for-XRP-up-or-down-market) #### Polymarket AI whale trades stream 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`. ▶️ [Polymarket AI whale trades stream](https://ide.bitquery.io/Polymarket-AI-whale-trades-stream) #### Polymarket whale trades alert Stream successful Polymarket trades whose collateral exceeds $10,000 USD. Adjust the threshold string as needed. ▶️ [Polymarket whale trades alert](https://ide.bitquery.io/polymarket-whale-trades-alert_1) ### Markets #### Real-Time Management Stream (Creations + Resolutions) Real-Time Management Stream (Creations + Resolutions). ▶️ [Real-Time Management Stream (Creations + Resolutions)](https://ide.bitquery.io/Prediction-Managements-subscription-resolutions-creations) #### Real-Time Market Creations Subscribe only to new market (Created) events. ▶️ [Real-Time Market Creations](https://ide.bitquery.io/track-realtime-new-polymarket-creations) #### Real-Time Market Resolutions Subscribe only to Resolved events. Winning outcome is in Prediction.Outcome; token details (e.g. AssetId) in Prediction.OutcomeToken. ▶️ [Real-Time Market Resolutions](https://ide.bitquery.io/track-realtime-polymarket-resolutions) ### Settlements #### Real-Time Settlement Stream Real-Time Settlement Stream. ▶️ [Real-Time Settlement Stream](https://ide.bitquery.io/realtime-predicion-market-settlements-stream) ## Perpetuals ### Hyperliquid #### Hyperliquid Real-time Trades Stream (WebSocket) Hyperliquid Real-time Trades Stream (WebSocket). ▶️ [Hyperliquid Real-time Trades Stream (WebSocket)](https://ide.bitquery.io/hyperliquid-trades-stream) #### Hyperliquid Price Updates Stream (WebSocket) Hyperliquid Price Updates Stream (WebSocket). ▶️ [Hyperliquid Price Updates Stream (WebSocket)](https://ide.bitquery.io/hyperliquid-price-updates-stream) #### Hyperliquid Real-time Candles Stream (WebSocket) Hyperliquid Real-time Candles Stream (WebSocket). ▶️ [Hyperliquid Real-time Candles Stream (WebSocket)](https://ide.bitquery.io/hyperliquid-candles-stream) ### Phoenix #### Solana Perps Live Trades Stream (Phoenix Fills) Stream every stop-loss and take-profit placement as it happens. ▶️ [Solana Perps Live Trades Stream (Phoenix Fills)](https://ide.bitquery.io/solana-perps-live-trades-stream) #### Solana Perpetuals Mark Price Stream (Phoenix) Solana Perpetuals Mark Price Stream (Phoenix). ▶️ [Solana Perpetuals Mark Price Stream (Phoenix)](https://ide.bitquery.io/solana-perpetuals-mark-price-stream) #### Collateral deposits and withdrawals Live collateral deposits and withdrawals on Phoenix perpetuals - the money-in and money-out feed for the venue. ▶️ [Collateral deposits and withdrawals](https://ide.bitquery.io/Solana---Phoenix-collateral-deposits-and-withdrawals-live) ## TRON ### Trades #### Real-time Trades on Sunpump This stream returns all the real time DEX trades happening on Sunpump exchange on the Tron network. You can modify this stream to get the trades of a particular token or trades by a particular trader. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real-time Trades on Sunpump](https://ide.bitquery.io/real-time-sunswapTrades) #### Real-time Trades on Tron This stream returns all the real time DEX trades happening on the Tron network. You can modify this stream to get DEX trades on a particular DEX or trades of a particular token or trades by a particular trader. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real-time Trades on Tron](https://ide.bitquery.io/Latest-trades-on-Tron) #### Sunpump trades To subscribe to latest Sunpump trades you can use. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Sunpump trades](https://ide.bitquery.io/Sunpump-trades) #### USDT TRC20 DEX Trades Real-time DEX trades where USDT is the bought currency on Tron — protocol, buyer and seller, amounts and order IDs. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [USDT TRC20 DEX Trades](https://ide.bitquery.io/USDT-TRC20-DEX-Trades) ### Transfers #### Real-time Tether USDT Transfers This subscription streams the latest USDT (TRC20) transfers on the TRON network. You can modify the stream to monitor Transfers of USDT from or to a particular address. ▶️ [Real-time Tether USDT Transfers](https://ide.bitquery.io/usdt-trc20-transfers_1) #### Sender is particular address Sender is particular address. Uses the `Transfers` cube. ▶️ [Sender is particular address](https://ide.bitquery.io/Sender-is-particular-address) #### Whale transfers of USDT on Tron The subscription query below fetches the whale transactions on the Tron network. We have used USDT address `TThzxNRLrW2Brp9DcTQU8i4Wd9udCWEdZ3`. ▶️ [Whale transfers of USDT on Tron](https://ide.bitquery.io/Whale-transfers-of-USDT-on-Tron) ### Price & OHLC #### Track price of a tron token in realtime Provides real-time updates on price of token `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` in terms of USDT `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`, including details about the DEX. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Track price of a tron token in realtime](https://ide.bitquery.io/Track-price-of-a-tron-token-in-realtime) ### Supply & Market Cap #### Get All DEX Trades on Tron With Price, Market Cap, and Supply Crypto Trades API: one row per swap, with USD and supply. Filter `Pair.Market.Network: Tron`. When to use this vs chain DEX APIs. ▶️ [Get All DEX Trades on Tron With Price, Market Cap, and Supply](https://ide.bitquery.io/Get-All-DEX-Trades-on-Tron-With-Price-Market-Cap-and-Supply) ### Transactions #### Monitor TRX address transactions The subscription query below fetches the transactions on the Tron network for the wallet address `TDqSquXBgUCLYvYC4XZgrprLK589dkhSCf`. ▶️ [Monitor TRX address transactions](https://ide.bitquery.io/monitor-TRX-address-transactions) ### Events & Calls #### Latest Buy on SunPump You can use following stream to get latest buys on Sunpump. You can try. ▶️ [Latest Buy on SunPump](https://ide.bitquery.io/latest-Buy-on-SunPump) #### New tokens on sunpump Will subscribe to the latest created sun pump tokens. You will find the newly created token address in `Log { SmartContract }`. ▶️ [New tokens on sunpump](https://ide.bitquery.io/New-tokens-on-sunpump_1) #### Sunpump sell event You can use following stream to get latest sells on Sunpump. You can try. ▶️ [Sunpump sell event](https://ide.bitquery.io/sunpump-sell-event) #### Tron sunpump first time buy event You can use follow stream to get stream of first time buy event for any new token. ▶️ [Tron sunpump first time buy event](https://ide.bitquery.io/Tron-sunpump-first-time-buy-event_1) ### Mempool #### Events with argumens Events with argumens. Uses the `Events` cube. Replace the address in the `where` clause to use it. ▶️ [Events with argumens](https://ide.bitquery.io/Events-with-argumens) #### Sunpump trades mempool We simulate transactions in mempool, therefore you can also get trades directly from mempool using. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Sunpump trades mempool](https://ide.bitquery.io/Sunpump-trades-mempool) #### Tron mempool transfers Provides real-time data on token transfers happening in the TRON mempool including the value of the transferred amount in USD. ▶️ [Tron mempool transfers](https://ide.bitquery.io/Tron-mempool-transfers) ## Cross-Chain ### Price & OHLC #### Crypto Price Stream This subscription gives you 1-second OHLC, mean price, averages for all tokens across Solana, Ethereum, BNB, Tron. ▶️ [Crypto Price Stream](https://ide.bitquery.io/1-second-crypto-price-stream-with-mcap) #### Stablecoin 1 sec Price Stream This subscription gives you 1-second OHLC, mean price, averages for all stablecoins including USDC, USDT, DAI, USDS etc. ▶️ [Stablecoin 1 sec Price Stream](https://ide.bitquery.io/stablecoin-1-second-price-stream) ## Ethereum ### Trades #### All DEX trades Every Ethereum DEX trade as it happens. Add a `where` filter to narrow to a token or protocol. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [All DEX trades](https://ide.bitquery.io/All-Ethereum-Trade-Stream_1) #### Trades of a specific trader of a specific token Crypto Trades API: filter `Pair.Market.Network: Ethereum` and `Trader.Address`. More examples: Trades API. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Trades of a specific trader of a specific token](https://ide.bitquery.io/trades-of-a-specific-trader-of-a-specific-token) #### All swap events Provides information on the latest real-time swap events on Ethereum. You can run it. ▶️ [All swap events](https://ide.bitquery.io/all-swap-events) #### Stream new position mints on Fluid DEX Vault 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. ▶️ [Stream new position mints on Fluid DEX Vault](https://ide.bitquery.io/stream-new-position-mints-on-Fluid-DEX-Vault) #### Latest token trades subscription Latest token trades subscription. Uses the Trading cube. Change the token address in the `where` clause to use it. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Latest token trades subscription](https://ide.bitquery.io/latest-token-trades-subscription) #### Real time trades of an ethereum address Real time trades of an ethereum address. Uses the Trading cube. Replace the address in the `where` clause to use it. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades of an ethereum address](https://ide.bitquery.io/Real-time-trades-of-an-ethereum-address) #### Subscribe to dex trades on ethereum mainnet Will get the realtime DEX trades happening on Ethereum Mainnet. Open it in the GraphQL IDE using this. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Subscribe to dex trades on ethereum mainnet](https://ide.bitquery.io/subscribe-to-dex-trades-on-ethereum-mainnet_2) #### Get pair trades data just like dexcsreener Will subscribe to real-time trade transactions for a pair, providing a continuous stream of data as new trades are processed and recorded. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get pair trades data just like dexcsreener](https://ide.bitquery.io/Get-pair-trades-data-just-like-dexcsreener) #### Get pair trades data just like geckoterminal Will subscribe to real-time trade transactions for a pair, providing a continuous stream of data as new trades are processed and recorded. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get pair trades data just like geckoterminal](https://ide.bitquery.io/Get-pair-trades-data-just-like-geckoterminal) #### Pepe live trades stream Every PEPE DEX trade as it is confirmed on-chain in real time using Bitquery subscription. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Pepe live trades stream](https://ide.bitquery.io/pepe-live-trades-stream) ### Transfers #### Token transfers Live ERC-20 transfers. Change the token address to follow a different one. ▶️ [Token transfers](https://ide.bitquery.io/Subscribe-to-Latest-WETH-token-transfers_3) #### Pepe whale transfer stream Subscribe to PEPE transfers above 1 billion tokens the moment they hit the chain. ▶️ [Pepe whale transfer stream](https://ide.bitquery.io/pepe-whale-transfer-stream) #### Subscribe to Latest WETH token transfers This example subscribes to WETH (Wrapped Ethereum) token transfers. The contract address is 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2. ▶️ [Subscribe to Latest WETH token transfers](https://ide.bitquery.io/Subscribe-to-Latest-WETH-token-transfers) #### Subscribe to latest Axie infinity token transfers You can open this API on our GraphQL IDE using this. ▶️ [Subscribe to latest Axie infinity token transfers](https://ide.bitquery.io/Subscribe-to-latest-Axie-infinity-token-transfers_1) ### Balances & Holders #### Balance of a specific address Live balance updates for one wallet. Replace the address. ▶️ [Balance of a specific address](https://ide.bitquery.io/Stream-Token-Balance-Updates-in-Real-Time) #### All transaction balances Every balance change on the chain — high volume, filter before using in production. ▶️ [All transaction balances](https://ide.bitquery.io/Subscribe-to-All-Transaction-Balances) #### Transaction balances for one address Balance changes scoped to a single wallet. ▶️ [Transaction balances for one address](https://ide.bitquery.io/Subscribe-to-Transaction-Balances-for-a-Specific-Address) #### Token balance changes by transaction Balance deltas for every token, transaction by transaction. ▶️ [Token balance changes by transaction](https://ide.bitquery.io/Track-Any-Token-Balance-Changes-by-Transaction-on-ETH) #### Balance update after transfer received from multiple addresses--stream Balance update after transfer received from multiple addresses--stream. Uses the `TransactionBalances` cube. ▶️ [Balance update after transfer received from multiple addresses--stream](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses--stream) #### Balance update after transfer received--stream Balance update after transfer received--stream. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update after transfer received--stream](https://ide.bitquery.io/Balance-update-after-transfer-received--stream) #### Balance update after transfer sent from multiple addresses--stream Balance update after transfer sent from multiple addresses--stream. Uses the `TransactionBalances` cube. ▶️ [Balance update after transfer sent from multiple addresses--stream](https://ide.bitquery.io/Balance-update-after-transfer-sent-from-multiple-addresses--stream) #### Balance update after transfer sent--stream Balance update after transfer sent--stream. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update after transfer sent--stream](https://ide.bitquery.io/Balance-update-after-transfer-sent--stream_3) #### Balance update from transfer for an address--stream Balance update from transfer for an address--stream. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update from transfer for an address--stream](https://ide.bitquery.io/balance-update-from-transfer-for-an-address--stream) #### Balance update from transfer for multiple addresses--stream Balance update from transfer for multiple addresses--stream. Uses the `TransactionBalances` cube. ▶️ [Balance update from transfer for multiple addresses--stream](https://ide.bitquery.io/balance-update-from-transfer-for-multiple-addresses--stream) ### Price & OHLC #### 1-second OHLC candles Rolling one-second candles for charting. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [1-second OHLC candles](https://ide.bitquery.io/1-second-OHLC-k-line-Ethereum) #### 1 second crypto price stream For a live ticker, use the Crypto Price API stream. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [1 second crypto price stream](https://ide.bitquery.io/1-second-crypto-price-stream) #### Pepe-ohlcv-stream Stream live PEPE price data with 1-minute candles, moving averages, and USD volume. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Pepe-ohlcv-stream](https://ide.bitquery.io/pepe-ohlcv-stream) #### Token price stream Live USD price updates as trades land. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Token price stream](https://ide.bitquery.io/token-price-stream) ### Supply & Market Cap #### Token market cap stream Live market cap updates for Ethereum tokens. ▶️ [Token market cap stream](https://ide.bitquery.io/ethereum-token-marketcap-stream_1) #### Tokens crossing $1M market cap Only tokens above a market cap floor. Change the threshold in the `where` clause. ▶️ [Tokens crossing $1M market cap](https://ide.bitquery.io/realtime-stream-ethereum-tokens-with-marketcap-above-1-million) #### All trades on Ethereum with Price, Marketcap, 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. ▶️ [All trades on Ethereum with Price, Marketcap, supply](https://ide.bitquery.io/All-trades-on-Ethereum-with-Price-Marketcap-supply) #### Token supply changes Mints and burns as they change a token's supply. ▶️ [Token supply changes](https://ide.bitquery.io/latest-token-supply-on-eth-chain) ### Liquidity & Pools #### Realtime slippage monitoring Slippage on every trade as it happens, across all pools. ▶️ [Realtime slippage monitoring](https://ide.bitquery.io/realtime-slippage-on-ethereum) #### 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. ▶️ [Realtime Liquidity Stream](https://ide.bitquery.io/Realtime-Liquidity-Stream_4) #### 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. ▶️ [Realtime Liquidity Stream of a Specific Pool](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_4) ### Transactions #### Get Transaction Hash In this section we will discuss how we can build eth_getTransactionByHash alternatives using Bitquery APIs. ▶️ [Get Transaction Hash](https://ide.bitquery.io/Get-Transaction-Hash) ### Events & Calls #### Stream pool and pair creation on ethereum Stream pool and pair creation on ethereum. Uses the `Events` cube. ▶️ [Stream pool and pair creation on ethereum](https://ide.bitquery.io/stream-pool-and-pair-creation-on-ethereum_1) #### 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. ▶️ [Subscribe to the Same Event Across Multiple Contracts](https://ide.bitquery.io/Subscribe-to-the-Same-Event-Across-Multiple-Contracts) ### Mempool #### Binance Mempool Transactions 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. ▶️ [Binance Mempool Transactions](https://ide.bitquery.io/Binance-Mempool-Transactions_1) #### Eth subscribe("logs") You can subscribe to all incoming logs filtered by any of the fields including method signature, tx value,sender , receiver and so on. In the below example we are tracking only logs where the method name is `transfer`. You can run it. ▶️ [Eth subscribe("logs")](https://ide.bitquery.io/eth_subscribelogs) #### Eth subscribe(“pendingTransactions”) To subscribe to incoming pending transactions, use the below subscription. You can run it. ▶️ [Eth subscribe(“pendingTransactions”)](https://ide.bitquery.io/eth_subscribependingTransactions) #### Current mempool fees Gas prices being offered by pending transactions right now. ▶️ [Current mempool fees](https://ide.bitquery.io/Get-Mempool-Fees) #### Mempool event stream 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. ▶️ [Mempool event stream](https://ide.bitquery.io/Mempool-event-stream) #### Pending DEX trades in the mempool Swaps sitting in the mempool — see trades before they confirm. ▶️ [Pending DEX trades in the mempool](https://ide.bitquery.io/mempool-token-trades_1) #### Pending transfers in the mempool Token transfers that are broadcast but not yet mined. ▶️ [Pending transfers in the mempool](https://ide.bitquery.io/mempool-transfers_1) #### New pairs being created, from the mempool Catches pool creation at broadcast time rather than after the block. ▶️ [New pairs being created, from the mempool](https://ide.bitquery.io/PairCreated-in-Mempool) #### Vrs signature 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. ▶️ [Vrs signature](https://ide.bitquery.io/vrs-signature) ### Blocks & Validators #### Balance after gas fee burn Tracks an address's balance alongside the gas it burns. ▶️ [Balance after gas fee burn](https://ide.bitquery.io/Monitor-balance-and-gas-fee-paid-for-an-address-using-stream_1) #### Self-destruct balance events Balances released when a contract self-destructs. ▶️ [Self-destruct balance events](https://ide.bitquery.io/All-Self-Destruct-Event-Balances-Stream) #### Block mining rewards Reward paid out per block. ▶️ [Block mining rewards](https://ide.bitquery.io/Track-Block-Mining-Rewards) #### MEV-related balance changes Balance movements tied to MEV payouts and builder rewards. ▶️ [MEV-related balance changes](https://ide.bitquery.io/Track-MEV-Related-Balance-Updates) #### Miner balance changes Balance movements on block producers. ▶️ [Miner balance changes](https://ide.bitquery.io/Track-Miner-Balance-Updates) #### Validator balance changes Balance movements on validator addresses. ▶️ [Validator balance changes](https://ide.bitquery.io/Track-Validator-Balance-Updates) #### Validator rewards Rewards paid to validators, block by block. ▶️ [Validator rewards](https://ide.bitquery.io/Track-Validator-Rewards) #### Filter by MEV Bot or Builder Address Track balance changes for specific MEV bots or block builders. ▶️ [Filter by MEV Bot or Builder Address](https://ide.bitquery.io/Filter-by-MEV-Bot-or-Builder-Address) #### Filter by Miner Address Track balance changes for a specific miner address. ▶️ [Filter by Miner Address](https://ide.bitquery.io/Filter-by-Miner-Address) #### Filter by Validator Address Track balance changes for a specific validator address. ▶️ [Filter by Validator Address](https://ide.bitquery.io/Filter-by-Validator-Address) ### Uniswap #### New Uniswap v3 pools Pool creation events as they are mined — new pair detection. ▶️ [New Uniswap v3 pools](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3_10_1) #### Slippage on Uniswap v4 pools Per-trade slippage for v4 pools. ▶️ [Slippage on Uniswap v4 pools](https://ide.bitquery.io/realtime-pair-slippage-on-ethereum-uniswap-v4) #### Uniswap trades Live trades on Uniswap only. ▶️ [Uniswap trades](https://ide.bitquery.io/All-Ethereum-Uniswap-Trade-Stream) #### Currency pair liquidity events stream If looking to monitor a currency pair across all virtual pools within Uniswap V4, then this subscription works the best. ▶️ [Currency pair liquidity events stream](https://ide.bitquery.io/currency-pair-liquidity-events-stream) #### 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. ▶️ [Latest Liquidity Changes of Pools in a Specific DEX Protocol - Uniswap V4](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4_6) #### Latest pools created Uniswap v3 Open this query on our GraphQL IDE using this. ▶️ [Latest pools created Uniswap v3](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3_9) #### Real time trades on uniswap v4 -- subscription These swaps use the chain-specific the Trading cube via `EVM { the Trading cube }`: `Trade.PoolId`, pool-relative Buy/Sell (the Trading cube). USD can be thin on small pools—use live swaps above when you want the Trading row shape. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades on uniswap v4 -- subscription](https://ide.bitquery.io/Real-time-trades-on-uniswap-v4----subscription) #### Stream all Uniswap Seconds OHLC Kline The new Price Index Stream 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 includes trading metrics like SMA, EMA, VWAP, and more. ▶️ [Stream all Uniswap Seconds OHLC Kline](https://ide.bitquery.io/Stream-all-Uniswap-Seconds-OHLC-Kline_1) #### Uniswap all versions trades stream Track live trades across all Uniswap versions. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Uniswap all versions trades stream](https://ide.bitquery.io/uniswap-all-versions-trades-stream_1) #### Uniswap v3 pairs websocket Open this query on our GraphQL IDE using this. ▶️ [Uniswap v3 pairs websocket](https://ide.bitquery.io/uniswap-v3-pairs-websocket) ## BSC ### Trades #### All BNB Trade Stream Crypto 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. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [All BNB Trade Stream](https://ide.bitquery.io/All-BNB-Trade-Stream) #### Real-time Trades on BSC This subscription returns the real-time trades happening on BSC Network. You can modify the stream to get real-time trades for a particular token, a particular token pair and even a particular trader. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real-time Trades on BSC](https://ide.bitquery.io/subscribe-to-dex-trades-on-BNB-mainnet) #### Subscribe to bsc dex trades This example uses the chain-specific the Trading cube via `EVM(network: bsc) { the Trading cube }` (pool-side Buy/Sell; see the Trading cube). USD fields can be empty on thin pools. For swap rows with trader + USD, use the stream at the top of this page. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Subscribe to bsc dex trades](https://ide.bitquery.io/subscribe-to-bsc-dex-trades) ### Transfers #### Transfers where sender is a particular address Transfers where sender is a particular address. Uses the `Transfers` cube. ▶️ [Transfers where sender is a particular address](https://ide.bitquery.io/Transfers-where-sender-is-a-particular-address) ### Balances & Holders #### Real-time Transaction Balance Update for a Wallet on BSC This stream provides real time transaction balance updates for a wallet on BSC. ▶️ [Real-time Transaction Balance Update for a Wallet on BSC](https://ide.bitquery.io/Subscribe-to-Transaction-Balances-for-a-Specific-Address-bsc) #### Balance update after transfer received from multiple addresses--stream bsc Balance update after transfer received from multiple addresses--stream bsc. Uses the `TransactionBalances` cube. ▶️ [Balance update after transfer received from multiple addresses--stream bsc](https://ide.bitquery.io/Balance-update-after-transfer-received-from-multiple-addresses--stream-bsc) #### Balance update after transfer received--stream bsc Balance update after transfer received--stream bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update after transfer received--stream bsc](https://ide.bitquery.io/Balance-update-after-transfer-received--stream-bsc) #### Balance update after transfer sent from multiple addresses--stream bsc Balance update after transfer sent from multiple addresses--stream bsc. Uses the `TransactionBalances` cube. ▶️ [Balance update after transfer sent from multiple addresses--stream bsc](https://ide.bitquery.io/Balance-update-after-transfer-sent-from-multiple-addresses--stream-bsc) #### Balance update after transfer sent--stream bsc Balance update after transfer sent--stream bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update after transfer sent--stream bsc](https://ide.bitquery.io/Balance-update-after-transfer-sent--stream-bsc) #### Balance update from transfer for an address--stream bsc Balance update from transfer for an address--stream bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update from transfer for an address--stream bsc](https://ide.bitquery.io/balance-update-from-transfer-for-an-address--stream-bsc) #### Balance update from transfer for multiple addresses--stream bsc Balance update from transfer for multiple addresses--stream bsc. Uses the `TransactionBalances` cube. ▶️ [Balance update from transfer for multiple addresses--stream bsc](https://ide.bitquery.io/balance-update-from-transfer-for-multiple-addresses--stream-bsc) #### Monitor balance after unused gas fee returned for an address--stream bsc Monitor balance after unused gas fee returned for an address--stream bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Monitor balance after unused gas fee returned for an address--stream bsc](https://ide.bitquery.io/Monitor-balance-after-unused-gas-fee-returned--for-an-address--stream-bsc) #### Monitor balance after unused gas fee returned for multiple addresses--stream bsc Monitor balance after unused gas fee returned for multiple addresses--stream bsc. Uses the `TransactionBalances` cube. ▶️ [Monitor balance after unused gas fee returned for multiple addresses--stream bsc](https://ide.bitquery.io/Monitor-balance-after-unused-gas-fee-returned--for-multiple-addresses--stream-bsc) #### Monitor balance and gas fee paid for an address using stream bsc Monitor balance and gas fee paid for an address using stream bsc. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Monitor balance and gas fee paid for an address using stream bsc](https://ide.bitquery.io/Monitor-balance-and-gas-fee-paid-for-an-address-using-stream-bsc) ### Price & OHLC #### Stream for latest prices for Flap.sh tokens Subscribe to real-time price updates for all Flap.sh tokens. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Stream for latest prices for Flap.sh tokens](https://ide.bitquery.io/Stream-for-latest-prices-for-Flapsh-tokens) #### Realtime price of a ETH in terms of WBNB Provides real-time updates on price of ETH `0x2170Ed0880ac9A755fd29B2688956BD959F933F8` in terms of WBNB `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c`, including details about the DEX, market, and order specifics. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Realtime price of a ETH in terms of WBNB](https://ide.bitquery.io/realtime-price-of-a-ETH-in-terms-of-WBNB) ### Supply & Market Cap #### BSC tokens with market cap above $1 million (Trading API) Subscribe when **`Token.Id`** matches BSC and **`Supply.MarketCap`** > 1,000,000 USD. ▶️ [BSC tokens with market cap above $1 million (Trading API)](https://ide.bitquery.io/realtime-stream-bsc-tokens-with-marketcap-above-1-million_1) #### All trades on BSC with Price, Marketcap, 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. ▶️ [All trades on BSC with Price, Marketcap, supply](https://ide.bitquery.io/All-trades-on-BSC-with-Price-Marketcap-supply) #### Bsc token marketcap stream Subscribe to `Tokens` where currency id includes `bsc`, with interval duration greater than 1 (second). ▶️ [Bsc token marketcap stream](https://ide.bitquery.io/bsc-token-marketcap-stream) ### Liquidity & Pools #### Realtime Liquidity Stream of a Specific Pool This subscription query monitors real-time liquidity changes for a specific DEX pool on BSC. Use this to track liquidity events, pool reserves, and spot prices for a particular pool as they occur. ▶️ [Realtime Liquidity Stream of a Specific Pool](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_1) #### 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. ▶️ [Realtime Slippage Monitoring](https://ide.bitquery.io/realtime-slippage-on-bsc) #### Realtime Liquidity Stream This subscription query returns real-time liquidity data for all DEX pools on BSC. You can monitor liquidity changes, pool reserves, and spot prices as trades and liquidity modifications occur across all pools. ▶️ [Realtime Liquidity Stream](https://ide.bitquery.io/Realtime-Liquidity-Stream_2) ### Events & Calls #### Newly Created Tokens on BSC network 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. ▶️ [Newly Created Tokens on BSC network](https://ide.bitquery.io/Newly-Created-Tokens-on-BSC-network_2) ### Mempool #### Bsc mempool txs Use a GraphQL `subscription` on the Bitquery streaming WebSocket `wss://streaming.bitquery.io/graphql` with root `EVM(network: bsc, mempool: true)`. ▶️ [Bsc mempool txs](https://ide.bitquery.io/bsc-mempool-txs) #### Monitor mempool trades 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. ▶️ [Monitor mempool trades bsc](https://ide.bitquery.io/monitor-mempool-trades-bsc) ### Blocks & Validators #### Real-time Validator Rewards for BSC This stream provides the info on rewards received by validators on BSC in real time. ▶️ [Real-time Validator Rewards for BSC](https://ide.bitquery.io/Track-Validator-Balance-Updates-bsc_1) #### Track MEV Balance in Real Time for BSC This stream monitors MEV activities and Balance Updates on BSC in real time. ▶️ [Track MEV Balance in Real Time for BSC](https://ide.bitquery.io/Track-MEV-Related-Balance-Updates-bsc) #### All Self-Destruct Event Balances Stream bsc Monitor all contract self-destruct event balances in real-time using this GraphQL subscription. ▶️ [All Self-Destruct Event Balances Stream bsc](https://ide.bitquery.io/All-Self-Destruct-Event-Balances-Stream-bsc) #### Filter by MEV Bot or Builder Address bsc Track balance changes for specific MEV bots or block builders. ▶️ [Filter by MEV Bot or Builder Address bsc](https://ide.bitquery.io/Filter-by-MEV-Bot-or-Builder-Address-bsc) #### Filter by Miner Address bsc Track balance changes for a specific miner address. ▶️ [Filter by Miner Address bsc](https://ide.bitquery.io/Filter-by-Miner-Address-bsc) #### Filter by Validator Address bsc Track balance changes for a specific validator address. ▶️ [Filter by Validator Address bsc](https://ide.bitquery.io/Filter-by-Validator-Address-bsc_1) #### Track Block Mining Rewards bsc Track rewards received by miners for successfully mining blocks. ▶️ [Track Block Mining Rewards bsc](https://ide.bitquery.io/Track-Block-Mining-Rewards-bsc) #### Track Ephemeral MEV Contract Balance Changes bsc Monitor balance changes for short-lived contracts that are created and destroyed in the same transaction (typical pattern for MEV bots) using this subscription. ▶️ [Track Ephemeral MEV Contract Balance Changes bsc](https://ide.bitquery.io/Track-Ephemeral-MEV-Contract-Balance-Changes-bsc) #### Track Large MEV Transactions bsc Monitor large transaction fee rewards that may indicate significant MEV extraction. ▶️ [Track Large MEV Transactions bsc](https://ide.bitquery.io/Track-Large-MEV-Transactions-bsc) #### Track Large Self-Destruct Transaction Balances bsc Monitor significant self-destruct balance changes (e.g., > $1000 USD) using this subscription. ▶️ [Track Large Self-Destruct Transaction Balances bsc](https://ide.bitquery.io/Track-Large-Self-Destruct-Transaction-Balances-bsc) ### Four Meme #### Four Meme Token Creations Stream This stream returns the latest token creations on `Four Meme` on BSC Network in real time. ▶️ [Four Meme Token Creations Stream](https://ide.bitquery.io/track-Four-meme-token-creation-using-events_2) #### Four Meme Trades Stream This stream returns the latest trades happening on `Four Meme` on BSC Network in real time. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Four Meme Trades Stream](https://ide.bitquery.io/Latest-trades-on-fourmeme) #### Four Meme User Trades This stream helps in monitoring the trades of a Four Meme user in real time. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Four Meme User Trades](https://ide.bitquery.io/monitor-trades-of-a-trader-on-four-meme) #### Stream Real-time MarketCap of FourMeme Tokens Real-time market cap stream with OHLC for FourMeme tokens at 1-second intervals. Market cap is calculated from price using fixed 1 billion supply. ▶️ [Stream Real-time MarketCap of FourMeme Tokens](https://ide.bitquery.io/Real-Time-Marektcap-and-price-for-Four-meme-tokens) #### Four Meme bonding curve completion mempool Monitor tokens that are about to complete their bonding curve (near graduation) in the mempool. ▶️ [Four Meme bonding curve completion mempool](https://ide.bitquery.io/Four-Meme-bonding-curve-completion-mempool) #### Four Meme large buys mempool Monitor large buy orders in the mempool to detect whale activity and potential price pumps. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Four Meme large buys mempool](https://ide.bitquery.io/Four-Meme-large-buys-mempool) #### Four Meme liquidity add mempool Monitor when liquidity is being added to Four Meme tokens before confirmation. Important for detecting graduation events. ▶️ [Four Meme liquidity add mempool](https://ide.bitquery.io/Four-Meme-liquidity-add-mempool) #### Four Meme mempool trades 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. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Four Meme mempool trades](https://ide.bitquery.io/Four-Meme-mempool-trades) #### Four Meme migration mempool Track when Four Meme tokens are graduating to PancakeSwap before the migration completes. Critical for trading strategies. ▶️ [Four Meme migration mempool](https://ide.bitquery.io/Four-Meme-migration-mempool) #### Four Meme rug pull detection mempool Monitor for suspicious activity like developers selling large amounts in mempool. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Four Meme rug pull detection mempool](https://ide.bitquery.io/Four-Meme-rug-pull-detection-mempool) ### PancakeSwap #### Real-time Mempool Trades on Pancakeswap Get real time unconfirmed trades on Pancakeswap, using the given stream. ▶️ [Real-time Mempool Trades on Pancakeswap](https://ide.bitquery.io/Mempool---Latest-BSC-PancakeSwap-v3-dextrades---Stream) #### Track Four Meme Token migrations to PancakeSwap This query tracks four meme token migrations to Pancakeswap in realtime by monitoring transactions sent to the Four Meme factory address and filtering for `PairCreated` and `PoolCreated` events. These events are emitted when a token graduates from Four Meme and migrates to Pancakeswap. ▶️ [Track Four Meme Token migrations to PancakeSwap](https://ide.bitquery.io/four-meme-migration-to-pancakeswap) #### Binance meme rush migration to pancakeswap 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. ▶️ [Binance meme rush migration to pancakeswap](https://ide.bitquery.io/binance-meme-rush-migration-to-pancakeswap) #### Latest BSC PancakeSwap v3 dextrades - Stream Latest BSC PancakeSwap v3 dextrades - Stream. Uses the `DEXTrades` cube. ▶️ [Latest BSC PancakeSwap v3 dextrades - Stream](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades---Stream_2) #### Mempool - Latest BSC PancakeSwap v3 dextrades - Stream Mempool - Latest BSC PancakeSwap v3 dextrades - Stream. Uses the `DEXTrades` cube. ▶️ [Mempool - Latest BSC PancakeSwap v3 dextrades - Stream](https://ide.bitquery.io/Mempool---Latest-BSC-PancakeSwap-v3-dextrades---Stream_1) #### Stream - BSC PancakeSwap v3 Trades for a token Stream - BSC PancakeSwap v3 Trades for a token. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. ▶️ [Stream - BSC PancakeSwap v3 Trades for a token](https://ide.bitquery.io/Stream---BSC-PancakeSwap-v3-Trades-for-a-token) #### Stream - Liqiidity add for all tokens on PancakeSwap v3 Liquidity addition is an important event related to any liquidity pool. Using. ▶️ [Stream - Liqiidity add for all tokens on PancakeSwap v3](https://ide.bitquery.io/Stream---Liqiidity-add-for-all-tokens-on-PancakeSwap-v3) #### Stream - Liquidity remove for all tokens on PancakeSwap v3 Filter `Burn` signatures on the same PancakeSwap v3 manager to track liquidity withdrawals in real time. ▶️ [Stream - Liquidity remove for all tokens on PancakeSwap v3](https://ide.bitquery.io/Stream---Liquidity-remove-for-all-tokens-on-PancakeSwap-v3) ### Uniswap #### 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 BSC. Here we have taken example of Uniswap V4. ▶️ [Latest Liquidity Changes of Pools in a Specific DEX Protocol - Uniswap V4](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4) #### Newly Created Pools on Uniswap v3 on BSC network This subscription websocket lets you track the newly created pools on Uniswap V3 `0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7`. ▶️ [Newly Created Pools on Uniswap v3 on BSC network](https://ide.bitquery.io/Newly-Created-Pools-on-Uniswap-v3-on-BSC-network_3) #### Real time trades for uniswap v4 bsc 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 BSC. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades for uniswap v4 bsc](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-bsc) #### Uniswap v4 pool liquidity bsc Stream live liquidity for all Uniswap v4 pools on BSC. ▶️ [Uniswap v4 pool liquidity bsc](https://ide.bitquery.io/uniswap-v4-pool-liquidity-bsc) #### Uniswap v4 pool liquidity by poolid bsc 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`. ▶️ [Uniswap v4 pool liquidity by poolid bsc](https://ide.bitquery.io/uniswap-v4-pool-liquidity-by-poolid-bsc) ## Base ### Trades #### All Base Trade Stream Crypto Trades API: one row per swap, with USD and supply. Filter `Pair.Market.Network: Base`. When to use this vs chain DEX APIs. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [All Base Trade Stream](https://ide.bitquery.io/All-Base-Trade-Stream) #### Base DEX Trades Stream This stream returns all the real time DEX trades happening on Base. You can modify this stream to get DEX trades on a particular DEX or trades of a particular token or trades by a particular trader. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Base DEX Trades Stream](https://ide.bitquery.io/subscribe-to-dex-trades-on-base_1) #### Subscribe to dex trades on base Read the Trading cube vs the Trading cube vs Trades cube to get a better understanding on when to use which cube. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Subscribe to dex trades on base](https://ide.bitquery.io/subscribe-to-dex-trades-on-base) #### Subscription for Latest Trades for AERO For this part, we have chosen AERO token as the token is currently trending and have high trade volume. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Subscription for Latest Trades for AERO](https://ide.bitquery.io/Subscription-for-Latest-Trades-for-AERO_1) ### Transfers #### Token Transfers Stream This stream lets you monitor all the token transfers for a particular token. You can modify this subscription to track and monitor token transfers for a particular token from or to a particular address. ▶️ [Token Transfers Stream](https://ide.bitquery.io/Subscribe-to-Latest-USDC-token-transfers) #### Newly created zora tokens stream You can also stream the latest tokens created in real-time using. ▶️ [Newly created zora tokens stream](https://ide.bitquery.io/Newly-created-zora-tokens-stream) #### Sender is a particular address Sender is a particular address. Uses the `Transfers` cube. ▶️ [Sender is a particular address](https://ide.bitquery.io/Sender-is-a-particular-address_3) #### Whale transfers of USDC on base The subscription query below fetches the whale transactions on the Base network. We have used USDC address `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. ▶️ [Whale transfers of USDC on base](https://ide.bitquery.io/Whale-transfers-of-USDC-on-base) ### Balances & Holders #### Stream Token Balance of a Address in Real Time Subscribe to real-time token balance updates for a specific address and token. This subscription will notify you whenever the token balance changes. ▶️ [Stream Token Balance of a Address in Real Time](https://ide.bitquery.io/Stream-Token-Balance-Updates-in-Real-Time-on-base) #### Subscribe to All Transaction Balances This subscription provides real-time balance updates for all addresses involved in transactions on the Base network. ▶️ [Subscribe to All Transaction Balances](https://ide.bitquery.io/Subscribe-to-All-Transaction-Balances_1) #### Subscribe to Transaction Balances for a Specific Address This subscription filters transaction balances for a specific address in real-time. ▶️ [Subscribe to Transaction Balances for a Specific Address](https://ide.bitquery.io/Subscribe-to-Transaction-Balances-for-a-Specific-Address_1) #### Track Token Balance Changes Monitor token balance changes for a specific token across all transactions. This helps track token movements and transfers. ▶️ [Track Token Balance Changes](https://ide.bitquery.io/Track-Token-Balance-Changes-by-Transaction-on-base) #### Balance update from transfer for an address stream base Balance update from transfer for an address stream base. Uses the `TransactionBalances` cube. Replace the address in the `where` clause to use it. ▶️ [Balance update from transfer for an address stream base](https://ide.bitquery.io/balance-update-from-transfer-for-an-address--stream-base) #### Subscribe to All Transaction Balances base Provides real-time balance updates for all addresses involved in transactions on the Base network. ▶️ [Subscribe to All Transaction Balances base](https://ide.bitquery.io/Subscribe-to-All-Transaction-Balances-base) #### Subscribe to Transaction Balances for a Specific Address base This subscription filters transaction balances for a specific address. ▶️ [Subscribe to Transaction Balances for a Specific Address base](https://ide.bitquery.io/Subscribe-to-Transaction-Balances-for-a-Specific-Address-base) #### Track Block Builder Rewards base Monitor transaction fee rewards received by block builders (MEV extractors) ▶️ [Track Block Builder Rewards base](https://ide.bitquery.io/Track-Block-Builder-Rewards-base) #### Track Transaction Fee Rewards base Monitor transaction fee rewards received by miners. ▶️ [Track Transaction Fee Rewards base](https://ide.bitquery.io/Track-Transaction-Fee-Rewards-base) ### Price & OHLC #### Aerodrome dex - realtime prices, 1-sec ohlc, trading volumes 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. ▶️ [Aerodrome dex - realtime prices, 1-sec ohlc, trading volumes](https://ide.bitquery.io/aerodrome-dex---realtime-prices-1-sec-ohlc-trading-volumes) #### Real-time 1 second OHLC This stream provides real time price and OHLC stream for all tokens on Base based on trades. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real-time 1 second OHLC](https://ide.bitquery.io/1-second-OHLC-k-line-Base) #### Price of USDC in terms of DAI on Base network Provides real-time updates on price of USDC `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` in terms of DAI `0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb`, including details about the DEX, market, and order specifics. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Price of USDC in terms of DAI on Base network](https://ide.bitquery.io/Price-of-USDC-in-terms-of-DAI-on-Base-network) #### Token Price Stream This stream returns the real time trade price of a token against the token it is traded with and the price in USD. You could modify the stream to get the price of the token for a particular token pair or against a particular token. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Token Price Stream](https://ide.bitquery.io/token-price-stream_2) #### Get latest price of DAI in USD on Base 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. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get latest price of DAI in USD on Base](https://ide.bitquery.io/Get-latest-price-of-DAI-in-USD-on-Base) ### Supply & Market Cap #### Base token market cap stream (Trading API) Subscribe to **`Tokens`** rows for assets whose currency id includes **`base`** (interval duration > 1s). ▶️ [Base token market cap stream (Trading API)](https://ide.bitquery.io/base-token-marketcap-stream) #### Base tokens with market cap above $1 million (Trading API) Subscribe when **`Token.Id`** matches Base and **`Supply.MarketCap`** > 1,000,000 USD. ▶️ [Base tokens with market cap above $1 million (Trading API)](https://ide.bitquery.io/realtime-stream-base-tokens-with-marketcap-above-1-million) #### All trades on Base with Price, Marketcap, 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. ▶️ [All trades on Base with Price, Marketcap, supply](https://ide.bitquery.io/All-trades-on-Base-with-Price-Marketcap-supply) #### Bankr token realtime marketcap OHLC stream Subscribe to live 1-second OHLC + market cap updates for a specific Bankr token. ▶️ [Bankr token realtime marketcap OHLC stream](https://ide.bitquery.io/Bankr-token-realtime-marketcap-OHLC-stream) #### Base tokens above 100k marketcap stream Stream every Base token currently above $100k FDV. Useful as a high-mcap or "graduated by mcap" alert. ▶️ [Base tokens above 100k marketcap stream](https://ide.bitquery.io/Base-tokens-above-100k-marketcap-stream) ### Liquidity & Pools #### 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. ▶️ [Realtime Slippage Monitoring](https://ide.bitquery.io/realtime-slippage-on-base) #### Realtime Liquidity Stream This subscription query returns real-time liquidity data for all DEX pools on Base. You can monitor liquidity changes, pool reserves, and spot prices as trades and liquidity modifications occur across all pools. ▶️ [Realtime Liquidity Stream](https://ide.bitquery.io/Realtime-Liquidity-Stream_3) #### Realtime Liquidity Stream of a Specific Pool This subscription query monitors real-time liquidity changes for a specific DEX pool on Base. Use this to track liquidity events, pool reserves, and spot prices for a particular pool as they occur. ▶️ [Realtime Liquidity Stream of a Specific Pool](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_3) ### Events & Calls #### Realtime stream Bankr launches Base Convert the above query into a subscription to be notified of every new token the moment it lands on Base. ▶️ [Realtime stream Bankr launches Base](https://ide.bitquery.io/Realtime-stream-Bankr-launches-Base) ### Blocks & Validators #### Monitoring Balance after Latest Gas Fee Burn Monitor the balance and gas fee burnt for a particular address in real-time. ▶️ [Monitoring Balance after Latest Gas Fee Burn](https://ide.bitquery.io/Monitor-balance-and-gas-fee-paid-for-an-address-using-stream_2) #### Track All Self-Destruct Event Balances Monitor all contract self-destruct event balances in real-time. ▶️ [Track All Self-Destruct Event Balances](https://ide.bitquery.io/All-Self-Destruct-Event-Balances-Stream-base_1) #### Track Block Mining Rewards Track rewards received by miners for successfully mining blocks in real-time. ▶️ [Track Block Mining Rewards](https://ide.bitquery.io/Track-Block-Mining-Rewards-base_1) #### Track MEV-Related Balance Updates Monitor balance changes related to MEV activities, including transaction fee rewards and block builder rewards. ▶️ [Track MEV-Related Balance Updates](https://ide.bitquery.io/Track-MEV-Related-Balance-Updates-base_1) #### Track Miner Balance Updates Monitor balance changes for Base miners, including block rewards, uncle block rewards, and transaction fee rewards. ▶️ [Track Miner Balance Updates](https://ide.bitquery.io/Track-Miner-Balance-Updates-BASE_1) #### Track Validator Rewards Track validator rewards and balance increases from staking activities in real-time. ▶️ [Track Validator Rewards](https://ide.bitquery.io/Track-Validator-Balance-Updates-on-base) #### All Self Destruct Event Balances Stream base Monitor all contract self-destruct event balances in real-time using this GraphQL subscription. ▶️ [All Self Destruct Event Balances Stream base](https://ide.bitquery.io/All-Self-Destruct-Event-Balances-Stream-base) #### Filter by MEV Bot or Builder Address base Track balance changes for specific MEV bots or block builders. ▶️ [Filter by MEV Bot or Builder Address base](https://ide.bitquery.io/Filter-by-MEV-Bot-or-Builder-Address-base) #### Filter by Miner Address base Track balance changes for a specific miner address. ▶️ [Filter by Miner Address base](https://ide.bitquery.io/Filter-by-Miner-Address-base) #### Track Block Mining Rewards base Track rewards received by miners for successfully mining blocks. ▶️ [Track Block Mining Rewards base](https://ide.bitquery.io/Track-Block-Mining-Rewards-base) ### Uniswap #### Pair Creation on Uniswap This stream returns the real time liquidity pools/token pairs created on Uniswap V3. You could modify the stream to monitor newly created pools on a different protocol. ▶️ [Pair Creation on Uniswap](https://ide.bitquery.io/Latest-pools-created-Uniswap-v3-Base) #### Uniswap v3 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders 1-second OHLC and volume stream for tokens traded on Uniswap v3 (Base). Great for bot trading strategies. ▶️ [Uniswap v3 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders](https://ide.bitquery.io/Uniswap-v3-DEX-tokens-1-second-price-stream-with-OHLC_1) #### Bankr token V4 swaps realtime Bankr trades clear on the Uniswap V4 singleton. Use the Crypto Trades API (`Trading.Trades`) to stream swap-level rows with USD price, market cap, supply, trader, and V4 pool id. ▶️ [Bankr token V4 swaps realtime](https://ide.bitquery.io/Bankr-token-V4-swaps-realtime) #### 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 Base. Here we have taken example of Uniswap V4. ▶️ [Latest Liquidity Changes of Pools in a Specific DEX Protocol - Uniswap V4](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4_5) #### Real time trades on uniswap v4 base 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. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades on uniswap v4 base](https://ide.bitquery.io/Real-time-trades-on-uniswap-v4-base) #### Uniswap v4 pool liquidity base Stream live liquidity for all Uniswap v4 pools on Base. ▶️ [Uniswap v4 pool liquidity base](https://ide.bitquery.io/uniswap-v4-pool-liquidity-base) #### Uniswap v4 pool liquidity by poolid base 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`. ▶️ [Uniswap v4 pool liquidity by poolid base](https://ide.bitquery.io/uniswap-v4-pool-liquidity-by-poolid-base) ## Arbitrum ### Trades #### Arbitrum Dextrades subscription This example uses the chain-specific the Trading cube via `EVM(network: arbitrum) { the Trading cube }` (pool-side Buy/Sell; see the Trading cube). USD can be weak on thin pools. For trader + USD swap rows, use the stream at the top. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Arbitrum Dextrades subscription](https://ide.bitquery.io/Arbitrum-Dextrades-subscription) ### Supply & Market Cap #### Arbitrum token marketcap stream 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. ▶️ [Arbitrum token marketcap stream](https://ide.bitquery.io/arbitrum-token-marketcap-stream) #### Realtime stream arbitrum tokens with marketcap above 1 million Subscribe when `Token.Id` matches Arbitrum (`arbitrum`) and `Supply.MarketCap` > 1,000,000 (USD). ▶️ [Realtime stream arbitrum tokens with marketcap above 1 million](https://ide.bitquery.io/realtime-stream-arbitrum-tokens-with-marketcap-above-1-million) ### Liquidity & Pools #### Realtime liquidity stream This subscription query returns real-time liquidity data for all DEX pools on Arbitrum. You can monitor liquidity changes, pool reserves, and spot prices as trades and liquidity modifications occur across all pools. ▶️ [Realtime liquidity stream](https://ide.bitquery.io/realtime-liquidity-stream_1) #### Realtime liquidity stream of a specific pool This subscription query monitors real-time liquidity changes for a specific DEX pool on Arbitrum. Use this to track liquidity events, pool reserves, and spot prices for a particular pool as they occur. ▶️ [Realtime liquidity stream of a specific pool](https://ide.bitquery.io/realtime-liquidity-stream-of-a-specific-pool) #### Realtime slippage on arbitrum This subscription query returns real-time slippage data for all DEX pools on Arbitrum. You can monitor price impact and liquidity depth as trades occur. ▶️ [Realtime slippage on arbitrum](https://ide.bitquery.io/realtime-slippage-on-arbitrum) ### Transactions #### Arbitrum: Timeboost Auction Transactions in Realtime 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. ▶️ [Arbitrum: Timeboost Auction Transactions in Realtime](https://ide.bitquery.io/Arbitrum-Timeboost-Auction-Transactions-in-Realtime) ### Uniswap #### Latest liquidity changes in uniswap v4 pools This subscription query monitors real-time liquidity changes for all pools in a specific DEX protocol on Arbitrum. Here we have taken example of Uniswap V4. ▶️ [Latest liquidity changes in uniswap v4 pools](https://ide.bitquery.io/latest-liquidity-changes-in-uniswap-v4-pools) #### Real time trades for uniswap v4 arbitrum 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 Arbitrum. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades for uniswap v4 arbitrum](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-arbitrum) ## Optimism ### Trades #### Real time trades for uniswap v4 optimism 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 Optimism. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades for uniswap v4 optimism](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-optimism) #### Realtime optimism dex trades websocket This example uses the chain-specific the Trading cube via `EVM(network: optimism) { the Trading cube }` (pool-side Buy/Sell; see the Trading cube). USD can be weak on thin pools. For trader + USD swap rows, use the stream at the top. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Realtime optimism dex trades websocket](https://ide.bitquery.io/Realtime-optimism-dex-trades-websocket) ### Transfers #### Sender is a particular address Sender is a particular address. Uses the `Transfers` cube. ▶️ [Sender is a particular address](https://ide.bitquery.io/Sender-is-a-particular-address) #### Whale transfers of USDT on optimism The subscription query below fetches the whale transactions on the Optimism network. We have used USDT address `0x94b008aA00579c1307B0EF2c499aD98a8ce58e58` ▶️ [Whale transfers of USDT on optimism](https://ide.bitquery.io/Whale-transfers-of-USDT-on-optimism) ### Price & OHLC #### Price of WETH in terms of USDC on Optimism Provides real-time updates on price of WETH `0x4200000000000000000000000000000000000006` in terms of USD Coin `0x7f5c764cbc14f9669b88837ca1490cca17c31607`, including details about the DEX, market, and order specifics. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Price of WETH in terms of USDC on Optimism](https://ide.bitquery.io/Price-of-WETH-in-terms-of-USDC-on-Optimism) #### Get latest price of WBTC in USD on optimism Retrieves the USD price of a token on Optimism by setting `SmartContract: {is: "0x68f180fcCe6836688e9084f035309E29Bf0A2095"}` . Check the field `PriceInUSD` for the USD value. You can access the query. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Get latest price of WBTC in USD on optimism](https://ide.bitquery.io/Get-latest-price-of-WBTC-in-USD-on-optimism) ## Polygon ### Trades #### Real time trades for uniswap v4 matic 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. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time trades for uniswap v4 matic](https://ide.bitquery.io/Real-time-trades-for-uniswap-v4-matic) #### Realtime matic dex trades websocket Read the Trading cube vs the Trading cube vs Trades cube to understand when to use which cube. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Realtime matic dex trades websocket](https://ide.bitquery.io/Realtime-matic-dex-trades-websocket) ### Transfers #### Sender is a particular address Sender is a particular address. Uses the `Transfers` cube. ▶️ [Sender is a particular address](https://ide.bitquery.io/Sender-is-a-particular-address_2) #### Whale transfers of USDC on matic The subscription query below fetches the whale transactions on the MATIC network. We have used USDC address `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359`. ▶️ [Whale transfers of USDC on matic](https://ide.bitquery.io/Whale-transfers-of-USDC-on-matic) ### Supply & Market Cap #### All trades on Polygon with Price, Marketcap, supply Crypto 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. ▶️ [All trades on Polygon with Price, Marketcap, supply](https://ide.bitquery.io/All-trades-on-Polygon-with-Price-Marketcap-supply) #### Matic token marketcap stream Subscribe to `Tokens` where currency id includes `matic`, with interval duration greater than 1 (second). ▶️ [Matic token marketcap stream](https://ide.bitquery.io/matic-token-marketcap-stream) ### Liquidity & Pools #### 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. ▶️ [Latest Liquidity Changes of Pools in a Specific DEX Protocol - Uniswap V4](https://ide.bitquery.io/Latest-Liquidity-Changes-of-Pools-in-a-Specific-DEX-Protocol---Uniswap-V4_7) #### 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. ▶️ [Realtime Liquidity Stream](https://ide.bitquery.io/Realtime-Liquidity-Stream_5) #### 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. ▶️ [Realtime Liquidity Stream of a Specific Pool](https://ide.bitquery.io/Realtime-Liquidity-Stream-of-a-Specific-Pool_5) #### Realtime slippage on matic 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. ▶️ [Realtime slippage on matic](https://ide.bitquery.io/realtime-slippage-on-matic) ## Trading API ### Trades #### All chains New Trades Stream - Solana, eth, bsc ,base , arbitrum, matic The same `NetworkBid` pattern applies on the Crypto Price API for `Token.NetworkBid` and `Market.NetworkBid` on Tokens and Pairs. ▶️ [All chains New Trades Stream - Solana, eth, bsc ,base , arbitrum, matic](https://ide.bitquery.io/all-chains-New-Trades-Stream---Solana-eth-bsc-base--arbitrum-matic_2) #### All trades of a trader All trades of a trader. Uses the `Trades` cube. Replace the address in the `where` clause to use it. ▶️ [All trades of a trader](https://ide.bitquery.io/All-trades-of-a-trader) #### All wsol Trade Stream All wsol Trade Stream. Uses the `Trades` cube. Replace the address in the `where` clause to use it. ▶️ [All wsol Trade Stream](https://ide.bitquery.io/All-wsol-Trade-Stream) #### How do I get a wallet's trades on a specific pair? Change the `Program` address to target different DEXs — e.g. `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` for Pump.fun. ▶️ [How do I get a wallet's trades on a specific pair?](https://ide.bitquery.io/How-do-I-get-a-wallets-trades-on-a-specific-pair) #### How do I monitor multiple wallets in one subscription? How do I monitor multiple wallets in one subscription?. Uses the `Trades` cube. ▶️ [How do I monitor multiple wallets in one subscription?](https://ide.bitquery.io/How-do-I-monitor-multiple-wallets-in-one-subscription) #### How do I monitor multiple wallets trading a specific token? How do I monitor multiple wallets trading a specific token?. Uses the `Trades` cube. ▶️ [How do I monitor multiple wallets trading a specific token?](https://ide.bitquery.io/How-do-I-monitor-multiple-wallets-trading-a-specific-token) #### How do I stream a wallet's trades on a specific DEX? How do I stream a wallet's trades on a specific DEX?. Uses the `Trades` cube. Replace the address in the `where` clause to use it. ▶️ [How do I stream a wallet's trades on a specific DEX?](https://ide.bitquery.io/How-do-I-stream-a-wallets-trades-on-a-specific-DEX) #### How do I stream a wallet's trades on a specific chain? How do I stream a wallet's trades on a specific chain?. Uses the `Trades` cube. Replace the address in the `where` clause to use it. ▶️ [How do I stream a wallet's trades on a specific chain?](https://ide.bitquery.io/How-do-I-stream-a-wallets-trades-on-a-specific-chain) #### How do I stream whale trades for a specific wallet? Adjust the `gt` threshold — e.g. `10000` for $10K+, `1000000` for $1M+ trades. ▶️ [How do I stream whale trades for a specific wallet?](https://ide.bitquery.io/How-do-I-stream-whale-trades-for-a-specific-wallet) #### How do I track trades for multiple tokens in one subscription? 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. ▶️ [How do I track trades for multiple tokens in one subscription?](https://ide.bitquery.io/How-do-I-track-trades-for-multiple-tokens-in-one-subscription) ### Price & OHLC #### Token price stream from top market (rank 1) Streams the price of one token from its top market, one-second intervals, quoted in USD. Prices the token from its single top market rather than blending every pool, which is what you want for one specific token. ▶️ [Token price stream from top market (rank 1)](https://ide.bitquery.io/Token-price-stream-from-top-market--rank-1) #### FourMeme 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Track token activity (OHLC, price, volume) every 1 second on FourMeme DEX (BSC). ▶️ [FourMeme 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders](https://ide.bitquery.io/FourMeme-DEX-tokens-1-second-price-stream-with-OHLC) #### PumpAMM 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders PumpAMM 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders. Uses the `Pairs` cube. ▶️ [PumpAMM 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders](https://ide.bitquery.io/PumpAMM-tokens-1-second-price-stream-with-OHLC_1) #### Raydium Launchlab 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders Raydium Launchlab 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders. Uses the `Pairs` cube. ▶️ [Raydium Launchlab 1-second Price, OHLC, Volume, SMA, EMA Stream for Traders](https://ide.bitquery.io/Raydium-Launchpad-DEX-tokens-1-second-price-stream-with-OHLC) #### Heaven DEX tokens 1 second price stream with OHLC Real-time (1s) stream of prices, OHLC, and volumes for tokens traded on Heaven DEX (Solana). ▶️ [Heaven DEX tokens 1 second price stream with OHLC](https://ide.bitquery.io/Heaven-DEX-tokens-1-second-price-stream-with-OHLC) #### Meteora DBC DEX tokens 1 second price stream with OHLC Meteora DBC DEX tokens 1 second price stream with OHLC. Uses the `Pairs` cube. ▶️ [Meteora DBC DEX tokens 1 second price stream with OHLC](https://ide.bitquery.io/Meteora-DBC-DEX-tokens-1-second-price-stream-with-OHLC) #### Real Time USD price on solana chain Real Time USD price on solana chain. Uses the `Pairs` cube. ▶️ [Real Time USD price on solana chain](https://ide.bitquery.io/Real-Time-USD-price-on-solana-chain_2) #### 5 minute price change api on solana 5 minute price change api on solana. Uses the `Tokens` cube. ▶️ [5 minute price change api on solana](https://ide.bitquery.io/5-minute-price-change-api-on-solana_6) #### Bitcoin currency price stream Get real-time Bitcoin OHLC data across all chains. ▶️ [Bitcoin currency price stream](https://ide.bitquery.io/bitcoin-currency-price-stream) ### Supply & Market Cap #### All trades of a specific Ethereum token with Price, Marketcap, supply All trades of a specific Ethereum token with Price, Marketcap, supply. Uses the `Trades` cube. ▶️ [All trades of a specific Ethereum token with Price, Marketcap, supply](https://ide.bitquery.io/All-trades-of-a-specific-Ethereum-token-with-Price-Marketcap-supply_1) ### Liquidity & Pools #### Liquidity addition for radium Subscribe to `Solana.DEXPools` with Raydium’s program and positive base change to detect new liquidity deposited into Raydium pools. ▶️ [Liquidity addition for radium](https://ide.bitquery.io/liquidity-addition-for-radium_1) #### Liquidity removal for radium Use the same Raydium program filter with negative `ChangeAmount` on the base side to stream liquidity withdrawals. ▶️ [Liquidity removal for radium](https://ide.bitquery.io/liquidity-removal-for-radium_1) ### Pump.fun #### All Pumpswap Trade Stream All Pumpswap Trade Stream. Uses the `Trades` cube. ▶️ [All Pumpswap Trade Stream](https://ide.bitquery.io/All-Pumpswap-Trade-Stream) #### All pumpfun Trade Stream All pumpfun Trade Stream. Uses the `Trades` cube. ▶️ [All pumpfun Trade Stream](https://ide.bitquery.io/All-pumpfun-Trade-Stream_2) #### Pump fun token live prices using trades api Pump fun token live prices using trades api. Uses the `Trades` cube. ▶️ [Pump fun token live prices using trades api](https://ide.bitquery.io/pump-fun-token-live-prices-using-trades-api_1) ### PancakeSwap #### Real-time Trades on Pancakeswap Streams PancakeSwap v3 trades on BSC from the Trading cube, with USD price and trade size on every row. The previous version streamed every BSC DEX despite its title; this one filters on `pancake_swap_v3`. ▶️ [Real-time Trades on Pancakeswap](https://ide.bitquery.io/Latest-BSC-PancakeSwap-v3-dextrades---Stream) #### PancakeSwap v3 DEX tokens 1 second price stream with OHLC PancakeSwap v3 DEX tokens 1 second price stream with OHLC. Uses the `Pairs` cube. Replace the address in the `where` clause to use it. ▶️ [PancakeSwap v3 DEX tokens 1 second price stream with OHLC](https://ide.bitquery.io/PancakeSwap-v3-DEX-tokens-1-second-price-stream-with-OHLC) ### Uniswap #### 1-second price, OHLC, volume, SMA and EMA — Uniswap v3 One-second candles with moving averages for Uniswap v3 tokens, built for trading front-ends. ▶️ [1-second price, OHLC, volume, SMA and EMA — Uniswap v3](https://ide.bitquery.io/Uniswap-v3-DEX-tokens-1-second-price-stream-with-OHLC) #### Stream all Uniswap Seconds OHLC Kline Subscribe to `Trading.Pairs` filtered by Uniswap protocols and 1s interval to power sub-minute charts and HFT analytics. ▶️ [Stream all Uniswap Seconds OHLC Kline](https://ide.bitquery.io/Stream-all-Uniswap-Seconds-OHLC-Kline) #### Uniswap all versions trades stream Filter the Trading cube with `ProtocolName` in `uniswap_v3`, `uniswap_v2`, `uniswap_v1` to stream only Uniswap family pools on mainnet. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Uniswap all versions trades stream](https://ide.bitquery.io/uniswap-all-versions-trades-stream) ## Stablecoins ### Trades #### Solana trades subscription Streams Solana trades quoted in USDT. USDT is the quote side on Solana, so it is filtered with `Pair.QuoteToken`, not `Pair.Token`. ▶️ [Solana trades subscription](https://ide.bitquery.io/solana-trades-subscription_10_1) #### Stablecoin trades for etheruem Stablecoin trades for etheruem. Uses the `DEXTrades` cube. Change the token address in the `where` clause to use it. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. ▶️ [Stablecoin trades for etheruem](https://ide.bitquery.io/Stablecoin-trades-for-etheruem) #### Stablecoin trades for tron Stablecoin trades for tron. Uses the Trading cube. Change the token address in the `where` clause to use it. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Stablecoin trades for tron](https://ide.bitquery.io/Stablecoin-trades-for-tron) #### Stablecoin Depeg tracking Stream for evm Stablecoin Depeg tracking Stream for evm. Uses the `DEXTradeByTokens` cube. Change the token address in the `where` clause to use it. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. ▶️ [Stablecoin Depeg tracking Stream for evm](https://ide.bitquery.io/Stablecoin-Depeg-tracking-Stream-for-evm) #### Stablecoin Depeg tracking Stream for tron Stablecoin Depeg tracking Stream for tron. Uses the Trading cube. Change the token address in the `where` clause to use it. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Stablecoin Depeg tracking Stream for tron](https://ide.bitquery.io/Stablecoin-Depeg-tracking-Stream-for-tron) #### Stablecoin depeg tracking stream for USDC Below stream will be able to track specific Stablecoin depeg. In this query example, we are tracking depeg for the stablecoin `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` which has a symbol `USDC`. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Stablecoin depeg tracking stream for USDC](https://ide.bitquery.io/stablecoin-depeg-tracking-stream-for-USDC) ### Transfers #### Latest Tron USDT Transfers stream Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest Tron USDT Transfers stream](https://ide.bitquery.io/Latest-Tron-USDT-Transfers-stream) #### Latest USDT/USDC Transfer Stream on BSC Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest USDT/USDC Transfer Stream on BSC](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-Stream-on-BSC) #### Latest USDT/USDC Transfer stream on base Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest USDT/USDC Transfer stream on base](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-stream-on-base) #### Latest USDT/USDC Transfer stream on ethereum Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest USDT/USDC Transfer stream on ethereum](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-stream-on-ethereum) #### Listening to All USDT and USDC Payments on Solana - stream Listening to All USDT and USDC Payments on Solana - stream. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. ▶️ [Listening to All USDT and USDC Payments on Solana - stream](https://ide.bitquery.io/Listening-to-All-USDT-and-USDC-Payments-on-Solana---stream) #### Listening to stablecoin Transfers for Specific Addresse on tron Listen to USDT sent or received by address `TUTQj7VJ1QjR3t2GJByvrP25yZNFcj38VJ`. This is the canonical "merchant/treasury wallet monitor" pattern — fan-out one subscription per wallet and route hits to your payments backend. ▶️ [Listening to stablecoin Transfers for Specific Addresse on tron](https://ide.bitquery.io/Listening-to-stablecoin-Transfers-for-Specific-Addresse-on-tron) #### Stablecoin Realtime Payments Stream on Eth Mainnet Stablecoin Realtime Payments Stream on Eth Mainnet. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. ▶️ [Stablecoin Realtime Payments Stream on Eth Mainnet](https://ide.bitquery.io/Stablecoin-Realtime-Payments-Stream-on-Eth-Mainnet) #### Stablecoin Realtime Transfers Stream on tron Stablecoin Realtime Transfers Stream on tron. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. ▶️ [Stablecoin Realtime Transfers Stream on tron](https://ide.bitquery.io/Stablecoin-Realtime-Transfers-Stream-on-tron) #### Stablecoin transfers websocket Stablecoin transfers websocket. Uses the `Transfers` cube. Change the token address in the `where` clause to use it. ▶️ [Stablecoin transfers websocket](https://ide.bitquery.io/stablecoin-transfers-websocket) #### USDT and USDC token Transfers stream on solana USDT and USDC token Transfers stream on solana. Uses the `Transfers` cube. ▶️ [USDT and USDC token Transfers stream on solana](https://ide.bitquery.io/USDT-and-USDC-token-Transfers-stream-on-solana) ### Balances & Holders #### Real time stablecoin portfolio Below stream will provide you the realtime portfolio updates for a particular address for a specific Stablecoin. In this query example, we are tracking portfolio updates for the address `3i51cKbLbaKAqvRJdCUaq9hsnvf9kqCfMujNgFj7nRKt` and for stablecoin `USDC`. Trading cube - MEV-filtered trades with USD prices on every row. ▶️ [Real time stablecoin portfolio](https://ide.bitquery.io/real-time-stablecoin-portfolio_2) ### Price & OHLC #### Stablecoin 1 sec Price Stream This subscription gives you 1-second OHLC, mean price, averages for all stablecoins including USDC, USDT, DAI, USDS etc. ▶️ [Stablecoin 1 sec Price Stream](https://ide.bitquery.io/stablecoin-1-second-price-stream) #### Stablecoin price stream of USDT Get real-time and historical USDT prices, OHLCV, and moving averages across supported networks and markets. ▶️ [Stablecoin price stream of USDT](https://ide.bitquery.io/stablecoin-price-stream-of-USDT_2) ### Supply & Market Cap #### USDT Stablecoin reserves on Solana USDT Stablecoin reserves on Solana. Uses the `TokenSupplyUpdates` cube. Change the token address in the `where` clause to use it. ▶️ [USDT Stablecoin reserves on Solana](https://ide.bitquery.io/USDT-Stablecoin-reserves-on-Solana) ### Mempool #### Latest Tron USDT Transfers stream in Mempool Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest Tron USDT Transfers stream in Mempool](https://ide.bitquery.io/Latest-Tron-USDT-Transfers-stream-in-Mempool) #### Latest USDT/USDC Transfer Stream on BSC on Mempool Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest USDT/USDC Transfer Stream on BSC on Mempool](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-Stream-on-BSC-on-Mempool) #### Latest USDT/USDC Transfer stream on ethereum in Mempool Listen to stablecoin payments across all major blockchains. The Mempool option lets you detect a payment *before* it is confirmed — useful for instant merchant UX. ▶️ [Latest USDT/USDC Transfer stream on ethereum in Mempool](https://ide.bitquery.io/Latest-USDTUSDC-Transfer-stream-on-ethereum-in-Mempool) ## NFTs ### Trades #### NFT Trades on Opensea This stream allows you to monitor real time NFT trades on OpenSea. It could also be modified to get trades of a particular NFT collection or NFTs traded by a particular trader. Built from raw DEX trades, so it carries per-swap detail the Trading cube normalises away. For a clean USD price feed prefer the Trading cube entries at the top of this section. ▶️ [NFT Trades on Opensea](https://ide.bitquery.io/Latests-OpenSea-Trades--stream) #### Latest Solana NFT Trades Streams the latest Solana NFT trades from the Trading cube, with USD price and trade size on every row. ▶️ [Latest Solana NFT Trades](https://ide.bitquery.io/Latest-Solana-NFT-Trades) ### Transfers #### ERC-721 (NFT) transfers NFT transfers as they are mined, with token IDs. ▶️ [ERC-721 (NFT) transfers](https://ide.bitquery.io/ERC721-token-transfers) #### Subscription WebSocket - Latest NFT Transfers Using Streaming APIs, you can subscribe to real-time changes on blockchains. We use a GraphQL subscription,which function similarly to WebSockets. ▶️ [Subscription WebSocket - Latest NFT Transfers](https://ide.bitquery.io/Subscription-WebSocket---Latest-NFT-Transfers) #### Subscribe to the latest NFT transfers on Solana Let's see an example of NFT token transfers using GraphQL Subscription (Webhook). In the following API, we will be subscribing to all NFT token transfers. ▶️ [Subscribe to the latest NFT transfers on Solana](https://ide.bitquery.io/Subscribe-to-the-latest-NFT-transfers-on-Solana) #### NFT Token Transfers API NFT Token Transfers API. ▶️ [NFT Token Transfers API](https://ide.bitquery.io/NFT-Token-Transfers-API_4) #### Transfers of a particular NFT This query subscribes you to the real time transfers of a specific non-fungible token (NFT) on the Base network. ▶️ [Transfers of a particular NFT](https://ide.bitquery.io/Transfers-of-a-particular-NFT_1) #### Track realtime NFT Transfers of a specific NFT on BSC chain This query subscribes you to the real time non-fungible token (NFT) transfers of a specific nft contract on the BSC network. ▶️ [Track realtime NFT Transfers of a specific NFT on BSC chain](https://ide.bitquery.io/Track-realtime-NFT-Transfers-of-a-specific-NFT-on-BSC-chain) #### Track realtime NFT Transfers on BSC chain Track realtime NFT Transfers on BSC chain. ▶️ [Track realtime NFT Transfers on BSC chain](https://ide.bitquery.io/Track-realtime-NFT-Transfers-on-BSC-chain) #### Websocket for tracking Transfers of a particular NFT websocket This query subscribes you to the real time transfers of a specific non-fungible token (NFT) on the Tron network. ▶️ [Websocket for tracking Transfers of a particular NFT websocket](https://ide.bitquery.io/Websocket-for-tracking-Transfers-of-a-particular-NFT-websocket) #### Real-time-transfer-websocket-for-NFT-token on matic This query subscribes you to the real time transfers of a specific non-fungible token (NFT) on the Matic network. ▶️ [Real-time-transfer-websocket-for-NFT-token on matic](https://ide.bitquery.io/Real-time-transfer-websocket-for-NFT-token-on-matic) ### Balances & Holders #### 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. ▶️ [Stream NFT Balance Updates in Real Time](https://ide.bitquery.io/Stream-NFT-Balance-Updates-in-Real-Time) #### Track Specific NFT Balance Changes Monitor NFT transfers for a specific collection across all transactions. This helps track NFT movements and ownership changes. ▶️ [Track Specific NFT Balance Changes](https://ide.bitquery.io/Track-specific-NFTs-Balance-Changes) ## x402 ### Transfers #### Real-Time Payment Monitoring for x402 Server Real-Time Payment Monitoring for x402 Server. Uses the `Transfers` cube. ▶️ [Real-Time Payment Monitoring for x402 Server](https://ide.bitquery.io/Monitoring-the-latest-payment-to-the-specific-X402-server) #### Real-Time Payment Monitoring for x402 Server on Solana Real-Time Payment Monitoring for x402 Server on Solana. Uses the `Transfers` cube. Replace the address in the `where` clause to use it. ▶️ [Real-Time Payment Monitoring for x402 Server on Solana](https://ide.bitquery.io/Real-Time---Solana-transfers-stream) --- ## Stellar Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/stellar/ Stellar Data - Snowflake, AWS S3, BigQuery from Bitquery cloud datasets using Parquet historical exports for S3, BigQuery, and Snowflake. # Stellar Data Bitquery provides **Stellar blockchain data dumps** in **Parquet format**, 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**. Stellar data is modelled around **ledgers → transactions → operations → effects**, so most topics carry the transaction and operation context alongside the topic-specific fields. ## Available Stellar Topics For Stellar, Bitquery currently provides the following datasets: - **Blocks** – Ledger-level metadata (protocol version, base fee, base reserve, fee pool, total coins) - **Transactions** – Full transaction-level data with fee account, memo, sequence, and time bounds - **Operations** – Operation-level records with source account and operation details - **Payments** – Payment and path-payment operations, including source and destination assets - **Transfers** – Native XLM and issued-asset transfers with sender, receiver, and direction - **Effects** – Ledger effects produced by operations - **Effect Arguments** – Key/value arguments attached to each effect - **Balance Effects** – Account balance changes per asset - **Trade Effects** – DEX trades on the Stellar order book, with buy/sell assets and price - **Claimable Balance Effects** – Claimable balance creation and claiming, with claimant and sponsor - **Liquidity Pool Effects** – Liquidity pool deposits, withdrawals, and share changes - **Liquidity Pool Trade Effects** – Trades executed against liquidity pools ## Sample Stellar Cloud Dataset You can explore schemas and validate your tooling using the **public Stellar sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/Stellar](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/Stellar) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/payments_tx/.parquet ``` **Sample Parquet downloads (public S3)** - **Blocks** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/blocks/55080300_55080349.parquet) - **Transactions** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/transactions/55080300_55080349.parquet) - **Operations** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/operations_tx/55080300_55080349.parquet) - **Payments** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/payments_tx/55080300_55080349.parquet) - **Transfers** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/transfers_tx/55080300_55080349.parquet) - **Trade Effects** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/trade_effects_tx/55080300_55080349.parquet) ## Stellar Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── stellar/ ├── balance_effects_tx/ │ ├── _.parquet │ └── ... ├── blocks/ │ ├── _.parquet │ └── ... ├── claimable_balance_effects/ │ ├── _.parquet │ └── ... ├── effect_arguments_tx/ │ ├── _.parquet │ └── ... ├── effects_tx/ │ ├── _.parquet │ └── ... ├── liquidity_pool_effects/ │ ├── _.parquet │ └── ... ├── liquidity_pool_trade_effects/ │ ├── _.parquet │ └── ... ├── operations_tx/ │ ├── _.parquet │ └── ... ├── payments_tx/ │ ├── _.parquet │ └── ... ├── trade_effects_tx/ │ ├── _.parquet │ └── ... ├── transactions/ │ ├── _.parquet │ └── ... └── transfers_tx/ ├── _.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Example: ``` 55080300_55080349.parquet ``` Here `block` is the Stellar **ledger sequence number**. ### Common Fields Most Stellar topics share the same transaction and operation context columns, which makes joining across topics straightforward: - `block`, `tx_date`, `tx_time` – ledger sequence, date partition, and ledger close time - `tx_hash`, `tx_hash_bin`, `tx_index`, `transaction_index` – transaction identity - `operation`, `op_index`, `operation_index`, `operation_name`, `op_source_account` – operation identity - `effect`, `effect_index`, `order` – effect identity on the effect-based topics - `*_annotation` fields – Bitquery address labels, empty when the address is unlabelled - Asset columns are prefixed per role: `currency_from_*` / `currency_to_*` on payments and transfers, `buy_currency_*` / `sell_currency_*` on trade effects ## Real-Time vs Batch Data Access Cloud data dumps are optimized for **batch analytics and historical workloads**. If you require **low-latency or streaming Stellar data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - **GraphQL subscriptions** --- ## StonkFun API - Solana - New Launches, Trades, Live Prices URL: https://docs.bitquery.io/docs/blockchain/Solana/stonkfun-api/ StonkFun API on Solana: stream StonkFun launches on Raydium LaunchLab, bonding curve progress, graduations, trades, USD prices and OHLC with Bitquery GraphQL. # StonkFun API - Solana - New Launches, Trades, Live Prices :::tip Need real-time StonkFun 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 swaps with **USD price, market cap, and supply on every row**, and [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) / [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) give you ready-made OHLC candles. Use the `DEXTradeByTokens` examples at the end of this page only for **historical StonkFun data older than ~30 days**. ::: [StonkFun](https://www.stonkfun.xyz/) is a Solana launchpad where every new coin is paired with a quote asset of the creator's choice: tokenized stocks such as SPYx, NVDAx and QQQx from [xStocks](/docs/blockchain/Solana/xstocks-api/), pre-IPO tokens from PreStocks such as OPENAI and ANTHROPIC, crypto assets such as ZEC, WBTC and HYPE, SOL, or another StonkFun coin. Since September 2026 new StonkFun launches run on [Raydium LaunchLab](/docs/blockchain/Solana/launchpad-raydium/): the token trades on a bonding curve first and graduates into a [Raydium CPMM](/docs/blockchain/Solana/raydium-cpmm-API/) pool once the curve has raised its target in the quote asset. Before that, every StonkFun launch opened a one-sided [Raydium CLMM](/docs/blockchain/Solana/raydium-clmm-API/) pool directly, and that direct-pool path still shows up on-chain. This page covers both, plus trades, prices, candles, holders and the Burn & Earn buybacks of the platform token STONK. You can also check out our [Raydium LaunchLab API Docs](/docs/blockchain/Solana/launchpad-raydium/), [xStocks API Docs](/docs/blockchain/Solana/xstocks-api/) and [LetsBonk.fun API Docs](/docs/blockchain/Solana/letsbonk-api/), which runs on the same LaunchLab program. :::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. ## How StonkFun works on-chain | What | Address | Notes | | ------------------------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------------------- | | Raydium LaunchLab program | `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` | Bonding-curve launches. `raydium_launchpad` in `Dex.ProtocolName` and `Market.Protocol` | | StonkFun platform config, reward launches | `6BwHHDg3u1854jC8PDLXvR4spTcLNaoBxLJNGC4nTESt` | Token-2022 mints with a 1% or 3% transfer fee, the source of StonkFun's reward payouts | | StonkFun platform config, standard launches | `4E876qZTE9FJMrBzgVtBrSrzz2TLivB5Y5QXPjB4gZL7` | Token-2022 mints without a transfer fee | | Raydium CPMM program | `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C` | Where graduated tokens trade. `raydium_cp_swap` | | CPMM fee config used at graduation | `CRRS5ieQmBrZjWhcj99JuGrT5tyuWDaGAXLXLFjbAtjQ` | 0.25% trade fee tier | | Raydium CLMM program | `CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK` | Direct-pool launches. `amm_v3` | | StonkFun launcher and fee wallet | `5CEbueQnq1Ym2uSSx2xXds3jQAqT1BDnkA59RZobSPAG` | Platform fee wallet of both configs, signs direct-pool launches and Burn & Earn burns | | STONK (platform token) | `6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx` | Used as the example token on this page | | STONK / SPYx pool (CLMM) | `7a8xxAJBELDo6P9dikSYctdw6ce8F4mWr3ahcAD8Ao49` | Used as the example pool on this page | | SPYx (xStocks S&P 500) | `XsoCS1TfEyfFhfvj8EtZ528L3CaKBDBRqRapnBbDF2W` | Most common stock quote asset | Both platform configs carry the name `StonkFun` on-chain and share the same fee settings. The only difference is the launch type: reward launches add a Token-2022 transfer-fee extension to the new mint, standard launches do not. ### Bonding-curve launch on Raydium LaunchLab A launch is one `initialize_with_token_2022` instruction on the LaunchLab program that references a StonkFun platform config. It does the following: 1. Creates the base mint with 1,000,000,000 supply and 6 decimals on the Token-2022 program. Reward launches attach a transfer fee of 100 or 300 basis points. Its authority is `5KXDF6QnqhBj72hDtJNkkpFaQVUfbFXNybMsp3DiK6tD`, the wallet that also sends out StonkFun's reward payouts. 2. Opens a constant-product bonding curve that sells 793,100,000 tokens (79.31% of supply). The graduation target is `total_quote_fund_raising`, expressed in the quote asset's smallest unit. StonkFun converts a fixed dollar target into the quote asset at launch time, so the number differs from launch to launch even for the same quote asset. Read it from the launch instruction instead of hard-coding it. 3. Charges a 1% fee on every curve trade, set by `fee_rate` (10,000 out of 1,000,000) on the platform config and paid in the quote asset. Raydium's 0.25% protocol fee, the RAY buyback share, comes out of that 1% rather than on top of it, and the rest goes to the StonkFun fee wallet. The creator fee rate is 0. On buys the fee comes off the quote amount before the curve math; on sells it comes off the quote amount the curve pays out. 4. Optionally runs the creator's dev buy as a `buy_exact_in` instruction in the same transaction. When the quote vault reaches the target, LaunchLab calls `migrate_to_cpswap`: the remaining 206,900,000 tokens and the raised quote asset seed a Raydium CPMM pool on the 0.25% fee tier. The whole LP position is locked to the platform (`platform_scale` 1,000,000, nothing burned, no creator share), which is how StonkFun keeps earning fees from graduated pools. ### Direct-pool launch on Raydium CLMM The original StonkFun mode mints the token and opens a one-sided Raydium CLMM pool in a single transaction signed by the launcher wallet: 1,000,000,000 supply with 9 decimals, mint and freeze authorities revoked, two one-sided positions holding the full supply (950M + 50M) and an optional dev buy as `swapV2`. There is no curve, no migration and no on-chain graduation, so the pool address never changes. ## Track StonkFun Token Launches on Raydium LaunchLab in Real Time Subscribe to LaunchLab `initialize_with_token_2022` instructions whose accounts include one of the two StonkFun platform configs. `initialize_v2` is included for completeness; it is the variant LaunchLab uses for classic SPL Token mints. `Program.AccountNames` names every account in the instruction, and `Program.Arguments` returns the decoded mint, curve and transfer-fee parameters.
Click to expand GraphQL query ```graphql subscription StonkFunLaunchLabLaunches { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } Method: { in: ["initialize_v2", "initialize_with_token_2022"] } } Accounts: { includes: { Address: { in: [ "6BwHHDg3u1854jC8PDLXvR4spTcLNaoBxLJNGC4nTESt" "4E876qZTE9FJMrBzgVtBrSrzz2TLivB5Y5QXPjB4gZL7" ] } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signature Signer } Instruction { Program { 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 } } } } Accounts { Address IsWritable Token { Mint Owner ProgramId } } } } } } ```
Account positions in the `initialize_with_token_2022` instruction (the same order as `AccountNames`): | Index | Account | | ----- | -------------------------------------------------- | | 0 | Payer | | 1 | Creator | | 2 | LaunchLab global config | | 3 | **StonkFun platform config** (reward or standard) | | 4 | LaunchLab authority | | 5 | **Pool state** (the bonding-curve market address) | | 6 | **Base mint** (the new StonkFun token) | | 7 | **Quote mint** (SPYx, OPENAI, ZEC, SOL, ...) | | 8, 9 | Base and quote vaults | | 10, 11 | Token programs for base and quote | | 12 | System program | | 13 | Event authority | | 14 | LaunchLab program | Arguments worth reading: | Argument | What it holds | | ------------------------------ | -------------------------------------------------------------------------------------------------- | | `base_mint_param` | `decimals`, `name`, `symbol` and metadata `uri` of the new token | | `curve_param` | `supply`, `total_base_sell`, `total_quote_fund_raising` (graduation target) and `migrate_type` (1 = CPMM) | | `vesting_param` | Creator vesting; StonkFun launches use zero | | `transfer_fee_extension_param` | `transfer_fee_basis_points` on reward launches, `null` on standard launches | Unlike the direct-pool launches below, the mints are not sorted by public key: the new token is always the base mint at index 6 and the quote asset is at index 7. ## Bonding Curve Progress of a StonkFun Token `DEXPools` returns the curve reserves after every trade. Because every StonkFun curve sells 793,100,000 of 1,000,000,000 tokens, progress can be computed from the base side without knowing the quote asset: ``` progress % = 100 - ((Base.PostAmount - 206,900,000) * 100 / 793,100,000) ``` Or use the quote side: `Quote.PostAmount` divided by the launch's `total_quote_fund_raising` (after adjusting for the quote asset's decimals). The example uses a live curve pool; bonding-curve pools graduate or go quiet within hours, so take a current `Pool state` address from the launch stream above and swap it in.
Click to expand GraphQL query ```graphql query StonkFunBondingCurveProgress { Solana { DEXPools( where: { Pool: { Market: { MarketAddress: { is: "AX4FJkpEPDeHdSdha5iGvyqnok8AdbjWJMg4u68GKPLh" } } } Transaction: { Result: { Success: true } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Block { Time } Pool { Dex { ProtocolName } Market { MarketAddress BaseCurrency { MintAddress Symbol } QuoteCurrency { MintAddress Symbol } } Base { PostAmount PostAmountInUSD PriceInUSD } Quote { PostAmount PostAmountInUSD } } } } } ```
Change `query` to `subscription` and drop `orderBy` and `limit` to get every reserve update of the curve as it happens. ## Track StonkFun Graduations to Raydium CPMM in Real Time Graduation is a `migrate_to_cpswap` instruction on the LaunchLab program that references the StonkFun platform config. The new CPMM pool is the sixth account and the old curve pool is the eighteenth, so one message gives you the mapping from the bonding curve to the pool where trading continues.
Click to expand GraphQL query ```graphql subscription StonkFunGraduations { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" } Method: { is: "migrate_to_cpswap" } } Accounts: { includes: { Address: { in: [ "6BwHHDg3u1854jC8PDLXvR4spTcLNaoBxLJNGC4nTESt" "4E876qZTE9FJMrBzgVtBrSrzz2TLivB5Y5QXPjB4gZL7" ] } } } } Transaction: { Result: { Success: true } } } ) { Block { Time } Transaction { Signature } Instruction { Program { Method AccountNames } Accounts { Address Token { Mint ProgramId } } } } } } ```
Account positions in `migrate_to_cpswap`: | Index | Account | | ----- | ----------------------------------------- | | 0 | Payer | | 1 | Base mint (the StonkFun token) | | 2 | Quote mint | | 3 | StonkFun platform config | | 4 | Raydium CPMM program | | 5 | **New CPMM pool** (the market address after graduation) | | 6 | CPMM authority | | 7 | CPMM LP mint | | 8, 9 | CPMM base and quote vaults | | 10 | CPMM fee config | | 11 | CPMM create-pool fee account | | 12 | CPMM observation state | | 13, 14, 15 | LP lock program, lock authority, locked LP vault | | 16 | LaunchLab authority | | 17 | **Bonding-curve pool state** being migrated | ## Latest StonkFun Trades using the Trading API StonkFun pools are ordinary Raydium pools, so the cleanest way to get their trades is the [Trading cube](/docs/trading/trading-data-overview). Every row already carries the USD price and market cap of the token at the time of the trade, and router hops from Jupiter or DFlow are attributed to the pool they hit, so nothing is double counted. The query below returns the latest trades quoted in SPYx across the three programs StonkFun uses. `Market.Protocol` tells you which stage the token is in: `raydium_launchpad` for bonding-curve trades, `raydium_cp_swap` for graduated pools and `amm_v3` for direct-pool launches. Swap the `QuoteToken.Address` for any other quote asset listed on StonkFun (NVDAx, OPENAI, ZEC, STONK itself) to follow that segment. Keep a `Block.Time` window on program-wide queries; without one the scan across all Raydium pools can time out.
Click to expand GraphQL query ```graphql query LatestStonkFunTrades { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } Program: { in: [ "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj" "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C" "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK" ] } } QuoteToken: { Address: { is: "XsoCS1TfEyfFhfvj8EtZ528L3CaKBDBRqRapnBbDF2W" } } } Block: { Time: { since_relative: { hours_ago: 6 } } } } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Block { Time } Side Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Supply { MarketCap } Trader { Address } Pair { Token { Symbol Name Address } QuoteToken { Symbol Address } Market { Address Program Protocol Network } } TransactionHeader { Hash } } } } ```
Note that in `Trading.Trades`, `Price` and `PriceInUsd` are plain float fields with no sub-selection, and `Side` is a string (`Buy` or `Sell`). To get trades in real time, change `query` to `subscription` and remove the `orderBy`, `limit` and `Block.Time` arguments. The same can be tracked using [Bitquery Kafka Streams](/docs/streams/kafka-streaming-concepts/). ## Latest Trades of a Specific StonkFun Token To follow one token, filter on `Pair.Token.Address` (the mint) or on `Pair.Market.Address` (the pool). Filtering by pool is the exact equivalent of the chart on the StonkFun token page. For a bonding-curve token, use the `Pool state` address before graduation and the new CPMM pool address after it, or filter by mint only to get both.
Click to expand GraphQL query ```graphql query LatestTradesOfStonkFunToken { Trading { Trades( where: { Pair: { Token: { Address: { is: "6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx" } } Market: { Address: { is: "7a8xxAJBELDo6P9dikSYctdw6ce8F4mWr3ahcAD8Ao49" } } } } orderBy: { descending: Block_Time } limit: { count: 50 } ) { Block { Time } Side Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Supply { MarketCap } Trader { Address } TransactionHeader { Hash } } } } ```
## Latest Price and Market Cap of a StonkFun Token [`Trading.Tokens`](/docs/trading/crypto-price-api/tokens) aggregates every pool of a token into one USD price series, which matters for STONK because it now trades in SOL pools on other DEXs as well as in its own SPYx pool. The one-minute interval with `limit: 1` gives you the latest price, volume and market cap in a single row.
Click to expand GraphQL query ```graphql query LatestStonkFunTokenPrice { Trading { Tokens( where: { Token: { Address: { is: "6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx" } } Interval: { Time: { Duration: { eq: 60 } } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Block { Time } Token { Symbol Name Address } Price { Ohlc { Close } IsQuotedInUsd } Volume { Usd } Supply { MarketCap CirculatingSupply TotalSupply } } } } ```
To stream price updates, change `query` to `subscription` and remove `orderBy` and `limit`. ## OHLC Candles of a StonkFun Token (Trading API) The same cube serves candles at 1, 3, 5, 10, 30 and 60 seconds and at 5, 15, 30 and 60 minutes. Set `Interval.Time.Duration` in seconds. The example returns hourly candles for the last two days.
Click to expand GraphQL query ```graphql query StonkFunTokenOHLC { Trading { Tokens( where: { Token: { Address: { is: "6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx" } } Interval: { Time: { Duration: { eq: 3600 } } } Block: { Time: { since_relative: { hours_ago: 48 } } } } orderBy: { descending: Block_Time } limit: { count: 48 } ) { Block { Time } Interval { Time { Start End Duration } } Price { Ohlc { Open High Low Close } Average { Mean } IsQuotedInUsd } Volume { Usd Base } } } } ```
## OHLC Candles of a StonkFun Pool [`Trading.Pairs`](/docs/trading/crypto-price-api/pairs) gives candles per pool, with volume in both the token and the quote asset. Use it when you want the STONK / SPYx chart specifically rather than the token-wide price, or the chart of one bonding curve.
Click to expand GraphQL query ```graphql query StonkFunPoolOHLC { Trading { Pairs( where: { Market: { Address: { is: "7a8xxAJBELDo6P9dikSYctdw6ce8F4mWr3ahcAD8Ao49" } } Interval: { Time: { Duration: { eq: 300 } } } Block: { Time: { since_relative: { hours_ago: 6 } } } } orderBy: { descending: Block_Time } limit: { count: 72 } ) { Block { Time } Interval { Time { Start End Duration } } Token { Symbol Address } QuoteToken { Symbol Address } Price { Ohlc { Open High Low Close } IsQuotedInUsd } Volume { Usd Base Quote } } } } ```
## Top Traders of a StonkFun Token Aggregate `Trading.Trades` by trader to rank the most active wallets over a time window. `AmountsInUsd_Base` is the USD value of the StonkFun token side of each trade, and `Side` is the trader's own action, so the buy and sell splits are labelled from the wallet's point of view.
Click to expand GraphQL query ```graphql query TopStonkFunTraders { Trading { Trades( where: { Pair: { Token: { Address: { is: "6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx" } } Market: { Network: { is: "Solana" } } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descendingByField: "volumeUsd" } limit: { count: 100 } ) { Trader { Address } volumeUsd: sum(of: AmountsInUsd_Base) boughtUsd: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) soldUsd: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) trades: count } } } ```
## Liquidity of a StonkFun Pool `DEXPools` returns the pool reserves after every liquidity change or trade. `Base` and `Quote` follow the pool's own ordering; for STONK / SPYx the base is SPYx and the quote is STONK. The same query works for a bonding-curve pool (it returns the curve reserves) and for the CPMM pool after graduation.
Click to expand GraphQL query ```graphql query StonkFunPoolLiquidity { Solana { DEXPools( where: { Pool: { Market: { MarketAddress: { is: "7a8xxAJBELDo6P9dikSYctdw6ce8F4mWr3ahcAD8Ao49" } } } Transaction: { Result: { Success: true } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { Block { Time } Pool { Dex { ProtocolName } Market { BaseCurrency { MintAddress Symbol } QuoteCurrency { MintAddress Symbol } } Base { PostAmount PostAmountInUSD PriceInUSD } Quote { PostAmount PostAmountInUSD } } } } } ```
## Top Holders of a StonkFun Token
Click to expand GraphQL query ```graphql query StonkFunTopHolders { Solana { BalanceUpdates( where: { BalanceUpdate: { Currency: { MintAddress: { is: "6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx" } } } } orderBy: { descendingByField: "BalanceUpdate_Holding_maximum" } limit: { count: 100 } ) { BalanceUpdate { Account { Address Owner } Holding: PostBalance(maximum: Block_Slot) Currency { Symbol } } } } } ```
## Track StonkFun Burn & Earn Buybacks StonkFun sweeps trading fees, buys tokens and burns them from the launcher wallet. STONK is burned every few minutes, and the program also buys and burns the platform's largest tokens by market cap. Each burn lowers the supply, so the whole buyback history is one `TokenSupplyUpdates` query filtered on the launcher wallet as signer. Add a `Currency.MintAddress` filter to follow STONK alone, and change `query` to `subscription` to get each burn as it happens.
Click to expand GraphQL query ```graphql query StonkFunBurns { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { Amount: { lt: "0" } } Transaction: { Signer: { is: "5CEbueQnq1Ym2uSSx2xXds3jQAqT1BDnkA59RZobSPAG" } Result: { Success: true } } } orderBy: { descending: Block_Time } limit: { count: 100 } ) { Block { Time } Transaction { Signature } TokenSupplyUpdate { Amount PostBalance Currency { Symbol MintAddress Decimals } } } } } ```
## Track Direct-Pool StonkFun Launches on Raydium CLMM The original StonkFun launch mode is a Raydium CLMM `create_customizable_pool` instruction signed by the StonkFun launcher wallet, and these launches still appear alongside the bonding-curve ones. Our decoder does not name this instruction, so `Program.Method` is empty for it; filter on the instruction data prefix `2B44D4A7592FA401` (the instruction discriminator) together with the launcher wallet as `Transaction.Signer`. The pool address is the third account in the `Accounts` array. The two mints are the fourth and fifth accounts, ordered by public key, so the new token can be in either slot: the new token is the mint whose `Token.Owner` and metadata were created in the same signature, and the other one is the quote asset.
Click to expand GraphQL query ```graphql subscription StonkFunDirectPoolLaunches { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK" } } Data: { startsWith: "2B44D4A7592FA401" } } Transaction: { Signer: { is: "5CEbueQnq1Ym2uSSx2xXds3jQAqT1BDnkA59RZobSPAG" } Result: { Success: true } } } ) { Block { Time } Transaction { Signature Signer } Instruction { Data Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { Address Name Method } } } } } ```
Account positions in the `create_customizable_pool` instruction: | Index | Account | | ----- | ----------------------------------------- | | 0 | Pool creator (StonkFun launcher wallet) | | 1 | Raydium amm config (fee tier) | | 2 | **Pool state** (the market address) | | 3 | Token mint 0 | | 4 | Token mint 1 | | 5, 6 | Token vaults 0 and 1 | | 7 | Observation state | | 8 | Tick array bitmap | | 9, 10 | Token programs for mint 0 and mint 1 | | 11 | System program | | 12 | Rent sysvar | To catch the creator's dev buy, subscribe to `swapV2` instructions on the same program and match on `Transaction.Signature`. The `Instructions` cube is real-time only and keeps a short window of history, with no archive dataset. For launches older than that, take the first trade of each pool from the `DEXTradeByTokens` archive instead. ## Historical StonkFun Data older than 30 days For history beyond the Trading cube window, use `DEXTradeByTokens` on the `combined` dataset. Always filter on the pool's `MarketAddress` so that aggregator hops and pools where the token is used as a quote asset are excluded; otherwise a token-level sum overstates volume. For a graduated token, run the query once for the bonding-curve pool and once for the CPMM pool. ### Daily Volume of a StonkFun Pool since Launch
Click to expand GraphQL query ```graphql query StonkFunDailyVolume { Solana(dataset: combined) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx" } } Market: { MarketAddress: { is: "7a8xxAJBELDo6P9dikSYctdw6ce8F4mWr3ahcAD8Ao49" } } } Block: { Time: { since: "2026-07-23T00:00:00Z" } } } orderBy: { ascending: Block_Date } limit: { count: 365 } ) { Block { Date } trades: count volumeUsd: sum(of: Trade_Side_AmountInUSD) priceUsd: median(of: Trade_PriceInUSD) } } } ```
### Historical Hourly OHLC of a StonkFun Pool
Click to expand GraphQL query ```graphql query StonkFunHistoricalOHLC { Solana(dataset: combined) { DEXTradeByTokens( where: { Trade: { Currency: { MintAddress: { is: "6GmAFSYs4gk3FDao5FzzySQpPZaWsa4rUJHacpMpUNgx" } } Market: { MarketAddress: { is: "7a8xxAJBELDo6P9dikSYctdw6ce8F4mWr3ahcAD8Ao49" } } } Block: { Time: { since: "2026-07-23T00:00:00Z" } } } orderBy: { descendingByField: "Block_Timefield" } limit: { count: 1000 } ) { Block { Timefield: Time(interval: { count: 1, in: hours }) } Trade { open: PriceInUSD(minimum: Block_Slot) high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) close: PriceInUSD(maximum: Block_Slot) } volumeInUSD: sum(of: Trade_Side_AmountInUSD) count } } } ```
--- ## Subscribe to Real-Time Blockchain Data URL: https://docs.bitquery.io/docs/start/getting-updates/ Subscribe to Real-Time Blockchain Data: practical Bitquery setup guidance with examples for authentication, endpoints, and first queries. # Subscribing to Real-Time Data After you have created and successfully run [your first query](/docs/start/first-query), it is time to get updates on the new data coming. It is just as easy as replacing "query" with "subscription" on the first line in the editor. Here, we will edit the query to use the BSC network so that it will now read as: ```graphql subscription RealTimeBlocks { EVM(network: bsc) { Blocks { Block { Number } } } } ``` The run button now again becomes green. But now, when you press it, you will not immediately get results, as it will wait for a new block to be formed. In the BSC network, blocks typically come in 3-4 seconds. Hence, you will see this sequence after some time on the result panel: > Query used: [Real Time Blocks Subscription | BSC](https://ide.bitquery.io/Real-Time-Blocks-Subscription--BSC) To stop updates, press the run button again. :::caution Resources usage Please note that as long as data is being received, the box on the right will continue to populate, which has no text limit, so make sure you don't waste your resources! ::: Read more about subscriptions and creating websockets [here](/docs/subscriptions/subscription/) --- ## Subscribing to Mempool Updates URL: https://docs.bitquery.io/docs/subscriptions/mempool-subscriptions/ Subscribing to Mempool Updates using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Subscribing to Mempool Updates The Mempool API allows you to access real-time data from the mempool for EVM chains including Ethereum, and BNB chains. You can use this API to monitor transactions, token trades, transfers, and any data stored in the mempool. Check examples [in this page](/docs/blockchain/Ethereum/mempool/mempool-api/). ## Understanding Mempool Queries When querying the mempool using the parameter `mempool: true`, it's important to know that the results do not directly reflect the live state of the mempool. Instead, this query returns transactions that have been broadcasted but may already be included in confirmed blocks. Therefore, use subscription to get Mempool data. ## What distinguishes mempool from standard on-chain data subscription Mempool subscriptions differ from regular subscriptions. This subscription involves a stream of broadcasted transactions, differing from standard on-chain data subscriptions in various aspects: - Transactions arrive in a random sequence. - Each transaction appears only once, even if the transaction has been broadcasted multiple times. - The `mempool:true` query showcases broadcasted transactions upto past hour and not earlier than that. - When using TX time (transaction time), remember it's exclusive to mempool queries, not standard ones. ### Advanced Query Strategies To distinguish between pending and confirmed transactions, use a two-step approach combining `mempool: true` for unconfirmed transactions and `mempool: false` for confirmed ones. ```graphql subscription { confirmed: EVM(mempool: false) { Transactions { Block { Time Number } Transaction { Hash Cost To From } } } } ``` Mempool Transactions ```graphql subscription { mempool_transactions: EVM(mempool: true) { Transactions { Block { Time Number } Transaction { Hash Cost To From } } } } ``` --- ## Subscription on Aggregated Metrics URL: https://docs.bitquery.io/docs/graphql/capabilities/subscription_aggregates/ Subscription on Aggregated Metrics in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Subscription on Aggregated Metrics It is a subscription to the results of [Query Aggregated Metrics](/docs/graphql/capabilities/aggregated_metrics). Query can be converted to subscription by replacing ```query``` word with ```subscription```. With every new block the aggregate will be calculated over the new data and **update** to the aggregates will be sent as a result. Note that in this case you will not get the re-calculation of the whole query, but the update to the previously calculated aggregate. This subscription is appropriate when: 1. application is not capable to process raw stream of the data; 2. the new data is used to be displayed or used inside the application in an aggregated form. --- ## Subscription on Facts URL: https://docs.bitquery.io/docs/graphql/capabilities/subscription_facts/ Subscription on Facts in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Subscription on Facts It is a subscription to the results of [Query Fact Records](/docs/graphql/capabilities/query_fact_records). Query can be converted to subscription by replacing ```query``` word with ```subscription```. Every new block on the blockchain will send the data to this subscription if it contains the data for the query. It can be one or more records. If the block does not contain data that you query, it will not trigger the results. This subscription is appropriate when: 1. application is capable to process raw stream of the data; 2. minimum delay required between the data in the blockchain and the application; 3. notification is required on trigger, defined on some specific conditions. --- ## Supply Fields Reference URL: https://docs.bitquery.io/docs/trading/crypto-price-api/supply-fields/ Supply Fields Reference via Bitquery Trading APIs for multi-chain prices, OHLC candles, volume metrics, and live streams. # Supply fields reference The **`Supply`** object appears on the **Tokens**, **Currency**, and **Pairs** cubes with the same field names. Values describe the **underlying asset** (**currency**), not a specific pool or DEX pair. - On **Tokens** and **Pairs**, **price** and **volume** on the row are **chain- or pair-specific**; **`Supply`** is still **currency-level** (aggregated for the asset across the platform’s reference data). - On **Currency**, price and volume are already aggregated across chains and representations; **`Supply`** uses the same currency-level semantics. For how **prices** and **volumes** are computed from trades, see the [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). ## Field definitions Amounts below are **human-readable token units** (not raw integer amounts with decimals applied on-chain), unless your client or tooling documents otherwise. ### `CirculatingSupply` An estimate of the number of tokens **available to the market** (public float), from CryptoRank. - Often **unavailable** for assets CryptoRank does not cover well (e.g. many meme tokens). - May be **null** when a reliable circulating figure is not available. **Circulating supply** and **max supply** coverage is available for assets that trade on **CEXs**; many **meme tokens** and thinly covered assets may **not** have these supply figures, so those fields are often missing for those names. ### `TotalSupply` The **total issued supply** of the asset as represented in reference data taken from on-chain **total supply**. May differ from **circulating** when a large portion is not treated as circulating. ### `MaxSupply` The **maximum supply cap** for the asset. For assets **without** a fixed cap, or when CryptoRank has no figure, this field is typically 0. Often **unavailable** for the same asset classes as **circulating supply** (e.g. many meme tokens). ### `MarketCap` **Market capitalization in USD**, usually **price × circulating supply** when **circulating supply** is known (using the currency-level figure and the Price Index USD price for that row). When **circulating supply** is **unknown**, **`MarketCap` equals `FullyDilutedValuationUsd`** (see below). ### `FullyDilutedValuationUsd` **Fully diluted valuation in USD**, computed as **`TotalSupply` x the currency-level USD price** (`Price.Average.Estimate`). When **circulating supply** is **unknown**, we set **`FullyDilutedValuationUsd` to the same value as `MarketCap`** (so both fields carry the same fallback valuation). :::note `MaxSupply` is not used in either valuation `MaxSupply` is reference data only — it is **not** the multiplier for FDV, and it is `0` for the large majority of currencies, which is why it cannot be. Both valuations are driven by `TotalSupply` / `CirculatingSupply` and `Price.Average.Estimate`. ::: ## Supply is a currency-level figure, repeated on every row This is the most important thing to know about the whole block. `Supply` is **one currency-level reference figure**. It is byte-identical on every token representation of that currency, on every pool of that token, and on the `Currencies` row — it is not computed per row. Consequences: - On a **`Pairs`** row, `MarketCap` and `FullyDilutedValuationUsd` are that currency-level valuation copied down verbatim. They are **not** derived from the row's own `Price.Ohlc.Close`, so a pool trading away from the blended price still reports the same market cap as every other pool of that token. - On **`Currencies`**, the figure is neither summed across chains nor taken from a top-ranked chain. It is the same single number. :::danger Summing MarketCap across rows double-counts Because the same valuation is repeated on every token representation and every pool, a `sum(of: Supply_MarketCap)` across a currency's rows multiplies it by the row count. Take `maximum:` or read one row instead. ::: :::caution Two ways a Supply figure can look wrong - The reference figure **refreshes in steps**, so rows a few seconds apart can carry slightly different values. Do not treat small differences as a data error. - `Trading.Tokens` can return a duplicate row for the same token and bar in which `Token.Symbol` is empty and **every `Supply` field is `0`** — a metadata-arrival split on freshly launched tokens. Filter those out before valuing anything. See [tokens.md](/docs/trading/crypto-price-api/tokens#identity-fields). ::: ## Bitcoin (`bid:bitcoin`) and on-chain supply For **Bitcoin**, the **`Supply`** block on **`Tokens`** rows describes **on-chain supply of wrapped and bridged BTC** (for example WBTC on Ethereum), **not** native Bitcoin UTXO supply on the Bitcoin network. **Native BTC does not exist as a single token contract** on EVM (and similar) chains the way ERC-20s do, so any **`TotalSupply`**-style figure in this API is tied to **those on-chain representations**. That is why you **do not** see **~21 million** in **`TotalSupply`** for a Bitcoin currency query: **21M** is the **network-level** cap for Bitcoin itself, while **`Supply` here** reflects **how much wrapped BTC is tracked on the chain(s)** backing that token row. ```graphql {Trading { Tokens( where: { Currency: { Id: { is: "bid:bitcoin" } } 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 } } Volume { Base Quote Usd } Price { IsQuotedInUsd Ohlc { Close High Low Open } Average { ExponentialMoving Mean SimpleMoving WeightedSimpleMoving } } Supply { TotalSupply MarketCap FullyDilutedValuationUsd } } } } ``` --- ## Supported Blockchains and Networks URL: https://docs.bitquery.io/docs/blockchain/supported-chains/ See which blockchains Bitquery supports across V1, V2 GraphQL, Kafka, gRPC, ClickHouse Cloud, and Parquet exports. Keep queries fast with indexed filters. # Supported blockchains & networks This guide lists **which blockchains Bitquery indexes** and how that lines up with each **delivery interface** on **[bitquery.io](https://bitquery.io/)**: legacy **[V1 GraphQL](https://docs.bitquery.io/v1/)** (broad catalog—schema reference), **[Data streams & GraphQL](https://bitquery.io/products/data-streams)** and **[WebSocket streams](https://bitquery.io/products/websocket-streams)** for real time, **[Kafka streams](https://bitquery.io/products/kafka-streams)** (protobuf), **[Solana gRPC (CoreCast)](https://bitquery.io/products/solana-grpc-streams)**, **[ClickHouse data warehouse](https://bitquery.io/products/data-warehouse)** with **[MCP server](https://bitquery.io/products/bitquery-mcp-server)** for AI clients, and **[cloud datashares & exports](https://bitquery.io/products/streaming)** (S3, Snowflake, BigQuery, and more). Major networks include **Bitcoin**, **Ethereum**, **Solana**, **BNB Chain**, **Polygon**, **Tron**, **Base**, **Arbitrum**, **Optimism**, and **Cardano**, plus additional L1s in the [matrix below](#supported-chains-matrix)—always validate your plan, entitlement, and live **[GraphQL IDE](https://ide.bitquery.io/)** before shipping. **Legend:** ✓ = included in this product line’s chain catalog below. **—** = not listed in that line’s default set (other Bitquery products or plans may still apply—ask support). --- ## Matrix: chain × product {#supported-chains-matrix} **ClickHouse replica:** SQL over Bitquery’s **[managed ClickHouse data warehouse](https://bitquery.io/products/data-warehouse)**—dedicated clusters with read replicas and real-time ingestion across **40+ chains** (see product page for full positioning). **Chain coverage for your project matches the catalog below** (aligned with cloud-style exports), with **tables and schema** depending on entitlement; for **AI assistants**, use the **[Bitquery MCP server](https://bitquery.io/products/bitquery-mcp-server)** ([technical setup](/docs/mcp/mcp-server/)). | Network | V1 GraphQL | V2 GraphQL / WebSocket | Kafka (protobuf) | Cloud (Parquet / datasets) | ClickHouse replica | |---------|:----------:|:----------------------:|:----------------:|:--------------------------:|:------------------:| | Bitcoin | ✓ | — | ✓ | ✓ | ✓ | | Litecoin | ✓ | — | — | ✓ | ✓ | | Bitcoin Cash | ✓ | — | — | ✓ | ✓ | | Zcash | ✓ | — | — | ✓ | ✓ | | Dash | ✓ | — | — | ✓ | ✓ | | Ethereum | ✓ | ✓ | ✓ | ✓ | ✓ | | BNB Chain (BSC) | ✓ | ✓ | ✓ | ✓ | ✓ | | Avalanche | ✓ | — | — | ✓ | ✓ | | Klaytn | ✓ | — | — | ✓ | ✓ | | Tron | ✓ | ✓ | ✓ | ✓ | ✓ | | Celo | ✓ | — | — | ✓ | ✓ | | Algorand | ✓ | — | — | ✓ | ✓ | | Cronos | ✓ | — | — | ✓ | ✓ | | Solana | ✓ | ✓ | ✓ | ✓ | ✓ | | Cardano | ✓ | — | — | ✓ | ✓ | | Polygon | ✓ | ✓ | ✓ | ✓ | ✓ | | Filecoin | ✓ | — | — | ✓ | ✓ | | Ripple (XRP) | ✓ | — | — | ✓ | ✓ | | Stellar | ✓ | — | — | ✓ | ✓ | | Arbitrum | — | ✓ | ✓ | ✓ | ✓ | | Optimism | — | ✓ | ✓ | ✓ | ✓ | | Base | — | ✓ | ✓ | ✓ | ✓ | | Robinhood | — | ✓ | ✓ | ✓ | ✓ | :::note More networks **V1** historically covers **40+** blockchains—see the [V1 docs](https://docs.bitquery.io/v1/) for the full, schema-accurate list and **[Bitquery platform](https://bitquery.io/)** for plans. **V2** may also expose additional networks in the IDE (for example **opBNB**, **TON**) that are not repeated in the short list above—check live schema and [chain docs](/docs/blockchain/introduction/). **Kafka** also exposes multi-chain **`trading.prices`** and **`trading.trades`** topics—see **[Kafka streams](https://bitquery.io/products/kafka-streams)** and [Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/). ::: --- ## gRPC (CoreCast) **Solana only** — filtered protobuf streams to `corecast.bitquery.io`. Not multi-chain. - [Solana gRPC streams (product)](https://bitquery.io/products/solana-grpc-streams) · [CoreCast docs](/docs/grpc/solana/introduction/) --- ## Where to read more | Product | Get started | |--------|-------------| | **V2** | [Bitquery platform](https://bitquery.io/) · [Data streams](https://bitquery.io/products/data-streams) · [WebSocket streams](https://bitquery.io/products/websocket-streams) · Docs: [Intro](/docs/intro/) · Chains: [Ethereum](https://bitquery.io/blockchains/ethereum-blockchain-api), [BNB Chain](/docs/blockchain/BSC/), [Arbitrum](https://bitquery.io/blockchains/arbitrum-blockchain-api), [Optimism](https://bitquery.io/blockchains/optimism-blockchain-api), [Base](https://bitquery.io/blockchains/base-blockchain-api), [Polygon](https://bitquery.io/blockchains/polygon-blockchain-api), [Solana](https://bitquery.io/blockchains/solana-blockchain-api), [Tron](https://bitquery.io/blockchains/tron-blockchain-api), [Robinhood](/docs/blockchain/robinhood/) | | **V1** | [Bitquery platform](https://bitquery.io/) · [V1 documentation](https://docs.bitquery.io/v1/) · [V1 vs V2 (IDE & schema)](https://docs.bitquery.io/v1/docs/graphql-ide/v1-and-v2) | | **Kafka** | [Kafka streams](https://bitquery.io/products/kafka-streams) · [Real-time streaming hub](https://bitquery.io/products/streaming) · Docs: [Streams overview](/docs/streams/) · [Kafka concepts](/docs/streams/kafka-streaming-concepts/) | | **Cloud** | [Streaming & datashares](https://bitquery.io/products/streaming) · Docs: [Cloud data](/docs/cloud/) · [EVM](/docs/cloud/evm/) · [Solana](/docs/cloud/solana/) · [Bitcoin](/docs/cloud/bitcoin/) · [Tron](/docs/cloud/tron/) | | **ClickHouse replica** | [ClickHouse data warehouse](https://bitquery.io/products/data-warehouse) · [MCP server](https://bitquery.io/products/bitquery-mcp-server) · [MCP docs](/docs/mcp/mcp-server/) | --- ## See also - [ClickHouse data warehouse](https://bitquery.io/products/data-warehouse) — fully managed clusters, replicas, and real-time ingestion - [Data streams & Kafka / WebSocket / gRPC](https://bitquery.io/products/data-streams) - [Blockchain data APIs overview](/docs/blockchain/introduction/) - [gRPC vs WebSocket vs Kafka](/docs/streams/) (docs) --- ## TRC20 USDT API - Transfers, Holders & Flows URL: https://docs.bitquery.io/docs/blockchain/Tron/usdt-trc20-api/ Query and stream USDT TRC20 on Tron with Bitquery GraphQL: live transfers, whale holders, exchange deposit flows, mempool, and cross-chain USDT comparison. # TRC20 USDT API Tron carries more USDT transfer activity than any other chain, which makes TRC20 USDT the single most-queried asset in the Bitquery Tron dataset. This page covers the queries people actually need: live transfer and DEX-trade streams, whale holders, exchange deposit flows, mempool visibility, and a cross-chain comparison. Every example uses the canonical USDT TRC20 contract: ``` TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t ``` :::tip Looking for USDT beyond Tron? This page is Tron-specific. For USDT price, payments, reserves and balances **across all supported chains**, see the [USDT Stablecoin API](/docs/stablecoin-APIs/usdt-api) and the broader [stablecoin API pages](/docs/category/stablecoin-apis). A single-request cross-chain comparison is included [below](#cross-chain). ::: ## Tether USD (USDT) transfers in real time To monitor USDT transfers on Tron in real time, use the following subscription. You can run the query [here](https://ide.bitquery.io/usdt-trc20-transfers_1) ```graphql subscription { Tron { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}}} ) { Transaction { Hash } Transfer { Amount Sender Receiver Currency { SmartContract Symbol Name Fungible Native } Id AmountInUSD } Block { Number } } } } ``` ## Daily USDT TRC20 transfer volume {#daily-volume} Daily transfer volume, transfer count and unique-address counts. Useful for stablecoin reports, market analytics and macro dashboards. Using `since_relative` instead of a fixed timestamp keeps the query correct whenever it runs — a hardcoded date silently widens the window every day it sits in your codebase. Run the query [here](https://ide.bitquery.io/daily-usdt-trc20-volume). ```graphql query DailyUSDTVolumeTron { Tron { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" } } } Block: { Time: { since_relative: { days_ago: 30 } } } TransactionStatus: { Success: true } } orderBy: { ascendingByField: "Block_Date" } ) { Block { Date(interval: { count: 1, in: days }) } transfers: count senders: uniq(of: Transfer_Sender) receivers: uniq(of: Transfer_Receiver) volume_usdt: sum(of: Transfer_Amount) volume_usd: sum(of: Transfer_AmountInUSD) } } } ``` `TransactionStatus: { Success: true }` matters here — without it, reverted transfers inflate both the count and the volume. ## Largest USDT transfers (whale movements) {#whale-transfers} Single transfers above a threshold, largest first. This is the fastest way to spot treasury moves, exchange rebalancing and OTC settlement. ```graphql query LargestUSDTTransfers($min_amount: String, $since: DateTime) { Tron { Transfers( limit: { count: 25 } orderBy: { descending: Transfer_Amount } where: { Transfer: { Currency: { SmartContract: { is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" } } Amount: { ge: $min_amount } } Block: { Time: { since: $since } } TransactionStatus: { Success: true } } ) { Block { Time } Transaction { Hash } Transfer { Amount Sender Receiver } } } } ``` ```json { "min_amount": "1000000", "since": "2026-01-01T00:00:00Z" } ``` ## Top USDT receivers — finding exchange deposit addresses {#top-receivers} Aggregating inbound transfers per receiver surfaces the busiest USDT destinations on Tron. Read two fields together and the address type becomes obvious: - **High `inbound` count and high `distinct_senders`** → an exchange hot wallet or payment processor. Many unrelated parties paying one address. - **High `received` but only a handful of senders** → a treasury, bridge or OTC desk. Few counterparties, large amounts. ```graphql query TopUSDTReceivers($since: DateTime) { Tron { Transfers( limit: { count: 50 } orderBy: { descendingByField: "received" } where: { Transfer: { Currency: { SmartContract: { is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" } } } Block: { Time: { since: $since } } TransactionStatus: { Success: true } } ) { Transfer { Receiver } received: sum(of: Transfer_Amount) inbound: count distinct_senders: uniq(of: Transfer_Sender) } } } ``` Swap `Receiver` for `Sender` and `descendingByField: "sent"` to rank outbound flow instead — useful for spotting withdrawal hot wallets. ## USDT balance of an address {#balances} Use the **`Balances`** cube for current token balances. It is live — no snapshot date needed — and returns USD value alongside the raw amount. :::note Use `Balances`, not `BalanceUpdates` `Balances` gives you the current balance directly. Summing `BalanceUpdates` to reconstruct a balance is slower, heavier, and easy to get wrong. ::: ```graphql query USDTBalance($addresses: [String!]) { Tron { Balances( where: { Balance: { Address: { in: $addresses } } Currency: { SmartContract: { is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" } } } orderBy: { descending: Balance_Amount } ) { Balance { Address Amount AmountInUSD UpdateCount FirstChangeTime LastChangeTime } Currency { Symbol Name SmartContract } } } } ``` ```json { "addresses": [ "TDqSquXBgUCLYvYC4XZgrprLK589dkhSCf", "TStieorQGxR7iVtUtUZPeyyVxQJR4TSQwu" ] } ``` ### Telling hot wallets from cold storage `UpdateCount` alongside `FirstChangeTime` / `LastChangeTime` classifies an address without any labelling data: - **Very high `UpdateCount`, `LastChangeTime` seconds ago** → exchange hot wallet or payment processor. Balance churns constantly. - **Single-digit `UpdateCount` on a large balance** → cold storage, treasury or a custody wallet. Funded once, rarely touched. Drop the `Balance.Address` filter and keep `Currency` to get every USDT balance the cube holds, but see the caution below first. :::caution Ranking all USDT holders on Tron USDT on Tron has tens of millions of holders. An unbounded `orderBy: { descending: Balance_Amount }` across all of them **times out server-side** on both `Balances` and `Holders` — this is a dataset-size limit, not a syntax problem. The `Balances` filter accepts `Balance.Address` only, so it cannot be narrowed by amount. If you need a *top-N whale list* rather than specific addresses, use the `Holders` snapshot cube with an amount floor: ```graphql query USDTWhales($floor: String, $date: String) { Tron { Holders( limit: { count: 100 } orderBy: { descending: Balance_Amount } date: $date where: { Currency: { SmartContract: { is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" } } Balance: { Amount: { ge: $floor } } } ) { Holder { Address } Balance { Amount } } } } ``` With `floor: "10000000"` this returns promptly. For a *complete* holder distribution, use [Bitquery Cloud exports](/docs/cloud/) or [Kafka streams](/docs/streams/protobuf/kafka-protobuf-python) rather than a synchronous GraphQL query. For TRC20 tokens far smaller than USDT you can drop the floor entirely. ::: ## USDT TRC20 DEX trades in real time Real-time DEX trades where USDT is the bought currency on Tron — protocol, buyer and seller, amounts and order IDs. Note that most USDT movement on Tron is plain transfers rather than DEX swaps, so this stream is far quieter than the transfer stream above. For trade-oriented work across chains, the [Trading API](/docs/trading/trading-data-overview) carries USD price, market cap and supply on every row. You can run the query [here](https://ide.bitquery.io/USDT-TRC20-DEX-Trades) ```graphql subscription { Tron { DEXTrades( where: {Trade: {Buy: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}}}} ) { Block { Time } Trade { Dex { ProtocolName ProtocolFamily SmartContract } Buy { Amount Buyer Seller Currency { Decimals Fungible HasURI Name ProtocolName SmartContract Symbol } OrderId AmountInUSD } Sell { Buyer Seller Currency { Fungible Decimals Name Native SmartContract Symbol } AmountInUSD Amount } } } } } ``` ## USDT across chains in one request {#cross-chain} Because `Tron` and `EVM` are separate top-level selectors, you can alias several of them in a **single GraphQL request** and compare the same asset across networks without four round trips. This is the clearest demonstration of why a unified API beats per-chain RPC nodes. The query below compares USDT transfer activity on Tron, Ethereum, BSC and Polygon over one window. Each chain uses its own USDT contract. ```graphql query USDTAcrossChains($since: DateTime) { tron: Tron { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" } } } Block: { Time: { since: $since } } TransactionStatus: { Success: true } } ) { transfers: count senders: uniq(of: Transfer_Sender) receivers: uniq(of: Transfer_Receiver) volume: sum(of: Transfer_Amount) } } ethereum: EVM(network: eth) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xdac17f958d2ee523a2206206994597c13d831ec7" } } } Block: { Time: { since: $since } } TransactionStatus: { Success: true } } ) { transfers: count senders: uniq(of: Transfer_Sender) receivers: uniq(of: Transfer_Receiver) volume: sum(of: Transfer_Amount) } } bsc: EVM(network: bsc) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } Block: { Time: { since: $since } } TransactionStatus: { Success: true } } ) { transfers: count senders: uniq(of: Transfer_Sender) receivers: uniq(of: Transfer_Receiver) volume: sum(of: Transfer_Amount) } } polygon: EVM(network: matic) { Transfers( where: { Transfer: { Currency: { SmartContract: { is: "0xc2132d05d31c914a87c6611c10748aeb04b58e8f" } } } Block: { Time: { since: $since } } TransactionStatus: { Success: true } } ) { transfers: count senders: uniq(of: Transfer_Sender) receivers: uniq(of: Transfer_Receiver) volume: sum(of: Transfer_Amount) } } } ``` ```json { "since": "2026-07-29T00:00:00Z" } ``` USDT contract addresses by chain: | Chain | Selector | USDT contract | Reported symbol | | --- | --- | --- | --- | | Tron | `Tron` | `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` | `USDT` | | Ethereum | `EVM(network: eth)` | `0xdac17f958d2ee523a2206206994597c13d831ec7` | `USDT` | | BNB Smart Chain | `EVM(network: bsc)` | `0x55d398326f99059ff775485246999027b3197955` | `USDT` | | Polygon | `EVM(network: matic)` | `0xc2132d05d31c914a87c6611c10748aeb04b58e8f` | `USDT0` | :::note Transfer counts are not comparable to volume Chains differ enormously in how USDT is used: some see very high transfer counts at small average size, others fewer and much larger transfers. Always read `transfers` and `volume` together — ranking chains on either one alone will mislead you. Note too that Polygon's bridged Tether reports as `USDT0`, so filter by contract, not symbol. ::: ## TRC20 mempool transfers Pending USDT transfers from the Tron mempool, before inclusion in a block — transaction hash, amount, sender and receiver, and the anticipated block number. ```graphql subscription { Tron(mempool: true) { Transfers( where: {Transfer: {Currency: {SmartContract: {is: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"}}}} ) { Transaction { Hash } Transfer { Amount Sender Receiver Currency { SmartContract Symbol Name Fungible Native } Id AmountInUSD } Block { Number } } } } ``` ## Related APIs - [USDT Stablecoin API](/docs/stablecoin-APIs/usdt-api) — USDT price, payments, reserves and balances across chains - [Tron Transfers API](/docs/blockchain/Tron/tron-transfers) — all TRC10/TRC20 and native TRX transfers - [Tron DEX Trades API](/docs/blockchain/Tron/tron-dextrades) — SunSwap and other Tron DEX activity - [SunSwap API](/docs/blockchain/Tron/sunswap-api) — Tron's largest DEX - [Trading API overview](/docs/trading/trading-data-overview) — structured trades and prices across 9 chains --- ## Telegram Bot for Live Blockchain Data URL: https://docs.bitquery.io/docs/usecases/telegram-bot/ Build a Telegram bot that streams Bitquery WebSocket GraphQL subscriptions and sends real-time blockchain alerts to chats. # Get Blockchain Data on Telegram Chat in Real-Time With this code, your Telegram bot will respond to the `/start` command by initiating a WebSocket connection to Bitquery and sending blockchain data updates to the Telegram chat. This is how it will look: You can find the complete code [here](https://github.com/divyasshree-BQ/telegram-bot/blob/main/getTransfer_WS.py) ## Step-by-Step Tutorial 1. Install the required Python libraries: ```bash pip install asyncio json websockets tracemalloc telegram-bot-api ``` **Step 2: Define Your Token and Keys** You need to provide your Telegram bot token from the BotFather. For this step you need to create a new Telegram bot. Check official tutorial [here](https://core.telegram.org/bots/tutorial) ![bot](/img/ApplicationExamples/telegram_bot.png) Replace `'tokenn'` with your actual bot token. BOT_TOKEN = 'YOUR_BOT_TOKEN' You also need to get your API OAuth Token from Bitquery, you can get it for free by creating an account [here](https://account.bitquery.io/user/account) **Step 3: Define a Function to Send Messages** A function named `send_message` is defined. It takes an `update` object and a `message` string as arguments and sends the message to the Telegram chat. def send_message(update: Update, message: str): update.message.reply_text(message) **Step 4: Define Functions for Handling Long Messages** Since the response received from the Bitquery API is much longer than allowed limits( 4000 characters), we will write a function that splits the text and sends it to the chat. ```python def split_text(text, max_length): return [text[i:i + max_length] for i in range(0, len(text), max_length)] def send_long_message(update: Update, long_message, max_message_length=4000): message_parts = split_text(long_message, max_message_length) for part in message_parts: send_message(update, part) ``` Two functions, `split_text` and `send_long_message`, are defined to handle long messages. `split_text` breaks a long message into smaller parts, and `send_long_message` sends a long message as multiple smaller messages to avoid Telegram's message length limits. **Step 5: Define WebSocket Code** The `my_component` function is an asynchronous function that handles the WebSocket connection to Bitquery. You can read more about how to use it [here](/docs/subscriptions/websockets/) The below code sends a GraphQL subscription query that listens to server for latest transfers on the Ethereum chain, i.e. it subscribes to the `EVM.Transfers` event. ```python async def my_component(update): url = 'wss://streaming.bitquery.io/graphql' message = json.dumps({ "type": "start", "id": "1", "payload": { "query": "subscription {\n EVM {\n Transfers {\n Transfer {\n Amount\n __typename\n Currency {\n __typename\n Symbol\n }\n }\n }\n }\n}", "variables": {} }, "headers": { Authorization: "Bearer your_access_token_here", } }) async def connect(update): async with websockets.connect(url, subprotocols=['graphql-ws']) as ws: await ws.send(message) while True: response = await ws.recv() response = json.loads(response) if response.get('type') == 'data': response_text = f"{response['payload']['data']['EVM']['Transfers']}" send_long_message(update, response_text) await connect(update) ``` 1. It waits for new events. 2. When it receives a new event, it sends the event data to the Telegram bot. **Step 6: Start WebSocket and Send Updates to Telegram** The `start_websocket_and_send_updates` function initiates the WebSocket connection defined in `my_component`. It also handles exceptions if the connection encounters any issues. ```python async def start_websocket_and_send_updates(update): try: await my_component(update) except Exception as e: print(str(e)) ``` **Step 7: Command Handler to Start WebSocket Connection** The `start` function is a command handler that responds to the `/start` command on Telegram. It sends a message indicating that it's starting the WebSocket connection and then calls `start_websocket_and_send_updates` to begin the WebSocket connection. ```python def start(update: Update, context: CallbackContext): update.message.reply_text("Starting WebSocket connection...") asyncio.run(start_websocket_and_send_updates(update)) ``` **Step 8: Create and Configure the Telegram Bot** In the `main` function, the Telegram bot is created and configured. It registers the `/start` command handler. It then starts the bot and waits for updates. ```python def main(): tracemalloc.start() updater = Updater(BOT_TOKEN, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) updater.start_polling() updater.idle() **Step 9: Run the Bot** The script checks if it's the main module and starts the bot. if __name__ == "__main__": main() ``` --- ## Token Transaction API URL: https://docs.bitquery.io/docs/blockchain/Ethereum/transactions/transaction-api/ Token Transaction API: query and stream Ethereum on-chain data with Bitquery GraphQL examples for developers. See examples in the Bitquery IDE. # Token Transaction API The Transaction API provides access to transaction data on the blockchain. Transactions are the fundamental unit of account on a blockchain and represent the transfer of value from one address to another. The Transaction API allows users to query for transaction data by specifying filters such as transaction hash, sender or receiver address, gas price, and more. The API also provides information about the block that the transaction was included in, including block number and block timestamp. ## Latest Transactions This query is using the Transactions API to retrieve transaction data from the Binance Smart Chain (BSC) blockchain network in real-time. You can find the query [here](https://ide.bitquery.io/Last-transactions-with-cost)
Click to expand GraphQL query ```graphql query { EVM(dataset: realtime, network: bsc) { Transactions( limit: { count: 100 } orderBy: [{ descending: Block_Number }, { descending: Transaction_Index }] ) { Block { Time Number } Transaction { Hash Cost } } } } ```
**Parameters:** - `dataset`: The data source to be used by the query (in this case, "realtime") - `network`: The blockchain network to be queried (in this case, "bsc") - `limit`: Limits the number of returned results to 100. - `orderBy`: Sorts the results by two fields, in descending order: `Block_Number` and `Transaction_Index`. **Results:** - `Block`: The block information of each transaction, including the block number and timestamp. - `Transaction`: The transaction hash and cost (gas used multiplied by the gas price) ## Latest Transactions From or To an Address This query retrieves 100 recent transactions where the specified address is either the sender (`From`) or the receiver (`To`). It is achieved by using the `any` filter which serves as the OR condition. It can help monitor incoming and outgoing transactions of a particular address. You can run the query [here](https://ide.bitquery.io/Latest-Transactions-fromto-address)
Click to expand GraphQL query ```graphql { EVM(dataset: archive, network: eth) { Transactions( limit: {count: 100} where: {any: [{Transaction: {From: {is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549"}}}, {Transaction: {To: {is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549"}}}]} ) { Block { Time Number } Transaction { Hash Cost To From } } } } ```
## Get Transaction Details using Hash The below query retrieves transaction details using the transaction hash. The `where` clause filters transactions based on the `Hash` field, which is set to `0xc3684c0ea63c0e081fb779bb8feaa5e5109ccc70ef30f17f4eea041ec5ea0bc7`. You can find the query [here](https://ide.bitquery.io/Get-a-transaction-by-hash) ```graphql query MyQuery { EVM(dataset: combined, network: eth) { Transactions( where: {Transaction: {Hash: {is: "0xc3684c0ea63c0e081fb779bb8feaa5e5109ccc70ef30f17f4eea041ec5ea0bc7"}}} ) { Block { Time Number } Transaction { From To Hash Value } } } } ``` ## Next available nonce The following query helps you determine the next available nonce for an Ethereum account by getting the latest transaction in the mempool (broadcasted transactions). The returned nonce is the highest nonce used by the account in the mempool. To get the next available nonce for a new transaction, you should increment this value by 1. You can find the query [here](https://ide.bitquery.io/get-next-available-nonce) ```graphql query MyQuery { EVM(mempool: true, network: eth) { Transactions(limit: {count: 1}, orderBy: {descending: Block_Time}) { Transaction { Nonce } } } } ``` ## Transaction Value in USD In the below query we will use the field `Transaction_ValueInUSD` to get the total amount sent to a particular address in USD. You can find the query [here](https://ide.bitquery.io/Transaction-value-in-USD) ```graphql query MyQuery { EVM(network: eth) { in_txs: Transactions( where: {Transaction: {To: {is: "0xdac17f958d2ee523a2206206994597c13d831ec7"}}} ) { sum(of: Transaction_ValueInUSD) } } } ``` ## Internal Transactions A single transaction on a smart contract can result in multiple internal transactions, which interact with different smart contracts. The below query gets all internal transactions for a particular tx filtered using hash. You can run the query [here](https://ide.bitquery.io/internal-transactions-for-a-particular-tx) ```graphql query MyQuery { EVM(network: eth) { Calls( where: {Transaction: {Hash: {is: "0xd1a49976cb217c92eea2bf897d8fe760333047fb555c261f7d2c96ea52901434"}}} ) { Call { Create Index From To ValueInUSD Value Output Signature { Signature Name } } Transaction { Hash } } } } ``` **Response** - **Call** - **Create**: Indicates if the call created a contract. - **Index**: The index of the call within the transaction. - **From**: The address from which the internal transaction was sent. - **To**: The recipient address of the internal transaction. - **Output**: The output data of the call. - **Signature**: Contains signature information. - **Signature**: The signature of the call. - **Name**: The name of the function called. - **Transaction** - **Hash**: The hash of the main transaction. --- ## Tools & SDKs Directory URL: https://docs.bitquery.io/docs/tools-directory/ Tools & SDKs Directory: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Works with WebSocket live subscriptions. # Tools & SDKs Directory Explore **sample applications**, **dashboards**, and **SDKs** built with Bitquery blockchain data. Use these tools to analyze tokens, monitor liquidity, score DeFi portfolios, build charts, or integrate real-time crypto data into your own apps. Each entry includes source code (GitHub), documentation, and—where available—a live demo you can try. For a complete list of step-by-step tutorials (bots, snipers, dashboards, wash trading, NFT tools), see the [How-To Guides index](/docs/category/how-to-guides/). --- ## Apps & Dashboards (UI-based) Ready-to-use web apps and dashboards powered by Bitquery APIs. Many include a live demo, GitHub repository, and a step-by-step how-to guide in our docs. ### Try live & documented | Tool | Description | Try it | How-to guide | Source | | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------- | | **PolyBit — Polymarket Alerts Telegram Bot** | Telegram bot that pushes alerts to you based on your set trade size, share price, trader wallet, or specific market. You can set multiple alerts. | [Add on Telegram](https://t.me/PolyBit_Polymarket_Bot) | [Guide](/docs/usecases/polymarket-tg-alerts-bot) | [GitHub](https://github.com/Akshat-cs/PolyBit-Polymarket-Alerts-Telegram-Bot) | | **Pump.fun Token Sniffer** | Analyze Pump.fun (Solana) token metrics: holder distribution, transfer vs purchase patterns, top holders, bonding curve. | [Open app](https://pumpfun-token-sniffer.vercel.app/) | [Guide](/docs/usecases/pumpfun-token-sniffer) | [GitHub](https://github.com/Akshat-cs/pumpfun-token-sniffer) | | **DeFi Portfolio Scorer** | Calculate a DeFi Strategy Score (25–100) for any Ethereum address using transaction count, protocol usage, and asset diversity. | [Open app](https://ethereum-wallet-defi-score.vercel.app/) | — | [GitHub](https://github.com/Akshat-cs/Defi-Portfolio-Profiler) | | **Realtime Liquidity Drain Detector** | Monitor DEX pools in real time via Kafka; detect significant liquidity drops and get alerts on a web dashboard. | — | [Guide](/docs/usecases/realtime-liquidity-drain-detector) | [GitHub](https://github.com/Akshat-cs/realtime-liquidity-drain-detector) | ### Open-source apps (GitHub) | Tool | Description | Source | | -------------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------- | | **Wash Trading Detector** | Detect wash trades on Solana using Bitquery data and ML. | [GitHub](https://github.com/Kshitij0O7/wash-trading-detector) | | **Staking Tax Report Generator** | Generate staking tax reports from blockchain data. | [GitHub](https://github.com/Kshitij0O7/staking-tax-report-generator) | | **Staking Dashboard** | Dashboard for staking activity and metrics. | [GitHub](https://github.com/Kshitij0O7/staking-dashboard) | | **Validator Data Dashboard** | Monitor and visualize validator data. | [GitHub](https://github.com/Kshitij0O7/validator-data-dashboard) | | **EVM Sniper** | EVM-based sniper tool using Bitquery data. | [GitHub](https://github.com/Kshitij0O7/evm-sniper) | | **Sentinel Crypto Watch** | Crypto monitoring and alerting. | [GitHub](https://github.com/Kshitij0O7/sentinel-crypto-watch) | --- ## Charting & trading | Tool | Description | Source | Docs | | -------------------------------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | **TradingView with Realtime Data** | TradingView charts with real-time OHLCV via Bitquery subscriptions. | [GitHub](https://github.com/bitquery/tradingview-subscription-realtime/tree/main) | [TradingView Realtime guide](/docs/usecases/tradingview-subscription-realtime/getting-started) | | **AI Crypto Trader All-in-One** | AI-driven crypto trading sample using Bitquery data. | [GitHub](https://github.com/divyasshree-BQ/AI-crypto-trader-all-in-one) | — | | **AI Crypto Trader All-in-One (CoW Intent)** | CoW Intent–based variant of the AI crypto trader. | [GitHub](https://github.com/divyasshree-BQ/AI-crypto-trader-all-in-one-CoW-Intent) | — | | **Best Route Trader on Uniswap** | Finds the most efficient swap route on Uniswap using on-chain liquidity and pricing data. | [GitHub](https://github.com/Divyn/best-route-trader-Uniswap) | — | | | **Live Demo:** [Try it](https://best-route-trader-uniswap.vercel.app/) | | | --- ## OpenClaw Agent Skills **[OpenClaw](https://openclaw.ai/)** skills stream live data from the **Bitquery WebSocket API** into an agent workspace. Install published skills with **[ClawHub](https://clawhub.ai/)** (`clawhub install …`); the full skill list, source folders, prerequisites, and `BITQUERY_API_KEY` setup are in the **[openclaw-skills-master](https://github.com/bitquery/openclaw-skills-master)** README. See also **[ClawHub CLI docs](https://docs.openclaw.ai/tools/clawhub)**. | `clawhub install` | Description | | ----------------------------- | -------------------------------------------------------------------------------------------------------------- | | `bitcoin-price-feed` | Real-time Bitcoin OHLC, volume, moving averages, and % change over WebSocket. | | `crypto-chart-usd` | Multi-token 1s OHLC with USD pricing, volume, and moving averages (Trading.Tokens API). | | `pumpfun-usd-price-stream` | Real-time Pump.fun tokens on Solana with USD OHLC, volume, moving averages, and tick-to-tick % change. | | `polymarket-real-time-trades` | Polymarket outcome trades on Polygon: buyer/seller, USD collateral, market question, tx details. | | `stablecoin-payments` | Solana USDC/USDT SPL transfers (mint filter; excludes swap-like program methods), amounts, USD, parties, fees. | --- ## SDKs & npm Packages Install these packages to fetch crypto prices, staking rewards, prediction market data, or to work with Bitquery Kafka protobuf schemas and TON. | Package | Description | npm | | ---------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------- | | **bitquery-tradingview-sdk** | Easy TradingView Charting via Bitquery | [npm](https://www.npmjs.com/package/@bitquery/tradingview-sdk) | | **bitquery-crypto-price** | Crypto price data via Bitquery APIs. | [npm](https://www.npmjs.com/package/bitquery-crypto-price) | | **staking-rewards-api** | Staking rewards and validator data. | [npm](https://www.npmjs.com/package/staking-rewards-api) | | **polymarket-api** | Polymarket prediction market data. | [npm](https://www.npmjs.com/package/polymarket-api) | | **bitquery-protobuf-schema** | Protobuf schemas for Bitquery Kafka streams (e.g. DEX pools, trades). | [npm](https://www.npmjs.com/package/bitquery-protobuf-schema) | | **bitquery-ton-sdk** | Bitquery SDK for TON blockchain data. | [npm](https://www.npmjs.com/package/bitquery-ton-sdk) | --- ## How to use this directory - **Try an app** — Use the “Try it” / “Open app” links to run demos in your browser. - **Build it yourself** — Follow the “How-to guide” links for installation, configuration, and code walkthroughs. - **Extend or fork** — Clone the GitHub repos to customize logic, add features, or integrate with your stack. - **Integrate via SDK** — Use the npm packages in Node.js or TypeScript projects for prices, staking, Polymarket, Kafka protobuf, or TON. For more step-by-step tutorials (Discord/Telegram bots, dashboards, snipers, wash trading, NFT tools), see [How-To Guides](/docs/category/how-to-guides/). --- ## Tracing MCP - What You Can Do With It URL: https://docs.bitquery.io/docs/mcp/Tracing/overview/ Tracing MCP - What You Can Do With It with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Tracing MCP - What You Can Do With It These are the patterns we see most often when teams plug the [Bitquery MCP server](https://mcp.bitquery.io) into Claude, Cursor, ChatGPT, or Claude Code. **You don't write SQL** - you ask in plain English, the agent does the rest. Each pattern below shows the kind of question that works and what comes back. --- ## 1. AML/KYC Risk Scoring > _"Score wallet 0x742d35Cc6634C0532925a3b844Bc9e7595f42cfe for AML risk. Check wallet age, transaction frequency, mixing signals, and any compliance flags."_ Score an incoming deposit or withdrawal using wallet age, transaction patterns, mixing signals, and known-entity labels. The agent returns a risk score (0-100) and flags suspicious patterns automatically. ## 2. Payment Tracing (Source to Destination) > _"Trace $500K USDT from Binance hot wallet 0x1234... to wallet 0x5678.... Show every hop, intermediate wallets, timing, and the final destination."_ Trace the full path of a single payment from source to final destination across one or more hops. The agent maps every intermediate wallet, any DEX swaps or bridge activity, and identifies if funds reached a CEX or high-risk address. ## 3. Phishing and Fraud Investigation > _"A user was phished on March 15 and 2 ETH were stolen from wallet 0xvictim. The attacker transferred to 0xattacker. Trace where that 2 ETH went. Show all hops, DEX swaps, bridges, and final deposits."_ Map the spread of stolen funds from a phishing attack or scam across wallets, DEXs, and chains. Identify if funds were consolidated, swapped, or deposited to an exchange, and cluster related attacker wallets. ## 4. Wallet Clustering for Compliance > _"Wallet 0x123... received funds from multiple sources. Identify all wallets that have sent to or received from this address, and cluster them by likely control."_ Identify related wallets using common-input-output heuristics, behavioral patterns, and timing analysis. The agent clusters wallets likely controlled by the same entity - useful for detecting account farming and money laundering rings. ## 5. Stablecoin Movement Monitoring > _"Show me all USDT movements from Tron to Ethereum in the last 24 hours. Flag transactions over $5M, any bridge activity, and final destinations."_ Real-time or historical tracking of USDC, USDT, BUSD, and other stablecoins across chains and wallets. Useful for treasury monitoring, flow analysis, and detecting unusual liquidity movement patterns. ## 6. Money Laundering Pattern Detection > _"Analyze wallet 0x... for layering patterns. Check for rapid mixing, frequent DEX swaps, cross-chain bridging, and rapid consolidation. Score likelihood of layering."_ Identify common money laundering stages (placement, layering, integration) in fund flow patterns. The agent scores layering likelihood based on rapid mixing, frequent swaps, bridge activity, and consolidation velocity. ## 7. Cross-Chain Bridge Activity > _"Trace 1000 USDC from Ethereum through any bridge to Solana, then back to Ethereum. Show all bridges used, timing, and final destination."_ Track when and where assets move across chain bridges (Wormhole, Stargate, LayerZero, etc.). Identify bridge concentration risk and detect round-tripping patterns that may indicate arbitrage or evasion. ## 8. CEX Deposit Clustering > _"Four wallets all deposited to Binance hot wallet within the same hour. Are these wallets related? Analyze creation dates, sources, and transaction patterns."_ Identify related wallets by finding addresses that all deposit to the same exchange hot wallets. The agent analyzes wallet age, common sources, interaction history, and synchronized deposits to score likelihood of same controller. ## 9. Sanctions and OFAC Compliance > _"Screen wallet 0x... against OFAC SDN list, FATF guidance, and known DeFi hack wallets. Flag any matches, sanctioned entity references, or high-risk signals."_ Screen wallets and transactions against sanctions lists and known-risk entity databases. The agent flags direct matches, cluster associations, and previous sanctions history. ## 10. Regulatory Reporting and Forensic Documentation > _"Generate a forensic report on wallet 0x... for SAR filing. Include creation date, transaction history, entity labels, risk flags, timeline of suspicious activity, and chain of custody."_ Generate comprehensive forensic reports with transaction chains, entity identification, and risk scoring for regulatory submission. Export with clickable block explorer links, exact timestamps, and audit trails. ## 11. Recovery and Law Enforcement Support > _"Law enforcement is investigating theft of 100 USDC on Solana reported on March 10. Trace all movements, identify exchanges involved, cluster related wallets, and flag final destinations."_ Support law enforcement and recovery efforts by identifying where stolen or fraudulent assets ended up and who may control them. The agent preserves chain of custody for legal proceedings and coordinates with exchanges for account freeze requests. --- ## Best Practices for Prompting You don't need to know SQL or the schema - but a few prompt habits make the agent's answers dramatically better. ### 1. Be explicit about the time window The tracing dataset is comprehensive. Always tell the agent the window you care about: _"in the last 24 hours"_, _"yesterday vs the day before"_, _"since March 1"_. Without it, the agent may scan unnecessary data. ### 2. Name the chain (or "all chains") Bitcoin, Ethereum, Solana, Tron, BSC, Base, Arbitrum, Optimism, Polygon, and 30+ more are all in the dataset. _"on Ethereum"_ or _"across all chains"_ keeps the agent's filter clean. ### 3. Include exact amounts and tokens Specify the token and amount: _"$500K USDT"_, _"2 ETH"_, _"1000 USDC"_. This helps disambiguate on shared addresses and tracks value precisely. ### 4. Ask for entity identification Request the agent identify counterparties: _"is this wallet an exchange, bridge, or risk entity?"_, _"compare against OFAC lists"_. The agent will enrich wallets with known-entity labels automatically. ### 5. Request risk scoring For compliance work, ask for scoring: _"score for AML risk"_, _"flag suspicious patterns"_, _"highlight probable entity matches"_. The agent applies behavioral analysis automatically. ### 6. Include investigation context Provide background: _"this is a phishing investigation"_, _"we're preparing a SAR filing"_, _"law enforcement requested this"_. Context helps the agent prioritize relevant data. ### 7. Ask for the data shape you want _"Give me a markdown table I can paste"_, _"return JSON for my script"_, _"format for a regulatory report"_ - the agent will adapt. For forensic output: _"include block explorer links, exact timestamps, and transaction hashes"_. ### 8. Trust the read-only sandbox The MCP only allows reads. The agent **cannot** delete, insert, drop, or modify anything - even if you ask it to. Explore freely. --- ## When MCP, When GraphQL, When Kafka? | Need | Best fit | | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Conversational forensic analysis, ad-hoc investigations, agent loops | **MCP** (this server) | | Compliance backend, subscription monitoring, mempool data | [**GraphQL API**](/docs/graphql/query/) and [WebSocket subscriptions](/docs/subscriptions/websockets/) | | Lowest-latency, highest-throughput streaming for real-time investigations | [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) and [**gRPC streams**](/docs/grpc/solana/introduction/) | | Transaction forensics, entity matching, AML risk scoring APIs | [**Coinpath API**](/docs/blockchain/Bitcoin/bitcoin-coinpath-api/) (GraphQL-based) | The MCP and the GraphQL API read the **same dataset**, so anything you discover via MCP is reproducible in GraphQL or your production compliance stream. --- ## Track Hyperliquid Order Flow by Wallet — Market Makers, Spoofing & Quote Behaviour URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/hyperliquid-order-flow-by-wallet/ Use Hyperliquid L3 market-by-order data to follow a single wallet's order flow: watch a market maker quote and pull, measure cancel-to-fill ratios, spot orders never intended to trade, and reconstruct full order lifecycles by trader address. # Track Hyperliquid Order Flow by Wallet On an aggregated **L2** feed you can see that 40 BTC rests at $95,000. You cannot see whether that is one order or twenty, who placed it, or whether it was pulled the instant a buyer approached. Bitquery serves Hyperliquid's book at **L3 (market-by-order)**: one event per individual order, carrying its order id (`Oid`) and the **wallet address** that placed it. Because Hyperliquid settles on a transparent L1, that attribution is public — L3 with real identity, which does not exist on centralised venues where L3 feeds are anonymised. This page shows what that unlocks. For the schema itself see the [L3 Order Book API](/docs/perpetuals/hyperliquid/hyperliquid-orders-api). :::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/) ::: ## 1. Watch one wallet quote in real time Filter the book stream to a single address and you see that participant's quoting as it happens — every level they add, resize and pull. Run it in the IDE: [Hyperliquid Wallet Book Activity ➤](https://ide.bitquery.io/hyperliquid-wallet-book-activity) ```graphql subscription { Hyperliquid { BookUpdates( where: {BookUpdate: {Trader: {Address: {is: "0x0000000000000000000000000000000000000000"}}}} ) { Block { Time } BookUpdate { Kind Side Px Size SizeBefore Oid Market { Symbol } } } } } ``` `Kind` tells you what happened to that specific order: `new` (placed), `change` (resized) or `remove` (pulled or filled). `SizeBefore` gives you the delta on that one order rather than a net change across the level. Swap the address for a list to follow a whole desk: ```graphql where: {BookUpdate: {Trader: {Address: {in: ["0xaaa...", "0xbbb...", "0xccc..."]}}}} ``` ## 2. Reconstruct a trader's full order lifecycle Fills alone tell you what a trader *did*. Orders tell you what they *intended* — including everything they placed and then cancelled, which never appears in trade data. Run it in the IDE: [Hyperliquid Wallet Order Lifecycle ➤](https://ide.bitquery.io/hyperliquid-wallet-order-lifecycle) ```graphql query { Hyperliquid { Orders( limit: {count: 200} orderBy: {descending: Block_Time} where: {Order: {Trader: {Address: {is: "0x0000000000000000000000000000000000000000"}}}} ) { Block { Time } Order { Market { Symbol } Oid Cloid Status OrderType Tif Side LimitPx Size OrigSz IsTrigger TriggerPx ReduceOnly } } } } ``` `Oid` is the join key. The same id appears on `BookUpdate.Oid` (how the order sat in the book) and on `Trade.Execution.Oid` (how it filled), so one order can be followed end to end across all three cubes. ## 3. Cancel-to-fill ratio — the spoofing signal An order placed and pulled without ever trading is normal market making. A wallet doing it at scale, on one side, repeatedly, is a different thing. L3 is what makes the ratio measurable at all: on L2 you cannot tell a cancellation from a fill, because both simply reduce the level. Count orders by status for a market over a window: Run it in the IDE: [Hyperliquid Order Status Breakdown ➤](https://ide.bitquery.io/hyperliquid-order-status-breakdown) ```graphql query { Hyperliquid { Orders( limit: {count: 100} orderBy: {descendingByField: "placed"} where: { Order: {Market: {Symbol: {is: "BTC"}}} Block: {Time: {since_relative: {hours_ago: 24}}} } ) { Order { Trader { Address } } placed: count canceled: count(if: {Order: {Status: {is: "canceled"}}}) filled: count(if: {Order: {Status: {is: "filled"}}}) } } } ``` This returns one row per wallet with all three counts, so the cancel-to-fill ratio is `canceled / filled` directly. A wallet with a very high cancel share, concentrated on one `Side`, placing size well away from the touch and pulling it as price approaches, is worth a closer look — pull that address back through query 1 to see the behaviour tick by tick. :::caution Interpret with care A high cancel rate on its own is not evidence of manipulation. Market makers legitimately cancel the large majority of their orders as they requote. Treat this as a screen that tells you where to look, not as a conclusion. ::: ## 4. Follow the wallet off Hyperliquid This is the part no Hyperliquid-only data source can do. Once you have an address of interest, the same API covers Solana, Ethereum, Base, BNB, Tron and Bitcoin — so you can ask where that trader's funds came from before the position and where they went after it. ```graphql query { EVM(network: eth) { Transfers( limit: {count: 50} orderBy: {descending: Block_Time} where: {Transfer: {Sender: {is: "0x0000000000000000000000000000000000000000"}}} ) { Block { Time } Transfer { Amount Currency { Symbol SmartContract } Receiver } } } } ``` Liquidation on Hyperliquid, followed by a deposit somewhere else, is a single question here rather than a reconciliation job across two vendors. ## Data window The `Hyperliquid` cubes serve a **rolling ~30-day window**, which covers live monitoring and recent-history analysis. For longer studies — behavioural baselines over months, backtests — use the [Blockchain Data Lake](/docs/data-lake/) for the full archive. ## Related - [Hyperliquid L3 Order Book API](/docs/perpetuals/hyperliquid/hyperliquid-orders-api) — `Orders`, `BookUpdates`, `Twaps` schema - [Hyperliquid Trades & Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) — fills, PnL, OHLCV - [Hyperliquid Signed Actions](/docs/perpetuals/hyperliquid/hyperliquid-signed-actions-api) — raw L1 actions beneath the book - [Bitquery vs Hyperliquid's free data](/docs/perpetuals/hyperliquid/vs-hyperliquid-api) — what the native API and S3 archive do and don't cover --- ## Track Millions Of Solana Wallets URL: https://docs.bitquery.io/docs/usecases/track-millions-of-solana-wallets/ Build Track Millions Of Solana Wallets: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # How to efficiently track millions of Solana Wallets Balance with Bitquery Kafka Streams Accurate, real-time wallet balance data is mission-critical for crypto businesses. Whether it's exchanges and custodians monitoring incoming deposits, DeFi protocols watching collateral positions, or analytics platforms tracking whale movements—speed matters. Just a few milliseconds can mean the difference between a successful liquidation or a costly missed opportunity. But tracking wallet balances on Solana is uniquely challenging. As a high-throughput blockchain, Solana processes thousands of transactions per second across millions of wallets. This makes traditional polling-based methods both inefficient and costly. Check this [bitquery API](https://ide.bitquery.io/Transaction-in-1-hour_1) here, we are getting around 4000 TPS on Solana at the time of writing this article. ### Why polling doesn't scale on Solana: - **High volume**: You risk missing updates due to polling intervals. - **Expensive**: RPC calls scale poorly and become cost-prohibitive at millions of wallets. - **Laggy**: Polling introduces delays between actual balance changes and detection. - **Unreliable**: Under heavy load, RPC nodes can time out or fail. Traditionally, teams rely on Remote Procedure Call (RPC) polling to query wallet balances. But as your tracking scales, that model breaks down—wasting resources, increasing latency, and burning through RPC limits. For a deeper dive into this problem space, check out our post on [Scalable Balance Tracking for Custodians: A Better Alternative to Node-Based Approaches](https://www.linkedin.com/pulse/scalable-balance-tracking-custodians-better-alternative-node-based-wiyuc). In this article, we’ll walk through a practical implementation of scalable Solana wallet balance tracking using Bitquery’s Kafka Streams. We'll share code examples, design insights, and explain how Kafka helps you stream balance changes in real time—without hammering RPC nodes. If you're new to Kafka, start with [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/) on Bitquery to get a basic understanding before diving in. ## Who Needs Real-Time Wallet Tracking? - **Exchanges**: Detect deposits, monitor wallets, verify withdrawals - **DeFi**: Track collateral, trigger liquidations, verify transactions - **Wallets**: Show live balances, send alerts, log history - **Analytics**: Spot whale moves, analyze trends, assess risks :::note The code presented here is a proof-of-concept intended to demonstrate core concepts. Production implementations for exchanges and financial institutions will require additional engineering as briefly outlined later in this article. ::: ## How is Balance Calculated in Solana? Solana handles balances in a unique way that's important to understand for accurate tracking: ### What is PostBalance? In Solana transaction data, each account involvement includes two important balance values: - **PreBalance**: The account's balance before the transaction execution - **PostBalance**: The account's balance after the transaction execution These are in the smallest token units (lamports for SOL, where 1 SOL = 1,000,000,000 lamports). ### How We Use PostBalance We use PostBalance because it's: 1. The final account state after all operations 2. Blockchain-verified (more reliable than manual calculations) Our implementation: ```python # Extract PostBalance from Kafka stream post_balance = balance_update.PostBalance # Convert to human-readable format human_balance = raw_balance / (10 ** decimals) ``` This ensures accurate balance tracking that matches wallet and explorer displays. ## Quick Start Guide **GitHub Repository**: https://github.com/akshat-cs/solana-wallet-tracker ### Prerequisites 1. Python 2. Access to Bitquery Kafka Streams (reach out to the Bitquery team on [Telegram](https://t.me/bloxy_info) for credentials) is a completely free trial ### Installation & Setup 1. Clone the repository: ``` git clone https://github.com/akshat-cs/solana-wallet-tracker.git cd solana-wallet-tracker ``` 2. Install dependencies: ```bash pip install confluent-kafka protobuf base58 bitquery-pb2-kafka-package python-dotenv ``` 3. Configure your credentials: Set these variables in a newly created .env file with the credentials you got from BQ support TG channel. ``` # Kafka credentials KAFKA_USERNAME = KAFKA_PASSWORD = ``` 4. Run the wallet tracker: ```bash python wallet_balance_extractor.py ``` ## Understanding the Kafka Stream Data Before diving into the implementation, let's look at what the actual data from the Bitquery Kafka stream looks like. This will help you understand the rich information available to work with: ``` Full Message Details: Header: Slot: 333862663 Hash: ParentSlot: 0 Height: 0 Timestamp: 0 ParentHash: Transactions (repeated): [0]: Index: 190 Signature: 5SLabhmtAh8Bynx4Ee9aPUd8g7pWSBCMSvEoWJaKN9aGRzpxgUS83oqyvPYje4rHLBjH2h6tCttNFC6RmsMyLFMM Status: Success: False ErrorMessage: Error processing Instruction 2: custom program error: 0x1771 Header: Fee: 5625 FeePayer: CtxJeBMW3kGg3yG4MPacVxFNp76pieVrWXVe86VEcrfP RecentBlockhash: EB3zVPGyV3ia6sDVxi2MHvu2B9KVGRuzUm2biggwBnbw Signer: CtxJeBMW3kGg3yG4MPacVxFNp76pieVrWXVe86VEcrfP Transfers (repeated): [0]: InstructionIndex: 4 Amount: 1691000000 Sender: Address: AkG8tvC27HbMLunku4GLSEXbmmTwgX1nDEGoBjyHTJFJ IsSigner: False IsWritable: True Token: Mint: So11111111111111111111111111111111111111112 Owner: CtxJeBMW3kGg3yG4MPacVxFNp76pieVrWXVe86VEcrfP Decimals: 9 ProgramId: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA Receiver: Address: DrVWWu8y13x5ZdSX7JTNH3XJJwptzh8xJ8nUphJZxY94 IsSigner: False IsWritable: True Token: Mint: So11111111111111111111111111111111111111112 Owner: 8wJymmvXgo7eK7kGgvwU3GaKaTN9nvZV2S36WC9gbrq4 Decimals: 9 ProgramId: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA Currency: Name: Wrapped Solana Decimals: 9 Uri: Symbol: WSOL Native: False Wrapped: True Fungible: True MintAddress: So11111111111111111111111111111111111111112 TokenBalanceUpdates (repeated): [0]: PreBalance: 6012783083 PostBalance: 4321783083 AccountIndex: 5 [1]: PreBalance: 1172836026228 PostBalance: 1174527026228 AccountIndex: 7 BalanceUpdates (repeated): [0]: BalanceUpdate: PreBalance: 120566794 PostBalance: 120561169 AccountIndex: 0 Currency: Name: Solana Decimals: 9 Symbol: SOL Native: True Wrapped: False Fungible: True MintAddress: 11111111111111111111111111111111 ``` This is just a small fraction of a single message - the actual messages can be several thousand lines long, containing detailed information about all token transfers, balance updates, and transaction details in a block. ## Complete Code Walkthrough Let's examine the entire implementation in detail: ### Imports ```javascript from dotenv import load_dotenv from datetime import datetime from confluent_kafka import Consumer, KafkaError, KafkaException from google.protobuf.message import DecodeError from solana import token_block_message_pb2 ``` ### Class Structure: IndexedWalletTracker The IndexedWalletTracker class is the heart of our implementation. It manages the in-memory wallet index and processes Kafka messages to update balances. #### Initialization ```python def __init__(self): # Create output directory self.output_dir = "wallet_balances" if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) # Timestamp for file naming self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # In-memory index of wallets: {address: {token: {balance, decimals, symbol, last_updated}}} self.wallet_index = {} # Token metadata cache: {token_mint: {symbol, decimals, name}} self.token_metadata = {} # Statistics tracking self.stats = { 'messages_processed': 0, 'balance_updates_received': 0, 'unique_addresses': 0, 'unique_tokens': 0, 'start_time': time.time(), 'last_export_time': time.time() } # Export settings self.export_interval = 30 # seconds between exports ``` This initializes: - A directory for storing exported data - The in-memory wallet index (nested dictionaries for fast lookups) - A token metadata cache (to avoid redundant processing) - Statistics tracking - Export interval settings #### Utility Functions ```python def convert_bytes(self, value): """Convert bytes to base58 string""" if isinstance(value, bytes): return base58.b58encode(value).decode() return str(value) ``` This simple utility converts byte values (like addresses) to Solana's base58 format. ```python def calculate_human_balance(self, raw_balance, decimals): """Calculate human-readable balance based on token decimals""" if decimals > 0: return raw_balance / (10 ** decimals) return raw_balance ``` This function converts raw token amounts (like 1000000000 lamports) to human-readable values (1 SOL) based on the token's decimal places. #### Extracting Data from Messages ```python def extract_token_metadata(self, currency): """Extract token metadata from Currency object""" token_mint = "UNKNOWN" token_symbol = "UNKNOWN" token_decimals = 0 token_name = "UNKNOWN" if hasattr(currency, 'MintAddress') and currency.MintAddress: token_mint = self.convert_bytes(currency.MintAddress) if hasattr(currency, 'Symbol') and currency.Symbol: token_symbol = currency.Symbol if hasattr(currency, 'Decimals'): token_decimals = currency.Decimals if hasattr(currency, 'Name') and currency.Name: token_name = currency.Name else: token_name = token_symbol # Update token metadata cache if token_mint != "UNKNOWN": self.token_metadata[token_mint] = { "symbol": token_symbol, "decimals": token_decimals, "name": token_name } # Update unique tokens count if len(self.token_metadata) > self.stats['unique_tokens']: self.stats['unique_tokens'] = len(self.token_metadata) return { "mint": token_mint, "symbol": token_symbol, "decimals": token_decimals, "name": token_name } ``` This function extracts token metadata (mint address, symbol, decimals, name) from the Currency objects in the Kafka messages. It also updates the token metadata cache for future reference. ```python def extract_address(self, tx, account_index): """Extract address from transaction using account index""" address = None # Try Header.Accounts if hasattr(tx, 'Header') and hasattr(tx.Header, 'Accounts'): accounts = tx.Header.Accounts if account_index < len(accounts): account = accounts[account_index] if hasattr(account, 'Address'): address = self.convert_bytes(account.Address) # Try Accounts directly if address is None and hasattr(tx, 'Accounts'): accounts = tx.Accounts if account_index < len(accounts): account = accounts[account_index] if hasattr(account, 'Address'): address = self.convert_bytes(account.Address) return address ``` This function extracts a wallet address from a transaction given an account index. It tries multiple locations because the Solana message structure can vary. #### Updating Wallet Balances ```python def update_wallet_balance(self, address, token_mint, token_info, raw_balance): """Update the wallet balance index with the latest balance""" if address == "UNKNOWN" or address is None: return False # Skip unknown addresses # Initialize address in index if needed if address not in self.wallet_index: self.wallet_index[address] = {} # Update unique addresses count self.stats['unique_addresses'] = len(self.wallet_index) # Calculate human-readable balance human_balance = self.calculate_human_balance(raw_balance, token_info['decimals']) # Update token balance for this address self.wallet_index[address][token_mint] = { 'raw_balance': raw_balance, 'human_balance': human_balance, 'symbol': token_info['symbol'], 'decimals': token_info['decimals'], 'last_updated': int(time.time()) } return True ``` This is the core function that updates our in-memory index with the latest wallet balance. It also calculates a human-readable balance value and tracks when the balance was last updated. ```python def process_balance_update(self, address, token_info, raw_balance): """Process a balance update and update the index""" if address and token_info['mint'] != "UNKNOWN": success = self.update_wallet_balance( address, token_info['mint'], token_info, raw_balance ) if success: self.stats['balance_updates_received'] += 1 return True return False ``` This is a wrapper around `update_wallet_balance` that also updates our statistics tracking. #### Exporting Balances ```python def export_balances(self, force=False): """Export current balances to file if interval has passed or forced""" current_time = time.time() elapsed = current_time - self.stats['last_export_time'] if force or elapsed >= self.export_interval: # Create export file with timestamp export_file = os.path.join(self.output_dir, f"balances_{self.timestamp}_latest.json") # Prepare export data export_data = { 'timestamp': datetime.now().isoformat(), 'stats': self.stats.copy(), 'wallets': self.wallet_index } # Add elapsed time and rate stats total_elapsed = current_time - self.stats['start_time'] export_data['stats']['elapsed_seconds'] = total_elapsed export_data['stats']['updates_per_second'] = ( self.stats['balance_updates_received'] / total_elapsed if total_elapsed > 0 else 0 ) # Write to file with open(export_file, 'w') as f: json.dump(export_data, f, indent=2) # Also create a CSV version for easy viewing csv_file = os.path.join(self.output_dir, f"balances_{self.timestamp}_latest.csv") with open(csv_file, 'w') as f: # Write header f.write("Address,Token,Symbol,HumanReadableBalance,RawBalance,Decimals,LastUpdated\n") # Write each wallet balance for address, tokens in self.wallet_index.items(): for token_mint, data in tokens.items(): f.write(f"{address},{token_mint},{data['symbol']}," + f"{data['human_balance']},{data['raw_balance']}," + f"{data['decimals']},{data['last_updated']}\n") # Update last export time self.stats['last_export_time'] = current_time print(f"Exported {len(self.wallet_index)} wallets with " + f"{self.stats['balance_updates_received']} balance records to {export_file}") print(f"CSV export available at: {csv_file}") return True return False ``` This function exports our in-memory wallet balances to both JSON and CSV files. It only exports if the export interval has passed or if forced (e.g., at shutdown). #### Processing Messages ```python def process_message(self, token_block): """Process a token block message""" self.stats['messages_processed'] += 1 # Process balance updates at block level if hasattr(token_block, 'BalanceUpdates'): for update in token_block.BalanceUpdates: if hasattr(update, 'BalanceUpdate') and hasattr(update, 'Currency'): balance_update = update.BalanceUpdate currency = update.Currency # Extract token metadata token_info = self.extract_token_metadata(currency) # Extract balance and account if hasattr(balance_update, 'PostBalance') and hasattr(balance_update, 'AccountIndex'): post_balance = balance_update.PostBalance account_index = balance_update.AccountIndex # For block level updates, we often can't resolve the address # But we can try to look in transactions address = None if hasattr(token_block, 'Transactions'): for tx in token_block.Transactions: addr = self.extract_address(tx, account_index) if addr: address = addr break if address: self.process_balance_update(address, token_info, post_balance) ``` This is the first part of the `process_message` method, which handles block-level balance updates. The method is quite long, as it needs to handle multiple data sources within each message. ``` # Process transactions if hasattr(token_block, 'Transactions'): for tx in token_block.Transactions: # Process transfers - these usually have the best address information if hasattr(tx, 'Transfers'): for transfer in tx.Transfers: # Extract token metadata token_info = {"mint": "UNKNOWN", "symbol": "UNKNOWN", "decimals": 0, "name": "UNKNOWN"} if hasattr(transfer, 'Currency'): token_info = self.extract_token_metadata(transfer.Currency) # Get sender and receiver addresses sender_address = None if hasattr(transfer, 'Sender') and hasattr(transfer.Sender, 'Address'): sender_address = self.convert_bytes(transfer.Sender.Address) receiver_address = None if hasattr(transfer, 'Receiver') and hasattr(transfer.Receiver, 'Address'): receiver_address = self.convert_bytes(transfer.Receiver.Address) # Process balance updates in instruction if hasattr(transfer, 'Instruction') and hasattr(transfer.Instruction, 'TokenBalanceUpdates'): for balance_update in transfer.Instruction.TokenBalanceUpdates: if hasattr(balance_update, 'PostBalance') and hasattr(balance_update, 'AccountIndex'): post_balance = balance_update.PostBalance account_index = balance_update.AccountIndex # Determine address based on account index address = None if account_index == 0 and sender_address: address = sender_address elif account_index == 2 and receiver_address: address = receiver_address if address: self.process_balance_update(address, token_info, post_balance) ``` The next segment processes transfers, which provide the most accurate and direct information about wallet balance changes. It extracts the token metadata, sender and receiver addresses, and processes the balance updates for each. ``` # Process transaction-level balance updates if hasattr(tx, 'BalanceUpdates'): for update in tx.BalanceUpdates: if hasattr(update, 'BalanceUpdate') and hasattr(update, 'Currency'): balance_update = update.BalanceUpdate currency = update.Currency # Extract token metadata token_info = self.extract_token_metadata(currency) # Extract balance and account if hasattr(balance_update, 'PostBalance') and hasattr(balance_update, 'AccountIndex'): post_balance = balance_update.PostBalance account_index = balance_update.AccountIndex # Get address from transaction address = self.extract_address(tx, account_index) if address: self.process_balance_update(address, token_info, post_balance) ``` This segment processes transaction-level balance updates, which provide additional balance information that might not be captured in transfers. ``` # Process token balance updates if hasattr(tx, 'TokenBalanceUpdates'): for update in tx.TokenBalanceUpdates: if hasattr(update, 'PostBalance') and hasattr(update, 'AccountIndex'): post_balance = update.PostBalance account_index = update.AccountIndex # Get address from transaction address = self.extract_address(tx, account_index) # Get token info from account token_info = {"mint": "UNKNOWN", "symbol": "UNKNOWN", "decimals": 0, "name": "UNKNOWN"} if hasattr(tx, 'Accounts') or (hasattr(tx, 'Header') and hasattr(tx.Header, 'Accounts')): accounts = tx.Accounts if hasattr(tx, 'Accounts') else tx.Header.Accounts if account_index < len(accounts): account = accounts[account_index] if hasattr(account, 'Token'): token = account.Token if hasattr(token, 'Mint'): token_info["mint"] = self.convert_bytes(token.Mint) if hasattr(token, 'Decimals'): token_info["decimals"] = token.Decimals # Use token metadata from cache if available if token_info["mint"] != "UNKNOWN" and token_info["mint"] in self.token_metadata: cached_data = self.token_metadata[token_info["mint"]] token_info["symbol"] = cached_data["symbol"] token_info["name"] = cached_data["name"] if address: self.process_balance_update(address, token_info, post_balance) ``` Finally, the method processes token balance updates, which provide yet another source of balance information. This multi-layered approach ensures we capture all possible balance changes. ``` # Export balances if it's time self.export_balances() # Periodically print stats if self.stats['messages_processed'] % 10 == 0: self.print_stats() ``` After processing all the balance updates, the method checks if it's time to export the balances and prints statistics periodically. #### Statistics Reporting ```python def print_stats(self): """Print tracker statistics""" elapsed = time.time() - self.stats['start_time'] updates_per_sec = ( self.stats['balance_updates_received'] / elapsed if elapsed > 0 else 0 ) print(f"\n--- Wallet Balance Tracker Stats ---") print(f"Runtime: {elapsed:.2f} seconds") print(f"Messages processed: {self.stats['messages_processed']}") print(f"Balance updates received: {self.stats['balance_updates_received']} ({updates_per_sec:.2f}/sec)") print(f"Unique addresses tracked: {self.stats['unique_addresses']}") print(f"Unique tokens tracked: {self.stats['unique_tokens']}") ``` This method prints statistics about the tracker's performance, including runtime, messages processed, balance updates received, and the number of unique addresses and tokens tracked. #### Main Consumer Function ```python def run_consumer(): """Run the Kafka consumer with the indexed wallet tracker""" # Load environment variables from .env file load_dotenv() # Get credentials from environment variables kafka_username = os.getenv("KAFKA_USERNAME") kafka_password = os.getenv("KAFKA_PASSWORD") # Kafka configuration group_id_suffix = uuid.uuid4().hex conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092', 'group.id': f'{kafka_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': kafka_username, 'sasl.password': kafka_password, 'auto.offset.reset': 'latest', } # Initialize consumer consumer = Consumer(conf) topic = 'solana.tokens.proto' consumer.subscribe([topic]) # Initialize wallet tracker tracker = IndexedWalletTracker() print(f"Starting indexed wallet balance tracker on topic: {topic}") print("Press Ctrl+C to stop...") ``` This function initializes the Kafka consumer with the appropriate configuration and sets up the wallet tracker. ``` 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()) try: # Parse the message buffer = msg.value() token_block = token_block_message_pb2.TokenBlockMessage() token_block.ParseFromString(buffer) # Process the message tracker.process_message(token_block) except DecodeError as err: print(f"Protobuf decoding error: {err}") except Exception as err: print(f"Error processing message: {err}") import traceback traceback.print_exc() ``` The main processing loop polls for messages from Kafka, parses them using the protobuf definition, and passes them to the tracker for processing. It includes error handling to catch and report any issues. ``` except KeyboardInterrupt: print("\nStopping wallet balance tracker...") finally: # Export final balances tracker.export_balances(force=True) consumer.close() print("Consumer closed.") ``` The function concludes with cleanup code that exports the final balances and closes the consumer when the program is stopped. ## Data Flow Through the System To understand how data flows through this system: 1. Kafka Consumer retrieves messages from Bitquery's Solana token stream 2. Each message is parsed into a protobuf TokenBlockMessage object 3. The process_message method extracts: - Block-level balance updates - Transfers and their associated balance updates - Transaction-level balance updates - Token balance updates 4. For each balance update, the system: - Extracts token metadata (mint, symbol, decimals) - Finds the associated wallet address - Updates the in-memory wallet index with the latest balance 5. Periodically, the system exports the in-memory balances to JSON and CSV files 6. Statistics are printed to the console to monitor performance ## Scaling for Production Use While this proof-of-concept demonstrates the core concepts, a production implementation would require several additional components: - **Database integration**: Replace file exports with a proper database system - **Distributed processing**: Run multiple consumer instances with the same group ID - **Caching strategy**: Implement memory management for less active wallets - **Error recovery**: Add robust error handling and consumer position checkpointing - **Monitoring and alerting**: Add systems to detect processing lags or failures - **API layer**: Create endpoints for querying balance data For exchanges, custodial services, and other financial institutions, additional considerations around security, high availability, and compliance would also be necessary. ## Conclusion: Beyond RPC Polling Traditional RPC-based balance monitoring simply can't keep up with the demands of modern blockchain applications. By leveraging Bitquery's Kafka Streams, you can: - Reduce infrastructure costs by up to 90% compared to RPC polling - Improve detection latency from seconds to milliseconds - Scale to millions of wallets without performance degradation - Achieve 100% accuracy with no missed transactions Ready to explore how Bitquery's Kafka Streams could transform your wallet monitoring capabilities? Clone the repository for a starting point and reach out to the Bitquery team on [Telegram](https://t.me/bloxy_info) to discuss your specific requirements and get access to the streams. --- _This article provides a technical overview and implementation guidance. The code presented is a proof-of-concept that demonstrates core principles but would require additional engineering for production use. Always conduct thorough testing and security reviews before deploying systems handling financial data._ --- ## Track Token Lock Unlock URL: https://docs.bitquery.io/docs/API-Blog/track-token-lock-unlock/ Track Token Lock Unlock: Bitquery documentation with GraphQL examples, real-time streams, and integration guidance. Keep queries fast with indexed filters. # How to Easily Track Token Lock and Unlock Events Using Bitquery APIs In this article, we are going to understand why tracking token lock and unlock events is necessary for investors and project teams in the quickly changing crypto space. Token lockups provide the project with stability and confidence by restricting token sales or transfers for a certain amount of time. The sudden release of a large number of tokens, however, may result in market instability. Tracking these occurrences allows stakeholders to anticipate market movements and make informed decisions. Anyone can follow this guide to understand how to use Bitquery APIs to track vested tokens and receive alerts when unlocking events are about to occur. ## Understanding Token Locks and Unlocks ### What Are Token Locks? Token locks are methods applied by blockchain projects to limit the ability to transfer of tokens for a certain duration. They're frequently used for: Vesting Periods: Tokens are gradually released to team members or early investors to ensure long-term commitment. This can help prevent immediate sell-offs that could negatively impact the token's price. Liquidity Locks: A certain amount of tokens is kept in liquidity pools for a defined duration to aid in market stability. This ensures there is always sufficient liquidity available, which is crucial for the smooth functioning of decentralized exchanges (DEXs) and other financial mechanisms within the ecosystem. ### Why Track Token Unlocks? Tracking token unlocks is necessary for: Investors: To predict possible adjustments in token supply that may affect market values. Knowing when big sums of tokens will be released might assist investors make informed purchases or sales. Project Teams: To oversee token distributions and maintain transparency with stakeholders. Transparency about token unlock schedules can build trust within the community and among investors. ## Key Data Points to Track When tracking token lock and unlock events, the following data points are essential: - Token Name and Symbol: Identify the token in question. - Unlock Date: When the tokens will be unlocked. - Amount to be Unlocked: The quantity of tokens that will be released. - Vesting Schedule: Details of the vesting period and intervals. - Contract Address: The smart contract address governing the lockup. - Transaction History: Past lock and unlock transactions for context. ### Adding Liquidity Event In decentralized finance (DeFi), adding liquidity means putting tokens into a pool on a decentralized exchange (DEX). This process ensures that there are enough tokens available for trading, which is essential for maintaining market stability and enabling smooth transactions. #### Why It's Important Adding liquidity can earn rewards for those who contribute tokens. It also helps keep the market running smoothly. By adding liquidity, token holders can participate in the ecosystem, earn transaction fees, and support the overall health of the market. #### How to Track Use Bitquery APIs to see when large amounts of tokens are added to pools. This can indicate important moves by project teams or big investors. By monitoring these events, you can gain insights into market behavior and anticipate potential price changes based on liquidity movements. #### Example Query To track liquidity events, you can use a query similar to the one for tracking token unlocks, but focusing on transactions related to liquidity pools. Here’s a sample query to track [liquidity additions](https://ide.bitquery.io/liquidity-additions) on the Ethereum network: ```graphql subscription { EVM(network: eth) { Events( where: {LogHeader: {Address: {is: "0x663A5C229c09b049E36dCc11a9B0d4a8Eb9db214"}}, Log: {Signature: {Name: {is: "onDeposit"}}}} ) { Block { Number Time } 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 } } } Transaction { From } } } } ``` This query helps identify significant liquidity additions, providing insights into market dynamics. ### Removing Liquidity Event Removing liquidity means taking tokens out of a pool. This action can have a significant impact on the market, as it reduces the available liquidity, which can lead to price volatility and affect the overall market stability. #### Why It's Important Removing a lot of liquidity can make the market less stable and cause price swings. It can signal that investors or project teams are withdrawing support from the market, which might indicate upcoming price drops or market corrections. #### How to Track In order to see when large amounts of tokens are taken out of pools, we can use Bitquery Event APIs. This can help predict potential market changes. By monitoring these events, you can stay ahead of market movements and adjust your strategies accordingly. #### Example Query To track liquidity removal events, use a query similar to the one for tracking liquidity additions, but focus on transactions related to liquidity removals. Here’s a sample query to [track liquidity removals](https://ide.bitquery.io/liquidity-removals) on the Ethereum network: ```graphql { EVM(dataset: combined, network: eth) { Events( where: { LogHeader: { Address: { is: "0x663A5C229c09b049E36dCc11a9B0d4a8Eb9db214" } } Log: { Signature: { Name: { is: "onWithdraw" } } } } limit: { count: 50 } orderBy: { descending: Block_Time } ) { Block { Number Time } 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 } } } Transaction { From } } } } ``` This query helps identify significant liquidity removals, providing insights into market behavior. - Detailed Steps to Track Token Unlocks - Identify the Token and Smart Contract - First, find out which token and smart contract you're dealing with. - Query the Lockup Transactions In order to search for transactions that lock tokens, we can use Bitquery real-time APIs to get alerts in realtime. Here’s a sample query for [locked tokens](https://ide.bitquery.io/realtime-token-lock) on the Ethereum network: ```graphql subscription { EVM( network: eth) { Calls(where: {Call: {Signature: {Signature: {is: "lock()"}}}}) { Call { LogCount InternalCalls } Transaction { Gas Hash From To } Block { Date Number } } } } ``` This query fetches transactions related to the lockup, providing details such as the date, transaction hash, gas price, and gas used. It helps in understanding the initial lockup conditions and timelines. ### Monitor Unlock Events Set up a query to keep an eye on upcoming [token unlock events](https://ide.bitquery.io/token-unlock). For example: ```graphql subscription { EVM(network: eth) { Calls(where: {Call: {Signature: {Signature: {is: "unlock()"}}}}) { Call { LogCount InternalCalls } Transaction { Gas Hash From To } Block { Date Number } } } } ``` This subscription query tracks transactions that signal token unlocks, providing details about the dates, transaction hash, gas price, and gas used. It helps in predicting when tokens will become available for trading. 4. Set Up Notifications [Create notifications to alert](/docs/usecases/monitoring-solana-blockchain-real-time-tutorial/) you when tokens are about to be unlocked. You can use email alerts, websockets, or messaging platforms like Slack. Setting up notifications ensures you stay informed about important events and can react promptly to market changes. ### Tracking Token Lock/ Unlock Without Knowing Log Signatures In any query if you are not sure about the event name or signature, use the `includes` filter to filter the events. In the below example, let's track latest token lock and unlock events on Optimism by using `includes: "locked"` filter for Log Signatures. You can run the query [here](https://ide.bitquery.io/Optimism-token-unlocked) ```graphql { EVM(dataset: archive, network: optimism) { Events( where: {Log: {Signature: {Name: {includes: "locked"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { ChainId Transaction { Hash } Log { Signature { Name Signature } } Fee { SenderFee } Block { Time Number } } } } ``` ### Arbitrum Token Unlock Arbitrum, a solution to help Ethereum scale better, has a schedule for when its tokens will be unlocked. Tracking these events helps investors predict market behavior and price impacts. By monitoring Arbitrum's token unlock schedule, investors can anticipate changes in token supply and adjust their strategies accordingly. You can run the query [here](https://ide.bitquery.io/Arbitrum-Token-Unlock_1) ```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" } ``` ### Solana Token Unlock Schedule Solana, known for its fast and cheap transactions, has important token unlock events. Tracking these can help understand its market dynamics and potential price movements. You can run the query [here](https://ide.bitquery.io/Solana-Token) ```graphql { Solana { Instructions( where: {Instruction: {Program: {Name: {is: "timelock"}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Instruction { Accounts { Address IsWritable Token { Mint Owner ProgramId } } Program { AccountNames Address Name Method } Logs } Transaction { Signature Signer } } } } ``` ## Conclusion Token lockups are becoming common in the cryptocurrency world. They help prevent price volatility and ensure long-term success for projects. This builds trust between investors and development teams. However, choosing the right lockup structure is crucial. It should fit the project's goals and objectives. Tracking token locks and unlocks is essential for managing cryptocurrencies effectively. Bitquery APIs offer powerful tools to monitor these events, providing detailed data and customizable queries. By using Bitquery, investors and project teams can stay informed about token movements, make well-informed decisions, and maintain market confidence. --- ## Track ZEC on Hyperliquid — Positions, Liquidations, Funding & Trades API URL: https://docs.bitquery.io/docs/perpetuals/hyperliquid/track-zec-on-hyperliquid/ Track Zcash (ZEC) perp activity on Hyperliquid with the Bitquery API: every open ZEC position market-wide, real-time liquidations, funding payments, whale trades, candles and mark prices over GraphQL and WebSocket. # Track ZEC on Hyperliquid ZEC (Zcash) is one of the most actively traded perp markets on Hyperliquid. This page collects ready-to-run queries for tracking the entire ZEC market — every open position, liquidations as they happen, funding flow, whale-sized fills, candles and mark prices — using the `Hyperliquid` cube on the [streaming API](https://streaming.bitquery.io/graphql). Every query below also works as a real-time WebSocket stream: change `query` to `subscription` and drop `limit`/`orderBy`. :::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 open ZEC position on the exchange `CurrentPositions` is a state cube: it holds the currently open perp position of every trader. Unlike the native Hyperliquid API — which only returns positions for an address you already know — this enumerates the whole ZEC book, so you can compute market-wide long/short totals or find the biggest whales without knowing a single wallet in advance. Negative `Size` is a short; `Funding` is the position's accumulated funding (positive = collected, negative = paid). Run it in the IDE: [All Open ZEC Positions ➤](https://ide.bitquery.io/zec-hyperliquid-open-positions) ```graphql query { Hyperliquid { CurrentPositions( limit: {count: 200} orderBy: {descending: LastTime} where: {Market: {Symbol: {is: "ZEC"}}} ) { LastTime Market { Symbol Kind } Position { Size Leverage IsCross Funding RealizedPnl } Trader { Address } } } } ``` To watch one whale instead, swap the filter to `where: {Trader: {Address: {is: "0x..."}}}` and you get every open position of that wallet across all markets. ## ZEC liquidations — history and live stream Each liquidation carries the liquidated user, the `Method` (`market` for open-market liquidation, `backstop` when the backstop vault takes over), the mark price and the forced execution. The execution `Side` tells you which side got wiped: a liquidated short is closed by a `Buy`, a liquidated long by a `Sell`. Run it in the IDE: [ZEC Liquidations ➤](https://ide.bitquery.io/zec-hyperliquid-liquidations) ```graphql query { Hyperliquid { PerpLiquidations( limit: {count: 100} orderBy: {descending: Block_Time} where: {Liquidation: {Market: {Symbol: {is: "ZEC"}}}} ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx Liquidator LiquidatedUser Execution { Price Size Side } Position { Leverage IsCross Side SizeBefore } } } } } ``` ### Real-time ZEC liquidation alerts Run it in the IDE: [ZEC Liquidations Stream ➤](https://ide.bitquery.io/zec-hyperliquid-liquidations-stream) ```graphql subscription { Hyperliquid { PerpLiquidations( where: {Liquidation: {Market: {Symbol: {is: "ZEC"}}}} ) { Block { Time } Liquidation { Market { Symbol } Method MarkPx LiquidatedUser Execution { Price Size Side } Position { Leverage IsCross SizeBefore } } } } } ``` ## ZEC funding payments — who pays whom `PerpFundings` records every per-trader funding transfer at each hourly tick: the signed `Amount` (negative = the trader paid funding), the `Rate` applied and the position `Size`. When ZEC longs are crowded the rate is positive and longs pay shorts — summing `Amount` over a window shows exactly how much it costs to stay long. Run it in the IDE: [ZEC Funding Payments ➤](https://ide.bitquery.io/zec-hyperliquid-funding-payments) ```graphql query { Hyperliquid { PerpFundings( limit: {count: 200} orderBy: {descending: Block_Time} where: {Funding: {Market: {Symbol: {is: "ZEC"}}}} ) { Block { Time } Funding { Market { Symbol } Amount Rate Size Trader { Address } } } } } ``` Add `Trader: {Address: {is: "0x..."}}` inside the `Funding` filter to compute the total funding one wallet has paid or collected on ZEC. ## Whale-sized ZEC trades Every fill carries direction, leverage and realized PnL. Filter on `Execution: {Size: ...}` to see only whale prints — here, fills of 200 ZEC or more. Run it in the IDE: [ZEC Whale Trades ➤](https://ide.bitquery.io/zec-hyperliquid-whale-trades) ```graphql query { Hyperliquid { Trades( limit: {count: 100} orderBy: {descending: Block_Time} where: {Trade: {Market: {Symbol: {is: "ZEC"}}, Execution: {Size: {ge: "200"}}}} ) { Block { Time } Trade { Execution { Price Size Side Direction IsAggressor } Position { Leverage IsCross RealizedPnl } Trader { Address } } } } } ``` ### Stream every ZEC fill in real time Run it in the IDE: [ZEC Trades Stream ➤](https://ide.bitquery.io/zec-hyperliquid-trades-stream) ```graphql subscription { Hyperliquid { Trades( where: {Trade: {Market: {Symbol: {is: "ZEC"}}}} ) { Block { Time } Trade { Execution { Price Size Side Direction IsAggressor } Position { Leverage IsCross RealizedPnl } Trader { Address } } } } } ``` ## ZEC candles (OHLCV) Candle `Duration` is in seconds — `60` for 1-minute, `300` for 5-minute, `3600` for hourly. Run it in the IDE: [ZEC Hourly Candles ➤](https://ide.bitquery.io/zec-hyperliquid-hourly-candles) ```graphql query { Hyperliquid { Candles( limit: {count: 168} orderBy: {descending: Interval_Time_Start} where: {Market: {Symbol: {is: "ZEC"}}, Interval: {Time: {Duration: {eq: 3600}}}} ) { Interval { Time { Start Duration } } Market { Symbol } Ohlc { Open High Low Close Volume } } } } ``` ## ZEC mark price The latest mark price per market, streamable for live dashboards. Run it in the IDE: [ZEC Mark Price ➤](https://ide.bitquery.io/zec-hyperliquid-mark-price) ```graphql query { Hyperliquid { MarkPrices( limit: {count: 1} orderBy: {descending: LastTime} where: {Market: {Symbol: {is: "ZEC"}}} ) { LastTime Mark Market { Symbol Kind } } } } ``` ## ZEC leverage changes `TraderLeverageUpdates` fires whenever a trader changes leverage or flips between cross and isolated margin on ZEC — often the tell that a large position is about to be opened or defended. Run it in the IDE: [ZEC Leverage Updates ➤](https://ide.bitquery.io/zec-hyperliquid-leverage-updates) ```graphql query { Hyperliquid { TraderLeverageUpdates( limit: {count: 100} orderBy: {descending: Block_Time} where: {LeverageUpdate: {Market: {Symbol: {is: "ZEC"}}}} ) { Block { Time } LeverageUpdate { Leverage IsCross Market { Symbol } Trader { Address } } } } } ``` ## Related pages - [Hyperliquid API overview](/docs/perpetuals/hyperliquid) — all available cubes and the Kafka streams - [Trades & Candles](/docs/perpetuals/hyperliquid/hyperliquid-trades-api) - [Liquidations, Funding, Positions & Leverage](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api) - [Mark Prices & Price Updates](/docs/perpetuals/hyperliquid/hyperliquid-prices-api) --- ## Trade Labelling Module URL: https://docs.bitquery.io/docs/usecases/wash-trading-detector/prepare-data/label/ Build Trade Labelling Module: a practical Bitquery tutorial with GraphQL examples, streams, and runnable application code. # Trade Labelling Module The `label.py` module provides a single function, `label_trades`, that accepts raw DEX trade data and applies a series of rule-based checks to label each trade as wash trade or not. These rules are imported from `token_rules.py`, allowing us to maintain a clean separation between rule logic and labeling orchestration. ## Purpose The goal of this module is to return a labeled DataFrame with a new column `is_wash_trade`, where: - `1` means the trade is flagged as wash trade - `0` means the trade is considered normal ## Understanding Code Logic ### Imports and Function Initialisation ```py from token_rules import ( detect_self_trades, detect_repeated_pairs, detect_loops, detect_spoofing, get_suspicious_summary ) def label_trades(trade_data): # All the code written below is placed here ``` - Imports all rule functions from `token_rules.py`. - Uses `pandas` to work with structured tabular data. ### Flattening Trade Data Converts the nested JSON object into a flat pandas Dataframe. ```py df = pd.json_normalize(trade_data) ``` ### Applying Rules Each function returns a filtered DataFrame of suspicious trades that match one rule and finaly returns suspicious trades. ```py self_trades = detect_self_trades(df) repeated_pairs = detect_repeated_pairs(df) loops = detect_loops(df) spoofing = detect_spoofing(df) suspicious_tokens, suspicious_tx, suspicious_wallets = get_suspicious_summary( self_df=self_trades, repeated_df=repeated_pairs, loops_df=loops, spoofed_df=spoofing, original_df=df ) ``` ### Return Labeled Data The suspicious trades are labelled as wash trades and returned. ```py df["is_wash_trade"] = ( df["Trade.Buy.Account.Address"].isin(suspicious_wallets) | df["Trade.Sell.Account.Address"].isin(suspicious_wallets) | df["Transaction.Signature"].isin(suspicious_tx) ) return df ``` --- ## Traders API: Stream and Rank Wallet Trades on Solana, Ethereum, BSC, Base URL: https://docs.bitquery.io/docs/trading/crypto-trades-api/traders-api/ Wallet view of the Trading API: stream one or many wallets' DEX trades, filter by token, chain, DEX or pair, catch whale trades, rank traders by volume and PnL. # Traders API: Stream and Rank Wallet Trades on Solana, Ethereum, BSC, Base The Traders API is the wallet view of `Trading.Trades`: every DEX trade a wallet makes on Solana, Ethereum, BSC, Base, Arbitrum and the other chains the cube covers, with the token pair, the USD amounts, the market and the side on each row. Filter on `Trader.Address` for one wallet, `in` for a watchlist, and combine with token, chain, DEX or pair filters. The cube keeps about a month of trades, which is where copy trading, whale alerts and leaderboards live; for older wallet history use the chain cubes. Every example runs in the [IDE](https://ide.bitquery.io) on a free account. The worked wallet, `AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51`, is one of the most active Solana wallets at the time of writing; take any address from the top-traders query below. ## Video Tutorial ## How do I stream all trades of a wallet? Every DEX trade the wallet sends, on every chain, as it lands. Saved stream [here](https://ide.bitquery.io/All-trades-of-a-trader). ```graphql subscription { Trading { Trades(where: { Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } }) { Block { Time } Side Price PriceInUsd Amounts { Base Quote } AmountsInUsd { Base Quote } Pair { Token { Symbol Id } QuoteToken { Symbol Id } Market { Address Protocol Network } } TransactionHeader { Fee } } } } ``` ## How do I track a wallet's trades on one token? The token can sit on either side of a pair, so match `Pair.Token.Id` or `Pair.QuoteToken.Id` with `any`. Token ids are `bid::
`. Saved stream [here](https://ide.bitquery.io/trades-of-a-specific-trader-of-a-specific-token_1). ```graphql subscription { Trading { Trades( where: { Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } any: [ { Pair: { Token: { Id: { is: "bid:solana:AGi2s9zPRPHs3zEDPhPTroumTEXK5ufymYSfEFndCSSW" } } } } { Pair: { QuoteToken: { Id: { is: "bid:solana:AGi2s9zPRPHs3zEDPhPTroumTEXK5ufymYSfEFndCSSW" } } } } ] } ) { Block { Time } Side PriceInUsd AmountsInUsd { Base Quote } Pair { Token { Symbol } QuoteToken { Symbol } Market { Protocol } } } } } ``` ## How do I monitor several wallets in one subscription? An `in` list on the trader address; each message carries the wallet it belongs to. Saved stream [here](https://ide.bitquery.io/How-do-I-monitor-multiple-wallets-in-one-subscription). ```graphql subscription { Trading { Trades( where: { Trader: { Address: { in: [ "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" "Gygj9QQby4j2jryqyqBHvLP7ctv2SaANgh4sCb69BUpA" "FHpcNSe6tb2n15bAdq4BkeYWGyZKFD7yLYrH92ng7wCT" ] } } } ) { Block { Time } Trader { Address } Side AmountsInUsd { Base } Pair { Token { Symbol } QuoteToken { Symbol } Market { Network Protocol } } } } } ``` ## How do I stream a wallet's trades on one chain? Add `Pair.Market.Network`. Saved stream [here](https://ide.bitquery.io/How-do-I-stream-a-wallets-trades-on-a-specific-chain). ```graphql subscription { Trading { Trades( where: { Pair: { Market: { Network: { is: "Solana" } } } Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } } ) { Block { Time } Side AmountsInUsd { Base } Pair { Token { Symbol } QuoteToken { Symbol } Market { Address Protocol } } } } } ``` ## How do I catch whale trades as they happen? Trades over a hundred thousand dollars on any chain, which arrive steadily across the cube. Saved stream [here](https://ide.bitquery.io/Stream---Trades-over-100k-usd). ```graphql subscription { Trading { Trades(where: { AmountsInUsd: { Base: { gt: 100000 } } }) { Block { Time } Side Trader { Address } AmountsInUsd { Base Quote } Pair { Token { Symbol } QuoteToken { Symbol } Market { Network Protocol } } } } } ``` ## How do I get the whale trades of one wallet? Combine the trader and the USD floor. The example wallet makes six-figure stablecoin trades on Manifest at the time of writing, so the query form over the last day returns rows; the same `where` as a subscription fires only when the wallet trades. Saved query [here](https://ide.bitquery.io/How-do-I-stream-whale-trades-for-a-specific-wallet). ```graphql { Trading { Trades( where: { Trader: { Address: { is: "5edLA6ZZFAUfDa8mkdPTi6GXY7fqiZ3CrbRwF7dCGjgr" } } AmountsInUsd: { Base: { gt: 100000 } } Block: { Time: { since_relative: { hours_ago: 24 } } } } orderBy: { descending: Block_Time } limit: { count: 20 } ) { Block { Time } Side AmountsInUsd { Base } Pair { Token { Symbol } QuoteToken { Symbol } Market { Network Protocol } } } } } ``` ## How do I get a wallet's recent trades? The last ten minutes as a query, newest first. Saved query [here](https://ide.bitquery.io/How-do-I-get-recent-trades-for-a-wallet-last-10-minutes). ```graphql { Trading { Trades( orderBy: { descending: Block_Time } limit: { count: 50 } where: { Block: { Time: { since_relative: { minutes_ago: 10 } } } Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } } ) { Block { Time } Side Price PriceInUsd AmountsInUsd { Base Quote } Pair { Token { Symbol Id } QuoteToken { Symbol } Market { Address Protocol Network } } } } } ``` ## How do I watch several wallets on one token? A watchlist and a token together, the copy-trading shape. Saved stream [here](https://ide.bitquery.io/How-do-I-monitor-multiple-wallets-trading-a-specific-token). ```graphql subscription { Trading { Trades( where: { Trader: { Address: { in: [ "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" "Gygj9QQby4j2jryqyqBHvLP7ctv2SaANgh4sCb69BUpA" ] } } any: [ { Pair: { Token: { Id: { is: "bid:solana:AGi2s9zPRPHs3zEDPhPTroumTEXK5ufymYSfEFndCSSW" } } } } { Pair: { QuoteToken: { Id: { is: "bid:solana:AGi2s9zPRPHs3zEDPhPTroumTEXK5ufymYSfEFndCSSW" } } } } ] } ) { Block { Time } Trader { Address } Side AmountsInUsd { Base } Pair { Token { Symbol } QuoteToken { Symbol } } } } } ``` ## How do I stream a wallet's trades on one DEX? `Pair.Market.Program` is the DEX program on Solana and the router or pool manager on EVM chains; the example is Raydium's CPMM. Saved stream [here](https://ide.bitquery.io/How-do-I-stream-a-wallets-trades-on-a-specific-DEX). ```graphql subscription { Trading { Trades( where: { Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } Pair: { Market: { Program: { is: "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C" } } } } ) { Block { Time } Side AmountsInUsd { Base } Pair { Token { Symbol } QuoteToken { Symbol } Market { Address Protocol } } } } } ``` ## How do I get a wallet's trades on one pair? Pin both token ids; here WSOL against USDC. Saved stream [here](https://ide.bitquery.io/How-do-I-get-a-wallets-trades-on-a-specific-pair). ```graphql subscription { Trading { Trades( where: { Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } Pair: { Token: { Id: { is: "bid:solana:So11111111111111111111111111111111111111112" } } QuoteToken: { Id: { is: "bid:solana:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } ) { Block { Time } Side Price AmountsInUsd { Base } Pair { Market { Address Protocol } } } } } ``` ## Who are the most active traders on Solana this hour? Wallets ranked by trade count, with USD volume split by side. Change the network or the window as needed. Saved query [here](https://ide.bitquery.io/Most-active-traders-by-trade-count). ```graphql { Trading { Trades( limit: { count: 100 } orderBy: [{ descendingByField: "Trades_count" }] where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pair: { Market: { Network: { is: "Solana" } } } } ) { Trader { 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" } }) } } } ``` Sort the same query on `Total_Volume` to rank whales by USD volume instead. Saved query [here](https://ide.bitquery.io/Whales-traders-by-total-USD-volume_1). ## Which wallets only bought, or only sold, this hour? `selectWhere` on an aggregate keeps rows where that count is zero. Sort by volume to see the largest one-sided flows. Saved queries: [only buys](https://ide.bitquery.io/Traders-who-only-buys), [only sells](https://ide.bitquery.io/Traders-who-only-sells_1). ```graphql { Trading { Trades( limit: { count: 100 } orderBy: [{ descendingByField: "Total_Volume" }] where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pair: { Market: { Network: { is: "Solana" } } } } ) { Trader { Address } Trades_count: count Total_Volume: sum(of: AmountsInUsd_Quote) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }, selectWhere: { eq: "0" }) } } } ``` For wallets that only sold, move `selectWhere` to `buys`. ## Which pools did a wallet trade this hour? One row per market with the counts and USD volume. Saved query [here](https://ide.bitquery.io/Trader-interacted-with-these-tokens). ```graphql { Trading { Trades( limit: { count: 100 } orderBy: [{ descendingByField: "Trades_count" }] where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pair: { Market: { Network: { is: "Solana" } } } Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } } ) { Pair { Market { Address Protocol } Token { Symbol Id } QuoteToken { Symbol } } Trades_count: count Total_Volume: sum(of: AmountsInUsd_Base) buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ``` ## How do I calculate a wallet's PnL on one token? Sum what the wallet paid and what it received in USD over the window; `calculate` takes the difference. It is a cash-flow PnL over the window, so open inventory is not marked to market. Saved query [here](https://ide.bitquery.io/Traders-PnL-for-the-last-30mins-for-a-specific-token). ```graphql { Trading { Trades( where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Token: { Id: { is: "bid:solana:AGi2s9zPRPHs3zEDPhPTroumTEXK5ufymYSfEFndCSSW" } } } Trader: { Address: { is: "AgmLJBMDCqWynYnQiPCuj9ewsNNsBJXyzoUhD9LJzN51" } } } ) { Trader { Address } Pair { Token { Symbol } } 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" } }) } } } ``` ## How do I rank traders by PnL on one pool? Filter `Pair.Market.Address` and sort on the calculated field. Saved query [here](https://ide.bitquery.io/Top-Traders-by-PnL-of-a-specific-pair). ```graphql { Trading { Trades( limit: { count: 10 } orderBy: [{ descendingByField: "PnL" }] where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Address: { is: "CsjcF4mEmJsXZDWzBtuviVEV7JiKTY4NAJ1rdcHhVxi3" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") buys: count(if: { Side: { is: "Buy" } }) sells: count(if: { Side: { is: "Sell" } }) } } } ``` ## How do I rank traders by PnL across Solana? Drop the pool filter and keep one row per wallet with `limitBy`. Saved query [here](https://ide.bitquery.io/Top-Traders-on-Solana_2). ```graphql { Trading { Trades( limit: { count: 10 } limitBy: { count: 1, by: Trader_Address } orderBy: [{ descendingByField: "PnL" }] where: { Block: { Time: { since_relative: { minutes_ago: 30 } } } Pair: { Market: { Network: { is: "Solana" } } } } ) { Trader { Address } Amount_Bought: sum(of: AmountsInUsd_Base, if: { Side: { is: "Buy" } }) Amount_Sold: sum(of: AmountsInUsd_Base, if: { Side: { is: "Sell" } }) PnL: calculate(expression: "$Amount_Sold - $Amount_Bought") } } } ``` ## Which traders paid the most fees this hour? `TransactionHeader.Fee` summed per wallet, a quick way to spot bots. Saved query [here](https://ide.bitquery.io/Traders-paying-the-highest-total-fees). ```graphql { Trading { Trades( limit: { count: 100 } orderBy: [{ descendingByField: "Total_fees_paid_by_trader" }] where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Pair: { Market: { Network: { is: "Solana" } } } } ) { Trader { Address } Trades_count: count Total_fees_paid_by_trader: sum(of: TransactionHeader_Fee) Total_Volume: sum(of: AmountsInUsd_