# Bitquery Docs — full text: Getting started, authorization, GraphQL, cubes, streams, gRPC, Kafka, cloud, MCP and everything else > 192 pages. All parts and the curated entry points: https://docs.bitquery.io/llms.txt ## API Schema Overview URL: https://docs.bitquery.io/docs/schema/schema-intro/ API Schema Overview: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. Great for bots, dashboards, and alerts. # API Schema Overview This section documents the Bitquery GraphQL **schema** — the fields, filters, and relationships you use to build queries — for both EVM and non-EVM chains. ## How the schema is organized Bitquery models blockchain data as **cubes** — typed collections like `Transfers`, `DEXTrades`, `Balances`, `Events`, and `Calls`. Each cube exposes: - **Dimensions** — the fields you select and group by (addresses, tokens, block time, amounts). - **Filters** — the `where` conditions that narrow results (see [filters](/docs/graphql/filters/)). - **Metrics** — aggregations like `sum`, `count`, and `uniq` (see [metrics](/docs/graphql/metrics/metrics/)). EVM chains (Ethereum, BSC, Base, Arbitrum, Arc, …) share one cube shape under the `EVM(...)` root; non-EVM chains (Solana, Tron, Bitcoin) have parallel cubes under their own roots. ## Browse the schema in the IDE The fastest way to explore fields is the schema explorer in the [Bitquery IDE](https://ide.bitquery.io/) — the left panel lists every cube and field for the selected endpoint, with inline types and descriptions. ## Which dataset a field comes from Field availability and history depth depend on the **dataset** (`realtime`, `archive`, `combined`) and the chain — see the [Data Coverage & Retention matrix](/docs/graphql/data-coverage-retention/) before assuming a field has deep history. ## Next steps - [Understanding cubes](/docs/category/understanding-cubes/) - [Building queries](/docs/graphql/query/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) --- ## Address Labels API: Identify Crypto Wallets URL: https://docs.bitquery.io/docs/labels/address-labels-api/ Identify wallets and contracts with the Bitquery Address Labels API: exchange hot and cold wallets, deposit addresses, token contracts and clones, any chain. # Address Labels API: Identify Crypto Wallets The Address Labels API tells you **who is behind a blockchain address**: which exchange owns a hot wallet, whether an address is a per-user deposit address, whether a contract is a token (or a clone imitating one), and whether an address has been frozen by a stablecoin issuer. One GraphQL query, `Metadata { Labels }`, answers this across EVM chains, Solana, Bitcoin, and Tron. | | | | -------------- | ---------------------------------------------------------------------------------------- | | **Cube** | `Metadata.Labels` | | **Endpoints** | `https://streaming.bitquery.io/graphql` | | **Auth** | [OAuth token](/docs/authorization/how-to-generate) as `Authorization: Bearer ` | | **Required** | An `Address` filter on every query | | **Batch size** | Up to **100 addresses** per query | | **Streaming** | Query-only, no subscription. Poll `RecordedAt` for newly added labels | Most people use it as the second step of a two-query pattern: pull addresses from an activity API such as [DEXTrades](/docs/cubes/dextrades) or [Transfers](/docs/cubes/transfers-cube), then resolve those addresses to entities here. Use the result to enrich analytics, screen flows for exchange or gambling exposure, or strip exchange and contract addresses out of "real user" metrics. ## Rules that matter 1. **The `Address` filter is mandatory.** Every query must pin `Address` with `is` or `in`. There is no way to list all addresses carrying a label. Without it you get: `"Labels query requires a Address filter in the where clause"`. 2. **Up to 100 addresses per query.** Split larger lists into batches of 100. 3. **Matching is exact and case-sensitive.** Pass EVM addresses in **lowercase**. A checksummed `0xAbC…` returns zero rows. Bitcoin, Solana, and Tron addresses are case-sensitive by nature, so pass them exactly as they appear on-chain. 4. **Labels can be corrected or removed, and old versions are not kept.** An address returns one row per chain, per label, per recording pass, so the same label can recur with different `RecordedAt` values. Fold that into a current view with `limitBy`, [shown below](#how-to-get-only-the-current-labels). When we find a wrong label we fix or delete it in place, so re-run a full lookup to pick up corrections. ## How to look up labels for one address ```graphql { Metadata { Labels( where: {Address: {in: ["0x18e296053cbdf986196903e889b7dca7a73882f6"]}} ) { Address Chain Label { Type Value } RecordedAt } } } ``` The response identifies the address as a Bybit hot wallet on every chain where it is labeled (abridged; the full response also repeats labels recorded on earlier passes): ```json { "Metadata": { "Labels": [ { "Address": "0x18e296053cbdf986196903e889b7dca7a73882f6", "Chain": "ethereum", "Label": { "Type": "cex-hot-wallet", "Value": "bybit-hot-1" }, "RecordedAt": "2026-07-31T13:11:13Z" }, { "Address": "0x18e296053cbdf986196903e889b7dca7a73882f6", "Chain": "bsc", "Label": { "Type": "cex-hot-wallet", "Value": "bybit-hot" }, "RecordedAt": "2026-07-22T07:53:03Z" } ] } } ``` ## How to get only the current labels Because the same label can come back once per recording pass, most applications want the **latest record per address, chain, and label type**. `limitBy` plus a `RecordedAt` sort does exactly that, and this is the shape you should reach for by default: ```graphql { Metadata { Labels( where: {Address: {is: "0x18e296053cbdf986196903e889b7dca7a73882f6"}} limitBy: {by: [Address, Chain, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } RecordedAt } } } ``` This returns one clean row per chain instead of the wallet's full recording history. Note the nested field is addressed as `Label_Type` in `limitBy` and `orderBy`. The groupable and sortable names are `Address`, `Chain`, `Label_Type`, `Label_Value`, and `RecordedAt`. Keep `Label_Type` in the `limitBy` key unless you deliberately want one row per address: an address can legitimately carry several different labels, since a token contract is often tagged both `token-contract` and `contract`. ## How to label up to 100 addresses at once Pass the list as a variable. This is the shape to use when enriching the output of another query, such as top traders, transfer counterparties, or token holders: ```graphql query ($addresses: [String!]) { Metadata { Labels( where: {Address: {in: $addresses}} limitBy: {by: [Address, Chain, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } RecordedAt } } } ``` ```json { "addresses": [ "0x18e296053cbdf986196903e889b7dca7a73882f6", "0x28c6c06298d514db089934071355e5743bf21d60" ] } ``` Addresses with no labels are simply absent from the response, with no error and no placeholder row. Anything missing is "unlabeled so far", which in wallet analytics usually means an ordinary user wallet. ## How to check if an address is an exchange wallet Combine a batch with a `Label.Type` filter to keep only exchange-owned addresses: ```graphql { Metadata { Labels( where: { Address: {in: [ "0x28c6c06298d514db089934071355e5743bf21d60", "0x18e296053cbdf986196903e889b7dca7a73882f6", "0x7a250d5630b4cf539739df2c5dacb4c659f2488d" ]} Label: {Type: {in: ["cex-hot-wallet", "cex-cold-wallet", "cex-deposit-address"]}} Chain: {is: "ethereum"} } limitBy: {by: [Address, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Label { Type Value } RecordedAt } } } ``` Only the Binance and Bybit hot wallets come back. The Uniswap router drops out because its labels (`contract: uniswap`) don't match the requested types, which is exactly how you separate exchange addresses from protocol contracts in a mixed list. ## How to screen for issuer-blocked (frozen) addresses Stablecoin issuers freeze addresses on their own contracts. `issuer-blocked-usdt` and `issuer-blocked-usdc` capture those, so a `startsWith` filter screens for both at once: ```graphql { Metadata { Labels( where: { Address: {in: [ "0x098b716b8aaf21512996dc57eb0615e2383e2f96", "0x28c6c06298d514db089934071355e5743bf21d60" ]} Label: {Type: {startsWith: "issuer-blocked"}} } limitBy: {by: [Address, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } } } } ``` ## How to label Bitcoin, Tron, and Solana addresses Address formats mix freely in one batch. Each row's `Chain` tells you where the label applies: ```graphql { Metadata { Labels( where: {Address: {in: [ "34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM" ]}} limitBy: {by: [Address, Chain, Label_Type], count: 1} orderBy: {descending: RecordedAt} ) { Address Chain Label { Type Value } } } } ``` This resolves a Binance Bitcoin cold wallet (`Chain: "bitcoin"`), the USDT contract on Tron (`Chain: "tron"`), and a Binance cold wallet on Solana (`Chain: "solana"`). ## How to watch for newly added labels The cube has no subscription, so poll the addresses you track with a `RecordedAt` window and keep the high-water mark on your side: ```graphql { Metadata { Labels( where: { Address: {is: "0x18e296053cbdf986196903e889b7dca7a73882f6"} RecordedAt: {since: "2026-07-15T00:00:00Z"} } ) { Chain Label { Type Value } RecordedAt } } } ``` This window catches newly added labels only. Labels can be corrected or removed when we find errors, and earlier versions are not kept. A label we fix can keep its old `RecordedAt`, so it never enters the window, and a label we remove simply disappears. To catch corrections, re-run a full lookup on the addresses you track from time to time and compare it with what you stored. ## How to aggregate labels The cube supports the standard [metrics](/docs/graphql/calculations) `count` and `uniq`, and the dimensions you select become the grouping key. This counts label records and distinct labeled addresses per chain: ```graphql { Metadata { Labels( where: {Address: {in: [ "0x18e296053cbdf986196903e889b7dca7a73882f6", "0x28c6c06298d514db089934071355e5743bf21d60", "0xdac17f958d2ee523a2206206994597c13d831ec7" ]}} ) { Chain count uniq(of: Address) } } } ``` ## Filters Full [filter](/docs/graphql/filters) support applies on top of the mandatory `Address`: | Filter | Operators | Notes | | --- | --- | --- | | `Address` | `is`, `in` **only** | Mandatory, max 100 in `in`. No negation, so you cannot exclude addresses server-side. | | `Chain` | `is`, `in`, `not`, `notIn`, `like`, `includes`, `startsWith`, … | Exact chain slugs, listed in the table below. | | `Label: {Type: …}` | full string set | e.g. `{is: "cex-hot-wallet"}` | | `Label: {Value: …}` | full string set | e.g. `{startsWith: "binance"}` | | `RecordedAt` | `since`, `till`, `after`, `before`, `is`, plus `_relative` variants | Standard [DateTime filters](/docs/graphql/datetime). | | `any` | list of sub-filters | OR-combinator across conditions. | ## Response fields | Field | Type | Meaning | | --- | --- | --- | | `Address` | String | The queried address, exactly as stored (EVM addresses lowercase). | | `Chain` | String | Chain this label applies to. One address can map to many chains. | | `Label.Type` | String | Label category, listed below. | | `Label.Value` | String | Entity slug within the category, e.g. `binance-hot-1`, `bybit-hot`, `wavax`, `banned-by-usdt`. Numbered suffixes distinguish instances of the same entity. | | `RecordedAt` | DateTime | When the row was added to Bitquery's label table. Most Bitcoin labels carry 28 May 2026, the date of the first bulk load, so it does not tell you when an address was first identified. A corrected label can keep its old `RecordedAt`. | ### Supported chains `Chain` values are plain slugs and the set grows as coverage expands. Verified live: | Ecosystem | `Chain` values | | --- | --- | | EVM | `ethereum`, `bsc`, `polygon`, `arbitrum`, `base`, `avalanche-c`, `fantom`, `ethpow` | | Non-EVM | `bitcoin`, `tron`, `solana` | If you're unsure what a chain is called, query a known address from it without a `Chain` filter and read the slug off the response. ### Label types `Label.Type` is an **open taxonomy**. New categories appear as the pipeline learns new entity classes, so handle unknown types gracefully. The common ones: | `Label.Type` | Meaning | Example `Value` | | --- | --- | --- | | `cex-hot-wallet` | Exchange-operated hot wallet | `binance-hot-1`, `bybit-hot` | | `cex-cold-wallet` | Exchange cold storage | `binance-cold` | | `cex-deposit-address` | Per-user deposit address swept to an exchange | `coinex-deposit` | | `token-contract` | A token's contract or mint address | `usdt`, `wavax`, `wbnb` | | `token-clone` | Contract imitating a well-known token | `clone-wmatic-2` | | `contract` | General smart-contract tag | `uniswap`, `bridge`, `stablecoin` | | `gambling` | Gambling platform wallet | `stake-com-hot` | | `issuer-blocked-usdt` | Frozen or blacklisted by Tether | `banned-by-usdt` | | `issuer-blocked-usdc` | Frozen or blacklisted by Circle | `banned-by-usdc` | ## Limits and common errors - **Missing `Address` filter.** The query fails with `"Labels query requires a Address filter in the where clause"`. A `Chain` or `Label` filter alone does not satisfy it. - **Wrong casing.** A checksummed EVM address silently returns zero rows. Lowercase before querying. - **No negation on `Address`.** `not`/`notIn` aren't part of the `Address` filter. Exclusion belongs client-side, or in `Chain`/`Label` filters, which do support it. - **Subscriptions.** `subscription { Metadata { … } }` is rejected; the cube exists only under `query`. - **Empty result is not an error.** Unlabeled addresses, and an empty `in: []`, return an empty list. - **[`limit` / `limitBy`](/docs/graphql/limits) and [`orderBy`](/docs/graphql/sorting)** behave as on every other cube. ## Pick the right query | You need | Use | | --- | --- | | Who is behind one address | `Address: {is: …}` | | Enrich a list of ≤100 addresses | `Address: {in: …}` with `limitBy: {by: [Address, Chain, Label_Type], count: 1}` | | Exchange-wallet screening | `Label: {Type: {in: ["cex-hot-wallet", "cex-cold-wallet", "cex-deposit-address"]}}` | | Fake-token checks | `Label: {Type: {is: "token-clone"}}` | | Sanctions and issuer-freeze screening | `Label: {Type: {startsWith: "issuer-blocked"}}` | | Newly added labels | Poll with `RecordedAt: {since: …}`, plus a periodic full lookup for corrections | ## Related - [DEXTrades cube](/docs/cubes/dextrades): trade activity whose maker and taker addresses you can label - [Transfers cube](/docs/cubes/transfers-cube): transfer counterparties to enrich - [Balances & Holders cubes](/docs/cubes/balances-cube): what the addresses you identified actually hold - [Filtering](/docs/graphql/filters), [Sorting](/docs/graphql/sorting), [Limits](/docs/graphql/limits): the query mechanics used above --- ## 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"] } ] } } ``` --- ## 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/) --- ## BSC Data - BNB Chain Export for Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/bsc/ BNB Chain blocks, transactions, transfers, balance updates, DEX trades, calls and events as Parquet, with a free sample and DuckDB and Python examples. # BSC Data - BNB Chain Bitquery provides **BSC (BNB Chain) blockchain data 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: ``` 77611000_77611049.parquet ``` ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=bsc), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Datasets you can buy on the Data Store: - [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) — every native BNB and token transfer, with sender, receiver and USD value ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bsc/dex_trades/77611000_77611049.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bsc/transfers/77611000_77611049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access 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** --- ## 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. --- ## Balances & Holders Cubes URL: https://docs.bitquery.io/docs/cubes/balances-cube/ Query current token and native balances per address with the Balances cube, and rank a token's holders with the Holders cube, on EVM chains and Tron. # Balances & Holders Cubes :::caution These cubes are query-only `Balances` and `Holders` are derived views that answer "what is true now", so there is no underlying event to push. A subscription against either is a valid document and the socket stays open, but **no message is ever delivered** — on EVM or Tron. For live balances, read the balance once and then keep it current from a stream that does fire: `EVM.TransactionBalances` or `EVM.Transfers` (and `Tron.Transfers` on Tron). See [which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/). ::: Two cubes answer balance questions, and picking the right one matters more than the fields you select: | Cube | Question it answers | Shape | | --- | --- | --- | | **`Balances`** | *What does this address hold?* | Current balance per address, live — no snapshot date | | **`Holders`** | *Who holds this token?* | A token's holders ranked by balance, as a dated snapshot | Both read from aggregate-state tables (`balances_by_address` / `balances_by_currency`), so they return the current state directly instead of replaying every change. :::note Availability `Balances` and `Holders` exist on **EVM networks** (`EVM(network: …)`) and **Tron** (`Tron`). They do **not** exist on Solana. Solana balance changes are queried with [`Solana.BalanceUpdates`](/docs/blockchain/Solana/solana-balance-updates) and `Solana.InstructionBalanceUpdates`. ::: ## Balances — what an address holds `Balances` returns one row per address/currency pair with the current amount. `Balance` fields: `Address`, `Amount`, `AmountInUSD`, `UpdateCount`, `FirstChangeTime`, `LastChangeTime`. Its `where` filter accepts **`Balance.Address`** plus `Currency` and `Block`. Note there is **no amount filter** on `Balances` — see [Holders](#holders) if you need to filter or rank by balance size. ### Token balance for one or more addresses ```graphql query TokenBalances($addresses: [String!], $token: String!) { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { in: $addresses } } Currency: { SmartContract: { is: $token } } } orderBy: { descending: Balance_Amount } ) { Balance { Address Amount AmountInUSD UpdateCount LastChangeTime } Currency { Symbol Name SmartContract } } } } ``` ```json { "addresses": [ "0x28C6c06298d514Db089934071355E5743bf21d60", "0x21a31Ee1afC51d94C2eFcCAa2092aD1028285549" ], "token": "0xdac17f958d2ee523a2206206994597c13d831ec7" } ``` To exclude zero balances, apply the filter on the field rather than in `where`: `Amount(selectWhere: { gt: "0" })`. ### Native balance Filter on `Currency: { Native: true }` to get the chain's native asset instead of a token: ```graphql { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x28C6c06298d514Db089934071355E5743bf21d60" } } Currency: { Native: true } } ) { Balance { Address Amount AmountInUSD } Currency { Symbol Native } } } } ``` The same query works on Tron by swapping the selector for `Tron` and using a Tron address. ### Classifying an address from its balance metadata `UpdateCount` with `LastChangeTime` separates wallet types without any labelling data: - **Very high `UpdateCount`, `LastChangeTime` seconds ago** — exchange hot wallet or payment processor; the balance churns continuously. - **Single-digit `UpdateCount` on a large balance** — cold storage, treasury or custody. Funded once, rarely touched. :::caution `FirstChangeTime` is not the address's first-ever activity `FirstChangeTime` reflects the earliest change **within the balances table's retention window**, not the first time the address ever moved funds. For true first-activity, query [Transfers](/docs/cubes/transfers-cube) with an ascending time order instead. ::: ## Holders — who holds a token {#holders} `Holders` lists a token's holders, ranked. It takes a **`date`** argument for the snapshot day, and unlike `Balances` it **does** accept a balance filter — which is what makes large tokens tractable. ```graphql query TopHolders($token: String!, $floor: String!, $date: String!) { EVM(network: eth) { Holders( limit: { count: 100 } orderBy: { descending: Balance_Amount } date: $date where: { Currency: { SmartContract: { is: $token } } Balance: { Amount: { ge: $floor } } } ) { Holder { Address } Balance { Amount } Currency { Symbol Name } } } } ``` ```json { "token": "0x514910771AF9Ca656af840dff83E8264EcF986CA", "floor": "1000000", "date": "2026-07-29" } ``` :::caution Set a balance floor on large tokens An unbounded top-N ranking across every holder of a very large token **times out server-side** — this is a dataset-size limit, not a syntax error. Ethereum USDT times out even with a 50,000,000 floor; Tron USDT behaves the same way. The fix is a `Balance: { Amount: { ge: … } }` floor high enough to shrink the working set. For a *complete* holder distribution rather than the top of it, use [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`. | ## Daily balance history `Balances` in the `archive` dataset gives you **one row per address per day**, exposed as `Block.Date`. A 30-day balance history is one query returning 30 rows. ```graphql query DailyBalanceHistory { EVM(network: eth, dataset: archive) { Balances( where: { Balance: { Address: { is: "0x28c6c06298d514db089934071355e5743bf21d60" } } } orderBy: { descending: Block_Date } limit: { count: 30 } ) { Block { Date } Balance { Amount AmountInUSD } Currency { Symbol } } } } ``` Always order by `Block_Date`. Without it you get an arbitrary day and the query still succeeds, which makes the mistake silent. | You need | Use | |---|---| | Current balance per address | `Balances` (latest row) | | Balance on a past date, or a daily series | `Balances` with `Block.Date` — or `Holders(date: …)`, which agrees exactly | | A token's holders, ranked | `Holders` | | When a position first or last moved | `Balances` — `FirstChangeTime`, `LastChangeTime`, `UpdateCount` | | The individual transfers behind a change | [`Transfers`](/docs/cubes/transfers-cube) | The daily aggregate does not say *why* a balance moved. For that, use [`Transfers`](/docs/cubes/transfers-cube) plus transaction context, or `TransactionBalances` for per-transaction balance changes. ## Related - [Address Labels API](/docs/labels/address-labels-api) — identify which of those addresses are exchanges, contracts, or known entities - [Transfers cube](/docs/cubes/transfers-cube) — the transfers that drive most balance changes - [Token Holders API (Ethereum)](/docs/blockchain/Ethereum/token-holders/token-holder-api) — worked `EVM.Holders` examples - [TRC20 USDT API](/docs/blockchain/Tron/usdt-trc20-api) — `Tron.Balances` and `Tron.Holders` in practice --- ## 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). --- ## Bitcoin Data - Snowflake, AWS S3, GCP BigQuery URL: https://docs.bitquery.io/docs/cloud/bitcoin/ Bitcoin blocks, transactions, inputs, outputs and Omni Layer data as Parquet files, with a free sample, the file layout and DuckDB and Python examples. # Bitcoin Data Bitquery provides **Bitcoin blockchain data 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: ``` 932100_932149.parquet ``` ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=bitcoin), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Datasets you can buy on the Data Store: - [Bitcoin](https://bitquery.io/datastore/datasets/bitcoin) — blocks, transactions, inputs, outputs and Omni Layer data since genesis ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bitcoin/transactions/932100_932149.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/bitcoin/blocks/932100_932149.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access 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 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. --- ## 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` | | Arc Mainnet | `https://streaming.bitquery.io/graphql` | | Arc Testnet | `https://streaming.bitquery.io/graphql` | ## Asia ### V1 - Historical Data API ``` https://asia.graphql.bitquery.io ``` ### V2 - Streaming API The following chains are available via the Asia regional endpoint: | Blockchain | Endpoint | |------------|----------| | Ethereum | `https://asia.streaming.bitquery.io/graphql` | | BSC (Binance Smart Chain) | `https://asia.streaming.bitquery.io/graphql` | | Base | `https://asia.streaming.bitquery.io/graphql` | | Solana | `https://asia.streaming.bitquery.io/graphql` | | Arbitrum | `https://asia.streaming.bitquery.io/graphql` | | Optimism | `https://asia.streaming.bitquery.io/graphql` | | Tron | `https://asia.streaming.bitquery.io/graphql` | | Matic (Polygon) | `https://asia.streaming.bitquery.io/graphql` | ## United States ### V1 - Historical Data API ``` https://us.graphql.bitquery.io ``` ### V2 - Streaming API The following chains are available via the United States regional endpoint: | Blockchain | Endpoint | |------------|----------| | Ethereum | `https://us.streaming.bitquery.io/graphql` | | BSC (Binance Smart Chain) | `https://us.streaming.bitquery.io/graphql` | | Base | `https://us.streaming.bitquery.io/graphql` | | Solana | `https://us.streaming.bitquery.io/graphql` | | Arbitrum | `https://us.streaming.bitquery.io/graphql` | | Optimism | `https://us.streaming.bitquery.io/graphql` | | Tron | `https://us.streaming.bitquery.io/graphql` | | Matic (Polygon) | `https://us.streaming.bitquery.io/graphql` | ## Next Steps - Learn about [API authentication](/docs/authorization/how-to-generate/) - Explore the [GraphQL IDE](https://ide.bitquery.io/) - Check [API examples](/docs/blockchain/introduction/) --- ## Bitquery API Product Comparison URL: https://docs.bitquery.io/docs/api-comparison/ Bitquery GraphQL queries, WebSocket subscriptions and Kafka streams compared: when to use each, plus how to pick realtime vs archive datasets in API v1. # API Comparison :::tip Looking specifically for trading / DEX data? This page compares **delivery methods** (GraphQL Query vs Subscription vs Kafka). For the **trading-data product choice** (chain-level `DEXTrades` / `DEXTradeByTokens` vs the curated `Trading` cube), see the dedicated [**Trading Data Overview**](/docs/trading/trading-data-overview). ::: To choose the right Bitquery API offering, it helps to understand their differences. The table below summarizes key features and capabilities of GraphQL Query vs GraphQL Subscription vs Kafka Streams: | Feature / Method | GraphQL Query | GraphQL Subscription (WebSocket) | Kafka Streams (Protobuf) | | --------------------------------- | -------------------------------------------- | ---------------------------------------------- | --------------------------------------------------------- | | **Use case** | On‑demand historical + real‑time via polling | Real-time pushes for new on-chain events | High‑throughput, event-driven pipelines | | **Data model** | Flexible GraphQL with filtering, aggregation | Same GraphQL query syntax, live updates | Topic-based structured streams with JSON or Protobuf | | **Latency** | ~1 sec | ~1 sec latency | Sub‑second; streamed within 500 ms, supports HFT | | **Delivery model** | Pull via REST/GraphQL | Push over WebSocket (GraphQL subscription) | Consumer‑driven pull from Kafka broker | | **Schema granularity** | Customizable projections | Customizable projection | Kafka topics per type (e.g., dextrades, transactions) | | **Ordering & duplication** | Strong consistency in query response | No guaranteed order; WebSocket delivery | Consumer logic needed | | **Authentication** | OAuth/API‑Key | OAuth token over WebSocket | SASL username, password | | **Ideal Implementation Language** | Any language | Any language except curl | Go, Java, Python, Rust | | **Best for** | Interactive apps, ad-hoc querying | Monitoring, alerts, dashboards, mempool events | Streaming pipelines, HFT, data lakes, analytics workloads | ## When to Use Each API ### GraphQL Queries **Best for on-demand, ad-hoc, and historical data needs:** - When you need to fetch past blockchain activity (trades, transfers, balances) - For dashboards, reports, and analytics that rely on filtering, sorting, and pagination - When requests are driven by user actions or scheduled jobs - Ideal for combining historical + near-real-time data via polling ### GraphQL Subscriptions (WebSocket) **Ideal for lightweight real-time updates and UI integration:** - When you want push-based delivery of live on-chain events (e.g., swaps, transfers, new blocks) - For wallet trackers, price alerts, or monitoring dashboards - When you need low-latency updates (~500 ms) but don’t require ultra-high throughput - Perfect for embedding live feeds into web or mobile interfaces ### Kafka Streams (JSON / Protobuf) **Perfect for high-throughput, fault-tolerant streaming pipelines:** - When you need sub-second end-to-end latency for trades, mempool events, or order books - For building scalable data lakes, HFT bots, or real-time analytics systems - When you require integration with Kafka-based ecosystems Pick Queries for flexibility and history, Subscriptions for easy real-time UI feeds, and Kafka Streams when you need industrial-scale, ultra-low-latency pipelines. ## How do I specify dataset: realtime vs archive in an API v1 query? This site documents **API V2** GraphQL, where you set **`dataset`** on the root field (for example **`EVM(dataset: archive)`** or **`Solana(dataset: combined)`**)—see [Dataset options](/docs/graphql/dataset/options). **API V1** uses a **different endpoint and schema**; realtime/archive semantics are **not** expressed the same way. For V1 query shapes and examples, use **[Bitquery V1 documentation](https://docs.bitquery.io/v1/)** and the [V1 examples catalog](https://docs.bitquery.io/v1/docs/category/examples). --- ## Bitquery Glossary: EVM and Solana Terms Used in the Docs URL: https://docs.bitquery.io/docs/category/glossary/ Definitions for the arguments, cubes and fields that appear in Bitquery queries, split into EVM terms and Solana terms, with the sections readers look up most. # Bitquery Glossary: EVM and Solana Terms Used in the Docs The glossary explains every argument, cube and field name a Bitquery query can contain, in two pages: one for the EVM chains and one for Solana. Each page walks the same order: the dataset, network and filter arguments on the root, then the terms of each cube (balance updates, blocks, calls or instructions, DEX trades, events, transactions, rewards, transfers), then the attributes of the `Currency` object that appears in most of them. Use it when a field name in an example is unclear, or when the IDE autocompletes something you have not seen before. ## The two pages | Page | Covers | |---|---| | [EVM builder terms](/docs/glossary/EVM) | `dataset`, `mempool` and `network` arguments, filter parameters, and the terms of the Balances, Holders, Blocks, Calls, DEXTradeByTokens, DEXTrades, Events, Transactions, MinerRewards and Transfers cubes, plus `Currency` attributes | | [Solana builder terms](/docs/glossary/solana) | `dataset` and filter arguments, and the terms of the BalanceUpdates, Blocks, DEXOrders, DEXTradeByTokens, DEXTrades, Instructions, Rewards, Transactions and Transfers cubes, plus `Currency` attributes | ## Most looked-up sections | Term | Where | |---|---| | `dataset: realtime`, `archive`, `combined` | [EVM dataset parameters](/docs/glossary/EVM#dataset-parameters), [Solana dataset parameters](/docs/glossary/solana#dataset-parameters) | | `mempool` argument | [EVM mempool parameter](/docs/glossary/EVM#mempool-parameter) | | `network` argument | [EVM network parameter](/docs/glossary/EVM#network-parameter) | | `where`, `orderBy`, `limit`, `limitBy` | [EVM filter parameters](/docs/glossary/EVM#filter-parameters), [Solana filter parameters](/docs/glossary/solana#filter-parameters) | | DEX trade fields: `Buy`, `Sell`, `Dex`, `Side`, `PriceInUSD` | [EVM DEXTrades terms](/docs/glossary/EVM#dextrades-api-terms), [Solana DEXTrades terms](/docs/glossary/solana#dextrades-api) | | Per-token trade aggregates | [EVM DEXTradeByTokens terms](/docs/glossary/EVM#dextradebytokens-api-terms), [Solana DEXTradeByTokens terms](/docs/glossary/solana#dextradebytokens-api) | | Decoded calls and instructions | [EVM Calls terms](/docs/glossary/EVM#calls-api-terms), [Solana Instructions terms](/docs/glossary/solana#instructions-api) | | `Currency` attributes: `Native`, `Fungible`, `SmartContract`, `MintAddress`, `Decimals` | [EVM currency attributes](/docs/glossary/EVM#currency-field-attributes-explained), [Solana currency terms](/docs/glossary/solana#currency-field-terms-explained) | ## Two terms in one query `dataset: combined` on the root reaches history and the realtime tail together; `Currency.Native` marks the chain's own coin (ETH here) as opposed to a token. Run it in the [Bitquery IDE](https://ide.bitquery.io); because it reads history, it needs an archive add-on (the free trial is real-time only). ```graphql { EVM(network: eth, dataset: combined) { Transfers( limit: { count: 3 } orderBy: { descending: Block_Time } where: { Transfer: { Currency: { Native: true } } } ) { Block { Time } Transfer { Amount Currency { Symbol Native } } } } } ``` ## Related pages - [Understanding cubes](/docs/category/understanding-cubes) - [GraphQL query capabilities](/docs/category/capabilities) - [Crypto Price API](/docs/trading/crypto-price-api/) --- ## Bitquery GraphQL Query Limits URL: https://docs.bitquery.io/docs/graphql/limits/ Bitquery GraphQL Query Limits in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Limits Results are limited by using attributes ```limit``` and ```limitBy``` ## limit ```limit``` just does what is says: limits the results to pre-defined size. :::note If you do not specify `limit`, a system default is applied. **GraphQL v2** uses a default of **25,000** rows per query result. You can override this by setting `limit` explicitly in your query filters. This is another argument to use aggregation when you need larger result sets. ::: ```limit``` attribute has a structure: * ```count``` is the maximum count of results returned * ```offset``` is the offset (0-based) of the results (default is 0) :::danger do not use ```offset``` for pagination of the result, unless you sure that the results are not modified or added between the queries and also have strong ordering ::: ## limitBy ```limitBy``` limits the result size for every value of the supplied attribute The following query returns just top 2 blocks by transaction count, **per every day** ```graphql { EVM (dataset: archive){ Transactions( where: {Block: {Date: {after: "2022-11-11"}}} orderBy: { descendingByField: "txCount" } limitBy: {count: 2 by: Block_Date} ) { Block { Date Number } txCount: count } } } ``` ```limitBy: {count: 2 by: Block_Date}``` here says: _"take just 2 records for every ```Block_Date``` the result has"_. :::tip ```limitBy``` is a good tool to do data sampling ::: --- ## Bitquery GraphQL in Postman URL: https://docs.bitquery.io/docs/graphql/postman/ Bitquery GraphQL in Postman in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Accessing Queries on Postman You can run Bitquery queries in Postman. The public workspace has one collection per chain: [Bitquery Postman Workspace](https://www.postman.com/interstellar-eclipse-270749/bitquery) ![Using the Bitquery GraphQL API in Postman](/img/postman.png) Every request in the workspace was executed against the live API before publishing. ## Setup 1. [Generate an access token](/docs/authorization/how-to-generate/). 2. Open the collection for the chain you want and set the `ACCESS_TOKEN` variable to your `ory_at_...` token. That is the only change you need to make — each collection ships with the right `BASE_URL` already set, and every request sends `Authorization: Bearer {{ACCESS_TOKEN}}`. ## Which endpoint a chain uses | Endpoint | Chains | | --- | --- | | `https://streaming.bitquery.io/graphql` | Solana, Ethereum, BSC, Base, Arbitrum, Polygon, Optimism, Tron, Robinhood Chain, Arc mainnet, Arc testnet, plus the Trading APIs, Perpetuals, Stablecoins, Prediction Markets and Cross-chain collections | | `https://graphql.bitquery.io` | Bitcoin, Litecoin, Bitcoin Cash, 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 30% or more) - 💳 Pay by card, cancel anytime - 🔢 Optionally **top up credits** (API points, stream-minutes, stream data) at checkout ![Select plan](/img/selfservice/select-plan.png) Plans on self-serve: **Personal** (100K API points/mo, 3 concurrent requests), **Pro** (1M points/mo, 100 streams), **Scale** ⭐ (5M points/mo, 1,000 streams), and **Enterprise** (custom limits, dedicated SLA & support — [contact sales](https://bitquery.io/forms/api)). See [full plans](https://bitquery.io/pricing), the [Upgrade to Paid Plan](/docs/ide/paid/) guide, or [Manage Your Subscription](/docs/plans/manage-subscription/) for video walkthroughs of paying, upgrading, downgrading and cancelling. Billing questions: [support@bitquery.io](mailto:support@bitquery.io). ## What you see on the Dashboard - **Plan** — Current tier, points allowance, and stream limits (with upgrade or sales contact where applicable). - **Usage** — Recent API usage (for example v1 / v2 queries and streams); links to more detailed reports where available. - **Account** — Profile, company, role, 2FA; links to password and security settings — [Account settings](https://account.bitquery.io/user/account). - **Access tokens** — Active tokens and applications; [generate or manage tokens](https://account.bitquery.io/user/api_v2/access_tokens) and [applications](https://account.bitquery.io/user/api_v2/applications). - **Bitquery Apps** — Quick entry to the IDE and other Bitquery products. - **Docs & Support** — Documentation, forum, blog, and contact options. - **System status** — Shortcuts to overall and per-service status (full detail also under **System Status** in the top menu). Deeper pages (detailed API statistics, referrers, error logs, messages, and similar) are reached from the **API V1**, **API V2**, or **Authorization** menus instead of a long static sidebar. --- ## Bitquery IDE Paid Plans URL: https://docs.bitquery.io/docs/ide/paid/ Bitquery IDE Paid Plans in Bitquery docs with practical setup steps, examples, and guidance for secure API access. Keep queries fast with indexed filters. # Upgrade to Bitquery Paid Plan You are now in full control of your plan. You can upgrade yourself from your account — no sales call required — or contact sales for custom/Enterprise volumes. 👉 [Upgrade now](https://account.bitquery.io/user/upgrade) · [See full plans](https://bitquery.io/pricing) ## Self-service upgrade Go to [Account → Billing → Select Plan](https://account.bitquery.io/user/upgrade). The checkout is a 4-step flow: **Choose plan → Plan configuration → Review & pay → Done**. ![Select plan](/img/selfservice/select-plan.png) On the **Choose plan** step you can: - ⚡ Pick a plan and upgrade instantly - 🔢 Switch between **Monthly** and **Annual** billing (annual saves 30% or more) - 💳 Pay by card, cancel anytime ### Plans available on self-serve | Plan | Monthly | Annual (per mo) | API points / mo | Requests / min | Concurrent requests | Simultaneous streams | Streaming time | Traffic | Team size | | -------------------------- | ------- | --------------- | --------------- | -------------- | ------------------- | -------------------- | -------------- | --------- | --------- | | **Personal** | $49 | $29 | 100,000 | 30 | 3 | — | — | — | 1 | | **Pro** | $99 | $69 | 1,000,000 | 90 | 6 | 100 | 100,000 min | 5 GB | 2 | | **Scale** ⭐ (recommended) | $299 | $199 | 5,000,000 | 240 | 12 | 1,000 | 2,000,000 min | 50 GB | 5 | | **Enterprise** | Custom | Custom | Custom | Custom | Custom | Unlimited | Custom | Unlimited | Custom | Streaming is **off on Personal** — it starts at Pro. Annual billing saves 30% or more and locks the price for 12 months. Self-serve plans query the `realtime` dataset by default. To query history — the `archive` and `combined` datasets — add the **historical data add-on** to your plan; see the [pricing page](https://bitquery.io/pricing) for the chains it covers. Without it, a query using `dataset: archive` or `dataset: combined` will be rejected. **Enterprise** includes all datasets (Archive, Realtime, Combined), volume pricing, and dedicated support & SLA — [contact sales](https://bitquery.io/forms/api) for a quote. For which cube has how much history on each chain, see [Data Coverage & Retention](/docs/graphql/data-coverage-retention/). Current pricing is always on the [pricing page](https://bitquery.io/pricing). ## Top up credits (add-ons) Step 2 of the checkout is **Plan configuration** — optional. Add-ons are billed together with your plan each period; skip the step if you don't need any. ![Top up credits](/img/selfservice/top-up-credits.png) | Add-on | What you get | Monthly | Annual (per mo) | | ------------------- | -------------------------- | ------- | --------------- | | **API points** | +1,000,000 API points | $50 | $35 | | **Stream-minutes** | +200,000 streaming minutes | $50 | $35 | | **Stream data** | +5 GB of stream traffic | $50 | $35 | | **MCP credits** | Credits for MCP / AI agent requests | from $13/mo | — | Top-ups are **recurring** — they refill each billing period. A one-time, non-recurring top-up of 1M points is also available at $100. Volume packs lower the unit rate as you scale: the largest pack cuts it by 70% for stream-minutes and 80% for stream data. ### Historical data add-ons Self-serve plans query the `realtime` dataset. To run `dataset: archive` or `dataset: combined`, add the historical add-on for the chain you need: | Chain | Add-ons | Indicative price (billed yearly) | | --- | --- | --- | | Ethereum, BNB Chain (BSC), Base, Arbitrum, Optimism, Polygon, Tron, Robinhood, Arc | **Historical Trading Data** · **Historical Transfers + Balances + Holders** | from $70/mo per chain, per pack | | Solana | **Historical OHLCV & Token Price** · **Historical Token Transfers & Balances** | $210/mo · $350/mo | | Bitcoin, Bitcoin Cash, Litecoin, Dogecoin, Dash, Zcash | **Chain Data (historical included)** | $175/mo per chain | | Cardano, Ripple, Stellar, Filecoin | **Chain Data (historical included)** | $175/mo per chain | | Avalanche, Algorand, Celo, Cronos, Klaytn | **Chain Data (historical included)** | $105/mo per chain | | Polymarket | **Historical Data** (from 1 September 2025) | $105/mo | | All chains | **Address Label Data (multi-chain)** | $69/mo | Bundles cover the eight EVM chains in one purchase, and all six UTXO chains in another — cheaper than buying the chains individually. Tron and Solana are sold per chain. Use the ⓘ on any add-on in checkout to see exactly which datasets, cubes and time scope it unlocks. Prices above are indicative and vary by monthly vs yearly billing — checkout and the [pricing page](https://bitquery.io/pricing) are the source of truth. Cardano, Ripple, Stellar, Algorand, Filecoin, Avalanche, Celo, Cronos and Klaytn are sold the same way as the UTXO chains: one pack per chain, history included. There is no bundle for these nine. You can add multiple units of each add-on using the quantity selector. Prices per unit are shown in the checkout and on the [pricing page](https://bitquery.io/pricing). ## Additional Points If you are on a paid plan and your points run out, you can either **top up API points** (add-on above) or **upgrade to a higher plan** — both from [Account → Billing](https://account.bitquery.io/user/billing). ## Contacting sales For **Enterprise**, custom limits, or an invoice-based purchase, [contact sales](https://bitquery.io/forms/api) using the official form, email [sales@bitquery.io](mailto:sales@bitquery.io), or reach the Bitquery team on Telegram at [https://t.me/bloxy_info](https://t.me/bloxy_info) (please be cautious about potential scammers — only trust official channels and double-check the admins). ## How to change the plan? You can change your plan any time from [Account → Billing](https://account.bitquery.io/user/billing) — **Change Plan** to move tier, or **Manage Add-Ons** to add capacity or data access without changing tier. - **Upgrades** apply immediately and are charged **pro rata** — only for the days left in your current period. The full amount bills from your next renewal. - **Downgrades** take effect at your **next renewal**, so you keep what you have already paid for until the period ends. Nothing is charged at the time of the downgrade. - **Cancelling** stops the renewal. Your current period and any remaining points stay available until the period end date; no refund is issued for the current period. For a walkthrough of all three, see [Manage Your Subscription](/docs/plans/manage-subscription/). ## What will happen if I upgrade the plan in the middle of the month? Your billing cycle starts on the date you pay — it is not tied to the calendar month. Whatever date you upgrade on, your points run month-on-month from that date. For example, if you pay on the **19th**, your points are available until the **19th of the next month**, when the plan renews and your allowance resets. ## Will response times improve if I upgrade to a paid plan? {#will-response-times-improve-if-i-upgrade-to-a-paid-plan} Paid plans have higher rate limits — more requests per minute and more concurrent requests (see the [plan table](#plans-available-on-self-serve) above). Per-query response time is driven by the query itself, so also [optimize your queries](/docs/graphql/optimizing-graphql-queries). If that doesn't help, ask the team on [Telegram](https://t.me/bloxy_info). ## When do API credits (points) reset — monthly or rolling? {#when-do-api-credits-points-reset-monthly-or-rolling} Points refresh on your **billing cycle**, which is anchored to the date you paid — not to the 1st of the calendar month. If you pay on the 19th, your points renew on the 19th of each following month. Your exact renewal date and usage appear in your [account billing](https://account.bitquery.io/user/billing). If your contract differs, use the dates on your invoice or ask [sales@bitquery.io](mailto:sales@bitquery.io). ## Can I buy points without contacting sales? {#can-i-only-buy-points-by-contacting-sales} Yes. Points and other credits are available **self-serve**: go to [Account → Billing → Select Plan](https://account.bitquery.io/user/upgrade), pick your plan, and add **Top Up Credits** (API points, stream-minutes, or stream data) at step 2 of checkout. Sales contact is only needed for **Enterprise**, custom volumes, or invoice-based billing. See also [Points](/docs/ide/points/). ## Need help? Questions about billing? Reach us at [support@bitquery.io](mailto:support@bitquery.io) or [support.bitquery.io](https://support.bitquery.io). > **WARNING** > Please do not send money or pay outside the official checkout unless you receive an invoice from [bitquery.io](https://bitquery.io). Beware of scammers. --- ## Bitquery IDE Points and Usage URL: https://docs.bitquery.io/docs/ide/points/ Bitquery IDE Points and Usage in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Points Bitquery indexes more than 1 Petabyte of structured blockchain data and exposes it through a single GraphQL interface. Using one endpoint, you can get a chain’s latest block height, follow money trails, pull DEX trades across supported blockchains, and more. Not every query uses the same resources: some need a small set of records, others scan billions; some are served from cache, others may use large amounts of memory. Charging only by number of API calls would be unfair, because each call has a different cost. **Points** solve this by tying cost to actual resource usage: **Points = Resources consumed × Price per unit** So you pay in proportion to what your queries consume. The exact algorithm and resource prices may change over time, but pricing is based on Points (not raw API call count). At Bitquery we use the points system to calculate the cost for each query. Each query consumes a different number of points based on its complexity and the amount of data requested. **For a comprehensive understanding of the points system, please see this [video](https://youtu.be/L5QOTnvUwkg).** 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 30% or more), pay by card, cancel anytime. - **Top up credits** — at step 2 of checkout, add **1 Million API points**, **200k Stream-minutes**, or **5 GB Stream Data** add-ons. Add-ons are billed together with your plan each period. ![Top up credits](/img/selfservice/top-up-credits.png) For Enterprise or custom volumes, [contact sales](mailto:sales@bitquery.io). Check pricing [here](https://bitquery.io/pricing). See the full billing walkthrough on the [Upgrade to Paid Plan](/docs/ide/paid/) page. > **WARNING** > Please do not send money or pay unless you receive an invoice from [bitquery.io](https://bitquery.io). Beware of scammers. ## How are points calculated? The number of points can vary for various reasons. Even the same query can produce different results. These points are dynamically calculated based on the following factors: - The quantity of records being queried, either through the count of records in limit or the date range. - The level of complexity of the query. For instance, if you include additional addresses, the points will be calculated considering the resources occupied by those addresses. To optimize this query, there are a few approaches you can consider. Firstly, narrowing down the date range can help to refine the results. Secondly, reducing the list of addresses may also be beneficial. However, the effectiveness of these strategies will depend on your specific goal. ## Why does a Net::ReadTimeout error consume my API credits? {#why-does-net-readtimeout-consume-api-credits} Bitquery **points** reflect **work the backend performs** (see [how points are calculated](#how-are-points-calculated)), not whether your HTTP client waited long enough. If the server **executes** your GraphQL operation before the client hits **Net::ReadTimeout**, that run can still **deduct points**. Reduce cost by **narrowing filters**, lowering **`limit`**, and fixing slow patterns—see [Common errors — timeout](/docs/start/errors/#timeout-tcp-socket). For billing edge cases, check usage in your [account](https://account.bitquery.io/) or ask [support](https://support.bitquery.io/). ## How are points calculated for the realtime dataset? 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/trading/crypto-price-api/)** - Learn **[Real-time Subscriptions](/docs/subscriptions/subscription)** - Explore **[DEX Trading APIs](/docs/blockchain/Solana/solana-dextrades)** ### For Developers - Begin with **[Your First Query](/docs/start/first-query)** - Master **[GraphQL Basics](/docs/graphql/query/)** - Build **[Custom Applications](/docs/category/how-to-guides/)** ### For Analysts - Start with **[Historical Data](/docs/graphql/dataset/archive)** - Learn **[Aggregation Queries](/docs/graphql/capabilities/aggregated_metrics/)** - Explore **[Analytics Examples](/docs/category/how-to-guides/)** ## Getting Help - **Documentation**: Search the docs first - **IDE Examples**: Try the pre-built queries in the IDE - **Community**: Ask questions on [Telegram](https://t.me/Bloxy_info) - **Support**: Contact [support](https://support.bitquery.io/) for technical issues --- ## Bitquery MCP Server for AI Agents URL: https://docs.bitquery.io/docs/mcp/mcp-server/ Connect Claude, Cursor, or ChatGPT to Bitquery MCP to query DEX trades, OHLC prices, wallet analytics, fund tracing, 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](https://mcp.bitquery.io), then sign in with your Bitquery account when the first tool runs. - **Cursor:** Settings, MCP, Add new MCP server, URL [https://mcp.bitquery.io](https://mcp.bitquery.io); or put the `mcp-remote` command in `.cursor/mcp.json`. - **Codex app:** add the server with an `Authorization: Bearer` header, then ask it to load the Bitquery tools in each new chat. See [Codex app](#codex-app). No API key is pasted anywhere; OAuth 2.1 handles sign-in and a 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](https://mcp.bitquery.io) 3. Click **Add**. ![Add custom connector: Name and Remote MCP server URL fields](/img/mcp/custom_connector.png) You don't need to pick tools by hand in the chat UI. Ask in plain language, for example _"get me the top Solana tokens by 24h volume"_, and Claude calls Bitquery when the request fits. ### ChatGPT 1. Settings → **Connectors** (requires Plus, Pro, or Business). 2. **Add connector → Custom connector**. 3. URL: [https://mcp.bitquery.io](https://mcp.bitquery.io). 4. Authenticate with your Bitquery account when prompted. ### Cursor Easiest path: 1. Settings → **MCP → Add new MCP server**. 2. URL: [https://mcp.bitquery.io](https://mcp.bitquery.io). Or add it to `.cursor/mcp.json` directly: ```json { "mcpServers": { "bitquery": { "command": "npx", "args": ["-y", "mcp-remote", "https://mcp.bitquery.io/mcp"] } } } ``` Restart Cursor, or reload the MCP configuration, so the server gets picked up. ### Codex app These steps are for the Codex desktop app, not the Codex CLI. You need a Bitquery API access token to use as the bearer token. Generate one on the [Access Tokens page](https://account.bitquery.io/user/api_v2/access_tokens) of your Bitquery account. Step-by-step instructions are in [Authorization](/docs/authorization/how-to-generate/). 1. Open **Plugins → MCPs → Add server**. 2. Fill in: - **URL:** [https://mcp.bitquery.io](https://mcp.bitquery.io) - **Bearer token env var:** leave empty 3. Under **Headers**, click **Add header**: - **Key:** `Authorization` - **Value:** `Bearer YOUR_BITQUERY_TOKEN` 4. Click **Save**. ![Codex MCP server settings with the Bitquery URL and an Authorization bearer header](/img/mcp/codex-mcp-bearer-header.png) Put the token in **Headers**, not in **Bearer token env var**. That field expects the name of an environment variable, not the token itself. 5. Start a **New chat** and ask Codex to load the tools before your first question: ``` Load all tools in bitquery mcp ``` ![Codex chat confirming all 173 Bitquery MCP tools are loaded](/img/mcp/codex-load-bitquery-tools.png) Codex keeps MCP tools hidden until they are searched for, so skipping this step can make it reply that no Bitquery tools are available. Send the load prompt once at the start of each new chat, then ask questions normally, for example _"get Solana trending tokens"_. ### Claude Code (terminal) ```bash claude mcp add bitquery -- npx -y mcp-remote https://mcp.bitquery.io/mcp ``` ### VS Code and other MCP clients Add a new MCP server with the URL [https://mcp.bitquery.io](https://mcp.bitquery.io). The client handles OAuth on its own. --- ## First Connection and Permissions Once it's configured, **Bitquery Trading Data** shows up in your client's connector list: ![Bitquery MCP listed among custom connectors](/img/mcp/mcp-connectors-bitquery-listed.png) The first time a tool runs, the client asks you to **connect** and approve: ![Tool run requesting Connect for Bitquery](/img/mcp/mcp-tool-connect-prompt.png) You're prompted to **sign in** to Bitquery. A 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`, `arc`, `arc_testnet` - `Solana` root — Solana - `Tron` root — Tron - `Hyperliquid` root — Hyperliquid perpetuals - `Trading` root — cross-chain prices and trades, no `network` argument Arc mainnet uses `EVM(network: arc)`; Arc testnet uses `EVM(network: arc_testnet)`. Leave the dataset argument out on both unless a fresh probe confirms `archive` or `combined`. The mainnet also appears in the `Trading` cubes as network name `Arc` and network id `bid:arc`. **Everything else is V1 only**: Bitcoin, Litecoin, Bitcoin Cash, Dogecoin, Dash, Zcash, Cardano, Ripple, Stellar, Algorand, 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. **On EVM and Tron, use `Balances` for current balances and `Holders` for holder rankings.** Both are query-only; for live balance changes use `TransactionBalances` or `Transfers`. On Solana, use `Solana.BalanceUpdates`. **Always filter `Interval.Time.Duration` on `Tokens` / `Pairs` / `Currencies`.** The cube stores ten bar durations simultaneously (1, 3, 5, 10, 30, 60, 300, 900, 1800, 3600 seconds). Omitting the filter returns one row per duration and inflates any aggregate roughly **ten-fold**. An unsupported value returns `[]` with HTTP 200 and no error, so a typo looks like "no data". **On `Trading.Trades`, use `AmountsInUsd.Quote` for USD, not `.Base`.** `.Base` is `Amounts.Base x PriceInUsd`, and `PriceInUsd` is a smoothed reference price rather than the executed one, so it diverges on fast-moving tokens. **`Trading.Trades` emits some exact duplicate 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. --- ## Blockchain Data Lake URL: https://docs.bitquery.io/docs/data-lake/ Blockchain data lake: what the lake holds, its data format including Hyperliquid, how streaming works, and a hands-on tutorial to stream and decode blocks. # Blockchain Data Lake The Bitquery **Blockchain Data Lake** gives you the complete archive of a blockchain. It holds every block from **genesis to the current tip** as 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/ Bitquery blockchain data as Parquet files for S3, Snowflake and BigQuery: which chains and tables exist, how the files are laid out, and where to buy them. # Blockchain Data in Cloud Bitquery 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** – Full history from genesis for most chains; Hyperliquid is a rolling 30-day window - **Multi-Chain Support** – Access data from major blockchain networks - **Cost-Effective** – Pay only for the data you need, when you need it - **Scalable** – Built for large historical backfills ## Available 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. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Ethereum Transfers](https://bitquery.io/datastore/datasets/ethereum-transfers) · [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) · [Base Transfers](https://bitquery.io/datastore/datasets/base-transfers) · [Polygon Transfers](https://bitquery.io/datastore/datasets/polygon-transfers) · [Arbitrum Transfers](https://bitquery.io/datastore/datasets/arbitrum-transfers) ### [Solana Blockchain Data Export](/docs/cloud/solana/) Export **Solana blockchain data** including slot-level blocks, transactions, transfers, and DEX activity: - **Blocks** – Slot-level block metadata - **Transactions** – Full transaction-level data with signatures - **Transfers** – Native SOL and SPL token transfers - **Balance Updates** – Account balance changes per slot - **DEX Pools** – Decentralized exchange pool metadata - **DEX Orders** – Order-level DEX activity and fills - **DEX Trades** – Executed trades on Solana DEXs - **Rewards** – Validator and staking rewards **Use Cases:** Solana DeFi analytics, NFT marketplace analysis, token transfer tracking, DEX volume analysis, validator performance monitoring. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [All Solana datasets](https://bitquery.io/datastore/datasets?network=solana), including [Pump.fun](https://bitquery.io/datastore/datasets/pumpfun), [PumpSwap](https://bitquery.io/datastore/datasets/pumpswap), [Raydium AMM v4](https://bitquery.io/datastore/datasets/raydium-amm-v4), [Jupiter](https://bitquery.io/datastore/datasets/jupiter), [Meteora DLMM](https://bitquery.io/datastore/datasets/meteora-dlmm) and [Orca Whirlpool](https://bitquery.io/datastore/datasets/orca-whirlpool) ### [Tron Blockchain Data Export](/docs/cloud/tron/) Export **Tron blockchain data** for comprehensive network analysis: - **Blocks** – Block-level metadata - **Transactions** – Full transaction-level data - **Transfers** – Native TRX and TRC-20 token transfers - **Balance Updates** – Account balance changes per block - **DEX Trades** – Executed trades on Tron DEXs **Use Cases:** Tron DeFi analytics, TRC-20 token tracking, DEX volume analysis, account balance monitoring, transaction flow analysis. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [TRON Transfers](https://bitquery.io/datastore/datasets/tron-transfers) ### [Bitcoin Blockchain Data Export](/docs/cloud/bitcoin/) Export **Bitcoin blockchain data** including transaction inputs, outputs, and OMNI Layer protocol data: - **Blocks** – Block-level metadata - **Transactions** – Full transaction-level data - **Inputs** – Transaction input data and UTXO references - **Outputs** – Transaction output data and addresses - **OMNI Transactions** – OMNI Layer protocol transactions - **OMNI Transfers** – OMNI Layer token transfers **Use Cases:** Bitcoin transaction analysis, UTXO tracking, address clustering, OMNI token analysis, blockchain forensics, historical price analysis. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Bitcoin](https://bitquery.io/datastore/datasets/bitcoin) ### [Ripple (XRP Ledger) Data Export](/docs/cloud/ripple/) Export **Ripple / XRP Ledger data**, modelled around XRPL's ledger objects: - **Transactions** – Transaction envelope with fee, sequence, result code, memos, and signers - **Transfers** – Unified value movement: XRP and issued-token payments, DEX and AMM trade sides, NFT trades and mints, and fee burns - **Payments** – `Payment` transactions with requested, delivered, send-max, and deliver-min amounts - **Balances** – Account balance before and after each change, native and issued - **Account Roots** – Account state: XRP balance, owner count, sequence, domain, transfer rate - **Ripple States** – Trust line balances between two accounts for an issued currency - **Offers** – DEX order book offers, before and after each change - **NFToken Offers** – NFT buy and sell offers with the asking price - **Escrows** – Escrow creation, finish, and cancel with conditions and time locks - **Checks** – Deferred payment authorizations **Use Cases:** XRP payment flow analysis, issued-token and stablecoin tracking, XRPL DEX and AMM volume analysis, order book reconstruction, trust line and issuer exposure analysis, NFT marketplace activity, network fee revenue analysis. ### [Hyperliquid (HyperCore) Data Export](/docs/cloud/hyperliquid/) Export **Hyperliquid Core (HyperCore)** order-book exchange data — an event stream rather than a state chain: - **Trades** – Both sides of every match, with realized PnL, fees, taker flag and TWAP link - **Perp Liquidations** – Both sides of every liquidation, with the liquidated account, mark price and method - **TWAPs** – TWAP order state, executed size and notional, terminal status - **Order Updates** – Full order lifecycle: open, canceled, filled, triggered, and every rejection reason - **Book Updates** – **L4** per-order book changes with the owning address and order id - **Price Updates** – Mark, oracle and external perp prices per coin, and the inputs behind them - **Perp Fundings** – Every account's funding payment at each hourly settlement **Use Cases:** Perp market microstructure research, order book reconstruction at L4, maker and taker behaviour analysis, per-wallet realized PnL and funding, liquidation forensics, HIP-3 builder market analysis, backtesting against full order flow. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Hyperliquid](https://bitquery.io/datastore/datasets/hyperliquid) · [Hyperliquid Trades](https://bitquery.io/datastore/datasets/hyperliquid-trades) · [Hyperliquid Order Book](https://bitquery.io/datastore/datasets/hyperliquid-order-book) · [Hyperliquid Funding](https://bitquery.io/datastore/datasets/hyperliquid-ledger) ### [Robinhood Chain Data Export](/docs/cloud/robinhood/) Export **Robinhood Chain** data — an EVM network (chain ID `4663`) where tokenized equities trade alongside crypto-native assets: - **DEX Trades** – Buy and sell side with token metadata, USD amounts, pool and protocol - **Transfers** – Native and ERC-20 movements with USD value and currency metadata - **Balances** – Balance snapshot per address and currency, with change times and update count - **Events** – Decoded logs with arguments, topics, and the emitting call context - **Calls** – Internal and top-level calls with decoded arguments, returns, and state changes **Use Cases:** Tokenized equity and RWA flow analysis, USDG stablecoin tracking, Robinhood DEX volume analysis across Uniswap and Pons, wallet balance reconstruction, contract call tracing, cross-venue arbitrage research. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [Pons](https://bitquery.io/datastore/datasets/pons) ### [BSC (BNB Chain) Data Export](/docs/cloud/bsc/) Export **BSC (BNB Chain) blockchain data** for comprehensive EVM-compatible chain analysis: - **Blocks** – Block-level metadata and timestamps - **Transactions** – Full transaction-level data with gas information - **Transfers** – Native BNB and BEP-20 token transfers - **Balance Updates** – Account balance changes per block - **DEX Trades** – Executed trades on BSC DEXs (PancakeSwap, etc.) - **DEX Pools** – Liquidity pool metadata and state - **Smart Contract Calls** – Function calls and contract interactions - **Events** – BSC event logs and emissions - **Miner Rewards** – Block rewards and transaction fees **Use Cases:** BSC DeFi analytics, PancakeSwap analysis, BEP-20 token tracking, DEX volume analysis, smart contract monitoring, yield farming analytics, NFT marketplace data. **Buy on the [Data Store](https://bitquery.io/datastore/datasets):** [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) ## Data Format and Structure Blockchain data is provided by default in **Apache Parquet format**, a columnar storage file format optimized for analytics workloads. We can also provide data in other file formats (CSV, JSON, Avro, etc.) based on your requirements. Parquet offers: - **High Compression** – Columnar encoding and compression keep files small - **Columnar Storage** – Enables efficient column pruning and predicate pushdown - **Schema Evolution** – Supports schema changes over time - **Universal Compatibility** – Works with all major analytics engines ### File Organization Data is organized by blockchain and topic, with files named using block/slot ranges: ``` bitquery-blockchain-dataset/ ├── ethereum/ │ ├── blocks/ │ ├── transactions/ │ ├── transfers/ │ ├── balance_updates/ │ ├── dex_trades/ │ └── ... ├── solana/ │ ├── blocks/ │ ├── transactions/ │ ├── transfers/ │ ├── dex_trades/ │ └── ... ├── bitcoin/ │ ├── blocks/ │ ├── transactions/ │ ├── inputs/ │ ├── outputs/ │ └── ... ├── tron/ │ ├── blocks/ │ ├── transactions/ │ ├── transfers/ │ └── ... ├── ripple/ │ ├── transactions_tx/ │ ├── transfers_tx/ │ ├── payments_tx/ │ ├── balances/ │ └── ... ├── hyperliquid/ │ ├── trades/ │ ├── order_updates/ │ ├── book_updates/ │ ├── perp_fundings/ │ └── ... └── robinhood/ ├── dex_trades/ ├── transfers/ ├── balances/ ├── events/ └── ... ``` ## Sample Parquet Data To quickly explore the structure of the data and test your tooling, you can use our **public sample datasets**: - **GitHub repository** with sample Parquet 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_24053899.parquet ├── 24053900_24053949.parquet └── 24053950_24053999.parquet ``` ### Use Sample Data To: - **Validate ETL Pipelines** – Test your data processing workflows against realistic blockchain data - **Inspect Schemas** – Review column names, types, and data structures before production - **Benchmark Performance** – Measure query performance on realistic data sizes - **Develop Analytics** – Build and test analytics queries before full dataset access - **Validate Tooling** – Ensure compatibility with your analytics stack ## Cloud Platform Integration ### AWS S3 Integration Store blockchain data in **Amazon S3** and query with: - **Amazon Athena** – Serverless SQL queries on S3 data - **Amazon Redshift** – Data warehouse with S3 integration - **AWS Glue** – ETL jobs and data catalog - **Amazon EMR** – Spark-based analytics on S3 ### Google Cloud Platform Integration Store blockchain data in **Google Cloud Storage** and analyze with: - **BigQuery** – Serverless data warehouse with native Parquet support - **Dataproc** – Managed Spark and Hadoop clusters - **Dataflow** – Stream and batch data processing - **BigQuery ML** – Machine learning on blockchain data ### Snowflake Integration Load blockchain data into **Snowflake** for: - **Data Warehousing** – Centralized blockchain data storage - **SQL Analytics** – Complex queries across multiple chains - **Data Sharing** – Share blockchain datasets across teams - **Snowpark** – Python, Java, and Scala analytics ### Other Platforms Our Parquet datasets are compatible with: - **Databricks** – Unified analytics platform - **Apache Spark** – Distributed data processing - **Presto/Trino** – Distributed SQL query engine - **Apache Drill** – Schema-free SQL queries - **DuckDB** – In-process analytical database ## Building Scalable Real-Time Solutions Bitquery enables you to build **enterprise-grade, scalable, real-time, low-latency solutions** in the cloud. Our cloud-native architecture supports both batch and streaming data pipelines for blockchain analytics. ### Real-Time Streaming Architecture Build low-latency applications using: - **[Kafka Streams](/docs/streams/kafka-streaming-concepts/)** – High-throughput, low-latency blockchain data streams - **Mempool Data** – Access pending transactions before block confirmation - **Committed Data** – Real-time confirmed transaction streams - **Multi-Chain Support** – Stream data from Ethereum, Solana, Bitcoin, Tron, and more - **Protobuf Format** – Efficient binary serialization for optimal performance - **GraphQL Subscriptions** – WebSocket-based real-time data subscriptions - **Live Queries** – Subscribe to specific blockchain events and transactions - **Custom Filters** – Filter data streams by address, token, contract, or event - **Low Latency** – Live delivery for time-sensitive applications ## 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: - **Deep Historical Data** – Full history for most datasets (Hyperliquid: rolling 30 days; Polymarket from September 2025) - **Cost-Effective Storage** – Optimized compression reduces costs - **Batch Processing** – Ideal for ETL pipelines and scheduled analytics - **Data Warehousing** – Perfect for building comprehensive 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 ::: --- ## 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). Queries on the `archive` or `combined` dataset need an archive add-on; the free trial is real-time only. ## Read in this order | Step | Guide | What you get | |---|---|---| | 1 | [Query principles](/docs/graphql/query) | The root, cube, filter and selection structure | | 2 | [Query filters](/docs/graphql/filters), [date and time filters](/docs/graphql/datetime), [relative time](/docs/graphql/capabilities/relative-time) | Narrowing rows by address, token, amount and time | | 3 | [Dataset options](/docs/graphql/dataset/options), [realtime](/docs/graphql/dataset/realtime), [archive](/docs/graphql/dataset/archive), [combined](/docs/graphql/dataset/combined) | How far back a query can reach and how fresh it is | | 4 | [Metrics overview](/docs/graphql/metrics/metrics), [count](/docs/graphql/metrics/count), [sum](/docs/graphql/metrics/sum), [uniq](/docs/graphql/metrics/uniq), [quantile](/docs/graphql/metrics/quantile), [conditional metrics](/docs/graphql/metrics/if) | Aggregates, conditions and statistics | | 5 | [Sorting](/docs/graphql/sorting), [limits](/docs/graphql/limits), [indexed fields](/docs/graphql/indexed-fields-reference), [optimizing queries](/docs/graphql/optimizing-graphql-queries) | Fast, well-formed queries | | 6 | [EVM schema reference](/docs/schema/evm/dextrades) | Exact field names per cube | The [data coverage and retention](/docs/graphql/data-coverage-retention) page answers "how far back does the data go" per cube and chain, and the [capabilities](/docs/category/capabilities) section covers joins, calculations, JSON filters and subscriptions. ## A first query The five most recent transfers on Ethereum: one root, one cube, an order and a limit. ```graphql { EVM(network: eth) { Transfers(limit: { count: 5 }, orderBy: { descending: Block_Time }) { Block { Time } Transfer { Amount Currency { Symbol } Sender Receiver } } } } ``` From here, add a `where` to pick one token or one wallet, replace the field list with `count` and `sum(of: Transfer_Amount)` to aggregate, add `dataset: archive` to the root to reach history, or change `query` to `subscription` to stream new transfers. ## The four groups in this section - **Capabilities** (20 pages): filters, time windows, sorting, limits, aggregates, calculations, joins, array and JSON filters, subscriptions, Postman. [Open the capabilities hub](/docs/category/capabilities). - **Dataset** (7 pages): [options](/docs/graphql/dataset/options), [realtime](/docs/graphql/dataset/realtime), [archive](/docs/graphql/dataset/archive), [combined](/docs/graphql/dataset/combined), [database selection](/docs/graphql/dataset/database), [network selection](/docs/graphql/dataset/network), [reorg handling](/docs/graphql/dataset/select-blocks). - **Metrics** (11 pages): [overview](/docs/graphql/metrics/metrics), [alias](/docs/graphql/metrics/alias), [count](/docs/graphql/metrics/count), [distinct](/docs/graphql/metrics/distinct), [if](/docs/graphql/metrics/if), [priceAsymmetry](/docs/graphql/metrics/priceAsymmetry), [selectWhere](/docs/graphql/metrics/selectWhere), [statistics](/docs/graphql/metrics/statistics), [sum](/docs/graphql/metrics/sum), [uniq](/docs/graphql/metrics/uniq), [quantile](/docs/graphql/metrics/quantile). - **Schema reference** (11 pages): [blocks](/docs/schema/evm/blocks), [miner rewards](/docs/schema/evm/miners), [uncles](/docs/schema/evm/uncles), [balances](/docs/schema/evm/balances), [token holders](/docs/schema/evm/token-holders), [transfers](/docs/schema/evm/transfers), [transactions](/docs/schema/evm/transactions), [events](/docs/schema/evm/events), [DEX trades](/docs/schema/evm/dextrades), [calls](/docs/schema/evm/calls), [arguments and returns](/docs/schema/evm/arguments). ## Related pages - [GraphQL query capabilities](/docs/category/capabilities) - [Understanding cubes](/docs/category/understanding-cubes) - [How to generate an access token](/docs/authorization/how-to-generate/) - [Data coverage and retention](/docs/graphql/data-coverage-retention) --- ## Building a 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. --- ## 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/ How to contribute to the Bitquery V2 docs: contribution steps, query format and description rules, where to get help, and docs maintenance policy. # 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). --- ## Cross-Chain Blockchain Data API: One Query Across Chains URL: https://docs.bitquery.io/docs/category/cross-chain/ Three ways to read several blockchains in one Bitquery call: Trading cubes with one schema for ten chains, aliases over chain roots, and the Currencies cube. # Cross-Chain Blockchain Data API: One Query Across Chains Bitquery serves every chain from one GraphQL endpoint, and there are three ways to read more than one chain in a single call. The `Trading` cubes carry trades, prices, market cap and supply for Solana, Ethereum, BNB Chain, Base, Arbitrum, Optimism, Polygon, Tron, Robinhood Chain and Arc in one schema, so a filter on a token symbol returns rows from every network at once. GraphQL aliases let one query address several chain roots, such as `EVM(network: bsc)` and `EVM(network: arc)`, and return them side by side. And the `Currencies` cube aggregates one asset across networks into a single price, so `bid:bitcoin` is one row rather than a list of wrapped versions. ## Three ways to go cross-chain | Approach | Use it when | Example | |---|---|---| | Trading cubes, one schema, ten chains | You want trades, candles, market cap or supply for a token wherever it trades | The USDC query below | | Aliases over chain roots | You need chain-level cubes (transfers, balances, calls) for the same address or contract on several chains | [NFTs tracking across chains](/docs/examples/cross-chain/cross-chain-api) | | `Trading.Currencies` | You want one price per asset regardless of chain | `Currency: { Id: { is: "bid:bitcoin" } }` on the [Crypto Price API](/docs/trading/crypto-price-api/) | ## USDC trades on every chain in one call No network filter: the rows come back tagged with the network they happened on. Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account. ```graphql { Trading { Trades( where: { Pair: { Token: { Symbol: { is: "USDC" } } } Block: { Time: { since_relative: { minutes_ago: 10 } } } } limit: { count: 5 } orderBy: { descending: Block_Time } ) { Block { Time } Pair { Market { Network Protocol } Token { Symbol Network } QuoteToken { Symbol } } PriceInUsd AmountsInUsd { Base } } } } ``` Add `Pair: { Market: { NetworkBid: { in: ["bid:eth", "bid:base"] } } }` to keep only the chains you care about, or group by `Pair_Market_Network` with `count` and `sum` to compare chains in one table. ## Aliases over several chain roots A GraphQL alias names each root, so `binance: EVM(network: bsc) { ... }` and `ethereum: EVM(network: eth) { ... }` run in one request and come back as two keys. Fragments keep the selection identical across them. The [NFTs tracking across chains](/docs/examples/cross-chain/cross-chain-api) page shows the pattern for one wallet's NFTs on several chains; the same pattern applies to transfers, calls or events. Note that the cubes and field names must exist on every root you alias, so it works across the EVM chains, while Solana needs its own selection. ## Related pages - [Crypto Price API](/docs/trading/crypto-price-api/) - [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api/) - [Supported chains](/docs/blockchain/supported-chains) - [Understanding cubes](/docs/category/understanding-cubes) --- ## DEX Trades Cube URL: https://docs.bitquery.io/docs/cubes/dextrades/ Use Bitquery’s DEX Trades cube to query swap-level DEX activity with filters, aggregates, and GraphQL examples for multi-chain analytics. # DEXTrades Cube :::tip Need real-time data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this page when you need **historical data older than ~30 days** (with `dataset: combined` or `archive`), raw per-swap detail, or call / event context. ::: > **Before you start**: Not sure when to use DexTrades vs DexTradesByTokens vs Events vs Calls? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. For a 1-page comparison of these three trade cubes, see [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades). The DEXTrades cube provides comprehensive information about the dex trading data, such as buyer, seller, token prices, pairs, transactions, etc. > **Advanced Usage Note**: This documentation includes advanced patterns for processing DEXTrades data based on production implementations. These patterns help handle complex scenarios like multi-hop swaps, proxy contracts, and proper volume calculations. > Import Note: If there is a trade between 2 addresses, the details in `Buy{}` dropdown are pool details, and the information displayed in the DEXTrades cube is from the pool's perspective. ![Token A to Token B trade pair diagram](/img/tokenAB.png) Let's understand the concept of buyer and seller. Token X and token Y swap as above. If we see the trade from user A's side, then we get the following: - User A becomes the seller of token X. - User A becomes the buyer of token Y. Now, if we see the trade from a user B side, we get the following. - User B becomes the seller of token Y. - User B becomes the buyer of token X. Therefore, buyers and sellers change relatively when the trade sides change. It is important to note that a pool is always involved; whenever any trade occurs between two traders, one must be a pool. Thus, we are considering User B as a pool. ## Understanding DEXTrade Cube data Next, we understand how the Dextrades Cube displays the result: Take this query for example: ```graphql { EVM(network: eth, dataset: archive) { DEXTrades( orderBy: {descending: Block_Time} limit: {count: 50} where: {TransactionStatus: {Success: true}, Block: {Number: {eq: "23674719"}}, Transaction: {Hash: {is: "0x0891b30722d44284d0c110c761190ecd6ad0f33946835bbde164561d847f5c87"}}} ) { Trade { Buy { Buyer Amount Price Currency { SmartContract Name } } Dex { Pair { Name SmartContract } ProtocolName } Sell { Buyer Amount Currency { Name SmartContract } } } Transaction { Hash } } } } ``` Output ```json { "EVM": { "DEXTrades": [ { "Trade": { "Buy": { "Amount": "4002.603343842926485635", "Buyer": "0xad4e4954b2f22525f5c9d7e7182fff9cf251d0f7", "Currency": { "Name": "MUSKITO Token", "SmartContract": "0x7ef790d9bccc87989be0fdb88ffb955bec3d5e92" }, "Price": 6.700259580759855e-9 }, "Dex": { "Pair": { "Name": "Uniswap V2", "SmartContract": "0xad4e4954b2f22525f5c9d7e7182fff9cf251d0f7" }, "ProtocolName": "uniswap_v2" }, "Sell": { "Amount": "0.000026818481402565", "Buyer": "0x5fbf1aba26bf1493cd7677ad4ec25d96a91ab0ec", "Currency": { "Name": "Wrapped Ether", "SmartContract": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } }, "Transaction": { "Hash": "0x0891b30722d44284d0c110c761190ecd6ad0f33946835bbde164561d847f5c87" } } ] } } ``` ### Analyzing the DEXTrades Output Let's break down how DEXTrades presents data from the pool's perspective: **Key Observations:** 1. **Pool Identification**: The `Buy.Buyer` address matches the `Dex.Pair.SmartContract` address. 2. **Buy Side (Pool's Perspective)**: - **Currency**: The token that the pool received (project token) - **Amount**: Quantity of tokens the pool received - **Buyer**: Pool address (the pool is "buying" these tokens) - **Price**: Current trading price per token 3. **Sell Side (Pool's Perspective)**: - **Currency**: The payment token (WETH, stablecoins, etc.) - **Amount**: Quantity of payment tokens the pool gave out - **Buyer**: User address who received the payment tokens **What Actually Happens:** From the **pool's perspective** (which is what DEXTrades shows): - The pool **bought** project tokens (received them from user) - The pool **sold** payment tokens (gave them to user) From the **user's perspective** (the actual trader): - User **sold** project tokens to the pool - User **bought** payment tokens (WETH/stablecoins) in return ## Metrics in DEXTrades Cube Metrics allow for sum, count, average, median, maximum, minimum, and more calculations The count metric can easily retrieve a specific token's total number of trades. [Run this API](https://ide.bitquery.io/Count-of-trade-on-Uniswap-of-pepe) to find the total trades of [PEPE](https://explorer.bitquery.io/ethereum/token/0x6982508145454ce325ddbe47a25d4ec3d2311933) "0x698…" tokens in the [Uniswap v3 factory](https://explorer.bitquery.io/ethereum/token/0x6982508145454ce325ddbe47a25d4ec3d2311933) "0x1f984…" in the ethereum network. ```graphql query MyQuery { EVM(dataset: archive, network: eth) { DEXTradeByTokens( where: {TransactionStatus: {Success: true}, Trade: {Currency: {SmartContract: {is: "0x6982508145454ce325ddbe47a25d4ec3d2311933"}}, Dex: {OwnerAddress: {is: "0x1f98431c8ad98523631ae4a59f267346ea31f984"}}}, Block: {Date: {since: "2024-01-01", till: "2024-06-02"}}} ) { total_trades: count } } } ``` ## How Does Bitquery Calculate USD Price for a Token? Bitquery calculates the token price using a simple formula: **UsdPrice of token 1 = amount2 in USD / amount1** **UsdPrice of token 2 = amount1 in USD / amount2** If either of these amounts is missing, the price cannot be determined. To better understand token prices, one must first examine the trade amounts involved. It's important to note that this "price" is not the actual market price of the token, but rather a derivative based on the trade amounts. **Example: BAR/WETH Pair** **BAR Price in USD = WETH amount in USD / Amount of BAR tokens** **WETH Price in USD = BAR amount in USD / Amount of WETH tokens** In this example, the second calculation (WETH Price) may not be accurate because the **BAR amount in USD is unknown**. **Example: WETH/USDT Pair** **USDT Price in USD = WETH amount in USD / Amount of USDT tokens** **WETH Price in USD = USDT amount in USD / Amount of WETH tokens** In this case, both values make sense, as both **WETH** and **USDT** can be valued in USD directly. ## Multi-Hop Trade Detection and Processing When processing DEXTrades data in production applications, it's crucial to handle multi-hop swaps correctly. Multi-hop trades occur when a single transaction contains multiple DEX trades that are part of one logical swap operation (e.g., Token A → WETH → Token B). ### Identifying Multi-Hop Trades Multi-hop trades can be detected by: 1. **Same Transaction Hash**: All trades in a multi-hop swap share the same transaction hash 2. **Sequential Processing**: Trades appear in sequence within the same block following the Trade_Index 3. **Token Chain Logic**: The sell token of one trade matches the buy token of the next ### Processing Strategy For multi-hop trades, use this approach: - **Token Identification**: Use the first hop to identify the actual token being swapped (not the intermediate tokens) - **Volume Calculation**: Use the last hop to determine the final payment amount - **Direction Detection**: Check the signer's role in the final hop to determine if it's a buy or sell ```python # Example pattern for multi-hop detection if tx_hash in processed_transactions: # This is part of a multi-hop swap first_hop = processed_transactions[tx_hash][0] current_hop = trade_data # Last hop seen # Get actual token from first hop (exclude payment tokens) actual_token = get_non_payment_token(first_hop) # Get final volume from last hop payment side final_volume = get_payment_side_amount(current_hop) # Determine buy/sell from signer's role in last hop is_buy = signer_is_buyer_in_final_hop(current_hop, signer) ``` ### Payment Token Classification Different token types require different processing logic: - **Native Tokens**: `0x` (ETH), direct BNB trades - **Wrapped Tokens**: WETH, WBNB - used for volume calculations - **Stablecoins**: USDT, USDC, DAI - also payment tokens ([DEXrabbit Stablecoins](https://dexrabbit.bitquery.io/categories/stablecoins)) - **Other Tokens**: Project tokens, memecoins, etc. (browse themed groups on [DEXrabbit Categories](https://dexrabbit.bitquery.io/categories)) ## Advanced Buyer/Seller Logic and Proxy Contracts ### Understanding BitQuery's Buy/Sell Fields In EVM chains, DEXTrades data, as we see above, the Buy fields represent the pool's events. ### Handling Different Scenarios When processing trades, check multiple scenarios for accurate buyer/seller identification: #### Scenario 1: Direct Signer Matches ```python # Check if signer is directly in buy/sell fields if signer == buy_buyer: # Signer bought the token process_as_buy() elif signer == sell_seller: # Signer sold the token process_as_sell() ``` #### Scenario 2: Proxy Contract Logic When the signer doesn't appear in buyer/seller fields (common with proxy contracts): ```python # Find consistent party across both sides if buy_buyer == sell_seller: # This party appears to buy token and sell payment # BUT for proxy contracts, logic is inverted if signer != buy_buyer: # Signer used proxy -> opposite action process_as_sell() # Inverted logic elif buy_seller == sell_buyer: # This party appears to sell token and buy payment # BUT for proxy contracts, logic is inverted if signer != buy_seller: # Signer used proxy -> opposite action process_as_buy() # Inverted logic ``` ### Trade Type Classification Different trade types require specific handling: #### 1. Native Token Trades ```graphql # Direct BNB/ETH trades (sell_contract = "0x") where: { Trade: { Sell: { Currency: { SmartContract: { is: "0x" } } } } } ``` #### 2. Wrapped Token Trades ```graphql # WETH/WBNB trades where: { Trade: { Buy: { Currency: { SmartContract: { is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" } } } } } ``` #### 3. Token-to-Token Swaps ```graphql # Both sides are tokens (not native/wrapped) where: { Trade: { Buy: { Currency: { SmartContract: { not: "0x" } } }, Sell: { Currency: { SmartContract: { not: "0x" } } } } } ``` ## Common Edge Cases and Filtering Strategies ### Filtering MEV Bots and Unwanted Trades Production applications often need to filter out certain types of trades: ```graphql # Filter out specific MEV bot contracts query FilterMEVBots { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Transaction: { To: { notIn: ["0x802b65b5d9016621e66003aed0b16615093f328b"] } } } ) { # Your trade data } } } ``` ### Handling Zero Value Trades Filter out trades with zero amounts or prices: ```graphql query FilterZeroTrades { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Trade: { Buy: { Amount: { gt: "0" }, PriceInUSD: { gt: 0 } }, Sell: { Amount: { gt: "0" }, PriceInUSD: { gt: 0 } } } } ) { # Your trade data } } } ``` ### Identifying Pool vs Trader Addresses For token-to-token swaps, distinguish between pool addresses and actual traders: ```graphql # Focus on specific signer addresses (real traders) query RealTraders { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Transaction: { Signer: { is: "0x742d35Cc6334C0532925a3b8C836f4b98C6b1e96" } } } ) { Transaction { Signer } Trade { Buy { Buyer Seller } Sell { Buyer Seller } } } } } ``` ### Transaction Status Filtering Always filter for successful transactions: ```graphql query SuccessfulTrades { EVM(dataset: realtime, network: eth) { DEXTrades( where: { TransactionStatus: { Success: true } } ) { # Your trade data } } } ``` ## Video Tutorial | Why PriceInUSD is 0 in Bitquery API response? --- ## DEXPools Cube on EVM Chains URL: https://docs.bitquery.io/docs/cubes/evm-dexpool/ DEXPools cube on EVM chains: pool structure, price tables, when Uniswap V2, V3 and V4 pool records are emitted, filters, and liquidity depth analysis. # DEXPools Cube on EVM Chains This section explains how the dexpool data is built and shared via APIs and [Kafka streams](/docs/streams/kafka-streaming-concepts/). It also explains how to understand each entry of the response. > **Note:** In GraphQL, DEXPools data is accessed through two schema cubes: > > - **`DEXPoolEvents`**: Provides pool event data (swaps, mints, burns, etc.) > - **`DEXPoolSlippages`**: Provides slippage and price impact data for different trade sizes ## Concept Explanation Liquidity pools are fundamental components of decentralized exchanges that enable token swaps without traditional order books. Each pool contains two tokens (CurrencyA and CurrencyB), and the ratio of these tokens determines the exchange rate. When a user wants to swap tokens, they interact with a liquidity pool. The pool calculates the output amount based on: - Current liquidity reserves - The amount being swapped - Price impact and slippage tolerance For example, if you want to sell ANKR tokens for WETH in a pool: ``` Pool: 0x13dc0a39dc00f394e030b97b0b569dedbe634c0d DEX: uniswap_v3 (3) Token0: ANKR (decimals: 18) Token1: WETH (decimals: 18) Liquidity: 604099.111169 ANKR, 1.074933 WETH Direction: Sell ANKR → Buy WETH slippage: 0.1%, MaxIn: 205.504593 ANKR, MinOut: 0.000434 WETH, ratio: 473132.526201 ANKR/WETH slippage: 0.5%, MaxIn: 997.299766 ANKR, MinOut: 0.002097 WETH, ratio: 475456.664617 ANKR/WETH slippage: 1.0%, MaxIn: 2012.776732 ANKR, MinOut: 0.004205 WETH, ratio: 478581.192432 ANKR/WETH slippage: 2.0%, MaxIn: 4067.602247 ANKR, MinOut: 0.008289 WETH, ratio: 490722.489031 ANKR/WETH slippage: 5.0%, MaxIn: 10501.563247 ANKR, MinOut: 0.020650 WETH, ratio: 508535.330236 ANKR/WETH slippage: 10.0%, MaxIn: 22396.241185 ANKR, MinOut: 0.040771 WETH, ratio: 549306.392584 ANKR/WETH ``` If you are willing to accept a price impact and slippage of up to 10.0% against the current spot price, you can sell a maximum of 22396.241185 ANKR into the pool. In return, you are guaranteed to receive at least 0.040771 WETH. The average execution price for this trade would be approximately 549306.392584 ANKR per 1 WETH. The calculation considers the price impact plus the worst-case scenario of slippage for different amounts, with limited losses for each, by simulating a swap by iterating through initialized ticks in the TickBitmap. > Important note: The liquidity calculation differs by protocol version: > > - For Uniswap V2 and V3, liquidity reflects exactly the balance of the pool > - For Uniswap V4, liquidity is the token balances in PoolManager ## Understanding Pool Structure In DEXPools, each pool is represented with several key components: - **`Pool`**: The pool smart contract address and token pair information - **`Dex`**: The DEX protocol details (name, version, family) - **`Liquidity`**: Current token reserves in the pool - **`PoolPriceTable`**: Price calculations for different slippage tolerances in both directions ### Example Data Structure A sample entry for a token pair shared via Bitquery Kafka streams is available [here](https://github.com/bitquery/kafka-data-sample/blob/main/evm/eth_dexpools.json) ### Understanding Price Tables The `PoolPriceTable` provides price information for swaps in both directions: - **`AtoBPrices`**: Array of price calculations for swapping CurrencyA to CurrencyB at different slippage tolerances - **`BtoAPrices`**: Array of price calculations for swapping CurrencyB to CurrencyA at different slippage tolerances - **`AtoBPrice`**: Current spot price for CurrencyA to CurrencyB - **`BtoAPrice`**: Current spot price for CurrencyB to CurrencyA Each price entry in the arrays contains: - **`SlippageBasisPoints`**: Slippage tolerance in basis points (100 = 1%) - **`MaxAmountIn`**: Maximum input amount that can be swapped at this slippage level - **`MinAmountOut`**: Minimum output amount guaranteed at this slippage level - **`Price`**: Average execution price for swaps at this slippage level The following slippage levels are available in the data: - 10 basis points (0.1%) - 50 basis points (0.5%) - 100 basis points (1.0%) - 200 basis points (2.0%) - 500 basis points (5.0%) - 1000 basis points (10.0%) For example, in the `AtoBPrices` array above, with a 10 basis point (0.1%) slippage tolerance, you can swap up to 2,557,952,147 units of CurrencyA (USDC) and receive at least 860,478,002,991,619,427 units of CurrencyB (WETH), at an average price of 0.0003364734002389014 USDC per WETH. ## When is a new DEXPool record emitted in the APIs & Streams? A new DEXPool record is emitted in the APIs and Kafka streams when specific events occur that change the pool's liquidity or state. The events tracked vary by protocol version: ### Uniswap V2 The following events trigger a new DEXPool entry: - `Swap(address,uint256,uint256,uint256,uint256,address)` - Emitted when tokens are swapped in the pool - `Mint(address,uint256,uint256)` - Emitted when liquidity is added to the pool - `Burn(address,uint256,uint256,address)` - Emitted when liquidity is removed from the pool ### Uniswap V3 The following events trigger a new DEXPool entry: - `Mint(address,address,int24,int24,uint128,uint256,uint256)` - Emitted when liquidity is added to a position - `Burn(address,int24,int24,uint128,uint256,uint256)` - Emitted when liquidity is removed from a position - `Swap(address,address,int256,int256,uint160,uint128,int24)` - Emitted when tokens are swapped in the pool ### Uniswap V4 The following events trigger a new DEXPool entry: - `ModifyLiquidity(bytes32,address,int24,int24,int256,bytes32)` - Emitted when liquidity is modified in the pool - `Swap(bytes32,address,int128,int128,uint160,uint128,int24,uint24)` - Emitted when tokens are swapped in the pool > Note: Forks of Uniswap can also be tracked with these APIs if the signature is exactly the same. ## Filtering in DEXPools Cube Filtering helps to fetch the exact pool data you are looking for. DEXPools Cube can filter based on pool address, token addresses, DEX protocol, liquidity amounts, and more. Everything inside the "where" clause filters; it follows the `AND` condition by default. ## API Examples For blockchain-specific slippage API documentation, see: - [Arbitrum Slippage API](/docs/blockchain/Arbitrum/arbitrum-slippage-api/) - [Base Slippage API](/docs/blockchain/Base/base-slippage-api/) - [BSC Slippage API](/docs/blockchain/BSC/bsc-slippage-api/) - [Matic Slippage API](/docs/blockchain/Matic/matic-slippage-api/) For blockchain-specific liquidity API documentation, see: - [Arbitrum Liquidity API](/docs/blockchain/Arbitrum/arbitrum-liquidity-api/) - [Base Liquidity API](/docs/blockchain/Base/base-liquidity-api/) - [BSC Liquidity API](/docs/blockchain/BSC/bsc-liquidity-api/) - [Ethereum Liquidity API](/docs/blockchain/Ethereum/dextrades/ethereum-liquidity-api/) - [Matic Liquidity API](/docs/blockchain/Matic/matic-liquidity-api/) ## Advanced Use Cases and Processing Patterns ### Liquidity Depth Analysis DEXPools enables analysis of liquidity depth across different pools. By examining the `MaxAmountIn` values at various slippage levels, you can determine: - Which pools can handle large trades without significant price impact - Optimal slippage tolerance for your trade size - Price impact estimation before executing trades ### Multi-Pool Price Comparison The price table data allows comparison of execution prices across different slippage scenarios, helping traders: - Identify the best pool for their trade size - Understand price impact before executing swaps - Optimize trade execution strategies based on available liquidity ### Protocol-Specific Analysis Different DEX protocols (Uniswap V2, V3, V4) have different liquidity mechanisms. The DEXPools cube provides protocol-specific information: - **Uniswap V2/V3**: Liquidity reflects the exact balance of the pool - **Uniswap V4**: Liquidity represents token balances in PoolManager This allows for accurate analysis across different protocol versions and their unique characteristics. --- ## DEXTrades vs DEXTradeByTokens vs Trades cube URL: https://docs.bitquery.io/docs/cubes/dextrades-dextradebytokens-trading-trades/ DEXTrades, DEXTradeByTokens and the Trades cube compared: what each returns, when to use which, a quick decision guide and chain-specific examples. # DEXTrades vs DEXTradeByTokens vs Trades cube > **Looking for the product-family choice first?** This page is the **cube-by-cube row-shape** comparison. For the higher-level "should I use chain-level trades or the curated Trading cube?" decision (with the full Trading cube family — `Trading.Trades`, `Tokens`, `Currencies`, `Pairs`), start with the [**Trading Data Overview**](/docs/trading/trading-data-overview). Bitquery exposes **three** common ways to work with **DEX swap–level** data. They differ by **GraphQL root**, **row shape** (how each swap is represented), and **what fields are normalized for you**. :::tip Time window decides first, row shape second - **Real-time + last ~30 days** → **`Trading { Trades }`** (and `Tokens` / `Pairs` / `Currencies` for OHLC). USD price, market cap, and supply on every row; MEV-filtered; 10 chains in one API. - **Older than ~30 days** → chain-level **`DEXTrades`** / **`DEXTradeByTokens`** with `dataset: combined` / `archive` — the Trading cube is a **rolling ~30-day window** and does not reach further back. Pick the cube by row shape (below) only after the time window has narrowed the choice. See the [Trading Data Overview](/docs/trading/trading-data-overview). ::: This page compares them so you can pick the right primitive before you write filters, subscriptions, or aggregations. For the broader “transfers vs events vs calls vs DEX” picture, see the [mental model guide](/docs/start/mental-model-transfers-events-calls). --- ## At a glance | | **DEXTrades** | **DEXTradeByTokens** | **Trades cube** (`Trading { Trades }` — [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api)) | |---|----------------|----------------------|---------------------------------------------| | **GraphQL root** | Chain APIs such as `EVM(...)`, `Solana { ... }`, `Tron { ... }` | Same chain roots | `Trading { Trades }` | | **Time window** | Full historical archive (`dataset: combined` / `archive`) | Full historical archive (`dataset: combined` / `archive`) | **Rolling ~30 days + real-time** — no deeper history | | **Focus (by chain)** | **EVM / Tron:** **Pool-focused**—`Buy`/`Sell` follow the pool’s perspective ([DEXTrades cube](/docs/cubes/dextrades)). **Solana:** **Trader-focused**—natural fit for signer, buyer/seller, and account-style filters (see [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades), [trader patterns](/docs/blockchain/Solana/solana-trader-API)). | **EVM / Tron:** Still **pool-relative** on the **`Side`** leg (e.g. `Side.Type` vs pool); rows are **token-expanded**, not “wallet-first.” **Solana:** **Trader-focused** in practice—e.g. buyers/sellers and volume by **`Transaction.Signer`** and `Side.Type` in [Solana examples](/docs/blockchain/Solana/solana-dextrades). | **Trader-focused** everywhere: first-class **`Trader.Address`**, **`Pair`**, **`Side`**, and USD fields aligned to the [Price Index](/docs/trading/crypto-price-api/price-index-algorithm). | | **Rows per swap** | **One** row per swap | **Multiple** rows per swap (token-centric; typically **two** for a two-token pool) | **One** row per swap | | **Core shape** | `Trade.Buy` / `Trade.Sell` (shape varies by chain; see above) | `Trade` (primary token) + `Trade.Side` (counter leg) | `Side`, `Pair` (market, tokens, currencies), `Amounts` / `AmountsInUsd`, `Price` / `PriceInUsd`, `Trader`, transaction header | | **USD / long-tail tokens** | **`PriceInUSD`** and related fields are **often missing or zero** for illiquid or meme tokens—amounts exist, but USD requires a usable valuation path ([DEXTrades cube — PriceInUSD](/docs/cubes/dextrades#video-tutorial--why-priceinusd-is-0-in-bitquery-api-response)). Same class of issue on **`DEXTradeByTokens`** when the schema cannot price the leg. | Same limitation as chain DEX rows: **not guaranteed** for every token. | **Much more usable USD for trading UIs:** **`PriceInUsd`** and **`AmountsInUsd`** are driven by the **Trading price index**, so you typically **do not hit the “no USD for meme coins” problem** that shows up on raw chain DEX cubes. | | **Best when you need** | **EVM:** one record per pool swap, protocol/pool analytics, multi-hop debugging. **Solana:** trades by **wallet** / signer / account, buy vs sell counts, DEX-level analytics on chain. | **EVM:** token-level OHLC from raw trades, “all pairs for this token,” portfolio-style filters (with dedupe discipline). **Solana:** token **and** trader analytics (buyers, sellers, makers) in one model. | **Real-time and anything within the last ~30 days**: **multi-chain** swap stream, **trader-centric** apps, **reliable USD** on each row, **supply snapshot** (market cap, FDV, circulating/total/max). | | **Watch out for** | On **EVM**, `Buy`/`Sell` are **pool**-relative—not the end-user’s intuition without reading the field docs. | **Double counting** if you sum without filtering by token or deduplicating (e.g. by transaction hash / index). | Not a substitute for **pre-aggregated OHLC** on **Tokens** / **Pairs**; for aggregated charts prefer [Crypto Price API](/docs/trading/crypto-price-api/) unless you need raw swap rows | Full reference pages: [DEXTrades cube](/docs/cubes/dextrades), [DEXTradesByTokens cube](/docs/cubes/dextradesbyTokens), [Crypto Trades API — `Trades`](/docs/trading/crypto-trades-api/trades-api). --- ## DEXTrades The [DEXTrades](/docs/cubes/dextrades) cube is **normalized DEX swap data** with **`Trade.Buy`** and **`Trade.Sell`**. How you should read those fields depends on the chain: **EVM (and similar pool-centric docs):** **`Buy`** and **`Sell`** are from the **pool’s** perspective—the pool always sits in the trade; **`Buy`** is what the pool received, **`Sell`** what it paid out (diagrams and examples on the [DEXTrades cube](/docs/cubes/dextrades) page). You get **one row per swap** at the pool, which fits **protocol**, **pair/pool**, **routing**, and **multi-hop** analysis ([multi-hop section](/docs/cubes/dextrades)). **Solana:** The same `DEXTrades` field is **trader- and account-oriented** in typical queries—e.g. filtering by **`Transaction.Signer`**, **`Trade.Buy` / `Trade.Sell`** accounts and token owners, and building **buy vs sell** stats for wallets. See [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades) and [Solana trader API patterns](/docs/blockchain/Solana/solana-trader-API). **USD on chain DEX rows:** For many **long-tail or meme** tokens, **`PriceInUSD`** (and similar) may be **0 or absent** because USD is derived from trade amounts and available USD legs—not a guaranteed field for every asset. See pricing notes and the video on the [DEXTrades cube — Why PriceInUSD is 0](/docs/cubes/dextrades#video-tutorial--why-priceinusd-is-0-in-bitquery-api-response) section. **Available on chain roots** such as `EVM`, `Solana`, and `Tron` (see [mental model — applying across chains](/docs/start/mental-model-transfers-events-calls#applying-this-model-across-chains)). --- ## DEXTradeByTokens (token-expanded; EVM pool leg vs Solana trader stats) The [DEXTradesByTokens](/docs/cubes/dextradesbyTokens) / **`DEXTradeByTokens`** field describes the **same swaps** as DEXTrades, but **explodes** them into **token-centric** rows: - Each row emphasizes **`Trade`** (one token leg: **currency**, **amount**, **buyer**, **seller**) and **`Side`** (the counter leg). On **EVM**, **`Side.Type`** and buyer/seller on the side are still **pool-relative** (see [structure comparison](/docs/cubes/dextradesbyTokens#understanding-trade-and-side-structure)). - **Solana** examples often stress **trader** dimensions—e.g. **distinct signers**, **buyers** and **sellers** conditional on **`Trade.Side.Type`**, and volume in USD when available ([Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades)). - A single swap can produce **multiple rows** (e.g. both tokens get a row). That is **by design** for “everything involving token X” without reshaping **`Buy`/`Sell`** yourself on **EVM**. **Important:** There are **roughly twice as many records per swap** as with DEXTrades for a two-asset swap. **Filter by token (or pair)** and understand [how to avoid duplicate-looking totals](/docs/cubes/dextradesbyTokens#how-do-i-avoid-duplicate-results-in-dex-trade-queries) (e.g. specify side currency, dedupe by transaction, or use DEXTrades when you need **strictly one row per swap**). **Typical uses:** token price across DEXs, portfolio-style **user** tracking (buyer or seller), pairs a token trades in, and **historical OHLC derived from raw DEX trades** (bucket with `Block { Time(interval: ...) }` and min/max price fields—see [OHLC on DEXTradeByTokens](/docs/cubes/dextradesbyTokens#how-do-i-get-ohlc-in-a-dextradebytokens-query)). **OHLCV choice between the two DEX cubes:** Prefer **`DEXTradeByTokens`** for **one token’s** candle path (all pools/sides from the token’s view). Prefer **`DEXTrades`** when you need **each raw swap** as a single row (pool view, routing, debugging). For **default** OHLC/charting, the docs recommend the **[Crypto Price API](/docs/trading/crypto-price-api/)** first; see [DEXTradeByTokens vs DEXTrades for OHLCV](/docs/cubes/dextradesbyTokens#how-do-i-use-dextradebytokens-vs-dextrades-for-ohlcv) and [Crypto OHLC FAQ](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api). --- ## Trades cube (Crypto Trades API — trader-focused, strong USD) The **`Trades`** field under **`Trading`** is documented as the [Crypto Trades API — real-time DEX trade streams](/docs/trading/crypto-trades-api/trades-api). It is **not** nested under `EVM` / `Solana` per chain in the same way; you use **`Trading { Trades }`** and narrow with **`Pair.Market.Network`**, token ids, and **`Trader.Address`**. **Trader-first model:** Rows are built for **who traded**—**`Trader.Address`** is a first-class filter—alongside **`Pair`**, **`Side`**, and amounts. That is the natural API for **wallet streams**, **leaderboards**, and **per-user** trade history across **Solana**, **Ethereum**, **BSC**, **Base**, **Arbitrum**, **Optimism**, **Polygon**, **Tron**, **Robinhood**, and **Arc** in one schema ([Trades API](/docs/trading/crypto-trades-api/trades-api)). **USD vs chain DEX cubes:** On **`DEXTrades`** / **`DEXTradeByTokens`**, **`PriceInUSD`** is often **missing or zero** for **meme or thinly traded** tokens (see [DEXTrades cube](/docs/cubes/dextrades) pricing notes). The **`Trades`** cube is different: **`PriceInUsd`** and **`AmountsInUsd`** are tied to the **Trading price index**, so you **usually get usable USD** for the same long-tail assets where raw chain DEX USD fields fail. Details: [Price Index Algorithm](/docs/trading/crypto-price-api/price-index-algorithm). **What each row includes (per docs):** **`Side`**, **amounts** (base, quote, **USD**), **`Price`** / **`PriceInUsd`**, **`Pair`** (market, tokens, currencies), **`Trader`**, **transaction** header fields, and **`Supply`** (**MarketCap**, **FDV**, circulating/total/max) for token context. **Operational notes from the Trades docs:** - **Subscriptions** are the primary pattern for **live** streams; you can often use the **same selection as a `query`** with a **time window** on **`Block`** / **`Interval`** where supported. - **Token filter:** **`Pair.Token.Id`** with the full id (e.g. `bid:solana:`, `bid:eth:`) per dataset conventions. - **Trader filter:** **`Trader.Address`**. For **aggregated** token metrics across pairs, use **[Tokens](/docs/trading/crypto-price-api/tokens)**; for **pair-level** OHLC intervals, use **[Pairs](/docs/trading/crypto-price-api/pairs)**—as noted on the [Trades API page](/docs/trading/crypto-trades-api/trades-api). --- ## Quick decision guide 1. **EVM / Tron: one row per pool swap** with pool **`Buy`/`Sell`** semantics, or **Solana: trades by signer / account / buy vs sell** on chain? → **`DEXTrades`** on the right **chain root**. 2. **Token-expanded rows**, OHLC **from raw DEX trades older than ~30 days**, or **Solana** maker/buyer/seller aggregates on **`DEXTradeByTokens`**? → **`DEXTradeByTokens`**, with **strict filters** on **EVM** so counts are not doubled. (For OHLC within ~30 days, prefer the pre-aggregated [Crypto Price API](/docs/trading/crypto-price-api/) instead.) 3. **Real-time or last-~30-days** trades: **trader-centric** product, **multi-chain** `Trading` stream, **reliable USD** (including meme / long-tail), plus **supply** on each row? → **`Trading { Trades }`** ([Crypto Trades API](/docs/trading/crypto-trades-api/trades-api)). Note the **~30-day rolling window** — for a deeper backfill, drop to the chain-level cubes above. 4. **Need pre-built candles / moving averages / mean price** without aggregating raw swaps yourself? → **[Crypto Price API](/docs/trading/crypto-price-api/)** (**Tokens**, **Pairs**, **Currencies**)—not the same as **`Trades`**, as explained in the [mental model](/docs/start/mental-model-transfers-events-calls#trading-crypto-price-cube). --- ## Chain hub examples These guides start with a **live swap stream** from the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api) (IDE link where we ship a saved query), then keep **`DEXTrades`** / **`DEXTradeByTokens`** for pools, OHLC, and analytics: - [BNB (BSC) DEX Trades](/docs/blockchain/BSC/bsc-dextrades) - [Base DEX Trades](/docs/blockchain/Base/base-dextrades) - [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades) - [Polygon (MATIC) DEX Trades](/docs/blockchain/Matic/matic-dextrades) - [Optimism DEX Trades](/docs/blockchain/Optimism/optimism-dextrades) - [Tron DEX Trades](/docs/blockchain/Tron/tron-dextrades) - [Arbitrum DEX Trades](/docs/blockchain/Arbitrum/DexTrades) --- ## Related documentation - [Mental model: transfers, events, calls, DEX, Trading](/docs/start/mental-model-transfers-events-calls) - [DEXTrades cube](/docs/cubes/dextrades) - [DEXTradesByTokens cube](/docs/cubes/dextradesbyTokens) - [Crypto Trades API — `Trades`](/docs/trading/crypto-trades-api/trades-api) - [GraphQL limits](/docs/graphql/limits) (paging, `orderBy`, time windows) --- ## DEXTradesByTokens Cube URL: https://docs.bitquery.io/docs/cubes/dextradesbyTokens/ DEXTradeByTokens cube explained: trade and side structure, OHLC queries, when to use it vs DEXTrades, filtering, portfolio tracking and avoiding duplicates. # DEXTradesByTokens Cube :::tip Need real-time data or anything from the last ~30 days? For **real-time + last ~30 days**, use the [**Trading cube**](/docs/trading/trading-data-overview) — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) gives you clean, MEV-filtered swaps with **USD price, market cap, and supply on every row** across **10 chains in one API**. Use this cube when you need **historical data older than ~30 days** (with `dataset: combined` or `archive`), custom OHLC intervals, or token-expanded rows. ::: > **Before you start**: Not sure when to use DexTradesByTokens vs DexTrades vs Events vs Calls? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. For a 1-page comparison of these three trade cubes, see [DEXTrades vs DEXTradeByTokens vs Trades cube](/docs/cubes/dextrades-dextradebytokens-trading-trades). The DEXTradesByTokens cube provides comprehensive information about DEX trading data from a token-centric perspective, showing both sides of each trade for every participant. This includes buyer, seller, token prices, pairs, transactions, OHLC data, and more. Unlike DEXTrades cube which uses `Buy` and `Sell` from the pool's perspective, DEXTradesByTokens uses the concept of `Trade` and `Side` to represent both sides of each trade from a token-centric view. ## Concept Explanation Let's understand the concept of buyer and seller when a trade occurs between User A and User B, and Token X and Token Y are swapped between them. ![Token A to Token B trade pair diagram](/img/tokenAB.png) We see the trade from user A's side, then we get the following: - User A becomes the seller of token X. - User A becomes the buyer of token Y. Now, if we see the trade from a user B side, we get the following. - User B becomes the seller of token Y. - User B becomes the buyer of token X. Therefore, buyers and sellers change relatively when the trade sides change. > Important note: If a trade occurs between User A and User B, the DexTradesByTokens API shows User A as both buyer and a seller, and similarly for User B. The result includes both perspectives, displaying each user as a buyer and then as a seller. [Run this API for better understanding](https://ide.bitquery.io/DEXTradeByTokens-API_1). When you run this API you get the following result. ```json { "EVM": { "DEXTradeByTokens": [ { "Trade": { "Buyer": "0x92560c178ce069cc014138ed3c2f5221ba71f58a", "Currency": { "Name": "Wrapped Ether" }, "Seller": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c", "Side": { "Buyer": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c", "Seller": "0x92560c178ce069cc014138ed3c2f5221ba71f58a" } } }, { "Trade": { "Buyer": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c", "Currency": { "Name": "Ethereum Name Service" }, "Seller": "0x92560c178ce069cc014138ed3c2f5221ba71f58a", "Side": { "Buyer": "0x92560c178ce069cc014138ed3c2f5221ba71f58a", "Seller": "0xa69babef1ca67a37ffaf7a485dfff3382056e78c" } } } ] } } ``` In the above result, User A (0x925...) is included as both a buyer and a seller. The same applies to User B (0xa69...), who is also shown as both a buyer and a seller. If one become a buyer then other automatically become a seller. > Important note: Let's say currency X and currency Y are swapped in trade. Then, the trade side currency of X is Y, and the trade side currency of Y is X. Therefore, the trade side currency is relatively changed based on the currency that is traded against it. ## Understanding Trade and Side Structure In DEXTradesByTokens, each trade is represented with two main components: - **`Trade`**: The primary side of the trade, focusing on one specific token/currency - **`Side`**: The counter-side of the trade, representing what the token is being traded against ### Example Structure Comparison **DEXTrades Approach (Pool Perspective):** ```graphql Trade { Buy { Currency { Symbol } # What the pool buys Amount Buyer # Pool address } Sell { Currency { Symbol } # What the pool sells Amount Seller # User address } } ``` **DEXTradesByTokens Approach (Token Perspective):** ```graphql Trade { Currency { Symbol } # Primary token (e.g., "PEPE") Amount # Amount of primary token Buyer # Who bought the primary token Seller # Who sold the primary token Side { Currency { Symbol } # Counter token (e.g., "WETH") Amount # Amount of counter token Type # "buy" or "sell" (from pool's perspective) Buyer # Buyer of the side currency Seller # Seller of the side currency } } ``` **Note on Pool Role**: The `Side.Type` field indicates the pool's role relative to the side currency: - If `Side.Type` is `"buy"`, the pool is the buyer of the side currency (pool = `Side.Buyer`) - If `Side.Type` is `"sell"`, the pool is the seller of the side currency (pool = `Side.Seller`) ## How do I get OHLC in a DEXTradeByTokens query? {#how-do-i-get-ohlc-in-a-dextradebytokens-query} For OHLC, use the **[Crypto Price API](/docs/trading/crypto-price-api/)** (`Trading` → `Tokens` / `Pairs`) as the **main** source—pre-aggregated and simpler. **Use `DEXTradeByTokens` on this page when you need historical OHLC** or when you must derive candles from **raw DEX trades** for a specific token or pool. Aggregate trades into candles with **`Block { Time(interval: { count, in: minutes | hours | days }) }`** on **`DEXTradeByTokens`**, then derive **open / high / low / close** from **`PriceInUSD`** (or your chain’s price field)—for example **`minimum`** / **`maximum`** of **`Trade_PriceInUSD`** and **`minimum`/`maximum` of `Block_Number`** for open and close. Filter by **`Trade.Currency`** (token address or mint) and optionally **`Trade.Dex`**. The same pattern works on **`EVM`** and **`Solana`**; see also [Solana OHLC API](/docs/blockchain/Solana/solana-dextrades/#solana-ohlc-api). ```graphql { EVM(network: eth, dataset: combined) { DEXTradeByTokens( limit: { count: 24 } orderBy: { ascending: Block_Time } where: { TransactionStatus: { Success: true } Trade: { Currency: { SmartContract: { is: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" } } } Block: { Time: { since: "2024-12-01" } } } ) { Block { Time(interval: { count: 1, in: hours }) } Trade { open: PriceInUSD(minimum: Block_Number) high: PriceInUSD(maximum: Trade_PriceInUSD) low: PriceInUSD(minimum: Trade_PriceInUSD) close: PriceInUSD(maximum: Block_Number) } volumeUsd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## How do I use DEXTradeByTokens vs DEXTrades for OHLCV? {#how-do-i-use-dextradebytokens-vs-dextrades-for-ohlcv} For **OHLCV**, treat the **Crypto Price API** as the default—see [when to use which](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api/#crypto-price-api-vs-dextradebytoken). Among DEX cubes, prefer **`DEXTradeByTokens`** for **one token’s** chart (all pools and sides from the token’s view with **`Trade`** + **`Side`**). Use **`DEXTrades`** when you need **each raw swap** as a row (pool **`Buy`/`Sell`** view, routing, or debugging). Both can power candles; **`DEXTradeByTokens`** is usually simpler for **per-token** open/high/low/close and volume. Compare with [DEXTrades](/docs/cubes/dextrades/). ## Filtering in DEXTradeByTokens Cube Filtering helps to fetch the exact data you are looking for. DexTradeByTokens Cube can filter based on currency, buyer, seller, dex, pool, sender, transaction, time, etc. Everything inside the "where" clause filters; it follows the `AND' condition by default. ## Advanced Use Cases and Processing Patterns ### Portfolio Tracking and User Analytics DEXTradesByTokens excels at tracking individual user activity across all their trades: #### User Portfolio Balance Tracker ```python def track_user_portfolio(user_address, trades_data): """Track user's token portfolio changes over time""" portfolio = defaultdict(lambda: {'balance': 0, 'total_bought': 0, 'total_sold': 0}) for trade in trades_data: token = trade['currency']['smart_contract'].lower() amount = float(trade['amount']) if trade['seller'].lower() == user_address.lower(): # User sold this token portfolio[token]['balance'] -= amount portfolio[token]['total_sold'] += amount elif trade['buyer'].lower() == user_address.lower(): # User bought this token portfolio[token]['balance'] += amount portfolio[token]['total_bought'] += amount return portfolio ``` #### Query for User Activity Tracking ```graphql query UserActivityTracking( $userAddress: String! $sinceDate: ISO8601DateTime! ) { EVM(dataset: combined, network: eth) { DEXTradeByTokens( where: { Block: { Time: { since: $sinceDate } } Trade: { # Get all trades where user is either buyer or seller any: [ { Buyer: { is: $userAddress } } { Seller: { is: $userAddress } } ] } } orderBy: { ascending: Block_Time } ) { Block { Time Number } Trade { Buyer Seller Amount AmountInUSD Currency { SmartContract Symbol Name } Side { Amount AmountInUSD Currency { SmartContract Symbol } } } Transaction { Hash Signer } } } } ``` ## How do I avoid duplicate results in DEX trade queries? **`DEXTradeByTokens`** intentionally returns **multiple rows per swap** (token-centric **Trade** + **Side**). If you want to avoid this, please specify the **Side** currency. Alternatively, switch to **`DEXTrades`** if you need **one row per pool swap**. To deduplicate during analysis, group or filter by **`Transaction.Hash`** (and trade index when present). For paging, use a **stable `orderBy`** and **time/blocks windows**; see [GraphQL limits](/docs/graphql/limits/). Background: [DEXTrades vs DEXTradeByTokens](/docs/cubes/dextradesbyTokens/#how-do-i-use-dextradebytokens-vs-dextrades-for-ohlcv) and the [mental model](/docs/start/mental-model-transfers-events-calls). --- ## 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/) 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. For AI-driven fund tracing, use the [Bitquery MCP server](https://mcp.bitquery.io/) ([Tracing MCP guide](/docs/mcp/Tracing/overview)). | ### Trading cube (cross-chain Trades / Tokens / Pairs) | Surface | Window | Notes | |---|---|---| | Trades / Tokens / Pairs / Currencies | ~30 days | All four cubes measure the same floor. For older raw trades use chain-level `DEXTradeByTokens` or 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. | ### Arc mainnet Circle's Arc mainnet uses `EVM(network: arc)`. The realtime path, USD fields, `Holders`, and the cross-chain `Trading.Trades`, `Trading.Tokens`, and `Trading.Pairs` cubes returned live data in checks on 16 September 2026. `dataset: archive` and `dataset: combined` were not enabled, so leave the dataset argument out and measure the live window before assuming a range. See the [Arc Mainnet API guides](/docs/blockchain/arc-mainnet/). | Surface | Window | Notes | |---|---|---| | EVM cubes | Realtime window | Query with `EVM(network: arc)` and no dataset argument. | | `Trading.Trades`, `Trading.Tokens`, `Trading.Pairs` | Trading rolling window | Filter with network name `Arc` or network id `bid:arc`. | | `archive`, `combined` | Not available | Retry before building a historical backfill. | ### Arc testnet Circle's Arc testnet (`EVM(network: arc_testnet)`) is served from the **realtime dataset only**. There is no archive for the testnet, so `dataset: archive` and `dataset: combined` return errors, the `Holders` cube is not available, and every `...InUSD` field is 0. The realtime window is a rolling range of recent blocks; measure it with `Block { Time(minimum: Block_Time) }`. Use [Arc mainnet](/docs/blockchain/arc-mainnet/) for live production data with USD pricing. See the [Arc Testnet hub](/docs/blockchain/arc-testnet/). | Cube | Window | Notes | |---|---|---| | `DEXTrades`, `DEXTradeByTokens`, `Transfers`, `Events`, `Calls`, `Transactions`, `Blocks`, `Balances`, `TransactionBalances` | Realtime window only | No archive; USD fields are 0. | | `Holders`, `DEXPoolEvents`, `DEXPoolSlippages`, `Trading.*` | Not available | `Holders` needs the archive; pool cubes have no data yet; the Trading cubes cover mainnet chains only. | ### Hyperliquid Hyperliquid core is an L1 order-book exchange, so its cubes carry exchange events rather than EVM blocks. 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. --- ## EVM Arguments and Returns API URL: https://docs.bitquery.io/docs/schema/evm/arguments/ EVM Arguments and Returns API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. # EVM Arguments and Returns API Smart contract calls and events have arguments. In case the call or event signature is parsed against ABI, the arguments are showing the values, types and names passed to call or event. In addition, returns shows the return values from the smart contract calls. Arguments and returns are represented by the same data structure. It is array, containing entries for each argument value. In case when the data type of argument is array or emedded structure, the argument will have separate object for every value of array or structure. It means that all argument values are flattened. To represent all possible cases, the following additional information is provided: - Index - sequential index of argument value inside an array or strucutre - Name - name of the argument or the name of the element of structure - Type - the type of the argument - Path - the array of top-level elements where the argument value is used. Each element of path have Name, Index, Type As example, the following data means the array of size 2 of addresses: ```json { "Index": 0, "Name": "", "Path": [ { "Index": 2, "Name": "path", "Type": "address[]" } ], "Type": "address", "Value": { "__typename": "EVM_ABI_Address_Value_Arg", "address": "0x6c812ab49f4b350b9d115e3f367302cd4fb58bbf" } }, { "Index": 1, "Name": "", "Path": [ { "Index": 2, "Name": "path", "Type": "address[]" } ], "Type": "address", "Value": { "__typename": "EVM_ABI_Address_Value_Arg", "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } }, ``` meaning `['0x6c812ab49f4b350b9d115e3f367302cd4fb58bbf','0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2']` To query attribute values, use union as shown: ```graphql Arguments { Index Name Type Path { Index Name Type } Value { __typename ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } ``` Data types are mapped to this values by the following rules: 1. string, addresses, boolean are mapped directly to corresponding types (EVM_ABI_String_Value_Arg,EVM_ABI_Address_Value_Arg,EVM_ABI_Boolean_Value_Arg) 2. bytes and byte array of any pre-defined size ( such as byte[24]) mapped to hex bytes (EVM_ABI_Bytes_Value_Arg) 3. integers of size int8,16,32 and uint8,16 are mapped to integer (EVM_ABI_Integer_Value_Arg) 4. all other integers mapped to big integer represented as string ( possible negative ) (EVM_ABI_BigInt_Value_Arg) ## Filters on arguments Arguments and returns are arrays, and this enables to use filtering on them as described on [filters](/docs/graphql/filters/#array-filter-types). For example, this query selects specific calls by applying filter to argument length and to specific values of arguments. Combining argument filters with signature filters on events and calls gives you the power to analyze the arguments used in smart contracts in specific context. ```graphql { EVM { Calls( where: { Arguments: { length: {eq: 2} includes: [ { Index: {eq: 0} Name: {is: "recipient"} Value: {Address: {is: "0xa7f6ebbd4cdb249a2b999b7543aeb1f80bda7969"}} } { Name: {is: "amount"} Value: {BigInteger: {ge: "1000000000"}} } ] } } limit: {count: 10}) { Arguments { Index Name Type Value { ... on EVM_ABI_Integer_Value_Arg { integer } ... on EVM_ABI_String_Value_Arg { string } ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_BigInt_Value_Arg { bigInteger } ... on EVM_ABI_Bytes_Value_Arg { hex } ... on EVM_ABI_Boolean_Value_Arg { bool } } } Call { Signature { Signature } } } } } ``` The value of argument filter must be defined depending on the expected argument type. There are the following options: - BigInteger - for uint256/int256/int64/uint64 arguments - Address - for addresses, 0x prefixed - String - for strings - Boolean - for boolean, just true/false - UnsignedInteger - for uint8/16/32 - SignedInteger - int8/16/32 - Bytes - for bytes, 0x prefixed optional :::note filters affect the whole query to calls / events, so you anyway can query all arguments, not just which pass the filter. ::: --- ## EVM Balance Schema API URL: https://docs.bitquery.io/docs/schema/evm/balances/ EVM Balance API: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. See examples in the Bitquery IDE. # EVM Balance API :::caution Query-only A subscription on `Balances` is accepted but never pushes a message. Poll it, or stream `TransactionBalances` / `Transfers` and apply deltas. See [which cubes support subscriptions](/docs/subscriptions/which-cubes-stream/). ::: The **Balances** API returns current and historical token balances for addresses on EVM chains. To return only non-zero balances, add `Amount(selectWhere: { gt: "0" })` on the `Balance` field (not in `where`). Use `dataset: combined` or `dataset: archive` as follows: | Dataset | When to use | |---------|-------------| | **`combined`** | Latest balances. Queries **realtime and archive** databases and merges results. | | **`archive`** | Historical snapshots with `Block.Date`, and balances for **addresses not recently active**. | Full Ethereum examples: [Address Balance API](/docs/blockchain/Ethereum/balances/balance-api/). ## Balance of an address ```graphql query { EVM(network: eth, dataset: combined) { Balances( where: { Balance: { Address: { is: "0x76147fd7891731e01f35cc18f87ae8e95bf06869" } } } ) { Currency { Symbol SmartContract } Balance { Amount(selectWhere: { gt: "0" }) AmountInUSD Address } } } } ``` ### Examples on Ethereum - [Balance of an address](/docs/blockchain/Ethereum/balances/balance-api/#balance-of-an-address) - [Balance on a specific date](/docs/blockchain/Ethereum/balances/balance-api/#balance-on-a-specific-date) - [Balance for a specific token](/docs/blockchain/Ethereum/balances/balance-api/#balance-for-a-specific-token) - [Balance history by date](/docs/blockchain/Ethereum/balances/balance-api/#balance-history-by-date) - [Wallet balance for a specific token on a date](/docs/blockchain/Ethereum/balances/balance-api/#wallet-balance-for-a-specific-token-on-a-date) --- ## EVM Blocks Schema URL: https://docs.bitquery.io/docs/schema/evm/blocks/ Blocks: Bitquery EVM GraphQL schema reference with fields, filters, relationships, and query patterns. Copy GraphQL snippets for production apps. # EVM Blocks Schema Blocks API provide details on blocks. You can use different [filters](/docs/graphql/filters/) to query data from different dimensions. You can find more examples [here](/docs/blockchain/Ethereum/blocks/blocks-api/) Let's see an example of Blocks API to get the latest 10 blocks on Ethereum blockchain. ```graphql { EVM(dataset: archive, network: eth) { Blocks(limit: { count: 10 }, orderBy: { descending: Block_Number }) { Block { Time Date Number Hash } } } } ``` You can see more example of Blocks api in [here](/docs/blockchain/Ethereum/blocks/blocks-api/). --- ## EVM Builder Terms Explaination URL: https://docs.bitquery.io/docs/glossary/EVM/ EVM API terms explained: dataset, mempool, network and filter parameters, plus field definitions for Blocks, Calls, DEXTrades, Events, Transfers and more. # EVM Builder Terms Explaination ### Dataset Parameters EVM API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from the first (genesis) block up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Mempool Parameter - `mempool` - The mempool in EVM (Ethereum Virtual Machine) is a temporary storage area where pending transactions are held before being included in a block by miners. ### Network Parameter - `network` - Through network field you can select EVM based network such as bsc, arbitrum, eth , and etc available on Bitquery. ### Filter Parameters EVM API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Address`: The wallet address where the balance update occurred. - `Amount`: The quantity of token involved in the balance update. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. - `Id`: The unique identifier for the balance update event. - `Type`: The nature of the balance update, such as `transfer` or `block_reward`. - `URI`: The link to additional information or metadata about the balance update. ### Blocks API Terms - `BaseFee`: The minimum gas price for transactions in the block. - `BaseFeeInUSD`: The equivalent base fee value in US dollars. - `Hash`: The unique identifier for the block. - `GasUsed`: The total gas consumed by all transactions in the block. - `GasLimit`: The maximum amount of gas that can be used by all transactions in the block. - `Extra`: Additional data included in the block. - `Difficulty`: The complexity level of the block mining process. - `Date`: The timestamp of when the block was mined. - `Coinbase`: The address of the miner who mined the block. - `Bloom`: A data structure for quickly checking the presence of a particular log entry. - `MixDigest`: A unique value from the proof-of-work algorithm. - `UnclesCount`: The number of uncle blocks included in this block. - `UncleHash`: The hash of the uncle blocks. - `TxHash`: The hash of the transactions included in the block. - `TxCount`: The number of transactions in the block. - `Time`: The exact time when the block was mined. - `Root`: The root hash of the state trie. - `Result`: Contains details about gas used and any errors encountered. - `ReceiptHash`: The hash of the transaction receipts. - `ParentHash`: The hash of the previous block. - `Number`: The unique number of the block in the blockchain. - `Nonce`: A value used to validate the block's proof-of-work. ### Calls API Terms #### Arguments - `Index`: The position of the argument within the function call. - `Name`: The name of the argument in the function call. - `Value`: The data value of the argument, which can be of various types such as boolean, bytes, big integer, address, string, or integer. - `bool`: A boolean value (true or false). - `hex`: A hexadecimal byte string. - `bigInteger`: A large integer value. - `address`: An Ethereum address. - `string`: A text string. - `integer`: A numerical integer value. - `Type`: The data type of the argument. - `Path`: The location of the argument in nested calls, including type, name, and index. #### Calls - `ValueInUSD`: The value of the call in US dollars. - `Value`: The value transferred in the call. - `To`: The recipient address of the call. - `Success`: Indicates whether the call was successful. - `Signature`: Details about the function signature used in the call. - `SignatureType`: The type of the signature. - `SignatureHash`: The hash of the function signature. - `Signature`: The actual function signature. - `Parsed`: The parsed details of the signature. - `Name`: The name of the function. - `Abi`: The ABI (Application Binary Interface) details. - `SelfDestruct`: Indicates if the contract self-destructed during the call. - `Reverted`: Indicates if the call was reverted. - `Output`: The output data from the call. - `Opcode`: The operation code details. - `Name`: The name of the opcode. - `Code`: The numeric code of the opcode. - `LogCount`: The number of logs generated by the call. - `InternalCalls`: Details about calls made within the current call. - `Input`: The input data for the call. - `Index`: The position of the call within a block or transaction. - `GasUsed`: The amount of gas used by the call. - `Gas`: The gas limit for the call. - `From`: The sender address of the call. - `CallPath`: The sequence of calls leading to the current call. - `CallerIndex`: The index of the caller within nested calls. - `Create`: Indicates if a new contract was created during the call. - `ExitIndex`: The exit position of the call. - `Error`: Details about any error that occurred during the call. - `EnterIndex`: The entry position of the call. - `Depth`: The depth of the call within nested calls. - `Delegated`: Indicates if the call was a delegated call. ### DEXTradeByTokens API Terms DEXTradeByTokens API retrieves trade details for a token pair, distinguishing between the primary token (`Trade{Currency}`) and the side currency (`Side{Currency}`). The fields within each section provide specific trade-related information as follows: DEXTradeByTokens API contains Trade field which has below attributes: - **Trade** - `Amount`: Quantity of tokens traded. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Buyer`: Address of the buyer. - `Fees` - `Amount`: Amount of fees paid. - `AmountInUSD`: Equivalent value of fees in USD. - `Ids`: IDs related to the trade. - `OrderId`: Identifier for the order. - `Price`: Price of Primary currency in the trade. - `PriceAsymmetry`: Asymmetry factor in token pricing. - `PriceInUSD`: Token price in USD. - `Sender`: Address of the sender. - `Seller`: Address of the seller. - `Success`: Indicates if the trade was successful. - `Dex` - `Delegated`: Indicates if the trade is delegated. - `DelegatedTo`: Address of the delegate. - `OwnerAddress`: Address of the owner. - `SmartContract`: DEX smart contract address. - `ProtocolVersion`: Version of the protocol. - `ProtocolName`: Name of the protocol. - `Pair` - `Symbol`: Symbol of the token pair. - `SmartContract`: Token Pair Smart contract address. - `Name`: Name of the token pair. - `Decimals`: Decimal places for token precision. - `ProtocolFamily`: Family of the protocol. - `Currency` - `Name`: Name of the currency. - `Symbol`: Symbol of the currency. - `SmartContract`: Currency smart contract address. - `Side` - `URIs`: Uniform Resource Identifiers related to the trade side. - `Type`: Type of the trade side (buy or sell). - `Seller`: Address of the seller. - `OrderId`: Identifier for the order related to the side. - `Ids`: IDs related to the trade side. - `AmountInUSD`:AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Amount`: Quantity of side tokens traded. - `Currency`: Side Currency Details. ### DEXTrades API Terms Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. For your information this buy side and sell side is wrt to Liquidity Pool. For video explaination, watch this [video](https://www.youtube.com/watch?v=f052KzAsqnQ). - `Buy` - `Buyer`: Address of the buyer of this bought currency. This is the pool address. - `Seller`: Address of the Seller of this bought currency. - `Amount`: Quantity of tokens bought. - `Price`: Price of the buy currency in the trade. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Sell` - `Buyer`: Address of the buyer of this sold currency. - `Seller`: Address of the Seller of this sold currency. This is the pool address. - `Amount`: Quantity of tokens sold. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Price`: Price of the sell currency in the trade. - `Dex` - `ProtocolName`: Name of the DEX protocol. - `SmartContract`: Smart contract address of the DEX. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolVersion`: Version of the DEX protocol. - `Pair`: Contains the liquidity pair details ### Events API Terms - `Log`: Detailed log information. - `LogAfterCallIndex`: Index after the call. - `Index`: Log index within the block. - `ExitIndex`: Index when exiting. - `EnterIndex`: Index when entering. - `Pc`: Program counter value. - `Signature`: Signature details of the log. - `Abi`: ABI of the signature. - `Name`: Name of the signature. - `SignatureType`: Type of the signature. - `SignatureHash`: Hash of the signature. - `Signature`: Full signature string. - `Parsed`: Indicates if the signature is parsed. - `SmartContract`: Indicates if the log involves a smart contract. - `LogHeader`: Header information of the log. - `Removed`: Indicates if the log is removed. - `Index`: Index of the log header. - `Data`: Data of the log. - `Address`: Address of the log. - `Receipt`: Transaction receipt details. - `GasUsed`: Amount of gas used by the transaction. - `CumulativeGasUsed`: Total gas used by the block. - `ContractAddress`: Address of the contract created. - `Status`: Status of the transaction. - `Type`: Type of the transaction. - `Topics`: Log topics. - `Hash`: Hash of the topic. ### Transactions API Terms - `ValueInUSD`: Value of the transaction in USD. - `Value`: Value of the transaction in cryptocurrency. - `Type`: Type of transaction (e.g., transfer, contract creation, contract creation). - `To`: Recipient address of the transaction. - `Time`: Timestamp of the transaction. - `Protected`: Indicates if the transaction is protected. - `Nonce`: Nonce value of the transaction. - `Index`: Index position of the transaction. - `Hash`: Hash of the transaction. - `GasTipCap`: Tip cap for gas. - `GasPriceInUSD`: Gas price in USD. - `GasPrice`: Gas price in cryptocurrency. - `GasFeeCap`: Fee cap for gas. - `Gas`: Amount of gas used. - `From`: Sender address of the transaction. - `Data`: Data associated with the transaction. - `Cost`: Cost of the transaction in cryptocurrency. - `CostInUSD`: Equivalent cost of the transaction in USD. - `CallCount`: Number of calls made in the transaction. ### MinerRewards API Terms - `Reward`: Details of the reward. - `UncleInUSD`: USD value of uncle rewards. - `Uncle`: Amount of uncle rewards. - `TxFeesInUSD`: USD value of transaction fees. - `TxFees`: Amount of transaction fees. - `TotalInUSD`: Total reward value in USD. - `Total`: Total reward amount. - `StaticInUSD`: USD value of static rewards. - `Static`: Amount of static rewards. - `DynamicInUSD`: USD value of dynamic rewards. - `Dynamic`: Amount of dynamic rewards. - `BurntFeesInUSD`: USD value of burnt transaction fees. - `BurntFees`: Amount of burnt transaction fees. ### Transfers API Terms - **Transfers**: Retrieves details of token transfers. - `Transfer` - `Type`: Type of transfer (e.g., token, transaction, call). - `Success`: Indicates if the transfer was successful. - `Sender`: Address of the sender. - `Receiver`: Address of the receiver. - `Id`: Identifier for the transfer. - `Data`: Additional data associated with the transfer. - `Currency` - `Name`: Name of the token transferred. - `Symbol`: Symbol of the token transferred. - `Amount`: Quantity of tokens transferred. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. ### Currency Field Attributes Explained - `Currency`: Details about a token or asset. - `Symbol`: Symbol representing the token. - `SmartContract`: Token Program Address. - `Name`: Name of the token. - `HasURI`: Indicates if the currency has a Uniform Resource Identifier (URI). - `Fungible`: Indicates if the currency is fungible. - `Decimals`: Number of decimal places used to represent fractional amounts of the currency. --- ## EVM Builder Terms Explanation URL: https://docs.bitquery.io/docs/cubes/EVM/ EVM cube terms explained: dataset, mempool, network and filter parameters, plus the fields of Blocks, Calls, Events, DEXTrades, Transfers and other EVM APIs. # EVM Builder Terms Explanation ### Dataset Parameters EVM API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from the first (genesis) block up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Mempool Parameter - `mempool` - The mempool in EVM (Ethereum Virtual Machine) is a temporary storage area where pending transactions are held before being included in a block by miners. ### Network Parameter - `network` - Through network field you can select EVM based network such as bsc, arbitrum, eth , and etc available on Bitquery. ### Filter Parameters EVM API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Address`: The wallet address where the balance update occurred. - `Amount`: The quantity of token involved in the balance update. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. - `Id`: The unique identifier for the balance update event. - `Type`: The nature of the balance update, such as `transfer` or `block_reward`. - `URI`: The link to additional information or metadata about the balance update. ### Blocks API Terms - `BaseFee`: The minimum gas price for transactions in the block. - `BaseFeeInUSD`: The equivalent base fee value in US dollars. - `Hash`: The unique identifier for the block. - `GasUsed`: The total gas consumed by all transactions in the block. - `GasLimit`: The maximum amount of gas that can be used by all transactions in the block. - `Extra`: Additional data included in the block. - `Difficulty`: The complexity level of the block mining process. - `Date`: The timestamp of when the block was mined. - `Coinbase`: The address of the miner who mined the block. - `Bloom`: A data structure for quickly checking the presence of a particular log entry. - `MixDigest`: A unique value from the proof-of-work algorithm. - `UnclesCount`: The number of uncle blocks included in this block. - `UncleHash`: The hash of the uncle blocks. - `TxHash`: The hash of the transactions included in the block. - `TxCount`: The number of transactions in the block. - `Time`: The exact time when the block was mined. - `Root`: The root hash of the state trie. - `Result`: Contains details about gas used and any errors encountered. - `ReceiptHash`: The hash of the transaction receipts. - `ParentHash`: The hash of the previous block. - `Number`: The unique number of the block in the blockchain. - `Nonce`: A value used to validate the block's proof-of-work. ### Calls API Terms #### Arguments - `Index`: The position of the argument within the function call. - `Name`: The name of the argument in the function call. - `Value`: The data value of the argument, which can be of various types such as boolean, bytes, big integer, address, string, or integer. - `bool`: A boolean value (true or false). - `hex`: A hexadecimal byte string. - `bigInteger`: A large integer value. - `address`: An Ethereum address. - `string`: A text string. - `integer`: A numerical integer value. - `Type`: The data type of the argument. - `Path`: The location of the argument in nested calls, including type, name, and index. #### Calls - `ValueInUSD`: The value of the call in US dollars. - `Value`: The value transferred in the call. - `To`: The recipient address of the call. - `Success`: Indicates whether the call was successful. - `Signature`: Details about the function signature used in the call. - `SignatureType`: The type of the signature. - `SignatureHash`: The hash of the function signature. - `Signature`: The actual function signature. - `Parsed`: The parsed details of the signature. - `Name`: The name of the function. - `Abi`: The ABI (Application Binary Interface) details. - `SelfDestruct`: Indicates if the contract self-destructed during the call. - `Reverted`: Indicates if the call was reverted. - `Output`: The output data from the call. - `Opcode`: The operation code details. - `Name`: The name of the opcode. - `Code`: The numeric code of the opcode. - `LogCount`: The number of logs generated by the call. - `InternalCalls`: Details about calls made within the current call. - `Input`: The input data for the call. - `Index`: The position of the call within a block or transaction. - `GasUsed`: The amount of gas used by the call. - `Gas`: The gas limit for the call. - `From`: The sender address of the call. - `CallPath`: The sequence of calls leading to the current call. - `CallerIndex`: The index of the caller within nested calls. - `Create`: Indicates if a new contract was created during the call. - `ExitIndex`: The exit position of the call. - `Error`: Details about any error that occurred during the call. - `EnterIndex`: The entry position of the call. - `Depth`: The depth of the call within nested calls. - `Delegated`: Indicates if the call was a delegated call. ### DEXTradeByTokens API Terms DEXTradeByTokens API retrieves trade details for a token pair, distinguishing between the primary token (`Trade{Currency}`) and the side currency (`Side{Currency}`). The fields within each section provide specific trade-related information as follows: DEXTradeByTokens API contains Trade field which has below attributes: - **Trade** - `Amount`: Quantity of tokens traded. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Buyer`: Address of the buyer. - `Fees` - `Amount`: Amount of fees paid. - `AmountInUSD`: Equivalent value of fees in USD. - `Ids`: IDs related to the trade. - `OrderId`: Identifier for the order. - `Price`: Price of Primary currency in the trade. - `PriceAsymmetry`: Asymmetry factor in token pricing. - `PriceInUSD`: Token price in USD. - `Sender`: Address of the sender. - `Seller`: Address of the seller. - `Success`: Indicates if the trade was successful. - `Dex` - `Delegated`: Indicates if the trade is delegated. - `DelegatedTo`: Address of the delegate. - `OwnerAddress`: Address of the owner. - `SmartContract`: DEX smart contract address. - `ProtocolVersion`: Version of the protocol. - `ProtocolName`: Name of the protocol. - `Pair` - `Symbol`: Symbol of the token pair. - `SmartContract`: Token Pair Smart contract address. - `Name`: Name of the token pair. - `Decimals`: Decimal places for token precision. - `ProtocolFamily`: Family of the protocol. - `Currency` - `Name`: Name of the currency. - `Symbol`: Symbol of the currency. - `SmartContract`: Currency smart contract address. - `Side` - `URIs`: Uniform Resource Identifiers related to the trade side. - `Type`: Type of the trade side (buy or sell). - `Seller`: Address of the seller. - `OrderId`: Identifier for the order related to the side. - `Ids`: IDs related to the trade side. - `AmountInUSD`:AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WETH, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WETH. - `Amount`: Quantity of side tokens traded. - `Currency`: Side Currency Details. ### DEXTrades API Terms Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. For your information this buy side and sell side is wrt to Liquidity Pool. For video explaination, watch this [video](https://www.youtube.com/watch?v=f052KzAsqnQ). - `Buy` - `Buyer`: Address of the buyer of this bought currency. This is the pool address. - `Seller`: Address of the Seller of this bought currency. - `Amount`: Quantity of tokens bought. - `Price`: Price of the buy currency in the trade. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Sell` - `Buyer`: Address of the buyer of this sold currency. - `Seller`: Address of the Seller of this sold currency. This is the pool address. - `Amount`: Quantity of tokens sold. - `Currency`: Sold Currency details such as Name, Symbol, Token Contract Address. - `Price`: Price of the sell currency in the trade. - `Dex` - `ProtocolName`: Name of the DEX protocol. - `SmartContract`: Smart contract address of the DEX. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolVersion`: Version of the DEX protocol. - `Pair`: Contains the liquidity pair details ### Events API Terms - `Log`: Detailed log information. - `LogAfterCallIndex`: Index after the call. - `Index`: Log index within the block. - `ExitIndex`: Index when exiting. - `EnterIndex`: Index when entering. - `Pc`: Program counter value. - `Signature`: Signature details of the log. - `Abi`: ABI of the signature. - `Name`: Name of the signature. - `SignatureType`: Type of the signature. - `SignatureHash`: Hash of the signature. - `Signature`: Full signature string. - `Parsed`: Indicates if the signature is parsed. - `SmartContract`: Indicates if the log involves a smart contract. - `LogHeader`: Header information of the log. - `Removed`: Indicates if the log is removed. - `Index`: Index of the log header. - `Data`: Data of the log. - `Address`: Address of the log. - `Receipt`: Transaction receipt details. - `GasUsed`: Amount of gas used by the transaction. - `CumulativeGasUsed`: Total gas used by the block. - `ContractAddress`: Address of the contract created. - `Status`: Status of the transaction. - `Type`: Type of the transaction. - `Topics`: Log topics. - `Hash`: Hash of the topic. ### Transactions API Terms - `ValueInUSD`: Value of the transaction in USD. - `Value`: Value of the transaction in cryptocurrency. - `Type`: Type of transaction (e.g., transfer, contract creation, contract creation). - `To`: Recipient address of the transaction. - `Time`: Timestamp of the transaction. - `Protected`: Indicates if the transaction is protected. - `Nonce`: Nonce value of the transaction. - `Index`: Index position of the transaction. - `Hash`: Hash of the transaction. - `GasTipCap`: Tip cap for gas. - `GasPriceInUSD`: Gas price in USD. - `GasPrice`: Gas price in cryptocurrency. - `GasFeeCap`: Fee cap for gas. - `Gas`: Amount of gas used. - `From`: Sender address of the transaction. - `Data`: Data associated with the transaction. - `Cost`: Cost of the transaction in cryptocurrency. - `CostInUSD`: Equivalent cost of the transaction in USD. - `CallCount`: Number of calls made in the transaction. ### MinerRewards API Terms - `Reward`: Details of the reward. - `UncleInUSD`: USD value of uncle rewards. - `Uncle`: Amount of uncle rewards. - `TxFeesInUSD`: USD value of transaction fees. - `TxFees`: Amount of transaction fees. - `TotalInUSD`: Total reward value in USD. - `Total`: Total reward amount. - `StaticInUSD`: USD value of static rewards. - `Static`: Amount of static rewards. - `DynamicInUSD`: USD value of dynamic rewards. - `Dynamic`: Amount of dynamic rewards. - `BurntFeesInUSD`: USD value of burnt transaction fees. - `BurntFees`: Amount of burnt transaction fees. ### Transfers API Terms - **Transfers**: Retrieves details of token transfers. - `Transfer` - `Type`: Type of transfer (e.g., token, transaction, call). - `Success`: Indicates if the transfer was successful. - `Sender`: Address of the sender. - `Receiver`: Address of the receiver. - `Id`: Identifier for the transfer. - `Data`: Additional data associated with the transfer. - `Currency` - `Name`: Name of the token transferred. - `Symbol`: Symbol of the token transferred. - `Amount`: Quantity of tokens transferred. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. ### Currency Field Attributes Explained - `Currency`: Details about a token or asset. - `Symbol`: Symbol representing the token. - `SmartContract`: Token Program Address. - `Name`: Name of the token. - `HasURI`: Indicates if the currency has a Uniform Resource Identifier (URI). - `Fungible`: Indicates if the currency is fungible. - `Decimals`: Number of decimal places used to represent fractional amounts of the currency. --- ## EVM Cloud Data Exports URL: https://docs.bitquery.io/docs/cloud/evm/ Access Bitquery EVM cloud datasets for historical blockchain exports in Parquet, ready for S3, BigQuery, Snowflake, and data lakes. # EVM Data Bitquery provides **blockchain data 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://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balance_updates/24053500_24053549.parquet) - **Balances** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/balances.js), daily snapshots, see [Balances](#balances-daily-snapshots) below - **DEX Trades** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/dextrades.js) - **Uncle Blocks** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/uncle_blocks.js) - **Transactions** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/transactions.js) - **Transfers** – [sample file](https://github.com/bitquery/blockchain-cloud-data-dump-sample/blob/main/ethereum/transfers.js) ## Sample Ethereum Cloud Dataset To explore the schema and test your tooling, use our **public sample EVM datasets** on GitHub: - **Ethereum samples**: [`https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/ethereum`](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/ethereum) The GitHub repository includes one sample file for most topics; Balance Updates is only in the public S3 bucket. 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 Ethereum staking deposit contract (`0x00000000219ab540356cbb839cbe05303d7705fa`) and the WETH contract (`0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2`), which you can cross-check on any block explorer. ### `Balance_Amount` Is a String Balances are stored as **decimal strings**, not floats, so that 18-decimal values survive intact. Casting to a 64-bit float silently loses precision on large balances. Parse to a decimal type instead: ```python from decimal import Decimal df["amount"] = df["Balance_Amount"].map(Decimal) ``` In SQL, cast to a wide decimal — for example `CAST(Balance_Amount AS DECIMAL(38, 18))` — rather than `DOUBLE`. Note that some scam tokens carry balances near `2^256`: in the sample, 2,419 rows across 70 contracts overflow `DECIMAL(38, 18)`, and 1,537 rows across 3 contracts overflow even `DECIMAL(76, 18)`. Filter those contracts out, or keep the column as a string. ### Row Grain and Deduplication The grain is nearly `(Balance_Address, Currency_SmartContract, Currency_ProtocolName)`; 177 sample rows repeat even that key. Tokens recorded under more than one standard appear once per standard, so the same address and contract can sit on several rows — about 4,600 such pairs in the sample, most of them `erc20` plus `erc20_deposable`. These rows can repeat the **same** balance under a different `Currency_ProtocolName` (about one pair in five in the sample), so summing across them double-counts. Pick one `Currency_ProtocolName`, or deduplicate on the address and contract before aggregating. ### Reading a File in Python ```python from decimal import Decimal url = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/ethereum/balances/2025-01-01.parquet" df = pd.read_parquet(url) # native ETH only, identified by contract address rather than symbol native = df[df.Currency_SmartContract == "0x"].copy() native["amount"] = native.Balance_Amount.map(Decimal) print(len(native), "accounts changed ETH balance on this date") # sort_values, not nlargest: pandas cannot rank an object/Decimal column top = native.sort_values("amount", ascending=False).head(10) print(top[["Balance_Address", "amount"]]) ``` ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. EVM transfer datasets on the Data Store, one row per native or token transfer with sender, receiver and USD value: - [Ethereum Transfers](https://bitquery.io/datastore/datasets/ethereum-transfers) — Ethereum - [BSC Transfers](https://bitquery.io/datastore/datasets/bsc-transfers) — BSC - [Base Transfers](https://bitquery.io/datastore/datasets/base-transfers) — Base - [Polygon Transfers](https://bitquery.io/datastore/datasets/polygon-transfers) — Polygon - [Arbitrum Transfers](https://bitquery.io/datastore/datasets/arbitrum-transfers) — Arbitrum ## 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, Robinhood and Arc: what each holds and which to query. # EVM Cubes: Trades, Transfers, Balances, Calls and Events Every EVM chain Bitquery indexes is queried through one root, `EVM(network: ...)`, with the same cubes underneath: `DEXTrades`, `DEXTradeByTokens`, `DEXPools`, `Transfers`, `Balances`, `Holders`, `TransactionBalances`, `Transactions`, `Calls`, `Events`, `Blocks` and `MinerRewards`. A query written for Ethereum runs on BNB Chain, Base, Arbitrum, Optimism, Polygon, Robinhood Chain or Arc by changing the network name. Each cube takes `where`, `orderBy` and `limit`, supports `count`, `sum`, `uniq` and the other aggregates, and streams as a subscription, except `Balances` and `Holders`, which are query-only. This page is the map; the [EVM builder terms](/docs/cubes/EVM) page lists every field. ## The cubes | Cube | One row is | Reach for it when | |---|---|---| | `DEXTrades` | One swap with buy and sell sides, DEX, pool and trader | You need individual trades or a trade feed | | `DEXTradeByTokens` | One token side of a swap | You want per-token volume, OHLC, buyers, sellers or top pairs | | `DEXPools` | A pool event: creation, liquidity change, reserves | Pool discovery, TVL, slippage | | `Transfers` | One token or native transfer | Wallet activity, whale alerts, holder movements | | `Balances` and `Holders` | Current balance of an address, or holders of a token | Portfolios, holder rankings, distribution | | `TransactionBalances` | One balance change caused by a transaction | Per-transaction balance changes, live balance streams | | `Transactions` | One transaction with receipt, gas and status | Receipts, fees, failure rates | | `Calls` | One call or internal call with decoded arguments | Method traces, contract deployments, reverts | | `Events` | One decoded log | Any contract event, an `eth_getLogs` replacement | | `Blocks` and `MinerRewards` | One block, one reward | Block metadata and validator or miner rewards | ## Networks `eth`, `bsc`, `base`, `arbitrum`, `optimism`, `matic`, `robinhood`, `arc` and `arc_testnet` work in `EVM(network: ...)`. Arc mainnet has live USD fields and is documented in the [Arc Mainnet hub](/docs/blockchain/arc-mainnet/). Arc testnet is realtime-only with USD fields at 0; see the [Arc Testnet hub](/docs/blockchain/arc-testnet/). The schema is shared across these EVM networks. ## Datasets and depth Add `dataset: archive` or `dataset: combined` for history; without it a cube returns its realtime window only, which is hours to a few days depending on the cube. `DEXPools` is realtime-only on every chain: the archive and combined datasets do not exist for it. `Transactions` keeps full history on archive. The per-cube table is on [data coverage and retention](/docs/graphql/data-coverage-retention). ## Example: the busiest tokens on Ethereum in the last hour `DEXTradeByTokens` with a relative time filter, sorted by an aggregate. Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account; change `eth` to another network and it still runs. ```graphql { EVM(network: eth) { DEXTradeByTokens( where: { Block: { Time: { since_relative: { hours_ago: 1 } } } } orderBy: { descendingByField: "trades" } limit: { count: 5 } ) { Trade { Currency { Symbol SmartContract } } trades: count volume_usd: sum(of: Trade_Side_AmountInUSD) } } } ``` ## Pages in this section | Page | Read it for | |---|---| | [EVM builder terms](/docs/cubes/EVM) | Every argument and field across the EVM cubes | | [DEX Trades cube](/docs/cubes/dextrades) | Swap-level rows | | [DEXTradeByTokens cube](/docs/cubes/dextradesbyTokens) | Per-token aggregates and OHLC | | [DEXTrades vs DEXTradeByTokens vs Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades) | Which trade cube to use | | [DEXPools cube](/docs/cubes/evm-dexpool) | Pools, reserves, liquidity events | | [Transaction cube](/docs/cubes/transaction-cube) | Transactions and receipts | | [Balances and Holders cubes](/docs/cubes/balances-cube) | Current balances and holder rankings | | [Balance Updates cube](/docs/cubes/balance-updates-cube) | Balance history | | [Transfers cube](/docs/cubes/transfers-cube) | Token and native transfers | | [EVM token holders schema](/docs/schema/evm/token-holders) | Holder field reference | ## Related pages - [Understanding cubes](/docs/category/understanding-cubes) - [Ethereum API hub](/docs/blockchain/Ethereum/) - [EVM schema reference](/docs/schema/evm/dextrades) - [Data coverage and retention](/docs/graphql/data-coverage-retention) --- ## EVM DEX 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 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. --- ## 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). --- ## 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/ Transfer extraction from streamed blocks: where transfers live in a block, decoding Transfer events with a parser, and converting raw amounts. # 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. --- ## 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) --- ## 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. --- ## 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) ``` --- ## 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. ### 8. **Example Use Cases** #### Example 1 : Check if an address is a smartcontract Take [this](https://ide.bitquery.io/check-if-an-address-is-a-smart-contract) query for example, it helps you detect if an address is a smart contract. ```graphql { EVM(dataset: archive, network: eth) { Transfers( where: {Transfer: {Sender: {is: "0xcf38be613203b39a14d2fb3c1a345122ec0a4351"}}, Block: {Date: {after: "2025-03-01"}}} ) { Transfer { Receiver } count joinCalls(Call_To: Transfer_Receiver, join: inner) { count } } } } ``` #### How This Works - The query finds all transfers from a specific sender - Then, it checks if the receivers of these transfers were later called as smart contracts. - Since only smart contracts can process function calls, it is likely a smart contract if an address appears in joinCalls.(since EOAs cannot process function calls) - The count in joinCalls shows how many times the receiver was called. #### Example 2: Get trades, volume and marketcap of a token [This](https://ide.bitquery.io/get-trades-volume-and-market-cap-of-a-token-in-one-query_1) query is a good example of how joins could be used to get mulltiple trade related matrixes with a single query. ```graphql query MyQuery($time_1hr: DateTime) { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "83vzRC3B9EQVjz8NDULhn7ywcX16TD8FsVFUAEE7pump"}}}, Block: {Time: {since: $time_1hr}}} limitBy: {by: Trade_Side_Currency_MintAddress, count: 1} ) { volume: sum(of: Trade_Side_AmountInUSD) trades: count joinBalanceUpdates( BalanceUpdate_Currency_MintAddress: Trade_Currency_MintAddress orderBy: {descending: Block_Time} ) { BalanceUpdate { PostBalanceInUSD PostBalance Currency { Name MintAddress Symbol } } } } } } ``` #### How this works - The query finds all the trades for the particular token after a given timestamp. - Then the query perform aggregates functions like `sum` and `count` to get `volume` and `trades` of a token after a given time. - Then it checks for the latest `BalanceUpdates` for the token. :::warning `joinBalanceUpdates` does not give you supply or market cap `BalanceUpdates` records a balance change for **one account**, so the joined `PostBalance` is whatever account happened to update most recently, not the token's total supply. `PostBalanceInUSD` is that account's holding value, not market cap. Checked against BONK: this join returns a `PostBalance` of a few million tokens worth tens of dollars, while the token's actual supply is ~88 trillion at a market cap in the hundreds of millions. The two are unrelated numbers. The join happens to approximate supply only for a token whose balance updates are dominated by a single supply-holding account, such as a launchpad bonding curve early in its life. Do not rely on it in general. **For supply and market cap, query `TokenSupplyUpdates` directly** rather than joining it. A `joinTokenSupplyUpdates` on this query returns empty fields, because the join finds no match in the same window (see [why a join returns empty fields](#7-why-a-join-returns-empty-fields)): ```graphql query TokenSupplyAndMarketCap { Solana { TokenSupplyUpdates( where: { TokenSupplyUpdate: { Currency: { MintAddress: { is: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } } } } orderBy: { descending: Block_Time } limit: { count: 1 } ) { TokenSupplyUpdate { PostBalance PostBalanceInUSD Currency { Symbol Name } } } } } ``` Here `PostBalance` is the circulating supply and `PostBalanceInUSD` is the market cap. ::: #### Example 3: Get latest price and liquidity of a token in token pair [This](https://ide.bitquery.io/get-latest-price-and-liquidity-of-a-token-in-token-pair) query is a good example of how joins could be used to get latest price and liquidity of a token in particular token pair. ```graphql query PoolLiquidityAndPrice { EVM(dataset: combined, network: eth) { Balances( where: { Balance: { Address: { is: "0x1bCd6B0E97B51D76FD1752111a1fe2b473F655eE" } } Currency: { SmartContract: { is: "0x6b175474e89094c44da98b954eedeac495271d0f" } } } limit: { count: 1 } ) { Balance { Amount } Currency { Symbol } joinDEXTradeByTokens( Trade_Currency_SmartContract: Currency_SmartContract limit: { count: 1 } ) { Trade { PriceInUSD } } } } } ``` #### How this works - `Balances` returns the pool address's current holding of the token directly. There is no summing step, because `Balances` is backed by an aggregate-state table rather than a log of changes. - The join then pulls a `DEXTradeByTokens` row for the same token to attach a USD price. :::caution Do not use this join to read a price `Balances` is daily-grained: it exposes `Block.Date` but not `Block.Time`, so `orderBy: { descending: Block_Time }` on the joined `DEXTradeByTokens` is rejected. With no time ordering available, the joined row is an **arbitrary** match — successive runs of this query return different values, including `PriceInUSD: 0`. The join is shown here because it demonstrates matching on `Currency_SmartContract` across cubes. For an actual price, query `DEXTradeByTokens` directly with an explicit `orderBy: { descending: Block_Time }` and combine the two results client-side. ::: --- ## GraphQL Metric Aliases URL: https://docs.bitquery.io/docs/graphql/metrics/alias/ Alias Bitquery GraphQL metrics to name aggregates, sort results cleanly, and return clearer API field names for apps. See examples in the Bitquery IDE. # Aliases Aliases is a part of the GraphQL [standard](https://spec.graphql.org/draft/#sec-Field-Alias) They become useful when you have the need to have two fields in the query **with the same name**. Most probable you will come to the following problem with metrics: ``` count(distinct: Block_GasUsed) count(distinct: Block_Date) ``` This query is not valid for GraphQL and will not execute. Use aliases to make the query valid and also more readable: ``` uniqueGasValues: count(distinct: Block_GasUsed) uniqueDates: count(distinct: Block_Date) ``` :::tip Aliases can also be used in [sorting](/docs/graphql/sorting) ::: --- ## GraphQL Metrics Overview URL: https://docs.bitquery.io/docs/graphql/metrics/metrics/ Metrics in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Built for traders and analytics teams. # Using Metrics Use metrics if you want to: * calculate some statistics over the results * aggregate the results in a smaller set Adding metrics make the query aggregate query, and it will return results, grouped by dimensions. Look [Query Aggregated Metrics](/docs/graphql/capabilities/aggregated_metrics/) for details. :::tip Consider using metrics in every query to the [archive database](/docs/graphql/dataset/archive/) ::: :::note Metrics can be also used in subscriptions, refer to [Subscription on Aggregated Metrics](/docs/graphql/capabilities/subscription_aggregates/) for details. ::: --- ## GraphQL Network Selection URL: https://docs.bitquery.io/docs/graphql/dataset/network/ Select the blockchain network in Bitquery GraphQL queries using the network attribute, with clear multi-chain examples. See examples in the Bitquery IDE. # Network Network attribute is a selection of the blockchain: * ```eth``` for Ethereum Mainnet * ```bsc``` for Binance Smart Chain * other blockchains are in progress to add to dataset If the attribute is missing, the default blockchain ```eth``` is used. In the resulting data, blockchain is identified by ChainId dimension of the query. There is a mapping of ChainId to the network as shown below: ``` eth: 1 bsc: 56 bsc_testnet: 97 goerli: 5 rinkeby: 4 ropsten: 3 sepolia: 11155111 classic: 61 mordor: 63 kotti: 6 astor: 212 polygon: 137 arbitrum: 42161 avalanche: 43114 optimism: 10 fantom: 250 cronos: 25 klaytn: 8217 fusion: 32659 huobi: 128 moonbeam: 1284 celo: 42220 canto: 7700 aurora: 1313161554 ``` --- ## GraphQL Price Asymmetry Metric URL: https://docs.bitquery.io/docs/graphql/metrics/priceAsymmetry/ Price Asymmetry in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Keep queries fast with indexed filters. # Price Asymmetry In this section, we will see how to use the `PriceAsymmetry` metric to filter results based on Price. ## Formula The Price Asymmetry is calculated using the following formula: ``` PriceAsymmetry = abs(BuyPrice - SellPrice) / (BuyPrice + SellPrice) ``` Where: - `BuyPrice` and `SellPrice` are the USD prices from both sides of a trade (what the wallet buys, the pool sells, and vice-versa) - The formula only calculates when USD prices are available for both tokens - If USD prices are not available for both tokens, the value returns `0` ## How to use PriceAsymmetry to filter anomalies and outliers in Trades ? The PriceAsymmetry metric is being used to filter outliers of anomalies. This means that trades that have a price asymmetry for example 0.1 will be excluded from the results. This helps to ensure that the results are more accurate and reliable, as it removes any trades that may have been caused by anomalies. The price Asymmetry value can only lie between 0 and 1. PriceAsymmetry measures how close the trade’s prices are to each other. If the price asymmetry is less than 0.01, then the difference between the prices is less than 1%. However, the value of 0.01 might be too small and could omit a lot of trades. To improve your anomaly filtering mechanism, , add another filter like `Trade_PriceInUSD: {gt: 100}` filter to only include trades with a trade amount of more than 100 USD. This metric operates consistently across various datasets, including archive, subscriptions and mempool. For live data streams or mempool transactions, the latest available prices from both sides of the trade are used as benchmarks. Use the PriceAsymmetry metric to filter the response. By comparing two values derived from market data, it effectively identifies and exclude trades outside the specified range. > Note: : If we do not know exchange prices for BOTH tokens of a trade pair we can not calculate priceAsymmetry, we set it to 0. Here's an example [query on ethereum trades](https://ide.bitquery.io/Price-based-on-DEX-trades-in-USD). ```graphql subscription { EVM { DEXTradeByTokens( where: { Trade: { Currency: { Symbol: { is: "WETH" } } PriceAsymmetry: { le: 0.1 } } } ) { Block { Time } median(of: Trade_PriceInUSD) } } } ``` Similarly, below is an example on solana trades. ```graphql subscription { Solana { DEXTradeByTokens( where: {Trade: {Currency: {MintAddress: {is: "So11111111111111111111111111111111111111112"}}, Side: {Currency: {MintAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}}}, PriceAsymmetry: {lt: 0.9}}} ) { Block { Time } Trade { Price } } } } ``` --- ## GraphQL Quantile Metric URL: https://docs.bitquery.io/docs/graphql/metrics/quantile/ Quantile in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. Scale further with Kafka 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 10 chains in one stream, has USD price, market cap, and supply on every row, is MEV/outlier-filtered, and ships pre-aggregated OHLC down to 1-second candles — so you stream far fewer rows for the same signal. See the [Trading Data Overview](/docs/trading/trading-data-overview/) for when to use which. ::: When creating queries for GraphQL subscriptions, here are some tips to consider: 1. **Avoid Limiting Results:** In most cases, you should avoid limiting the results of your subscription query. This is because subscriptions are meant to stream data in real-time and limiting the results could cause you to miss out on new data. 2. **Ordering Might Not Be Necessary:** Given that subscriptions are meant to provide real-time data, ordering might not be necessary or even meaningful since data is sent as it becomes available. 3. **Test Your Queries:** Before deploying your application, make sure to thoroughly test your subscription queries to ensure they return the data you expect and can handle high volumes of data. 4. **Modifying Subscriptions Does Not Work**: If you try to modify a running subscription, it will end the subscription. In addition, optimizing your queries can significantly enhance the performance of your subscriptions. For more insights on how to optimize your websocket queries, go [here](/docs/graphql/optimizing-graphql-queries/). Subscriptions are also priced using our point-based system. Read about it [here](/docs/ide/points/) ## Default Parameters (GraphQL v2) GraphQL v2 applies the following default to subscriptions. You can override it by specifying a different value explicitly in your GraphQL filters. | Parameter | Default value | |-----------|---------------| | **Subscription `limit`** | 800 (per message) | Each subscription message returns at most 800 items by default. Override this by specifying a different `limit` in your subscription filters if you need a different batch size. For **default success and other filters** (e.g. only successful transactions, calls, events, transfers, DEX trades; Trade API defaults), see [Default filters (GraphQL v2)](/docs/graphql/query/#default-filters-graphql-v2) in Query Principles. For default limits on **queries**, see [Limits](/docs/graphql/limits/). ## Creating Multiple Subscriptions in one Websocket It is possible—and often more efficient—to manage multiple subscriptions over a single WebSocket connection. This approach allows you to bundle various subscriptions, such as DEX Trades, Transactions, Blocks, and Transfers, into a single Websocket stream. However, it's important to note that your top-level element must be only one. ```graphql subscription{ EVM{ Transfers{ } Transactions{ } } } ``` ### Example: Tracking USDT Transfers on Ethereum In this graphQL stream, we see how to run multiple streams with a single WebSocket. This query will return two sets of transfer data for USDT on the Ethereum network: `transfers_above_10K` and `transfers_below_10K`. The `transfers_above_10K` data set includes all transfers with an amount greater than or equal to 10,000 USDT. The `transfers_below_10K` data set includes all transfers with an amount less than 10,000 USDT. Both data sets include the transaction hash, sender, receiver, and amount of each transfer. You can run the query [here](https://ide.bitquery.io/USDT-transfers-of-different-amounts-mempool) ```graphql subscription ($token: String!, $minamount: String!, $mempool: Boolean, $network: evm_network!) { usdt: EVM(network: $network, mempool: $mempool) { transfers_above_10K: Transfers( where: {Transfer: {Amount: {ge: $minamount}, Currency: {SmartContract: {is: $token}}}} ) { Transaction { Hash From Gas } Receipt { GasUsed } Transfer { Sender Receiver Amount } } transfers_below_10K: Transfers( where: {Transfer: {Amount: {lt: $minamount}, Currency: {SmartContract: {is: $token}}}} ) { Transaction { Hash From Gas } Receipt { GasUsed } Transfer { Sender Receiver Amount } } } } { "token": "0xdac17f958d2ee523a2206206994597c13d831ec7", "minamount": "10000", "mempool": true, "network": "eth" } ``` --- ## GraphQL Sum Metric URL: https://docs.bitquery.io/docs/graphql/metrics/sum/ Sum trade amounts and transfer volumes in Bitquery GraphQL aggregates to power clear blockchain analytics dashboards. See examples in the Bitquery IDE. # Sum ```sum``` element in the query returns the sum of elements **in each set of dimensions**. Example: ```graphql { EVM (dataset: archive){ MinerRewards { Block { Date } sum(of: Reward_Total) miners: count(distinct: Block_Coinbase) } } } ``` ```sum(of: Reward_Total)``` returns the sum of total rewards over every date. --- ## GraphQL Uniq Metric URL: https://docs.bitquery.io/docs/graphql/metrics/uniq/ Count unique addresses, tokens, or traders with Bitquery’s uniq metric inside GraphQL aggregate blockchain queries. Keep queries fast with indexed filters. # Uniq The `uniq` function is used to estimate the count of unique values in a dataset. It's particularly useful for analyzing large datasets where an exact count may not be necessary or where performance is a concern. Below is an example query using the `uniq` function with the EVM Holders API to get the number of unique token holders for a specific token on a given date. ### Example Query ```graphql { EVM(dataset: archive, network: eth) { Holders( date: "2024-03-04" where: { Currency: { SmartContract: { is: "0x95AD61B0A150D79219DCF64E1E6CC01F0B64C4CE" } }, Balance: {Amount: {gt: "0"}}} ) { exact: uniq(of: Holder_Address, method: exact) count(distinct: Holder_Address) approximate: uniq(of: Holder_Address, method: approximate) } } } ``` ### Result ```json { "EVM": { "Holders": [ { "approximate": "1373089", "count": "1378364", "exact": "1378364" } ] } } ``` ### Understanding Uniq Function Variants - **Estimate (`uniq`)**: The `uniq` function estimates the count of unique values. It uses an adaptive sampling algorithm. This approach is highly accurate and CPU-efficient for processing large datasets. - **Exact Count (`uniqExact`)**: For scenarios requiring precision, the `uniqExact` function calculates the exact number of unique values. Although more memory-intensive it guarantees accuracy. ### When to Use Each Variant - **Use `uniq` for Estimates**: Opt for the `uniq` function when an approximate count suffices. This function is ideal for large datasets where performance and efficiency are priorities. - **Use `uniqExact` for Precision**: Choose the `uniqExact` function when accuracy is non-negotiable. Keep in mind the potential for increased memory usage. --- ## 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 | $29/mo | 100K | 30 / min | — | | Pro | $99/mo | $69/mo | 1M | 90 / min | 100 | | Scale | $299/mo | $199/mo | 5M | 240 / min | 1,000 | | Enterprise | Custom | Custom | Custom | Custom | Unlimited | Annual billing saves 30% or more and locks the price for 12 months. **Self-service plans are real-time only** — no plan includes archive history. Archive access is bought per chain as an add-on; see [Upgrade to Paid Plan](/docs/ide/paid/#historical-data-add-ons). 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 **$35 per 1M points** (annual). - **After upgrading, regenerate your access token if you still see the old limit.** A token minted under the previous plan can keep returning `points limit exceeded` until you generate a fresh one. Check your live usage at [Account → Usage](https://account.bitquery.io/user/stats/queries) and via the [Usage API](/docs/authorization/usage-api/). ## Per-chain entitlements Plans grant access to a specific set of chains. **Querying a chain that isn't in your plan fails** — and the error can look like a data problem rather than a billing one. If a query works in the IDE but fails from your app (or vice-versa), confirm the chain is included in your plan. ## Trials The free trial runs for **7 days** and includes **1,000 API points, 100 MCP credits, 2 simultaneous streams, 17 stream-minutes, and 0.2 GB of stream data**, on **real-time data only**. Queries on the `archive` and `combined` datasets are not part of the trial. No card required. Want to look at historical data before you buy? Every dataset in the [Bitquery Data Store](https://bitquery.io/datastore/datasets?utm_source=docs&utm_medium=referral&utm_campaign=datastore&utm_content=billing-trial) has a free sample file. ## Paying by crypto Card payment is available on all plans; **crypto payment is available on annual plans**. For invoices, only pay against an invoice issued from `bitquery.io` — beware of impersonation. ## Next steps - [IDE Points (how points are calculated)](/docs/ide/points/) - [Upgrade to a paid plan](/docs/ide/paid/) - [Rate Limits & Concurrency](/docs/plans/rate-limits/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) --- ## How to 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 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. --- ## Hyperliquid Historical Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/hyperliquid/ The last 30 days of Hyperliquid (HyperCore) as Parquet: trades from both sides, liquidations, L4 order book updates, the full order lifecycle, oracle prices and hourly funding. # 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 state. It is an **event stream, not a state chain**: there are no blocks, transactions or transfers tables. Every row is an exchange event (a fill, an order status change, a book delta, an oracle price, a funding payment), and every row carries `Block_Number` and `Block_Time`, so tables join on block without a separate blocks table. ## Coverage & Freshness - **History**: a rolling window of the **last 30 days**, across all seven tables. Older blocks are trimmed by whole UTC day. - **Same window as the API**: the [Hyperliquid GraphQL API and streams](/docs/perpetuals/hyperliquid/) also keep the last 30 days. The difference is shape and delivery, not depth. - **Freshness**: the archive is written from the same pipeline as our live streams, so the cloud export can follow new blocks as they are produced. A Data Store purchase is a one-time set of files covering the 30 days up to the day before we prepare them. - **Markets**: plain perpetuals, HIP-3 builder-deployed perps, spot pairs, and outcome/prediction tokens. See [Markets](#markets) for how they share one column. ## How Much History Is Included? The last **30 days**, on every table. The window rolls forward each UTC day, so at any moment you can replay roughly a month of live HyperCore, including any HIP-3 market that launched inside that window. Blocks older than 30 days are not in the dataset. The `Hyperliquid` cube on the streaming API has the same 30-day window, and a query for anything earlier returns an empty result. If you need to keep more than 30 days, land the Parquet files in your own bucket as they arrive and they stay there for as long as you want. ## How Is This Different From Hyperliquid's Free S3 Archive? Hyperliquid's own archive (and free mirrors of it) publishes **L2 snapshots and asset contexts**. This dataset is a different shape: | | Free archives (HL S3, Reservoir) | Bitquery cloud dataset | | ------------- | ------------------------------------------- | ------------------------------------------------------------------------------- | | Order book | L2 snapshots (price levels, fixed cadence) | **L4 per-order updates** with owner address and order id, every change | | Orders | Not included | **Full lifecycle**: opens, cancels, every reject reason, TP/SL children | | Fills | Not included | Both sides of every match, realized PnL, fees, builder and deployer fees | | Liquidations | Not included | Both sides, with the liquidated account, mark price and method | | Funding | Not included | Every account's payment at each hourly settlement | | Oracle | Not included | Mark, oracle and external perp prices per coin, plus the inputs behind them | | History | Varies by bucket, no completeness guarantee | Rolling last 30 days (keep your own copies to build a longer archive) | | Freshness | Roughly monthly uploads | Follows the chain | Queue position, order lifetime, maker behaviour, spoofing patterns, and _why_ a liquidation fired are only recoverable from this shape of data. ## Hyperliquid Data for Tax Reporting Tax reports need every trading event a wallet produced. The dataset carries the last 30 days of fills, liquidations, TWAP fills and funding, so you, your accountant or your tax software can compute gains, losses and income for any wallet inside that window. To cover a full tax year, keep the files as they land in your bucket and the archive builds itself. | Tax input | Bitquery table | | ------------------------------------------------------- | --------------------------------------------------------------------------- | | Realized PnL on every closed position | `trades` and `perp_liquidations`: `*_Position_RealizedPnl` | | Trading fees, including builder and HIP-3 deployer fees | `trades` and `perp_liquidations`: `*_Fees_Fee`, `_FeeToken`, `_BuilderFee`, `_DeployerFee` | | Funding paid and received | `perp_fundings`: `Funding_Amount` | | Liquidations | `perp_liquidations` | | TWAP executions, fill by fill | `trades` where `Trade_IsTwap = 1`, with `twaps` for the parent order | | Spot buys and sells for cost basis | `trades` where `Trade_Market_Kind = 'spot'` | Deposits, withdrawals and transfers between accounts are **not** in the export today. Why teams use it for tax work: - **Nothing dropped from trading.** Funding, TWAP child fills and liquidations are included alongside regular trades, so PnL reconciles. - **Exact amounts.** Prices, sizes, PnL and fees are stored as decimal strings, so no precision is lost to floating point. - **Works with your stack.** Delivered to S3, GCS, Snowflake or BigQuery. Query one wallet or thousands with SQL, then export to CSV for tax software. Built for tax platforms, accountants and funds reconciling Hyperliquid activity, as well as individual traders with high trade counts. To get the full dataset, [buy it from the Bitquery Data Store](https://bitquery.io/datastore/datasets?network=hyperliquid), [fill the API form](https://bitquery.io/forms/api) or email **sales@bitquery.io**. ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=hyperliquid), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Datasets you can buy on the Data Store, as one-time files covering the last 30 days: - [Hyperliquid](https://bitquery.io/datastore/datasets/hyperliquid): all seven tables - [Hyperliquid Trades](https://bitquery.io/datastore/datasets/hyperliquid-trades): `trades`, `perp_liquidations` and `twaps` - [Hyperliquid Order Book](https://bitquery.io/datastore/datasets/hyperliquid-order-book): `order_updates`, `book_updates` and `price_updates` - [Hyperliquid Funding](https://bitquery.io/datastore/datasets/hyperliquid-ledger): `perp_fundings` ## Available Hyperliquid Tables | Table | Grain | What it holds | | ------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `trades` | one row per side of each match, liquidations excepted | Price, size, direction, taker flag, fees, signed position before the fill, realized PnL, TWAP link | | `perp_liquidations` | one row per side of each liquidation match | The same fields as `trades`, plus the liquidated account, mark price and method | | `twaps` | one row per TWAP status change | Total size, executed size and notional, duration, status and error text | | `order_updates` | one row per order status change | Full lifecycle: `open`, `canceled`, `filled`, `triggered` and every `*Rejected` state, with TIF, triggers and TP/SL children | | `book_updates` | one row per L4 change of a single order | `new`, `update` or `remove`, each with the owning address, order id, price and size | | `price_updates` | one row per coin and price kind in each oracle push | Resulting mark, oracle and external perp prices, and the inputs behind them | | `perp_fundings` | one row per account and market at each hourly settlement | Funding rate, signed position size, USDC paid or received | Pick `trades` for executed volume and realized PnL, `order_updates` for intent and rejection analysis, and `book_updates` when you need to rebuild the book at an arbitrary block. ### Why L4 Matters An L2 snapshot tells you the book was 12 deep at a price; an L4 stream tells you _which_ order moved and _whose_ it was. Likewise, `order_updates` includes orders that **never traded**. Rejects and cancels are invisible in any trades-only dataset, and in the sample below they are most of the order events. ## Sample Hyperliquid Cloud Dataset You can explore schemas and validate your tooling using the **public Hyperliquid sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/hyperliquid](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/hyperliquid) **Sample Parquet downloads (public S3)** Every sample is written by the same exporter that produces a delivery, with every column. | Table | Rows | Source | Download | | --------------- | ---: | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `trades` | 100 | first rows of pack `1165214000`–`1165214999` | [1165214001_1165214024.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/trades/1165214001_1165214024.parquet) | | `twaps` | 7 | every TWAP status in the same pack | [1165214012_1165214910.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/twaps/1165214012_1165214910.parquet) | | `perp_fundings` | 100 | the settlement in block `1165214467` | [1165214467_1165214467.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/perp_fundings/1165214467_1165214467.parquet) | | `order_updates` | 100 | first rows from block `1078000000` | [1078000000_1078000000.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/order_updates/1078000000_1078000000.parquet) | | `book_updates` | 100 | first rows from block `1078000000` | [1078000000_1078000001.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/book_updates/1078000000_1078000001.parquet) | | `price_updates` | 100 | first rows from block `1078000000` | [1078000012_1078000012.parquet](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/price_updates/1078000012_1078000012.parquet) | `perp_liquidations` has no public sample; liquidations are rare, and its columns match `trades` plus `Liquidation_MarkPx`, `Liquidation_Method` and `Liquidation_LiquidatedUser`. The figures on this page come from the full export of two 1,000-block packs, not only the small samples: pack `1165214000`–`1165214999` (29 September 2026) held **11,082** trade rows, **7** TWAP statuses and one funding settlement of **411,880** rows across 327 markets, and pack `1078000000`–`1078000999` (19 July 2026) held **321,282** order updates, **193,903** book updates and **22,696** price updates. ## Hyperliquid Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── hyperliquid/ ├── trades/ ├── perp_liquidations/ ├── twaps/ ├── order_updates/ ├── book_updates/ ├── price_updates/ └── perp_fundings/ ├── _.parquet └── ... ``` Each file name gives the first and last block it holds. HyperCore produces roughly 14 blocks per second. File sizes track activity rather than block count, so size a download from the delivery manifest rather than from the block range. **A range with no events produces no file.** Sparse tables such as `twaps`, `perp_liquidations` and `perp_fundings` (one settlement an hour) skip ranges, so discover files under a prefix rather than generating names from a stride. ## Common Columns Every table starts with the same block columns and ends with the same bookkeeping columns: | Column | Type | Description | | ----------------------------------- | -------- | ------------------------------------------------------------- | | `ChainId` | `string` | Always `hyperliquid-core` | | `Block_Number` | `uint64` | HyperCore block height; the join key across tables | | `Block_Time` | `int64` | Block timestamp, **epoch nanoseconds** | | `Indexing_Time` | `int64` | When our pipeline indexed the block, epoch nanoseconds | | `Indexing_OnTree`, `Indexing_OnTrunk` | `uint8` | 1 when the block was on our block tree and finalized chain | | `Recording_Time` | `uint32` | When the row was written, epoch seconds | | `Recording_Hash` | `uint64` | Row hash used to drop duplicates | | `Block_Date` | `date` | UTC date of the block, handy for partitioning | Each table then prefixes its own fields with its entity name: `Trade_*`, `Liquidation_*`, `Twap_*`, `Order_*`, `BookUpdate_*`, `PriceUpdate_*`, `Funding_*`. Nested structures are flattened with `_`, for example `Trade_Execution_Price` and `Order_Market_CoinRaw`. The trading tables share these groups: | Group | Columns | | ------------ | ----------------------------------------------------------------------------- | | `_Trader_*` | `Address`, `Signer`, `Vault`, `Broadcaster`, `SignedAt` | | `_Market_*` | `Symbol`, `Kind`, `Protocol`, `CoinRaw`, `IsPerp`, `MaxLeverage` | | `_Position_*`| `Side`, `Size`, `SizeBefore`, `EntryPrice`, `RealizedPnl`, `Funding`, `Leverage`, `IsCross`, `Closed` | Some of these are never filled in a given table (for example `Trade_Position_EntryPrice` or `Trade_MarkPx`), and signer, vault and leverage fields are filled only when the source data carries them. The listing on the Data Store says, per column, when it can be empty. ## Correctness Notes Five things about this dataset will silently produce wrong numbers if you treat it like an EVM chain export. ### 1. Money Is Strings Prices, sizes, PnL, fees and funding amounts are stored as **decimal strings**, not numerics. This is deliberate: exchange decimals must not pass through a float. Block numbers, ids and timestamps are integers. Use `Decimal` rather than `float` for money: ```python from decimal import Decimal df["px"] = df.Trade_Execution_Price.map(Decimal) ``` Summing `Trade_Execution_Price` as float across a large export will drift; `Decimal` will not. ### 2. Every Match Appears Twice `trades` carries **one row per side**, so a single match produces two rows, one taker and one maker. In the 29 September pack, 11,082 trade rows are 5,548 with `Trade_Execution_IsAggressor = 1` and 5,534 with `0`, resolving to 5,555 unique `(Block_Number, Trade_Market_CoinRaw, Trade_Execution_Tid)` keys. Summing `Trade_Execution_Size` across the raw table **double-counts volume**. Filter to one side: ```sql SELECT SUM(CAST(Trade_Execution_Size AS DECIMAL(38,8))) FROM hyperliquid_trades WHERE Trade_Execution_IsAggressor = 1 -- taker side only ``` Liquidation fills are **not** in `trades`; they are only in `perp_liquidations`. Include both tables for complete volume and PnL. ### 3. `Trade_Execution_Hash` Is Not a Join Key One L1 transaction spans many matches, and TWAP fills carry 32 zero bytes. In the same pack, 11,082 rows share only 2,938 distinct hashes, and 1,296 rows (the TWAP fills, `Trade_IsTwap = 1`) have an all-zero hash. Key matches on **`(Block_Number, Trade_Market_CoinRaw, Trade_Execution_Tid)`** instead. ### 4. Rejected Orders Dominate `order_updates` `order_updates` is a record of _intent_, and most intent never trades. The 19 July pack's 321,282 order events break down as: | Status | Records | | --------------------------------- | ------: | | `badAloPxRejected` | 108,952 | | `open` | 95,735 | | `canceled` | 91,148 | | `perpMarginRejected` | 15,373 | | `reduceOnlyCanceled` | 3,875 | | `iocCancelRejected` | 3,505 | | `insufficientSpotBalanceRejected` | 1,299 | | `filled` | 1,118 | | `minTradeNtlRejected` | 121 | | `reduceOnlyRejected` | 101 | | `selfTradeCanceled` | 48 | | `tooManyOpenOrdersRejected` | 6 | | `triggered` | 1 | Only **1,118 of 321,282** events, about 0.35%, are `filled`. `badAloPxRejected` alone is a third of the file: post-only (`Alo`) orders priced through the book, rejected rather than crossed. `Alo` is 313,186 of the 321,282 `Order_Tif` values, so this table is dominated by market makers quoting and requoting. `Order_IsReject = 1` flags every `*Rejected` state. Filter on `Order_Status` for whatever you are measuring; never treat row count as order flow. ### 5. Time Units Differ by Field Two different epochs are in play, and mixing them is a factor-of-a-million error: | Field | Unit | | ------------------------------------------------------------- | ------------ | | `Block_Time`, `Order_EventTime`, `Twap_Interval_EventTime` | nanoseconds | | `Trade_Execution_EventTime`, `Liquidation_Execution_EventTime` | milliseconds | | `Order_PlacedTime`, `Twap_Interval_StartTime` | milliseconds | | `Recording_Time` | seconds | In the sample, the same fill carries `Block_Time = 1790672366376122193` and `Trade_Execution_EventTime = 1790672366376`. ## Markets `*_Market_CoinRaw` covers four market types in one column, and `*_Market_Kind` names the type so you do not have to parse the prefix: | `CoinRaw` | `Kind` | Meaning | Trade rows (29 Sep pack) | Order events (19 Jul pack) | | ------------- | --------- | --------------------------- | -----------------------: | -------------------------: | | `HYPE`, `BTC` | `perp` | Plain perpetual | 6,406 | 258,980 | | `xyz:DRAM` | `hip3` | HIP-3 builder-deployed perp | 4,044 | 50,963 | | `@107` | `spot` | Spot pair, by index | 524 | 10,603 | | `#1890` | `outcome` | Outcome / prediction token | 108 | 736 | `*_Market_Protocol` is `hypercore` for plain perps, spot and outcome tokens, and the deploying dex (such as `xyz`) for HIP-3 markets. HIP-3 perps were 36% of trade rows in the 29 September pack, so leaving them in a "Hyperliquid perps" aggregate will not give you the numbers you expect. ## Table Notes The full column list for every table, with a description of each column, is on the [Data Store listings](https://bitquery.io/datastore/datasets?network=hyperliquid). The points below are the ones that matter when you query. ### trades - `Trade_Execution_Side` is `Buy` or `Sell` for this side; `Trade_Execution_Direction` is the node's label: `Open Long`, `Close Short`, `Long > Short`, `Buy`, `Sell` and so on. - `Trade_Position_SizeBefore` is the **signed position before the fill** (negative is short), not money. `Trade_Position_RealizedPnl` is the realized PnL of the fill in USDC. It was non-zero on 5,277 of the 11,082 rows in the 29 September pack. - `Trade_Fees_Fee` is negative when the maker received a rebate. `Trade_Fees_FeeToken` was `USDC` on 10,743 of those rows. - `Trade_TwapId` joins to `Twap_TwapId`. ### perp_liquidations - Each liquidation match has two rows, one for the liquidated account and one for the counterparty. `Liquidation_LiquidatedUser` names the liquidated account on both. - `Liquidation_MarkPx` and `Liquidation_Method` (for example `market`) come from the node. `Liquidation_Liquidator` is always empty. ### twaps - `Twap_State_Status` is `activated`, `finished`, `terminated` or `error`, with the error text in `Twap_State_StatusError`. - `Twap_Order_Size` is the total to execute; `Twap_State_ExecutedSize` and `Twap_State_ExecutedNotional` are the running totals. ### order_updates - `Order_Oid` joins to `Trade_Execution_Oid` and `BookUpdate_Oid`. - `Order_ParentOid` and `Order_Leg` link take-profit and stop orders to the order they are attached to. ### book_updates - `BookUpdate_Kind` is `new` (95,060 rows in the 19 July pack), `remove` (95,456) or `update` (3,387). - `BookUpdate_Size` is the order's size on `new` and the size after the change on `update`; `BookUpdate_SizeBefore` is the size before an `update`. - Replay in `Block_Number` then `BookUpdate_Index` order to reconstruct the book at any block. ### price_updates - `PriceUpdate_Kind` says which price the row is: `mark`, `oracle` or `extPerp` for the resulting prices, `markInput`, `spotInput` or `extPerpInput` for the inputs. - Oracle prices drive funding and liquidation, so join these to `perp_liquidations` on `Block_Number` when reconstructing why a liquidation fired. ### perp_fundings - `Funding_Amount` is the USDC the account received, negative when it paid. `Funding_Size` is the signed position, negative for a short. With a positive `Funding_Rate`, longs pay shorts. ## Joining Tables Every table carries `Block_Number`, and the order id threads the trading tables together: ```sql -- taker fills with the order that produced them SELECT t.Trade_Market_CoinRaw, t.Trade_Execution_Price, t.Trade_Execution_Size, t.Trade_Position_RealizedPnl, o.Order_Tif, o.Order_ReduceOnly FROM hyperliquid_trades t JOIN hyperliquid_order_updates o ON t.Trade_Execution_Oid = o.Order_Oid AND o.Order_Status = 'filled' WHERE t.Trade_Execution_IsAggressor = 1 ``` Because one order produces many status events and many fills, join on the order id plus a status filter, or aggregate one side first; otherwise you get a cross product. ## Reading Files with DuckDB No key, no client library. Point DuckDB at the public sample directly: ```sql SELECT Trade_Market_CoinRaw, SUM(CAST(Trade_Execution_Size AS DECIMAL(38,8)) * CAST(Trade_Execution_Price AS DECIMAL(38,8))) AS notional FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/trades/1165214001_1165214024.parquet') WHERE Trade_Execution_IsAggressor = 1 -- taker side only, see Correctness Notes GROUP BY Trade_Market_CoinRaw ORDER BY notional DESC LIMIT 10; ``` ## Reading Files in Python ```python from decimal import Decimal BASE = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/hyperliquid/" trades = pd.read_parquet(f"{BASE}trades/1165214001_1165214024.parquet") orders = pd.read_parquet(f"{BASE}order_updates/1078000000_1078000000.parquet") # taker side only: every match is in the file twice taker = trades[trades.Trade_Execution_IsAggressor == 1] taker = taker.assign( px=taker.Trade_Execution_Price.map(Decimal), sz=taker.Trade_Execution_Size.map(Decimal), ) print("matches:", len(taker), "of", len(trades), "trade rows") print("notional:", (taker.px * taker.sz).sum()) # realized PnL net of fees, by wallet net = trades.assign( pnl=trades.Trade_Position_RealizedPnl.map(Decimal) - trades.Trade_Fees_Fee.map(Decimal) ).groupby("Trade_Trader_Address").pnl.sum() print(net.sort_values().tail()) # order flow is mostly rejects, not trades print(orders.Order_Status.value_counts().head()) ``` ## Real-Time vs Batch Data Access 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 code. ## Buy the Full Dataset The public samples above are a few hundred rows. The full product is the rolling 30-day history, delivered into your own S3/GCS bucket or as a Snowflake/BigQuery share. A Data Store purchase is a one-time set of files covering the last 30 days. - [Buy it from the Bitquery Data Store](https://bitquery.io/datastore/datasets?network=hyperliquid), or - [Fill the request form](https://bitquery.io/forms/api), or - Email **sales@bitquery.io** --- ## Hyperliquid MCP Server for Claude, ChatGPT and Cursor URL: https://docs.bitquery.io/docs/mcp/hyperliquid/ Ask Claude, ChatGPT or Cursor about Hyperliquid in plain English: top markets, funding, open interest, liquidations, the best wallets and what they hold. Read-only, from on-chain data. # Hyperliquid MCP Server The Bitquery MCP server gives an AI client 18 tools for Hyperliquid data. You ask a question in Claude, ChatGPT, Cursor, VS Code or Codex, the agent picks a tool, and rows come back from Bitquery's index of the exchange's own blocks: perpetuals, spot pairs, markets listed by third parties, and outcome markets. It reads data only. It cannot place, change or cancel an order, and it never touches a key. To trade, use Hyperliquid's own API; to research markets and wallets, use this. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Other clients take the same URL. Steps for each are in the [MCP server install guide](/docs/mcp/mcp-server/). A 38-second demo, [Polymarket and Hyperliquid data in ChatGPT and Claude](https://www.youtube.com/watch?v=IwuIlcKsANk), shows the server answering questions like the ones below. Every figure on this page came from a call to the production server on 21 September 2026, between 10:21 and 10:25 UTC, on a morning when Bitcoin had risen 5.4% in a day. Your numbers will differ. ## What can I ask? ### What is trading most on Hyperliquid? > *"What are the five most traded Hyperliquid markets in the last 24 hours?"* The agent calls `hyperliquid_markets`. | Market | Last price | 24h change | 24h volume | Wallets | |---|---:|---:|---:|---:| | BTC | 84,666 | +5.39% | $2,872,395,664 | 22,251 | | ETH | 2,719.7 | +5.66% | $1,776,080,523 | 10,550 | | ZEC | 1,517.4 | +5.46% | $600,636,368 | 7,799 | | HYPE | 95.244 | +4.96% | $430,607,975 | 7,935 | | NEAR | 4.2931 | +21.45% | $356,057,954 | 7,430 | BTC alone had 375,429 trades. Volume counts each fill once. The `Market` column is the id that every other tool takes, which matters because a ticker is not unique: BTC exists as the native perpetual and again on third-party venues. ### Where are the big positions, and who is paying for them? > *"Show open interest, the long and short split, and funding for the biggest Hyperliquid perpetuals."* `hyperliquid_open_interest`, from the 10:00 UTC hourly settlement: | Market | Open interest | Long | Short | Funding per year | |---|---:|---:|---:|---:| | BTC | $1,865,713,119 | 21,904 | 11,693 | 78.64% | | ETH | $1,540,615,295 | 13,476 | 5,128 | 18.81% | | HYPE | $1,042,186,424 | 13,035 | 4,566 | 42.40% | | ZEC | $398,747,943 | 6,733 | 3,395 | 10.95% | | SOL | $351,305,718 | 9,886 | 2,885 | 10.95% | Long and Short are counts of accounts. On a perpetual the size held long always equals the size held short, so the crowd shows up in the count of accounts. On BTC 65% of accounts were long, and they were paying shorts at a rate worth 78.64% per year, $167,486 in that one hour. Funding is paid every hour; the yearly figure is the hourly rate times 24 times 365. ### How did funding get there? > *"How has BTC funding moved over the last 24 hours?"* `hyperliquid_funding_rates` returns one row per hourly settlement. | Hour (UTC) | Funding per year | Accounts short | Paid in that hour | Price | |---|---:|---:|---:|---:| | 20 Sep, 11:00 | 10.95% | 14,990 | $20,212 | 80,314 | | 21 Sep, 08:00 | 10.95% | 14,486 | $22,221 | 81,706 | | 21 Sep, 09:00 | 24.91% | 12,137 | $52,981 | 83,768 | | 21 Sep, 10:00 | 78.64% | 11,693 | $167,486 | 84,651 | For the first 22 hours of that window the rate sat at the same 10.95%. Then the price moved $2,945 in two hours, the count of short accounts fell by 2,793, and the hourly bill for longs went up more than seven times. ### Who was liquidated? > *"Which Hyperliquid markets had the most value liquidated in the last 24 hours, and on which side?"* `hyperliquid_liquidations`, grouped by market: | Market | Liquidations | Longs | Shorts | Value | |---|---:|---:|---:|---:| | BTC | 9,334 | 69 | 9,265 | $92,691,944 | | ETH | 2,234 | 24 | 2,210 | $25,332,321 | | NEAR | 1,299 | 103 | 1,196 | $2,863,062 | | xyz:CL | 316 | 212 | 104 | $2,403,537 | | XRP | 513 | 1 | 512 | $2,322,937 | The liquidation table tells the same story from the other side. On BTC 99.3% of forced closes were shorts. None of the five markets needed the exchange's backstop, which is the tool's sign of real stress. Without the grouping, the same tool lists single liquidations, newest first. With a $100,000 floor, the newest rows were a run on a third-party market, `xyz:CL`: one account lost four long positions in three seconds at 10:17 UTC, worth $802,815 together. ### Who made the most on BTC? > *"Who made the most money trading BTC on Hyperliquid in the last 24 hours?"* `hyperliquid_top_traders` with the market set to BTC: | Account | Net result | Volume | Fills | Share as taker | |---|---:|---:|---:|---:| | `0xb1ec7feb...e86a` | $857,387 | $11,676,991 | 385 | 49.9% | | `0xe77cdee1...15db` | $819,890 | $38,134,857 | 1,066 | 10.6% | | `0x4044570e...794c` | $361,813 | $5,814,128 | 266 | 10.2% | | `0xe60dcdf2...7738` | $296,546 | $9,082,225 | 216 | 100% | | `0xb5a6924d...2f82` | $258,300 | $24,013,654 | 1,292 | 100% | Net result is closed profit plus funding minus fees. It leaves out open positions, so a wallet can rank high here and be deep under water on a trade it has not closed. Check the next tool before calling anyone a winner. ### What is the top wallet holding now? > *"What positions does 0xb1ec7febea4f841d525785955b7fe0e812d6e86a hold?"* `hyperliquid_trader_positions`, positions above $1 million: | Market | Side | Exposure | Position vs margin | |---|---|---:|---:| | BTC | Long 47.23 BTC | $3,998,475 | 40x | | HYPE | Long 21,298 HYPE | $2,023,857 | 10x | | xyz:SPCX | Short 12,887 | $1,990,058 | not observed | | LINK | Long 104,855 LINK | $1,357,129 | 10x | The day's best BTC account is still long $4.0 million of BTC, a position 40 times its margin. The tool returned no entry price or open profit for these rows, and said why: every position was opened before the month of history it can rebuild from, so it reports the size as exact and leaves the rest empty. ## All 18 Hyperliquid tools | Tool | Use it for | |---|---| | `hyperliquid_markets` | List and rank markets, and turn a ticker into a market id | | `hyperliquid_price` | Current price of one market, with the source it came from | | `hyperliquid_candles` | Price bars of 1, 5, 15 or 60 minutes for one market | | `hyperliquid_recent_trades` | The latest fills on a market | | `hyperliquid_open_interest` | Open interest, account split and current funding across perpetuals | | `hyperliquid_funding_rates` | Hourly funding and open interest history of one perpetual | | `hyperliquid_liquidations` | Forced closes, one by one or totalled per market or account | | `hyperliquid_twaps` | Large orders being worked in slices, and how far along they are | | `hyperliquid_top_traders` | Accounts ranked by net result, volume or fills | | `hyperliquid_trader_summary` | One account's scorecard: profit, funding, fees, win rate | | `hyperliquid_trader_positions` | What an account holds now | | `hyperliquid_trader_fills` | An account's fill history with profit and fee per fill | | `hyperliquid_linked_accounts` | Accounts tied together by a shared signing wallet | | `hyperliquid_book_makers` | Which accounts post the resting orders on a market | | `hyperliquid_order_flow` | Orders placed, filled, cancelled and rejected, with the reason | | `hyperliquid_action_rejections` | Rejected account actions such as margin settings and transfers | | `hyperliquid_builders` | Volume and fees of the apps that route orders, and of third-party venues | | `hyperliquid_raw_sql` | Your own SQL over the Hyperliquid tables | ## What to know before you rely on it - **Read-only.** No order placement and no live order book depth. - **About a month of history.** Most tools look back up to 720 hours. Price bars reach back about three weeks. Order and book events are kept for two days. - **Rankings leave out open positions.** Read `hyperliquid_trader_positions` next to any profit ranking. - **Entry price can be empty.** A position opened before the history window has an exact size and no entry price or open profit. - **Funding and open interest are hourly.** They come from the hourly settlement, so they can be up to an hour old. - **Pin a market by its id.** Third-party markets carry a prefix such as `xyz:`, spot pairs start with `@` and outcome markets with `#`. - **No transfer tracing.** The general token, price and wallet-tracing tools do not cover Hyperliquid. It has its own set. ## MCP, GraphQL or the official API? | You want to | Use | |---|---| | Place or cancel orders, read the live book | Hyperliquid's own API | | Ask questions in a chat, or let an agent research markets and wallets | This MCP server | | Build a dashboard, alert or bot in code | The [Bitquery Hyperliquid API](/docs/perpetuals/hyperliquid/hyperliquid-perpetuals-api/), with WebSocket and Kafka streams | | Load the last 30 days into a warehouse | [Hyperliquid Parquet exports](/docs/cloud/hyperliquid/) | Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-hyperliquid#pricing). --- ## Indexed Fields Reference (where & orderBy) URL: https://docs.bitquery.io/docs/graphql/indexed-fields-reference/ Indexed Fields Reference (where & orderBy) in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # Indexed Fields Reference for `where` and `orderBy` Use **indexed fields** in your `where` filters and `orderBy` clauses. Filtering or sorting on non-indexed fields can lead to slow queries, timeouts. This page lists the fields that are indexed for each cube, dataset, and chain type. Prefer these fields when building `where` and `orderBy` conditions. :::tip Best practice In `where`, filter on at least one indexed field (Index 1, 2, 3, or 4 where applicable). In `orderBy`, sort by an indexed field when possible. ::: --- ## EVM (Archive) | Cube | Index 1 | Index 2 | Index 3 | Index 4 | | -------------------- | ---------------------------- | ---------------------- | ----------------- | ------------------------------- | | **Balances** | Balance_Address | Currency_SmartContract | — | — | | **Blocks** | Block_Hash | Block_Number | — | — | | **Calls** | Call_From | Call_To | Transaction_Hash | — | | **DEXTrades** | Transaction_Hash | — | — | — | | **DEXTradeByTokens** | Trade_Currency_SmartContract | Trade_Side_Seller | — | — | | **Events** | Call_To | Transaction_Hash | — | — | | **MinerRewards** | Block_Coinbase | Block_Number | Block_Hash | — | | **Holders** | Currency_SmartContract | — | — | — | | **Transactions** | Transaction_From | Transaction_Hash | Transaction_To | — | | **Transfers** | Transaction_Hash | Transfer_Sender | Transfer_Receiver | Transfer_Currency_SmartContract | --- ## Tron (Archive) | Cube | Index 1 | Index 2 | Index 3 | Index 4 | | -------------------- | ---------------------------- | ---------------------- | ----------------- | ------------------------------- | | **Balances** | Balance_Address | Currency_SmartContract | — | — | | **Blocks** | Block_Hash | Block_Number | — | — | | **Calls** | Call_From | Call_To | Transaction_Hash | — | | **DEXTrades** | Transaction_Hash | — | — | — | | **DEXTradeByTokens** | Trade_Currency_SmartContract | Trade_Side_Seller | — | — | | **Events** | Call_To | Transaction_Hash | — | — | | **Holders** | Currency_SmartContract | — | — | — | | **Transactions** | Transaction_Hash | — | — | — | | **Transfers** | Transaction_Hash | Transfer_Sender | Transfer_Receiver | Transfer_Currency_SmartContract | --- ## Solana ### Solana Realtime | Cube | Index 1 | Index 2 | Index 3 | | -------------------- | -------------------------- | --------------------------- | --------------------- | | **DEXPools** | Pool_Market_MarketAddress | — | — | | **DEXTradeByTokens** | Trade_Currency_MintAddress | — | — | | **Instructions** | Transaction_Signer | Instruction_Program_Address | — | | **Transfers** | Transfer_Receiver_Owner | Transfer_Sender_Owner | Transaction_Signature | ### Solana Archive | Cube | Index 1 | Index 2 | Index 3 | | -------------------- | -------------------------- | ------------------- | ------- | | **DEXTradeByTokens** | Trade_Currency_MintAddress | Trade_Account_Owner | — | --- ## Trading (Realtime) | Cube | Index 1 | Index 2 | Index 3 | Index 4 | Index 5 | | -------------- | ------------------ | --------------------- | --------------------- | ------------------ | ------------ | | **Currencies** | Currency_Id | Interval_Time_Start | — | — | — | | **Tokens** | Token_Id | Interval_Time_Start | Currency_Id | Token_Address | — | | **Pairs** | Token_Id | Currency_Id | Interval_Time_Start | Token_Address | Pool_Address | | **Trades** | Trader_Address | Pair_Token_Address | Pair_Pool_Address | — | — | --- ## How to use this reference 1. **Identify your cube** — e.g. `EVM.Transactions`, `Solana.Transfers`, `Trading.Tokens`. 2. **Check chain and dataset** — EVM Archive, Tron Archive, Solana Realtime/Archive, or Trading Realtime. 3. **Use indexed fields in `where`** — Prefer filters on the indexed columns (Index 1, 2, 3, 4). Example: for `EVM(dataset: archive).Transactions`, filter on `Transaction_From`, `Transaction_Hash`, or `Transaction_To`. 4. **Use indexed fields in `orderBy`** — Sort by one of the indexed fields (e.g. `Block_Number`, `Transaction_Hash`) for predictable, fast ordering. Using fields that are **not** in these tables for filtering or sorting may work in some cases but can cause poor performance or unexpected behavior. When in doubt, stick to the indexed fields listed above. --- ## Javascript Tutorial to Setup Solana Kafka Shred Stream URL: https://docs.bitquery.io/docs/streams/protobuf/kafka-protobuf-js/ Javascript Tutorial to Setup Solana Kafka Shred Stream with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. # Javascript Tutorial to Setup Solana Kafka Shred Stream This tutorial explains how to consume **Solana** protobuf messages from **Bitquery Kafka** using **JavaScript** (Node.js **CommonJS** — not a browser bundle), and print them with **`bytes`** fields decoded to **base58** where **`printProtobufMessage`** applies that encoding. **Streaming concepts:** **[Kafka streaming concepts — Protobuf streams](/docs/streams/kafka-streaming-concepts/#what-to-know-about-protobuf-streams)**. **Runnable project:** **[`bitquery/kafka-streams-examples-usecases`](https://github.com/bitquery/kafka-streams-examples-usecases)** — **[`js-consumer-example/`](https://github.com/bitquery/kafka-streams-examples-usecases/tree/main/js-consumer-example)** ([`src/index.js`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/src/index.js), [`src/config.js`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/src/config.js), [`package.json`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/package.json)). Use **[`bitquery-protobuf-schema npm Package`](https://www.npmjs.com/package/bitquery-protobuf-schema)** so you do **not** hand-manage `.proto` files—the package resolves the schema from **`KAFKA_TOPIC`**. > **Throughput:** Treat this repo as a **minimal** consumer. Saturating high-volume topics typically requires tuning **KafkaJS** parallelism, **partition-aware** runners, or **multiple consumers under one consumer group**. See **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)** for partition-oriented guidance. ## Prerequisites - **Node.js 18+** (`package.json` `engines`). - **npm** - Bitquery **Kafka username and password** for stream access. > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). Install all dependencies declared in **`package.json`**: ```bash npm install ``` Key runtime libraries: **`kafkajs`**, **`kafkajs-lz4@^1.2.1`** (+ **`lz4` / `lz4-asm`**), **`bitquery-protobuf-schema`**, **`dotenv`**, **`uuid`**, **`bs58`**. ## 1. Kafka client initialization (non-TLS baseline) The sample builds a **KafkaJS** client with **SASL SCRAM-SHA-512**, **no TLS** (**`ssl: false`**), and default Bitquery broker endpoints (overridable via **`KAFKA_BOOTSTRAP_SERVERS`**). Compression: **LZ4** codec registration matches Bitquery payloads. See the live **`createKafka`** helper in **`src/index.js`** and env loading in **`src/config.js`** on GitHub (**links above**). > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ## 2. Protobuf traversal and `bytes` (Solana vs EVM) Printing is implemented in **`src/printProtobuf.js`** and mirrors the **recursive traversal** pattern from earlier Bitquery tutorials: nested objects descend; **`bytes`** are encoded with **`bs58`** when the printer runs in **`base58`** mode (Solana-focused default in **`index.js`**). > **Solana vs EVM `bytes`** > > Protobuf **`bytes`** often encode addresses, hashes, or signatures—the display encoding depends on the chain: > > - **Solana:** **base58** (this tutorial’s default path). > - **EVM (Ethereum, BSC, Base, etc.):** **hex**, typically **`0x` + buffer.toString("hex")** when you customize the printer. > > Example pattern for hex (not used in the default Solana tree): > > ```js > const hex0x = (buffer) => "0x" + Buffer.from(buffer).toString("hex"); > ``` ## 3. Consumer group and subscribe Group id: - Prefer **stable** **`KAFKA_GROUP_ID`** beginning with **your Kafka username** (Bitquery requirement for stable ids). - If unset, **`index.js`** uses **`${username}-group-${uuid}`** (hyphens stripped from uuid), matching the spirit of the older tutorial’s dynamic suffix. Subscribe uses **`fromBeginning`** from **`KAFKA_FROM_BEGINNING`** (boolean-style env parsing in **`config.js`**). > **Reminder vs Python / Go** > > Node uses **`KAFKA_FROM_BEGINNING`**. Python and Go in the **same repository** use **`KAFKA_AUTO_OFFSET_RESET`** (**`latest` / `earliest`**). Align env vars when you compare languages side by side. ## 4. Run stream: load proto, decode, LZ4-ready pipeline [`src/index.js`](https://github.com/bitquery/kafka-streams-examples-usecases/blob/main/js-consumer-example/src/index.js): 1. **`await loadProto(cfg.topic)`** before consuming. 2. **`consumer.connect()`** → **`subscribe({ topic, fromBeginning })`**. 3. **`consumer.run({ autoCommit: false, eachMessage: ... })`**. 4. **`decode`** + **`toObject`** ( **`bytes`** as **`Buffer`** for the printer ). 5. **`printProtobufMessage`** to stdout; errors logged to stderr. KafkaJS timeouts in code: **`connectionTimeout: 10_000`**, **`requestTimeout: 60_000`**. ## Execution workflow 1. **Initialize client** — brokers from env or defaults; **`ssl: false`**; SCRAM SASL credentials. 2. **Resolve group id** — explicit **`KAFKA_GROUP_ID`** or generated **`username-group-uuid`**. 3. **`loadProto(topic)`** — bind decode type to **`KAFKA_TOPIC`**. 4. **Connect and subscribe** — optional **`fromBeginning`** for new consumer groups without committed offsets—understand semantics vs **`autoCommit: false`** in this baseline. 5. **Process messages** — **`eachMessage`** decodes protobuf, prints traversal. 6. **Compression** — LZ4 codec registered for Kafka compression on the wire. 7. **Errors** — caught per message where possible; fatal errors exit non-zero. **TLS:** baseline is **plaintext Kafka** on **9092**. For **`SASL_SSL`**, populate KafkaJS **`ssl`** objects and migrate brokers per **[Kafka streaming concepts — SASL_SSL](/docs/streams/kafka-streaming-concepts/#ssl-connection-sasl_ssl-)** plus **`js-consumer-example/README.md`**. ## Clone and run (quick reference) > You need separate Kafka credentials. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ```bash git clone https://github.com/bitquery/kafka-streams-examples-usecases.git cd kafka-streams-examples-usecases/js-consumer-example npm install cp .env.example .env # set KAFKA_USERNAME, KAFKA_PASSWORD npm start ``` Debug KafkaJS internals: ```bash npm run start:debug ``` ## Troubleshooting | Issue | Action | | ------------------------- | ---------------------------------------------------------------------------------------- | | Missing env vars | **`cp .env.example .env`**, validate names | | Auth / SASL failures | Credentials, **`scram-sha-512`** mechanism, broker connectivity **9092** | | LZ4 / native addon errors | Re-run **`npm install`**; verify Node version ≥ 18 | | Decode failures | Topic unsupported in your **`bitquery-protobuf-schema`** version or wrong topic spelling | ## See also - **[bitquery-protobuf-schema (npm package)](https://www.npmjs.com/package/bitquery-protobuf-schema)** - **[Kafka streaming concepts](/docs/streams/kafka-streaming-concepts/)** --- ## Kafka Operations Cookbook URL: https://docs.bitquery.io/docs/streams/kafka-operations/ Connect, authenticate, and operate Bitquery Kafka consumers — offsets, timestamps, retention, billing, and schema gotchas. # Kafka Operations Cookbook Practical operating guidance for Bitquery Kafka consumers: how to connect and authenticate, how offsets and timestamps behave, what retention to expect, and the schema traps that trip up new integrators. For the streaming concepts and topic catalogue, start with [Kafka Streaming Concepts](/docs/streams/kafka-streaming-concepts/). :::caution Verify connection details for your account Broker hosts, ports, and credential rules are provisioned per account — use the values in your onboarding details. ::: ## Connection recipe - **Port:** `9092` - **Security protocol:** `SASL_PLAINTEXT` with your Kafka **username and password** (SASL/PLAIN) — no client TLS certificates required. - **Consumer group id:** use any stable `group.id` for your consumer. - Credentials for the chain topics (e.g. `solana.*`) and the `trading.*` topic family may differ — use the credential issued for the family you're consuming. See the language-specific starters: [Python](/docs/streams/protobuf/kafka-protobuf-python/), [JavaScript](/docs/streams/protobuf/kafka-protobuf-js/), [Go](/docs/streams/protobuf/kafka-protobuf-go/). ## Retention: Kafka is not a historical firehose Kafka delivers **realtime data plus a small backfill window (hours, not history)**. A fresh consumer sees recent messages forward — not the chain from genesis. For anything older, use GraphQL (within its [retention window](/docs/graphql/data-coverage-retention/)) or a [cloud/S3 export](/docs/cloud/). Two independent integrators have assumed Kafka replays genesis; it does not. ## Offsets and restart behavior Two common restart modes: - **Skip the backlog (only new messages):** reset the group to the latest offset — e.g. `auto.offset.reset=latest`, or an explicit reset to end on startup. - **Resume where you stopped (backfill the gap):** reuse the **same `group.id`** and resume from committed offsets. Commit periodically — but **not too frequently**, since very frequent commits create broker backpressure. - If you see **`Offset out of range`** (your committed offset aged out of the retention window), reset to `latest` and continue. ## Timestamps (especially Solana) - On Solana shred streams, a message carries its **slot**, but the **block timestamp is only populated on the final message of a block** (messages are pushed before the block finalizes). **Do not treat an empty/zero `BlockHeader.Timestamp` on non-final messages as staleness.** - Block time is rounded and propagation adds a small delay, so an event can carry a timestamp a second or two before it reaches your consumer. Budget for this when computing "latency". ## No server-side filtering Kafka topics are **firehoses** — there is no server-side filter. Consume the topic and filter client-side (by mint, program, pair, address, etc.). If you need server-side filtering, use GraphQL subscriptions or Solana gRPC (which requires at least one filter) instead. ## Billing: what counts as a "stream" Each **environment / consumer group** counts as its own stream. Running the same topic from `dev`, `staging`, and `prod` (three consumer groups) counts as three streams. Kafka capacity is billed separately from GraphQL query points. See [How Billing Works](/docs/plans/how-billing-works/). ## Schema gotchas - In `BlockHeader`, the fields **`TxHash`, `Root`, and `ReceiptHash` are block-level Merkle roots — not a transaction hash.** The actual transaction hash lives on the transaction record (`TransactionHeader`), not the block header. The `TxHash` name is a common source of confusion. - Message nesting generally goes block → transaction → event; consult the [protobuf schema](/docs/streams/protobuf/kafka-trading-topics-protobuf/) for the exact shape of each topic. ## Diagnosing lag If messages arrive late or pile up, check **consumer lag first** — it's usually the client (slow processing, too few partitions consumed, large payloads on some chains) rather than the broker. Scale consumers or parallelize partition consumption. ## Next steps - [Kafka Streaming Concepts & topic list](/docs/streams/kafka-streaming-concepts/) - [Protobuf schema reference](/docs/streams/protobuf/kafka-trading-topics-protobuf/) - [Data Coverage & Retention](/docs/graphql/data-coverage-retention/) - [Common errors — Kafka auth](/docs/start/errors/#kafka-auth-errors) --- ## Kafka Streaming Concepts URL: https://docs.bitquery.io/docs/streams/kafka-streaming-concepts/ Learn Bitquery Kafka stream concepts: topics, offsets, SASL auth, protobuf payloads, and when Kafka beats WebSockets for crypto data. # Bitquery Kafka Streams - Understanding Concepts Bitquery provides realtime data via Kafka as well in addition to GraphQL subscriptions. In this section, we'll see how Kafka-based streaming works and how to integrate it into your application using practical code examples. For price data streams, check out our [Crypto Price API](/docs/trading/crypto-price-api/) Kafka topic. ## How to Get Access to these Streams? IDE credentials will not work with our Kafka Streams. You need a separate username and password. Please contact sales on our official telegram channel or fill out the [form on our website](https://bitquery.io/forms/api). ### Pros and Cons Kafka provides faster and more reliable streams comparing to GraphQL subscriptions due to the following advantages: 1. It has lower latency due to the shorter data pipeline, as GraphQL subscriptions involve custom databases and additional logic to process, filter and format the data 2. Better reliability of the connection protocol compared to WebSocket interface, better optimized for persistent connections 3. Messages from Kafka topic can be read from the latest offset, it is possible to create consumers that have all messages without gaps and interruption. 4. Scalability is better as multiple consumers may split the load to consume one topic, automatically redistributing load on them There are some disadvantages however compared to GraphQL subscriptions: 1. There is no way to consume Kafka streams in browser. You can only use it only on server side. 2. It is not possible to pre-filter or re-format messages on Kafka streams, as schema is pre-defined, and you need to make all post-processing in your code. Some calculations, as usd value of trade have to be executed on client side as well 3. IDE does not support Kafka streams yet, debugging the code have to be done on consumer side Kafka streams contains same set of data as GraphQL subscriptions, and the decision which one to use dependent more on your application type. Consider the following factors when selecting which technology to use. ### Consider using GraphQL if: - You are building a prototype and the speed of development is a primary factor for you. Integrating GraphQL is easier, IDE helps to de-bug queries and see the data you receive in application; - Your application uses archive and real-time data altogether. GraphQL has a unified interface to query and subscribe the data streams, that makes such application easier to build and maintain; - Your application provides different data on web pages, for example show price diagrams for trading. Then GraphQL makes simpler to filter the data and make queries based on page content; - There is no server side for your application, or it is minimal. Then GraphQL can be integrated directlty to JS client code; ### Consider using Kafka if: - Latency is the most important factor and you building fast scalable application in cloud or on dedicated servers; - It is not acceptable to lose any single message from the stream, you need persistent reliability; - You have a complex calculations, filtering or formatting of the data that GraphQL does not deliver. Then instead of consuming unfiltered stream from GraphQL consider switch to Kafka. This decision sometimes not straightforward, consult our sales and support team, we will help you find optimal solution. ### Important Notes about Kafka Streams - Stream is not filtered, it contains all the messages with a complete data for every topic. It means you need to have a good throughput network, fast server and code to efficently consume and parse it; - Granularity of data message is different in topics, depending on the nature of the data. - It is **not** guaranteed that the message will come in sequence of the block number, time or any other attribute. - Messages in topic **may have** duplicates. If this is a problem, your code must have a storage or the cache to remember which messages are already processed to avoid double processing. - Large messages can be separated on smaller ones, as Kafka does not allow pass more than 1 Mbyte in one message. For example, first 1200 transaction may come in one message, and the remaining 1000 will follow in another. - **Transactions themselves will never be split**: each transaction record is always delivered in full. If a single transaction payload exceeds Kafka’s maximum message size, the producer will receive an error—Kafka will not peek inside the payload to automatically fragment it into multiple messages. ### Kafka Streams Lattency Topics for the same blockchain are not equal by latency. If you have requirements on latency, consider to select the proper stream for your application: 1. Broadcasted topics are available for most blockchains. They can be faster, as the transactions are not waiting till include and commit the block in the chain 2. Streams are chained while they are parsing, the closer the topic to the original blockchain node, the less is the latency. Consider selecting the closest topic that you can effectively parse. Every transformation introduces 100-1000 msec latency in the overall topic delay. The diagram shows the data pipeline of the streams on the way to KAFKA topics. Broadcasted and committed transaction datapipelines are identical: ![Topic Data Pipeline](/img/streams/latency.png) #### Measured Latency: Kafka vs GraphQL Subscription The table below compares end-to-end latency for **Solana token transfers** delivered over Kafka (`solana.tokens.proto`) and over a GraphQL subscription (WebSocket, `streaming.bitquery.io/graphql`). Both streams were consumed **simultaneously from the same server** over a 5-minute window, and both delivered the same volume of data (~1.227M transfers each, a 0.01% difference). Latency is measured from the **Solana block timestamp** to the moment the message is available to application code. | | p50 | p90 | p95 | p99 | mean | | ----------------------------------------------- | ------ | ------- | ------- | ------- | ------ | | **Kafka** (`solana.tokens.proto`) | 383 ms | 1450 ms | 1636 ms | 1847 ms | 495 ms | | **WebSocket** (`streaming.bitquery.io/graphql`) | 405 ms | 1488 ms | 1674 ms | 2013 ms | 530 ms | A few notes on how to read these numbers: - **Solana block timestamps have 1-second granularity.** This adds up to ±1s of quantization noise to every sample, which inflates the p90/p99 figures for both transports. The noise is identical for Kafka and WebSocket, so the comparison between them remains valid. - **Comparing arrival times slot-by-slot** removes that quantization entirely. On this basis Kafka arrived first for **77%** of slots, leading by a median of **~5 ms** and by **~64 ms** at p99. - **Measured on the Kafka side alone**, delivery from broker to consumer (using millisecond-precision Kafka record timestamps, so no quantization) was **17 ms at p50** and **141 ms at p99**. - **Bandwidth differs far more than latency.** Kafka transferred ~10.9 GB over the window against ~332 MB for the WebSocket subscription — roughly **33× more** for the same transfers. Kafka topics carry the complete `TokenBlockMessage` (balance updates, supply updates, token metadata), while a GraphQL subscription sends only the fields you request. Budget for this if you only need a narrow slice of the data. Latency and throughput both depend on your network, server and consumer code, so treat these figures as a reference point rather than a guarantee. ## Consuming Messages Your application must implement the code: - Connect to Kafka server; - Subscribe to particular topic(s); - Read and parse messages; ## Retention Period of Messages **Proto Streams**: Messages are retained for **4 hours**. ## Connect to Kafka Server To connect to Bitquery’s Kafka streaming service, you’ll need the following: 1. **Kafka Broker Addresses** Use the following server list: `rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092` 2. **Authentication Credentials** A **username** and **password** for **SASL over PLAINTEXT authentication** – provided by the Bitquery support team. ### Non-SSL Connection (SASL_PLAINTEXT ) If you prefer to connect without SSL, you can use **SASL_PLAINTEXT** on port `9092`. This does **not** require certificates: ```python sasl_conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9092,rpk1.bitquery.io:9092,rpk2.bitquery.io:9092', 'security.protocol': 'SASL_PLAINTEXT', 'sasl.mechanism': 'SCRAM-SHA-512', 'sasl.username': '', 'sasl.password': '', } ``` > Use plaintext only in trusted or local environments, as the connection is not encrypted. ### SSL Connection (SASL_SSL ) If you prefer to connect with SSL, you can use **SASL_SSL** on port `9093`. This requires certificates which can be accessed [here](https://github.com/bitquery/kafka-consumer-example) ```python sasl_conf = { 'bootstrap.servers': 'rpk0.bitquery.io:9093,rpk1.bitquery.io:9093,rpk2.bitquery.io:9093', 'security.protocol': 'SASL_SSL', 'sasl.mechanism': 'SCRAM-SHA-512', 'sasl.username': '', 'sasl.password': '', 'ssl.key.location': 'client.key.pem', 'ssl.ca.location': 'server.cer.pem', 'ssl.certificate.location': 'client.cer.pem', 'ssl.endpoint.identification.algorithm': 'none' } ``` ### Subscribe to particular topic(s) To receive messages you first create consumer and subscribe it to a topic or list of topics. General pattern of the topic name is: ``` . .broadcasted. ``` ### General Message Types MESSAGE_TYPE is specific on blockchain, most blockchain has topics for: - dextrades - events from DEX trading - transactions - events, calls, transactions - tokens - token and coin transfers events - raw - blocks or transactions directly from node Refer to [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf) schemas for structure. ### EVM Chains **Broadcasted (Mempool-level):** - `*.broadcasted.transactions.proto` → `ParsedAbiBlockMessage` - `*.broadcasted.tokens.proto` → `TokenBlockMessage` - `*.broadcasted.dextrades.proto` → `DexBlockMessage` - `*.broadcasted.raw.proto` → `BlockMessage` **Committed Blocks:** - `*.transactions.proto` - `*.tokens.proto` - `*.dextrades.proto` - `*.raw.proto` ## Complete List of Topics All topics deliver data in **protobuf** format. JSON samples for inspection: [kafka-data-sample](https://github.com/bitquery/kafka-data-sample). ### Multi-chain trading topics The **`trading`** namespace defines two Kafka topics. **Both use the same credentials** as your subscription: - **`trading.prices`** — Multi-chain [Price Index Streams](/docs/trading/crypto-price-api/). See the [Crypto Price API](/docs/trading/crypto-price-api/) for usage. - **`trading.trades`** — Real-time DEX trades aligned with the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api). Message structure is defined in [`market/trades.proto`](https://github.com/bitquery/streaming_protobuf/blob/main/market/trades.proto) in [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf). ### EVM chains **Committed** topics use: - **`*.transactions.proto`** → `ParsedAbiBlockMessage` - **`*.tokens.proto`** → `TokenBlockMessage` - **`*.dextrades.proto`** → `DexBlockMessage` - **`*.raw.proto`** → `BlockMessage` **Mempool / broadcasted** topics insert **`broadcasted`** immediately after the chain prefix (example: **`eth.broadcasted.transactions.proto`**). They use: - **`*.broadcasted.transactions.proto`** → `ParsedAbiBlockMessage` - **`*.broadcasted.tokens.proto`** → `TokenBlockMessage` - **`*.broadcasted.dextrades.proto`** → `DexBlockMessage` - **`*.broadcasted.raw.proto`** → `BlockMessage` **`*.dexpools.proto`** → `DexPoolBlockMessage`. See the [DEXPools Cube documentation](/docs/cubes/evm-dexpool) for details. #### Ethereum (`eth`) - `eth.transactions.proto` → `ParsedAbiBlockMessage` - `eth.tokens.proto` → `TokenBlockMessage` - `eth.dextrades.proto` → `DexBlockMessage` - `eth.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) - `eth.raw.proto` → `BlockMessage` - `eth.broadcasted.transactions.proto` → `ParsedAbiBlockMessage` - `eth.broadcasted.tokens.proto` → `TokenBlockMessage` - `eth.broadcasted.dextrades.proto` → `DexBlockMessage` - `eth.broadcasted.raw.proto` → `BlockMessage` #### BNB Chain (`bsc`) - `bsc.transactions.proto` → `ParsedAbiBlockMessage` - `bsc.tokens.proto` → `TokenBlockMessage` - `bsc.dextrades.proto` → `DexBlockMessage` - `bsc.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) Where enabled, **`bsc.broadcasted.*`** topics follow the same mapping as **`eth.broadcasted.*`**. #### Base (`base`) - `base.transactions.proto` → `ParsedAbiBlockMessage` - `base.tokens.proto` → `TokenBlockMessage` - `base.dextrades.proto` → `DexBlockMessage` - `base.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) Where enabled, **`base.broadcasted.*`** topics follow the same mapping as **`eth.broadcasted.*`**. #### Polygon (`matic`) - `matic.transactions.proto` → `ParsedAbiBlockMessage` - `matic.tokens.proto` → `TokenBlockMessage` - `matic.dextrades.proto` → `DexBlockMessage` - `matic.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) - `matic.predictions.proto` — prediction markets; decode using [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf) - `matic.broadcasted.predictions.proto` — prediction markets (broadcasted) Where enabled, **`matic.broadcasted.*`** topics for standard EVM **`transactions`**, **`tokens`**, **`dextrades`**, and **`raw`** streams follow the broadcasted mapping above. #### Optimism (`optimism`) - `optimism.transactions.proto` → `ParsedAbiBlockMessage` - `optimism.tokens.proto` → `TokenBlockMessage` - `optimism.dextrades.proto` → `DexBlockMessage` Where enabled, **`optimism.broadcasted.*`** topics follow the same mapping as **`eth.broadcasted.*`**. #### Robinhood (`robinhood`) - `robinhood.transactions.proto` → `ParsedAbiBlockMessage` - `robinhood.tokens.proto` → `TokenBlockMessage` - `robinhood.dextrades.proto` → `DexBlockMessage` - `robinhood.raw.proto` → `BlockMessage` - `robinhood.dexpools.proto` → `DexPoolBlockMessage` — see [DEXPools Cube documentation](/docs/cubes/evm-dexpool) #### Arc Testnet (`arc-testnet`) - `arc-testnet.transactions.proto` → `ParsedAbiBlockMessage` - `arc-testnet.tokens.proto` → `TokenBlockMessage` - `arc-testnet.dextrades.proto` → `DexBlockMessage` - `arc-testnet.raw.proto` → `BlockMessage` Arc testnet is Circle's Arc Layer 1 test network (`EVM(network: arc_testnet)` in GraphQL). All `...InUSD` fields in its messages are 0 because a testnet has no token price index; native amounts are USDC, the chain's gas token. See the [Arc Testnet hub](/docs/blockchain/arc-testnet/). ### Bitcoin - `btc.transactions.proto` — decode using Bitquery Bitcoin protobuf definitions in [Bitquery Streaming Protobuf](https://github.com/bitquery/streaming_protobuf). ### Solana (`solana`) - `solana.transactions.proto` → `ParsedIdlBlockMessage` - `solana.tokens.proto` → `TokenBlockMessage` - `solana.dextrades.proto` → `DexParsedBlockMessage` ### Hyperliquid (`hyperliquid`) Message types are defined in [hyperliquid/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, Robinhood Chain and Arc testnet | [EVM protobuf streams](/docs/streams/protobuf/chains/EVM-protobuf) | | Solana | Shred-level transactions, DEX trades, transfers and balances, ahead of block confirmation | [Solana shred streams](/docs/streams/protobuf/chains/Solana-protobuf) | | Solana perpetuals | Orders, fills, positions, PnL, liquidations and prices | [Solana perpetuals stream](/docs/streams/protobuf/chains/Solana-perpetual-protobuf) | | Tron | Transactions, transfers, balances and blocks | [Tron protobuf streams](/docs/streams/protobuf/chains/Tron-protobuf) | | Bitcoin | Blocks, transactions, inputs and outputs | [Bitcoin protobuf streams](/docs/streams/protobuf/chains/Bitcoin-protobuf) | 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/) --- ## 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 ================================================================================ ``` --- ## Live Reload Configuration for gRPC Streams URL: https://docs.bitquery.io/docs/grpc/solana/live-reload/ Live Reload Configuration for gRPC Streams for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Live Reload Configuration for gRPC Streams Live reload enables dynamic configuration changes without you having to restart your application. This feature automatically detects changes to your `config.yaml` file and restarts the stream with the new settings. ## Why Live Reload? Live reload is essential for: - **Testing different filters**: Quickly test various filter combinations without stopping and restarting your application - **Switching stream types**: Change between dex_trades, transactions, balances, and other stream types on the fly - **Dynamic monitoring**: Adjust which programs, pools, or traders to monitor in real-time - **Production updates**: Update filters in production without downtime - **Development efficiency**: Iterate faster during development and debugging ## How It Works The live reload system monitors your `config.yaml` file for changes using Node.js's `fs.watch()` API. When a change is detected: 1. The configuration file is reloaded 2. The current stream connection is gracefully stopped 3. If server settings changed, the gRPC client is reinitialized 4. A new stream is started with the updated configuration 5. All of this happens automatically without manual intervention ## Setup ### Prerequisites Install the required dependencies: ```bash npm install @grpc/grpc-js @grpc/proto-loader js-yaml bs58 ``` Or using package.json: ```json { "dependencies": { "@grpc/grpc-js": "^1.9.0", "@grpc/proto-loader": "^0.7.10", "js-yaml": "^4.1.0", "bs58": "^5.0.0" } } ``` ### Configuration File Create a `config.yaml` file with your stream settings: ```yaml server: address: "corecast.bitquery.io" authorization: "ory_YOUR_API_TOKEN_HERE" insecure: false stream: type: "dex_trades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Pump.fun ``` **Get your API token**: Generate one at [https://account.bitquery.io/user/api_v2/access_tokens](https://account.bitquery.io/user/api_v2/access_tokens) ## Implementation ### Basic Live Reload Setup Here's the core implementation for live reload functionality: ```javascript const fs = require('fs'); const yaml = require('js-yaml'); let config = null; let currentStream = null; let isReloading = false; // Load configuration from file function loadConfig() { try { const newConfig = yaml.load(fs.readFileSync('./config.yaml', 'utf8')); console.log('Configuration loaded successfully'); return newConfig; } catch (error) { console.error('✗ Failed to load configuration:', error.message); return null; } } // Watch config file for changes let watchTimeout = null; fs.watch('./config.yaml', (eventType, filename) => { if (eventType === 'change') { // Debounce multiple rapid file changes if (watchTimeout) { clearTimeout(watchTimeout); } watchTimeout = setTimeout(() => { reloadAndRestart(); watchTimeout = null; }, 300); // Wait 300ms after last change } }); console.log(' Watching config.yaml for changes...'); ``` ### Complete Live Reload Function The reload function handles the full lifecycle of stopping the old stream and starting a new one: ```javascript // Check if server configuration changed function hasServerConfigChanged(oldConfig, newConfig) { return oldConfig.server.address !== newConfig.server.address || oldConfig.server.authorization !== newConfig.server.authorization || oldConfig.server.insecure !== newConfig.server.insecure; } // Reload configuration and restart stream function reloadAndRestart() { if (isReloading) { return; // Prevent concurrent reloads } isReloading = true; console.log('\n Configuration changed, reloading...'); // Load new configuration const newConfig = loadConfig(); if (!newConfig) { console.error('Failed to reload configuration, keeping current settings'); isReloading = false; return; } // Check if we need to reinitialize the client const needsNewClient = hasServerConfigChanged(config, newConfig); // Stop current stream stopStream(); // Update configuration config = newConfig; // Reinitialize client if server settings changed if (needsNewClient) { console.log('Server configuration changed, reinitializing client...'); try { initializeClient(); } catch (error) { console.error('Failed to initialize client:', error.message); isReloading = false; return; } } // Start new stream try { startStream(); isReloading = false; } catch (error) { console.error(' Failed to start stream:', error.message); isReloading = false; } } // Stop current stream function stopStream() { if (currentStream) { try { currentStream.cancel(); console.log('Stream stopped'); } catch (error) { console.error('Error stopping stream:', error.message); } currentStream = null; } } ``` ### Graceful Shutdown Handle process termination properly: ```javascript // Handle process termination process.on('SIGINT', () => { console.log('\nShutting down gracefully...'); stopStream(); process.exit(0); }); process.on('SIGTERM', () => { console.log('\nShutting down gracefully...'); stopStream(); process.exit(0); }); ``` ## Usage Examples ### Example 1: Switching Between Stream Types Start with DEX trades: ```yaml stream: type: "dex_trades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" ``` Then modify the config to switch to transactions: ```yaml stream: type: "transactions" filters: signers: - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" ``` The stream will automatically restart with the new configuration. ### Example 2: Adding Multiple Program Filters Start monitoring one program: ```yaml filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Pump.fun ``` Add more programs without restarting: ```yaml filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Pump.fun - "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK" # Raydium CLMM - "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" # Raydium V4 ``` ### Example 3: Switching Filter Types Monitor by program: ```yaml filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" ``` Switch to monitoring specific pools: ```yaml filters: pool: - "5tUu7bX8d8Zz1v3v4Y9H9F6J7K8L9M0N1O2P3Q4R5S6T" - "7GJz9X7b1G9Nf1d5uQq2Z3B4nPq6F8d9LmNoPQrsTUV" ``` Or monitor specific traders: ```yaml filters: traders: - "7GJz9X7b1G9Nf1d5uQq2Z3B4nPq6F8d9LmNoPQrsTUV" ``` ### Example 4: Testing Multiple Configurations You can quickly test different configurations by editing the YAML file: ```yaml # Test 1: Monitor Pump.fun trades stream: type: "dex_trades" filters: programs: - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" # Test 2: Monitor specific wallet transactions # stream: # type: "transactions" # filters: # signers: # - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" # Test 3: Monitor token transfers # stream: # type: "transfers" # filters: # tokens: # - "So11111111111111111111111111111111111111112" # WSOL ``` Simply uncomment the configuration you want to test, and the stream will reload automatically. ## Available Stream Types You can switch between these stream types using live reload: - **`dex_trades`**: Real-time DEX trade/swap data - **`dex_orders`**: Order lifecycle updates - **`dex_pools`**: Pool creation and liquidity changes - **`transactions`**: Finalized transactions with instructions - **`transfers`**: Token transfer events - **`balances`**: Balance updates for accounts For detailed information on each stream type, see: - [DEX Trades](/docs/grpc/solana/topics/dextrades) - [Transactions](/docs/grpc/solana/topics/transactions) - [Balances](/docs/grpc/solana/topics/balance) ## Available Filters Different stream types support different filters: ### DEX Trades Filters ```yaml filters: programs: # DEX program addresses - "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P" pool: # Market/pool addresses - "5tUu7bX8d8Zz1v3v4Y9H9F6J7K8L9M0N1O2P3Q4R5S6T" traders: # Trader wallet addresses - "7GJz9X7b1G9Nf1d5uQq2Z3B4nPq6F8d9LmNoPQrsTUV" ``` ### Transaction Filters ```yaml filters: signers: # Transaction signers - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" ``` ### Transfer Filters ```yaml filters: tokens: # Token mint addresses - "So11111111111111111111111111111111111111112" # WSOL signers: # Transaction signers - "E6SykRdyqq24QJYcZ1kEbYoNtC3jYojE6fSvwBUqxAts" ``` ## Debouncing The live reload implementation includes a 300ms debounce to handle multiple rapid file changes. This prevents unnecessary restarts when your editor makes multiple writes while saving a file. ```javascript // Debounce multiple rapid file changes if (watchTimeout) { clearTimeout(watchTimeout); } watchTimeout = setTimeout(() => { reloadAndRestart(); watchTimeout = null; }, 300); // Wait 300ms after last change ``` You can adjust this delay based on your needs: - **Shorter delay (100-200ms)**: Faster reloads, but might trigger multiple times - **Longer delay (500-1000ms)**: More stable, but slower to reflect changes ## Error Handling The live reload system includes comprehensive error handling: ### Configuration Errors If the new configuration is invalid, the system keeps the current working configuration: ``` Failed to reload configuration, keeping current settings ``` ### Stream Errors Stream errors during reload are logged but don't crash the application: ```javascript stream.on('error', (error) => { if (!isReloading) { console.error('Stream error:', error); } }); ``` The `isReloading` flag prevents error spam during normal reload operations. ## Best Practices 1. **Test changes locally first**: Validate your configuration changes work before deploying to production 2. **Use version control**: Keep your config.yaml in version control to track changes 3. **Comment your filters**: Add comments to document what each filter monitors 4. **Monitor reload events**: Log when reloads happen to track configuration changes 5. **Handle edge cases**: Ensure your application handles the brief disconnection during reload ### Environment Variables For sensitive data like API tokens, use environment variables: ```javascript function loadConfig() { const config = yaml.load(fs.readFileSync('./config.yaml', 'utf8')); // Override with environment variables if (process.env.BITQUERY_TOKEN) { config.server.authorization = process.env.BITQUERY_TOKEN; } return config; } ``` ## Logging Output When live reload is active, you'll see these messages: ``` Watching config.yaml for changes... Configuration loaded successfully Stream connected and listening for data... Configuration changed, reloading... Stream stopped Configuration loaded successfully Stream connected and listening for data... ``` ## Related Documentation - [Introduction to gRPC Streams](/docs/grpc/solana/introduction) - [Best Practices](/docs/grpc/solana/best_practices) - [Authorization](/docs/grpc/solana/authorization) - [Error Handling](/docs/grpc/solana/errors) ## Troubleshooting ### Stream Not Reloading If changes aren't being detected: 1. Check file permissions on `config.yaml` 2. Ensure the file is being saved properly by your editor 3. Look for configuration syntax errors in the console 4. Verify the debounce timeout hasn't been set too high ### Frequent Disconnections If the stream disconnects frequently during reloads: 1. Check your network connection stability 2. Verify your API token is valid 3. Ensure you're not hitting rate limits 4. Review your filter configuration for errors ### Memory Issues If you experience memory issues with live reload: 1. Ensure streams are properly cancelled before creating new ones 2. Clear any message buffers during reload 3. Monitor for event listener leaks 4. Use the provided cleanup functions ## Next Steps Now that you understand live reload, explore: - [Stream Topics](/docs/grpc/solana/topics/dextrades) - Different types of streams available - [Best Practices](/docs/grpc/solana/best_practices) - Production-ready patterns - [Examples](/docs/grpc/solana/examples/pump-fun-grpc-streams) - Real-world use cases --- ## Manage Your Bitquery Subscription URL: https://docs.bitquery.io/docs/plans/manage-subscription/ Video walkthroughs for paying, upgrading, downgrading and cancelling your Bitquery subscription — including pro-rata charges and what happens at renewal. # Manage Your Subscription Everything about your subscription — paying for a plan, buying add-ons, moving between tiers, and cancelling — is self-serve from [Account → Billing](https://account.bitquery.io/user/billing). The two walkthroughs below show the full flow end to end. For the written reference, see [Upgrade to Paid Plan](/docs/ide/paid/) and [How Billing Works](/docs/plans/how-billing-works/). ## Paying for Bitquery products Covers the four-step checkout — **Choose plan → Plan configuration → Review & pay → Done**: - Picking a tier, and switching between monthly and annual billing (annual saves 30% or more) - **Top-up credits** — API points, stream data, stream-minutes, and MCP credits. These are recurring: they refill each billing period rather than being a one-time bucket. - **Historical (archive) data add-ons**, bought per chain and dataset family. Your subscription covers realtime on a rolling window; the archive add-on is what unlocks full history. Use the ⓘ on any add-on to see the exact datasets, cubes and time scope it unlocks. - Reviewing the service agreement and paying by card through Stripe ## Upgrading, downgrading and cancelling Covers changing an existing subscription from the Billing page: - **Change Plan** — the tier comparison, and what moving up actually buys you (streaming, for example, is off on Personal and starts at Pro) - **Manage Add-Ons** — adding capacity or data access without changing tier - **Upgrades are charged pro rata.** When you upgrade or add an add-on mid-cycle, you are only charged for the days remaining in your current period, and the exact amount is finalized by Stripe before you pay. From your next renewal, the full amount bills as one normal monthly subscription. - **Downgrades take effect at your next renewal**, so you keep everything you have already paid for until the period ends. Nothing is charged at the time of the downgrade. - **Cancelling** stops the renewal — no further payments. Your current period and any remaining points stay available until the period end date shown on the cancellation page. No refund is issued for the current period. :::tip Before you cancel If the issue is price or volume rather than the product, a downgrade or a plan sized to your actual usage is usually the better answer. Unlimited streams, custom limits, private endpoints and chains that are not available self-serve are all part of Enterprise — [talk to sales](https://bitquery.io/forms/api) or email [sales@bitquery.io](mailto:sales@bitquery.io). ::: ## Related pages - [Upgrade to Paid Plan](/docs/ide/paid/) — plan table, add-ons and self-serve checkout in detail - [How Billing Works](/docs/plans/how-billing-works/) — points, streams billing and overage - [Manage Account](/docs/ide/account/) — dashboard, navigation and account settings - [Pricing](https://bitquery.io/pricing) — current prices and allowances Billing questions: [support@bitquery.io](mailto:support@bitquery.io). --- ## 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/) --- ## 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) --- ## 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). --- ## Optimize Bitquery GraphQL Queries URL: https://docs.bitquery.io/docs/graphql/optimizing-graphql-queries/ Optimize Bitquery GraphQL Queries in Bitquery GraphQL with clear syntax, examples, and tips for fast blockchain queries and streams. # GraphQL query optimization for APIs GraphQL is an open-source query language for APIs. It allows clients to define the required data structure, and the server responds with only that data. This allows for more efficient and flexible communication between the client and server, as well as enabling better performance and easier development of APIs. GraphQL query optimization is a crucial aspect of utilizing V2 APIs to their full potential. By optimizing your queries, you can significantly reduce the amount of time and resources required to retrieve the data you need. In this section, we will see how to optimize your V2 API queries. ### Understanding Datasets Choosing the right dataset is critical for both correctness and performance. We offer three datasets with different guarantees and latency characteristics: - **realtime**: Default if omitted. Contains the most recent data (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) { Balances(limit: { count: 1000 }) { ... } } ``` ### Understanding limits in GraphQL In V2 APIs, it's crucial to note the implicit default limit applied when a specific limit isn't explicitly defined within a query. [By default, this limit restricts the number of records returned to 10,000](/docs/start/errors/#limits). This safeguard is in place to prevent excessive resource consumption, ensuring the efficient processing of queries. However, to tailor data retrieval according to specific needs, V2 APIs provide the flexibility to set custom limits using the 'limit' parameter. This filter allows you to refine your query results, ensuring that only the necessary records are returned, reducing unnecessary point consumption risk. Let's take an example, the below query retrieves information about calls on the BNB network. For each call, it retrieves the internal call and transaction information. The number of responses is restricted to 20 by the limit field. ```graphql query CustomLimitQuery { EVM(dataset: realtime, network: bsc) { Calls(limit: { count: 20 }) { Call { LogCount InternalCalls } Transaction { Gas Hash From To Type Index } Block { Date } } } } ``` ### Understanding limitBy In addition to the 'limit' parameter, V2 APIs also offer the 'limitBy' parameter, which allows you to set limits based on specific criteria. For example, you can set a limit on the number of records returned based on a certain attribute or field. This helps to further refine your queries and reduce unnecessary resource consumption. Using the 'limitBy' parameter is particularly useful when dealing with large datasets, as it allows you to retrieve only the data that is relevant to your needs. Below is an example query that retrieves information about limitBy. For each call, it retrieves the internal call and transaction information. The number of responses is limited to 10 by the 'limit' field. ```graphql { EVM(dataset: realtime, network: eth) { DEXTrades( where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } } } } limit: { count: 10 } limitBy: { by: Trade_Sell_Currency_SmartContract, count: 1 } ) { Trade { Dex { ProtocolName OwnerAddress ProtocolVersion Pair { SmartContract Name Symbol } } Buy { Currency { Name SmartContract } } Sell { Currency { Name SmartContract } } } } } } ``` ### Understanding Indexes In each table, certain columns are used as indexes, you can use those columns to sort in `orderby` field to improve time to response. A detailed list is available in this [Indexes](/docs/graphql/indexed-fields-reference/) page. ### Sorting Queries in GraphQL Sorting can be done by using the `order by` argument. This argument takes a list of fields to sort by, as well as the direction of the sorting (ascending or descending). For example, if you wanted to sort a list of users by their age in descending order, your GraphQL query looks like below. ```graphql query ($network: evm_network, $till: String!, $token: String!, $limit: Int) { EVM(network: $network, dataset: archive) { Holders( date: $till orderBy: { descending: Balance_Amount } limit: { count: $limit } where: { Currency: { SmartContract: { is: $token } } } ) { Holder { Address } Balance { Amount } } Blocks(limit: { count: 1 }) { ChainId } } } ``` ### Sort by Metrics Sorting by metrics in GraphQL can be achieved by using the `order by` argument along with specific metrics. This allows you to sort data based on certain criteria, such as popularity, rating, or relevance. Metric-based sorting is a powerful feature in GraphQL that allows you to sort data based on a specific metric or criteria. Let me give you some examples to help explain how this works. ```graphql { EVM(network: bsc, dataset: realtime) { Transfers( limit: { count: 10 } orderBy: { descendingByField: "received" } where: { Block: { Time: { since_relative: { hours_ago: 1 } } } Transfer: { Currency: { SmartContract: { is: "0x55d398326f99059ff775485246999027b3197955" } } } } ) { Transfer { Receiver } received: sum(of: Transfer_Amount) } } } ``` In the above example, we use the `sum` metric to total the USDT each address received on BNB Chain in the last hour. We give an [alias](/docs/graphql/metrics/alias/) to the sum field (`received`) and sort the responses from highest to lowest with `descendingByField`. ### Filtering data in GraphQL queries Filtering data in GraphQL queries is done by using the `where` argument along with specific conditions. This allows you to retrieve only the data that meets certain criteria, such as a specific date range, a certain value, or a particular category. Filtering data is an important feature in GraphQL that allows you to narrow down the results of a query to only the relevant information you need. Let me give you an example to help illustrate how this works. We will look at how to use filters, with the help of the below example. ```graphql { EVM(dataset: combined, network: eth) { buyside: DEXTrades( limit: { count: 10 } orderBy: { descending: Block_Time } where: { Trade: { Buy: { Currency: { SmartContract: { is: "0x5283d291dbcf85356a21ba090e6db59121208b44" } } Seller: { is: "0x1111111254eeb25477b68fb85ed929f73a960582" } } } Block: { Time: { till: "2023-03-05T05:15:23Z", since: "2023-03-03T01:00:00Z" } } } ) { Block { Number Time } Transaction { From To Hash } Trade { Buy { Amount Buyer Currency { Name Symbol SmartContract } } Sell { Amount Buyer Currency { Name SmartContract Symbol } } } } } } ``` In the above GraphQL query, filtering is performed using the `where` argument in conjunction with conditions defined for the Trade and Block. For the `Trade` filtering, two conditions need to be satisfied. - The `Buy` property's `Currency` should have a `SmartContract` value of "0x5283d291dbcf85356a21ba090e6db59121208b44", and - The `Seller` property should be "0x1111111254eeb25477b68fb85ed929f73a960582". The `Block` filtering is based on the `Time` property. The `Time` should fall within a certain range - specifically, from "2023-03-03T01:00:00Z" to "2023-03-05T05:15:23Z". This combination of filters narrows down the results of `DEXTrades` to only include trades that meet all of the specified conditions within the given time frame. This will return only the posts that meet this criteria, and will only include their title and content fields in the response. #### Exploring Filter Types and Operators Filters play a crucial role in data retrieval systems by narrowing down search results to specific data sets. In the realm of databases, a filter acts as a condition applied to a query, fetching only the records that meet that specific condition. A variety of filter types and operators are available, allowing you to customize your search queries and obtain more accurate results. Some common filter types include: 1. Text filters: These filters enable you to search for specific text or words within a given field. 2. Numeric filters: These filters allow you to search for records based on numeric values within a specified range. Numeric filter types encompass: - Equals: represented by `is` or `=` - Not equals: represented by `NOT IN` - Greater than: represented by `gt` - Less than: represented by `lt` - Greater than or equal to: represented by `ge` - Less than or equal to: represented by `le` These operators aid in filtering data based on numeric values. 3. Date filters: These filters enable you to search for records based on specific dates or date ranges. 4. Boolean filters: These filters facilitate the search for records based on true/false values. For instance, consider the following query. Here, we utilize a string filter to narrow down the token contract to `0x23581767a106ae21c074b2276D25e5C3e136a68b` and a numeric filter with `ge` (greater than or equal to) 50, indicating a minimum balance requirement: ```graphql { EVM(dataset: archive, network: eth) { greater_than_50: Holders( date: "2023-10-23" where: { Currency: { SmartContract: { is: "0x23581767a106ae21c074b2276D25e5C3e136a68b" } }, Balance: { Amount: { ge: "50" } } } ) { uniq(of: Holder_Address) } greater_than_or_equal_to_50: Holders( date: "2023-10-23" where: { Currency: { SmartContract: { is: "0x23581767a106ae21c074b2276D25e5C3e136a68b" } }, Balance: { Amount: { gt: "50" } } } ) { uniq(of: Holder_Address) } } } ``` ### Running the same query for multiple addresses Let's say you have built a query that filters results using an address filter `{Address: {is: $token}`. To run the same query for multiple addresses, you can change the filter to `{Address: {in: ["A","B","C"]}` where `A`, `B`, `C` are all representative of addresses. --- ## Polymarket Analytics with AI: Volume, Odds History, Holders URL: https://docs.bitquery.io/docs/mcp/polymarket-analytics/ Run Polymarket analytics from a chat in Claude, ChatGPT or Cursor: rank markets by volume or by crowd, slice by subject, chart how the odds moved, and see who holds an outcome. Read-only, from on-chain data. # Polymarket Analytics with AI A dashboard gives you a fixed set of charts. This page shows the other way to do it: ask for the cut you want in plain English and get a table back. It uses six of the 14 Polymarket tools in the [Bitquery MCP server](/docs/mcp/polymarket/), in Claude, ChatGPT or Cursor. It reads data only and cannot place an order. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Every figure below came from the production server on 21 September 2026, between 15:11 and 15:15 UTC, with data 12 to 15 minutes behind the clock. ## Where is the money today? > *"Which Polymarket markets had the most volume in the last 24 hours?"* `polymarket_top_markets`, default sort. | # | Market | 24h volume | Wallets | |---|---|---:|---:| | 1 | Colts vs. Chiefs | $4,070,630 | 283 | | 2 | Will United Russia gain the most seats? | $3,815,310 | 493 | | 3 | Packers vs. Jets | $1,595,455 | 190 | | 4 | Raiders vs. Chargers | $1,486,917 | 133 | | 5 | Panthers vs. Falcons | $1,385,725 | 153 | ## Where is the crowd? > *"Now rank them by the number of wallets that traded."* Same tool, sorted by traders. | # | Market | Wallets | 24h volume | |---|---|---:|---:| | 1 | Browns vs. Buccaneers | 3,089 | $1,304,941 | | 2 | Milwaukee Brewers vs. Baltimore Orioles | 2,450 | $340,780 | | 3 | Will CD Leganés vs. Granada CF end in a draw? | 2,123 | $91,754 | | 4 | Solana Up or Down, 21 September, 8AM ET | 1,264 | $21,015 | | 5 | Will Panaitolikos Agrinio win on 20 September? | 776 | $11,171 | Not one market is on both lists. The biggest market by money had 283 wallets, about $14,384 each. The Leganés draw market had 2,123 wallets at about $43 each. Volume tells you where a few large accounts are. Wallet count is closer to the crowd, and a dashboard that shows only one of the two hides half the picture. Row 3 deserves a second look, though. It had 2,188 orders from 2,123 wallets at an average price of 0.97. One small order each on a near-certain outcome is not what a crowd of fans looks like, so check orders per wallet before you call a market popular. ## Slice by subject > *"Show the biggest politics markets over the last 7 days."* `polymarket_top_markets` takes a category (sports, crypto, politics, esports, weather, stocks, mentions, entertainment) and a title search, together or alone. | # | Market | 7-day volume | Wallets | |---|---|---:|---:| | 1 | Will United Russia (ER) gain the most seats in the next Russian parliamentary election? | $7,895,729 | 894 | | 2 | Will New People (NL) gain the most seats in the next Russian parliamentary election? | $1,391,623 | 440 | | 3 | Will United Russia (ER) win the most seats in the next Russian parliamentary election? | $827,239 | 137 | | 4 | Will AfD win the most seats in the 2026 Mecklenburg-Vorpommern elections? | $419,479 | 332 | | 5 | Will Flávio Bolsonaro win the 2026 Brazilian presidential election? | $329,878 | 191 | Read rows 1 and 3 twice. Their titles differ by one word, "gain" and "win", and they are different questions. `polymarket_market_info` returns each market's written rules: row 3 asks which party wins the most seats, and row 1 asks which party's seat count rises the most compared with before the election. Row 1 traded almost ten times as much. Every answer carries a question id. Pass that id to the next tool instead of the title, or you may chart the wrong market. ## How did the odds move? > *"Show the daily close and volume for Yes on the first market since 12 September."* `polymarket_market_price_history` with a one-day interval. Intervals run from 1 second to 1 day. | Day | Yes close | Volume on Yes | |---|---:|---:| | 12 Sep | 0.79 | $69,175 | | 13 Sep | 0.80 | $17,215 | | 14 Sep | 0.77 | $69,756 | | 15 Sep | 0.77 | $170,235 | | 16 Sep | 0.73 | $474,884 | | 17 Sep | 0.76 | $183,599 | | 18 Sep | 0.83 | $833,802 | | 19 Sep | 0.81 | $1,163,964 | | 20 Sep | 0.985 | $3,528,998 | | 21 Sep, part day | 0.999 | $786,474 | A price is dollars per share between 0 and 1, so 0.79 is a 79% chance. For eight days the close sat between 73% and 83%. On 20 September it went from 0.81 to 0.985, and that one day carried 48% of the ten days' volume. Then look at the last row: $786,474 changed hands at an average of 0.9946 when the question was all but settled. Those buyers paid 99.5 cents for a dollar. `polymarket_market_events` puts the official resolution at 12:43 UTC on 21 September, one minute after the last Yes trade. The same tool's `Vwap` column is the safer number on a thin day. A close is one fill, and on a quiet market that fill can be a few cents of dust. ## How big was it over its life? > *"What are the odds and lifetime volume on that market?"* `polymarket_market_odds` returns one row per outcome. | Outcome | Price | Lifetime volume | Lifetime trades | |---|---:|---:|---:| | Yes | 0.999 | $11,103,433 | 64,523 | | No | 0.001 | $2,026,043 | 51,476 | That is $13.1 million across 115,999 trades since the first one on 7 January 2026. Add an `at_time` and the same call gives the odds as they stood at any past moment, which is how you check what the market believed when a piece of news broke. ## Who holds what is left? > *"Who holds the most Yes shares in that market?"* `polymarket_outcome_holders`: | # | Holder | Yes shares | Share of all Yes | First acquired | |---|---|---:|---:|---| | 1 | `0x59368957...0b7b` | 140,452 | 20.9% | 21 Sep 2026 | | 2 | `0x5c14eb6a...cc49` | 89,422 | 13.3% | 29 Apr 2026 | | 3 | `0x7818687f...d185` | 45,000 | 6.7% | 12 Aug 2026 | | 4 | `0x58490840...4986` | 26,300 | 3.9% | 12 Sep 2026 | | 5 | `0x4a86dfe0...501e` | 26,047 | 3.9% | 19 Sep 2026 | 4,628 addresses still hold Yes, and five of them hold 48.8% of the 671,029 shares outstanding. The largest holder first acquired its shares on the morning of 21 September, a day when Yes never traded below 98 cents. Balances are rebuilt from every share movement, plain transfers included, so they are holdings and not a guess from the order tape. One caution the tool gives itself: a holder of record is often a proxy contract or a market maker's address, so do not read each row as one person. Run the list through `labels_for_addresses` first. Here it named one of the five, number 3, as a Polymarket deposit address. ## A prompt you can reuse > *"For Polymarket over the last 24 hours, give me two top-10 lists, by volume and by number of wallets, and mark any market on both. For the largest market, show the daily Yes close and volume for the past two weeks, the lifetime volume per outcome, and the five largest holders of Yes with their share of supply."* ## What to know before you rely on it - **Read-only.** No order placement and no order book depth. - **One market at a time below the rankings.** There is no single call for all-of-Polymarket volume per day. The rankings cover many markets; history, odds and holders take one question id. - **A few minutes behind.** Calls on this page trailed the clock by 12 to 15 minutes. A window of an hour or two can be partly unrecorded, and the first row of each answer says so. - **History starts in September 2025.** - **Categories are a best-effort sort.** They come from each market's own wording, and sports and crypto together make up about three quarters of all markets. - **Volume counts resting orders by default.** That is the right basis for market volume. Ask for taker orders if you want the aggressive side only. ## Related - [Polymarket MCP server](/docs/mcp/polymarket/): all 14 tools. - [Track Polymarket whales and top traders](/docs/mcp/polymarket-whale-tracker/): the same method pointed at wallets. - [Polymarket GraphQL API](/docs/examples/polymarket-api/) and [Polymarket Parquet exports](/docs/cloud/polymarket/): the same data in code or in a warehouse, for a dashboard that runs by itself. Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-polymarket-analytics#pricing). --- ## Polymarket Historical Data - Parquet, S3, Snowflake, BigQuery URL: https://docs.bitquery.io/docs/cloud/polymarket/ Polymarket historical data as Parquet: on-chain trades, prices and settlements with market question and outcome labels, delivered to S3, Snowflake or BigQuery. # Polymarket Historical Data Bitquery provides **Polymarket historical data** as **Parquet files** covering on-chain trades, outcome prices and settlements, already joined with the market question, outcome label and collateral token. It is built for backtesting, research, leaderboards and data lake integrations where paging through a REST API is too slow. These datasets can be hosted directly in your own cloud storage (for example, **AWS S3**) and queried using engines like **Snowflake, BigQuery, Athena, Spark, DuckDB, etc**. Polymarket runs on **Polygon (Matic)**, so all Polymarket datasets live under the `matic/` prefix. ## Which Polymarket data source should I use? | Need | Use | | --- | --- | | Last ~7 days, ad-hoc queries and aggregations | [Polymarket API](/docs/examples/polymarket-api/) (GraphQL, `dataset: realtime`) | | Live trades, whale alerts, odds as they change | [GraphQL subscriptions](/docs/examples/polymarket-api/) or [Kafka streams](/docs/streams/kafka-streaming-concepts/) | | History since September 2025, backtests, model training, warehouse joins | **Parquet exports on this page** | Polymarket moved to new CTF Exchange contracts and pUSD collateral in April 2026. Each row carries `Trade_Prediction_Marketplace_SmartContract` and `Trade_Prediction_CollateralToken_*`, so you can separate trades before and after the migration. ## Available Polymarket Topics For Polymarket, Bitquery currently provides the following datasets: - **Prediction Trades** – Outcome-token trades with market question, outcome label, price, and collateral amounts - **Prediction Settlements** – Position splits, merges and payout redemptions - **DEX Trades** – Polymarket trades in the standard EVM DEX trades schema ## Sample Polymarket Cloud Dataset You can explore schemas and validate your tooling using the **public Polymarket sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/polymarket](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/polymarket) **Sample Parquet downloads (public S3)** - **Prediction Trades** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet) - **Prediction Settlements** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/PredictionSettlements/85230000_85230049.parquet) - **DEX Trades** – [Download](https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/dex_trades/polymarket/83713800_83713849.parquet) ## Polymarket Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── matic/ ├── polymarket/ │ ├── prediction_trades/ │ │ ├── 84735000_84735049.parquet │ │ ├── 84735050_84735099.parquet │ │ └── ... │ └── PredictionSettlements/ │ ├── 85230000_85230049.parquet │ ├── 85230050_85230099.parquet │ └── ... └── dex_trades/ └── polymarket/ ├── 83713800_83713849.parquet ├── 83713850_83713899.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Example: ``` 84735000_84735049.parquet ``` ## Dataset Fields **Prediction Trades** records an outcome-token trade together with the market it belongs to: - `Block_Number`, `Block_Time`, `Transaction_Hash`, `Transaction_From` - `Trade_OutcomeTrade_*` – buyer, seller, order id, amount, collateral amount, price, `IsOutcomeBuy`, plus USD equivalents - `Trade_Prediction_Question_*` – market question title, id, market id, resolution source, image, creation time - `Trade_Prediction_Outcome_*` – outcome id, index, and label (for example `Down`) - `Trade_Prediction_OutcomeToken_*` / `Trade_Prediction_CollateralToken_*` – ERC-1155 outcome token and ERC-20 collateral token (for example USDC) details - `Trade_Prediction_Marketplace_*` – protocol name, family (`Gnosis_CTF`), version, and contract **Prediction Settlements** records position splits, merges and redemptions for a holder: - `Settlement_EventType` (for example `Redemption`), `Settlement_Holder`, `Settlement_OutcomeTokenIds` - `Settlement_Amounts_*` – amount and collateral amount, with USD equivalents - `Settlement_Prediction_*` – same question, outcome, token, and marketplace structure as trades **DEX Trades** uses the standard EVM DEX trades schema documented on the [EVM Data](/docs/cloud/evm/) page. ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=polymarket&utm_source=docs&utm_medium=referral&utm_campaign=datastore&utm_content=cloud-polymarket), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Datasets you can buy on the Data Store: - [Polymarket](https://bitquery.io/datastore/datasets/polymarket?utm_source=docs&utm_medium=referral&utm_campaign=datastore&utm_content=cloud-polymarket): order fills, position splits, merges and payouts, with market titles, outcomes and USD values ## Reading Files with DuckDB You need no key or client library. Point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet') LIMIT 10; ``` ## Example: daily Polymarket volume from the sample file DuckDB can aggregate the Parquet file over HTTPS without loading it anywhere first. Swap the single file for a glob over your own bucket to run it across the full history. ```sql SELECT Trade_Prediction_Question_Title AS market, Trade_Prediction_Outcome_Label AS outcome, count(*) AS trades, sum(CAST(Trade_OutcomeTrade_CollateralAmountInUSD AS DOUBLE)) AS volume_usd, avg(CAST(Trade_OutcomeTrade_Price AS DOUBLE)) AS avg_price FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet') GROUP BY 1, 2 ORDER BY volume_usd DESC LIMIT 20; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/matic/polymarket/prediction_trades/84735000_84735049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access Cloud data dumps are built for **batch analytics and historical workloads**. If you require **low-latency or streaming Polymarket data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - [**GraphQL subscriptions and queries**](/docs/examples/polymarket-api/) for trades, odds, wallets and whale alerts See also [Polymarket API vs Bitquery Polymarket API](/docs/API-Blog/polymarket-api-vs-bitquery-polymarket-api/) for how this compares with Polymarket's own Data API. --- ## Polymarket MCP Server for Claude, ChatGPT and Cursor URL: https://docs.bitquery.io/docs/mcp/polymarket/ Give Claude, ChatGPT, Cursor or your own AI agent live Polymarket data: top markets, odds, price history, large fills, top wallets and disputed resolutions, from on-chain data. Read-only. # Polymarket MCP Server The Bitquery MCP server gives an AI client 14 tools for Polymarket data. You ask a question in Claude, ChatGPT, Cursor, VS Code or Codex, the agent picks a tool, and rows come back from Bitquery's on-chain index of Polymarket on Polygon. It reads data only. It cannot place, change or cancel an order. To trade, use Polymarket's own CLOB API; to research markets, wallets and odds, use this. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Other clients take the same URL. Steps for each are in the [MCP server install guide](/docs/mcp/mcp-server/). A 38-second demo, [Polymarket and Hyperliquid data in ChatGPT and Claude](https://www.youtube.com/watch?v=IwuIlcKsANk), shows the server answering questions like the ones below. Every figure on this page came from a call to the production server on 21 September 2026, between 09:00 and 09:10 UTC. Polymarket moves fast, so your numbers will differ. ## What can I ask? ### Which markets are people trading right now? > *"What are the five most traded Polymarket markets in the last 24 hours?"* The agent calls `polymarket_top_markets`. | # | Market | 24h volume | Orders | Wallets | |---|---|---:|---:|---:| | 1 | Colts vs. Chiefs | $4,114,943 | 9,124 | 292 | | 2 | Will United Russia (ER) gain the most seats in the next Russian parliamentary election? | $4,065,436 | 8,532 | 565 | | 3 | Will Manchester City FC win on 2026-09-20? | $1,918,415 | 5,523 | 386 | | 4 | Eagles vs. Titans | $1,800,372 | 4,075 | 188 | | 5 | Packers vs. Jets | $1,666,912 | 4,181 | 190 | The first row of every answer states the window that was ranked and how far the data trails the clock. On this call it was 14 minutes behind. A short window can therefore look quieter than it was, and the tool says so instead of reporting an empty market. ### What are the odds on a market I only know by name? > *"Find the open Polymarket markets about the Fed rate, then give me the odds on the first one."* Two calls. `polymarket_find_markets` with the text "Fed rate" returned three open markets, all created on 16 September 2026: "Another Fed rate hike in 2026?", "Fed rate cut by July 2027 meeting?" and "Fed rate cut by January 2027 meeting?". Then `polymarket_market_odds` on the first: | Outcome | Price | Implied probability | Lifetime volume | |---|---:|---:|---:| | Yes | 0.86 | 86% | $24,260 | | No | 0.15 | 15% | $8,783 | A price is dollars per share between 0 and 1, which is the market's own probability. The two sides add up to 1.01 here because the last fill on each side happened at a different minute. When one side's last trade is old, ask for the 24-hour VWAP, which the same tool returns. Search text is a plain substring. Asking for "Fed" alone also returned tennis markets for a player named Fedor. Give the agent two words when one is ambiguous. ### How did the odds move? > *"Show the daily close for Yes on the United Russia market over the last week."* `polymarket_market_price_history` with a one-day interval: | Day (UTC) | Close | Volume | |---|---:|---:| | 15 Sep | 0.77 | $170,235 | | 16 Sep | 0.73 | $474,884 | | 17 Sep | 0.76 | $183,599 | | 18 Sep | 0.83 | $833,802 | | 19 Sep | 0.81 | $1,163,964 | | 20 Sep | 0.985 | $3,528,998 | | 21 Sep (to 09:00) | 0.998 | $544,109 | Volume tripled on the day the price went from 0.81 to 0.985. Intervals run from one second to one day, and days with no trades are left out instead of being filled in. ### Who is behind the volume? > *"Who traded the most in that market, and is the top wallet a directional bettor or a market maker?"* `polymarket_top_traders` for the one market, over its whole history: | Wallet | Volume | Bought | Sold | Orders | |---|---:|---:|---:|---:| | `0xf2f6…5817` | $934,582 | $608,832 | $325,750 | 1,700 | | `0x369f…873e` | $701,366 | $421,191 | $280,175 | 498 | | `0x6575…b198` | $570,815 | $570,815 | $0 | 364 | | `0x44c1…ebc1` | $414,423 | $414,423 | $0 | 102 | | `0xc021…1fa8` | $413,220 | $297,140 | $116,080 | 511 | This list ranks by dollars traded. It says nothing about profit. The follow-up call shows why that matters: `polymarket_trader_summary` on the top wallet returns 51,391 lifetime orders across 1,237 markets and $19.55 million traded, and 48,736 of those orders (95%) were resting orders on the book. That is the footprint of a market maker. Wallets three and four are the opposite: buys only, and both placed their first order in this market within the last week (16 and 18 September). ### Where are the big fills? > *"Show the latest fills above $10,000 in that market."* `polymarket_market_trades` with a minimum size, newest four: | Time (UTC) | Wallet | Side | Price | Size | |---|---|---|---:|---:| | 08:32:02 | `0xc021…1fa8` | sell Yes | 0.998 | $49,900 | | 08:32:02 | `0xb24c…eefe` | sell Yes | 0.998 | $21,153 | | 07:51:50 | `0xb24c…eefe` | sell Yes | 0.997 | $13,757 | | 06:53:51 | `0xe25b…0f1b` | sell Yes | 0.997 | $60,782 | Read side and outcome together. Buying No is the same bet as selling Yes. Most fills on a busy market are under a dollar, so a size floor of $100 or $1,000 is what turns the tape into something readable. ### Was a resolution challenged? > *"Which Polymarket outcomes were disputed in the last day?"* The four newest rows from `polymarket_market_disputes` fell between 08:27 and 08:31 UTC, all on one tennis match (M15 Baku, Aleshchev vs Skvortcov) and its set-handicap and total-sets markets. Two wallets raised them, and all four were against answers proposed by the same address. A dispute restarts resolution; it is not a verdict, and the market often settles to the same outcome afterwards. Challenge records start on 9 March 2026. For an older market an empty answer means "not covered", and the tool's own text tells the agent to say so. ## Build a Polymarket AI agent with Claude or ChatGPT An agent that reasons about prediction markets needs current odds, fills and wallet history, and a language model has none of those by itself. This server is that data layer. Any client or framework that speaks MCP can call the same 14 tools, so a Polymarket AI agent built on Claude, ChatGPT or an open model reads the same numbers a person gets in chat. Three jobs people give such an agent: - **A morning brief.** "List the ten most traded markets in the last 24 hours, the odds on each, and any whose Yes price moved more than 10 points since yesterday." That chains `polymarket_top_markets`, `polymarket_market_odds` and `polymarket_market_price_history`. A worked version is in [Polymarket analytics with AI](/docs/mcp/polymarket-analytics/). - **A wallet watch.** Rank wallets, drop the market makers, and score the rest. The full walk-through is in [Track Polymarket whales and top traders](/docs/mcp/polymarket-whale-tracker/). - **A resolution check.** Before trusting a settled market, ask `polymarket_market_disputes` whether the answer was challenged. The agent still cannot trade through this server. Pair it with Polymarket's CLOB API if you want it to place orders, and keep a person in charge of that step. ## All 14 Polymarket tools | Tool | Use it for | |---|---| | `polymarket_find_markets` | Find markets by title text or category and get their question id | | `polymarket_market_info` | One market's detail: outcome tokens, oracle, collateral, resolution rules | | `polymarket_market_odds` | Current price and implied probability per outcome, or as of a past moment | | `polymarket_market_price_history` | OHLC, VWAP and volume per interval, 1 second to 1 day | | `polymarket_market_trades` | Individual fills, newest first, with a size floor and a per-wallet filter | | `polymarket_market_events` | Created and resolved lifecycle events | | `polymarket_market_disputes` | Challenged answers and rule changes after launch | | `polymarket_top_markets` | Markets ranked by volume, orders, wallets or fees in a window | | `polymarket_top_traders` | Wallets ranked by volume, across all markets or inside one | | `polymarket_trader_summary` | One wallet's lifetime card: first and last trade, volume, markets, maker share | | `polymarket_trader_activity` | One wallet's breakdown by market and outcome | | `polymarket_trader_positions` | What a wallet still holds | | `polymarket_outcome_holders` | Who holds an outcome token | | `polymarket_settlements` | Redemptions, splits and merges | ## What to know before you rely on it - **Read-only.** No order placement, no order book depth. Fills are settled on-chain orders. - **A few minutes behind.** Calls on this page trailed the clock by 12 to 15 minutes. Every answer reports its own lag. - **History starts in September 2025.** A wallet whose "first trade" is 1 September 2025 may have traded earlier. Dispute records start on 9 March 2026. - **No profit and loss in the rankings.** `polymarket_top_traders` is volume only. - **Collateral changed in 2026.** Older fills settle in USDC, newer ones in pUSD. The tools report which one each market used. ## MCP, GraphQL or the official API? | You want to | Use | |---|---| | Place or cancel orders, read the order book | Polymarket's CLOB API | | Ask questions in a chat or let an agent research a market | This MCP server | | Build a dashboard, alert or backfill in code | The [Bitquery Polymarket GraphQL API](/docs/examples/polymarket-api/), with WebSocket and Kafka streams | | Load full history into a warehouse | [Polymarket Parquet exports](/docs/cloud/polymarket/) | Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-polymarket#pricing). --- ## Polymarket Whale Tracker: Follow Top Traders with Claude URL: https://docs.bitquery.io/docs/mcp/polymarket-whale-tracker/ Track Polymarket whales and top traders from a chat: rank wallets by volume, tell market makers from bettors, read a wallet's bets, profit and open positions, and see its largest fills. Read-only. # Track Polymarket Whales and Top Traders with Claude A whale tracker answers three questions. Who is trading the most? Are they betting or just making markets? And is a given trader winning? This page walks through all three with the [Bitquery MCP server](/docs/mcp/polymarket/) in Claude, ChatGPT or Cursor, using six of its 14 Polymarket tools and the address-label tool. It reads data only. It cannot place or copy a trade. What it gives you is the research step before you decide whether anyone is worth following. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` A 38-second demo, [Polymarket and Hyperliquid data in ChatGPT and Claude](https://www.youtube.com/watch?v=IwuIlcKsANk), shows the server at work in a chat. Every figure below came from the production server on 21 September 2026, between 12:22 and 12:27 UTC, with data 13 to 16 minutes behind the clock. ## Step 1: Rank traders by what they traded > *"Who were the top Polymarket traders by volume over the last 7 days?"* The agent calls `polymarket_top_traders` with a 168-hour window. | # | Address | 7-day volume | Orders | Orders that took liquidity | Outcomes traded | |---|---|---:|---:|---:|---:| | 1 | `0x2005d16a...75ea` | $24,961,757 | 91,987 | 14.8% | 11,142 | | 2 | `0xfe787d2d...0319` | $24,249,729 | 63,289 | 7.0% | 5,989 | | 3 | `0x2c335066...0563` | $21,549,928 | 7,243 | 10.3% | 551 | | 4 | `0x821dab05...cf16` | $20,905,918 | 152,003 | 79.6% | 29,675 | | 5 | `0x2a696600...d2f7` | $18,645,208 | 144,594 | 100% | 28,702 | | 6 | `0x52685279...135d` | $16,084,516 | 31,618 | 33.3% | 4,423 | | 7 | `0x224a89db...a3d5` | $14,817,566 | 17,551 | 14.6% | 917 | | 8 | `0x63cf8544...e4d0` | $12,104,594 | 303 | 11.2% | 6 | This is a volume ranking. The tool computes no profit here and says so in its first row. The two right-hand columns already sort the list into types. Seven of them placed thousands of orders across hundreds or thousands of outcomes. Number 8 reached $12.1 million with 303 orders on six. ## Step 2: Tell a market maker from a bettor > *"Give me the lifetime summary of number 1 and number 8."* `polymarket_trader_summary` returns one row per address, covering its whole recorded history. | | Number 1 | Number 8 | |---|---:|---:| | First trade | 1 September 2025 | 16 September 2026 | | Orders | 4,606,941 | 303 | | Orders resting on the book | 92.5% | 88.8% | | Markets traded | 141,322 | 6 | | Lifetime volume | $597,996,502 | $12,104,594 | Number 1 has quoted 141,322 markets since the first day of recorded history. That is the footprint of a market maker, which quotes both sides for the spread, so its trades say little about who will win. Number 8 appeared five days before this page was written, bet on six sports results in two days and stopped. That is what people mean by a whale. ## Step 3: Read what the whale bet on > *"What did 0x63cf8544631c31e9fcea0b02141dd24d01d6e4d0 bet on this week?"* `polymarket_trader_activity` breaks its orders out by market and outcome. | Market | Bought | Spent | Average price | |---|---|---:|---:| | Lions vs. Bills | Bills | $3,329,463 | 0.70 | | Will Real Betis win on 17 September? | Yes | $2,130,921 | 0.65 | | Will AC Milan win on 16 September? | Yes | $1,975,524 | 0.45 | | Will Chelsea FC win on 18 September? | Yes | $1,070,173 | 0.38 | | Will Villarreal CF win on 17 September? | Yes | $90,000 | 0.45 | | Will Real Sociedad win on 17 September? | Yes | $36,660 | 0.33 | A price is dollars per share between 0 and 1, so 0.70 means it paid as if Bills had a 70% chance. ## Step 4: Score it > *"Show its positions, open and closed, with profit and loss."* `polymarket_trader_positions` with status set to all adds how each market resolved and, where it can, the profit. | Market | Result | Profit or loss (tool) | |---|---|---:| | Real Betis | Won, sold at 0.999 | +$1,136,626 | | Villarreal | Won, sold at 0.999 | +$109,800 | | Real Sociedad | Lost, sold at 0.04 | -$32,205 | | Chelsea | Lost, still holds 2.8 million worthless shares | -$1,070,216 | | Bills | Won | not computed | | AC Milan | Lost | not computed | On the last two rows the tool leaves profit empty and explains why: the shares left the address without a trade, so no sale price exists. It reports the share count as exact and will not guess the rest. The Bills shares left at 03:46:30 UTC on 18 September. `polymarket_settlements` shows other Bills holders being paid out through a relayer contract in that same second, which fits a payout, though no record ties this address to one. The arithmetic from here is ours, not the tool's. The four scored markets sum to +$144,005. The Bills shares, 4,726,883 of them, paid $1 each against $3,329,463 spent, a gain of $1,397,421 if they were cashed at the payout, which is our assumption. The AC Milan shares paid nothing, a loss of $1,975,524. Across six markets that is about -$434,000, before $149,358 of trading fees. So the eighth-largest trader of the week won three of six bets and still lost money. Volume made it look worth following. The positions say otherwise. ## Step 5: Watch the fills > *"Show its orders in Lions vs. Bills."* `polymarket_market_trades` with the trader filter lists each order. | Time (UTC, 17 September) | Price | Size | |---|---:|---:| | 20:28:52 | 0.71 | $698,710 | | 20:28:54 | 0.69 | $56,484 | | 20:28:54 | 0.70 | $1,989,229 | | 20:28:54 | 0.70 | $356,534 | | 20:30:04 | 0.70 | $32,106 | | 21:29:45 | 0.70 | $196,399 | $3.1 million went in across four orders inside two seconds, all of them taking liquidity from the book. Drop the trader filter and set a size floor instead, and the same tool becomes a live feed of large fills for any market. To put a name on an address, pass the list to `labels_for_addresses`. For four of the addresses above it returned a label on three: two carry a Polymarket account name and number 1 is tagged only as a Polymarket proxy wallet. Number 8 has no label. ## A prompt you can reuse > *"Rank Polymarket wallets by 7-day volume. Drop any with more than 1,000 orders or more than 100 outcomes traded. For the rest, show the lifetime summary, then open and closed positions with profit and loss, and tell me which markets they hold now."* The order and outcome cut-offs are a starting point taken from the table in step 1. Tune them to the market you follow. ## What to know before you rely on it - **Read-only.** No order placement and no copy trading. To place orders use Polymarket's own CLOB API. - **Rankings are by volume.** Profit lives in `polymarket_trader_positions`, one address at a time. - **Profit is sometimes empty.** When shares arrive or leave without a trade the tool cannot price them and says so. Its own notes put this at roughly a quarter of open positions. - **Profit is before fees.** The fee total comes back as its own column. - **One wallet is not one person.** A trader can split bets across wallets, and these tools do not link them. - **A few minutes behind.** Calls on this page trailed the clock by 13 to 16 minutes. - **History starts in September 2025.** A first trade on 1 September 2025 may be older than it looks. ## Related - [Polymarket MCP server](/docs/mcp/polymarket/): all 14 tools, with odds, price history and disputes. - [Polymarket GraphQL API](/docs/examples/polymarket-api/): the same data in code, with WebSocket and Kafka streams, for a tracker that runs by itself. - [Polymarket earnings bets that beat the odds on KPMG's clients](https://bitquery.io/investigations/polymarket-insider-trading-kpmg-clients?ref=docs-mcp-polymarket-whales): a Bitquery investigation that scored a group of wallets the same way. Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-polymarket-whales#pricing). --- ## 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 Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/pumpfun/ Pump.fun token creations, migrations, trades, pools and OHLCV candles as Parquet, with a free sample, the file naming and DuckDB and Python examples. # Pump.fun Data Bitquery provides **Pump.fun data 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` / `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 ``` ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=solana), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Datasets you can buy on the Data Store: - [Pump.fun](https://bitquery.io/datastore/datasets/pumpfun) — bonding-curve trades, token creations, migrations, pools and OHLCV - [PumpSwap](https://bitquery.io/datastore/datasets/pumpswap) — trades on the AMM that Pump.fun tokens migrate to ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/dex_trades/pumpfun/390740000_390740049.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/dex_trades/pumpfun/390740000_390740049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access 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 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 ================================================================================ ``` --- ## 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) --- ## 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/) --- ## 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)** | < 500ms | Solana, Ultra-Low Latency, MEV | [gRPC Docs](/docs/grpc/solana/introduction/) | ## Blockchain Data Streaming Technologies Overview ### Real-time GraphQL Subscriptions (WebSocket API) {#websocket-graphql-subscriptions} **Multichain Support** | **Live Data** | **Beginner-friendly** Our **WebSocket-based GraphQL subscriptions** provide **real-time cryptocurrency data** with very high filtering and formatting capabilities. You can filter by wallet addresses, token contracts, transaction amounts, USD values, and much more directly in your queries. Perfect for **crypto trading applications**, **DeFi dashboards**, and **blockchain analytics platforms**. - **Endpoint**: `wss://streaming.bitquery.io/graphql` - **Protocols**: `graphql-transport-ws`, `graphql-ws` - **Latency**: ~1 second (network + parsing overhead) - **Use Cases**: **Crypto trading dashboards**, **DeFi interfaces**, **real-time portfolio monitoring** > Streaming live **token trades or prices**? Subscribe to the [Trading API](/docs/trading/trading-data-overview/) cubes (`Trading.Trades`, `Trading.Tokens`, `Trading.Pairs`) rather than raw per-chain `DEXTrades` — one stream covers 10 chains with USD prices, market cap, and MEV-filtered trades built in. ### High-Performance Kafka Blockchain Streams {#kafka-streams} **Multichain Support** | **Ultra-low latency** | **High throughput** High-performance, **low-latency blockchain data streaming** for mission-critical **cryptocurrency trading systems** requiring maximum reliability and scalability. **No server-side filtering available** – you receive complete blockchain transaction data and must filter on the client side. Ideal for **MEV bots**, **arbitrage trading systems**, and **high-frequency DeFi applications** that need complete data streams. - **Endpoints**: `rpk0.bitquery.io:9092`, `rpk1.bitquery.io:9092`, `rpk2.bitquery.io:9092` - **Protocol**: Apache Kafka with SASL authentication - **Latency**: < 500ms (sub-second) - **Use Cases**: **[Cryptocurrency trading bots](/docs/streams/sniper-trade-using-bitquery-kafka-stream/)**, **real-time DeFi applications**, **MEV bot development**, **high-frequency blockchain monitoring** ### Ultra-fast gRPC Streams (CoreCast) {#corecast-grpc-streams} **Solana Blockchain** | **Sub-100ms latency** | **Smart filtering** Our newest **ultra-low latency streaming technology** provides the fastest **Solana blockchain data** with server-side filtering capabilities and efficient binary serialization. Perfect for **Solana trading bots** and **MEV applications**. Filtering is available but more limited compared to WebSocket's extensive filtering options. - **Endpoint**: `corecast.bitquery.io` - **Protocol**: gRPC with Protobuf - **Latency**: < 500ms (low latency) - **Use Cases**: **Solana trading bots**, **Solana MEV applications**, **real-time Solana DeFi protocols**, **Jupiter aggregator monitoring** ## Feature Comparison | Feature / Stream | WebSocket | Kafka | CoreCast (Smart gRPC) | |------------------|-----------|-------|----------------------| | **Latency** | ~1 second (network + parsing overhead) | < 500 ms (sub-second) | < 500ms ms (low latency) | | **Filtering** | ✅ Very high capability: addresses, tokens, pools, value thresholds, USD values, complex conditions | ❌ No filtering - complete data stream | ✅ Basic filtering: addresses, tokens, pools, thresholds (limited compared to WebSocket) | | **USD Values** | ✅ Built-in | ❌ Not available (Available in different topic) | ❌ Not available (planned) | | **Reliability** | Auto-reconnect via GraphQL, but no replay | ✅ Retention available, replay from checkpoints | Query GraphQL, no replay support | | **Retention / Replay** | ❌ No | ✅ Yes, configurable retention window | ❌ No | | **Schema / Data Format** | JSON over WebSocket | Avro/Protobuf over Kafka | Protobuf (typed contracts) | | **Delivery Guarantee** | At-most-once | ✅ At-least-once (can configure exactly-once) | At-most-once | | **Integration Complexity** | Easiest for frontends, explorers, bots | Requires infra (Kafka cluster, consumers) | Lightweight, good for backend apps and trading strategies | | **Bandwidth Efficiency** | Medium (JSON, more verbose) | High (binary encoding, batching) | Medium (Protobuf, direct streams) | | **Use Case Fit** | Dashboards, explorers, analytics needing USD values & rich filters | Mission-critical infra: indexing, ETL pipelines, 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/)** - **[Arc Mainnet](/docs/blockchain/arc-mainnet/)** (GraphQL and WebSocket subscriptions) - **[Arc Testnet](/docs/blockchain/arc-testnet/)** - **[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) --- 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. --- ## 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. --- ## 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 Chain Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/robinhood/ Robinhood Chain DEX trades, transfers, balances, events and calls as Parquet, with column schemas and notes on USDG, tokenized equities and decimals. # Robinhood Chain Data Bitquery provides **Robinhood Chain data 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 side of a trade in the sample — 150 of 554 trade sides — followed by WETH (93) and native ETH (38). A pricing or volume query ported from Ethereum that hardcodes the USDC address returns **zero rows** here. ### 5. Tokenized Equities Share the ERC-20 Schema `NVDA`, `SPY`, and `SLV` are ordinary ERC-20 contracts with 18 decimals, indistinguishable from a memecoin by schema alone. **54 of the sample's 277 trades** have an equity token on one side — a fifth of all trading. | Symbol | Contract | Decimals | | --- | --- | ---: | | `NVDA` | `0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec` | 18 | | `SPY` | `0x117cc2133c37b721f49de2a7a74833232b3b4c0c` | 18 | | `SLV` | `0x411efb0e7f985935daec3d4c3ebaea0d0ad7d89f` | 18 | Maintain a contract allowlist if you need to separate RWA flow from crypto-native flow. Symbol matching is not safe: anyone can deploy a token called `NVDA`. ## DEX Venues Trades in the sample spread across six protocols, including **Pons**, which is native to Robinhood Chain: | `Trade_Dex_ProtocolName` | Family | Trades | | --- | --- | ---: | | `uniswap_v4` | Uniswap | 109 | | `uniswap_v3` | Uniswap | 106 | | `pons_v2` | Pons | 49 | | `uniswap_v2` | Uniswap | 7 | | `pancakeswap_infinity` | PancakeSwapInfinity | 5 | | `aerodrome_v1` | Aerodrome | 1 | Group on `Trade_Dex_ProtocolFamily` for venue-level aggregates and `Trade_Dex_ProtocolName` to separate versions. ## Topic Schemas Columns listed in [Common Columns](#common-columns) are omitted below. ### dex_trades One row per DEX trade. 277 rows in the sample, across 159 transactions. | Column | Type | Description | | --- | --- | --- | | `Trade_Buy_Amount`, `Trade_Sell_Amount` | string | Amounts, as decimal strings | | `Trade_Buy_AmountInUSD`, `Trade_Sell_AmountInUSD` | float64 | USD value of each side | | `Trade_Buy_Buyer`, `Trade_Buy_Seller` | string | Counterparties on the buy side | | `Trade_Sell_Buyer`, `Trade_Sell_Seller` | string | Counterparties on the sell side | | `Trade_Buy_Price`, `Trade_Buy_PriceInUSD` | float64 | Execution price, in the paired token and in USD | | `Trade_*_Currency_*` | mixed | `Symbol`, `Name`, `SmartContract`, `Decimals`, `ProtocolName`, `Fungible`, `HasURI` per side | | `Trade_Dex_SmartContract` | `string` | Router or pool manager contract | | `Trade_Dex_ProtocolName`, `_ProtocolFamily`, `_ProtocolVersion` | string | Venue identification | | `Trade_Dex_Pair_*` | mixed | Pair token metadata, where the protocol exposes one | | `Trade_Fees` | `string` | JSON array of `[Amount, AmountInUSD, [Currency…], Payer, Recipient]` | | `Trade_Index` | `uint32` | Trade position within the transaction | | `Trade_PriceAsymmetry` | `float64` | Price divergence between the two sides | | `Trade_Sender` | `string` | Address that initiated the swap | ### transfers One row per value movement, native and ERC-20. 1,374 rows in the sample, across 200 transactions. | Column | Type | Description | | --- | --- | --- | | `Transfer_Amount` | `string` | Amount, as a decimal string | | `Transfer_AmountInUSD` | `float64` | USD value | | `Transfer_Sender`, `Transfer_Receiver` | string | Counterparties | | `Transfer_Type` | `string` | `token`, `call`, or `transaction` — see note 3 above | | `Transfer_Currency_SmartContract` | `string` | Token contract; `0x` for native ETH | | `Transfer_Currency_Native` | `string` | `"true"` for native ETH | | `Transfer_Currency_Symbol`, `_Name`, `_Decimals`, `_ProtocolName` | mixed | Token metadata | | `Transfer_Currency_Fungible` | `string` | `"false"` marks NFTs | | `Transfer_Id` | `string` | Token id for non-fungible transfers | | `Transfer_Index` | `uint32` | Position within the transaction | | `Transfer_URI` | `string` | Token URI, for NFTs | ### balances Balance snapshot — levels, not deltas. 858 rows covering 427 distinct addresses in the sample. | Column | Type | Description | | --- | --- | --- | | `Balance_Address` | `string` | Account holding the balance | | `Balance_Amount` | `string` | Balance level, as a decimal string | | `Balance_FirstChangeTime`, `_LastChangeTime` | datetime | First and last change in the covered range | | `Balance_UpdateCount` | `uint64` | Number of balance changes in the range | | `Balance_RowCount` | `uint64` | Always `1` — a per-row marker | | `Currency_Name`, `_Symbol`, `_SmartContract`, `_ProtocolName` | string | Currency metadata | Only accounts whose balance changed in the range appear. Native ETH is 284 of the sample's 858 rows, ERC-20s 570, and ERC-721s 4. ### events One row per decoded log. 2,211 rows across 33 distinct decoded event names in the sample, plus 384 logs with no decoded name. | Column | Type | Description | | --- | --- | --- | | `Arguments` | `string` | JSON array of `[Index, Name, Path, Type, Value]` | | `Log_Signature_Name`, `_Signature`, `_SignatureHash` | string | Decoded event signature — `Transfer` (964), `Swap` (229), `Approval` (194) | | `Log_SmartContract` | `string` | Contract that emitted the log | | `Log_Index`, `Log_Pc` | uint32, uint64 | Log position and program counter | | `LogHeader_Address`, `_Data`, `_Index` | mixed | Raw log address, data, and index | | `Topics_Hash` | list\ | Topic hashes, **without** the `0x` prefix | | `Call_*` | mixed | The call that emitted the log — `From`, `To`, `Gas`, `Signature_Name`, `Value` | | `ChainId` | `uint64` | `4663` on every row | 384 of the sample's rows have an empty `Log_Signature_Name` — logs whose ABI Bitquery has not resolved. Their `LogHeader_Data` and `Topics_Hash` are still present, so you can decode them yourself. ### calls One row per contract call, internal calls included. 7,885 rows in the sample. | Column | Type | Description | | --- | --- | --- | | `Call_From`, `Call_To` | string | Caller and callee | | `Call_Value`, `Call_ValueInUSD` | string, float64 | Native value attached to the call | | `Call_Signature_Name`, `_Signature`, `_SignatureHash` | string | Decoded function — `balanceOf` (2,136), `transfer` (995), `transferFrom` (394) | | `Call_Input`, `Call_Output` | string | Raw calldata and return data | | `Arguments`, `Returns` | string | JSON arrays of `[Index, Name, Path, Type, Value]` | | `StateChanges` | `string` | JSON array of `[Address, ChangeAfterCallIndex, Location, Value]` | | `Call_Gas`, `_GasUsed` | uint64 | Gas supplied and consumed | | `Call_Depth`, `_Index`, `_CallPath` | mixed | Position in the call tree | | `Call_InternalCalls`, `_LogCount` | uint32 | Children and logs produced | | `Call_Success`, `_Reverted`, `_Error` | string | Outcome — strings, not booleans | | `Call_Opcode_Name`, `_Code` | string, uint32 | Call opcode, e.g. `CALL`, `STATICCALL`, `DELEGATECALL` | | `Call_Create`, `_SelfDestruct`, `_Delegated` | string | Contract creation, destruction, and delegation flags | Read-only calls dominate: `balanceOf` alone is 27% of the sample. Filter on `Call_Signature_Name` before aggregating, or you will measure RPC-style reads rather than economic activity. ## Joining Topics Every topic except `balances` carries `Transaction_Hash`, so it is the natural join key. To attach trades to the events that produced them: ```sql SELECT t.Trade_Dex_ProtocolName, t.Trade_Buy_Currency_Symbol, t.Trade_Buy_AmountInUSD, e.Log_Signature_Name FROM robinhood_dex_trades t JOIN robinhood_events e ON t.Transaction_Hash = e.Transaction_Hash WHERE t.TransactionStatus_Success = 'true' AND e.Log_Signature_Name = 'Swap' ``` One transaction fans out to many rows in `calls`, `events`, and `transfers`, so joining two of them on `Transaction_Hash` alone produces a cross product. Aggregate one side first, or add `Block_Number` and the per-row index columns to the join. ## Reading Files in Python ```python from decimal import Decimal BASE = "https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/robinhood/" RANGE = "56600000_56600049" trades = pd.read_parquet(f"{BASE}dex_trades/{RANGE}.parquet") transfers = pd.read_parquet(f"{BASE}transfers/{RANGE}.parquet") # venue mix print(trades.Trade_Dex_ProtocolName.value_counts()) # tokenized equity flow, by contract not symbol EQUITIES = { "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec", # NVDA "0x117cc2133c37b721f49de2a7a74833232b3b4c0c", # SPY "0x411efb0e7f985935daec3d4c3ebaea0d0ad7d89f", # SLV } eq = trades[ trades.Trade_Buy_Currency_SmartContract.isin(EQUITIES) | trades.Trade_Sell_Currency_SmartContract.isin(EQUITIES) ] print(f"equity-side trades: {len(eq)} of {len(trades)}") # native ETH is NOT Transfer_Type == 'token' native = transfers[transfers.Transfer_Currency_Native == "true"] print("native ETH moved:", sum(native.Transfer_Amount.map(Decimal))) print("types carrying it:", native.Transfer_Type.unique()) ``` ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=robinhood), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Datasets you can buy on the Data Store: - [Pons](https://bitquery.io/datastore/datasets/pons) — every Pons launch, bonding-curve trade and graduation on Robinhood Chain, priced in USD ## 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/) --- ## 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 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! ::: --- ## Solana Balance Updates - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/balance/ Solana Balance Updates - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana Balance Updates gRPC Stream The `balance` gRPC Stream provides real-time balance update data for Solana accounts and token accounts. --- ## Overview Subscribe to live balance changes for accounts and token accounts. Each event includes pre/post balances, currency details, and account context. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. ## Configuration To subscribe to balance updates, configure your stream as follows: ```yaml stream: type: "balance" ``` ## Available Data The balance updates stream provides comprehensive balance change information including: - **Transaction details**: Slot, signature, status, fees (in native and USD) - **Account information**: Signers, token accounts, program IDs - **Token context**: Mint addresses, decimals, owners - **Balance changes**: Pre/post balances for accounts and token accounts - **Currency details**: Token metadata, symbols, mint addresses ## Sample Data Structure Here's an example of the data structure you'll receive: ```json { "Block": { "Slot": 370025845 }, "Transaction": { "Index": 664, "Signature": "MgetT2Zi7PtLP867x2xioiCmimwe1H4rtTiDuqwE8eqjGuK4CTs4CBiKCKyfJHh8mXmQcK4hY9aMVsngg9v1mw5", "Header": { ... "Accounts": [ ... ] } }, "BalanceUpdate": { "BalanceUpdate": { "PreBalance": 412870875328, "PostBalance": 412392356516, "AccountIndex": 4 }, "Currency": { "Name": "Wrapped Solana", ... } } } ``` ## Key Points - **Balance tracking**: Monitor pre and post balances for any account changes - **Token context**: Each balance update includes full token metadata and currency information - **Account indexing**: Balance updates reference specific account indices within transactions - **Comprehensive metadata**: Currency details include mint addresses, symbols, decimals, and program IDs ## Filtering Options The filter options are defined in the `request.proto` file. You can filter balance updates using the following filters: ```protobuf message SubscribeBalanceUpdateRequest { AddressFilter address; AddressFilter token; } ``` Available filters: - **address**: Filter by account address - **token**: Filter by token mint address (e.g., WSOL, USDC) ## Schema Reference - **Protobuf Schema**: [balance_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/block_message.proto) - **Sample Data**: [solana_balance.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_balance.json) ## Python Installation For Python development, install the protobuf package: ```bash pip install bitquery-corecast-proto ``` ## NPM Package ```bash npm install bitquery-corecast-proto ``` This package includes all necessary protobuf definitions without requiring manual downloads. --- ## Related - [CoreCast Introduction](/docs/grpc/solana/introduction/) — Topics and concepts - [Transfers gRPC](/docs/grpc/solana/topics/transfer/) — Token transfers - [Solana Balance Updates (GraphQL)](/docs/blockchain/Solana/solana-balance-updates/) — WebSocket subscriptions - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana Balance Updates Cube URL: https://docs.bitquery.io/docs/cubes/balance-updates-cube/ How the Solana BalanceUpdates cube models every balance change per account, with Type attribution, pre and post balances, and aggregation examples. # Solana Balance Updates Cube The `BalanceUpdates` cube on Solana returns every change to an account's balance, with the transaction that caused it. Use it for balance history, live balance tracking and per-account aggregates. `Solana.InstructionBalanceUpdates` gives the same changes broken down by instruction. :::note EVM and Tron For current balances and holder rankings on EVM chains and Tron, use the [Balances and Holders cubes](/docs/cubes/balances-cube). ::: ## What is a Balance Update? Any change in the balance of any account, by any means, is a balance update. On Solana that covers token transfers, fees, rewards and account changes inside a transaction. Each row carries the `Amount` of the change, the `PreBalance` and `PostBalance` of the account, and a `Type`. ## Balance updates of an account The latest balance changes of one account, newest first. ```graphql {r('b1_s1.graphql')} ``` Fields in the response: - `Account.Address`: the account whose balance changed. `Account.Owner` is the wallet that owns it (for token accounts). - `Amount` and `AmountInUSD`: the size of the change. Positive values are inflows. - `PreBalance` and `PostBalance`: the balance before and after the change. - `Type`: what kind of change it was. - `Currency`: the token; SOL has mint `11111111111111111111111111111111`. ## Stream balance updates The same query as a subscription. A new row arrives each time the account's balance changes. ```graphql {r('b1_s4.graphql')} ``` ## Aggregation in the BalanceUpdates cube Aggregates run at query time, so you can group balance changes by currency, type, time or account. ### Latest balance per token for a wallet `PostBalance(maximum: Block_Slot)` picks the post-balance of the most recent update per currency, which is the current balance. Filter on `Account.Owner` to cover all token accounts of a wallet. ```graphql {r('b1_s3.graphql')} ``` ### Net change per currency and type Sum the updates over the last 24 hours, grouped by currency and `Type`. ```graphql {r('b1_s2.graphql')} ``` ## Related - [Solana Balance & Balance Updates API](/docs/blockchain/Solana/solana-balance-updates) - [Balances and Holders cubes (EVM and Tron)](/docs/cubes/balances-cube) --- ## Solana Builder Terms Explaination URL: https://docs.bitquery.io/docs/glossary/solana/ Solana API glossary: dataset and filter parameters plus field terms for BalanceUpdates, Blocks, DEXTrades, DEXOrders, Instructions, Rewards and Transfers. # Solana Builder Terms Explaination ### Dataset Parameters Solana API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from May 2024 up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Filter Parameters Solana API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Account`: The specific Solana account that the balance update pertains to. - `Amount`: The quantity of tokens that were added to or subtracted from the account. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WSOL, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WSOL. - `Currency`: The type of token or cryptocurrency involved in the balance update. - `PostBalance`: The account's balance after the update has been applied. - `PostBalanceInUSD`: The equivalent value of the PostBalance in US dollars at the time of the transaction. - `PreBalance`: The account's balance before the update was applied. - `PreBalanceInUSD`: The equivalent value of the PreBalance in US dollars at the time of the transaction. ### Block API Terms - `Date`: The specific date on which a block was created or recorded on the Solana blockchain. - `Hash`: A unique identifier generated from the block's data, ensuring data integrity and security. - `Height`: The position of a block in the blockchain, indicating its order relative to other blocks. - `ParentHash`: The unique identifier (hash) of the preceding block in the blockchain, linking the current block to its parent. - `ParentSlot`: The slot number of the block that precedes the current block, used to maintain the order of blocks. - `RewardsCount`: The number of rewards transactions included in a block, often related to staking or validation rewards. - `Slot`: A specific time interval in which a block is proposed and validated on the Solana network. - `Time`: The precise timestamp when the block was created, recorded in Coordinated Universal Time (UTC). - `TxCount`: The total number of transactions included within a specific block on the Solana blockchain. ### DEXOrders API DEX Orders API contains Order field in OrderEvent Field which has below attributes: - `Account`: The Solana account initiating the order. - `BuySide`: Indicates whether the order is a buy (true) or sell (false). - `LimitAmount`: The maximum quantity of the asset to be traded. - `LimitAmountInUSD`: The maximum trade amount expressed in USD. - `LimitPrice`: The price per unit of the asset specified in the order. - `LimitPriceInUSD`: The price per unit of the asset specified in USD. - `Mint`: The specific token mint address for the asset being traded. - `OrderID`: A unique identifier for the order. - `Owner`: The owner of the order, typically the Solana wallet address. - `Payer`: The Solana account responsible for paying transaction fees. ### DEXTradeByTokens API DEXTradeByTokens API gives us trades wrt a token pair. `Trade{Currency}` is first currency and details just before side are for this first currency. Whereas details such as Account, Amount, Price, PriceInUSD, etc inside side are for side currency. Side also has `type` field which tells us if its a `buy` trade or a `sell` trade. The `type` is wrt the pool and side currency. DEXTradeByTokens API contains Trade field which has below attributes: - `Account`: The unique identifier for the wallet involved in the trade. - `Amount`: The quantity of tokens traded. - `AmountInUSD`: The value of the traded tokens in US dollars. - `Currency`: The name of the token being traded. - `DEX`: This contains `ProtocolName`, `ProtocolFamily`, `ProgramAddress`. Here, Protocol or Program refers to DEX. - `Index`: The position number of the trade within a sequence. - `Market`: The address of the trading pair or market. - `Price`: The rate at which this currency is exchanged for the side currency. - `PriceInUSD`: The token's price in US dollars - `Side`: Specifies the `account` address, side `currency`, `amount`, `type` etc. ### DEXTrades API Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. - `Buy`: Details of the buy side of the trade. - `Amount`: Quantity of tokens bought. - `AmountInUSD`: Equivalent value of tokens bought in USD. - `Price`: Price at which tokens were bought. - `PriceInUSD`: Price of bought tokens in USD. - `Account` - `Address`: Address of the buyer's account. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. - `Dex`: Details of the decentralized exchange. - `ProgramAddress`: Address of the DEX program. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolName`: Name of the DEX protocol. - `Market` - `MarketAddress`: Address of the trading pair or market. - `Sell`: Details of the sell side of the trade. - `Account` - `Address`: Address of the seller's account. - `Amount`: Quantity of tokens sold. - `AmountInUSD`: Equivalent value of tokens sold in USD. - `Price`: Price at which tokens were sold. - `PriceInUSD`: Price of sold tokens in USD. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. ### Instructions API Instructions API contains Trade field which has below attributes: - `Accounts`: Details about the accounts involved, including address, writable status, token mint, owner, and program ID. - `AncestorIndexes`: Indexes of ancestor instructions in the call path. - `BalanceUpdatesCount`: The number of balance updates associated with the instruction. - `CallPath`: The sequence of calls leading to the instruction. - `CallerIndex`: Index of the calling instruction. - `Data`: Raw data of the instruction. - `Logs`: Execution logs generated by the instruction. - `InternalSeqNumber`: Internal sequence number of the instruction. - `Index`: Position number of the instruction within the transaction. - `ExternalSeqNumber`: External sequence number of the instruction. - `Depth`: Depth of the instruction in the call stack. - `TokenBalanceUpdatesCount`: Number of token balance updates triggered by the instruction. - `Program`: Information about the program, including parsed details, name, JSON, arguments, address, and account names. The Accounts addresses that we got above with `Accounts{Address}` are the addresses mapped directly to these `AccountNames`. ### Rewards API Rewards API contains Trade field which has below attributes: - `Address`: The wallet address receiving the reward. - `Amount`: The quantity of tokens rewarded. - `AmountInUSD`: The value of the rewarded tokens in US dollars. - `CommissionInUSD`: The commission earned in US dollars. - `Commission`: The commission percentage earned. - `RewardType`: The type or category of the reward. - `PostBalanceInUSD`: The wallet balance after receiving the reward in US dollars. - `PostBalance`: The wallet balance after receiving the reward in tokens. - `Index`: The position or sequence number of the reward entry. ### Transactions API Transactions API contains Trade field which has below attributes: - `Address`: The address of an account involved in the transaction. - `IsWritable`: Indicates whether the account can be modified in the transaction. - `ProgramId`: The identifier of the program associated with a token. - `Mint`: Token Program Address. - `BalanceUpdatesCount`: Number of changes in token balances during the transaction. - `Fee`: The fee paid for executing the transaction. - `FeeInUSD`: The equivalent fee amount in US dollars. - `FeePayer`: The account responsible for paying the transaction fee. - `RecentBlockhash`: The hash of the recent block involved in the transaction. - `InstructionsCount`: Number of instructions in the transaction. - `Index`: The position or sequence number of the transaction. - `Signature`: The digital signature of the transaction. - `Success`: Indicates whether the transaction was successful. - `ErrorMessage`: Details of any error encountered during the transaction. - `Signer`: The account that signed the transaction. - `TokenBalanceUpdatesCount`: Number of changes in token balances due to the transaction. ### Transfers API Transfers API contains Trade field which has below attributes: `Amount`: The quantity of tokens transferred. `AmountInUSD`: The equivalent value of the transferred tokens in US dollars. `Authority`: The wallet address that authorized the transfer. `Index`: The sequential number or position of the transfer event. `Currency`: Details about the token transferred, including its name, mint address, and metadata address, etc. `Receiver`: The recipient's wallet address and ownership details of the received tokens. `Sender`: The sender's wallet address and ownership details of the transferred tokens. ### Currency field Terms Explained Currency has many attributes. It can be a fungible token or non-fungible token(NFT). So it needs an altogether different explaination of its terms- - **CollectionAddress**: Collection address of the NFT, if the currency is an NFT. - **Decimals**: Number of decimals for the token's precision. - **EditionNonce**: Nonce used to derive the edition account address. - **Wrapped**: Indicates if the token is wrapped or not. - **VerifiedCollection**: Indicates if the token's collection is verified. - **Uri**: URI associated with the token. - **UpdateAuthority**: Authority allowed to update the token. - **TokenStandard**: Standard or protocol governing the token. - **TokenCreator**: - **Verified**: Indicates if the token creator is verified. - **Share**: Share of the token creator. - **Address**: Address of the token creator. - **Symbol**: Symbol representing the token. - **SellerFeeBasisPoints**: Basis points of the seller's fee. - **ProgramAddress**: Address of the program managing the token. - **PrimarySaleHappened**: Indicates if the primary sale has occurred. - **Native**: Indicates if the token is native to the blockchain. - **Name**: Name of the token. - **MintAddress**: Token Program Address. - **IsMutable**: Indicates if the token is mutable. - **Fungible**: Indicates if the token is fungible. --- ## Solana Builder Terms Explanation URL: https://docs.bitquery.io/docs/cubes/solana/ Solana cube terms explained: dataset and filter parameters, plus the fields of BalanceUpdates, Blocks, DEXOrders, DEXTrades, Instructions and Transfers. # Solana Builder Terms Explanation > **Before you start**: Not sure when to use Transfers vs DEX Trades vs other data primitives? Read our [Mental Model guide](/docs/start/mental-model-transfers-events-calls) to understand which primitive to use for your use case. ### Dataset Parameters Solana API allows you to narrow down your results using these parameters: - `archive`: Archive dataset contains the data from the first (genesis) block up until the realtime dataset(not including). - `realtime`: Realtime dataset containing last set of blocks. Eg. only few hours recent data - `combined`: Combined dataset ( realtime and archive ). ### Filter Parameters Solana API allows you to narrow down your results using these parameters: - `limit`: Limit the results to a specified number. - `limitBy`: Limit results based on a specific field's value. - `orderBy`: Order results according to a field's value. - `where`: Filter results based on specific criteria related to the value of the returned field. ### BalanceUpdate API Terms - `Account`: The specific Solana account that the balance update pertains to. - `Amount`: The quantity of tokens that were added to or subtracted from the account. - `AmountInUSD`: AmountInUSD will always be calculated based on the USD value of an asset pulled from centralized exchanges. If it is 0, it means we don't have a USD value. In such cases, you can use counterparty AmountInUSD. For example, if token A is traded against WSOL, and we are showing 0 for token A's AmountInUSD, it means we don't have token A's USD value, but you can use the AmountInUSD of WSOL. - `Currency`: The type of token or cryptocurrency involved in the balance update. - `PostBalance`: The account's balance after the update has been applied. - `PostBalanceInUSD`: The equivalent value of the PostBalance in US dollars at the time of the transaction. - `PreBalance`: The account's balance before the update was applied. - `PreBalanceInUSD`: The equivalent value of the PreBalance in US dollars at the time of the transaction. ### Block API Terms - `Date`: The specific date on which a block was created or recorded on the Solana blockchain. - `Hash`: A unique identifier generated from the block's data, ensuring data integrity and security. - `Height`: The position of a block in the blockchain, indicating its order relative to other blocks. - `ParentHash`: The unique identifier (hash) of the preceding block in the blockchain, linking the current block to its parent. - `ParentSlot`: The slot number of the block that precedes the current block, used to maintain the order of blocks. - `RewardsCount`: The number of rewards transactions included in a block, often related to staking or validation rewards. - `Slot`: A specific time interval in which a block is proposed and validated on the Solana network. - `Time`: The precise timestamp when the block was created, recorded in Coordinated Universal Time (UTC). - `TxCount`: The total number of transactions included within a specific block on the Solana blockchain. ### DEXOrders API DEX Orders API contains Order field in OrderEvent Field which has below attributes: - `Account`: The Solana account initiating the order. - `BuySide`: Indicates whether the order is a buy (true) or sell (false). - `LimitAmount`: The maximum quantity of the asset to be traded. - `LimitAmountInUSD`: The maximum trade amount expressed in USD. - `LimitPrice`: The price per unit of the asset specified in the order. - `LimitPriceInUSD`: The price per unit of the asset specified in USD. - `Mint`: The specific token mint address for the asset being traded. - `OrderID`: A unique identifier for the order. - `Owner`: The owner of the order, typically the Solana wallet address. - `Payer`: The Solana account responsible for paying transaction fees. ### DEXTradeByTokens API DEXTradeByTokens API gives us trades wrt a token pair. `Trade{Currency}` is first currency and details just before side are for this first currency. Whereas details such as Account, Amount, Price, PriceInUSD, etc inside side are for side currency. Side also has `type` field which tells us if its a `buy` trade or a `sell` trade. The `type` is wrt the pool and side currency. DEXTradeByTokens API contains Trade field which has below attributes: - `Account`: The unique identifier for the wallet involved in the trade. - `Amount`: The quantity of tokens traded. - `AmountInUSD`: The value of the traded tokens in US dollars. - `Currency`: The name of the token being traded. - `DEX`: This contains `ProtocolName`, `ProtocolFamily`, `ProgramAddress`. Here, Protocol or Program refers to DEX. - `Index`: The position number of the trade within a sequence. - `Market`: The address of the trading pair or market. - `Price`: The rate at which this currency is exchanged for the side currency. - `PriceInUSD`: The token's price in US dollars - `Side`: Specifies the `account` address, side `currency`, `amount`, `type` etc. ### DEXTrades API Using DEXTrades API, you will be able to get the trades and will easily be able to bifurcate according to buyside and sellside. - `Buy`: Details of the buy side of the trade. - `Amount`: Quantity of tokens bought. - `AmountInUSD`: Equivalent value of tokens bought in USD. - `Price`: Price at which tokens were bought. - `PriceInUSD`: Price of bought tokens in USD. - `Account` - `Address`: Address of the buyer's account. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. - `Dex`: Details of the decentralized exchange. - `ProgramAddress`: Address of the DEX program. - `ProtocolFamily`: Family of the DEX protocol. - `ProtocolName`: Name of the DEX protocol. - `Market` - `MarketAddress`: Address of the trading pair or market. - `Sell`: Details of the sell side of the trade. - `Account` - `Address`: Address of the seller's account. - `Amount`: Quantity of tokens sold. - `AmountInUSD`: Equivalent value of tokens sold in USD. - `Price`: Price at which tokens were sold. - `PriceInUSD`: Price of sold tokens in USD. - `Currency`: Details such as name, symbol, program address(mint address) of the bought Currency. ### Instructions API Instructions API contains Trade field which has below attributes: - `Accounts`: Details about the accounts involved, including address, writable status, token mint, owner, and program ID. - `AncestorIndexes`: Indexes of ancestor instructions in the call path. - `BalanceUpdatesCount`: The number of balance updates associated with the instruction. - `CallPath`: The sequence of calls leading to the instruction. - `CallerIndex`: Index of the calling instruction. - `Data`: Raw data of the instruction. - `Logs`: Execution logs generated by the instruction. - `InternalSeqNumber`: Internal sequence number of the instruction. - `Index`: Position number of the instruction within the transaction. - `ExternalSeqNumber`: External sequence number of the instruction. - `Depth`: Depth of the instruction in the call stack. - `TokenBalanceUpdatesCount`: Number of token balance updates triggered by the instruction. - `Program`: Information about the program, including parsed details, name, JSON, arguments, address, and account names. The Accounts addresses that we got above with `Accounts{Address}` are the addresses mapped directly to these `AccountNames`. ### Rewards API Rewards API contains Trade field which has below attributes: - `Address`: The wallet address receiving the reward. - `Amount`: The quantity of tokens rewarded. - `AmountInUSD`: The value of the rewarded tokens in US dollars. - `CommissionInUSD`: The commission earned in US dollars. - `Commission`: The commission percentage earned. - `RewardType`: The type or category of the reward. - `PostBalanceInUSD`: The wallet balance after receiving the reward in US dollars. - `PostBalance`: The wallet balance after receiving the reward in tokens. - `Index`: The position or sequence number of the reward entry. ### Transactions API Transactions API contains Trade field which has below attributes: - `Address`: The address of an account involved in the transaction. - `IsWritable`: Indicates whether the account can be modified in the transaction. - `ProgramId`: The identifier of the program associated with a token. - `Mint`: Token Program Address. - `BalanceUpdatesCount`: Number of changes in token balances during the transaction. - `Fee`: The fee paid for executing the transaction. - `FeeInUSD`: The equivalent fee amount in US dollars. - `FeePayer`: The account responsible for paying the transaction fee. - `RecentBlockhash`: The hash of the recent block involved in the transaction. - `InstructionsCount`: Number of instructions in the transaction. - `Index`: The position or sequence number of the transaction. - `Signature`: The digital signature of the transaction. - `Success`: Indicates whether the transaction was successful. - `ErrorMessage`: Details of any error encountered during the transaction. - `Signer`: The account that signed the transaction. - `TokenBalanceUpdatesCount`: Number of changes in token balances due to the transaction. ### Transfers API Transfers API contains Trade field which has below attributes: `Amount`: The quantity of tokens transferred. `AmountInUSD`: The equivalent value of the transferred tokens in US dollars. `Authority`: The wallet address that authorized the transfer. `Index`: The sequential number or position of the transfer event. `Currency`: Details about the token transferred, including its name, mint address, and metadata address, etc. `Receiver`: The recipient's wallet address and ownership details of the received tokens. `Sender`: The sender's wallet address and ownership details of the transferred tokens. ### Currency field Terms Explained Currency has many attributes. It can be a fungible token or non-fungible token(NFT). So it needs an altogether different explaination of its terms- - **CollectionAddress**: Collection address of the NFT, if the currency is an NFT. - **Decimals**: Number of decimals for the token's precision. - **EditionNonce**: Nonce used to derive the edition account address. - **Wrapped**: Indicates if the token is wrapped or not. - **VerifiedCollection**: Indicates if the token's collection is verified. - **Uri**: URI associated with the token. - **UpdateAuthority**: Authority allowed to update the token. - **TokenStandard**: Standard or protocol governing the token. - **TokenCreator**: - **Verified**: Indicates if the token creator is verified. - **Share**: Share of the token creator. - **Address**: Address of the token creator. - **Symbol**: Symbol representing the token. - **SellerFeeBasisPoints**: Basis points of the seller's fee. - **ProgramAddress**: Address of the program managing the token. - **PrimarySaleHappened**: Indicates if the primary sale has occurred. - **Native**: Indicates if the token is native to the blockchain. - **Name**: Name of the token. - **MintAddress**: Token Program Address. - **IsMutable**: Indicates if the token is mutable. - **Fungible**: Indicates if the token is fungible. --- ## Solana Copy Trading Bot with gRPC Streams URL: https://docs.bitquery.io/docs/grpc/solana/examples/grpc-copy-trading-bot/ Solana Copy Trading Bot with gRPC Streams for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Building Solana Copy Trading Bot with gRPC Streams A comprehensive guide to building a **high-performance Solana trading bot** that leverages **gRPC streams** for real-time copy trading using [Bitquery CoreCast](/docs/grpc/solana/introduction/). ## Table of Contents - [Architecture Overview](#architecture-overview) - [Bitquery CoreCast Streams](#bitquery-corecast-integration) - [Streaming Real-Time Solana DEX Trades](#streaming-real-time-solana-dex-trades) - [Trade Execution with Jupiter API](#trade-execution-with-jupiter-api) - [Code Walkthrough](#code-walkthrough) - [Configuration & Filtering](#configuration--filtering) - [Best Practices](#best-practices) - [Output](#output) --- ## Output The final result of this project would appear as the one given below. ## Architecture Overview This **Solana trading bot** implements a streaming architecture for **copy trading**: ``` ┌─────────────────────┐ │ Solana Blockchain │ │ (DEX Trades) │ └──────────┬──────────┘ │ ▼ ┌─────────────────────────────────┐ │ Bitquery CoreCast gRPC Stream │ ← Real-time data streaming │ docs.bitquery.io/docs/grpc/ │ └──────────┬──────────────────────┘ │ ▼ ┌─────────────────────┐ │ gRPC Client │ ← @grpc/grpc-js │ (CoreCast Proto) │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Event Handler │ ← Trade filtering & strategy └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Jupiter Swap API │ ← Optimal trade execution └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Solana Transaction │ ← On-chain execution └─────────────────────┘ ``` Learn more about [Bitquery CoreCast architecture](/docs/grpc/solana/introduction/). --- ## Bitquery CoreCast Integration [Bitquery CoreCast](/docs/grpc/solana/introduction/) provides real-time blockchain data streaming via gRPC for **Solana trading bots**. ```javascript // index.js - Loading Protocol Buffers const { loadPackageDefination } = require('bitquery-corecast-proto'); const packageDefinition = loadPackageDefination(); const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); const solanaCorecast = protoDescriptor.solana_corecast; ``` Reference: [Protobuf Loading Documentation](https://www.npmjs.com/package/bitquery-corecast-proto) --- ## Streaming Real-Time Solana DEX Trades ### Initializing the gRPC Client The bot connects to Bitquery's CoreCast server using the given below code snippet: ```javascript // index.js - Client Initialization function initializeClient() { client = new solanaCorecast.CoreCast( config.server.address, // corecast.bitquery.io grpc.credentials.createSsl() ); metadata = new grpc.Metadata(); metadata.add('authorization', config.server.authorization); } ``` Refer to [this document](/docs/grpc/solana/authorization/) for any issues related to authorization. ### Creating the Stream Multiple [Solana stream topics](/docs/category/topics/) are available: ```javascript // index.js - Stream Creation function startStream() { const request = createRequest(); let stream; switch (config.stream.type) { case 'dex_trades': // Real-time DEX trades stream = client.DexTrades(request, metadata); break; case 'dex_orders': // Order book updates stream = client.DexOrders(request, metadata); break; case 'transactions': // All transactions stream = client.Transactions(request, metadata); break; // ... more stream types } } ``` ### Handling Stream Events The bot processes incoming trade messages in real-time: ```javascript // index.js - Event Handler stream.on('data', async (message) => { if (message.Trade) { // Extract trade data from protobuf message const marketAddress = toBase58(message.Trade.Market?.MarketAddress); const inputMint = toBase58(message.Trade.Buy?.Currency?.MintAddress); const outputMint = toBase58(message.Trade.Sell?.Currency?.MintAddress); const buyAmount = message.Trade.Buy?.Amount; // Apply trading strategy if (approveTrade(buyAmount)) { await executeTrades({ inputMint, outputMint, marketAddress, buyAmount }); } } }); stream.on('error', (error) => { console.error('Stream error:', error); }); stream.on('end', () => { console.log('Stream ended'); }); ``` --- ## Trade Execution with Jupiter API ### Native SOL Conversion Jupiter requires wrapped SOL (wSOL) instead of native SOL for trading. Our bot handles this conversion: ```javascript // trade.js - SOL Mint Conversion const NATIVE_SOL_MINT = '11111111111111111111111111111111'; const WRAPPED_SOL_MINT = 'So11111111111111111111111111111111111111112'; const convertedInputMint = inputMint === NATIVE_SOL_MINT ? WRAPPED_SOL_MINT : inputMint; ``` ### Fetching Swap Quotes We use Jupiter's aggregation API to find optimal swap routes: ```javascript // trade.js - Quote Fetching const jupiter = createJupiterApiClient({ basePath: 'https://quote-api.jup.ag/v6' }); const quoteReq = { inputMint: convertedInputMint, outputMint: convertedOutputMint, amount: amountInRaw, slippageBps: slippageBps.toString(), onlyDirectRoutes: false // Allow indirect routes for better liquidity }; const quote = await jupiter.quoteGet(quoteReq); ``` ### Creating and Sending Transactions Once we have a quote, we build and execute the swap transaction: ```javascript // trade.js - Transaction Execution const swapReq = { quoteResponse: quote, userPublicKey: wallet.publicKey.toString(), wrapAndUnwrapSOL: true, // Handle SOL wrapping automatically asLegacyTransaction: true }; const swapRes = await jupiter.swapPost({ swapRequest: swapReq }); // Deserialize and sign transaction const txBuf = Buffer.from(swapRes.swapTransaction, 'base64'); const tx = Transaction.from(txBuf); tx.sign([wallet]); // Send to Solana network const txSig = await connection.sendRawTransaction( tx.serialize(), { skipPreflight: true, maxRetries: 3 } ); // Wait for confirmation await connection.confirmTransaction(txSig, 'confirmed'); ``` --- ## Code Walkthrough ### Helper Functions #### Base58 Encoding Solana addresses are encoded in base58. We convert byte arrays to base58 strings: ```javascript // index.js - Base58 Conversion function toBase58(bytes) { if (!bytes || bytes.length === 0) return 'undefined'; try { return bs58.encode(bytes); } catch (error) { return 'invalid_address'; } } ``` ### Configuration Management The bot supports hot-reloading of configuration without restart: ```javascript // index.js - Config Watching fs.watch('./config.yaml', (eventType, filename) => { if (eventType === 'change') { clearTimeout(watchTimeout); watchTimeout = setTimeout(() => { reloadAndRestart(); }, 300); // Debounce rapid changes } }); ``` ### Trading Strategy Implement your **copy trading** logic in the `approveTrade()` function: ```javascript // index.js - Trade Approval Logic function approveTrade(buyAmount) { // Example: Only approve large trades if (buyAmount > 100 * 1000000000) { console.log('Approving large trade:', buyAmount); return true; } return false; } ``` **Strategy Ideas:** - Volume-based filtering - Token whitelist/blacklist - Risk management (max position size) - Cooldown periods - Multi-signal confirmation --- ## Configuration & Filtering ### Stream Configuration Configure which on-chain activity to monitor: ```yaml # config.yaml stream: type: "dex_trades" # Real-time DEX trades ``` **Available Stream Types:** - `dex_trades` - [DEX trades](/docs/grpc/solana/topics/dextrades/) - `dex_orders` - [Order book data](/docs/grpc/solana/topics/dexorder/) - `dex_pools` - [Pool liquidity events](/docs/grpc/solana/topics/dexpools/) - `transactions` - [All transactions](/docs/grpc/solana/topics/transactions/) - `transfers` - [Token transfers](/docs/grpc/solana/topics/transfer/) - `balances` - [Balance updates](/docs/grpc/solana/topics/balance/) ### Filters Use [filtering options](/docs/grpc/solana/topics/dextrades/#filtering-options) to target specific trades: ```yaml # config.yaml filters: traders: # Copy trades from specific addresses - "HV1KXxWFaSeriyFvXyx48FqG9BoFbfinB8njCJonqP7K" programs: # Filter by DEX programs - "..." pool: # Filter by liquidity pools - "..." signers: # Filter by transaction signers - "..." ``` ```javascript // index.js - Request Builder function createRequest() { const request = {}; if (config.filters.traders?.length > 0) { request.trader = { addresses: config.filters.traders }; } if (config.filters.programs?.length > 0) { request.program = { addresses: config.filters.programs }; } // ... more filter types return request; } ``` --- ## Best Practices ### 1. Error Handling Implement comprehensive error handling for network failures: ```javascript // trade.js - Error Handling try { const quote = await jupiter.quoteGet(quoteReq); } catch (error) { console.error('Jupiter API error:', error.response?.data || error.message); // Implement retry logic or fallback } ``` ### 2. Rate Limiting To avoid being rate-limited by Jupiter: ```javascript // Add delays between trades await new Promise(resolve => setTimeout(resolve, 1000)); ``` ### 3. Monitoring Log all trade executions for analysis: ```javascript console.log('✅ Copy trade executed!', { tx: txSig, inputMint, outputMint, amount: buyAmount }); ``` ### 4. Security - Keep API keys in `secrets.json` (never commit) - Use separate trading wallet - Set maximum trade amounts - Implement stop-loss mechanisms ### 5. Testing Start with small amounts: ```javascript // Reduce trade amount for testing amountInRaw: (buyAmount / 100).toString() // 1% of original ``` --- ## Additional Resources ### Bitquery Documentation - [CoreCast Introduction](/docs/grpc/solana/introduction) - [Authentication Guidelines](/docs/grpc/solana/authorization/) - [Best Practices for gRPC streams](/docs/grpc/solana/best_practices/) - [Other Solana gRPC Examples](/docs/category/examples/) - [Error Handling](/docs/grpc/solana/errors/) ### External APIs - [Jupiter Swap API](https://dev.jup.ag/docs/swap/) - [Solana Web3.js](https://solana-foundation.github.io/solana-web3.js/) - [Solana RPC](https://docs.solana.com/api/http) ### Get Started [Sign up for Bitquery CoreCast](https://account.bitquery.io/auth/signup) and start building your **Solana copy trading bot** today! --- ## Solana DEX Orders - gRPC Stream (CoreCast) URL: https://docs.bitquery.io/docs/grpc/solana/topics/dexorder/ Solana DEX Orders - gRPC Stream (CoreCast) for Bitquery Solana gRPC (CoreCast), covering setup, filters, reliability, and stream examples. # Solana DEX Orders gRPC Stream The `dex_orders` gRPC Stream provides real-time DEX order placement and execution data across supported Solana protocols. --- ## Overview Subscribe to live DEX order book events (place, cancel, fill) from OpenBook, Serum, and other order-book DEXs. Each event includes order details, market info, and balance updates. Data is in **protobuf format** — use `bitquery-corecast-proto` to parse. ## Configuration To subscribe to DEX orders, configure your stream as follows: ```yaml stream: type: "dex_orders" ``` ## Available Data The DEX orders stream provides comprehensive order information including: - **Transaction details**: Slot, signature, status, fees (in native and USD) - **Account information**: Signers, token accounts, program IDs - **Token context**: Mint addresses, decimals, owners, metadata - **Order specifics**: Order IDs, prices, amounts, order types, buy/sell sides - **Market data**: Market addresses, base/quote currencies, order books - **Balance updates**: Pre/post balances for accounts and token accounts ## Sample Data Structure Here's an example of the data structure you'll receive: ```json { "Block": { "Slot": 370028492 }, "Transaction": { "Index": 779, "Signature": "2eoFGRLxJFXhLGBXS4dPgSGYfjF9yGx3Tfc4EgJqrndiMqTX22SZwaH1E8E8p7333z2CWqofY8YvJgB7DN6hJv1L", ... }, "Order": { "InstructionIndex": 7, "Type": 0, "Dex": { "ProgramAddress": "opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb", "ProtocolName": "openbook_v2", "ProtocolFamily": "OpenBook" }, "Market": { "MarketAddress": "6NtxTCJuhNixA5Z2MBT4mrCuBk7qLQ69htcCNfySdu7J", "BaseCurrency": { ... }, "QuoteCurrency": { ... } }, "Order": { "OrderId": "11111111", "BuySide": true, "LimitPrice": 9223372036854775807, "LimitAmount": 92233720368547, "Account": "2qwiCSJJuDz3AX39LvgSGhPKoWeTSBAJvqzNwYNQAavj", "Owner": "2qwiCSJJuDz3AX39LvgSGhPKoWeTSBAJvqzNwYNQAavj", "Mint": "So11111111111111111111111111111111111111112" }, "Instruction": { "Index": 7, "Program": { "Address": "opnb2LAfJYbRMAHHvqjCwQxanZn7ReEHp1k81EohpZb", "Name": "openbook_v2", "Method": "placeTakeOrder" }, "Arguments": [ { "Name": "args", "Type": "PlaceTakeOrderArgs", "Json": "{\"side\":0,\"priceLots\":9223372036854775807,\"maxBaseLots\":92233720368547,\"maxQuoteLotsIncludingFees\":443279519,\"orderType\":3,\"limit\":50}" } ], "AccountNames": [ "signer", "penaltyPayer", "market", "marketAuthority", "bids", "asks", "marketBaseVault", "marketQuoteVault", "eventHeap", "userBaseAccount", "userQuoteAccount" ] }, "BalanceUpdates": [ { "PreBalance": 13595078208, "PostBalance": 13151798872, "AccountIndex": 2 } ], "TokenBalanceUpdates": [ { "PreBalance": 13593036926, "PostBalance": 13149757590, "AccountIndex": 2 }, { "PreBalance": 77176413, "PostBalance": 436576413, "AccountIndex": 3 } ] } } ``` ## Key Points - **Order tracking**: Monitor real-time order placement and execution on DEX order books - **Order book data**: Access to bids, asks, and order book state changes - **Token metadata**: Comprehensive token information including metadata and collection details - **Instruction parsing**: Detailed instruction data with arguments and account mappings - **Balance changes**: Track both native SOL and token balance updates - **Multiple protocols**: Supports various DEX protocols including OpenBook, Serum, and other order book DEXs ## Filtering Options The filter options are defined in the `request.proto` file. You can filter DEX orders using the following filters: ```protobuf message SubscribeOrdersRequest { AddressFilter program; AddressFilter pool; AddressFilter token; AddressFilter trader; } ``` Available filters: - **program**: Filter by DEX program address - **pool**: Filter by specific pool/market address - **token**: Filter by token mint address (e.g., WSOL, USDC) - **trader**: Filter by trader's wallet address ## Order Data Fields - **OrderId**: Unique identifier for the order - **BuySide**: Boolean indicating if it's a buy order (true) or sell order (false) - **LimitPrice**: The price limit for the order - **LimitAmount**: The maximum amount to be traded - **Account**: The order account address - **Owner**: The order owner address - **Payer**: The account paying for the order - **Mint**: The token mint address for the order ## Schema Reference - **Protobuf Schema**: [dex_block_message.proto](https://github.com/bitquery/streaming_protobuf/blob/main/solana/dex_block_message.proto) - **Sample Data**: [solana_dex_order.json](https://github.com/bitquery/grpc-code-samples/blob/main/data-sample/solana_dex_order.json) ## Python Installation For Python development, install the protobuf package: ```bash pip install bitquery-corecast-proto ``` ## NPM Package ```bash npm install bitquery-corecast-proto ``` This package includes all necessary protobuf definitions without requiring manual downloads. --- ## Related - [CoreCast Introduction](/docs/grpc/solana/introduction/) — Topics and concepts - [DEX Trades gRPC](/docs/grpc/solana/topics/dextrades/) — DEX swap stream - [Copy Trading Bot](/docs/grpc/solana/examples/grpc-copy-trading-bot/) — Uses dex_orders - [Authorization](/docs/grpc/solana/authorization/) — Token setup --- ## Solana DEX 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 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 Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/solana/ Solana blocks, transactions, transfers, balance updates, DEX orders and trades, pools and rewards as Parquet, with a free sample and code examples. # Solana Data Bitquery provides **Solana blockchain data 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 ``` ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=solana), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Per-protocol Solana datasets on the Data Store, each with decoded trades priced in USD: - [Pump.fun](https://bitquery.io/datastore/datasets/pumpfun) - [PumpSwap](https://bitquery.io/datastore/datasets/pumpswap) - [Raydium AMM v4](https://bitquery.io/datastore/datasets/raydium-amm-v4) - [Raydium CLMM](https://bitquery.io/datastore/datasets/raydium-clmm) - [Raydium CPMM](https://bitquery.io/datastore/datasets/raydium-cpmm) - [Raydium Launchpad](https://bitquery.io/datastore/datasets/raydium-launchpad) - [Jupiter](https://bitquery.io/datastore/datasets/jupiter) - [Orca Whirlpool](https://bitquery.io/datastore/datasets/orca-whirlpool) - [Meteora DLMM](https://bitquery.io/datastore/datasets/meteora-dlmm) - [Meteora DAMM V2](https://bitquery.io/datastore/datasets/meteora-damm-v2) - [Meteora DBC](https://bitquery.io/datastore/datasets/meteora-dbc) - [Meteora Pools](https://bitquery.io/datastore/datasets/meteora-pools) - [PancakeSwap (Solana)](https://bitquery.io/datastore/datasets/pancakeswap-solana) - [DFlow Aggregator](https://bitquery.io/datastore/datasets/dflow) - [OKX DEX](https://bitquery.io/datastore/datasets/okx-dex) - [SolFi](https://bitquery.io/datastore/datasets/solfi) - [BisonFi](https://bitquery.io/datastore/datasets/bisonfi) - [Bonkswap](https://bitquery.io/datastore/datasets/bonkswap) - [Heaven](https://bitquery.io/datastore/datasets/heaven) - [Moonshot](https://bitquery.io/datastore/datasets/moonshot) - [Boop](https://bitquery.io/datastore/datasets/boop) - [Manifest](https://bitquery.io/datastore/datasets/manifest) - [Phoenix](https://bitquery.io/datastore/datasets/phoenix) ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/balance_updates/390740000_390740049.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/solana/balance_updates/390740000_390740049.parquet") print(df.info()) df.head() ``` ## Real-Time vs Batch Data Access 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 MCP Server for Claude, ChatGPT and Cursor URL: https://docs.bitquery.io/docs/mcp/solana/ Ask Claude, ChatGPT or Cursor about Solana in plain English: trending tokens, pump.fun launches, first buyers, token prices and where a wallet sent its SOL. Read-only, from on-chain data. # Solana MCP Server The Bitquery MCP server lets an AI client answer questions about Solana trading and money movement. You ask in Claude, ChatGPT, Cursor, VS Code or Codex, the agent picks a tool, and rows come back from Bitquery's index of Solana DEX trades and transfers. It reads data only. It cannot sign or send a transaction, and it does not hold keys. If you want an MCP that helps you write Solana programs, that is the Solana Foundation's developer MCP; this one is for market and wallet research. ```bash claude mcp add --transport http bitquery https://mcp.bitquery.io ``` Other clients take the same URL. Steps for each are in the [MCP server install guide](/docs/mcp/mcp-server/). Every figure on this page came from a call to the production server on 21 September 2026, between 10:19 and 10:25 UTC. Solana moves fast, so your numbers will differ. ## What can I ask? ### What is trading most on Solana today? > *"What are the most traded tokens on Solana in the last 24 hours?"* The agent calls `trending_tokens` with the chain set to Solana. | # | Symbol | Token address | 24h volume | 24h price change | |---|---|---|---:|---:| | 1 | USDT | `USD2Ttdo...CdTho` | $986,660,608 | -0.68% | | 2 | SОL | `SoJh2C73...4GhTC` | $952,089,984 | -0.11% | | 3 | WSOL | `So111111...11112` | $822,212,759 | +7.09% | | 4 | USDC | `EPjFWdd5...TDt1v` | $128,175,125 | -0.01% | Rows 5 to 8 were four small tokens up between 4,618% and 11,241% on $70 million to $119 million of volume each. Wrapped SOL went from $108.00 to $115.66. Look at rows 1 and 2 again. Neither address is the real one. Tether's Solana address starts `Es9vMF`, and the "SОL" in row 2 is spelled with a Cyrillic letter. The next question shows how to catch that. ### Is that volume real? > *"Where does the token USD2Ttdovnui8b6YG3NFreErgiNJv34UwritmRCdTho trade, and how many wallets trade it?"* `token_dex_venues`, grouped by protocol: | Token | Trades | Wallets | Trading span | Reported volume | |---|---:|---:|---|---:| | "USDT" `USD2Ttdo...` | 5 | 2 | 9 minutes | $986,660,663 | | "SОL" `SoJh2C73...` | 58 | 3 | 16 hours | $952,090,033 | Both trade on one venue only, Orca Whirlpool, and the first token's nine minutes fell on 20 September. Five trades between two wallets produced a reported $987 million. The answer also lists what each token was swapped for, and the two counterfeits were swapped for each other. A handful of swaps of made-up size printed a dollar figure that nobody paid. On the second token the tool also sets `Symbol_NonAscii` to 1, its flag for look-alike letters. Two habits follow. Give the agent a token address, because a symbol is not unique on Solana. And before you trust a volume figure, ask how many wallets stood behind it. ### What launched on pump.fun in the last six hours? > *"Show new pump.fun tokens from the last 6 hours, ranked by volume."* `new_tokens` with the address pattern `%pump`, which matches pump.fun token addresses. | Token | Age | Volume | Valuation now | Fall from peak | |---|---:|---:|---:|---:| | BABYJEAN | 3.3 h | $1,855,343 | $3,483 | -99.64% | | SCRIBJEAN | 5.3 h | $1,822,028 | $2,391 | -99.70% | | JEANGREY | 1.3 h | $1,791,345 | $2,761 | -99.66% | | JEANGRINO | 4.3 h | $1,422,407 | $2,444 | -99.66% | | JeanJaks | 4.3 h | $1,249,362 | $2,664 | -98.80% | All five share a name theme, and all five had already lost at least 98.8% from their peak price. BABYJEAN peaked at a valuation of $427,193 before falling to $3,483. Valuation here is price times total supply, which the tool labels FDV. The peak and the fall come back in the same row so the agent can tell a live launch from one that is over. ### How did one of those launches go? > *"How did the BABYJEAN launch go in its first 60 seconds?"* `token_launch_stats` with a 60-second window returns one row, shown here on its side: | Measure | First 60 seconds | |---|---:| | First trade | 07:50:43 UTC | | Trades | 340 (225 buys, 115 sells) | | Wallets | 109 | | Wallets in the first block | 3 | | Wallets in the first 10 seconds | 31 | | Bought | $23,925 | | Sold | $12,646 | The same answer lists the 20 largest wallets of that minute. Two things stand out. Four wallets each made a single buy of $2,061 to $2,371 at the same instant, 1.2 seconds after the first trade. And the largest wallet of the minute, `3e1hq8LB...Cctm`, bought nothing in the window and sold $8,648 across 19 trades, starting at 14.8 seconds. ### Who got in first? > *"Who were the first buyers of BABYJEAN?"* `early_buyers`, sorted by arrival: | Wallet | Seconds after launch | Bought | Sold | Result inside the minute | |---|---:|---:|---:|---:| | `LfEcaUf7...a9Uw` | 0 | $55.33 | $57.36 | +$2.03 | | `GePaAUXD...Xjft` | 0 | $341.88 | $377.51 | +$35.63 | | `F7LqQscx...YwmE` | 0 | $289.84 | $193.43 | -$96.41, still holding | | `8N4QDR8m...kZoc` | 1 | $0.01 | $0 | -$0.01 | | `9FVZMzqS...zhcz` | 1 | $22.01 | $23.88 | +$1.87 | | `3xezief4...B69T` | 2 | $23.40 | $20.95 | -$2.45 | Arriving in the first second did not pay much here. The best of the six made $35.63. ### Where did the seller's money go? > *"Where did 3e1hq8LBpHmEQqwTp5ADrUbgWtN4coBBsN3Y3NRRCctm send its SOL?"* Two calls. `solana_address_profile` says the wallet sent 65 transfers to 7 receivers in 30 days and received 61 from 3 senders, so it is a small wallet and not an exchange. `solana_trace_next_hop`, pinned to native SOL, ranks where the money went: | Receiver | SOL | Time (UTC) | Label | |---|---:|---|---| | `3S5A2dpJ...GwqN` | 70.53 | 07:51:58 | none | | `3repxLH4...uxWQ` | 65.28 | 07:52:29 | none | | `34YJ1Xkd...XHYv` | 58.23 | 07:51:34 | none | | `iWnj1DuR...s2Ek` | 52.57 | 07:53:05 | none | | `FWZdfwbs...LeRK` | 22.06 | 07:52:42 | none | That is 268.68 SOL to five unlabeled wallets, all between 51 and 142 seconds after the token's first trade. A trace stops when a receiver carries a label such as an exchange. None did here, so the next step would be the same call on each receiver. One gap: `solana_transfers_in` returned no rows for this token on this wallet, so the transfer data does not say how the wallet got the tokens it sold. ## Tools that cover Solana Ten tools are Solana-only and carry the `solana_` prefix: | Tool | Use it for | |---|---| | `solana_address_profile` | Counts of transfers and counterparties, to size up a wallet before tracing | | `solana_address_flow_summary` | Totals in and out per token | | `solana_transfers_in` | Incoming transfers, newest or largest first, with sender labels | | `solana_transfers_out` | Outgoing transfers | | `solana_trace_next_hop` | Receivers of a wallet's funds, ranked and labeled | | `solana_flow_edges` | Wallet-to-wallet edges for a graph | | `solana_tx_transfers` | Every transfer inside one transaction | | `solana_signatures` | Every transaction an address took part in, newest first, with paging into old history | | `solana_find_instructions` | Search by program and instruction name | | `solana_transfers_raw_sql` | Your own SQL over the transfer tables | The market tools take a `blockchain` argument and work on Solana and eight other chains: | Tools | Use them for | |---|---| | `trending_tokens`, `new_tokens` | What is hot, and what just launched | | `find_tokens`, `find_token_by_address` | Turn a name or an address into a token | | `token_price`, `token_ohlcv`, `token_trade_bars`, `token_supply` | Price, candles down to 1 second, supply | | `token_dex_venues`, `pool_recent_trades`, `tx_trades` | Pools, venues and single swaps | | `token_launch_stats`, `early_buyers` | The first seconds of a launch | | `top_traders_by_token`, `profitable_traders_by_token`, `accumulating_traders_by_token` | Rank the wallets trading one token | | `trader_profile`, `trader_activity`, `trader_positions` | One wallet's trading record | | `address_labels`, `labels_for_addresses` | Exchange, bridge and scam labels | ## What to know before you rely on it - **Read-only.** No signing, no sending, no account state. For those you need a Solana RPC node. - **Check the token address.** Counterfeit tokens copy names and symbols, and one topped the volume ranking on the day this page was written. - **Dollar volume can be fake.** Ask for the number of trades and wallets before quoting a figure. - **Trade history is about 30 days.** A launch older than that is anchored at the start of the history, and the tool sets `Launch_May_Predate_History` to say so. - **Transfer tools default to 90 days.** Raise `days` to look further back. An empty answer can mean the window ended. - **Transfer amounts are in token units.** There is no dollar value on a transfer, so totals of different tokens cannot be added. - **No program logs.** Search programs with `solana_find_instructions`. Decoded events and token-holder lists are not available for Solana. ## MCP, GraphQL or an RPC node? | You want to | Use | |---|---| | Send transactions or read account state | A Solana RPC node | | Get help writing Solana programs | The Solana Foundation's developer MCP | | Ask questions in a chat, or let an agent research tokens and wallets | This MCP server | | Build a bot, dashboard or alert in code | The [Bitquery Solana API](/docs/blockchain/Solana/) and the [pump.fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/), with WebSocket and Kafka streams | | Load full history into a warehouse | [Solana Parquet exports](/docs/cloud/solana/) | For a longer worked example, see the [pump.fun launch pulse](/docs/mcp/trading/examples/pumpfun-launch-pulse/). Plans and the trial are on the [Bitquery MCP server page](https://bitquery.io/products/bitquery-mcp-server?ref=docs-mcp-solana#pricing). --- ## Solana 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 Shred Streams URL: https://docs.bitquery.io/docs/streams/protobuf/chains/Solana-protobuf/ Solana Shred Streams with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. See examples in the Bitquery IDE. # Solana Shred Streams This section provides details about Bitquery's Solana Shred Streams via Kafka. The top-level Kafka section explains how we use Kafka Streams to deliver data. You can find the schema [here](https://github.com/bitquery/streaming_protobuf/tree/main/solana). Remember that Solana blocks are produced with a target block time of 400ms, in practice resulting in high throughput of approximately 4,000 transactions per second while achieving a theoretical maximum of 65,000 transactions per second (TPS). :::info USD Values All amounts in the Solana protobuf streams now include USD equivalents — token transfer amounts, DEX trade sides, transaction fees, and balance updates each carry an `...InUSD` field (e.g. `AmountInUSD`, `FeeInUSD`, `PostBalanceInUSD`). These are populated in real time on the streams. ::: ## Structure of On-Chain Data The Solana Protobuf Streams provide three main message types for different use cases: - `BlockMessage`: Basic blocks, transactions, and rewards - `TokenBlockMessage`: Focused on token transfers and currency metadata - `DexParsedBlockMessage`: Specialized for DEX (Decentralized Exchange) activity Perpetual futures activity has its own topic, `solana.perpetual.proto` (`PerpetualBlockMessage`) — documented on the [Solana Perpetuals Stream](/docs/streams/protobuf/chains/Solana-perpetual-protobuf) page. ### Block-Level Data Each block in the stream includes a `BlockHeader` with fields such as: - `Slot`: The slot number for this block - `Hash`: The unique identifier of the block - `ParentSlot`: The previous slot in the chain - `Height`: The block height - `Timestamp`: The Unix timestamp when this block was produced - `ParentHash`: The hash of the parent block ### Transaction-Level Data Transactions across all stream types share common elements: - `Signature`: The transaction's unique signature - `Status`: The execution status (Success/Error) - `Header`: Transaction metadata including fees and signers - `FeeInUsd`: Equivalent transaction fee in US dollars - `Index`: Position within the block #### Transaction Header The `Header` (`TransactionHeader`) carries: - `Fee`: Transaction fee in lamports - `FeePayer`: Account that paid the fee - `RecentBlockhash`: Blockhash the transaction was built against - `Signer`: Primary signer - `Signatures`: All transaction signatures - `Accounts`: Accounts referenced by the transaction (address, signer/writable flags, token info) - `TransactionConfig`: Execution parameters for V1 transactions (see below) #### V1 Transactions: `TransactionConfig` Solana V1 transactions store execution parameters in a dedicated message field instead of ComputeBudget program instructions. Bitquery exposes them in `Header.TransactionConfig`: | Field | Type | Description | | ----------------------------- | ------ | -------------------------------------------- | | `PriorityFee` | uint64 | Priority fee set for the transaction | | `ComputeUnitLimit` | uint32 | Maximum compute units the transaction can use | | `LoadedAccountsDataSizeLimit` | uint32 | Maximum size of account data that can be loaded | | `HeapSize` | uint32 | Requested heap size | All four fields are optional. - **V1 transactions:** `TransactionConfig` is set, and it is the **only** place these values appear. - **Legacy and V0 transactions:** `TransactionConfig` is **unset**. Read these values from the ComputeBudget program instructions in the instruction list, as before. :::tip To get priority fees or compute limits across all transaction versions, check `Header.TransactionConfig` first. If it is not set, fall back to decoding ComputeBudget instructions. ::: ```python from solana import block_message_pb2 def print_tx_config(raw_bytes: bytes): block = block_message_pb2.BlockMessage() block.ParseFromString(raw_bytes) for tx in block.Transactions: if tx.Header.HasField("TransactionConfig"): cfg = tx.Header.TransactionConfig print(tx.Signature.hex(), "priority fee:", cfg.PriorityFee, "compute unit limit:", cfg.ComputeUnitLimit) else: # Legacy / V0: decode ComputeBudget instructions instead pass ``` Use `bitquery-pb2-kafka-package` version 0.2.34 or later to get this field in Python. Transactions contain various types of instructions, which are the core of Solana's execution model: - `ProgramAccountIndex`: The program being called - `Data`: Encoded instruction data - `AccountIndexes`: Accounts referenced by this instruction - `BalanceUpdates`: SOL balance changes from this instruction ### Token Data The `TokenBlockMessage` stream provides detailed information about token transfers and balances: - `Transfer`: Records token movements with: - `Amount`: Number of tokens transferred - `Sender`: Source account - `Receiver`: Destination account - `Authority`: Account authorizing the transfer - `Currency`: Detailed token information - `AmountInUSD`: USD value of the transferred amount - `Currency`: Rich metadata for each token, including: - `Name`, `Symbol`, `Decimals` - `MintAddress`: Token's mint account - `MetadataAddress`: Metadata program account - `TokenCreators`: Original creators of the token - NFT properties like `SellerFeeBasisPoints` and `TokenStandard` - `PriceInUSD`: Current USD price of the token - `TotalSupplyInUSD`: USD value of the token's total supply The `solana.tokens.proto` topic uses this message type to share details of: #### Account Addresses - These are listed under the "Accounts" section of the transaction header. #### Balance Updates - These are listed under "BalanceUpdates", with each update linked to an account using the `AccountIndex`. - Each balance update has: - **PreBalance:** The balance of the account before the transaction. - **PostBalance:** The balance of the account after the transaction. - **Currency Details:** Information about the currency type (e.g., Solana (SOL), Wrapped Solana (WSOL)). - **PreBalanceInUSD / PostBalanceInUSD:** USD value of the balance before and after the transaction. #### Balance Updates After Each Instruction - These updates are shown under the "BalanceUpdates" section within each instruction of the transaction. - These updates reflect the immediate effect of an instruction on the balance of the involved wallets. - For example, if an instruction transfers a certain amount from one wallet to another, the balance update directly after this instruction will reflect the new balances for both wallets. #### Balance Updates After the Entire Transaction - These updates are shown under the "BalanceUpdates" section at the transaction level. - They show the final state of the balances after all instructions in that transaction have been executed. - This is essentially the final balance state of all wallets involved in that transaction. ### DEX (Decentralized Exchange) Data The `DexParsedBlockMessage` stream is specialized for decentralized exchange activity. Each transaction in this stream contains `Trades`, `OrderEvents`, and `PoolEvents` arrays, along with transaction-level balance summaries. #### DexInfo Details about the exchange program: - `ProgramAddress`: Address of the DEX program - `ProtocolName`: Name of the DEX (e.g., "cp_amm", "pump_amm") - `ProtocolFamily`: Family of DEX protocols (e.g., "Meteora", "Pumpswap", "Raydium") #### DexTradeEvent Records of trades executed on DEXs, including full instruction-level data: - `InstructionIndex`: Position of the instruction within the transaction - `Dex`: The `DexInfo` for this trade - `Market`: The trading pair information - `MarketAddress`: Pool/market address - `BaseCurrency` / `QuoteCurrency`: Detailed currency metadata for both sides of the pair (Name, Symbol, Decimals, MintAddress, MetadataAddress, TokenStandard, Uri, etc.) - `Buy` / `Sell`: Both sides of the trade, each containing: - `Amount`: Raw token amount (in the token's smallest unit) - `AmountInUsd`: USD value of the trade side - `Currency`: Detailed token metadata (Name, Symbol, Decimals, MintAddress, MetadataAddress, TokenStandard, etc.) - `Account`: The token account involved (Address, IsSigner, IsWritable) with an optional `Token` sub-object containing `Mint`, `Owner`, `Decimals`, `ProgramId`, and `Supply` - `Order`: Linked DEX order information when the trade fills a specific limit order (see `DexOrder` below) - `Fee`: DEX trading fee in the quote currency's smallest unit - `Royalty`: Creator royalties paid (in the quote currency's smallest unit) - `Instruction`: Full `ParsedIdlInstruction` containing: - `Program`: Parsed IDL program info (Address, Name, Method, Signature, Arguments with Name/Type/Json, and the full IDL JSON) - `AccountNames`: Ordered list of account names from the IDL - `Accounts`: Account details with token sub-objects (Mint, Owner, Decimals, ProgramId, Supply) - `Logs`: Program logs emitted during execution - `BalanceUpdates`: Native SOL balance changes caused by this instruction (with `AccountIndex`, `PreBalance`, `PostBalance`) - `TokenBalanceUpdates`: SPL token balance changes caused by this instruction (with `AccountIndex`, `PreBalance`, `PostBalance`) - `AncestorIndexes`, `CallerIndex`, `ExternalSeqNumber`, `InternalSeqNumber`, `Depth`: Instruction hierarchy and sequencing metadata - `Data`: Raw encoded instruction data #### DexOrderEvent Records of DEX order lifecycle events (open, update, cancel). Each event contains: - `InstructionIndex`: Position of the instruction within the transaction - `Type`: Order event type — `OPEN`, `UPDATE`, or `CANCEL` - `Dex`: The `DexInfo` for this order - `Market`: The trading pair information - `Order`: The `DexOrder` details: - `OrderId`: Unique identifier for the order - `BuySide`: Whether this is a buy (true) or sell (false) order - `LimitPrice`: Limit price set for the order - `LimitAmount`: Amount of tokens in the order - `LimitPriceInUsd` / `LimitAmountInUsd`: USD equivalents - `Account`: Token account for the order - `Owner`: Wallet that owns the order - `Payer`: Fee payer for the order transaction - `Mint`: Token mint address - `Instruction`: Full `ParsedIdlInstruction` (same structure as in `DexTradeEvent`) #### PoolLiquidityChangeEvent Records changes to liquidity pools (adds, removes, swaps that change pool reserves): - `InstructionIndex`: Position of the instruction within the transaction - `Dex`: The `DexInfo` for this pool - `Market`: The trading pair information - `BaseCurrency` / `QuoteCurrency`: Each side contains: - `ChangeAmount`: Amount added (positive) or removed (negative) - `PostAmount`: Pool balance after the change - `ChangeAmountInUsd` / `PostAmountInUsd`: USD equivalents - `Instruction`: Full `ParsedIdlInstruction` (same structure as in `DexTradeEvent`) #### 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 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 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 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 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) --- ## Solana gRPC Streams (CoreCast): 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. --- ## 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/). --- ## 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 - [Arc Mainnet](#arc-mainnet) - [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) ## Arc Mainnet ### Trades #### Quick start: latest Arc mainnet swaps This query returns the newest swaps with USD values and the DEX name. ▶️ [Quick start: latest Arc mainnet swaps](https://ide.bitquery.io/arc-mainnet-docs-overview-quick-start-latest-arc-mainnet-swaps) #### Latest trades on Arc The most recent swaps on the network. `Trade.Buy` is the currency the trader received and `Trade.Sell` is what they paid. ▶️ [Latest trades on Arc](https://ide.bitquery.io/arc-mainnet-latest-dex-trades) #### Trades of a token on Arc `DEXTradeByTokens` returns one row per token side of every trade, so a token filter catches it whether it was bought or sold. `Side.Type` says which direction the trade was from the token's point of view. ▶️ [Trades of a token on Arc](https://ide.bitquery.io/arc-mainnet-trades-of-a-token) #### Trades on one DEX on Arc Filter by `Dex.ProtocolName`. Values seen on Arc mainnet are `uniswap_v4`, `uniswap_v3`, `uniswap_v2`, `curve_v1` and `aerodrome_v1`. ▶️ [Trades on one DEX on Arc](https://ide.bitquery.io/arc-mainnet-uniswap-v4-trades) #### Trades in one pool on Arc For Uniswap v2 and v3 the pool has its own address in `Trade.Dex.SmartContract`. This example reads a live v3 BUILDOG/USDC pool. ▶️ [Trades in one pool on Arc](https://ide.bitquery.io/arc-mainnet-trades-in-a-pool) #### Trades of a wallet on Arc `Transaction.From` is the externally owned account that signed the swap. `Trade.Buy.Buyer` and `Trade.Sell.Seller` are the addresses that received and paid the tokens, which can be a router rather than the signer. ▶️ [Trades of a wallet on Arc](https://ide.bitquery.io/arc-mainnet-trades-of-a-wallet) #### Most traded tokens on Arc Tokens ranked by trade count over the last 24 hours. Native USDC is the quote on most pools, so it tops the list; the rows under it are the tokens people actually trade. ▶️ [Most traded tokens on Arc](https://ide.bitquery.io/arc-mainnet-most-traded-tokens) #### Trade count by DEX protocol on Arc Which DEXes carry mainnet volume. Uniswap v4 led the launch-day check. ▶️ [Trade count by DEX protocol on Arc](https://ide.bitquery.io/arc-mainnet-trades-by-dex) #### Most active traders on Arc Signers ranked by swap count. The top rows often include bots and routers, so inspect the address before treating it as a person. ▶️ [Most active traders on Arc](https://ide.bitquery.io/arc-mainnet-most-active-traders) ### Transfers #### Latest transfers on Arc The most recent token and native USDC transfers on Arc mainnet. ▶️ [Latest transfers on Arc](https://ide.bitquery.io/arc-mainnet-latest-transfers) #### Native USDC transfers on Arc `Currency: {Native: true}` selects value transfers of the gas token. The floor of 100 USDC keeps dust and fee movements out. ▶️ [Native USDC transfers on Arc](https://ide.bitquery.io/arc-mainnet-native-usdc-transfers) #### Transfers of a token on Arc Filter on the token contract. This example reads the ERC-20 USDC interface; swap in EURC or any test token. ▶️ [Transfers of a token on Arc](https://ide.bitquery.io/arc-mainnet-erc20-usdc-transfers) #### Transfers of an address on Arc Incoming and outgoing transfers in one list. Replace the address with any wallet or contract. ▶️ [Transfers of an address on Arc](https://ide.bitquery.io/arc-mainnet-transfers-of-an-address) #### Sent and received totals per token on Arc Two aliased selections give the outbound and inbound sums per currency for a wallet. ▶️ [Sent and received totals per token on Arc](https://ide.bitquery.io/arc-mainnet-address-sent-received) #### Transfers between two addresses on Arc Flows from one address to another, in either direction. Useful for tracing a faucet, a bridge or a counterparty. ▶️ [Transfers between two addresses on Arc](https://ide.bitquery.io/arc-mainnet-transfers-between-addresses) #### Large transfers on Arc This catches ERC-20 USDC moves above 10,000 and returns both token and USD amounts. ▶️ [Large transfers on Arc](https://ide.bitquery.io/arc-mainnet-large-usdc-transfers) #### Most transferred tokens on Arc Tokens ranked by transfer count over 24 hours, with distinct senders and receivers. The system ledger address is excluded. ▶️ [Most transferred tokens on Arc](https://ide.bitquery.io/arc-mainnet-most-transferred-tokens) #### Hourly transfer volume of a token on Arc Transfer volume of ERC-20 USDC bucketed by hour, for charts and alerts. ▶️ [Hourly transfer volume of a token on Arc](https://ide.bitquery.io/arc-mainnet-hourly-transfer-volume) ### Balances & Holders #### Portfolio of a wallet on Arc Every currency an address holds, with the computed balance and when it last changed. Native USDC has `Native: true`; the ERC-20 interface at `0x3600...` is listed separately. ▶️ [Portfolio of a wallet on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-portfolio-of-a-wallet) #### Balance of one token on Arc The `balanceOf` equivalent for ERC-20 USDC. For the gas token use `Currency: {Native: true}` instead of a contract filter. ▶️ [Balance of one token on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-balance-of-one-token) #### Balances of several wallets on Arc One call for a batch of addresses, grouped by address and currency. ▶️ [Balances of several wallets on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-balances-of-several-wallets) #### Top holders of a token on Arc Current EURC holders ranked by token balance. Add `Balance: {Amount: {gt: "0"}}` so wallets that once held the token but now hold zero do not appear. ▶️ [Top holders of a token on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-top-holders-of-a-token) #### Balance history of a wallet on Arc Each change to a wallet's ERC-20 USDC balance, newest first, with the transaction behind it. Positive amounts are inflows. ▶️ [Balance history of a wallet on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-balance-history-of-a-wallet) #### Net change per currency over a window on Arc Sum the updates per currency to see what a wallet gained or lost over the last 24 hours. ▶️ [Net change per currency over a window on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-net-change-per-currency-over-a-window) ### Price & OHLC #### OHLCV candles for a token on Arc Hourly candles for EURC priced in ERC-20 USDC. `Block.Time(interval: ...)` buckets the trades; `open` and `close` take the price at the lowest and highest block in the bucket. Change `count` and `in` for other intervals. ▶️ [OHLCV candles for a token on Arc](https://ide.bitquery.io/arc-mainnet-ohlcv-candles) #### Latest price of a token on Arc The price of the most recent EURC trade against ERC-20 USDC. `Trade.PriceInUSD` is populated on Arc mainnet. ▶️ [Latest price of a token on Arc](https://ide.bitquery.io/arc-mainnet-latest-token-price) ### Supply & Market Cap #### Total supply of a token on Arc `TransactionBalances` records the token's total supply after each transaction that touched it. The latest row is the current supply, already adjusted for decimals. ▶️ [Total supply of a token on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-total-supply-of-a-token) ### Liquidity & Pools #### New Uniswap v4 pools on Arc Uniswap v4 carried most launch-day swaps. A new pool is an `Initialize` event on the PoolManager; its arguments give the pool `id`, the two currencies, the fee tier, tick spacing, hook address and opening price. ▶️ [New Uniswap v4 pools on Arc](https://ide.bitquery.io/arc-mainnet-new-uniswap-v4-pools) #### New Uniswap v3 and v2 pools on Arc Several v3 and v2 factory deployments appeared on mainnet, so filter on the event name rather than one factory address. `PoolCreated` is v3, `PairCreated` is v2; both carry the two tokens and the new pool address in their arguments. ▶️ [New Uniswap v3 and v2 pools on Arc](https://ide.bitquery.io/arc-mainnet-new-v3-v2-pools) ### Transactions #### Latest transactions on Arc The most recent transactions on Arc mainnet, newest first. ▶️ [Latest transactions on Arc](https://ide.bitquery.io/arc-mainnet-latest-transactions) #### Transaction by hash on Arc The equivalent of `eth_getTransactionByHash` plus `eth_getTransactionReceipt` in one call. The example hash is a live USDC value transfer; replace it with any recent hash. ▶️ [Transaction by hash on Arc](https://ide.bitquery.io/arc-mainnet-transaction-by-hash) #### Transactions of an address on Arc Sent and received transactions of one address, newest first. This is the explorer's address page. ▶️ [Transactions of an address on Arc](https://ide.bitquery.io/arc-mainnet-transactions-of-an-address) #### Failed transactions on Arc Transactions whose receipt status is 0. Join the [reverted calls](/docs/blockchain/arc-mainnet/arc-mainnet-calls-api/#reverted-calls) query on the hash to see the revert reason. ▶️ [Failed transactions on Arc](https://ide.bitquery.io/arc-mainnet-failed-transactions) #### Gas fees in USDC on Arc Because gas is paid in USDC, `Fee.SenderFee` is already a dollar amount. This gives the average, median and total fee per hour along with the average effective gas price. ▶️ [Gas fees in USDC on Arc](https://ide.bitquery.io/arc-mainnet-gas-fee-statistics) ### Events & Calls #### Latest calls on Arc The most recent top-level calls, one per transaction. ▶️ [Latest calls on Arc](https://ide.bitquery.io/arc-mainnet-latest-calls) #### Calls of one method on Arc Filter on the decoded method name and the contract. This reads `transfer` calls into the ERC-20 USDC contract with their decoded arguments. ▶️ [Calls of one method on Arc](https://ide.bitquery.io/arc-mainnet-calls-of-a-method) #### Calls by 4-byte selector on Arc When the ABI is not registered, filter on the selector in `Call.Input` instead. This matches `approve(address,uint256)` by its `0x095ea7b3` prefix on any contract. ▶️ [Calls by 4-byte selector on Arc](https://ide.bitquery.io/arc-mainnet-calls-by-selector) #### Internal calls of a transaction on Arc The full call tree of one transaction, ordered by call index. Replace the hash with any recent transaction from the [Transactions API](/docs/blockchain/arc-mainnet/arc-mainnet-transactions-api/). ▶️ [Internal calls of a transaction on Arc](https://ide.bitquery.io/arc-mainnet-internal-calls-of-transaction) #### Contract deployments on Arc `Call.Create: true` marks a call that deployed a contract. The new address is in `Receipt.ContractAddress` for top-level deployments; for factory deployments read `Call.To` on the create call. ▶️ [Contract deployments on Arc](https://ide.bitquery.io/arc-mainnet-contract-deployments) #### Reverted calls on Arc Calls that reverted, with the error string when the EVM returned one. Useful for debugging a contract under test. ▶️ [Reverted calls on Arc](https://ide.bitquery.io/arc-mainnet-reverted-calls) #### Most called methods on Arc Method signatures ranked by call count over 24 hours. ERC-20 `transfer`, `balanceOf` and `approve` dominate, followed by Uniswap v4 hook callbacks. ▶️ [Most called methods on Arc](https://ide.bitquery.io/arc-mainnet-most-called-methods) #### Calls that move native USDC on Arc Internal calls that carried native USDC value. This is how value moves between contracts shows up, since those movements are not ERC-20 `Transfer` events. ▶️ [Calls that move native USDC on Arc](https://ide.bitquery.io/arc-mainnet-calls-with-value) #### Events from one contract on Arc `LogHeader.Address` is the `address` filter of `eth_getLogs`. This reads the latest events of the ERC-20 USDC contract. ▶️ [Events from one contract on Arc](https://ide.bitquery.io/arc-mainnet-events-from-a-contract) #### One event across all contracts on Arc Filter by decoded signature name to watch one event type from every contract that emits it. This catches every `Swap`, from Uniswap v2 pairs, v3 pools and the v4 PoolManager alike. ▶️ [One event across all contracts on Arc](https://ide.bitquery.io/arc-mainnet-swap-events) #### Filter by raw topic0 on Arc When you have the signature hash rather than the name, filter on `Log.Signature.SignatureHash`. This is the ERC-20 `Transfer(address,address,uint256)` hash, written without `0x`. ▶️ [Filter by raw topic0 on Arc](https://ide.bitquery.io/arc-mainnet-events-by-topic0) #### Filter by a decoded argument on Arc Server-side filtering on decoded values is what a node cannot do. This finds every event whose argument named `to` equals a wallet, across all contracts and signatures. ▶️ [Filter by a decoded argument on Arc](https://ide.bitquery.io/arc-mainnet-events-by-argument) #### Busiest contracts and signatures on Arc Which contracts and event types dominate the log stream over 24 hours. Run this first on any network you have not explored yet. ▶️ [Busiest contracts and signatures on Arc](https://ide.bitquery.io/arc-mainnet-busiest-event-contracts) #### Undecoded events on Arc Events whose ABI is not registered arrive with an empty `Signature.Name` and no `Arguments`, but the raw `Topics` and `Log.SmartContract` are still there. This lists the contracts emitting the most undecoded events; if one matters to you, ask support to register its ABI. ▶️ [Undecoded events on Arc](https://ide.bitquery.io/arc-mainnet-undecoded-events) ### Launchpads #### Latest launches on Arc Use the same filters with `query`, a row limit, and descending block time to fetch the newest launches. ▶️ [Latest launches on Arc](https://ide.bitquery.io/arc-mainnet-docs-launchpads-latest-launches) #### Launch count by platform on Arc Group launch events by emitting contract to compare activity during the last hour. The result uses contract addresses, so map them to the table above in your app. ▶️ [Launch count by platform on Arc](https://ide.bitquery.io/arc-mainnet-docs-launchpads-launch-count-by-platform) #### Trades for a launched token on Arc Copy the token address from `Topics[1]` into `Trade.Currency.SmartContract`. This example follows a token launched through RadarDEX. ▶️ [Trades for a launched token on Arc](https://ide.bitquery.io/arc-mainnet-docs-launchpads-trades-for-a-launched-token) #### OHLCV for a launched token on Arc This query builds five-minute candles for the same token against Arc's ERC-20 USDC interface. It returns USD volume, open, high, low, close, and trade count. ▶️ [OHLCV for a launched token on Arc](https://ide.bitquery.io/arc-mainnet-docs-launchpads-ohlcv-for-a-launched-token) ### Blocks & Validators #### Datasets and history on Arc On 16 September 2026, only the realtime path answered. Its depth changes, so measure the current window before running a long-range query. ▶️ [Datasets and history on Arc](https://ide.bitquery.io/arc-mainnet-docs-overview-datasets-and-history) #### Latest blocks on Arc Change `query` to `subscription` and drop `limit` and `orderBy` to receive each block header as it is indexed. ▶️ [Latest blocks on Arc](https://ide.bitquery.io/arc-mainnet-latest-blocks) #### Block by number on Arc Header, gas and transaction count of one Arc mainnet block. ▶️ [Block by number on Arc](https://ide.bitquery.io/arc-mainnet-block-by-number) #### Block and throughput statistics on Arc Blocks, transactions, average transactions per block and average gas per block for each of the last 24 hours. Divide the block count by 3600 to get blocks per second. ▶️ [Block and throughput statistics on Arc](https://ide.bitquery.io/arc-mainnet-block-statistics) ## 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 #### Latest Bitcoin price The current BTC price in USD from the [Crypto Price API](/docs/trading/crypto-price-api/currency). `bid:bitcoin` blends native BTC, WBTC, cbBTC and other wrapped versions across chains into one price, returned with USD volume and market cap. ▶️ [Latest Bitcoin price](https://ide.bitquery.io/Latest-Bitcoin-Price-Trading-API) #### Latest Bitcoin price on each chain One latest USD price per BTC representation (WBTC on Ethereum, cbBTC on Base and so on) from the [Tokens cube](/docs/trading/crypto-price-api/tokens). Use it to spot a wrapped BTC trading away from the blended price. ▶️ [Latest Bitcoin price on each chain](https://ide.bitquery.io/Latest-Bitcoin-Price-on-Each-Chain) #### Latest BTC/USDT price on every market The latest BTC/USDT price from each DEX market across chains, one row per market. Useful for comparing venues and finding arbitrage gaps. ▶️ [Latest BTC/USDT price on every market](https://ide.bitquery.io/Find-arbitrage-opportunity-with-same-token-across-chains_1) #### 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) #### 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) #### 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 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 - [Arc Mainnet](#arc-mainnet) - [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) ## Arc Mainnet ### Trades #### Stream real-time trades on Arc One WebSocket delivers every swap on the network as blocks are indexed, with both sides, the protocol and the trader. ▶️ [Stream real-time trades on Arc](https://ide.bitquery.io/arc-mainnet-stream-dex-trades) ### Transfers #### Stream real-time transfers on Arc Every transfer on the network as it is indexed. Filter inside `where` to narrow the socket to a token, an address or a size floor. ▶️ [Stream real-time transfers on Arc](https://ide.bitquery.io/arc-mainnet-stream-transfers) ### Balances & Holders #### Stream balance changes on Arc Every balance change of a wallet as it happens. Widen the filter to a list of addresses or a single token to build alerts. ▶️ [Stream balance changes on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-stream-balance-changes) ### Supply & Market Cap #### Stream supply changes on Arc A new row arrives whenever a mint or burn changes the supply of the token. ▶️ [Stream supply changes on Arc](https://ide.bitquery.io/arc-mainnet-docs-balances-stream-supply-changes) ### Transactions #### Stream transactions on Arc Every transaction as blocks are indexed. Arc produces a block well under every second, so expect a steady feed. ▶️ [Stream transactions on Arc](https://ide.bitquery.io/arc-mainnet-stream-transactions) ### Events & Calls #### Stream calls to a contract on Arc Every call into the Uniswap v4 PoolManager, internal or top-level, as it happens. ▶️ [Stream calls to a contract on Arc](https://ide.bitquery.io/arc-mainnet-stream-calls-to-contract) #### Stream all events on Arc One socket, every event on the chain. Good for building an indexer; heavy for anything else, so use the filtered streams below in production. ▶️ [Stream all events on Arc](https://ide.bitquery.io/arc-mainnet-stream-all-events) ### Launchpads #### Stream launches on Arc Change nothing else to receive launches from all six platforms over one WebSocket. Add or remove contract and signature pairs as launchpads deploy new versions. ▶️ [Stream launches on Arc](https://ide.bitquery.io/arc-mainnet-docs-launchpads-stream-launches) ## 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 ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/blocks/55080300_55080349.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/stellar/blocks/55080300_55080349.parquet") print(df.info()) df.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 Stellar data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - **GraphQL subscriptions** --- ## 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. --- ## Tools & SDKs Directory URL: https://docs.bitquery.io/docs/tools-directory/ Bitquery tools and SDKs: live apps and dashboards, open-source GitHub apps, charting and trading tools, OpenClaw agent skills, and npm packages. # 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. For the full product, see [AI Investigations](https://bitquery.io/solutions/ai-investigations). --- ## 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. --- ## Trading Data on the Bitquery MCP — Overview URL: https://docs.bitquery.io/docs/mcp/trading/overview/ Trading Data on the Bitquery MCP — Overview with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Trading Data on the Bitquery MCP The [Bitquery MCP server](/docs/mcp/mcp-server/) plugs your AI agent directly into Bitquery's **trading dataset** — the same data that powers the [Crypto Trades API](/docs/trading/crypto-trades-api/trades-api/), [Crypto Price API](/docs/trading/crypto-price-api/), [TradingView feeds](/docs/usecases/tradingview-subscription-realtime/getting-started/), and our GraphQL endpoints. Ask in plain English, get clean rows back. No SQL required. ## At a Glance | | | |---|---| | **Endpoint** | [`https://mcp.bitquery.io`](https://mcp.bitquery.io) | | **Chains** | Solana, Ethereum, BSC, Base, Arbitrum, Optimism, Polygon (Matic), Tron, Robinhood | | **Granularity** | Per-trade rows + pre-aggregated 1m / 5m / 1h / 1d cubes | | **Outlier filter** | Built in — just say "skip wash-traded pools" in your prompt | | **Latency** | Near real-time, updates as blocks land | | **Coverage** | Years of history on every supported chain | ## Chains and DEX Protocols Live on the MCP today: | Network | DEXs / venues exposed | |---|---| | **Solana** | Raydium, Pumpfun, PumpSwap, Meteora (DLMM, DAMM v2, Dynamic Bonding Curve), Orca Whirlpool, BonkSwap, Lifinity, Phoenix, OpenBook, Manifest, MagicEden, Moonshot, Believe, LetsBonk, Heaven, Goonfi, Bags.fm, Trends.fun, Jupiter Studio, Boop.fun, Aldrin, SolFi, Orbic, xStocks, Jupiter Z (RFQ), Tessera V, HumidiFi, QuantumAMM, Scorch, … | | **Ethereum** | Uniswap (v2/v3/v4), PancakeSwap, Curve, Balancer, 1inch, Bancor, KyberNetwork, Mooniswap, Magpie, Seaport, … | | **Binance Smart Chain** | PancakeSwap (incl. Infinity), Uniswap, FourMeme, Flap, Magpie, Aerodrome, Bancor, Balancer, 1inch, … | | **Base** | Aerodrome, Uniswap (incl. v4), PancakeSwap, Zora, Magpie, Apestore, Clanker, JumpBase, Seaport, … | | **Arbitrum** | Uniswap, PancakeSwap, Curve, Balancer, Magpie, GMX, esGMX, … | | **Optimism** | Uniswap, Aerodrome, Balancer, PancakeSwap, … | | **Polygon (Matic)** | Uniswap, PancakeSwap, Balancer, Polymarket, Seaport, … | | **Tron** | SunSwap, SunPump | | **Robinhood** | Uniswap (v2/v3/v4), PancakeSwap, Balancer, Aerodrome, Curve, Flap, Bags.fm, … | Per-chain coverage details live in the [Blockchains section](/docs/blockchain/introduction/). ## What's on Every Trade For each swap, the agent can pull: - **When** — block date and time, down to the millisecond. - **What** — the base token (network, contract, name, symbol) and the quote token (USDC, WETH, SOL, …). - **Where** — the DEX (Meteora, Pumpswap, Raydium, Uniswap, …) and the specific pool address. - **How much** — base and quote amounts, both in USD; the realised price; whether it was a buy or a sell. - **Who** — the trader's wallet, the transaction hash, the fee payer. - **Token economics at the moment of the trade** — total, circulating, and max supply; market cap; fully diluted valuation. - **A quality score** — Bitquery's outlier ranking, so you can tell real liquidity from wash-traded noise in one filter. ## Two Levels of Granularity The dataset gives you two views of the same trades: 1. **Per-trade rows** — one row per swap. Best for replays, audits, wallet PnL, sniping research, and any trader-level breakdown. 2. **Pre-built candles** at 1-minute, 5-minute, hourly, and daily intervals — with OHLC, multiple price averages, USD volume, and a supply snapshot on every row. Best for charts, dashboards, and trends. When you ask the agent for "candles", "OHLC", "hourly volume", or "trend", it picks the candle view. When you ask for "trades", "swaps", "wallet history", or "the last 100 buys", it picks the per-trade view. You don't have to think about it. ## Outlier Filtering Is Built In Every row carries a quality score from Bitquery's [price-index ranking](/docs/trading/crypto-price-api/price-index-algorithm/). Pools with low scores are noisy, wash-traded, or thinly liquid. To activate it, just say *"skip wash-traded pools"* or *"only clean volume"* in your prompt — the agent applies the filter automatically. Companion read: [How to filter anomaly prices](/docs/usecases/how-to-filter-anomaly-prices/). ## Where to Go Next - [**Worked examples with charts**](/docs/mcp/trading/examples/) — six self-contained trader workflows with prompts and real-data charts: - [Hottest Solana Tokens](/docs/mcp/trading/examples/top-tokens-discovery/) - [Cross-Chain DEX Snapshot](/docs/mcp/trading/examples/cross-chain-snapshot/) - [Build an OHLC Candle Chart](/docs/mcp/trading/examples/token-ohlc-chart/) - [Solana DEX Market Share Battle](/docs/mcp/trading/examples/solana-dex-market-share/) - [Pump.fun Launch Pulse](/docs/mcp/trading/examples/pumpfun-launch-pulse/) - [Decode a Whale Wallet](/docs/mcp/trading/examples/whale-wallet-decode/) - [**What you can do with it**](/docs/mcp/trading/use-cases/) — eleven common patterns with the natural-language prompts that trigger them, plus best practices for prompting. - [**MCP server landing**](/docs/mcp/mcp-server/) — install, OAuth, architecture. - [**Crypto Price Index Algorithm**](/docs/trading/crypto-price-api/price-index-algorithm/) — how outlier filtering and ranking are computed. - [**Supply fields**](/docs/trading/crypto-price-api/supply-fields/) — what `MarketCap`, `FDV`, `CirculatingSupply` mean and how they are derived. --- ## Trading MCP Examples — Real Data, Real Charts URL: https://docs.bitquery.io/docs/mcp/trading/examples/ Trading MCP Examples — Real Data, Real Charts with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Trading MCP Examples Six worked examples of what your AI agent can do once the [Bitquery MCP server](/docs/mcp/mcp-server/) is connected. Each page is **self-contained** and includes: - The trader question in plain language - The exact prompt to paste into Claude / Cursor / ChatGPT - A chart of the live result (built from real production data, snapshot **2026-04-23**) - A "What this tells a trader" insight section - A "trader playbook" with conversational tweaks the agent will handle - One-sentence variations the agent will handle without further prompting | # | Example | What it shows | |---|---|---| | 1 | [**Hottest Solana Tokens**](/docs/mcp/trading/examples/top-tokens-discovery/) | Top 10 Solana tokens by clean 24h USD volume — your morning watchlist. | | 2 | [**Cross-Chain DEX Snapshot**](/docs/mcp/trading/examples/cross-chain-snapshot/) | 24h USD volume, trade count, and unique traders for all 9 chains in one query. | | 3 | [**Build an OHLC Candle Chart**](/docs/mcp/trading/examples/token-ohlc-chart/) | 24h hourly candlesticks for any token on any chain, ready for TradingView. | | 4 | [**Solana DEX Market Share Battle**](/docs/mcp/trading/examples/solana-dex-market-share/) | Meteora vs Pumpswap vs Raydium vs Orca and the long tail. | | 5 | [**Pump.fun Launch Pulse**](/docs/mcp/trading/examples/pumpfun-launch-pulse/) | New tokens launched per hour — diurnal patterns and meta cooldowns. | | 6 | [**Decode a Whale Wallet**](/docs/mcp/trading/examples/whale-wallet-decode/) | Per-token buy / sell / net flow for a single wallet; spot bots vs humans. | > **Reproducibility:** every chart in this section is rendered from a live query you can re-run via the MCP yourself. The numbers will move; the patterns and the prompts will not. --- ## Trading MCP — What You Can Do With It URL: https://docs.bitquery.io/docs/mcp/trading/use-cases/ Trading 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. # Trading MCP — What You Can Do With It These are the patterns we see most often when teams plug the [Bitquery MCP server](/docs/mcp/mcp-server/) 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. For end-to-end worked answers — including the live data table and a chart — see the [examples section](/docs/mcp/trading/examples/). --- ## 1. Token Discovery and Trending > *"What are the top 10 Solana tokens by USD volume in the last 24 hours? Skip wash-traded pools."* You get a clean, ranked list of the most-traded tokens for any chain — your daily watchlist generator. The agent automatically applies Bitquery's outlier filter so the noise is already gone. **See it live:** [Hottest Solana Tokens](/docs/mcp/trading/examples/top-tokens-discovery/). ## 2. Trader Analytics and Realized PnL > *"Pull every trade for wallet `7xKX…` in the last 7 days. Compute realized PnL per token in USD."* Wallet-centric breakdown — token by token, with bought, sold, and net flow in USD. Same idea works for any wallet on any supported chain. For a GraphQL equivalent see the [Traders API](/docs/trading/crypto-trades-api/traders-api/). **See it live:** [Decode a Whale Wallet](/docs/mcp/trading/examples/whale-wallet-decode/). ## 3. OHLC Charts for Any Pool or Token > *"Give me 1-minute OHLC for the WIF/USDC pool on Raydium for the last 6 hours."* Pre-aggregated candles at any interval — 1m, 5m, 1h, daily — for any pool, token, or currency. Ready to drop into [TradingView](/docs/usecases/tradingview-subscription-realtime/getting-started/) or your bot. **See it live:** [Build an OHLC Candle Chart](/docs/mcp/trading/examples/token-ohlc-chart/). ## 4. Market Cap and FDV Monitoring > *"Which Base tokens crossed $10M market cap in the last 24 hours?"* Every token aggregate row carries the latest market cap and fully diluted valuation. Background on the math: [Supply fields](/docs/trading/crypto-price-api/supply-fields/). ## 5. Wash-Trade and Outlier Filtering > *"Show me 24h volume per chain, but only counting clean (non-wash-traded) flow."* Bitquery's price-index ranking is baked into every row. A simple "skip the noisy pools" instruction in your prompt is enough — no model to train, no list to maintain. Companion read: [How to filter anomaly prices](/docs/usecases/how-to-filter-anomaly-prices/) and the [price-index algorithm](/docs/trading/crypto-price-api/price-index-algorithm/). ## 6. New Token / Launch Monitoring > *"How many new tokens launched on Pump.fun in the last hour? How does that compare to the 24h average?"* Track launchpad activity in real time across **Pump.fun**, **LetsBonk**, **FourMeme**, **Boop**, **Bags**, **Believe**, **Heaven**, **Goonfi**, **Trends.fun**, **Meteora Dynamic Bonding Curve**, and more. Spot meta cooldowns and frenzy hours. **See it live:** [Pump.fun Launch Pulse](/docs/mcp/trading/examples/pumpfun-launch-pulse/). Per-launchpad GraphQL coverage: [Pump.fun](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/), [LetsBonk](/docs/blockchain/Solana/letsbonk-api/), [FourMeme](/docs/blockchain/BSC/four-meme-api/), [Meteora DBC](/docs/blockchain/Solana/meteora-dynamic-bonding-curve-api/). ## 7. Cross-Chain Market Overview > *"For each chain, show 24h DEX volume, number of trades, and number of unique traders."* A single sentence gets you a chain-by-chain comparison — no per-chain GraphQL juggling. Useful for spotting chain rotations and weighing where to deploy capital next. **See it live:** [Cross-Chain DEX Snapshot](/docs/mcp/trading/examples/cross-chain-snapshot/). ## 8. DEX Market Share Battles > *"Which Solana DEX is winning today's volume? Meteora vs Pumpswap vs Raydium vs Orca."* The agent ranks DEXs (Meteora, Pumpswap, Raydium, Uniswap, PancakeSwap, …) by 24h volume. The same pattern answers *"which DEX is the cheapest for this pair?"*, *"which DEX is the most retail-driven?"*, or *"which DEX has the most active market-makers?"* **See it live:** [Solana DEX Market Share](/docs/mcp/trading/examples/solana-dex-market-share/). ## 9. Sniping and Copy-Trading Research > *"Find Solana wallets that bought any token in the first 60 seconds of its first Pumpfun trade in the last 24 hours, then sold within 10 minutes for a positive USD PnL."* The same data behind production bots — [Solana sniper](/docs/usecases/solana-sniper-bot/), [Base sniper](/docs/usecases/base-sniper-bot/), [Arbitrum sniper](/docs/usecases/arbitrum-sniper-bot/), [copy-trading bot](/docs/usecases/copy-trading-bot/) — is queryable conversationally. Perfect for prototyping signals before you commit to a Kafka stream. ## 10. Slippage and Liquidity Inspection > *"For pool `0xabc…` on the last 100 trades, compute realized slippage relative to the volume-weighted price."* Every trade row carries price, USD amount, and side — enough to derive realised slippage and effective depth. Conceptual companion docs: [Ethereum slippage](/docs/blockchain/Ethereum/dextrades/ethereum-slippage-api/), [Base slippage](/docs/blockchain/Base/base-slippage-api/), [BSC slippage](/docs/blockchain/BSC/bsc-slippage-api/). ## 11. AI Agents and Trading Copilots The MCP is also the data layer for autonomous trading workflows: - **In a chat assistant** — Claude, Cursor, or ChatGPT answers ad-hoc data questions without context-switching to a separate IDE. - **In a coding agent** — Claude Code or Cursor generates ready-to-run analyses, charts, and alerts grounded in real on-chain data. - **In a custom agent loop** — pipe MCP tool calls into your own agent skill or trading bot. See the [AI Agent on Solana data](/docs/blockchain/Solana/ai-agent-solana-data/) and [AI Agent on Base data](/docs/blockchain/Base/ai-agent-base-data/) walkthroughs. --- ## 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 trading dataset is huge. Always tell the agent the window you care about: *"in the last 24 hours"*, *"yesterday vs the day before"*, *"since 09:00 UTC today"*. Without it, the agent may scan more data than it needs to (slow) or pick a default that doesn't match what you wanted. ### 2. Name the chain (or "all chains") Solana, Ethereum, BNB Smart Chain, Base, Arbitrum, Optimism, Polygon, and Tron are all in the same dataset. *"on Solana"* or *"across all chains"* keeps the agent's filter clean. ### 3. Ask for clean (non-wash-traded) data when relevant Just say *"skip wash-traded pools"* or *"only clean volume"*. The agent will apply Bitquery's outlier filter automatically. Use this for token discovery, market-cap rankings, and any time you want a "real" view of the market. ### 4. Pin the granularity for charts For OHLC and trend questions, name the bucket size: *"1-minute candles"*, *"hourly volume"*, *"daily for the last 30 days"*. Otherwise the agent guesses. ### 5. Give it the address if you have one If you know a token contract, pool address, or wallet, **paste it**. Address-based lookups are the fastest the MCP can do, and they avoid symbol collisions (there are dozens of tokens called "PEPE"). ### 6. Ask for the data shape you want *"Give me a markdown table I can paste"*, *"return JSON for my script"*, *"format it for a Telegram message"* — the agent will adapt. For chart-ready output: *"return rows with timestamp, open, high, low, close, volume"*. ### 7. Iterate, don't restart Once you've built a good question, refine it instead of starting over: *"same query, but for Base"*, *"same chart, but only memecoins"*, *"same wallet, but for the last 7 days"*. The agent keeps context. ### 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 analysis, ad-hoc questions, agent loops | **MCP** (this server) | | Application backend, predictable contract, subscriptions, mempool | [**GraphQL API**](/docs/intro/) and [WebSocket subscriptions](/docs/subscriptions/websockets/) | | Lowest-latency, highest-throughput streaming for production bots | [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) and [**gRPC streams**](/docs/grpc/solana/introduction/) | | Pre-built OHLC, market cap, token metadata over GraphQL | [**Crypto Price API**](/docs/trading/crypto-price-api/) | The MCP and the GraphQL API read the **same dataset**, so anything you discover via MCP is reproducible in GraphQL or your production stream. --- ## Transaction Cube URL: https://docs.bitquery.io/docs/cubes/transaction-cube/ Transaction cube reference: filter blockchain transactions by fields such as sender, receiver and hash, and compute metrics over them with GraphQL examples. # Transaction Cube Transaction Cube provides comprehensive information about transactions, blocks, receipts, fees, transaction status, signatures, and more. You can check all the fields in [this query](https://ide.bitquery.io/transaction-cube-with-all-fields). ![Transaction Cube Fields](/img/cubes/transactionCubeFields.png) ## Filtering in Transaction Cube Efficient blockchain filtering is one of the main strengths of our infrastructure. All cubes offer the ability to filter by any field available in the result. For example, if you can retrieve the transaction hash in the result, you can filter transactions based on it. Therefore, Transaction Cube can filter transactions based on transaction hash, value, fee, status, transaction sender, receiver, block details, receipt, signature, etc. By default all filters are `AND` operator. We will see example of `Or` operator later in examples. ### Transaction Filtering Examples Using the `From` filter in Transaction Cube, you can get all transactions sent by a specific address. Check [this query](https://ide.bitquery.io/Transactions-of-an-address) for an example. You can use one or multiple filters based on your requirements. Check [this example](https://ide.bitquery.io/Multiple-filters) to see how multiple filters can be applied. Additionally, you can use the OR operator among your filters. For example, check [this query](https://ide.bitquery.io/transactions-sent-or-received-by-an-address) where we retrieve all transactions sent or received by an address. ## Metrics Metrics allow you to perform mathematical functions such as `sum`, `count`, `average`, `median`, `maximum`, `minimum`, etc. Let's understand this with a few examples. Check [this query](https://ide.bitquery.io/transactions-on-ethereum-in-may) where we get the count of transactions in a given month. Now, see [this API example](https://ide.bitquery.io/total-ethereum-transaction-value-in-april) where we get the sum of ETH transferred in a given month. In the same way, you can use metrics and filters to obtain analytical metrics from blockchains. --- ## Transfers Cube URL: https://docs.bitquery.io/docs/cubes/transfers-cube/ Transfers cube explained: filter token transfers by sender, receiver, currency and amount, read transfer types, and compute metrics like sums and counts. # Transfer Cube > **Before you start**: Not sure when to use Transfers vs Events 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 Transfer cube provides details on asset transfers, blocks, contract calls, fees, event logs, receipts, transaction details, and transaction status. ![Transfers Fields](/img/cubes/transfers-cube.png) ### Filters in Transfer Cube The Transfer cube allows filtering by any field available in the result fields. By default, all filters use the `AND` operator. We will see an example of the `OR` operator later. For example, check the [transfers for the Tether token](https://ide.bitquery.io/Transfers-of-USDT-token-in-real-time-db). ### More Transfer Cube Filter Examples Let's explore more examples of filtering in the Transfer cube. Check [this query](https://ide.bitquery.io/transfers-over-100-eth-in-a-given-month), where we retrieve transfers over 100 ETH in a given month. Another example is [this query](https://ide.bitquery.io/Only-wallet-to-wallet-eth-transfers-on-ethereum), where we filter to get only wallet-to-wallet ETH transfers using `Transfer_Type` filter. For an example of the `OR` operator, see [this query](https://ide.bitquery.io/all-transfers-of-a-address), which retrieves all transfers of a given address. ## Transfer Type Every EVM chain transfer has **`Transfer_Type`** property, which provides insights about the type of transfer taking place. The three values classify **native** vs **token** transfers and whether native value moved at the **top level** or **inside a contract call** as shown in the table below. | Value | Meaning | Native? | `Call.CallPath` | | ----- | ------- | ------- | --------------- | | **`transaction`** | Native transfer from the **transaction signer** at the **root** of the transaction (external send). Not ERC-20. | Yes | Empty `[]` | | **`call`** | Native transfer as **`value` on an internal contract call** (contract forwards ETH during execution). | Yes | Non-empty | | **`token`** | **ERC-20** (or other token standard) transfer from contract execution. Never native. | No (`Currency.Native: false`) | Any | **Examples:** - ERC-20 Token Transfer: `Transfer: { Type: { is: token } }`. [Run this Example](https://ide.bitquery.io/Only-token-transfers-on-ethereum) - Wallet to Wallet ETH Transfer: `Type: { is: transaction }`. [Run this Example](https://ide.bitquery.io/Only-wallet-to-wallet-eth-transfers-on-ethereum) - Internal Transfer → `Type: { is: call }`. [Run this Example](https://ide.bitquery.io/internal-transfers-on-ethereum) ## Metrics in Transfer Metrics allow you to perform mathematical functions such as `sum`, `count`, `average`, `median`, `maximum`, `minimum`, etc. Let's understand this with a few examples. Check [this example](https://ide.bitquery.io/biggest-transfer-on-a-given-date), where we get the biggest ETH transfer on a given date. Another way to write this query is by sorting based on amount, as shown [here](https://ide.bitquery.io/biggest-transfer-on-a-given-date-using-sorting). See [this query](https://ide.bitquery.io/total-shiba-transferred-on-a-given-date_2) to learn how to get the token transfer volume and count of SHIB tokens on a given date. --- ## Transfers vs Events vs Calls vs DexTrades URL: https://docs.bitquery.io/docs/start/mental-model-transfers-events-calls/ Transfers vs Events vs Calls vs DexTrades: practical Bitquery setup guidance with examples for authentication, endpoints, and first queries. # Mental Model: Transfers, Events, Calls, and DexTrades Understanding when to use **Transfers**, **Events**, **Calls**, or **DexTrades** is one of the decisions you'll make when querying blockchain data. This guide explains the conceptual differences and helps you choose the right primitive for your use case. **Chain scope:** The primitives below are described for **EVM chains** (Ethereum, BSC, Base, Arbitrum, etc.). **Solana** and **Tron** share the same high-level ideas (Transfers, DexTrades) but use different cubes where the chain model differs. See [Applying this model across chains](#applying-this-model-across-chains) for Solana, Tron, and other non-EVM chains. ## The Core Question: What Are You Really Looking For? Before writing a query, ask yourself: 1. **Do I need DEX swap/trade data or aggregated price/OHLC data?** → For **real-time + the last ~30 days**, use the curated **`Trading`** cube — [`Trading.Trades`](/docs/trading/crypto-trades-api/trades-api) for swap-level rows or [`Trading.Tokens` / `Pairs` / `Currencies`](/docs/trading/crypto-price-api/) for pre-aggregated OHLC. For **historical** data older than ~30 days, use chain-level **`DexTrades`** / **`DexTradesByTokens`**. See the [**Trading Data Overview**](/docs/trading/trading-data-overview) for the full decision matrix. 2. **Do I need token movements?** → Consider `Transfers` or `Calls` 3. **Do I need smart contract state changes?** → Consider `Events` 4. **Do I need function execution details?** → Consider `Calls` ## Understanding Each Primitive ### Transfers **What it represents:** Token movements between addresses (ERC-20, ERC-721, native tokens like ETH, BNB, SOL). **Key characteristics:** - Captures **all token movements** including native tokens - Includes both direct transfers and transfers that happen as part of contract calls - Can include "noise" from native token transfers (ETH, BNB, SOL) that you might not want **When to use:** - Tracking token balances and movements - Wallet-to-wallet transfers - Token distribution analysis - Tax/accounting use cases **When NOT to use:** - Filtering for specific token contract addresses (you'll get native tokens mixed in) - Tracking smart contract function calls - Monitoring specific contract events **Common pitfall:** ```graphql # This returns BNB transfers too, not just your token! EVM { Transfers(where: {Currency: {SmartContract: {is: "0x..."}}}) { # You'll see native BNB transfers mixed with token transfers } } ``` **Solution:** Filter by `Currency { Native: false }` or use `Calls` instead. --- ### Events **What it represents:** Log entries emitted by smart contracts (e.g., `Transfer`, `Approval`, `Swap`, `Mint`). **Key characteristics:** - Only includes **logged events** from smart contracts - Requires the contract to explicitly emit the event - More precise than Transfers for contract-specific activities - Can be empty if the event doesn't exist or wasn't emitted **When to use:** - Monitoring specific contract events (e.g., `Swap` events from a DEX) - Tracking contract state changes (e.g., `Approval`, `Mint`) - Real-time event monitoring via subscriptions - When you know the exact event signature **When NOT to use:** - You don't know what events exist (use event discovery first) - You need function call details, not just logs - You need native token transfers (events don't capture these) **Common pitfall:** ```graphql # Returns empty if event doesn't exist or wasn't emitted EVM { Events(where: {Log: {Signature: {Name: {is: "EVENTSIGNATURNAME"}}}}) { # Empty result - why? } } ``` **Solution:** First discover what events exist, then query them. --- ### Calls **What it represents:** Function calls to smart contracts, including internal calls and their execution details. **Key characteristics:** - Captures **all function executions** (external and internal) - Includes function parameters and return values - Can filter by specific contracts and functions - Most precise for contract interactions - **Best choice for token contract interactions** (avoids native token noise) **When to use:** - Tracking smart contract function calls - Filtering token transfers by contract address (avoids native token noise) - Monitoring specific contract interactions - Getting function call parameters and return values - Internal transaction tracking **When NOT to use:** - Simple wallet-to-wallet native token transfers - When you only need event logs, not function details **Why Calls is often the right choice:** ```graphql # This gives you ONLY token transfers from the contract, no native tokens EVM { Calls( where: { To: {is: "0xTokenContract"}, Signature: {Name: {is: "transfer"}} } ) { # Clean token transfers, no BNB/ETH noise } } ``` --- ### DexTrades and DexTradesByTokens **What they represent:** Pre-parsed, normalized DEX swap data—every swap on supported DEXs (Uniswap, PancakeSwap, etc.) with buy/sell sides, prices, pools, and protocols. **Key characteristics:** - **DexTrades**: One record per swap, from the **pool's perspective** (`Buy` = what the pool bought, `Sell` = what the pool sold). Best for protocol-level queries (trade count by DEX, gas on trades, dynamics over time). - **DexTradesByTokens**: Same swaps but **token-centric**—each swap appears as **two records** (one per token). Uses `Trade` + `Side` instead of `Buy`/`Sell`. Best for token-level queries (price of a token, OHLC by token, every pair a token is in). **When to use DexTrades:** - Swap counts by protocol or smart contract - Gas spending on trades - DEX usage over time - One record per swap, pool-centric **When to use DexTradesByTokens:** - Price of a token across DEXs - OHLC (candles) for a token or pair - "Every pair this token is involved in" - Queries by token or pair of tokens **When NOT to use DexTrades/DexTradesByTokens:** - Raw event logs (use **Events**) - Non-DEX token transfers (use **Transfers** or **Calls**) - Orderbook / open orders (data is swap-level, not order-level) **DexTrades vs Events for swaps:** For DEX swap monitoring, **DexTrades** is usually better than querying raw `Swap` events: you get normalized buy/sell amounts, prices, pool, and protocol without parsing logs. Use **Events** only when you need raw log data or a DEX that isn’t fully supported in DexTrades. **Important:** DexTradesByTokens has **twice as many records** per swap (one per token). Always filter by token (or pair) to get correct counts and avoid double-counting. --- ### Trading (Crypto Price) cube **What it represents:** Pre-aggregated price and volume data across chains—OHLC, moving averages (SMA, WMA, EMA), mean price, and volume, at configurable intervals (e.g. 1s, 1m). Uses the root `Trading { Tokens | Currencies | Pairs(...) }` and is **multi-chain** (EVM, Solana, Tron). **Key characteristics:** - **Pre-aggregated**: OHLC, SMA, WMA, EMA, mean price and volume are computed for you; no need to build OHLC from raw swaps. - **Real-time streaming**: 1-second granularity via GraphQL subscriptions (and Kafka). - **Three cubes**: **Tokens** (price per token per chain), **Currencies** (same asset across chains, e.g. BTC/WBTC/cbBTC), **Pairs** (price per pair per market, e.g. SOL/USDC on Raydium). - **Clean feed**: Low-quality and outlier trades are filtered automatically. **When to use the Trading cube:** - Real-time or historical **price feeds** and **charting** (OHLC, candles). - **Moving averages** and **mean price** over time. - **Cross-chain** or **cross-DEX** aggregated price for a token or currency. - Trading bots, DeFi oracles, and dashboards that need **price index** data, not per-swap detail. **When NOT to use the Trading cube:** - Per-swap detail (who traded, which pool, tx hash) → use **DexTrades** or **DexTradesByTokens**. - Raw trade-level analytics (e.g. swap count by pool) → use **DexTrades**. - Token movements or balance changes → use **Transfers**, **Calls**, **Balances** / **Holders** (EVM, Tron), or **BalanceUpdates** (Solana). **Trading vs DexTrades:** Use **Trading** when you need **aggregated price/OHLC/volume** for charting or feeds. Use **DexTrades** when you need **individual swaps**, protocol/pool breakdown, or trade-level fields (buyer, seller, tx, block). Docs: [Crypto Price API (Trading)](/docs/trading/crypto-price-api/), [Tokens / Currencies / Pairs](/docs/trading/crypto-price-api/tokens), [OHLC & candles](/docs/trading/crypto-price-api/crypto-ohlc-candle-k-line-api). --- ## Applying this model across chains The concepts above apply to **EVM** (Ethereum, BSC, Base, Arbitrum, Matic, Optimism, etc.). Other chains expose the same ideas under different cube names and with chain-specific primitives. ### EVM chains (Ethereum, BSC, Base, Arbitrum, etc.) - **Transfers** – Token movements (including native ETH/BNB/etc.). - **Events** – Smart contract log entries (e.g. `Swap`, `Transfer`, `Approval`). - **Calls** – Function executions (external and internal). - **DexTrades / DexTradesByTokens** – Normalized DEX swap data (Buy/Sell, Trade/Side). Use the root `EVM(network: eth | bsc | base | ...)` in your query. ### Solana - **Transfers** – SPL token and SOL movements. Same idea as EVM Transfers; use `Solana { Transfers(...) }`. - **DexTrades / DEXTradeByTokens** – DEX swap data (Buy/Sell, Trade/Side). Same idea as EVM; use `Solana { DEXTrades(...) }` or `Solana { DEXTradeByTokens(...) }`. - **Instructions** – Execution units (program calls). Closest to EVM **Calls** + execution context; use when you need “what program ran” and call paths, not raw logs. - **BalanceUpdates** – Balance deltas per account. Use for balance history and “who gained/lost what” rather than full transfer history. - **DEXOrders** – Order-level data (open/unfilled orders, orderbook-style). Use when you need orders, not only filled swaps. Solana does **not** have EVM-style **Events** or **Calls**; use **Instructions** and **Logs** (inside Instructions) for program activity. Docs: [Solana Builder Terms](/docs/cubes/solana), [Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades), [Solana Transfers](/docs/blockchain/Solana/solana-transfers), [Solana Instructions](/docs/blockchain/Solana/solana-instructions), [Solana Balance Updates](/docs/blockchain/Solana/solana-balance-updates). ### Tron - **Transfers** – TRC-20 and native TRX movements. Same idea as EVM Transfers; use `Tron { Transfers(...) }`. - **DEXTrades** – DEX swap data (e.g. SunSwap). Same idea as EVM; use `Tron { DEXTrades(...) }`. Tron’s model is close to EVM (TVM); Transfers and DEXTrades map directly. For logs and contract calls, see the [Tron API docs](/docs/blockchain/Tron/). Docs: [Tron API](/docs/blockchain/Tron/), [Tron DEX Trades](/docs/blockchain/Tron/tron-dextrades), [Tron Transfers](/docs/blockchain/Tron/tron-transfers). ### Quick mapping | Concept | EVM | Solana | Tron | |--------------------|--------------------------|--------------------------------|-------------------| | Token movements | Transfers, Calls | Transfers | Transfers | | DEX swaps | DexTrades, DexTradesByTokens | DEXTrades, DEXTradeByTokens | DEXTrades | | Execution / “calls”| Calls | Instructions | (see Tron docs) | | Contract “events” | Events | (Instructions + Logs) | (see Tron docs) | | Current balances | Balances, Holders | (from BalanceUpdates) | Balances, Holders | | Balance deltas | TransactionBalances | BalanceUpdates | (from Transfers) | | Orderbook / orders | (swap-level only) | DEXOrders | (see Tron docs) | --- ## Decision Tree The tree below is **EVM-oriented**. For Solana, use **Instructions** where it says Events/Calls; for Tron, use **Transfers** and **DEXTrades** (see [chain mapping](#applying-this-model-across-chains)). ``` Start: What do you need? ├─ Price / OHLC / charting (aggregated)? │ └─ Pre-aggregated OHLC, SMA, volume, 1s+ intervals? → Trading cube (Tokens / Currencies / Pairs) │ ├─ DEX swap/trade data (per-swap)? │ ├─ By protocol, pool, or one record per swap? → DexTrades (EVM/Solana/Tron) │ └─ By token, OHLC from swaps, or "pairs for this token"? → DexTradesByTokens (EVM/Solana; filter by token!) │ ├─ Token movements? │ ├─ Need native tokens (ETH, BNB, SOL, TRX)? → Transfers │ └─ EVM only: only specific token contracts? → Calls (better) or Transfers + filter │ ├─ EVM: Smart contract events/logs? │ └─ Know the event name? → Events │ └─ Don't know what exists? → Discover events first, then query │ ├─ Solana: Program execution / call path? │ └─ Use Instructions (and Logs inside Instructions) │ └─ EVM: Function execution details? └─ Need parameters/return values? → Calls └─ Need internal calls? → Calls ``` ## Real-World Examples ### Example 1: Tracking Token Transfers **Goal:** Get all USDT transfers on BSC, excluding native BNB. **Wrong approach (Transfers):** ```graphql EVM(network: bsc) { Transfers( where: {Currency: {SmartContract: {is: "0x55d398326f99059fF775485246999027B3197955"}}} ) { # Problem: Might include BNB transfers if not filtered } } ``` **Better approach (Calls):** ```graphql EVM(network: bsc) { Calls( where: { To: {is: "0x55d398326f99059fF775485246999027B3197955"}, Signature: {Name: {is: "transfer"}} } ) { # Clean USDT transfers only, no BNB noise } } ``` **Alternative (Transfers with filter):** ```graphql EVM(network: bsc) { Transfers( where: { Currency: { SmartContract: {is: "0x55d398326f99059fF775485246999027B3197955"}, Native: false # Exclude native tokens } } ) { # USDT transfers only } } ``` ### Example 2: Monitoring DEX Swaps **Goal:** Track all swaps on a DEX (prices, amounts, buyer/seller, pool). **Best approach (DexTrades):** ```graphql EVM(network: eth) { DEXTrades( where: {Trade: {Dex: {ProtocolName: {is: "uniswap_v2"}}}}} limit: {count: 10} orderBy: {descending: Block_Time} ) { Block { Time Number } Transaction { Hash From } Trade { Buy { Amount Price Currency { Symbol } Buyer Seller } Sell { Amount Price Currency { Symbol } Buyer Seller } Dex { ProtocolName Pair { SmartContract } } } } } ``` **Why DexTrades?** You get normalized buy/sell amounts, prices, pool, and protocol without parsing raw logs. Use **DexTradesByTokens** when you need token-centric data (e.g. "all pairs for this token", OHLC by token)—and always filter by token to avoid double-counting. **Alternative (Events):** Use **Events** when you need raw `Swap` log data or a DEX not fully supported in DexTrades. ### Example 3: Tracking Contract Function Calls **Goal:** Monitor when users call `approve()` on a token contract. **Best approach (Calls):** ```graphql EVM(network: eth) { Calls( where: { To: {is: "0xTokenContract"}, Signature: {Name: {is: "approve"}} } ) { Call { Arguments { Name Value { ... on EVM_ABI_Address_Value_Arg { address } ... on EVM_ABI_Integer_Value_Arg { integer } } } } } } ``` **Why Calls?** You need the function parameters (who approved, how much), which Calls provides. --- ## Common Confusion Points ### "Why does my Transfers query return BNB instead of my token?" **Answer:** Transfers includes native tokens. Use `Currency { Native: false }` filter or switch to `Calls`. ### "Why is my Events query returning empty?" **Possible reasons:** 1. The event doesn't exist at that contract 2. The event wasn't emitted in your time range 3. Wrong event signature name 4. Wrong contract address **Solution:** First discover what events exist: ```graphql EVM { Events(where: {LogHeader: {Address: {is: "0xContract"}}}) { Log { Signature { Name } } } } ``` ### "Should I use Transfers or Calls for token transfers?" **Answer:** - Use **Calls** if you want to filter by contract and avoid native token noise - Use **Transfers** if you need all token movements including native tokens, or for simple wallet-to-wallet transfers ### "DexTrades or DexTradesByTokens?" **Answer:** - **DexTrades**: One record per swap, pool perspective (`Buy`/`Sell`). Use for protocol-level stats (trade count by DEX, gas, time series). - **DexTradesByTokens**: Two records per swap (one per token), token perspective (`Trade`/`Side`). Use for token price, OHLC, "every pair this token is in". **Always filter by token** so counts and volumes are correct. ### "DEX swaps: DexTrades or Events?" **Answer:** Prefer **DexTrades** (or **DexTradesByTokens**) for swap monitoring—you get normalized prices, amounts, and protocol. Use **Events** when you need raw log data or a DEX not covered by DexTrades. --- ## How do I identify which exchange a wallet belongs to (e.g., Binance)? Bitquery exposes **on-chain** activity (transfers, trades, calls)—not centralized-exchange **KYC or account labels**. To say “this is Binance,” combine Bitquery flows with a **third-party labeling API** or a curated list of **known deposit / hot wallets**, then detect when user funds move to or from those addresses. Bitquery is ideal for measuring **timing and amounts**; attribution is your mapping layer. However, Bitquery has some limited attribution data in [V1 apis](https://docs.bitquery.io/v1/docs/Examples/coinpath/money-flow-api). ## Quick Reference | Use Case | Recommended Primitive | Why | |----------|---------------------|-----| | Aggregated price / OHLC / charting | **Trading** (Tokens/Currencies/Pairs) | Pre-aggregated OHLC, SMA, volume; multi-chain | | DEX swaps (by protocol/pool) | **DexTrades** | One record per swap, normalized | | DEX swaps (by token, OHLC from swaps, pairs) | **DexTradesByTokens** | Token-centric; filter by token | | Token transfers (specific contract) | **Calls** | Avoids native token noise | | All token movements (including native) | **Transfers** | Captures everything | | Smart contract events | **Events** | Direct event logs | | Function call details | **Calls** | Includes parameters | | Internal transactions | **Calls** | Tracks call depth | | Wallet balance tracking | **Transfers** | Complete transfer history | | Contract interaction analytics | **Calls** | Full execution context | --- ## Next Steps Now that you understand the mental model: **Price / OHLC / charting (all chains):** 1. **[Crypto Price API (Trading)](/docs/trading/crypto-price-api/)** - Pre-aggregated OHLC, SMA, volume; Tokens, Currencies, Pairs cubes **EVM (Ethereum, BSC, Base, etc.):** 2. **[Explore Transfers API](/docs/blockchain/Ethereum/transfers/erc20-token-transfer-api)** - Learn Transfers in detail 3. **[Explore Events API](/docs/blockchain/Ethereum/events/events-api)** - Learn Events in detail 4. **[Explore Calls API](/docs/blockchain/Ethereum/calls/smartcontract)** - Learn Calls in detail 5. **[DEXTrades Cube](/docs/cubes/dextrades)** - Pool perspective, one record per swap 6. **[DEXTradesByTokens Cube](/docs/cubes/dextradesbyTokens)** - Token perspective, filter by token 7. **[Ethereum DEX API](/docs/blockchain/Ethereum/dextrades/dex-api)** - DEX trading examples **Solana:** 8. **[Solana Builder Terms](/docs/cubes/solana)** - Transfers, DEXTrades, Instructions, BalanceUpdates, DEXOrders 9. **[Solana DEX Trades](/docs/blockchain/Solana/solana-dextrades)** - DEX swap data 10. **[Solana Transfers](/docs/blockchain/Solana/solana-transfers)** - Token movements 11. **[Solana Instructions](/docs/blockchain/Solana/solana-instructions)** - Program execution (Calls-like) **Tron:** 12. **[Tron API](/docs/blockchain/Tron/)** - Overview 13. **[Tron DEX Trades](/docs/blockchain/Tron/tron-dextrades)** - DEX swap data 14. **[Tron Transfers](/docs/blockchain/Tron/tron-transfers)** - Token movements **General:** 16. **[Build Your First Query](/docs/start/first-query)** - Put it into practice --- ## Summary - **Transfers** = Token movements (includes native tokens). Available on EVM, Solana, Tron. - **Events** = Contract log entries (EVM only; requires events to be emitted). - **Calls** = Function executions (EVM only; most precise for contract interactions). - **DexTrades** = DEX swaps, pool perspective, one record per swap. Available on EVM, Solana, Tron. - **DexTradesByTokens** = DEX swaps, token perspective, two records per swap (EVM, Solana)—always filter by token. - **Trading (Crypto Price)** = Pre-aggregated price/OHLC/volume (Tokens, Currencies, Pairs). Multi-chain; use for charting, feeds, moving averages—not per-swap detail. - **Solana:** **Instructions** (execution units), **BalanceUpdates** (balance deltas), **DEXOrders** (orderbook). No Events/Calls; use Instructions + Logs for program activity. - **Tron:** Transfers and DEXTrades map directly; see Tron docs for logs/calls. --- ## Tron Data - Snowflake, AWS S3, BigQuery URL: https://docs.bitquery.io/docs/cloud/tron/ Tron blocks, transactions, TRX and token transfers, balance updates and DEX trades as Parquet, with a free sample and DuckDB and Python examples. # Tron Data Bitquery provides **Tron 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 Tron Topics For Tron, Bitquery currently provides the following datasets: - **Blocks** – Block-level metadata - **Transactions** – Full transaction-level data - **Transfers** – Native TRX and token transfers - **Balance Updates** – Account balance changes per block - **DEX Trades** – Executed trades on Tron DEXs ## Sample Tron Cloud Dataset You can explore schemas and validate your tooling using the **public Tron sample datasets**: **GitHub reference (schemas & examples)** [https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/tron](https://github.com/bitquery/blockchain-cloud-data-dump-sample/tree/main/tron) **Example Parquet file (public S3)** ``` https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/tron/balance_updates/.parquet ``` ## Tron Dataset Directory Structure ```text bitquery-blockchain-dataset/ └── tron/ ├── balance_updates/ │ ├── _.parquet │ ├── _.parquet │ └── ... ├── blocks/ │ ├── _.parquet │ ├── _.parquet │ └── ... ├── dex_trades/ │ ├── _.parquet │ └── ... ├── transactions/ │ ├── _.parquet │ └── ... └── transfers/ ├── _.parquet └── ... ``` ### Block Range Naming Convention Each Parquet file name follows this format: ``` _.parquet ``` Example: ``` 78861100_78861149.parquet ``` ## Get Full Access The full dataset is delivered into your own cloud storage (S3, GCS) or warehouse share (Snowflake, BigQuery). To buy or trial it, go to the [Bitquery Data Store](https://bitquery.io/datastore/datasets?network=tron), [fill the API form](https://bitquery.io/forms/api) or contact **sales@bitquery.io**. Datasets you can buy on the Data Store: - [TRON Transfers](https://bitquery.io/datastore/datasets/tron-transfers) — every TRX, TRC-10 and TRC-20 transfer since mainnet launch, valued in USD where a price exists ## Reading Files with DuckDB No key, no client library — point DuckDB at the public sample directly: ```sql SELECT * FROM read_parquet('https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/tron/transactions/78861100_78861149.parquet') LIMIT 10; ``` ## Reading Files in Python ```python df = pd.read_parquet("https://bitquery-blockchain-dataset.s3.us-east-1.amazonaws.com/tron/transactions/78861100_78861149.parquet") print(df.info()) df.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 Tron data**, Bitquery also provides: - [**Kafka streams**](/docs/streams/kafka-streaming-concepts/) - **GraphQL subscriptions** --- ## Tron Kafka Protobuf Streams URL: https://docs.bitquery.io/docs/streams/protobuf/chains/Tron-protobuf/ Tron Protobuf with Bitquery Kafka and protobuf streams for low-latency blockchain ingestion in trading systems. Run it in the IDE, then ship in your app. # TRON Streams You can find the schema [here](https://github.com/bitquery/streaming_protobuf/tree/main/tron). TRON produces blocks approximately every 3 seconds, offering high throughput for transactions and smart contracts. :::info USD Values All amounts in the TRON protobuf streams now include USD equivalents — token transfer amounts, DEX trade sides, and transaction fees each carry an `...InUSD` field (e.g. `AmountInUSD`, `TransactionFeeInUSD`). These are populated in real time on the streams. ::: ## Structure of On-Chain Data The TRON Protobuf Streams provide three main message types for different use cases: - `BlockMessage`: Full blocks with detailed transaction information - `TokenBlockMessage`: Focused on token transfers - `DexBlockMessage`: Specialized for DEX (Decentralized Exchange) trading activity ### Block-Level Data Each block in the stream includes a `BlockHeader` with fields such as: - `Number`: Block height in the chain - `Hash`: The unique identifier of the block - `Timestamp`: When the block was produced - `ParentHash`: Hash of the previous block - `TxTrieRoot`: Merkle root of transactions - `AccountStateRoot`: State root hash - `TransactionsCount`: Number of transactions in this block The `BlockMessage` also includes: - `Chain`: Information about the blockchain - `Witness`: Details about the block producer (Super Representative) - `Address`: The witness account address - `Id`: Witness identifier - `Signature`: Block signature ### Transaction-Level Data Transactions include: - `TransactionHeader`: Core transaction data - `Hash`: Transaction hash - `Fee`: Transaction fee - `Index`: Position in the block - `Expiration`: When the transaction expires - `FeeLimit`: Maximum fee allowed - `Signatures`: Transaction signatures - `FeePayer`: Account that pays the fee - `Result`: Execution outcome - `Status`: Transaction status - `Success`: Whether transaction succeeded - `Message`: Error message if failed - `Receipt`: Resource consumption details - `EnergyUsageTotal`: Total energy consumed - `EnergyFee`: Fee paid for energy - `NetUsage`: Bandwidth used - `NetFee`: Fee paid for bandwidth ### Contract Data The `Contract` section contains detailed information about smart contract interactions: - `Address`: Contract address - `Type`: Contract type (e.g., "TransferContract", "TriggerSmartContract") - `TypeUrl`: Protocol buffer type URL - `Arguments`: Contract-specific arguments - `InternalTransactions`: Sub-transactions created during execution - `CallerAddress`: Initiator address - `TransferToAddress`: Recipient address - `CallValues`: Assets transferred - `Note`: Additional information - `Logs`: Event logs emitted by the contract - `Trace`: Detailed execution trace (similar to EVM) - `RewardWithdraw`: Information about reward distribution ### 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 - `Currency`: Detailed token information - `Success`: Whether the transfer succeeded - `AmountInUSD`: USD value of the transferred amount TRON supports multiple token standards: - TRC10: Native TRON tokens identified by TokenId - TRC20: Similar to ERC20 on Ethereum - TRC721/TRC1155: Non-fungible tokens ### DEX (Decentralized Exchange) Data The `DexBlockMessage` stream is specialized for DEX trading activity: - `DexTrade`: Records of trades executed on DEXs (TRON reuses the EVM `DexTrade` message) - `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 ### TRON-Specific Features TRON has several unique features compared to other blockchain protocols: - **Energy and Bandwidth Model**: Instead of a simple gas model, TRON uses Energy for smart contract execution and Bandwidth (Net) for transaction size - **Witness System**: Block producers are called Witnesses or Super Representatives - **Contract Types**: TRON has predefined contract types for common operations - **TRC10 Tokens**: Native token support without smart contracts, referenced by TokenId - **Resource Delegation**: Users can delegate resources to each other ### 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: - `tron.raw.proto` (for raw block data) - `tron.transactions.proto` - `tron.tokens.proto` - `tron.dextrades.proto` - `tron.broadcasted.raw.proto` (for raw broadcasted block data) - `tron.broadcasted.transactions.proto` (for broadcasted transactions) - `tron.broadcasted.tokens.proto` (for broadcasted token transfers) - `tron.broadcasted.dextrades.proto` (for broadcasted DEX trades) 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. --- ## Understanding Bitquery Cubes: Which Cube Answers Which Question URL: https://docs.bitquery.io/docs/category/understanding-cubes/ One GraphQL root per data type: trades, transfers, balances, calls, events, blocks. The EVM, Solana and Trading cube families, datasets, and which cube to pick. # Understanding Bitquery Cubes: Which Cube Answers Which Question A cube is one GraphQL root per kind of on-chain fact. `DEXTrades` holds swaps, `Transfers` holds token movements, `Balances` holds what an address owns now, `Calls` and `Events` hold decoded contract activity, `Blocks` and `Transactions` hold the chain itself. Every cube takes the same `where`, `orderBy` and `limit` arguments, supports aggregates such as `count`, `sum` and `uniq`, and runs as a query or, with the keyword changed, as a WebSocket subscription. Cubes come in three families: chain-level EVM cubes under `EVM(network: ...)`, chain-level Solana cubes under `Solana`, and the cross-chain `Trading` cubes that carry USD prices for ten chains in one schema. The `dataset` argument decides how far back a chain-level cube reaches. ## The three families | Family | Root | Cubes | What it is for | |---|---|---|---| | EVM | `EVM(network: eth)` and the other EVM chains | DEXTrades, DEXTradeByTokens, DEXPools, Transfers, Balances, Holders, TransactionBalances, Transactions, Calls, Events, Blocks, MinerRewards | Anything on Ethereum, BNB Chain, Base, Arbitrum, Optimism, Polygon, Robinhood Chain or Arc, from a single swap to decoded contract logs | | Solana | `Solana` | DEXTrades, DEXTradeByTokens, DEXOrders, DEXPools, Transfers, BalanceUpdates, Instructions, Transactions, Blocks, Rewards, TokenSupplyUpdates | Solana at instruction level, including launchpads and program calls | | Trading | `Trading` | Trades, Tokens, Pairs, Currencies | Prices, OHLC, market cap and supply across ten chains with one schema and USD on every row | ## Which cube answers which question | Question | Cube | |---|---| | Every swap on a DEX, with both sides and the trader | `DEXTrades` | | Volume, OHLC, buyers and sellers for one token over time | `DEXTradeByTokens` | | Pool creation and liquidity changes | `DEXPools` | | Who sent what to whom | `Transfers` | | What an address holds right now, or who holds a token | `Balances` and `Holders` | | Every balance change, per transaction | `TransactionBalances` on EVM, `BalanceUpdates` on Solana | | Method calls, internal transactions, reverts | `Calls` | | Decoded contract logs, an `eth_getLogs` replacement | `Events` | | Receipts, gas, status | `Transactions` | | A token's price on any chain, market cap, candles | `Trading.Tokens`, `Trading.Pairs`, `Trading.Currencies` | The comparison page [DEXTrades vs DEXTradeByTokens vs Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades) settles the most common choice: swap rows, per-token aggregates, or cross-chain USD prices. ## Datasets decide depth Chain-level cubes accept `dataset: realtime`, `archive` or `combined`. Realtime is the freshest and shortest window (hours to days depending on the cube), archive is the history, combined stitches both. Leaving the argument out means realtime, which is the usual reason a query "works" but returns nothing for last month. The Trading cubes take no dataset argument and hold roughly the last 30 days. Per-cube windows are on [data coverage and retention](/docs/graphql/data-coverage-retention). ## A first cube query The latest three DEX trades on Ethereum. Run it in the [Bitquery IDE](https://ide.bitquery.io) on a free account, then change the network, the cube or the filter. ```graphql { EVM(network: eth) { DEXTrades(limit: { count: 3 }, orderBy: { descending: Block_Time }) { Block { Time } Trade { Dex { ProtocolName } Buy { Currency { Symbol } Amount } Sell { Currency { Symbol } Amount } } } } } ``` ## Pages in this section | Page | Read it for | |---|---| | [EVM builder terms](/docs/cubes/EVM) | Every argument and field name across the EVM cubes, in one place | | [Solana builder terms](/docs/cubes/solana) | The same for Solana | | [DEX Trades cube](/docs/cubes/dextrades) | Swap-level rows with filters and aggregates | | [DEXTradeByTokens cube](/docs/cubes/dextradesbyTokens) | Per-token aggregates, OHLC and stats | | [DEXTrades vs DEXTradeByTokens vs Trades](/docs/cubes/dextrades-dextradebytokens-trading-trades) | Picking between the three trade cubes | | [DEXPools cube on EVM](/docs/cubes/evm-dexpool) | Pools, reserves and 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) | Per-change balance history | | [Transfers cube](/docs/cubes/transfers-cube) | Token and native transfers | | [EVM token holders schema](/docs/schema/evm/token-holders) | Field reference for holders | ## Related pages - [Building GraphQL queries](/docs/category/building-queries) - [GraphQL query capabilities](/docs/category/capabilities) - [Data coverage and retention](/docs/graphql/data-coverage-retention) - [Crypto Price API (Trading cubes)](/docs/trading/crypto-price-api/) --- ## Usage API - Track Billing and Quota Programmatically URL: https://docs.bitquery.io/docs/authorization/usage-api/ Usage API - Track Billing and Quota Programmatically in Bitquery docs with practical setup steps, examples, and guidance for secure API access. # Usage API The **Usage API** exposes OAuth2-authenticated endpoints on [account.bitquery.io](https://account.bitquery.io/) so you can **programmatically track billing period status, plan limits, and consumption** for your Bitquery account. Open the interactive reference and copy a bearer token from **[Authorization → Usage API](https://account.bitquery.io/user/api)**. To create or manage tokens, see [How to Generate a Token](/docs/authorization/how-to-generate/). :::caution Keep your token secret Authenticate every request with your account bearer token in the `Authorization` header. The token identifies your account — do not expose it in client-side code, public repos, or logs. ::: ## Authentication Send your account bearer token on every request: ```bash curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ https://account.bitquery.io/api/usage ``` Replace `YOUR_ACCESS_TOKEN` with a token from [Access tokens](https://account.bitquery.io/user/api_v2/access_tokens) or the token shown on the [Usage API](https://account.bitquery.io/user/api) page. Token format is typically `ory_at_...` with an expiration date. ## Billing plan usage **`GET /api/usage`** Returns your **current billing period** — its plan, limits, usage recorded against them, and an overall status. - **Team members** receive their **team manager's** billing period (`payer_id` is the manager's account id). - When no period is active, the **most recent** period is returned instead. ### Period status | Status | Description | | --- | --- | | **`active`** | The period currently covers the present time. | | **`grace`** | The period ended but is still within the grace window. | | **`blocked`** | The period or account is blocked. | | **`expired`** | The period ended and the grace window has passed. | ### Response fields | Field | Type | Description | | --- | --- | --- | | `account_id` | integer | Your account id. | | `payer_id` | integer | Account that owns the billing period — the team manager for team members, otherwise the same as `account_id`. | | `status` | string | `active`, `grace`, `blocked`, or `expired` (see above). | | `billing_period.started_at` | datetime | Period start (ISO 8601, UTC). | | `billing_period.ended_at` | datetime | Period end (ISO 8601, UTC). | | `billing_period.plan_name` | string | Display name of the plan. | | `billing_period.product` | object \| null | Linked product as `{ "name": "..." }`, or `null` when the period has no product (e.g. free plans). Use `plan_name` for a label that is always present. | | `billing_period.limits` | object | Plan limits: `points_limit`, `rate_limit`, `session_limit`, `subscription_limit`, `time_sec_limit`, `traffic_bytes_limit`, `team_slots_limit`. | | `billing_period.usage` | object | Usage so far this period: `points_usage`, `requests_usage`, `time_sec_usage`, `traffic_bytes_usage`. | | `billing_period.description` | object | Full raw period description (all plan attributes). | ### Example response ```json { "account_id": 12345, "payer_id": 12345, "status": "active", "billing_period": { "started_at": "2026-06-24T00:00:00Z", "ended_at": "2026-07-23T23:59:59Z", "plan_name": "Paid plan", "product": null, "limits": { "points_limit": 100000000000, "rate_limit": 10000, "session_limit": 1000, "subscription_limit": 1000, "time_sec_limit": 0, "traffic_bytes_limit": 0, "team_slots_limit": 5 }, "usage": { "points_usage": 4458, "requests_usage": 184, "time_sec_usage": 301, "traffic_bytes_usage": 3763747 }, "description": { "points_limit": 100000000000, "rate_limit": 10000, "session_limit": 1000, "subscription_limit": 1000 } } } ``` ## Example: Python ```python ACCESS_TOKEN = "YOUR_ACCESS_TOKEN" response = requests.get( "https://account.bitquery.io/api/usage", headers={"Authorization": f"Bearer {ACCESS_TOKEN}"}, ) response.raise_for_status() data = response.json() period = data["billing_period"] print(f"Status: {data['status']}") print(f"Plan: {period['plan_name']}") print(f"Points used: {period['usage']['points_usage']} / {period['limits']['points_limit']}") print(f"Requests: {period['usage']['requests_usage']}") ``` --- ## Use Bitquery MCP in Claude Desktop URL: https://docs.bitquery.io/docs/mcp/claude-desktop/ Use Bitquery MCP in Claude Desktop with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Use Bitquery MCP in Claude Desktop Connect Claude Desktop to [`https://mcp.bitquery.io`](https://mcp.bitquery.io) and query Bitquery's blockchain trading dataset in plain English — DEX trades, OHLC, market cap, and wallet history across Solana, Ethereum, BSC, Base, and more. ## Setup 1. Open **Claude Desktop** → **Settings** → **Connectors** (or **MCP Servers**). 2. Choose **Add custom connector** / **Custom MCP server**. 3. Paste the server URL: ``` https://mcp.bitquery.io ``` 4. Save and restart Claude Desktop if prompted. 5. When a tool runs for the first time, sign in with your [Bitquery account](https://account.bitquery.io/) and approve access. OAuth tokens refresh automatically (~30 days). ## Example prompts - *"Top 10 Solana tokens by USD volume in the last 24 hours."* - *"1-minute OHLC for WIF on Raydium for the last 6 hours."* - *"Show every trade for wallet `7xKX…` on Base in the last 7 days."* See the full [MCP server overview](/docs/mcp/mcp-server/) for coverage, authentication options, and more clients. --- ## Use Bitquery MCP in Cursor URL: https://docs.bitquery.io/docs/mcp/cursor/ Use Bitquery MCP in Cursor with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Use Bitquery MCP in Cursor Add Bitquery to Cursor so the AI can query live and historical DEX trades, OHLC, market cap, and wallet data via [`https://mcp.bitquery.io`](https://mcp.bitquery.io). ## Setup via Cursor settings 1. Open **Cursor Settings** → **MCP** (or **Features → MCP Servers**). 2. Add a new MCP server. 3. URL: `https://mcp.bitquery.io` 4. Reload MCP configuration or restart Cursor. 5. Approve Bitquery when prompted and sign in with your Bitquery account. ## Setup via config file Add to `.cursor/mcp.json` in your project (or global Cursor config): ```json { "mcpServers": { "bitquery": { "command": "npx", "args": ["-y", "mcp-remote", "https://mcp.bitquery.io/mcp"] } } } ``` Restart Cursor so the server is picked up. On first tool call, complete OAuth in the browser. ## Example prompts - *"Which Base tokens crossed $10M market cap in the last 24h?"* - *"Pull Pump.fun trades for mint `…` in the last hour."* - *"Compare 24h volume on Raydium vs Orca for SOL pairs."* More detail: [MCP server overview](/docs/mcp/mcp-server/). --- ## Use Bitquery MCP in Windsurf URL: https://docs.bitquery.io/docs/mcp/windsurf/ Use Bitquery MCP in Windsurf with Bitquery MCP for AI tools like Claude and Cursor to analyze on-chain data in plain English. # Use Bitquery MCP in Windsurf Connect Windsurf to Bitquery's hosted MCP endpoint at [`https://mcp.bitquery.io`](https://mcp.bitquery.io) to query DEX trades, prices, liquidity, and wallet history while you build trading tools and dashboards. ## Setup 1. Open **Windsurf** → **Settings** → **MCP** (or the MCP / Cascade connectors panel). 2. Add a **custom MCP server**. 3. Server URL: `https://mcp.bitquery.io` 4. Save and reload the MCP configuration. 5. On first use, sign in with your Bitquery account when OAuth opens in the browser. If Windsurf expects a JSON config, use the same `mcp-remote` pattern as Cursor: ```json { "mcpServers": { "bitquery": { "command": "npx", "args": ["-y", "mcp-remote", "https://mcp.bitquery.io/mcp"] } } } ``` ## Example prompts - *"Latest Raydium pool creations on Solana in the last 2 hours."* - *"OHLC 5m candles for ETH/USDC on Uniswap v3 today."* - *"Wallet PnL summary for `0x…` on Ethereum last 30 days."* See [MCP server overview](/docs/mcp/mcp-server/) for full coverage and auth options. --- ## Using Bitquery Subscriptions to Load On-chain Data into S3 URL: https://docs.bitquery.io/docs/subscriptions/aws/s3_tutorial/ Using Bitquery Subscriptions to Load On-chain Data into S3 using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. # Using Bitquery Subscriptions to Load On-chain Data into S3 In this tutorial we will use Bitquery Subscription queries to fetch latest Pumpfun information on Solana upload it to an S3 Bucket. ![Uploading streamed data to AWS S3](/img/aws/upload.png) #### **1. Prerequisites** Before diving into the tutorial, ensure you have: 1. **AWS Account**: With access to an S3 bucket and all permissions configured for Write Access. 2. **Bitquery Account**: For generating a token to access the Streaming APIs. Follow [this link](/docs/authorization/how-to-generate/) for token generation. 3. **Python Environment**: With required libraries installed. Install required libraries if not already done: ```bash pip install asyncio websockets boto3 ``` #### **2. Setting Up AWS S3 Configuration** The code initializes the AWS S3 client to upload JSON data: ```python # AWS S3 configuration s3_client = boto3.client( 's3', aws_access_key_id='your_aws_access_key', aws_secret_access_key='your_aws_secret_key', region_name='your_aws_region' ) bucket_name = 'your_s3_bucket_name' ``` - Replace `your_aws_access_key`, `your_aws_secret_key`, `your_aws_region`, and `your_s3_bucket_name` with your AWS credentials and bucket name. #### **3. Setting Up the WebSocket Connection** The WebSocket connection is established with the Bitquery API: ```python # Bitquery WebSocket API details url = "wss://streaming.bitquery.io/graphql?token=your_bitquery_token" ``` - Replace `your_bitquery_token` with the token generated from Bitquery ([guide](/docs/authorization/how-to-generate/)). #### **4. Writing the Subscription Query** The subscription query gets real-time Pumpfun DEX trades : ```python 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 } } } } """ ``` You can find more queries here: [Solana Pump Fun API](/docs/blockchain/Solana/Pumpfun/Pump-Fun-API/). #### **5. Fetching and Uploading Data** The `fetch_and_upload` function manages the WebSocket connection, listens for messages, and uploads them to S3. ##### **a. Initialize Connection** ```python await websocket.send(json.dumps({"type": "connection_init"})) ``` The WebSocket connection is initialized by sending a `connection_init` message. It waits for an acknowledgment (`connection_ack`). ##### **b. Send Subscription Query** ```python await websocket.send(json.dumps({"type": "start", "id": "1", "payload": {"query": query}})) ``` After acknowledgment, the subscription query is sent. ##### **c. Listen for Messages** ```python while True: response = await websocket.recv() data = json.loads(response) if data.get("type") == "data" and "payload" in data: trades = data['payload']['data'].get('Solana', {}).get('DEXTrades', []) ``` The WebSocket listens continuously for messages and processes subscription data. ##### **d. Upload Data to S3** ```python def upload_to_s3(data): s3_key = f"data/{data['transaction_signature']}.json" s3_client.put_object(Body=json.dumps(data), Bucket=bucket_name, Key=s3_key) print(f"Uploaded message to S3: {s3_key}") ``` For each message, a JSON file is created with a unique key (`transaction_signature`) and uploaded to S3. #### **6. Error Handling** The code includes error handling for the WebSocket and S3 uploads: ```python try: await fetch_and_upload() except Exception as e: print(f"Error occurred: {e}") ``` This ensures the program continues running even if an error occurs. #### **7. Running the Script** The `asyncio.run(main())` function starts the asynchronous process: ```python async def main(): try: await fetch_and_upload() except Exception as e: print(f"Error occurred: {e}") asyncio.run(main()) ``` ### **Execution Steps** 1. Replace placeholder values (`your_aws_access_key`, `your_bitquery_token`, etc.) with your credentials. 2. Save the script as `bitquery_s3_upload.py`. 3. Run the script: ```bash python bitquery_s3_upload.py ``` 4. Check your S3 bucket for uploaded JSON files. --- ## What Does Not Survive Streaming URL: https://docs.bitquery.io/docs/subscriptions/what-does-not-survive-streaming/ Query features that are unavailable or silently degraded in Bitquery GraphQL subscriptions, including selectWhere, if, statistical metrics, intervals and calculate expressions. # What Does Not Survive Streaming Most queries convert to a subscription by replacing `query` with `subscription`. **Trading cube queries are the exception.** Subscriptions are served by a separate, reduced type tree (`Trading__Stream_Cube`), so a query that works over HTTP can fail — or worse, silently return `null` — as a stream. The five rules below are what actually differs. ## 1. `selectWhere` and `if` do not exist on the stream `selectWhere` is absent from **280** field positions across the four Trading cubes, and `if` from **264**. Both produce a hard schema error in a subscription rather than being ignored. The practical consequence: **live threshold alerting is not expressible on a Trading stream.** You cannot say "notify me when a wallet's buy volume crosses $1M" in the subscription itself. Stream the rows and apply the threshold in your client, or poll a query on an interval. ## 2. Eighteen statistical metrics are query-only Streams keep `average`, `calculate`, `count`, `sum` and `uniq`. Everything else in the metric family — `correlation`, `covariance`, `rank_correlation`, `contingency`, `cramers`, `cramers_bias_corrected`, `theils_corrected`, `nakamoto`, `gini`, `theil_index`, `entropy`, `quantile`, `median`, `skew`, `kurtosis`, `dispersion` and the rest — is unavailable. ## 3. `interval:` is accepted and is a silent no-op The field-level `interval:` argument is accepted by the subscription schema and has **no effect**. It does not error, so a stream that looks like it is emitting 4-hour buckets is emitting whatever the underlying grain is. Do the bucketing client-side. ## 4. `calculate` needs a `$` on every field reference, and has no functions In a subscription, every field reference inside an expression must carry the `$` sigil. A single unsigiled token makes the whole expression return `null` — silently. A mixed expression fails just as completely as a fully bare one: ```graphql # null — bare names calculate(expression: "Price_Ohlc_Close - Price_Ohlc_Open") # null — one bare term is enough to poison it calculate(expression: "$Price_Ohlc_Close - Price_Ohlc_Open") # works calculate(expression: "$Price_Ohlc_Close - $Price_Ohlc_Open") ``` Subscriptions also support **arithmetic operators only**. Function calls — `round()`, `floor()`, `abs()`, `plus()`, `greatest()` — return `null` in a stream while working normally in a query. Drop them from the expression and round in your client. Aliased results can still be referenced and chained: `diff: calculate(...)` then `change: calculate(expression: "$diff / $Price_Ohlc_Open * 100")`. Queries are unaffected by all of this — bare names and functions both work there. ## 5. The Trading subscription root takes no arguments `RootSubscription.Trading` accepts no arguments, so `dataset:` and `aggregates:` are unavailable. `trigger_on` and mempool subscriptions are likewise not part of the Trading stream surface. ## Before you convert a query 1. Remove `selectWhere` and `if`. 2. Replace any statistical metric outside `average` / `calculate` / `count` / `sum` / `uniq`. 3. Drop `interval:` and bucket client-side. 4. Add `$` to every field reference inside `calculate`, and remove function calls. 5. Check the result for `null` computed fields before trusting the stream. ## Related - [Subscriptions](/docs/subscriptions/subscription/) - [Which cubes stream](/docs/subscriptions/which-cubes-stream/) - [Expressions](/docs/graphql/capabilities/expression/) - [Select by metric (`selectWhere`)](/docs/graphql/metrics/selectWhere/) --- ## What is a Trigger? URL: https://docs.bitquery.io/docs/subscriptions/trigger/ What is a Trigger? using Bitquery GraphQL subscriptions over WebSocket for live multi-chain blockchain monitoring. Keep queries fast with indexed filters. # What is a Trigger? The new data pushed to subscription on receiving the new block in the real time database assuming that the criteria, defined in the query are met: * ```trigger_on``` attribute matches the block * conditions defined in the query matches this block * data filtered by all provided conditions, are not empty ## trigger_on ```trigger_on``` attribute controls on which blocks the update of data is triggered for the subscription. It has the following options: * ```all``` - **any** block triggers data update * ```head``` - **new** blocks on the trunk (with the highest tip) triggers data update * ```head_updates``` - **any** blocks on the trunk (with the highest tip) triggers data update * ```branches_updates``` - **any** blocks on the branch (not with the highest tip) triggers data update [Blockchain Reorg Tree](/docs/graphql/dataset/select-blocks/) describes how the tree is represented in the databases. In most cases you just not specify this attribute, assuming all option is what you need. Other options are suitable for event-driven applications: ## Filtering Out All Branch Blocks Even with `trigger_on: head`, you might receive branch blocks. When a blockchain forks, the subscription cannot determine in real time whether the fork selected will become the longest chain (trunk) in the future. At the moment a fork occurs, the system may initially treat a branch block as the head, only to later discover it becomes part of a branch when a longer chain emerges. If you need to completely filter out branch-related blocks and transactions, you can run two streams: 1. **Stream with `trigger_on: all`** - This captures all blocks (both trunk and branch) 2. **Stream with `trigger_on: branch_updates`** - This captures only branch blocks By comparing these two streams, you can identify and filter out branch-related blocks and transactions. Any block or transaction that appears in the `branch_updates` stream should be excluded from your final dataset, ensuring you only process blocks that remain on the trunk chain. :::tip Use ```head_updates``` together with ```branches_updates``` when you need to accumulate all branches and the trunk ::: :::tip Use ```head``` if you need to listen only head blocks in your application. This can slightly delay the data however, as the new block may need the other block to wait to be detected that it is on the tree. ::: --- ## Which Cubes Support Subscriptions URL: https://docs.bitquery.io/docs/subscriptions/which-cubes-stream/ Every Bitquery cube accepts a subscription, but not every cube pushes data. Which cubes stream, which are query-only, and which need a filter. # Which cubes support subscriptions Every cube on `EVM`, `Solana`, `Trading` and `Tron` appears on the subscription schema. A subscription against any of them is a valid document and the server accepts it. That does not mean every cube pushes data. :::danger A valid subscription is not a working subscription Three cubes accept your subscription and then disconnect you under load. Five accept it and never send a single message. In both cases you get no error from the schema, no rejection at subscribe time, and nothing in your logs except silence. This page tells you which is which. ::: --- ## The three behaviours | Behaviour | What you see | What to do | |---|---|---| | **Streams** | Messages arrive within seconds | Nothing, it works | | **Needs a filter** | Some messages, then the socket closes with code `1013` | Add a `where` filter, consume asynchronously | | **Query-only** | Socket stays open, no message ever arrives | Use a query, or stream a different cube | --- ## Matrix Relative volume is a rough guide to what your consumer has to keep up with, not a throughput guarantee. ### Solana | Cube | Subscription | Volume | |---|---|---| | `Blocks` | Streams | High | | `Transactions` | Streams | High | | `Transfers` | Streams | High | | `TokenSupplyUpdates` | Streams | High | | `DEXPools` | Streams | High | | `DEXTrades` | Streams | Moderate | | `DEXTradeByTokens` | Streams | Moderate | | `Rewards` | Streams | Moderate | | `DEXOrders` | Streams | Low | | `PerpetualOrders` | Streams | Moderate | | `PerpetualFills` | Streams | Low | | `PerpetualPositions` | Streams | Low | | `PerpetualPrices` | Streams | Low | | `PerpetualMarketSummaries` | Streams | Low | | `Instructions` | **Filter required** | Very high | | `BalanceUpdates` | **Filter required** | Very high | | `InstructionBalanceUpdates` | **Filter required** | Very high | ### EVM | Cube | Subscription | Volume | |---|---|---| | `MinerRewards` | Streams | High | | `Events` | Streams | Moderate | | `Transactions` | Streams | Moderate | | `Transfers` | Streams | Moderate | | `Blocks` | Streams | Low (block cadence) | | `Calls` | Streams | Low | | `DEXTrades` | Streams | Low | | `DEXTradeByTokens` | Streams | Low | | `DEXPoolEvents` | Streams | Low | | `DEXPoolSlippages` | Streams | Low | | `TransactionBalances` | Streams | Low | | `PredictionTrades` | Streams (`network: matic`) | Moderate | | `PredictionSettlements` | Streams (`network: matic`) | Moderate | | `PredictionManagements` | Streams (`network: matic`) | Low | | `Balances` | **Query-only** | — | | `Holders` | **Query-only** | — | | `Uncles` | **Query-only** | — | ### Trading | Cube | Subscription | Volume | |---|---|---| | `Trades` | Streams | Very high | | `Pairs` | Streams | Very high | | `Currencies` | Streams | Very high | | `Tokens` | Streams | Very high | All four Trading cubes are among the busiest streams on the platform. Filter them. ### Tron | Cube | Subscription | Volume | |---|---|---| | `Transfers` | Streams | Moderate | | `Transactions` | Streams | Moderate | | `DEXTradeByTokens` | Streams | Low | | `Events` | Streams | Low | | `Blocks` | Streams | Low (block cadence) | | `Calls` | Streams | Low | | `DEXTrades` | Streams | Low | | `Balances` | **Query-only** | — | | `Holders` | **Query-only** | — | --- ## Filter-required cubes and close code 1013 `Solana.Instructions`, `Solana.BalanceUpdates` and `Solana.InstructionBalanceUpdates` carry every instruction and every balance change on Solana. Subscribing without a filter asks for the entire firehose, and when your client cannot drain the socket fast enough the server closes it: ``` close code 1013 — client is not consuming messages fast enough ``` `1013` is "Try Again Later" in the WebSocket spec. Nothing is wrong with your query. The server is shedding a consumer that fell behind. The failure is worse than a clean error because it is **load-dependent**. The same unfiltered subscription can run fine during a quiet minute and get dropped during a busy one, so it passes in development and fails in production. ### The fix Add a `where` filter so the server sends you only what you need. An unfiltered `BalanceUpdates` subscription is dropped; the same subscription narrowed to a single token runs cleanly: ```graphql subscription { Solana { BalanceUpdates( where: { BalanceUpdate: { Currency: { MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" } } } } ) { BalanceUpdate { Amount Currency { Symbol } Account { Address } } } } } ``` The same applies to `Instructions`. Filter by program: ```graphql subscription { Solana { Instructions( where: { Instruction: { Program: { Address: { is: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" } } } } ) { Block { Time } Transaction { Signature } Instruction { Program { Method } } } } } ``` Filtering is not only a throughput fix. It is also cheaper, since you are not paying to receive rows you discard. ### Also drain the socket asynchronously A filter reduces the rate; it does not make a blocking consumer safe. Push each message onto a queue and process it elsewhere, so parsing or database writes never stall the read loop. See [Reconnect automatically after disconnect](/docs/subscriptions/silent-disconnect-reconnect/) for a working consumer and reconnect loop. --- ## Query-only cubes These accept a subscription and never emit, and the reason is structural. `Balances` and `Holders` are backed by **aggregate-state tables** (`balances_by_address` and `balances_by_currency`) holding **daily** balance aggregates rather than individual changes. A daily grain has no per-event row to push, so there is nothing for a subscription to deliver. That is also what makes them fast to query and what gives them `combined` support, so the trade-off is deliberate rather than a gap. :::info Stream the changes, query the state For a live view, stream `Transfers` (or `TransactionBalances` on EVM) and apply the deltas yourself. Use `Balances` and `Holders` for the starting state and for periodic checks. ::: | Cube | Use instead | |---|---| | `EVM.Balances` | Query it on a schedule, or stream `EVM.TransactionBalances` / `EVM.Transfers` and apply deltas | | `EVM.Holders` | Query it on a schedule; stream `EVM.Transfers` for the token to know when to refresh | | `Tron.Balances` | Query on a schedule, or stream `Tron.Transfers` | | `Tron.Holders` | Query on a schedule, or stream `Tron.Transfers` | | `EVM.Uncles` | Query with `dataset: archive`. Ethereum has produced no uncles since the Merge | The pattern for a live balance is to read the balance once, then keep it current from the transfer stream, rather than polling the balance cube in a loop. --- ## Cubes that need a specific network or dataset Some cubes exist on the `EVM` root but only carry data on one network or one dataset. The error message is the only place this is stated today, so it is worth listing: | Cube | Requirement | |---|---| | `EVM.PredictionTrades` | `network: matic` | | `EVM.PredictionManagements` | `network: matic` | | `EVM.PredictionSettlements` | `network: matic` | | `EVM.Uncles` | `dataset: archive` | | `EVM.TransactionBalances` | realtime only, no archive tables | Querying `EVM.PredictionTrades` on `network: eth` returns `no data available yet to query dataset realtime eth for PredictionTrade`, which reads like an outage but is a routing mistake. --- ## How this was measured Every row was tested against `wss://streaming.bitquery.io/graphql` with the `graphql-ws` subprotocol, one socket per cube, using a minimal selection set generated from schema introspection. Cubes that produced nothing in the first pass were retried on a longer window, because some low-frequency cubes take longer than 20 seconds to deliver their first message. Classification rules: - **Streams** — at least one message on a socket held open long enough for the cube's cadence. - **Filter required** — reproducibly closed with `1013` when unfiltered, and delivered normally once a `where` clause was added. - **Query-only** — no message and no error across repeated runs, while control subscriptions on the same chain in the same session delivered normally. The controls matter: a chain-level failure would have shown up as every cube on that chain going quiet, and that did not happen. --- ## Related - [Reconnect automatically after disconnect](/docs/subscriptions/silent-disconnect-reconnect/) - [Subscriptions overview](/docs/subscriptions/subscription/) - [WebSocket authorization](/docs/authorization/websocket/) - [Backfilling a subscription](/docs/subscriptions/backfilling-subscription/) --- ## Your First Bitquery GraphQL Query URL: https://docs.bitquery.io/docs/start/first-query/ Run your first Bitquery GraphQL query in minutes with IDE setup, authentication basics, and a simple starter example you can reuse. # Your First Query Create and run your first query on Bitquery IDE by visiting [https://ide.bitquery.io/](https://ide.bitquery.io/). ## Create an account To continue, you must first [register](https://account.bitquery.io/auth/signup) an account to access the IDE window. **Registration Process**: - Navigate to the Bitquery GraphQL IDE by visiting [https://ide.bitquery.io/](https://ide.bitquery.io/). - If you are not registered, click on the "Not registered" link. - You will need to provide your Email, Password, Password Confirmation, Name, and Company Name in the designated fields. - Complete the CAPTCHA challenge and click the Submit button to proceed. - After submitting your registration form, check your email for a confirmation message. Click the link within this email to verify your account. Once your email is successfully verified, you will receive a notification, confirming your account creation is complete. If IDE points to the default endpoint https://graphql.bitquery.io, use the dropdown to change it to the new endpoint https://streaming.bitquery.io/graphql which is labelled as "V2". If you do everything correctly, you will see the grey triangle in the middle of the screen to run the query. The query editor is in the center of the screen, and you can use handy Ctrl-Space key combination to see all possible options that you can enter at the edit point. On the empty editor, it will show the drop-down list: ![IDE context menu](/img/ide/context_menu.png) So you can type the query using hints from IDE. For example, you can query the latest 10 blocks on the ETH network: ```graphql { EVM(network: eth) { Blocks(limit: { count: 10 }) { Block { Number Time } } } } ``` After you create a query, the run triangle button will appear to be green, and you can press it now to see the results: ![IDE query execution](/img/ide/query_execution.png) ## Selecting the Dataset When choosing a dataset from the dropdown menu, you have three options: "realtime," "archive," and "combined." Based on your needs, pick an option. - `realtime`: provides data in real-time as it is published onchain, usually used for data obtained through subscriptions. - `archive`: contains non-real-time data. - `combined`: includes both types of data, but it's advisable not to use it for complex queries. For example, ```graphql { EVM(network: eth, dataset: archive) { Blocks(limit: { count: 10 }) { Block { Number Time } } } } ``` ## Next Steps Now that you've created your first query, learn which data primitives to use: - **[Mental Model: Transfers, Events, Calls, and DexTrades](/docs/start/mental-model-transfers-events-calls)** - Understand when to use Transfers, Events, Calls, or DexTrades for your queries - **[Starter Queries](/docs/start/starter-queries)** - Try pre-built queries for common use cases - **[Learning Path](/docs/start/learning-path)** - Follow a structured path from beginner to advanced --- ## 中文文档 (Chinese) URL: https://docs.bitquery.io/docs/chinese/ Bitquery 中文文档说明:如何用浏览器自动翻译阅读完整文档,以及中文支持渠道。 # Bitquery 中文文档 Bitquery 的完整文档目前以**英文**提供。您可以使用浏览器的自动翻译功能,用中文阅读所有页面。 ## 使用自动翻译 - **Chrome / Edge**:在任意文档页面右键单击 → 选择“翻译成中文”。 - **Safari**:点击地址栏中的翻译图标 → 选择中文。 翻译后即可浏览全部内容,包括代码示例。 ## 常用页面 - [快速开始(第一个查询)](/docs/start/first-query/) - [数据覆盖与保留时间](/docs/graphql/data-coverage-retention/) - [套餐、积分与限制](/docs/plans/how-billing-works/) - [Solana API](/docs/blockchain/Solana/) - [MCP 服务器(AI 代理)](/docs/mcp/mcp-server/) ## 中文支持 如需中文支持,请通过 [Telegram](https://t.me/Bloxy_info) 联系我们,或发送邮件至 [support@bitquery.io](mailto:support@bitquery.io)。