# Metastreams API > This file is very large and may be truncated. For an index of this content, please refer to https://docs.metastreams.io/llms.txt instead. > Real-time and historical spot market data: tokens, OHLCV candles, trades, discovery boards and live streams. # Chains Source: https://docs.metastreams.io/concepts/chains Supported chain slugs, address formats and native units. The API identifies each chain by a slug, used in the `chain` and `chains` query parameters, in request bodies and in stream filters. ## Supported chains | Slug | Chain | Address format | Native unit | | - | - | - | - | | `solana` | Solana | Base58 | SOL | | `bsc` | BNB Smart Chain | `0x` hex | BNB | | `robinhood` | Robinhood Chain | `0x` hex | ETH | | `elysium` | Elysium | `0x` hex | HYPE | Every price, market cap and volume on a chain includes a `native` value in that chain's native unit, alongside `usd`. See [Money](/concepts/reading-responses#money). `native` fluctuates against the dollar. ## Validation * Slugs are lowercase and must match exactly. The API does not accept aliases (`sol`, `bnb`), numeric chain IDs (`56`) or other casing (`Solana`). An unknown slug returns [`UNSUPPORTED_CHAIN`](/concepts/errors#error-codes), with a message that lists every supported slug. * A malformed address, one that is neither Base58 nor `0x` hex, returns [`VALIDATION_ERROR`](/concepts/errors#error-codes). * On REST list endpoints, such as `GET /v1/tokens`, an address is read only on the listed chains that match its format. A Base58 address with `chains=bsc` returns `200` with no element for it. The request still costs a [credit](/concepts/errors#credits). * On streams and the [deprecated per-chain paths](/concepts/errors#deprecated-paths), an address in the wrong format for the chain returns `VALIDATION_ERROR`. * EVM addresses are case-insensitive, and responses return them in lowercase. Solana addresses are case-sensitive. * One `0x` address reads on every EVM chain in scope, and is charged once. # Errors and rate limits Source: https://docs.metastreams.io/concepts/errors Error format, error codes, rate and connection limits, and retry guidance. All API errors share the same response body: ```json theme={null} { "error": { "code": "VALIDATION_ERROR", "message": "One or more parameters are invalid.", "details": [ { "field": "countBack", "message": "Must be between 1 and 5000." } ] } } ``` | Field | Description | | - | - | | `code` | Stable, machine-readable error code. Use this field for error handling. | | `message` | Developer-facing description of what happened and what to do next. Safe to log and display, but do not parse it, because the wording can change. | | `details` | Additional details, present on some codes only, with a fixed shape per code | The HTTP status always matches the code. Two responses have no JSON body: a request with the wrong method for its path returns `405 Method Not Allowed`, and a request to `/v1/stream` without WebSocket upgrade headers returns a plain-text `4xx`. ## Error codes | Code | Status | Cause | Retry | | - | - | - | - | | `VALIDATION_ERROR` | 400 | A parameter or body is malformed, or the request sends a query parameter that the endpoint does not take | No. Fix the request. | | `UNSUPPORTED_CHAIN` | 400 | The chain slug is not [supported](/concepts/chains) | No. Fix the request. | | `UNAUTHORIZED` | 401 | The API key or session token is missing, malformed, unknown, revoked or expired | No. See [Authentication](/get-started/authentication). | | `CREDITS_EXHAUSTED` | 402 | The organization has used the credits its plan includes this billing period. See [Credits](#credits). | No. Wait for the next billing period, or change the plan. | | `FORBIDDEN` | 403 | The request used a session token to call `POST /v1/session-tokens` or `POST /v1/stream/connect`, which require an API key | No. Call the endpoint from your backend with the API key. | | `ORIGIN_NOT_ALLOWED` | 403 | The request used a session token from an origin that the token does not allow, or has no `Origin` header | No. Create a token that allows the origin. | | `NOT_FOUND` | 404 | The path or resource does not exist, or the API has no [direct stream route](/streams/overview#routes) | No. | | `RATE_LIMITED` | 429 | A [rate or connection limit](#limits) was reached | Yes, after `Retry-After`. | | `INTERNAL_ERROR` | 500 | An unexpected server error | Yes, with backoff, a few times. | | `SERVICE_UNAVAILABLE` | 503 | Maintenance, or a temporary outage | Yes, with backoff. | New codes may be added. Handle an unrecognized code according to its HTTP status. ### Validation details Only two codes include `details`. `UNSUPPORTED_CHAIN` includes `{chain}`, and `VALIDATION_ERROR` includes a list of `{field, message}` objects, one per problem, as in the example at the top of this page. `field` is the parameter name as sent in the request, or `path`, `query` or `body` when the problem is not tied to a single field. ## Limits Limits are set well above normal use. Reaching one usually indicates a retry loop or leaked stream connections. | Limit | Value | Behavior when reached | | - | - | - | | Requests per organization | 10 per second on the free plan. Paid plans set a higher rate. | `429 RATE_LIMITED`. Wait for `Retry-After`. | | Stream connections | Included in paid plans. The free plan has none. | `403 FORBIDDEN` on the handshake and on `POST /v1/stream/connect`. Open connections close with code `4403` when the organization moves to a plan without streams. | | Open stream connections per API key | 20 | `429 RATE_LIMITED` on the handshake. Waiting does not free a slot; close a connection that is no longer needed. | | Subscriptions per API key | 20, across all its connections | The subscribe request is rejected with an `error` frame | | Addresses per API key | 2,000, across all its subscriptions. See [Address limits](/streams/filters#address-limits). | The subscribe request is rejected with an `error` frame | | Session-token stream connections per API key | 10,000, across all the tokens created with the key | `429 RATE_LIMITED` on the handshake | | Origins per session token | 10 | `400 VALIDATION_ERROR` when creating the token | | Session token lifetime | 3,600 seconds | `400 VALIDATION_ERROR` when creating the token | | Active API keys per organization | 10 | The dashboard rejects a new key with `409 KEY_LIMIT_REACHED` | | Unsent frames per stream connection | 1,024 | The connection closes with code `4008`. See [Close codes](/streams/overview#close-codes). | | Time to deliver one frame to your client | 10 seconds | The connection closes with code `4008` | | Size of a frame you send | 1 MiB | The connection closes with no close code | | Matching tokens per `spot.tokens` subscription | 10,000 | An `exit` frame for the least recently matched token | | Positions per `spot.positions` subscription | 10,000 | New positions are not sent | | Open buckets per `spot.candles` subscription with `closedOnly` | 10,000 | New series are not sent | | Tokens per request | 100 on `/v1/tokens`; 10 on `/v1/ohlcv`, `/v1/holders` and `/v1/trades`; 1 on `/v1/ohlcv` with `pool` | `400 VALIDATION_ERROR` | | Pools per `POST /v1/trades` filter | 10 | `400 VALIDATION_ERROR` | | Wallets per request | 100 | `400 VALIDATION_ERROR` | | Trades or positions per page | 100 | Larger `limit` values are lowered to 100 | | Holders per token | 150, and 30 by default | Larger `limit` values are lowered to 150 | | Trades of a `wallets` read | The last 90 days | Older trades are not returned | | Window of a `POST /v1/trades` read | See [Time window](/reference/rest/trade-search#time-window) | Older trades are not returned | | Search results per request | 20, and 10 by default | Larger `limit` values are lowered to 20 | | Candles per request | 5,000 | `countBack` above 5,000 returns `400 VALIDATION_ERROR` | | `throttleMs` | 60,000 | `VALIDATION_ERROR` in an `error` frame | All keys of one organization share a single request budget. Your plan, or an agreement for your organization, can set another rate, including a separate rate for one endpoint. On paid plans, `POST /v1/discovery`, `POST /v1/trending` and `GET /v1/search` each have a budget of their own, so a request to one of them does not count against the budget of every other endpoint. On the free plan, they share that budget. Each [session token](/get-started/authentication#session-tokens) has its own stream connection, subscription and address limits, equal to its key's, and counts against its key's request budget. The request budget refills continuously, at one request every tenth of a second for a rate of 10 per second, and allows a burst of at most one second's worth of requests. Limits are not applied per IP address, so multiple servers behind one outbound IP are limited only by their key's budget. Design your client to stay well below these values. A stream connection counts against your key from its handshake until it closes, and frames sent over a connection do not consume request budget. The 20 subscriptions belong to the key rather than to a connection, so a single connection can hold all of them. `GET /openapi.json` requires no key, consumes no budget, and returns no `X-RateLimit-Remaining` header. ## Credits A successful (`2xx`) request costs one credit for each token or wallet it lists, and at least one credit. For example, `GET /v1/tokens?tokens=A,B,C` costs three credits, and `POST /v1/trending` costs one. A `POST /v1/trades` request costs one credit for each token and wallet in its filter; pools are free. `POST /v1/stream/connect` costs nothing. An address counts once even when it reads on several chains. Each stream `update` frame costs one third of a credit. Error responses, the stream handshake, and the `ack`, `exit`, `error` and `pong` frames cost nothing. A narrower stream filter, `throttleMs` and `closedOnly` each send fewer frames, so they cost less. When an organization has used the credits its plan includes for the billing period: * Every request with any of its keys returns `402 CREDITS_EXHAUSTED`, including the stream handshake. * Its open stream connections close with code `4402`. * Requests succeed again when the next billing period starts or the organization moves to a larger plan. An organization admin can request a plan change on the **Billing** page of the [dashboard](https://metastreams.io/dashboard/billing). The change is confirmed by email before it takes effect. The cutoff takes effect within about 10 seconds, so usage can briefly exceed the plan's allowance. ## Response headers | Header | Present on | Description | | - | - | - | | `X-Request-ID` | Every response | Trace ID of the request: the value you sent, or a generated UUID. See [Request IDs](#request-ids). | | `X-RateLimit-Remaining` | Every `/v1` response with a valid key, including rejected requests | Number of requests you can send right now | | `Retry-After` | Every `429` | Number of whole seconds to wait before retrying, never `0` | `X-RateLimit-Remaining` reports the remaining requests in the budget this request counted against. It is absent from a `401`, because the request has no valid key, from a `403 ORIGIN_NOT_ALLOWED`, and from a `503` returned when the key could not be validated. Use `X-RateLimit-Remaining` to pace your client and slow down before you reach the limit. The API compresses a response body of 1 KB or more with zstd, Brotli or gzip when the request's `Accept-Encoding` allows it. ### Deprecated paths The per-token and per-wallet paths that the [collection endpoints](/resources/changelog) replaced still serve. Each of their responses includes a `Deprecation` header and a `Link` header that identifies the replacement, such as `; rel="successor-version"`. Move to the replacement; a deprecated path can be removed later. | Deprecated path | Replacement | | - | - | | `GET /v1/tokens/{chain}/{address}` | [`GET /v1/tokens`](/reference/rest/token-details) | | `GET /v1/tokens/{chain}/{address}/ohlcv` | [`GET /v1/ohlcv`](/reference/rest/token-ohlcv) | | `GET /v1/tokens/{chain}/{address}/trades` | [`GET /v1/trades`](/reference/rest/trades) | | `GET /v1/tokens/{chain}/{address}/holders` | [`GET /v1/holders`](/reference/rest/token-holders) | | `GET /v1/wallets/balances` | [`GET /v1/balances`](/reference/rest/wallet-balances) | | `GET /v1/activity` | [`GET /v1/trades`](/reference/rest/trades) | ## Retry strategy 1. **Respect `Retry-After`.** Wait at least the number of seconds it specifies. 2. **Use exponential backoff with jitter on `500` and `503`,** so parallel workers do not retry in sync. 3. **Limit retries.** Three to five attempts are enough; beyond that, the problem needs investigation. 4. **Do not retry a `4xx` other than `429`.** The request fails the same way every time. ```typescript Node.js theme={null} const RETRYABLE = new Set([429, 500, 503]); async function getWithRetries(url: string, headers: Record, attempts = 5) { for (let attempt = 0; ; attempt++) { const response = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) }); if (!RETRYABLE.has(response.status) || attempt >= attempts - 1) return response; const retryAfter = response.headers.get("Retry-After"); const delay = retryAfter ? Number(retryAfter) * 1000 : Math.min(30_000, 1000 * 2 ** attempt) + Math.random() * 1000; await new Promise((resolve) => setTimeout(resolve, delay)); } } ``` ```rust Rust theme={null} use std::time::Duration; use rand::Rng; use reqwest::{Client, Response, StatusCode}; const RETRYABLE: [StatusCode; 3] = [ StatusCode::TOO_MANY_REQUESTS, StatusCode::INTERNAL_SERVER_ERROR, StatusCode::SERVICE_UNAVAILABLE, ]; /// `client` carries a request timeout, for example `Client::builder().timeout(Duration::from_secs(10))`. async fn get_with_retries(client: &Client, url: &str, key: &str, attempts: u32) -> reqwest::Result { let mut attempt = 0; loop { let response = client.get(url).bearer_auth(key).send().await?; if !RETRYABLE.contains(&response.status()) || attempt + 1 >= attempts { return Ok(response); } let retry_after = response.headers().get("Retry-After").and_then(|value| value.to_str().ok()?.parse().ok()); let delay = match retry_after { Some(seconds) => Duration::from_secs(seconds), None => Duration::from_millis((1000 * 2u64.pow(attempt.min(5))).min(30_000) + rand::rng().random_range(0..1000)), }; tokio::time::sleep(delay).await; attempt += 1; } } ``` ## Request IDs Every response includes an `X-Request-ID` header. You can also send your own `X-Request-ID` of up to 128 visible ASCII characters with no spaces, and the API returns it unchanged. An invalid value is replaced with a generated ID rather than rejected. When you contact support about a failed request, include its `X-Request-ID`. ## Stream errors When the API rejects a stream frame, it returns an `error` frame with the same `code`, `message` and `details` fields. See [WebSocket streams](/streams/overview#errors). # Response format Source: https://docs.metastreams.io/concepts/reading-responses Conventions for field names, timestamps, prices, decimals and percentages. All REST endpoints and streams follow the same response conventions, described on this page. ## Field names Field names and query parameters are **camelCase**: `marketCap`, `priceChangePct`, `countBack`. Enumerated **values** are case-sensitive strings, such as `"side": "buy"`, `"flags": ["pro_trader"]` and `"metric": "marketCap"`. Send and compare them exactly as documented. Responses can include values that are new since you wrote your client, such as a new flag, venue or trader source. Ignore a value you do not recognize, rather than failing to parse the response. ## Timestamps Every timestamp is an integer count of **milliseconds** since the Unix epoch, in requests and responses alike. * Fields that hold a point in time end in `At`: `createdAt`, `graduatedAt`, `updatedAt`. * Some records use a plain name instead, such as a trade's `timestamp` and a candle's `time`. ```json theme={null} { "createdAt": 1723180800000 } ``` ```typescript Node.js theme={null} const created = new Date(token.createdAt); ``` ```rust Rust theme={null} use time::OffsetDateTime; let created_at = token["createdAt"].as_i64().ok_or("createdAt is missing")?; let created = OffsetDateTime::from_unix_timestamp_nanos(i128::from(created_at) * 1_000_000)?; ``` ## Money Every price, market cap, liquidity, volume and fee total is returned in two units: ```json theme={null} { "price": { "native": "0.000000121", "usd": "0.0000216" } } ``` | Field | Description | | - | - | | `native` | Value in the chain's native unit: SOL on Solana, BNB on BSC, ETH on Robinhood Chain, HYPE on Elysium | | `usd` | Value in US dollars, or `null` when the native unit has no USD price | No response has a standalone `priceUsd` field; `priceUsd` is only a filter key. The [portfolio](/reference/rest/portfolio) sums are the exception to the pair: fields such as `totalValueUsd` and `stableBalanceUsd` contain only the USD value, as a decimal string. ## Decimals Prices, amounts, supplies and percentages are returned as **strings** containing exact decimals: `"0.0000216"`, `"1000000000"`. JSON numbers are floating point and lose precision on small prices and large token amounts, so parse these strings with a decimal type: ```typescript Node.js theme={null} import Big from "big.js"; const price = token.price.usd === null ? null : new Big(token.price.usd); ``` ```rust Rust theme={null} use rust_decimal::Decimal; let price: Option = token["price"]["usd"].as_str().map(str::parse).transpose()?; ``` Counts, such as `holders.count` and `buyCount`, are plain JSON integers. ### Candle values Candle values (`open`, `high`, `low`, `close`, `volume`) are **JSON numbers**, because charting libraries consume them as floats. Candles are the only place where the API returns money as a number. ## Percentages A field ending in `Pct` holds a signed percentage on a **0–100 scale**, as a decimal string. ```json theme={null} { "priceChangePct": "-2.5", "top10Pct": "31.7" } ``` For example, `"-2.5"` means a decrease of 2.5%, not a factor of -0.025. Fields ending in `Bps` are the exception: they are integers in **basis points**, so `250` means 2.50%. Examples are `transferFeeBps`, `buyTaxBps` and `totalSellBps`. ## Trailing windows A token's `stats` object holds one entry per trailing window, keyed `5m`, `30m`, `1h`, `6h` and `24h`. Each window ends at the current time rather than aligning to a calendar bucket. ```json theme={null} { "stats": { "1h": { "priceChangePct": "1.8", "volume": { "native": "4120.5", "usd": "735509" }, "buyCount": 2210, "sellCount": 1984, "buyVolume": { "native": "2101.2", "usd": "375064" }, "sellVolume": { "native": "2019.3", "usd": "360445" } } } } ``` ## Missing values * Most values that are not yet known are `null`. For example, `graduatedAt` is `null` until a token leaves its launchpad. * A few fields use an empty value instead. For example, a trade's `name` and `symbol` are empty strings until the token's metadata is available. * Empty lists may be omitted: `platforms` and `annotations` on a token, and `flags`, `platforms` and `identities` on a trade. Treat a missing list as empty. * A token's `fees` object is omitted when no fee data is known. * Each URL in a token's `logo` can return `404` while the artwork is not yet stored. Show a placeholder when the image does not load. # AI tools Source: https://docs.metastreams.io/get-started/ai-tools Read these docs from an AI assistant or coding agent: the MCP server, the llms.txt index, Markdown pages and the API specs. These docs are published in forms that AI assistants and coding agents read directly. Point your agent at one of them before it writes code against the API. ## MCP server The docs have a Model Context Protocol server. An MCP client connected to it can search every page and read any page in full. ```text theme={null} https://docs.metastreams.io/mcp ``` The server uses the Streamable HTTP transport and needs no key. > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http metastreams-docs https://docs.metastreams.io/mcp > ``` > [tab] Cursor > > Add the server to `.cursor/mcp.json` in your project, or to `~/.cursor/mcp.json` for every project. > > ```json theme={null} > { > "mcpServers": { > "metastreams-docs": { "url": "https://docs.metastreams.io/mcp" } > } > } > ``` > [tab] VS Code > > Add the server to `.vscode/mcp.json` in your project. > > ```json theme={null} > { > "servers": { > "metastreams-docs": { "type": "http", "url": "https://docs.metastreams.io/mcp" } > } > } > ``` The menu at the top of each page also connects the server to Cursor or VS Code, and copies a page or opens it in Claude or ChatGPT. ## Text files | File | Contents | | - | - | | [`llms.txt`](https://docs.metastreams.io/llms.txt) | An index of every page, grouped as in the sidebar, with a one-line description of each | | [`llms-full.txt`](https://docs.metastreams.io/llms-full.txt) | Every page in one file | | Any page with `.md` appended | That page as Markdown, such as [`/get-started/quickstart.md`](https://docs.metastreams.io/get-started/quickstart.md) | A request for a page that sends `Accept: text/markdown` also receives Markdown. ## API specs | Spec | URL | Contents | | - | - | - | | OpenAPI | `https://api.metastreams.io/openapi.json` | Every REST endpoint, parameter, response and error. Public; no key needed. | | AsyncAPI | `https://docs.metastreams.io/specs/asyncapi.yaml` | Every stream channel, filter and frame | Generate a client from the OpenAPI spec, or give it to an agent as the source of truth for request and response shapes. # Get an API key Source: https://docs.metastreams.io/get-started/api-keys Create an API key in the dashboard, keep it secure, and rotate or revoke it. Every request to `/v1` requires an API key, or a [session token](/get-started/authentication#session-tokens) created with one. You create, list and revoke your organization's keys in the [dashboard](https://metastreams.io/dashboard/api-keys). ## Create a key 1. [Sign up](https://metastreams.io/signup) with an email address or a Google account. Signing up creates your account and an organization, with you as its admin. 2. If you signed up with an email address, open the verification link sent to it. Only an admin with a verified email address can create or revoke keys. 3. On the **API Keys** page, select **Create a key**. Enter a name of 1 to 24 characters, such as `Production server`, and select **Create key**. 4. Copy the key and store it securely. The dashboard shows the full key only once. Every new organization starts on the free plan, which includes REST requests but no stream connections. A stream handshake on the free plan returns `403 FORBIDDEN`. The [pricing page](https://metastreams.io/pricing) lists the [credits](/concepts/errors#credits) and limits of each plan. To join an existing organization instead of creating one, open the invitation link that its admin sends you, then sign up or sign in. ## Key format A key consists of `meta_` followed by 43 characters. The first 12 characters, such as `meta_9tK2vQx`, form the key's **prefix**, which identifies the key without revealing it. When you contact support, include the prefix, never the full key. Keys have no environment prefix. All keys have the same format, but a key works only in the environment that issued it. ## Organizations and key lifetime Every key belongs to an organization, and an organization can have up to 10 active keys. Creating an eleventh returns `409 KEY_LIMIT_REACHED`; revoke a key first. All keys of one organization share its request budget, its credits and its plan. Each key has its own stream [limits](/concepts/errors#limits). A key does not expire. It stays valid until it is revoked. ## Key security * Store the key in a secret manager or an environment variable on your server. * Never put the key in browser code, a mobile app, a public repository or a URL. See [Choosing a credential](/get-started/authentication#choosing-a-credential) for the reasons. In a browser, use a [session token](/get-started/authentication#session-tokens). * Use a separate key for each environment, so you can revoke one without affecting the others. ## Rotate a key 1. Create a new key in the dashboard. If the organization already has 10 active keys, first revoke one that is not in use. 2. Deploy the new key everywhere the old one is in use. 3. Restart your stream connections so that none still use the old key. 4. Revoke the old key in the dashboard. Both keys remain valid until the old one is revoked, so rotation requires no downtime. ## Revoke a leaked key If a key leaks, revoke it on the **API Keys** page of the dashboard: open the key's actions menu, select **Revoke**, then select **Revoke key**. Within about 30 seconds of revocation, requests and new stream connections that use the key return `401 UNAUTHORIZED`, as with any unknown key, and open stream connections that use the key close with code `1008`. Revoking a key also invalidates every session token created with it. See [Close codes](/streams/overview#close-codes). # Authentication Source: https://docs.metastreams.io/get-started/authentication Authenticate REST requests and stream connections with an API key, or with a session token from a browser. Every request under `/v1` must include a credential as a bearer token in the `Authorization` header. The credential is your API key, or a [session token](#session-tokens) created with it: ```http theme={null} Authorization: Bearer meta_... ``` The API rejects a credential sent in any other header, in the query string or in a cookie. The only exception is the WebSocket handshake, where a browser can send a session token in the `Sec-WebSocket-Protocol` header. See [Session tokens](#session-tokens). ## REST requests Include the header on every request: ```bash theme={null} curl "https://api.metastreams.io/v1/tokens?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana" \ -H "Authorization: Bearer $API_KEY" ``` The scheme name `Bearer` is case-insensitive, but the key itself is case-sensitive. ## Stream handshake The WebSocket endpoint at `/v1/stream` accepts the same header on its opening HTTP request. The key is validated before the upgrade, so a client without a valid key cannot open a connection. On the [direct route](/streams/overview#routes), your backend sends `POST /v1/stream/connect` with its API key, then opens the returned `url` with the returned `metaconnect_` token in the same header. The token is valid for 30 seconds and is accepted only on that URL. ```typescript Node.js (ws) theme={null} import WebSocket from "ws"; const socket = new WebSocket("wss://api.metastreams.io/v1/stream", { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); // A refused handshake arrives as an `error` event. Without a listener, Node exits. socket.on("error", (error) => console.error("stream error:", error.message)); ``` ```rust Rust (tokio-tungstenite) theme={null} use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; #[tokio::main] async fn main() -> Result<(), Box> { let mut request = "wss://api.metastreams.io/v1/stream".into_client_request()?; let auth = format!("Bearer {}", std::env::var("API_KEY")?); request.headers_mut().insert("Authorization", auth.parse()?); // A refused handshake returns `Error::Http` with the response status. let (socket, _) = connect_async(request).await?; Ok(()) } ``` ## Authentication errors A missing, malformed, unknown or revoked key returns the same response, as does an expired or invalid session token: ```http theme={null} HTTP/1.1 401 Unauthorized X-Request-ID: 0b7e6a3c-2d4f-4c1a-9e8b-5f6a7b8c9d0e ``` ```json theme={null} { "error": { "code": "UNAUTHORIZED", "message": "Missing or invalid credential. Send an API key or a session token as `Authorization: Bearer `." } } ``` The response does not indicate which of these cases applies, so it cannot reveal which keys exist. Do not retry a `401`. Instead, check that the key is set, sent in the correct header, and not revoked. For a session token, request a new one from your backend. > [!NOTE] > > A `503 SERVICE_UNAVAILABLE` means the key could not be validated at that moment and does not indicate a problem with your key. Retry with backoff and keep using the same key. ## Choosing a credential | Where your code runs | How it calls the API | | - | - | | Your backend | Directly, with your API key | | A browser | Directly, with a [session token](#session-tokens) that your backend creates | | A mobile or desktop app | Through your backend | Keep your API key on servers you control, because anyone can extract it from a web page or an app. A browser also blocks the response to a request with an API key, because the API sends CORS headers only on requests with a session token. ## Session tokens A session token is a short-lived credential that your backend creates with its API key for one signed-in user. The browser sends the token instead of the key, so the key never leaves your backend. 1. Your backend signs in its user and calls [`POST /v1/session-tokens`](/reference/rest/session-tokens) with its key. The request specifies 1 to 10 origins your page is served from, and can include a `subject` of up to 128 characters that identifies your user, and a lifetime in `ttlSeconds`. 2. Your backend returns the `token` to the page. 3. The page sends the token as `Authorization: Bearer ` on REST requests. On the stream, it passes `metastreams.v1` and the token as WebSocket subprotocols. A handshake that passes the token without `metastreams.v1` returns `400 VALIDATION_ERROR`. 4. Before `expiresAt`, the page requests a new token from your backend. A token cannot be refreshed. ```typescript Browser theme={null} const token = await fetch("/api/metastreams-token").then((r) => r.text()); const response = await fetch( "https://api.metastreams.io/v1/tokens?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana", { headers: { Authorization: `Bearer ${token}` } }, ); const socket = new WebSocket("wss://api.metastreams.io/v1/stream", ["metastreams.v1", token]); ``` In the sample, `/api/metastreams-token` is the route on your backend that creates the token. ### Origins Each request with a session token must come from one of the origins specified when the token was created. A request from any other origin, or without an `Origin` header, returns `403 ORIGIN_NOT_ALLOWED`. The API sends CORS headers on every response to a request with a session token, including an error response. The origin check prevents one site from using a token created for another. A client outside a browser can set any `Origin` header, so create tokens only for users your backend has signed in. ### Lifetime and revocation A token is valid for 60 to 3,600 seconds, 900 by default. After it expires, requests with the token return `401 UNAUTHORIZED`, and stream connections the token opened close with code `1008` and the reason `token expired`. A single token cannot be revoked. Revoking the key invalidates every token created with it within about 30 seconds. ### Billing and limits Requests with a session token count against the rate limit and credits of the key that created it. Creating a token costs one credit. Each token has its own stream limits of 20 connections, 20 subscriptions and 2,000 addresses, counted separately from its key. All the tokens of one key share a limit of 10,000 open connections. Only an API key can create a token. A request to create a token with a session token returns `403 FORBIDDEN`. A session token also cannot request a [direct stream connection](/streams/overview#routes): `POST /v1/stream/connect` returns `403 FORBIDDEN`. Browsers use the proxied route. ## Public endpoints `GET https://api.metastreams.io/openapi.json` returns the OpenAPI document without a key, so you can generate a client before you have one. # Quickstart Source: https://docs.metastreams.io/get-started/quickstart Make your first REST request and open your first stream in a few minutes. In this guide, you fetch a Solana token, request its candles, and stream its trades in real time. The examples use BONK (`DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263`) as the example token. REST samples come in cURL, TypeScript for Node.js 18 or later, and Rust. Stream samples come in Node.js and Rust. The Node.js stream samples need the [`ws`](https://github.com/websockets/ws) package, and the Rust samples need these dependencies: ```toml Cargo.toml theme={null} [dependencies] futures-util = "0.3" rand = "0.9" reqwest = { version = "0.13", features = ["json", "query"] } rust_decimal = "1" serde_json = "1" time = "0.3" tokio = { version = "1", features = ["full"] } tokio-tungstenite = { version = "0.30", features = ["rustls-tls-webpki-roots"] } ``` The Rust samples call the API directly, so you can see each request. For typed responses and managed stream subscriptions, use the [Rust SDK](/sdks/rust) instead. **1. Set your API key** If you don't have a key yet, see [Get an API key](/get-started/api-keys). Then export it in your shell: ```bash theme={null} export API_KEY="meta_..." ``` **2. Fetch a token** Request the token object, sending your key as a bearer token: ```bash cURL theme={null} curl "https://api.metastreams.io/v1/tokens?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const response = await fetch( "https://api.metastreams.io/v1/tokens?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana", { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }, ); if (!response.ok) throw new Error(`HTTP ${response.status}`); const [token] = await response.json(); console.log(token.symbol, token.price.usd); ``` ```rust Rust theme={null} use serde_json::Value; #[tokio::main] async fn main() -> Result<(), Box> { let tokens: Vec = reqwest::Client::new() .get("https://api.metastreams.io/v1/tokens") .query(&[("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"), ("chains", "solana")]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; let token = &tokens[0]; println!("{} {}", token["symbol"].as_str().unwrap_or_default(), token["price"]["usd"].as_str().unwrap_or("null")); Ok(()) } ``` The response is a list with one token object per chain that holds the token. Shortened here: ```json theme={null} [{ "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "name": "Bonk", "symbol": "Bonk", "decimals": 5, "logo": { "small": "https://cdn.example.com/DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263_16x16.webp", "medium": "https://cdn.example.com/DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263_60x60.webp", "large": "https://cdn.example.com/DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263.webp" }, "price": { "native": "0.000000121", "usd": "0.0000216" }, "marketCap": { "native": "10741962.1", "usd": "1917440000" }, "liquidity": { "native": "61230.4", "usd": "10929626" }, "stats": { "24h": { "priceChangePct": "-3.4", "volume": { "native": "301422.8", "usd": "53803970" }, "buyCount": 48211, "sellCount": 45390, "buyVolume": { "native": "151002.1", "usd": "26953870" }, "sellVolume": { "native": "150420.7", "usd": "26850100" } } }, "holders": { "count": 972311, "top10Pct": "31.7", "sniperPct": "0.2" }, "security": { "mintDisabled": true, "transferBlockable": false }, "updatedAt": 1789632012345 }] ``` Prices and amounts are decimal strings, and every priced value includes both a `native` and a `usd` value. See [Response format](/concepts/reading-responses) for details on each convention. **3. Fetch candles** Request the last 24 hourly candles, priced in USD: ```bash theme={null} curl "https://api.metastreams.io/v1/ohlcv?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana&timeframe=1h&metric=price&countBack=24" \ -H "Authorization: Bearer $API_KEY" ``` ```json theme={null} [ { "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "candles": [ { "time": 1789545600000, "open": 0.0000221, "high": 0.0000224, "low": 0.0000219, "close": 0.0000222, "volume": 2104410.5 }, { "time": 1789549200000, "open": 0.0000222, "high": 0.0000223, "low": 0.0000215, "close": 0.0000216, "volume": 2981337.2 } ], "nextCursor": null, "hasMore": false } ] ``` Candles are sorted oldest first, and `time` is the open time of each bucket in milliseconds. Buckets with no trades are omitted. `nextCursor` and `hasMore` page further back; see [Candles](/reference/rest/token-ohlcv). **4. Stream live trades** Streams need a paid plan. On the free plan, the handshake returns `403 FORBIDDEN`; see [Get an API key](/get-started/api-keys). Connect, passing your key in the handshake, and send a subscribe frame. Each sample prints every frame it receives: ```typescript Node.js (ws) theme={null} import WebSocket from "ws"; const socket = new WebSocket("wss://api.metastreams.io/v1/stream", { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); socket.on("error", (error) => console.error("stream error:", error.message)); socket.on("open", () => { socket.send(JSON.stringify({ action: "subscribe", channel: "spot.trades", filters: { chains: ["solana"], tokens: ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] }, id: "bonk-trades", })); }); socket.on("message", (raw) => console.log(raw.toString())); ``` ```rust Rust (tokio-tungstenite) theme={null} use futures_util::{SinkExt, StreamExt}; use serde_json::json; use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest}; #[tokio::main] async fn main() -> Result<(), Box> { let mut request = "wss://api.metastreams.io/v1/stream".into_client_request()?; let auth = format!("Bearer {}", std::env::var("API_KEY")?); request.headers_mut().insert("Authorization", auth.parse()?); let (mut socket, _) = connect_async(request).await?; let subscribe = json!({ "action": "subscribe", "channel": "spot.trades", "filters": { "chains": ["solana"], "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] }, "id": "bonk-trades", }); socket.send(Message::text(subscribe.to_string())).await?; while let Some(message) = socket.next().await { if let Message::Text(frame) = message? { println!("{frame}"); } } Ok(()) } ``` An `ack` frame confirms the subscription: ```json theme={null} {"type": "ack", "channel": "spot.trades", "subscriptionId": "5f0c6d1e-8a2b-4c3d-9e4f-1a2b3c4d5e6f", "id": "bonk-trades", "status": "success", "message": "subscribe successful"} ``` After that, you receive one `update` frame per trade: ```json theme={null} {"type": "update", "channel": "spot.trades", "subscriptionId": "5f0c6d1e-8a2b-4c3d-9e4f-1a2b3c4d5e6f", "data": {"id": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h:2", "chain": "solana", "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "name": "Bonk", "symbol": "Bonk", "trader": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "transactionHash": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h", "side": "buy", "amount": "12500000", "price": {"native": "0.000000121", "usd": "0.0000216"}, "volume": {"native": "1.51", "usd": "270.12"}, "marketCap": {"native": "10741962.1", "usd": "1917440000"}, "flags": ["whale"], "timestamp": 1789632015120}} ``` The `data` field of each update contains the same trade object that the REST trades endpoint returns. You can also filter by wallet, venue, trader flag or trade size; see [`spot.trades`](/reference/streams/spot-trades#filters). The same filter reads past trades with [`POST /v1/trades`](/reference/rest/trade-search). ## Next steps > [card] [Response format](/concepts/reading-responses) > > Prices, decimals, percentages and timestamps. > [card] [WebSocket streams](/streams/overview) > > Frames, channels and reconnection. > [card] [Errors and rate limits](/concepts/errors) > > Error codes, retries and rate limits. > [card] [Trades](/reference/rest/trades) > > Trades by token, wallet or identity feed, with pagination. # Introduction Source: https://docs.metastreams.io/index Spot market data for Solana, BNB Smart Chain, Robinhood Chain and Elysium: tokens, candles, trades, discovery boards and live streams. Metastreams is a real-time and historical spot market data API for Solana, BNB Smart Chain, Robinhood Chain and Elysium. It provides token prices and stats, OHLCV candles, trades, holders and launchpad discovery over REST and WebSocket, for trading bots, terminals, dashboards and alerts. > [card] [Get an API key](/get-started/api-keys) > > Sign up and create a key for your organization. > [card] [Quickstart](/get-started/quickstart) > > Make your first REST request and open your first stream. ## Endpoints | Endpoint | Path | Returns | | - | - | - | | [Tokens](/reference/rest/token-details) | `GET /v1/tokens` | Price, stats, holders, security and launchpad of up to 100 tokens | | [Candles](/reference/rest/token-ohlcv) | `GET /v1/ohlcv` | OHLCV from 1s to 7d, per token or per pool | | [Trades](/reference/rest/trades) | `GET /v1/trades` | Recent trades by token, wallet or notable-wallet feed | | [Trade history](/reference/rest/trade-search) | `POST /v1/trades` | Trades that match any `spot.trades` filter, newest first or ranked | | [Holders](/reference/rest/token-holders) | `GET /v1/holders` | Current holders, largest balance first | | [Search](/reference/rest/search) | `GET /v1/search` | Tokens by symbol, name or address, and wallets by name | | [Discovery boards](/reference/rest/discovery) | `POST /v1/discovery` | Ranked launchpad tokens, filtered | | [Trending](/reference/rest/trending) | `POST /v1/trending` | Tokens ranked by trending score | | [Wallet balances](/reference/rest/wallet-balances) | `GET /v1/balances` | Latest balance of each wallet and asset | | [Positions](/reference/rest/positions) | `GET /v1/positions` | Spot positions of wallets, with cost basis and PnL | | [Portfolio](/reference/rest/portfolio) | `GET /v1/portfolio` | Value, balances, positions and stats of a set of wallets | | [Native prices](/reference/rest/native-prices) | `GET /v1/native-prices` | USD price of each chain's gas asset | | [Session tokens](/reference/rest/session-tokens) | `POST /v1/session-tokens` | A short-lived credential for a browser user | | [Live streams](/streams/overview) | `GET /v1/stream` | Trades, transfers, candles, tokens, discovery and trending boards, wallet balances, positions, holders and native prices over WebSocket | All responses use camelCase field names, Unix millisecond timestamps and decimal strings for monetary values. See [Response format](/concepts/reading-responses). ## Base URLs | Transport | URL | | - | - | | REST | `https://api.metastreams.io/v1` | | WebSocket | `wss://api.metastreams.io/v1/stream` | | OpenAPI document | `https://api.metastreams.io/openapi.json` | The OpenAPI document is public and can be used to generate a client. Every other path requires an API key, sent from your backend, or a session token, sent from a browser. Never use an API key in browser or mobile code. See [Authentication](/get-started/authentication#choosing-a-credential). ## Next steps > [card] [Authentication](/get-started/authentication) > > Pass your API key, or a session token from a browser, on REST requests and WebSocket connections. > [card] [Response format](/concepts/reading-responses) > > Timestamps, prices, decimals and percentages. > [card] [Errors, limits and retries](/concepts/errors) > > Error codes, rate limits and retry behavior. > [card] [WebSocket streams](/streams/overview) > > Subscribe to real-time trades, candles and token updates. > [card] [Rust SDK](/sdks/rust) > > Call every endpoint and stream with typed Rust. ## Need help? Ask in the Telegram developer group or email the team. [Support](/resources/support) lists the details to include. > [card] [Telegram developer group](https://t.me/metastreamsdevs) > > Ask the team and other developers. > [card] [contact@metastreams.io](mailto:contact@metastreams.io) > > Write to the team by email. # Build a discovery board Source: https://docs.metastreams.io/recipes/discovery-board Build a board that shows new, graduating and graduated launchpad tokens in three filtered, ranked columns. This recipe shows you how to build a discovery board that follows launchpad tokens through their lifecycle: newly launched, close to graduating, and graduated. `POST /v1/discovery` returns all three columns in one request. ## 1. Request the columns ```bash theme={null} curl "https://api.metastreams.io/v1/discovery" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "chains": ["solana"], "newPairs": { "limit": 30, "filters": { "withAtLeastOneSocial": true, "devHoldingPercent": { "max": 10 } } }, "graduating": { "limit": 30, "filters": { "holderCount": { "min": 100 }, "maxGraduationStaleMinutes": 30 } }, "graduated": { "sortBy": "volume24hUsd", "limit": 30, "filters": { "liquidityUsd": { "min": "10000" } } } }' ``` Each column takes its own `sortBy`, `order`, `limit` and `filters`. [Discovery boards](/reference/rest/discovery) documents every filter and sort field. Every column also applies [defaults](/reference/rest/discovery#column-defaults), such as a 24-hour activity cutoff and, on `graduating` and `graduated`, at least 10 holders. Your filters can tighten these defaults but cannot loosen them. ## 2. Render the response ```json theme={null} [ { "column": "newPairs", "deltas": [ { "chain": "solana", "address": "…", "rank": 1, "data": { } } ] }, { "column": "graduating", "deltas": [ ] }, { "column": "graduated", "deltas": [ ] } ] ``` The response is a list with one entry per column. The `deltas` array of each column contains the whole ranked list. Draw the items in `rank` order. `data` is the token object of [Tokens](/reference/rest/token-details) without `decimals` and `supply`, so each card can show the following fields. | Card element | Field | | - | - | | Name and symbol | `data.name`, `data.symbol` | | Age | now minus `data.createdAt` | | Market cap | `data.marketCap.usd` | | Launchpad progress | `data.bondingCurvePct` | | 5-minute volume and trades | `data.stats["5m"].volume.usd`, `data.stats["5m"].buyCount`, `data.stats["5m"].sellCount` | | Holders | `data.holders.count` | | Risk badges | `data.holders.devPct`, `data.holders.sniperPct`, `data.holders.bundlerPct`, `data.security.mintDisabled` | | Links | `data.metadata.twitter`, `data.metadata.website`, `data.metadata.telegram` | ## 3. Keep the board live Subscribe to [`spot.discovery`](/reference/streams/spot-discovery) with the same body as `filters`: ```json theme={null} { "action": "subscribe", "channel": "spot.discovery", "filters": { "chains": ["solana"], "newPairs": { "limit": 30 }, "graduating": { "limit": 30 }, "graduated": { "sortBy": "volume24hUsd", "limit": 30 } } } ``` The first update for each column contains the whole column, already ranked, so no REST request is needed. Apply later updates as [Message format](/reference/streams/spot-discovery#message-format) describes. The stream does not rank the columns again, so a token that stops trading stays on the board. [Subscribe again](/reference/streams/spot-discovery#updates) every few minutes, and after a reconnect. If you poll `POST /v1/discovery` instead, each request costs one credit and counts against your [rate limit](/concepts/errors#limits). When you redraw, match cards by `chain` + `address` so that a token that changes rank animates instead of flickering. A token that leaves a column's ranked list is no longer in that column, and a token that graduates appears in `graduated`. Occasionally, a card's windowed `stats` are zero in one response although the token has trades. When this happens, keep the card's previous values; the next update corrects them. ## Filter presets | Preset | Filters | | - | - | | Hide likely rugs | `devHoldingPercent: { max: 10 }`, `snipersSupplyPercent: { max: 20 }`, `top10HoldersPercent: { max: 40 }` | | Socials required | `withAtLeastOneSocial: true` | | Only active | `lastActivityMinutes: 5` | | Real liquidity | `liquidityUsd: { min: "5000" }` | | One launchpad | `protocols: ["pumpfun"]` | | No copycats | `excludeSymbolOrName: ["test", "scam"]` | These values are starting points, not recommendations. Tune them for your users. ## Multiple chains To cover more than one chain, send several slugs in `chains`, for example `["solana", "bsc", "robinhood"]`. Each column then ranks tokens from all listed chains as one set. Use `data.chain` to label each card with its chain. # Render a live chart Source: https://docs.metastreams.io/recipes/live-chart Load candle history, then keep the latest candle updated with the candles stream. This recipe shows you how to render a live price chart. A live chart needs candle history to draw and updates to the bar that is still open. The OHLCV endpoint provides the history, and the `spot.candles` stream provides the live updates. ## Series parameters | Parameter | Options | Recommendation | | - | - | - | | `timeframe` | `1s`, `5s`, `15s`, `30s`, `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `7d` | The bar size the user selected | | `metric` | `marketCap` (default) or `price` | `marketCap` for new launchpad tokens, where supply is fixed and small prices are hard to read; `price` for established tokens | | `denomination` | `usd` (default) or `native` | `usd`, unless your users trade in SOL, BNB, ETH or HYPE terms | Use the same three values for the history request and the subscription. Otherwise, the stream updates do not line up with the bars you drew. ## 1. Subscribe and load history Subscribe first and wait for the ack before you read history, so that no update is missed between the two. See [Initial snapshot](/streams/overview#initial-snapshot). ```javascript theme={null} import WebSocket from "ws"; const series = { chain: "solana", token: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", timeframe: "1m", metric: "price", denomination: "usd" }; const headers = { Authorization: `Bearer ${process.env.API_KEY}` }; const socket = new WebSocket("wss://api.metastreams.io/v1/stream", { headers }); const pending = []; let bars = null; let subscriptionId; let olderCursor = null; socket.on("error", (error) => console.error("stream error:", error.message)); const subscribed = new Promise((resolve, reject) => { socket.on("message", (raw) => { const frame = JSON.parse(raw.toString()); if (frame.type === "ack") { subscriptionId = frame.subscriptionId; resolve(); } if (frame.type === "error" && !subscriptionId) reject(new Error(`${frame.code}: ${frame.message}`)); if (frame.type !== "update") return; if (bars) upsert(bars, frame.data); else pending.push(frame.data); }); }); socket.on("open", () => { socket.send(JSON.stringify({ action: "subscribe", channel: "spot.candles", filters: { chains: [series.chain], tokens: [series.token], timeframes: [series.timeframe] }, metric: series.metric, denomination: series.denomination, })); }); await subscribed; const params = new URLSearchParams({ tokens: series.token, chains: series.chain, timeframe: series.timeframe, metric: series.metric, denomination: series.denomination, countBack: "500" }); const response = await fetch(`https://api.metastreams.io/v1/ohlcv?${params}`, { headers }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const [history] = await response.json(); const loaded = history?.candles ?? []; olderCursor = history?.hasMore ? history.nextCursor : null; for (const candle of pending) upsert(loaded, candle); bars = loaded; draw(bars); ``` ## 2. Update the open bar Each stream update contains the current state of one bucket, and the open bucket is sent again each time a new trade executes. Replace the bar with the same `time`, or append a new one. ```javascript theme={null} function upsert(bars, candle) { const last = bars[bars.length - 1]; if (last && last.time === candle.time) bars[bars.length - 1] = candle; else if (!last || candle.time > last.time) bars.push(candle); draw(bars); } ``` ## Missing candles Buckets with no trades are not sent, either in history or on the stream, so a quiet token has gaps between bars. Most charting libraries handle gaps. If yours needs a bar for every bucket, fill each gap with a flat bar at the previous `close` and zero volume. ## Load older history When the user scrolls left, request the next, older page with the series' cursor. Send the same parameters as the first request. ```javascript theme={null} async function loadOlder(bars) { if (!olderCursor) return; const params = new URLSearchParams({ tokens: series.token, chains: series.chain, timeframe: series.timeframe, metric: series.metric, denomination: series.denomination, countBack: "500", cursor: olderCursor }); const response = await fetch(`https://api.metastreams.io/v1/ohlcv?${params}`, { headers }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const [older] = await response.json(); bars.unshift(...(older?.candles ?? [])); olderCursor = older?.hasMore ? older.nextCursor : null; } ``` When `hasMore` is `false`, you have reached the start of the token's history. ## TradingView datafeeds The OHLCV endpoint follows the TradingView datafeed contract. In `getBars`, map `periodParams.countBack` to `countBack` and `periodParams.to` (seconds) to `to` in milliseconds. In `subscribeBars`, subscribe to `spot.candles` and pass each update to the `onTick` callback. ## Changing series To change the timeframe or metric, unsubscribe using the stored `subscriptionId`, subscribe with the new values, and reload history. To chart one pool instead of the token across all its pools, send `pool` on the history request and list the pool in the subscription's `pools` filter. # Build a token page Source: https://docs.metastreams.io/recipes/token-page Build a token page that shows price, stats, holders, security and live trades, and keep it current with streams. This recipe shows you how to build a token page that shows what a token is worth, who holds it, and what is trading now. You fill each section from one set of REST requests, then keep the page live with two stream subscriptions. | Section | Source | | - | - | | Header: name, symbol, price, market cap, liquidity | Token object | | Stats: change and volume over 5m to 24h | Token object `stats` | | Holders and risk: top 10, dev, snipers, bundlers, insiders | Token object `holders` | | Holders list: who holds it, ranked | [`GET /v1/holders`](/reference/rest/token-holders), kept live by [`spot.holders`](/reference/streams/spot-holders) | | Security: mint, freeze, LP burnt, taxes and fees | Token object `security` | | Launchpad status: launchpad progress, graduation | Token object `bondingCurvePct`, `graduatedAt` | | Recent trades | [`GET /v1/trades`](/reference/rest/trades) | | Live updates | `spot.tokens` and `spot.trades` | ## 1. Subscribe Open the stream and subscribe before you read the snapshot, so that no change is missed between the request and the subscription. Wait for both acks; each ack always arrives before the first update of its subscription. See [Initial snapshot](/streams/overview#initial-snapshot). ```javascript theme={null} import WebSocket from "ws"; const API = "https://api.metastreams.io/v1"; const headers = { Authorization: `Bearer ${process.env.API_KEY}` }; const chain = "solana"; const address = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"; const socket = new WebSocket("wss://api.metastreams.io/v1/stream", { headers }); const buffered: any[] = []; let ready = false; socket.on("error", (error) => console.error("stream error:", error.message)); const subscribed = new Promise((resolve) => { let acks = 0; socket.on("message", (raw) => { const frame = JSON.parse(raw.toString()); if (frame.type === "ack" && ++acks === 2) resolve(); if (frame.type !== "update") return; if (ready) apply(frame); else buffered.push(frame); }); }); socket.on("open", () => { socket.send(JSON.stringify({ action: "subscribe", channel: "spot.tokens", filters: { chains: [chain], tokens: [address] } })); socket.send(JSON.stringify({ action: "subscribe", channel: "spot.trades", filters: { chains: [chain], tokens: [address] } })); }); await subscribed; ``` ## 2. Read the snapshot Read the token object and the latest trades in parallel. ```javascript theme={null} async function getJson(url) { const response = await fetch(url, { headers }); if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); } const scope = new URLSearchParams({ tokens: address, chains: chain }); const [tokens, page] = await Promise.all([ getJson(`${API}/tokens?${scope}`), getJson(`${API}/trades?${scope}&limit=50`), ]); // A token the API does not know returns an empty list. Show a "token not found" state rather than retrying. const [token] = tokens; if (token === undefined) throw new Error("Token not found"); const state = { token, trades: page.trades as any[] }; for (const frame of buffered) apply(frame); ready = true; render(state); ``` ## 3. Apply updates ```javascript theme={null} function apply(frame) { if (frame.channel === "spot.tokens") { if (frame.data.updatedAt >= state.token.updatedAt) state.token = frame.data; } if (frame.channel === "spot.trades") { if (!state.trades.some((trade) => trade.id === frame.data.id)) { state.trades = [frame.data, ...state.trades].slice(0, 50); } } render(state); } ``` Streamed trades include `flags` and `platforms` when they are present, so you can show wallet badges on live trades immediately. ## 4. Render the sections ### Header ```javascript theme={null} const price = Number(state.token.price.usd); // display only; keep the string for maths const change24h = state.token.stats["24h"].priceChangePct; // "-3.4" means -3.4% ``` Show the `native` value next to the USD value for traders who think in SOL, BNB, ETH or HYPE. ### Holders and risk | Metric | Field | Warning condition | | - | - | - | | Top 10 share | `holders.top10Pct` | High concentration, for example above 50 | | Creator share | `holders.devPct` | Creator holds a large share | | Snipers | `holders.sniperPct`, `holders.sniperCount` | Snipers hold a large share | | Bundlers | `holders.bundlerPct`, `holders.bundlerCount` | Bundled buys hold a large share | | Insiders | `holders.insiderPct`, `holders.insiderCount` | Very early buyers hold a large share | | Fresh wallets | `holders.freshWalletPct` | New wallets hold a large share | You choose the thresholds. Every `Pct` field uses a 0–100 scale, and the [glossary](/resources/glossary#holder-groups) defines each holder group. ### Security | Check | Field | Safe value | | - | - | - | | Mint revoked | `security.mintDisabled` | `true` | | Transfers can be blocked (freeze authority, blacklist or pause) | `security.transferBlockable` | `false` | | Liquidity burnt or locked | `security.lpBurntPct` | Close to `100` | | Transfer fee | `security.transferFeeBps` | `0`. `null` means the contract has not been checked yet. | | Buy and sell tax of the token contract (EVM) | `security.buyTaxBps`, `security.sellTaxBps` | `0`. `null` means no rate is known. | | Total cost of a buy or a sell, with every fee layer | `security.totalBuyBps`, `security.totalSellBps` | Low. `null` means no rate is known. | A high `sellTaxBps` is the main sign of a honeypot. `…Bps` fields are in [basis points](/concepts/reading-responses#percentages). `security.rugPct` is `"0"` on every token, so do not show it. ### Holders list The token object contains the holder groups, not the holders. To list the holders: 1. Subscribe to [`spot.holders`](/reference/streams/spot-holders) with `{ "chain": "solana", "token": address, "period": "lifetime" }`, and buffer its updates. 2. Read [`GET /v1/holders`](/reference/rest/token-holders) with `tokens`, `chains`, the same `period`, and a `limit` of up to 150. To list more holders, page with the series' `nextCursor`. 3. Apply each update by `address`: replace the row, and remove it when its `balance` is `0`. A streamed row has no `rank`, so sort by `balance` in your client. ### Launchpad status * While `graduatedAt` is `null` and `bondingCurvePct` is set, show a progress bar based on `bondingCurvePct`. * Once `graduatedAt` is set, show the DEX the token graduated to from `graduatedToDex`. ### Links `metadata.website`, `metadata.twitter`, `metadata.telegram` and `metadata.discord` can each be `null`. Hide any link that is `null`. ## Next steps * Add a chart: [Render a live chart](/recipes/live-chart). * Handle reconnects: [WebSocket streams](/streams/overview#close-codes). # Discovery boards Source: https://docs.metastreams.io/reference/rest/discovery specs/openapi.json POST /v1/discovery Returns launchpad tokens ranked by launch stage, across one or more chains, in a single request. Returns ranked boards of launchpad tokens for the requested chains and columns. Each column is ranked and filtered independently and returns its top `limit` tokens. ## Columns Each column represents one stage of a token's launchpad lifecycle; see [launchpad terms](/resources/glossary#launchpad-terms). | Column | Holds | Default ranking | | - | - | - | | `newPairs` | Launchpad tokens below 40% of their bonding curve | `createdAt`, newest first | | `graduating` | Launchpad tokens at 40% or more of their bonding curve, not yet graduated | `bondingCurveActivity`, highest first | | `graduated` | Launchpad tokens that have graduated, or that have no bonding-curve reading | `graduatedAt`, newest first | ## Request body The body must name at least one chain and at least one column. A repeated chain slug is counted once, and every column ranks tokens from all the named chains as one set. Omit a column to skip it, or send `{}` to use its defaults. Inside a column, `sortBy` is the [field to rank on](#sort-fields), `order` is `desc` or `asc`, `limit` defaults to 20 and is clamped to 1–100 rather than rejected, and `filters` adds conditions on top of the [column defaults](#column-defaults). ## Column defaults Every column applies its own conditions in addition to request filters: * **Every column** excludes tokens with no update in the last 24 hours. * **`graduating` and `graduated`** keep only tokens with at least 10 holders, $1,000 of liquidity and a $5,000 market cap. * **`graduating`** also excludes tokens with no update in the last 60 minutes, unless they are at 99.5% or more of their bonding curve. Request filters can tighten these conditions but not loosen them. For example, a `holderCount` minimum below 10 on `graduated` is raised to 10, and a `maxGraduationStaleMinutes` above 60 on `graduating` is lowered to 60. ## Sort fields | `sortBy` | Ranks on | | - | - | | `createdAt` | Token creation time | | `volume24hUsd` | USD volume over the last 24 hours | | `marketCapUsd` | USD market cap | | `liquidityUsd` | USD liquidity | | `holdersCount` | Current number of holders | | `tradeCount24h` | Buys plus sells over the last 24 hours | | `bondingCurvePct` | Bonding-curve completion; on `graduating`, ranks on `bondingCurveActivity` instead | | `bondingCurveActivity` | Bonding-curve completion weighted by the last hour's volume: `bondingCurvePct` multiplied by `ln(1 + stats["1h"].volume.usd)` | | `graduatedAt` | Graduation time | Tokens with equal values are returned in a stable order. ## Filters A token must match every filter in the request, as well as the [column defaults](#column-defaults). The schema below lists each filter, and the following rules apply to all of them. > [!WARNING] > > An unknown filter name returns `400 VALIDATION_ERROR`. The sort field is `holdersCount`, but the filter is `holderCount`. * **Ranges** are `{ "min": …, "max": … }`. Both bounds are inclusive, and either can be left out. A `min` above `max` returns `400 VALIDATION_ERROR`. Each bound takes the type the schema gives its field: decimal strings for USD and native values and for `bundlerSupplyPercent` and `insiderSupplyPercent`, numbers for counts and the other percentages. * **Lists** are unions: a token passes when it matches any entry. `symbolOrName` and `excludeSymbolOrName` match the symbol or the name, ignoring case, and a word that looks like an address matches the token's address exactly instead. * **`withAtLeastOneSocial`** includes only tokens with at least one social link; `false` applies no condition. * **`dexPaid`** includes tokens with a paid DexScreener profile when `true`, and tokens without one when `false`. * **`excludeAnnotations`** excludes tokens with any of the listed annotations, each written as `{ "kind": "mayhem_mode" }`. An unknown kind returns `400 VALIDATION_ERROR`. * **Time limits** are `lastActivityMinutes`, which includes tokens updated within that many minutes, and `maxGraduationStaleMinutes`, which excludes tokens with no update within that many minutes unless they are at 99.5% or more of their bonding curve. `maxGraduationStaleMinutes` applies to any column, and `graduating` caps it at 60. An update is any change to a token's record, such as a trade, not only bonding-curve progress. > [!NOTE] > > `twitterReuseCount` is accepted but not yet applied, so every token passes it. ## Response The response is a list with one entry per requested column, in the order `newPairs`, `graduating`, `graduated`. Each entry's `deltas` lists the column's top `limit` tokens, with one item per rank starting from 1. Each item's `data` is the token object that [Tokens](/reference/rest/token-details) returns, without `decimals` and `supply`. Fields that the boards do not use, such as `pools`, `ath`, `security.mintDisabled` and most window stats, are sent with their zero, `false`, `null` or empty value. Read [Tokens](/reference/rest/token-details) for the full token. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chains` is not supported | | `VALIDATION_ERROR` | No chain or no column requested, a range whose `min` is above its `max`, or a malformed body | ```bash cURL theme={null} curl -X POST "https://api.metastreams.io/v1/discovery" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "chains": ["solana", "bsc"], "graduating": { "sortBy": "volume24hUsd", "limit": 20, "filters": { "liquidityUsd": { "min": "20000" }, "holderCount": { "min": 500 } } } }' ``` ```typescript Node.js theme={null} const response = await fetch("https://api.metastreams.io/v1/discovery", { method: "POST", headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ chains: ["solana", "bsc"], graduating: { sortBy: "volume24hUsd", limit: 20 }, }), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const columns = await response.json(); ``` ```rust Rust theme={null} use serde_json::{Value, json}; let columns: Vec = reqwest::Client::new() .post("https://api.metastreams.io/v1/discovery") .bearer_auth(std::env::var("API_KEY")?) .json(&json!({ "chains": ["solana", "bsc"], "graduating": { "sortBy": "volume24hUsd", "limit": 20 }, })) .send() .await? .error_for_status()? .json() .await?; ``` ```json Shortened theme={null} [ { "column": "graduating", "deltas": [ { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "rank": 1, "data": { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "name": "Example", "symbol": "EXAMPLE", "logo": { "small": "https://cdn.example.com/TokenMint1111111111111111111111111111111pump_16x16.webp", "medium": "https://cdn.example.com/TokenMint1111111111111111111111111111111pump_60x60.webp", "large": "https://cdn.example.com/TokenMint1111111111111111111111111111111pump.webp" }, "price": { "native": "0.00000042", "usd": "0.000075" }, "marketCap": { "native": "420.5", "usd": "75000" }, "liquidity": { "native": "128.4", "usd": "22900" }, "bondingCurvePct": "91.4", "updatedAt": 1789632012345 } } ] } ] ``` # Native prices Source: https://docs.metastreams.io/reference/rest/native-prices specs/openapi.json GET /v1/native-prices Returns the latest USD price of each chain's gas asset. Returns the latest USD price of each chain's gas asset: SOL on `solana`, BNB on `bsc`, ETH on `robinhood` and HYPE on `elysium`. `chains` limits results to a comma-separated list of [chain slugs](/concepts/chains); omit it to include every chain. ## Response The response is a list with one row per chain with a known price, in the order of the [chain table](/concepts/chains#supported-chains). A chain with no price yet has no row, and a missing row does not mean a price of zero. `price` is the price of one whole unit of `asset`, so `price.native` is always `"1"`. `observedAt` is when the price source reported the rate. New `asset` values can be added, so keep unrecognized values rather than discarding them. The [`chain.nativePrices`](/reference/streams/native-prices) stream sends each new price. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A `chains` value is not a supported slug | | `VALIDATION_ERROR` | An unknown parameter | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/native-prices?chains=solana,bsc" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/native-prices"); url.searchParams.set("chains", "solana,bsc"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const nativePrices = await response.json(); ``` ```rust Rust theme={null} use serde_json::Value; let native_prices: Vec = reqwest::Client::new() .get("https://api.metastreams.io/v1/native-prices") .query(&[("chains", "solana,bsc")]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; ``` ```json Native prices theme={null} [ { "chain": "solana", "asset": "SOL", "price": { "native": "1", "usd": "178.42" }, "observedAt": 1789632015120 }, { "chain": "bsc", "asset": "BNB", "price": { "native": "1", "usd": "612.35" }, "observedAt": 1789632014870 } ] ``` # Portfolio Source: https://docs.metastreams.io/reference/rest/portfolio specs/openapi.json GET /v1/portfolio Returns the summed spot holdings of up to 100 wallets, per chain, with each wallet's share and optional PnL stats. Returns the spot holdings of the wallets in `wallets`, a comma-separated list of 1 to 100 addresses, as one value summed across them. `chains` limits the read to a comma-separated list of [chain slugs](/concepts/chains); omit it to read every chain. An EVM address counts on every EVM chain in scope, and a Solana address on Solana. ## Value A value is the sum of three parts: * The balance of the chain's gas asset, at its latest price. * The stablecoin balances, at $1 each. An open position in a stablecoin with no balance row also counts at $1. * The open [positions](/reference/rest/positions), at each token's latest price. A position adds nothing to the value when: * Its token has no price. * It is worth more than its token's market cap. * Its token has no known market cap and under \$1,000 of liquidity. `hideLowLiquidity=true` drops every open position in a token with under \$1,000 of liquidity, or with no known liquidity, from the values and the stats. A stablecoin is never dropped. The default is `false`. ## Response * `totalValueUsd` is the value of every product. It equals `spot.valueUsd`, because spot is the only product. * `spot` splits the value into balances and positions, with one item in `spot.chains` per chain in scope. In the portfolio total, a chain with no holdings has zero values. A wallet's share lists only the chains where it has holdings. A gas balance without a known price has a `null` USD value, and no total counts it. * `wallets` lists each requested wallet's share, in the order of the request. The shares add up to the totals. `addresses` holds the wallet under its format, `evm` or `solana`, and the other is `null`. * `asOf` is the time the response was calculated. ## Stats `include=stats` adds `stats` to the portfolio and to each wallet. `stats` reports performance over four timeframes: `oneDay`, `sevenDays` and `thirtyDays` cover positions whose first purchase falls in that window, and `max` covers every position. Each timeframe contains the realized and unrealized PnL per chain, the number of open positions, the trade counts, and `buckets`. `buckets` counts positions by realized return: `rekt` loses more than 50%, `loss` loses up to 50%, `win` returns 1x to 2x, `pump` from 2x to 5x, and `moonshot` at 5x or better. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chains` is not supported | | `VALIDATION_ERROR` | No wallet or more than 100, a malformed address, an unknown `include` value, or an unknown parameter | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/portfolio?wallets=7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5&chains=solana" \ -H "Authorization: Bearer $API_KEY" ``` ```bash With stats theme={null} curl "https://api.metastreams.io/v1/portfolio?wallets=7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5&include=stats" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/portfolio"); url.searchParams.set("wallets", "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"); url.searchParams.set("chains", "solana"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const portfolio = await response.json(); ``` ```rust Rust theme={null} use serde_json::Value; let portfolio: Value = reqwest::Client::new() .get("https://api.metastreams.io/v1/portfolio") .query(&[("wallets", "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"), ("chains", "solana")]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; ``` ```json Portfolio theme={null} { "asOf": 1789632015120, "totalValueUsd": "11962.40", "spot": { "valueUsd": "11962.40", "balancesValueUsd": "7518.40", "positionsValueUsd": "4444.00", "chains": [ { "chain": "solana", "nativeBalance": { "native": "41.208113", "usd": "7418.40" }, "stableBalanceUsd": "100.00", "positionsValue": { "native": "24.688888", "usd": "4444.00" }, "valueUsd": "11962.40" } ] }, "wallets": [ { "addresses": { "evm": null, "solana": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5" }, "spot": { "valueUsd": "11962.40", "balancesValueUsd": "7518.40", "positionsValueUsd": "4444.00", "chains": [ { "chain": "solana", "nativeBalance": { "native": "41.208113", "usd": "7418.40" }, "stableBalanceUsd": "100.00", "positionsValue": { "native": "24.688888", "usd": "4444.00" }, "valueUsd": "11962.40" } ] } } ] } ``` # Positions Source: https://docs.metastreams.io/reference/rest/positions specs/openapi.json GET /v1/positions Returns the spot positions of one or more wallets, with cost basis and PnL. Returns the spot positions of the requested wallets, with one row per chain, wallet and token. `wallets` takes 1 to 100 comma-separated addresses, and `chains` limits results to specific chains. ## Filters * `lifecycle` selects `open` positions (the default) or `closed` positions. * `hideLowLiquidity` excludes open positions in tokens with under \$1,000 of liquidity. The default is `true`; send `false` to include every position. * `hideDust` excludes open positions worth under \$1. The default is `false`. * `hideTransfers` excludes positions not opened by a buy, such as airdrops. The default is `false`. * `chain` and `token` together limit results to one token's positions and must be sent together. * `q` matches tokens whose symbol or name contains the value, case-insensitively. ## Sort `sort` is `field:asc` or `field:desc`, where `field` is `value`, `pnl`, `pnlPct`, `openedAt` or `closedAt`. The default is `value:desc` for open positions and `closedAt:desc` for closed positions. ## Response A page contains `positions`, `nextCursor`, `hasMore`, `asOf` and `counts`. `counts.spot` is the number of open and closed positions. It ignores `lifecycle`, the `hide…` parameters, `q`, `chain` and `token`, so it stays the same across all pages of one request. Holdings are valued at the token's latest price. `value`, `unrealizedPnl`, `totalPnl` and `pnlPct` are `null` for a token with no market record, and `pnlPct` is also `null` for a position with no invested cost. `version` orders the changes to a position, and the highest version is the current one. The [`spot.positions`](/reference/streams/spot-positions) stream follows the same rule. ## Pagination Send `nextCursor` back exactly as received. A cursor encodes the filters and sort of the request that produced it, so a cursor sent with different filters returns `400 VALIDATION_ERROR`. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A `chains` or `chain` value is not a supported slug | | `VALIDATION_ERROR` | No wallet or more than 100; a malformed wallet or token address; `chain` without `token`, or the reverse; an unknown sort; a cursor from other filters; or an unknown parameter | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/positions?wallets=7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5&chains=solana&sort=pnl:desc" \ -H "Authorization: Bearer $API_KEY" ``` ```bash Closed theme={null} curl "https://api.metastreams.io/v1/positions?wallets=7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5&lifecycle=closed" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/positions"); url.searchParams.set("wallets", "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"); url.searchParams.set("chains", "solana"); const headers = { Authorization: `Bearer ${process.env.API_KEY}` }; let cursor = null; do { if (cursor) url.searchParams.set("cursor", cursor); const response = await fetch(url, { headers }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const page = await response.json(); for (const position of page.positions) console.log(position.token.symbol, position.value?.usd); cursor = page.hasMore ? page.nextCursor : null; } while (cursor); ``` ```rust Rust theme={null} use serde_json::Value; let key = std::env::var("API_KEY")?; let client = reqwest::Client::new(); let mut cursor: Option = None; loop { let mut request = client .get("https://api.metastreams.io/v1/positions") .query(&[("wallets", "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"), ("chains", "solana")]) .bearer_auth(&key); if let Some(cursor) = &cursor { request = request.query(&[("cursor", cursor)]); } let page: Value = request.send().await?.error_for_status()?.json().await?; for position in page["positions"].as_array().into_iter().flatten() { println!("{} {}", position["token"]["symbol"].as_str().unwrap_or_default(), position["value"]["usd"].as_str().unwrap_or("null")); } if page["hasMore"] != true { break; } cursor = page["nextCursor"].as_str().map(String::from); } ``` # Search Source: https://docs.metastreams.io/reference/rest/search specs/openapi.json GET /v1/search Returns the tokens and wallets that match a search text: a symbol, a name, an address or a wallet name. Returns the tokens and wallets that match a search text. Each result includes a `kind`: `spotToken` or `spotWallet`. ## Query `q` can be a token symbol or name, a token, pool or wallet address, or a wallet name. Leading and trailing spaces are removed, and an empty `q` returns `400 VALIDATION_ERROR`. | Search text | Results | | - | - | | A symbol or name, such as `bonk` | Tokens ranked by relevance. A wallet whose name equals the text is also returned, up to 3 of them, after the first token. | | A name that starts with `@`, such as `@ansem` | Wallets whose name starts with the text after the `@`. No tokens. | | A token or pool address | That token, on each chain where it is found | | A wallet address | That wallet on each chain where it has a position | A wallet name is a handle, a display name or a label from one of the wallet's `identities`. A text search does not return tokens with less than $1,000 of liquidity or more than $100 billion of market cap. An address search returns the token at any size. ## Filters * `kind` limits results to `spotToken` or `spotWallet`. With `kind=spotWallet`, a text returns wallets whose name starts with it, as with `@`. With `kind=spotToken`, a text that starts with `@` searches tokens. * `chain` takes one [chain slug](/concepts/chains), and `chains` a comma-separated list. When both are sent, the results cover every chain listed in either. Omit both to search every chain. * `graduated=true` returns only tokens that have left their launchpad, and `graduated=false` only tokens that have not, including tokens that never launched on one. It requires `kind=spotToken`. * `sortBy` orders the results. The default is `relevance`. `volume24h`, `marketCap`, `liquidity` and `createdAt` order every matching token by that value and require `kind=spotToken`. `sortDirection` is `desc` by default, or `asc`. ## Response The response is a list, not a page, and has no cursor. `limit` sets the number of results. The default is 10, and out-of-range values are clamped to 1–20. The list can be shorter than `limit`. A wallet address can return more than `limit` results, one per chain. * A token result is the full [token object](/reference/rest/token-details) with `"kind": "spotToken"`. * A wallet result contains `kind`, `chain`, `address` and `identities`, in the same shape as a [holder's](/reference/rest/token-holders#response) `identities`. `identities` is empty when no source names the wallet. Wallets returned beside tokens are best effort. When their lookup is slow, the response is sent without them, or with wallets whose `identities` is empty. An unknown text returns an empty list, not a `404`. Each request costs one [credit](/concepts/errors#credits). ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chain` or `chains` is not supported | | `VALIDATION_ERROR` | A missing or empty `q`; `graduated`, or a `sortBy` other than `relevance`, without `kind=spotToken`; an unknown `kind`, `sortBy` or `sortDirection`; or an unknown parameter | | `SERVICE_UNAVAILABLE` | The server is handling too many searches. Retry after a short delay. | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/search?q=bonk&chains=solana&limit=5" \ -H "Authorization: Bearer $API_KEY" ``` ```bash Wallet names theme={null} curl "https://api.metastreams.io/v1/search?q=@ansem&kind=spotWallet" \ -H "Authorization: Bearer $API_KEY" ``` ```bash By volume theme={null} curl "https://api.metastreams.io/v1/search?q=pepe&kind=spotToken&sortBy=volume24h" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/search"); url.searchParams.set("q", "bonk"); url.searchParams.set("chains", "solana"); url.searchParams.set("limit", "5"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const results = await response.json(); const tokens = results.filter((result) => result.kind === "spotToken"); ``` ```rust Rust theme={null} use serde_json::Value; let results: Vec = reqwest::Client::new() .get("https://api.metastreams.io/v1/search") .query(&[("q", "bonk"), ("chains", "solana"), ("limit", "5")]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; let tokens: Vec<&Value> = results.iter().filter(|result| result["kind"] == "spotToken").collect(); ``` ```json Results (shortened) theme={null} [ { "kind": "spotToken", "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "name": "Bonk", "symbol": "Bonk", "decimals": 5, "price": { "native": "0.000000121", "usd": "0.0000216" }, "marketCap": { "native": "10741962.1", "usd": "1917440000" }, "liquidity": { "native": "51820.4", "usd": "9250000" }, "updatedAt": 1789632012345 }, { "kind": "spotWallet", "chain": "solana", "address": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "identities": [ { "source": "gmgn", "displayName": "Bonk Whale", "handle": "bonkwhale", "twitter": "bonkwhale", "telegram": null, "farcaster": null, "avatar": null } ] } ] ``` ```json No match theme={null} [] ``` # Session tokens Source: https://docs.metastreams.io/reference/rest/session-tokens specs/openapi.json POST /v1/session-tokens Creates a short-lived credential that a browser sends instead of an API key. Creates a session token, a short-lived credential that a browser sends instead of an API key. This endpoint requires an API key, and each successful call costs one credit. [Session tokens](/get-started/authentication#session-tokens) describes how a backend and a browser use it. ## Request body * `origins` lists 1 to 10 origins allowed to use the token, each in the format of the browser's `Origin` header, such as `https://app.example.com`. * `subject` is an optional label for the user, such as a user ID, of 1 to 128 characters without control characters. * `ttlSeconds` is the token's lifetime, from 60 to 3,600 seconds. The default is 900. ## Response `token` is an opaque string of a few hundred characters that starts with `metasession_`. Treat it as a secret, and do not parse it. `expiresAt` is the expiry time in Unix milliseconds. Tokens cannot be refreshed, so create a new token before `expiresAt`. ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | No origin or more than 10, a value that is not a valid origin, a `subject` or `ttlSeconds` out of range, or an unknown field | | `FORBIDDEN` | The request used a session token instead of an API key | | `ORIGIN_NOT_ALLOWED` | The request used a session token from an origin that the token does not allow | ```bash cURL theme={null} curl -X POST "https://api.metastreams.io/v1/session-tokens" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"origins": ["https://app.example.com"], "subject": "user-42", "ttlSeconds": 900}' ``` ```typescript Node.js theme={null} const response = await fetch("https://api.metastreams.io/v1/session-tokens", { method: "POST", headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ origins: ["https://app.example.com"], subject: "user-42", ttlSeconds: 900 }), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const { token, expiresAt } = await response.json(); ``` ```rust Rust theme={null} use serde_json::{Value, json}; let response: Value = reqwest::Client::new() .post("https://api.metastreams.io/v1/session-tokens") .bearer_auth(std::env::var("API_KEY")?) .json(&json!({ "origins": ["https://app.example.com"], "subject": "user-42", "ttlSeconds": 900 })) .send() .await? .error_for_status()? .json() .await?; let token = &response["token"]; ``` ```json Created theme={null} { "token": "metasession_AbC...", "expiresAt": 1789632915120 } ``` # Stream connect Source: https://docs.metastreams.io/reference/rest/stream-connect specs/openapi.json POST /v1/stream/connect Returns a direct WebSocket URL and a short-lived token that opens connections there. Returns a direct WebSocket URL and a connect token. A connection opened at that URL does not pass through `api.metastreams.io`. Its frames, limits and billing are the same as on [`/v1/stream`](/streams/overview). The request requires an API key and costs no credit. [Routes](/streams/overview#routes) describes when to use it. ## Response * `url` is the WebSocket URL to connect to, such as `wss://:/v1/stream`. Use it exactly as returned. * `token` is an opaque string that starts with `metaconnect_`. Send it as `Authorization: Bearer ` in the WebSocket handshake. Treat it as a secret. * `expiresAt` is the token's expiry time in Unix milliseconds, 30 seconds after the response. The token opens any number of connections until then, within the key's limit of 20. The token is not accepted on any REST endpoint or on `/v1/stream` at `api.metastreams.io`. ## Errors | Code | When | | - | - | | `FORBIDDEN` | The request used a session token instead of an API key, or the organization's plan does not include streams | | `ORIGIN_NOT_ALLOWED` | The request used a session token from an origin that the token does not allow | | `NOT_FOUND` | No direct URL is available. Connect to `wss://api.metastreams.io/v1/stream` instead. | ```bash cURL theme={null} curl -X POST "https://api.metastreams.io/v1/stream/connect" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} import WebSocket from "ws"; const response = await fetch("https://api.metastreams.io/v1/stream/connect", { method: "POST", headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const { url, token } = await response.json(); const socket = new WebSocket(url, { headers: { Authorization: `Bearer ${token}` } }); socket.on("error", (error) => console.error("stream error:", error.message)); ``` ```rust Rust theme={null} use serde_json::Value; use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; let answer: Value = reqwest::Client::new() .post("https://api.metastreams.io/v1/stream/connect") .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; let mut request = answer["url"].as_str().ok_or("no url")?.into_client_request()?; let token = answer["token"].as_str().ok_or("no token")?; request.headers_mut().insert("Authorization", format!("Bearer {token}").parse()?); let (socket, _) = connect_async(request).await?; ``` ```json Created theme={null} { "url": "wss://:/v1/stream", "token": "metaconnect_AbC...", "expiresAt": 1789632915120 } ``` # Tokens Source: https://docs.metastreams.io/reference/rest/token-details specs/openapi.json GET /v1/tokens Returns the price, market cap, liquidity, trailing stats, holders, security and launch data of up to 100 tokens. Returns the current state of each token in `tokens`, a comma-separated list of 1 to 100 addresses. `chains` limits the read to a comma-separated list of [chain slugs](/concepts/chains). Omit it to read every chain. `updatedAt` is the time a token's state was last refreshed. ## Response The response is a list with one token object per chain that holds each requested token, in the order of the request. An address reads on every chain in scope of its format, so an EVM address can return one object for each EVM chain that holds it. Each object carries its own `chain` and `address`. A token that no chain in scope holds has no object, so the response can be an empty list. It is not a `404`. ## Response fields * [Holder groups](/resources/glossary#holder-groups) defines every field of `holders`, and [wallet classifications](/resources/glossary#wallet-classifications) defines the flags those groups count. * `security.rugPct` and `metadata.twitterReuseCount` are `"0"` and `0` on every token and should not be relied on yet. * `platforms` and `annotations` are omitted when empty. Currently, the only listing in `platforms` is a paid DexScreener profile. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chains` is not supported | | `VALIDATION_ERROR` | No token or more than 100, a malformed address, or an unknown parameter | Every endpoint can also return the [universal errors](/concepts/errors). ```bash cURL theme={null} curl "https://api.metastreams.io/v1/tokens?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/tokens"); url.searchParams.set("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"); url.searchParams.set("chains", "solana"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const tokens = await response.json(); ``` ```rust Rust theme={null} use serde_json::Value; let tokens: Vec = reqwest::Client::new() .get("https://api.metastreams.io/v1/tokens") .query(&[("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"), ("chains", "solana")]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; ``` # Holders Source: https://docs.metastreams.io/reference/rest/token-holders specs/openapi.json GET /v1/holders Returns the current holders of up to 10 tokens, largest balance first, with each wallet's trading figures on the token. Returns the current holders of each token in `tokens`, a comma-separated list of 1 to 10 addresses. Each series ranks holders by balance, largest first. `chains` limits the read to a comma-separated list of [chain slugs](/concepts/chains). Omit it to read every chain. Pools and lockers are ranked alongside other wallets and carry the `liquidity_pool` or `locker` flag. The [`spot.holders`](/reference/streams/spot-holders) stream delivers the same rows. ## Filters * `flags` takes a comma-separated list of [wallet classifications](/resources/glossary#wallet-classifications), such as `bundler,insider`. A holder is included when it has at least one of them. * `period` sets the span of the trading figures. `lifetime`, the default, covers every round trip the wallet made on the token. `cycle` covers the current round trip, from the time the wallet last had a zero balance. * `limit` sets the number of rows returned for each token. The default is 30, and out-of-range values are clamped to 1–150 rather than rejected. ## Response The response is a list with one series per chain that holds each requested token, in the order of the request. Each series contains `chain`, `address`, `holders`, `holderCount`, `top10`, `nextCursor` and `hasMore`. Each token costs one [credit](/concepts/errors#credits). ## Pagination Each series pages on its own, largest balance first. `hasMore` is `true` while the token has more holders, and `nextCursor` reads the next page. Send it as `cursor` with the same options, with that series' token alone in `tokens` and, for an EVM token, its chain in `chains`. A holder whose balance changes between two pages can move across the page boundary. * `holders` lists the rows. `rank` is 1-based and, when `flags` is set, ranks within the matching wallets. * `holderCount` is the token's total number of holders and is not affected by `limit` or `flags`. It counts trading wallets only, so it can be lower than a list that includes pools. * `top10` contains `avgEntryPrice` and `avgExitPrice`, weighted by balance, across the first 10 rows returned. Each is `null` when no row has a value. `top10` is `null` on every page after the first. Volumes, token totals, trade counts, entry and exit prices and `realizedPnl` cover the selected `period`. `balance`, `supplyPct`, `nativeBalance` and `funding` reflect the wallet's current state. With `period=cycle`, `avgEntryPrice` is the cost basis of the open position. `flags`, `platforms` and `identities` are omitted from a row when empty. Rows do not include a value or unrealized PnL. Calculate them from the token's `price`, available from [Tokens](/reference/rest/token-details) or [`spot.tokens`](/reference/streams/spot-tokens): * The value is `balance` times the token's price. * The unrealized PnL is the value minus `balance` times `avgEntryPrice`. A token that no chain in scope holds has no series, so the response can be an empty list. It is not a `404`. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chains` is not supported | | `VALIDATION_ERROR` | No token or more than 10, a malformed address, an unknown flag or period, a cursor sent with other tokens, chains or options than its own series, or an unknown parameter | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/holders?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana&limit=50" \ -H "Authorization: Bearer $API_KEY" ``` ```bash Filtered theme={null} curl "https://api.metastreams.io/v1/holders?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana&flags=bundler,insider" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/holders"); url.searchParams.set("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"); url.searchParams.set("chains", "solana"); url.searchParams.set("limit", "50"); url.searchParams.set("period", "cycle"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const [{ holders, holderCount, top10 }] = await response.json(); ``` ```rust Rust theme={null} use serde_json::Value; let series: Vec = reqwest::Client::new() .get("https://api.metastreams.io/v1/holders") .query(&[ ("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"), ("chains", "solana"), ("limit", "50"), ("period", "cycle"), ]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; ``` ```json List theme={null} [ { "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "holders": [ { "rank": 7, "address": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "nativeBalance": "412.7", "balance": "20500000000", "supplyPct": "0.0231", "buyVolume": { "native": "2500", "usd": "450000" }, "tokensBought": "25000000000", "buyCount": 14, "sellVolume": { "native": "598.5", "usd": "108000" }, "tokensSold": "4500000000", "sellCount": 3, "firstPurchaseAt": 1781250000000, "avgEntryPrice": { "native": "0.0000001", "usd": "0.000018" }, "avgExitPrice": { "native": "0.000000133", "usd": "0.000024" }, "avgEntryMarketCap": { "native": "8880000", "usd": "1598400000" }, "avgExitMarketCap": { "native": "11810400", "usd": "2131200000" }, "realizedPnl": { "native": "148.5", "usd": "27000" }, "remainingPct": "82", "funding": { "status": "resolved", "address": "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9", "amount": "500", "asset": null, "symbol": "SOL", "sourceKind": "cex", "sourceLabel": "Binance", "timestamp": 1781200000000, "tx": "3nVq8Fz1kT7pR2mWcX9sLdHfA4jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h" }, "flags": ["whale"], "platforms": [{ "platform": "photon" }], "identities": [ { "source": "gmgn", "displayName": "Bonk Whale", "handle": "bonkwhale", "twitter": "bonkwhale", "telegram": null, "farcaster": null, "avatar": null } ] } ], "holderCount": 982114, "top10": { "avgEntryPrice": { "native": "0.000000094", "usd": "0.0000169" }, "avgExitPrice": { "native": "0.000000128", "usd": "0.0000231" } }, "nextCursor": "eyJyIjozMH0", "hasMore": true } ] ``` ```json Unknown token theme={null} [] ``` # OHLCV candles Source: https://docs.metastreams.io/reference/rest/token-ohlcv specs/openapi.json GET /v1/ohlcv Returns OHLCV candles for up to 10 tokens at any timeframe, by price or by market cap. Returns one OHLCV candle series for each token in `tokens`, a comma-separated list of 1 to 10 addresses. `chains` limits the read to a comma-separated list of [chain slugs](/concepts/chains). Omit it to read every chain. Each series is oldest first, with one candle per bucket that traded. Buckets with no trades are omitted. Each token costs one [credit](/concepts/errors#credits). The defaults are `timeframe=1m`, `metric=marketCap` and `denomination=usd`. ## Pool candles By default, a token's candles include trades in all of its pools. To read one pool's candles, send its address in `pool` and name that pool's token alone in `tokens`. The pool must use the same address format as the token. ## Response The response is a list with one series per chain where each requested token has candles in the window, in the order of the request. Each series contains `chain`, `address`, `candles`, `nextCursor` and `hasMore`. A token with no candles in the window has no series, so the response can be an empty list. It is not a `404`. ## Time range `countBack` sets the number of bars and overrides `from`, while `to` and `timeframe` still apply. A request with neither `countBack` nor `from` returns the most recent 500 buckets, and a window with more than 5000 candles returns the newest 5000. This matches the behavior TradingView's charting library expects. ## Pagination `from` is inclusive and `to` is exclusive, both in milliseconds. Omit `to` to read up to the current time. Each series pages back on its own. `hasMore` is `true` while the window has older candles for that series, and `nextCursor` reads the next, older page. Send it as `cursor` with the same options, with that series' token alone in `tokens` and, for an EVM token, its chain in `chains`. A page can hold fewer candles than requested while `hasMore` is `true`, so page until it is `false`. ```bash theme={null} curl "https://api.metastreams.io/v1/ohlcv?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana&timeframe=1m&countBack=5000&cursor=$NEXT_CURSOR" \ -H "Authorization: Bearer $API_KEY" ``` To read a window that ends earlier without a cursor, set `to` to the `time` of the oldest candle received. Because `to` is exclusive, that candle is not returned again. ## Response fields Candle values are JSON numbers rather than the decimal strings used in token and trade objects, because charting libraries expect numbers. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chains` is not supported | | `VALIDATION_ERROR` | No token or more than 10, a malformed address, an unknown `timeframe`, `from` greater than `to`, a `countBack` outside 1–5000, a `pool` beside more than one token, of another address format than the token or at the zero address, a cursor sent with other tokens, chains or options than its own series, or an unknown parameter | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/ohlcv?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana&timeframe=1h&metric=price&countBack=24" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/ohlcv"); url.searchParams.set("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"); url.searchParams.set("chains", "solana"); url.searchParams.set("timeframe", "1h"); url.searchParams.set("metric", "price"); url.searchParams.set("countBack", "24"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const [series] = await response.json(); ``` ```rust Rust theme={null} use serde_json::Value; let series: Vec = reqwest::Client::new() .get("https://api.metastreams.io/v1/ohlcv") .query(&[ ("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"), ("chains", "solana"), ("timeframe", "1h"), ("metric", "price"), ("countBack", "24"), ]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; ``` ```json Series theme={null} [ { "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "candles": [ { "time": 1789545600000, "open": 0.0000221, "high": 0.0000224, "low": 0.0000219, "close": 0.0000222, "volume": 2104410.5 }, { "time": 1789549200000, "open": 0.0000222, "high": 0.0000223, "low": 0.0000215, "close": 0.0000216, "volume": 2981337.2 } ], "nextCursor": "eyJ0IjoxNzg5NTQ1NjAwMDAwfQ", "hasMore": true } ] ``` ```json Inverted window theme={null} { "error": { "code": "VALIDATION_ERROR", "message": "One or more parameters are invalid.", "details": [{ "field": "from", "message": "Must not be greater than `to`." }] } } ``` # Trade history Source: https://docs.metastreams.io/reference/rest/trade-search specs/openapi.json POST /v1/trades Returns past trades that match a spot.trades filter, newest first or ranked by a value. Returns past trades that match a [`spot.trades`](/reference/streams/spot-trades#filters) filter, newest first or ranked by a value. The same filter object reads the history and streams new trades. ## Filter `filter` takes every key of a `spot.trades` subscription filter, such as `chains`, `tokens`, `wallets`, `pools`, `side`, `flags`, `platforms`, `volumeUsd`, `token` and `exclude`. See [`spot.trades`](/reference/streams/spot-trades#filters) for each key and [Filtering streams](/streams/filters) for the rules they share. Omit `filter` to match every trade. A filter can list at most 10 `tokens`, 10 `pools` and 100 `wallets`, and each list must contain at least one value. The filter keeps the same trades as the subscription, with two differences: * `token` tests the token's state when the request is read, not when the trade was made. * A trade that was corrected after it was first recorded matches when any recorded version matches. A ranking can return such a trade once per version. ## Order * **Newest first.** With no `sortBy`, or `sortBy` set to `timestamp`, trades are returned newest first. `order` must stay `desc`. * **Ranked.** Any other `sortBy` ranks the trades in the window by that value, such as `volumeUsd` or `marketCapUsd`. `order` is `desc` by default, or `asc`. A trade without a value for the key is not ranked. ## Time window `fromAt` is inclusive and `toAt` is exclusive, both in Unix milliseconds. * A newest-first read that lists `tokens` pages back through the whole history of those tokens. A read that lists no token returns the last 30 days. * A ranked read requires `fromAt`. The listed tokens share a window of 30 days, with at least one day each, so one token ranks up to 30 days and ten tokens rank up to 3 days. A read that lists no token ranks at most one day, inside the last 30 days. * Without `toAt`, a ranking ends at `fromAt` plus the widest allowed window, or at the current time if that is earlier. Every page of the ranking keeps that end. * A ranking that pages past the 30-day limit returns `400 VALIDATION_ERROR` on `fromAt`. Start again with a later `fromAt`. ## Response A page contains `trades`, `nextCursor` and `hasMore`, in the same shape as [Trades](/reference/rest/trades#response). `limit` sets the page size. The default is 20, and out-of-range values are clamped to 1–100. Each token and each wallet in `filter` costs one [credit](/concepts/errors#credits), and a request that lists neither costs one. Pools are free. ## Pagination Send `nextCursor` back as `cursor`, with the rest of the body unchanged. A cursor continues only the request that made it, and a cursor from another request returns `400 VALIDATION_ERROR` on `cursor`. A page can hold fewer than `limit` trades, or none, while `hasMore` is `true`. Page until `hasMore` is `false`. ## Backfill a stream To fill a list with past trades and keep it live without a gap: 1. Subscribe to `spot.trades` with the filter, and buffer the trades you receive. 2. Read `POST /v1/trades` with the same filter, newest first. 3. Drop each buffered trade whose `id` the read returned, then apply the rest. A trade's `id` is the same on both. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `filter.chains` is not supported | | `VALIDATION_ERROR` | More than 10 `tokens` or `pools`, more than 100 `wallets`, or an empty list; a ranking without `fromAt`, or with a window that is too wide or too old; a ranking whose `fromAt` is in the future; a `toAt` at or before `fromAt`; `order` set to `asc` on a newest-first read; a range with `min` above `max`; an unknown filter key, flag or value; a cursor from another request; or a malformed body | ```bash cURL theme={null} curl -X POST "https://api.metastreams.io/v1/trades" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "filter": { "chains": ["solana"], "side": "buy", "flags": ["whale"], "volumeUsd": { "min": "1000" } }, "limit": 30 }' ``` ```bash Ranked theme={null} curl -X POST "https://api.metastreams.io/v1/trades" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "filter": { "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] }, "sortBy": "volumeUsd", "fromAt": 1789545600000, "limit": 20 }' ``` ```typescript Node.js theme={null} const response = await fetch("https://api.metastreams.io/v1/trades", { method: "POST", headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ filter: { chains: ["solana"], side: "buy", flags: ["whale"], volumeUsd: { min: "1000" } }, limit: 30, }), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const { trades, nextCursor, hasMore } = await response.json(); ``` ```rust Rust theme={null} use serde_json::{Value, json}; let page: Value = reqwest::Client::new() .post("https://api.metastreams.io/v1/trades") .bearer_auth(std::env::var("API_KEY")?) .json(&json!({ "filter": { "chains": ["solana"], "side": "buy", "flags": ["whale"], "volumeUsd": { "min": "1000" } }, "limit": 30, })) .send() .await? .error_for_status()? .json() .await?; let trades = &page["trades"]; ``` ```json Page theme={null} { "trades": [ { "id": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h:2", "chain": "solana", "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "name": "Bonk", "symbol": "Bonk", "trader": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "transactionHash": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h", "side": "buy", "amount": "62500000", "price": { "native": "0.000000121", "usd": "0.0000216" }, "volume": { "native": "7.55", "usd": "1350.60" }, "marketCap": { "native": "10741962.1", "usd": "1917440000" }, "flags": ["whale"], "timestamp": 1789632015120 } ], "nextCursor": "eyJ0cyI6MTc4OTYzMjAxNTEyMCwiaWQiOiI0eFFtVmI4ZTJrVDFuUjdwWmNXM3NMZEhmQTlq", "hasMore": true } ``` ```json Ranking without fromAt theme={null} { "error": { "code": "VALIDATION_ERROR", "message": "One or more parameters are invalid.", "details": [{ "field": "fromAt", "message": "A ranking needs the start of its window." }] } } ``` # Trades Source: https://docs.metastreams.io/reference/rest/trades specs/openapi.json GET /v1/trades Returns recent trades, newest first, for a set of tokens, a set of wallets, or a feed of notable wallets. Returns recent trades, newest first, merged across every chain and token in scope. Each trade includes its own `chain` and `token`. To read trades that match any [`spot.trades`](/reference/streams/spot-trades) filter, or to rank them by a value, use [Trade history](/reference/rest/trade-search). ## What to read Choose one of these reads: * `tokens`, a comma-separated list of 1 to 10 token addresses, reads the trades on those tokens. * `wallets`, a comma-separated list of 1 to 100 wallet addresses, reads the trades those wallets made. * `tokens` and `wallets` together read the named wallets' trades on the named tokens. * `identity` alone reads one feed of notable wallets across every token. `kol` covers wallets labelled as key opinion leaders, and `fomo` covers wallets with a fomo.family profile. A read that names `wallets` returns only the last 90 days of trades. `chains` limits results to a comma-separated list of [chain slugs](/concepts/chains), such as `solana,bsc`. Omit it to include every chain. An address reads on every chain in scope of its format, so an EVM address reads on each EVM chain. ## Filters * `flags` takes a comma-separated list of [wallet classifications](/resources/glossary#wallet-classifications), such as `bundler,insider`. A trade is included when its trader has at least one of them. `fomo` matches traders flagged `fomo` and trades routed through the fomo.family terminal. `flags` applies only to a read by `tokens`. * `side` keeps only `buy` or `sell` trades. It applies only to a read by `wallets`. ## Response `limit` sets the page size. The default is 20, and out-of-range values are clamped to 1–100. Each token and each wallet in the request costs one [credit](/concepts/errors#credits), and an `identity` read costs one. A page contains `trades`, `nextCursor` and `hasMore`. `nextCursor` is the cursor for the next page, or `null` on the last page, and `hasMore` is `true` while more pages remain. An unknown token or wallet returns an empty page, not a `404`. ## Pagination * **Opaque cursors.** The cursor must not be constructed, modified or parsed. Send it back exactly as received. * **Stable pages.** The cursor marks a position in the list, not an offset, so trades that arrive during pagination do not cause duplicated or skipped results. * **One query per cursor.** A cursor continues only the query that made it. Send the same parameters with each page. * **Invalid cursors.** An unreadable cursor returns `400 VALIDATION_ERROR` on the `cursor` field rather than silently restarting from the first page. * **Short pages.** A page can hold fewer than `limit` trades, or none, while `hasMore` is `true`. Page until `hasMore` is `false`. ```typescript Node.js theme={null} const url = "https://api.metastreams.io/v1/trades"; const headers = { Authorization: `Bearer ${process.env.API_KEY}` }; let cursor = null; do { const params = new URLSearchParams({ tokens: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", chains: "solana", limit: "100" }); if (cursor) params.set("cursor", cursor); const response = await fetch(`${url}?${params}`, { headers }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const page = await response.json(); for (const trade of page.trades) console.log(trade.id, trade.side, trade.volume.usd); cursor = page.hasMore ? page.nextCursor : null; } while (cursor); ``` ```rust Rust theme={null} use serde_json::Value; let url = "https://api.metastreams.io/v1/trades"; let key = std::env::var("API_KEY")?; let client = reqwest::Client::new(); let mut cursor: Option = None; loop { let mut request = client.get(url).bearer_auth(&key).query(&[ ("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"), ("chains", "solana"), ("limit", "100"), ]); if let Some(cursor) = &cursor { request = request.query(&[("cursor", cursor)]); } let page: Value = request.send().await?.error_for_status()?.json().await?; for trade in page["trades"].as_array().into_iter().flatten() { println!("{} {} {}", trade["id"].as_str().unwrap_or_default(), trade["side"].as_str().unwrap_or_default(), trade["volume"]["usd"].as_str().unwrap_or("null")); } if page["hasMore"] != true { break; } cursor = page["nextCursor"].as_str().map(String::from); } ``` ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chains` is not supported | | `VALIDATION_ERROR` | A combination of `tokens`, `wallets`, `identity`, `flags` and `side` that the rules above do not allow, such as `flags` with `identity`; more than 10 tokens or 100 wallets; a malformed address; an unknown flag or feed; a cursor that does not decode or that another query made; or an unknown parameter | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/trades?tokens=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263&chains=solana&limit=50" \ -H "Authorization: Bearer $API_KEY" ``` ```bash Wallets theme={null} curl "https://api.metastreams.io/v1/trades?wallets=7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5&side=buy" \ -H "Authorization: Bearer $API_KEY" ``` ```bash Identity feed theme={null} curl "https://api.metastreams.io/v1/trades?identity=kol&chains=solana,bsc" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/trades"); url.searchParams.set("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"); url.searchParams.set("chains", "solana"); url.searchParams.set("limit", "50"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const { trades, nextCursor, hasMore } = await response.json(); ``` ```rust Rust theme={null} use serde_json::Value; let page: Value = reqwest::Client::new() .get("https://api.metastreams.io/v1/trades") .query(&[ ("tokens", "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"), ("chains", "solana"), ("limit", "50"), ]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; let trades = &page["trades"]; ``` ```json Page theme={null} { "trades": [ { "id": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h:2", "chain": "solana", "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "name": "Bonk", "symbol": "Bonk", "trader": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "transactionHash": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h", "side": "buy", "amount": "12500000", "price": { "native": "0.000000121", "usd": "0.0000216" }, "volume": { "native": "1.51", "usd": "270.12" }, "marketCap": { "native": "10741962.1", "usd": "1917440000" }, "timestamp": 1789632015120 } ], "nextCursor": "eyJ0cyI6MTc4OTYzMjAxNTEyMCwiaWQiOiI0eFFtVmI4ZTJrVDFuUjdwWmNXM3NMZEhmQTlq", "hasMore": true } ``` ```json Empty page theme={null} { "trades": [], "nextCursor": null, "hasMore": false } ``` # Trending Source: https://docs.metastreams.io/reference/rest/trending specs/openapi.json POST /v1/trending Returns tokens ranked by trending score across one or more chains. Returns tokens ranked by trending score across the requested chains. Tokens from every requested chain are ranked as one set. ## Request body `chains` is required and must list at least one chain. A repeated chain slug counts once. * `window` sets the period the score covers: `1m`, `5m`, `30m`, `1h`, `6h` or `24h`. The default is `24h`. * `limit` sets the number of tokens on the board. The default is 100, and out-of-range values are clamped to 1–100. * `filters` takes the same filters as [Discovery boards](/reference/rest/discovery#filters). A token must match every filter to be ranked. An unknown top-level field or filter name returns `400 VALIDATION_ERROR`. ## Ranking The trending score combines USD volume, trade count and volume growth over the window. Tokens created in the last 24 hours receive a bonus. On `24h`, the score also includes holder growth and favors tokens with recent activity. The score is not returned. `rank` gives the order, and tokens with equal scores are returned in a stable order. The board can contain fewer tokens than `limit`. ## Response The response lists the board, with one item per rank starting from 1. Each item's `data` is the same token object that [Tokens](/reference/rest/token-details) returns. The [`spot.trending`](/reference/streams/spot-trending) channel streams changes to the same board. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A slug in `chains` is not supported | | `VALIDATION_ERROR` | An empty `chains` list, an unknown field or filter name, or a malformed body | ```bash cURL theme={null} curl -X POST "https://api.metastreams.io/v1/trending" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "chains": ["solana", "bsc"], "window": "1h", "limit": 50, "filters": { "marketCapUsd": { "min": "100000" } } }' ``` ```typescript Node.js theme={null} const response = await fetch("https://api.metastreams.io/v1/trending", { method: "POST", headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ chains: ["solana", "bsc"], window: "1h", limit: 50, }), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const deltas = await response.json(); ``` ```rust Rust theme={null} use serde_json::{Value, json}; let deltas: Vec = reqwest::Client::new() .post("https://api.metastreams.io/v1/trending") .bearer_auth(std::env::var("API_KEY")?) .json(&json!({ "chains": ["solana", "bsc"], "window": "1h", "limit": 50, })) .send() .await? .error_for_status()? .json() .await?; ``` ```json Shortened theme={null} [ { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "rank": 1, "data": { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "name": "Example", "symbol": "EXAMPLE", "decimals": 6, "logo": { "small": "https://cdn.example.com/TokenMint1111111111111111111111111111111pump_16x16.webp", "medium": "https://cdn.example.com/TokenMint1111111111111111111111111111111pump_60x60.webp", "large": "https://cdn.example.com/TokenMint1111111111111111111111111111111pump.webp" }, "price": { "native": "0.0000031", "usd": "0.00055" }, "marketCap": { "native": "3100", "usd": "552000" }, "liquidity": { "native": "410.2", "usd": "73100" }, "updatedAt": 1789632012345 } } ] ``` # Balances Source: https://docs.metastreams.io/reference/rest/wallet-balances specs/openapi.json GET /v1/balances Returns the latest balance of each wallet and asset, across one or more chains. Returns the latest balance of each requested wallet, with one row per chain, wallet and asset. `wallets` takes 1 to 100 comma-separated addresses. `chains` limits results to a comma-separated list of [chain slugs](/concepts/chains); omit it to include every chain. Each `wallet` comes back in canonical form: Base58 on Solana, and lowercase hex on EVM chains. ## Response The response is a list with one row per chain, wallet and asset with at least one transaction, ordered by chain, wallet, then asset. A wallet and asset with no observed balance has no row, and a missing row does not mean a zero balance. `balance` is the amount after the most recent transaction that changed it, in the asset's own units. `trigger` is the event type that changed it, such as `trade` or `deposit`. New `trigger` and `asset` values can be added, so keep unrecognized values rather than discarding them. `blockNumber` and `txIndex` give the row's position in its chain. To merge this response with the [`wallet.balances`](/reference/streams/wallet-balances#message-format) stream, follow the rule on that page. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | A `chains` value is not a supported slug | | `VALIDATION_ERROR` | No wallet or more than 100, a malformed address, or an unknown parameter | ```bash cURL theme={null} curl "https://api.metastreams.io/v1/balances?wallets=7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5&chains=solana" \ -H "Authorization: Bearer $API_KEY" ``` ```typescript Node.js theme={null} const url = new URL("https://api.metastreams.io/v1/balances"); url.searchParams.set("wallets", "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"); url.searchParams.set("chains", "solana"); const response = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const balances = await response.json(); ``` ```rust Rust theme={null} use serde_json::Value; let balances: Vec = reqwest::Client::new() .get("https://api.metastreams.io/v1/balances") .query(&[("wallets", "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"), ("chains", "solana")]) .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; ``` ```json Balances theme={null} [ { "chain": "solana", "wallet": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "asset": "SOL", "balance": "41.208113", "trigger": "trade", "blockNumber": 371204118, "signature": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h", "txIndex": 812, "updatedAt": 1789632015120 } ] ``` ```json Never moved theme={null} [] ``` # chain.nativePrices Source: https://docs.metastreams.io/reference/streams/native-prices Streams the USD price of each chain's gas asset. Streams the USD price of each chain's gas asset: SOL on `solana`, BNB on `bsc`, ETH on `robinhood` and HYPE on `elysium`. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection. ## Filters **chains** `string[]` [Chain slugs](/concepts/chains) whose prices to send. Omit it or send `[]` to include every chain. `{}` sends the price of every chain. Each subscription counts as one address against the [address limit](/streams/filters#address-limits), whatever its `chains`. ## Message format Each update's `data` is the price of one whole unit of one chain's gas asset. It has the same row shape that [Native prices](/reference/rest/native-prices) returns, and `price.native` is always `"1"`. An update is sent for each chain about every 10 seconds, whether or not the price changed. Each update costs one third of a [credit](/concepts/errors#credits), so a `{}` subscription costs about that per chain every 10 seconds. List only the chains you need. Keep one price per `chain`, choosing the row with the later `observedAt`. ## Initial snapshot 1. Subscribe. 2. Read [Native prices](/reference/rest/native-prices) with `chains` set to the subscription's chains. 3. Merge the REST response and the updates using the rule above. A chain with no price yet has no row in the REST response. Its price is sent with the next update. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | Unsupported slug in `chains` | | `VALIDATION_ERROR` | An unknown filter field; an exceeded [subscription limit](/streams/filters#address-limits) | ```json Subscribe theme={null} { "action": "subscribe", "channel": "chain.nativePrices", "filters": { "chains": ["solana", "bsc"] } } ``` ```json Update theme={null} { "type": "update", "channel": "chain.nativePrices", "subscriptionId": "8c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f", "data": { "chain": "solana", "asset": "SOL", "price": { "native": "1", "usd": "178.42" }, "observedAt": 1789632015120 } } ``` # spot.candles Source: https://docs.metastreams.io/reference/streams/spot-candles Streams candle buckets that match a filter on chain, token, pool, timeframe, volume or price change. Streams OHLCV candle buckets that match the subscription's filters, updating each bucket as it forms. Each update identifies the series it belongs to, so one subscription can feed many chart series, and `{}` matches every token bucket on every chain. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection, and [Filtering streams](/streams/filters) for how keys, lists and ranges combine. ## Filters | Group | Keys | | - | - | | Scope | `chains`; `tokens`, `pools` (addresses); `timeframes` (`1s`, `5s`, `15s`, `30s`, `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `7d`) | | Bucket | `volumeUsd`, `volumeNative`; `buyCount`, `sellCount`; `changePct` (close against open, signed); `rangePct` (high less low, against open); `liquidityUsd`, `liquidityNative` (at the close) | | Token state | `token`, which takes any [`spot.tokens` filter](/reference/streams/spot-tokens#filters) | ### Token and pool buckets Without `pools`, the buckets are token buckets, and each one aggregates every pool the token trades in. With `pools`, the buckets are the named pools' buckets. * `tokens` and `pools` each cover every chain in their address family that `chains` includes. * Omit a list to match every address. An empty list is rejected. * `pools` rejects the zero address. * A pool bucket has no liquidity value, so it never matches `liquidityUsd` or `liquidityNative`. ### Bucket values * `changePct` and `rangePct` are computed from the bucket in the subscription's `metric` and `denomination`. A bucket with a zero open never matches either key. * An omitted `timeframes` matches every timeframe. ### Token state `token` tests the latest state of the bucket's token, as on [`spot.trades`](/reference/streams/spot-trades#token-state). A token has a state once it changes, and a token that has not changed for 15 minutes can lose it. ## Options These options are top-level fields of the subscribe frame, alongside `filters`, not inside it. **metric** `string` (default: marketCap) `price` for price candles, or `marketCap` for market-cap candles. **denomination** `string` (default: usd) `usd` for US dollars, or `native` for the chain's native unit. **closedOnly** `boolean` (default: false) Sends only each bucket's final state instead of every update. Cannot be combined with `throttleMs`. **throttleMs** `integer` (default: 0) Minimum interval between updates of one series, in milliseconds, from 0 to 60,000. The first update in an interval is sent immediately. Later updates in the same interval are merged into the newest, which is sent when the interval ends. `0` sends every update. To follow several metrics or denominations, open a separate subscription for each. ### Closed buckets With `closedOnly: true`, a bucket's final state is sent 2 seconds after the bucket ends, or as soon as a newer bucket of the same series opens. * A bucket whose final state does not match the filter is not sent. * A late change to a bucket that was already sent is sent again, as a correction. * One subscription tracks at most 10,000 open buckets. Beyond that, new series are not sent, so narrow the filter with `tokens` or `timeframes`. ## Message format Each update's `data` is the current state of one bucket, in the same shape that [OHLCV candles](/reference/rest/token-ohlcv) returns, plus the four fields that identify its series. An open bucket is sent again on every trade, so key each candle on `chain`, `token`, `pool`, `timeframe` and `time`: replace a candle with the same key, and append a new one. **chain** `string` *required* [Chain slug](/concepts/chains). **token** `string` *required* Token address. **pool** `string | null` *required* Pool address of a pool bucket; `null` on a token bucket. **timeframe** `string` *required* Bucket size, such as `1m`. **time** `integer` *required* Bucket open time, in milliseconds. **open** `number` *required* First value in the bucket. **high** `number` *required* Highest value in the bucket. **low** `number` *required* Lowest value in the bucket. **close** `number` *required* Latest value in the bucket. **volume** `number` *required* Traded volume in the bucket, in the subscription's denomination. Candle values are JSON numbers, not decimal strings. See [Candles are numbers](/concepts/reading-responses#candle-values). To load history from before the stream starts, read candles with the same `timeframe`, `metric` and `denomination` from [OHLCV candles](/reference/rest/token-ohlcv). ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | Any cause listed under [Errors](/streams/filters#errors); an empty `tokens` or `pools` list; the zero address in `pools`; an unknown timeframe; an unknown `metric` or `denomination`; `closedOnly` with `throttleMs` | | `UNSUPPORTED_CHAIN` | Unsupported chain slug | ## Unsupported filters `spot.candles` rejects the following filters. Use the replacement in the right column instead. | Unsupported | Use instead | | - | - | | `{ "chain": "solana", "token": "…", "timeframe": "1m" }` | `{ "chains": ["solana"], "tokens": ["…"], "timeframes": ["1m"] }` | | `metric` or `denomination` inside `filters` | `metric` or `denomination` beside `filters` | ```json Token chart theme={null} { "action": "subscribe", "channel": "spot.candles", "filters": { "chains": ["solana"], "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"], "timeframes": ["1m", "5m"] }, "metric": "price", "denomination": "usd" } ``` ```json Breakouts theme={null} { "action": "subscribe", "channel": "spot.candles", "filters": { "chains": ["solana"], "timeframes": ["1m"], "volumeUsd": { "min": "10000" }, "changePct": { "min": "5" }, "token": { "marketCapUsd": { "max": "5000000" } } }, "closedOnly": true } ``` ```json Update theme={null} { "type": "update", "channel": "spot.candles", "subscriptionId": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d", "data": { "chain": "solana", "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "pool": null, "timeframe": "1m", "time": 1789632000000, "open": 0.0000216, "high": 0.0000218, "low": 0.0000215, "close": 0.0000217, "volume": 48211.7 } } ``` # spot.discovery Source: https://docs.metastreams.io/reference/streams/spot-discovery Streams the discovery board: each column in full after subscribing, then each change. Streams the columns of the discovery board, ranked. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection. ## Filters The filter is the [Discovery](/reference/rest/discovery) request body: `chains`, and one or more of the columns `newPairs`, `graduating` and `graduated`. Each column takes `sortBy`, `order`, `limit` and `filters`, with the same defaults as the REST request. `chains` must list at least one chain, and the filter must include at least one column. Each subscription counts as one address against the [address limit](/streams/filters#address-limits). The channel does not accept a `throttleMs` above 0 or any other subscribe option. ## Updates * After the `ack`, one update for each requested column contains the whole column, in rank order. It matches the REST response for the same body. An empty column sends an update with an empty `deltas` list. * After that, each change to a token can add, move or remove it. A token is added while its column has room, or when it ranks above the last row of a full column, which then drops. * A token that no longer matches `filters` or the column defaults is removed, and the rows below it move up. A token that graduates moves from `newPairs` or `graduating` to `graduated`. * Changes are batched every 250 milliseconds. Each batch sends one update for each column that changed, and nothing for a column that did not. * If the first request for one chain does not succeed, the first update omits that chain's rows, and the other chains still fill the column. The REST request returns an error instead. The server never ranks a column again, and checks the time rules, such as the 24-hour activity cutoff and `lastActivityMinutes`, only when a token changes. A token that stops trading therefore stays in the column, and a removed row's place stays empty until another token fills it. Over time, a column drifts from the REST response for the same body. To realign it, subscribe again, for example every few minutes. Each update costs [one third of a credit](/concepts/errors#credits). ## Message format Each update's `data` contains the `column` it describes and a `deltas` list. Keep one row per `column`, `chain` and `address`, and apply each delta in order: | Delta | Action | | - | - | | `data` and `rank` | Replace the row with `data`, and place it at `rank`. The row is new, or its token changed. | | `rank` without `data` | Move the row to `rank`. | | `rank` is `null` | Remove the row. | In each update, the removals come first, then the other rows in rank order. `rank` starts at 1. `data` has the same fields as a token in the [Discovery](/reference/rest/discovery) response. After a reconnect, subscribe again. No REST request is needed. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | Unsupported slug in `chains` | | `VALIDATION_ERROR` | An empty `chains` list; no column; an unknown field in a column's `filters`; a `throttleMs` above 0 or another subscribe option; an exceeded subscription or [address limit](/streams/filters#address-limits) | ```json Subscribe theme={null} { "action": "subscribe", "channel": "spot.discovery", "filters": { "chains": ["solana"], "newPairs": { "limit": 30 }, "graduating": { "sortBy": "bondingCurveActivity", "limit": 30 } } } ``` ```json First update (shortened) theme={null} { "type": "update", "channel": "spot.discovery", "subscriptionId": "6f7a8b9c-0d1e-4f2a-8b3c-4d5e6f7a8b9c", "data": { "column": "newPairs", "deltas": [ { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "rank": 1, "data": { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "name": "Example", "symbol": "EXAMPLE", "launchpad": "pumpfun", "bondingCurvePct": "12.4", "price": { "native": "0.000000031", "usd": "0.0000055" }, "marketCap": { "native": "31", "usd": "5520" }, "createdAt": 1789632001000, "updatedAt": 1789632012345 } } ] } } ``` ```json Later update (shortened) theme={null} { "type": "update", "channel": "spot.discovery", "subscriptionId": "6f7a8b9c-0d1e-4f2a-8b3c-4d5e6f7a8b9c", "data": { "column": "newPairs", "deltas": [ { "chain": "solana", "address": "TokenMint2222222222222222222222222222222pump", "rank": null }, { "chain": "solana", "address": "TokenMint3333333333333333333333333333333pump", "rank": 1, "data": { "chain": "solana", "address": "TokenMint3333333333333333333333333333333pump", "symbol": "NEW" } }, { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "rank": 2 } ] } } ``` # spot.holders Source: https://docs.metastreams.io/reference/streams/spot-holders Streams a token's holder rows each time a trade or transfer changes them. Streams a holder's row on a token each time a trade or transfer changes it. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection. ## Filters **chain** `string` *required* [Chain slug](/concepts/chains) of the token. **token** `string` *required* Token address on `chain`. The subscription counts as one address against the [address limit](/streams/filters#address-limits). **flags** `string[]` [Wallet classifications](/resources/glossary#wallet-classifications) to match, using the same values as the [Token holders](/reference/rest/token-holders#filters) `flags` parameter. A holder matches when it carries at least one of them, and `fomo` matches wallets flagged `fomo`. Omit it to match every holder. On a busy token, most trades change a holder, so `flags` reduces the number of updates. **period** `string` (default: lifetime) Span that each row's trading figures cover. One of `cycle`, the open round trip, or `lifetime`, every round trip. It is a key of `filters`, the same as the [Token holders](/reference/rest/token-holders) `period` parameter. This channel does not accept a `throttleMs` above 0 or any other subscribe option, and does not send `exit` frames. ## Message format Each update's `data` is one holder's full row on the token after a change, in the same row shape that [Token holders](/reference/rest/token-holders) returns, without `rank`. Its trading figures cover the subscription's `period`. * Keep one row per `chain`, token and `address`; a later update replaces the earlier one. * Rank the rows by `balance` on the client, largest first. * A holder that sells its entire balance is sent with a `balance` of `0`. Remove it from the list. Rows do not include value or unrealized PnL. To price a row, use the formulas on [Token holders](/reference/rest/token-holders#response). ## Initial snapshot 1. Subscribe. 2. Read [Token holders](/reference/rest/token-holders) with the same `flags` and `period`. 3. Merge the REST response and the updates on `address`. One REST page returns at most 150 holders; page with `cursor` for more. The stream sends every holder that changes. A holder missing from the REST response can therefore appear on the stream, so rank the merged rows by `balance`. Repeat the REST request after every reconnect. ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | Missing `chain` or `token`; a token address in the wrong format for the chain; an unknown flag; an unknown `period`; an unknown filter field; a `throttleMs` above 0 or another subscribe option; an exceeded [address limit](/streams/filters#address-limits) | | `UNSUPPORTED_CHAIN` | Unsupported `chain` slug | ```json Subscribe theme={null} { "action": "subscribe", "channel": "spot.holders", "filters": { "chain": "solana", "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "flags": ["bundler", "insider"] } } ``` # spot.positions Source: https://docs.metastreams.io/reference/streams/spot-positions Streams a wallet's full, priced position in a token each time a trade, a transfer or its price changes it. Streams a wallet's full position in a token each time a trade, a transfer or the token's price changes it. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection. ## Filters **chain** `string` *required* [Chain slug](/concepts/chains) of the positions. **wallets** `string[]` *required* One or more wallet addresses on `chain`. For a single wallet, `wallet` with one address is also accepted. Each wallet counts as one address against the [address limit](/streams/filters#address-limits). **throttleMs** `integer` (default: 1000) A top-level subscribe option, next to `filters`. Sends at most one update per position in this many milliseconds, up to 60,000. The default is 1,000, and `0` also means 1,000, so updates are always throttled. A subscription can have at most 10,000 positions. See [Limits](/concepts/errors#limits). ## Message format Each update's `data` is a wallet's full position in one token after a change, in the same row shape that [Positions](/reference/rest/positions) returns. Keep one row per `chain`, `walletAddress` and token. Each row is priced the same way as the REST endpoint, so `value`, `unrealizedPnl`, `totalPnl` and `pnlPct` are `null` only where the REST response has `null`. A trade or transfer raises `version`. Any change to the token of an open position, such as a new price, sends the row again with the same `version`. A closed position is sent once, and later price changes send nothing. Replace your row with an update whose `version` is equal to or higher than yours. If you keep only a strictly higher `version`, you miss every price change. ## Cost Each update costs one third of a [credit](/concepts/errors#credits). An open position is sent again whenever its token changes, at most once per `throttleMs`. A wallet with 100 open positions in active tokens can use about 33 credits per second at the default of 1,000. Set a larger `throttleMs` when the positions do not need to be live to the second. ## Initial snapshot 1. Subscribe. 2. Read every page of [Positions](/reference/rest/positions) with the same wallets, `chains` set to the subscription's chain, and `hideLowLiquidity=false`. The stream does not filter anything out, so the REST request must not either. The request returns only open positions; to keep closed rows, also request `lifecycle=closed`. 3. Merge the REST response and the updates on `version`, as [Message format](#message-format) describes. Repeat the REST request after every reconnect. ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | Missing `chain`; no wallet; an address in the wrong format for the chain; an unknown filter field; `throttleMs` above 60,000; an exceeded [address limit](/streams/filters#address-limits) | | `UNSUPPORTED_CHAIN` | Unsupported `chain` slug | ```json Subscribe theme={null} { "action": "subscribe", "channel": "spot.positions", "filters": { "chain": "solana", "wallets": ["7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"] }, "throttleMs": 5000 } ``` # spot.tokens Source: https://docs.metastreams.io/reference/streams/spot-tokens Streams every token that matches a filter each time it changes, plus an exit when it stops matching. Streams every token that matches the subscription's filters each time the token changes, and sends an `exit` frame when a token stops matching. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection, and [Filtering streams](/streams/filters) for how keys, lists and ranges combine. ## Overview Each time a token changes, the subscription tests the token's full state against the filters. * When a token starts to match, it is sent as an `update` with the full token object, and so is each later change while it still matches. * When a token stops matching, a single `exit` frame with its `chain` and `address` is sent. The token can match again later and be sent again. * The subscription does not start with a snapshot; each token is sent on its next change. To show a full view first, read [Tokens](/reference/rest/token-details) or [Discovery](/reference/rest/discovery). * One subscription tracks at most 10,000 matching tokens. Beyond that, the token that matched least recently receives an `exit`, and it is sent again the next time it matches. ## Filters `{}` matches every token on every chain. Each key below narrows the set. | Group | Keys | | - | - | | Scope | `chains`; `tokens` (1 to 100 addresses); `devAddresses`, `fundingAddresses`; `fundingKinds` (`cex`, `wallet`); `symbolOrName` (text in the symbol or name, or the exact address) | | Venue and stage | `protocols` (launchpads); `dexes`; `graduatedToDexes`; `stages` (`newly_created`, `about_to_graduate`, `graduated`); `anchors` (`native`, `usdc`, `usdt`, `usd1`, `busd`, `uusd`, `usdg`); `annotations` (`mayhem_mode`, `cashback_coin`, `anchor`, `x_mode`, `tax_token`, `stock_quote`, `stock_dividend`, `ai_vault`, `tax_vault`) | | Market and age | `priceUsd`, `marketCapUsd`, `liquidityUsd`, `supply`, `athMarketCapUsd`, `drawdownFromAthPct`, `bondingCurvePct`, `ageMs`, `sinceGraduationMs`, `lastActivityMs` | | Window stats, under `stats.5m`, `stats.30m`, `stats.1h`, `stats.6h` or `stats.24h` | `volumeUsd`, `buyVolumeUsd`, `sellVolumeUsd`, `netBuyVolumeUsd`, `buys`, `sells`, `txns`, `priceChangePct` (signed) | | Holders | `holderCount`; `top10HoldersPct`, `devHoldingPct`; `fundedByCexPct` (share of holders funded by an exchange) | | Holder-group supply, per [holder group](/resources/glossary#holder-groups) | `snipersSupplyPct`, `bundlerSupplyPct`, `insiderSupplyPct`, `freshWalletSupplyPct`, `fomoSupplyPct`, `phishingSupplyPct`, `proTraderSupplyPct` | | Holder-group size | `sniperCount`, `bundlerCount`, `insiderCount`, `freshWalletCount`, `fomoCount`, `phishingCount`, `proTraderCount` | | Security | `mintDisabled`, `transferBlockable`, `dexPaid` (`true` or `false`); `lpBurntPct`, `transferFeeBps`, `buyTaxBps`, `sellTaxBps` | | Socials and fees | `socials` (`twitter`, `telegram`, `website`, `discord`); `feesDexUsd`, `feesPlatformUsd`, `feesValidatorUsd`, `totalVolumeUsd`, all over the token's life | | Exclude | `exclude` takes every list key above, plus `websites` (hosts) and `twitter` (X handles) | Ages are milliseconds since the event, so `ageMs: { "max": 3600000 }` matches tokens created in the last hour. `ageMs`, `sinceGraduationMs` and `lastActivityMs` are tested only when the token changes, so a token that ages out of the range receives its `exit` at its next change. An unknown value never matches a range (see [Ranges](/streams/filters#ranges)). Two cases are specific to this channel: * `drawdownFromAthPct` is unknown when the USD market cap or its all-time high is unknown. * A holder count of zero makes every Holders key unknown. ## Throttle `throttleMs`, set alongside `filters` in the subscribe frame, limits the subscription to one update per token per interval. It accepts an integer from 0 to 60,000. Omit it or send `0` to receive every update. * The first update in an interval is sent immediately. * Later updates in the same interval are collapsed into the newest one, which is sent when the interval ends. * An `exit` is never delayed. It discards any pending update and ends the interval, so a token that matches again is sent immediately. ## Message format Each `update` contains the full token object in `data`, which replaces the stored copy. [Tokens](/reference/rest/token-details) documents every field. Each `exit` contains only the token's `chain` and `address` in `data`, and means the token should be removed from the view. `exit` frames are [not billed](/streams/overview). ## Unsupported filters `spot.tokens` accepts `chains` and `tokens` lists and rejects `chain` and `token`: | Unsupported | Use instead | | - | - | | `{ "chain": "solana", "tokens": ["…"] }` | `{ "chains": ["solana"], "tokens": ["…"] }` | | `{ "chain": "solana", "token": "…" }` | `{ "chains": ["solana"], "tokens": ["…"] }` | ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | Any cause listed under [Errors](/streams/filters#errors); an empty `tokens` list or one over 100; `throttleMs` outside 0–60,000 | | `UNSUPPORTED_CHAIN` | Unsupported chain slug | ```json Watchlist theme={null} { "action": "subscribe", "channel": "spot.tokens", "filters": { "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] }, "id": "watchlist" } ``` ```json Screener theme={null} { "action": "subscribe", "channel": "spot.tokens", "filters": { "chains": ["solana", "bsc"], "protocols": ["pumpfun", "four_meme"], "marketCapUsd": { "min": "100000", "max": "5000000" }, "stats": { "1h": { "priceChangePct": { "min": "20" } } }, "top10HoldersPct": { "max": "30" }, "mintDisabled": true, "socials": ["twitter", "telegram"], "exclude": { "annotations": ["mayhem_mode"] } }, "throttleMs": 1000, "id": "screener" } ``` ```json Update (shortened) theme={null} { "type": "update", "channel": "spot.tokens", "subscriptionId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "data": { "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "name": "Bonk", "symbol": "Bonk", "decimals": 5, "logo": { "small": "https://cdn.example.com/DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263_16x16.webp", "medium": "https://cdn.example.com/DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263_60x60.webp", "large": "https://cdn.example.com/DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263.webp" }, "price": { "native": "0.000000121", "usd": "0.0000216" }, "marketCap": { "native": "10741962.1", "usd": "1917440000" }, "liquidity": { "native": "61230.4", "usd": "10929626" }, "updatedAt": 1789632012345 } } ``` ```json Exit theme={null} { "type": "exit", "channel": "spot.tokens", "subscriptionId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "data": { "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } } ``` # spot.trades Source: https://docs.metastreams.io/reference/streams/spot-trades Streams every trade that matches a filter on token, wallet, pool, venue, trader or size. Streams every trade that matches the subscription's filters, in real time. Each trade is tested once, as it happens, and `{}` matches every trade on every chain. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection, and [Filtering streams](/streams/filters) for how keys, lists and ranges combine. ## Filters | Group | Keys | | - | - | | Scope | `chains`; `tokens`, `wallets`, `pools` (addresses) | | Venue | `dexes`, `launchpads`; `anchors` (`native`, `usdc`, `usdt`, `usd1`, `busd`, `uusd`, `usdg`) | | Trader | `flags` (`dev`, `sniper`, `insider`, `bundler`, `fresh`, `whale`, `kol`, `fomo`, `pro_trader`, `phishing`); `platforms` (trading terminal, such as `fomo`, `axiom`, `photon`, `bullX`, `gmgn` or `trojan`); `traderSources` (EVM chains only) | | Trade | `side` (`buy` or `sell`); `volumeUsd`; `amount` (in token units); `priceUsd` and `marketCapUsd` at the fill; `liquidityUsd`; `priceImpactPct`; `feesValidatorUsd`, `feesPlatformUsd`; `fullExit` (`true` or `false`) | | Token state | `token`, which takes any [`spot.tokens` filter](/reference/streams/spot-tokens#filters) | | Exclude | `exclude.wallets`, `exclude.flags`, `exclude.platforms` | ### Addresses `tokens`, `wallets` and `pools` each cover every chain in their address family that `chains` includes. A `0x…` wallet therefore covers every EVM chain at once, unless `chains` narrows it. * Omit a list to match every address. An empty list is rejected. * These three lists have no limit of their own; only the [address limit](/streams/filters#address-limits) applies. * `pools` rejects the zero address. ### Flags and platforms A flag matches when the trader carries it, either on this token or on the wallet. The [glossary](/resources/glossary#wallet-classifications) defines each flag. * `kol` matches trades by key opinion leaders. * The `fomo` flag matches trades by wallets that have traded through the fomo.family terminal in any token on the chain. * The `fomo` platform matches trades routed through the fomo.family terminal. `traderSources` is the method used to identify an EVM trade's trader: `swap_recipient`, `tx_origin`, `launchpad_buyer`, `settlement_endpoint`, `authority7702`, `user_op_sender`, `relay_caller`, `pool_caller`, `net_principal`, `net_sender`, `net_payer`, `unresolved`, `cycle_sender`, `native_out_sender`, `contract_caller`, `net_holder`, `net_receiver` or `token_funded`. New sources can be added. Solana trades have no trader source, so they never match this key. ### Trade values * `fullExit: true` matches a sell that leaves the trader with none of the token, and `false` matches every other trade. A sell whose post-trade balance is unknown matches neither. * A zero price, market cap or liquidity on a trade means the value was not measured, so it does not match any range. * `priceImpactPct` is accepted but matches no trade, because trades do not include a pre-trade price. ### Token state `token` tests the latest state of the traded token, as seen by `spot.tokens`. * A token has a state once it changes. A token that has not changed for 15 minutes can lose its state, and a trade on a token with no state does not match `token`. * A trade and the matching token change can be processed in either order, so the first trades after a quiet period can be missed. ## Message format Each update's `data` is one trade, in the same shape that [Trades](/reference/rest/trades) returns. It includes `flags`, `platforms` and `identities` when the trade has any; empty lists are omitted. ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | Any cause listed under [Errors](/streams/filters#errors); an empty `tokens`, `wallets` or `pools` list; the zero address in `pools`; any `throttleMs` above 0, which this channel does not accept | | `UNSUPPORTED_CHAIN` | Unsupported chain slug | ## Unsupported filters `spot.trades` rejects the following filters. Use the replacement in the right column instead. | Unsupported | Use instead | | - | - | | `{ "chain": "solana", "token": "…" }` | `{ "chains": ["solana"], "tokens": ["…"] }` | | `{ "chain": "bsc", "wallet": "0x…" }` | `{ "chains": ["bsc"], "wallets": ["0x…"] }` | | `{ "identity": "kol" }` | `{ "flags": ["kol"] }` | | `{ "identity": "fomo" }` | No exact equivalent, because `spot.trades` has no profile filter. `{ "flags": ["fomo"] }` approximates it: it matches every wallet that has traded through the fomo.family terminal, including wallets without a fomo.family profile. | | `{ "identity": "kol", "flags": ["whale"] }` | No exact equivalent, because a `flags` list matches as OR. To match KOL trades of \$10,000 or more, send `{ "flags": ["kol"], "volumeUsd": { "min": "10000" } }`. | ```json Token theme={null} { "action": "subscribe", "channel": "spot.trades", "filters": { "chains": ["solana"], "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] }, "id": "bonk-trades" } ``` ```json Wallet theme={null} { "action": "subscribe", "channel": "spot.trades", "filters": { "chains": ["bsc"], "wallets": ["0x4c2f1b6a8e0d7c9b3a5f2e1d0c9b8a7f6e5d4c3b"] } } ``` ```json KOL buys theme={null} { "action": "subscribe", "channel": "spot.trades", "filters": { "chains": ["solana"], "flags": ["kol", "fomo"], "side": "buy", "volumeUsd": { "min": "1000" }, "token": { "marketCapUsd": { "max": "5000000" }, "ageMs": { "max": 3600000 } }, "exclude": { "platforms": ["axiom"] } } } ``` ```json Update theme={null} { "type": "update", "channel": "spot.trades", "subscriptionId": "5f0c6d1e-8a2b-4c3d-9e4f-1a2b3c4d5e6f", "data": { "id": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h:2", "chain": "solana", "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "name": "Bonk", "symbol": "Bonk", "trader": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "transactionHash": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h", "side": "buy", "amount": "12500000", "price": { "native": "0.000000121", "usd": "0.0000216" }, "volume": { "native": "1.51", "usd": "270.12" }, "marketCap": { "native": "10741962.1", "usd": "1917440000" }, "flags": ["kol"], "timestamp": 1789632015120 } } ``` # spot.transfers Source: https://docs.metastreams.io/reference/streams/spot-transfers Streams every wallet-to-wallet transfer that matches a filter on token, wallet, sender, recipient or amount. Streams every transfer between two wallets that matches the subscription's filters, in real time. Each transfer is tested once, as it happens, and `{}` matches every transfer on every chain. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection, and [Filtering streams](/streams/filters) for how keys, lists and ranges combine. ## Filters | Group | Keys | | - | - | | Scope | `chains`; `tokens`, `wallets` (either side), `senders`, `recipients` (addresses) | | Transfer | `native` (`true` for the chain's native asset, `false` for a token); `amount` (in token units) | | Token state | `token`, which takes any [`spot.tokens` filter](/reference/streams/spot-tokens#filters) | | Exclude | `exclude.wallets` (either side), `exclude.tokens` | ### Addresses `tokens`, `wallets`, `senders` and `recipients` each cover every chain in their address family that `chains` includes. * `wallets` matches a transfer whose sender or recipient is in the list. `senders` and `recipients` each match one side. * Omit a list to match every address. An empty list is rejected. * These four lists have no limit of their own; only the [address limit](/streams/filters#address-limits) applies. `chains`, `exclude.wallets` and `exclude.tokens` take at most 100 values each. * A transfer that matches two addresses of one subscription, such as its sender and its recipient, is sent once. ### Native transfers A native transfer moves the chain's gas asset and has no token, so it does not match `tokens` or `token`. `native: true` combined with `tokens` or `token` is rejected. ### Token state `token` tests the latest state of the transferred token, as on [`spot.trades`](/reference/streams/spot-trades#token-state). A token has a state once it changes, and a token that has not changed for 15 minutes can lose it. ### Values A transfer has no USD or native value, so the filter has no value keys. `valueUsd` and `valueNative` are rejected like any unknown key. This channel does not accept `throttleMs` and does not send `exit` frames. ## Message format Each update's `data` is one transfer. **chain** `string` *required* [Chain slug](/concepts/chains). **token** `string | null` *required* Token address; `null` for the chain's native asset. **sender** `string` *required* Wallet that sent the transfer. **recipient** `string` *required* Wallet that received the transfer. **amount** `string` *required* Amount moved, in token units, as a [decimal string](/concepts/reading-responses#decimals). **senderBalanceAfter** `string | null` *required* Sender's balance of the asset after the transaction; `null` when unknown. **recipientBalanceAfter** `string | null` *required* Recipient's balance of the asset after the transaction; `null` when unknown. **transactionHash** `string` *required* On-chain transaction hash. **eventIndex** `integer | null` *required* Position of this transfer within the transaction; `null` for a native transfer on an EVM chain. **timestamp** `integer` *required* Execution time, in milliseconds. No REST endpoint returns transfers, so the stream has no snapshot to merge with. ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | Any cause listed under [Errors](/streams/filters#errors); an empty `tokens`, `wallets`, `senders` or `recipients` list; `native: true` with `tokens` or `token`; any `throttleMs` above 0, which this channel does not accept | | `UNSUPPORTED_CHAIN` | Unsupported chain slug | ```json Wallet theme={null} { "action": "subscribe", "channel": "spot.transfers", "filters": { "chains": ["solana"], "wallets": ["8D2YW555vKLbTjhhhJggAEbcioLEGzgiQpFVXq3LxLHA"] } } ``` ```json Large token moves theme={null} { "action": "subscribe", "channel": "spot.transfers", "filters": { "chains": ["solana"], "native": false, "amount": { "min": "1000" }, "token": { "marketCapUsd": { "max": "5000000" } }, "exclude": { "tokens": ["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"] } } } ``` ```json Update theme={null} { "type": "update", "channel": "spot.transfers", "subscriptionId": "3c4d5e6f-7a8b-4c9d-8e0f-1a2b3c4d5e6f", "data": { "chain": "solana", "token": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "sender": "8D2YW555vKLbTjhhhJggAEbcioLEGzgiQpFVXq3LxLHA", "recipient": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "amount": "250000000", "senderBalanceAfter": "750000000", "recipientBalanceAfter": "250000000", "transactionHash": "5kT9rWc2xQ8mNbV3pL7dHfA1jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6hJ9", "eventIndex": 3, "timestamp": 1789632015120 } } ``` # spot.trending Source: https://docs.metastreams.io/reference/streams/spot-trending Streams a trending board: the full board after subscribing, then each change. Streams one trending board. The first update contains the full board, and later updates contain only the rows that changed. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection. ## Filters The filter is the [Trending](/reference/rest/trending) request body: `chains`, `window`, `limit` and `filters`. `chains` must list at least one chain. Each subscription counts as one address against the [address limit](/streams/filters#address-limits). The channel does not accept a `throttleMs` above 0 or any other subscribe option. ## Updates * The full board is sent as one update after the `ack`. It matches the REST response for the same body, in content and order, as read about when you subscribed. * The board is ranked again every 5 seconds for the `1m` and `5m` windows, every 30 seconds for `30m` and `1h`, and every 60 seconds for `6h` and `24h`. The update after each ranking contains only the rows that changed. * Between rankings, changes to a ranked token's state are batched every 250 milliseconds and sent as one update. * A token is added to the board only when the board is ranked again. * A token whose new state no longer matches `filters` is removed between rankings, and the rows below it move up. * No update is sent when nothing changed, so an empty board sends no update. Each update costs one third of a [credit](/concepts/errors#credits). Between rankings, a board sends at most four updates per second. ## Message format Each update's `data` is a list of deltas, the same shape that [Trending](/reference/rest/trending) returns. Keep one row per `chain` and `address`, and apply each delta in order: | Delta | Action | | - | - | | `data` and `rank` | Replace the row with `data`, and place it at `rank`. | | `rank` without `data` | Move the row to `rank`. | | `rank` is `null` | Remove the row. | The score is not sent. After a reconnect, subscribe again: the first update contains the full board, so no REST request is needed. ## Errors | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | Unsupported slug in `chains` | | `VALIDATION_ERROR` | An empty `chains` list; an unknown filter field; a `throttleMs` above 0 or another subscribe option; an exceeded [subscription limit](/streams/filters#address-limits) | ```json Subscribe theme={null} { "action": "subscribe", "channel": "spot.trending", "filters": { "chains": ["solana", "bsc"], "window": "1h", "limit": 50, "filters": { "marketCapUsd": { "min": "100000" } } } } ``` ```json Update (shortened) theme={null} { "type": "update", "channel": "spot.trending", "subscriptionId": "4d5e6f7a-8b9c-4d0e-9f1a-2b3c4d5e6f7a", "data": [ { "chain": "bsc", "address": "0x4200000000000000000000000000000000000abc", "rank": null }, { "chain": "solana", "address": "TokenMint1111111111111111111111111111111pump", "rank": 3 }, { "chain": "solana", "address": "TokenMint2222222222222222222222222222222pump", "rank": 4, "data": { "chain": "solana", "address": "TokenMint2222222222222222222222222222222pump", "name": "Example", "symbol": "EXAMPLE", "decimals": 6, "price": { "native": "0.0000031", "usd": "0.00055" }, "marketCap": { "native": "3100", "usd": "552000" }, "updatedAt": 1789632012345 } } ] } ``` # wallet.balances Source: https://docs.metastreams.io/reference/streams/wallet-balances Streams a wallet's new balance of an asset each time a transaction changes it. Streams a wallet's updated balance of an asset each time a transaction changes it. Subscribe on an open stream connection. See [WebSocket streams](/streams/overview) for connections, frames and reconnection. ## Filters **chain** `string` *required* [Chain slug](/concepts/chains) of the wallets' balances. **wallets** `string[]` *required* One or more wallet addresses on `chain`. For a single wallet, `wallet` with one address is also accepted. Each wallet counts as one address against the [address limit](/streams/filters#address-limits). To follow a wallet on multiple chains, open one subscription per chain. ## Message format Each update's `data` is one wallet's balance of one asset after a transaction, not the change in balance. It has the same row shape that [Wallet balances](/reference/rest/wallet-balances) returns. Updates for one wallet can be delivered out of order, and some can be missed during a reconnect. Keep one row per `chain`, `wallet` and `asset`, choosing the row with the higher `blockNumber`, then the higher `txIndex`. Two rows with equal versions come from the same transaction, so either one is correct. Rows are never retracted, even after a chain reorganization. Some changes, such as Solana rent and the fee of a failed transaction, produce no row, so a balance can lag until the wallet's next captured change. ## Initial snapshot 1. Subscribe. 2. Read [Wallet balances](/reference/rest/wallet-balances) with the same wallets and `chains` set to the subscription's chain. 3. Merge the REST response and the updates using the rule above. The REST response can lag the stream by a few seconds, so a change made just before subscribing can be missing from both. Read again a few seconds after subscribing, and again after every reconnect. ## Errors | Code | When | | - | - | | `VALIDATION_ERROR` | Missing `chain`; no wallet; an address in the wrong format for the chain; an unknown filter field; an exceeded [address limit](/streams/filters#address-limits) | | `UNSUPPORTED_CHAIN` | Unsupported `chain` slug | ```json Subscribe theme={null} { "action": "subscribe", "channel": "wallet.balances", "filters": { "chain": "solana", "wallets": ["7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"] } } ``` ```json Update theme={null} { "type": "update", "channel": "wallet.balances", "subscriptionId": "8c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f", "data": { "chain": "solana", "wallet": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5", "asset": "SOL", "balance": "41.208113", "trigger": "trade", "blockNumber": 371204118, "signature": "4xQmVb8e2kT1nR7pZcW3sLdHfA9jEuY6gVnX1oB5iC0wQ2rT8yU3iO7pA1sD4fG6h", "txIndex": 812, "updatedAt": 1789632015120 } } ``` # Changelog Source: https://docs.metastreams.io/resources/changelog API changes, listed newest first. This page lists changes to the API, newest first. **Plans, tax filters and named accounts** Plan limits, new filters and a new value * The free plan includes no stream connections. On a plan without streams, the stream handshake and [`POST /v1/stream/connect`](/reference/rest/stream-connect) return `403 FORBIDDEN`, and open connections close with code `4403` and the reason `plan excludes streams` after a move to such a plan. See [Close codes](/streams/overview#close-codes). * On paid plans, [`POST /v1/discovery`](/reference/rest/discovery), [`POST /v1/trending`](/reference/rest/trending) and [`GET /v1/search`](/reference/rest/search) each have a request budget of their own. See [Limits](/concepts/errors#limits). * New [discovery](/reference/rest/discovery) filters on a token's tax: `taxPercent`, `excludeHighSellTax`, and the share of the tax that goes to each destination, from `taxToBurnPercent` to `taxToVaultPercent`. [`spot.discovery`](/reference/streams/spot-discovery) takes them too. * New value: the `registry` identity source names well-known accounts, such as exchange wallets, routers and protocol contracts, on their positions, holder rows and trades. **Search, trade history and paged reads** New endpoints and paged reads * New endpoint: [`GET /v1/search`](/reference/rest/search) returns the tokens and wallets that match a symbol, a name, an address or a wallet name. * New endpoint: [`POST /v1/trades`](/reference/rest/trade-search) returns past trades that match any [`spot.trades`](/reference/streams/spot-trades) filter, newest first or ranked by a value such as `volumeUsd`. * [`GET /v1/ohlcv`](/reference/rest/token-ohlcv) and [`GET /v1/holders`](/reference/rest/token-holders) page with `cursor`. Each series includes `nextCursor` and `hasMore`. A page can be short, or empty, while `hasMore` is `true`. * [`GET /v1/ohlcv`](/reference/rest/token-ohlcv) takes `pool`, to read one pool's candles. * [`spot.holders`](/reference/streams/spot-holders) takes `period` in its filter, the same as `GET /v1/holders`. * Frame timing: a stream connection opened with `?timing=true` receives a `timing` object on each `update`. See [Frame timing](/streams/overview#frame-timing). * Direct stream connections: [`POST /v1/stream/connect`](/reference/rest/stream-connect) returns a URL that connects to the stream without a proxy. See [Routes](/streams/overview#routes). * New value: the `proxima` wallet flag on trades and holders. * Fix: a [`spot.trending`](/reference/streams/spot-trending) update's `data` is a list of deltas, as the reference now shows. **Discovery stream, cheaper frames and self-serve keys** New channel, pricing change and dashboard * Self-serve keys: sign up in the dashboard, and create and revoke your organization's keys there. See [Get an API key](/get-started/api-keys). * New channel: [`spot.discovery`](/reference/streams/spot-discovery) streams the discovery board. Its first updates contain each column in full, ranked, and later updates contain each change, batched every 250 milliseconds. It takes the [`POST /v1/discovery`](/reference/rest/discovery) body as its filter. * A stream `update` frame costs one third of a [credit](/concepts/errors#credits), not one. * [`spot.positions`](/reference/streams/spot-positions) sends priced positions, and sends a position again, with the same `version`, when its token changes. The channel takes `throttleMs`, and sends at most one update per position each second by default. * The deprecated per-token paths still serve, with a `Deprecation` header and a `Link` to their replacement. See [Deprecated paths](/concepts/errors#deprecated-paths). * Breaking: the `fomoscan` flag, identity feed and identity source are now `fomo`. Update any filter or parser that uses `fomoscan`. * New values: ten more EVM [trader sources](/reference/streams/spot-trades#filters), from `net_principal` to `token_funded`. **One endpoint per resource** Breaking endpoint changes and a new endpoint * Breaking: every read names what it reads with comma-separated `tokens`, `wallets` and `chains` query lists, and no path carries a chain or an address. One request reads many tokens or wallets, and costs one credit for each one it names. * `GET /v1/tokens/{chain}/{address}` is now [`GET /v1/tokens`](/reference/rest/token-details), for 1 to 100 tokens. * `GET /v1/tokens/{chain}/{address}/ohlcv` is now [`GET /v1/ohlcv`](/reference/rest/token-ohlcv), and `GET /v1/tokens/{chain}/{address}/holders` is now [`GET /v1/holders`](/reference/rest/token-holders), each for 1 to 10 tokens. The holders read no longer takes `trader`; read one wallet's trades with `wallets` on `GET /v1/trades`. * `GET /v1/tokens/{chain}/{address}/trades` is merged into [`GET /v1/trades`](/reference/rest/trades), which reads by `tokens`, by `wallets`, by both, or by an `identity` feed. `trader` is replaced by `wallets`, and `side` keeps one side of a wallet's trades. * `GET /v1/wallets/balances` is now [`GET /v1/balances`](/reference/rest/wallet-balances). * Breaking: the token, candle and holder reads return a JSON array, with one element per chain that holds each requested token. Each element carries its `chain` and `address`. An unknown token returns an empty list, not a `404`. * Breaking: the balance, discovery, trending and native-price reads also return a JSON array, without the `balances`, `columns`, `deltas` and `nativePrices` wrappers. * Breaking: `base` and `arc` are no longer supported [chains](/concepts/chains), and return `UNSUPPORTED_CHAIN`. * New endpoint: [`GET /v1/portfolio`](/reference/rest/portfolio) returns the summed spot value of up to 100 wallets, per chain, with each wallet's share, and PnL stats under `include=stats`. **Logo sizes, Elysium and new values** Breaking field change, new chain and new values * Breaking: the token object's `logoUrl` is replaced by `logo`, with a `small` (16×16), `medium` (60×60) and `large` URL. Each URL returns `404` while no logo is available. This applies to [`GET /v1/tokens/{chain}/{address}`](/reference/rest/token-details), [`POST /v1/discovery`](/reference/rest/discovery), [`POST /v1/trending`](/reference/rest/trending), [`spot.tokens`](/reference/streams/spot-tokens) and [`spot.trending`](/reference/streams/spot-trending). The position token keeps `logoUrl`. * Discovery board items no longer include `decimals` or `supply`. Fields the boards do not use are sent with their zero, `false`, `null` or empty value. Request Token details for the full token. * New chain: [`elysium`](/concepts/chains), with HYPE as its native unit. Wallet balances can report a `HYPE` asset. * New trending window: `1m`, on [`POST /v1/trending`](/reference/rest/trending) and [`spot.trending`](/reference/streams/spot-trending). * New fields: `devFunding.amount` and `devFunding.fundedAt` on the token object. * New values: the `marketplace` wallet flag on trades and holders, the `arkham` identity source and the `dex_protocol_fee` fee kind. * An unknown filter name in `filters` on [`POST /v1/discovery`](/reference/rest/discovery) and [`POST /v1/trending`](/reference/rest/trending) returns `400 VALIDATION_ERROR`. **Trending** New endpoint, channel and annotation * New endpoint: [`POST /v1/trending`](/reference/rest/trending) returns tokens ranked by trending score across one or more chains. * New channel: [`spot.trending`](/reference/streams/spot-trending) sends the full board after subscribing, then each change. Each subscription uses one unit of the [address limit](/streams/filters#address-limits). * New Rust SDK method: `trending_board`, and the `SpotTrendingFilter` stream filter. * New annotation: `tax_vault` marks a token that pays its tax into a revenue vault. **Token logos** New field and a renamed field * New field: `logoUrl` on the token object, in [`GET /v1/tokens/{chain}/{address}`](/reference/rest/token-details), [`POST /v1/discovery`](/reference/rest/discovery) and [`spot.tokens`](/reference/streams/spot-tokens). It is an `http` or `https` URL, or `null` when the token has no logo. * Renamed: the position token's `image` is now `logoUrl`, in [`GET /v1/positions`](/reference/rest/positions) and [`spot.positions`](/reference/streams/spot-positions). It follows the same rule. **Native prices** New endpoint and channel * New endpoint: [`GET /v1/native-prices`](/reference/rest/native-prices) returns the latest USD price of each chain's gas asset. * New channel: [`chain.nativePrices`](/reference/streams/native-prices) streams each new price, about every 10 seconds per chain. Each subscription uses one unit of the [address limit](/streams/filters#address-limits). * New Rust SDK method: `native_prices`, and the `NativePricesFilter` stream filter. * Every field and parameter in the REST reference has a description. **Session tokens and the Rust SDK** New endpoint, error codes and SDK * New endpoint: [`POST /v1/session-tokens`](/reference/rest/session-tokens) creates a short-lived [session token](/get-started/authentication#session-tokens), so a browser can call the API without your API key. * A browser opens the stream with `metastreams.v1` and a session token as WebSocket subprotocols. * New error codes: `403 FORBIDDEN` and `403 ORIGIN_NOT_ALLOWED`. See [Error codes](/concepts/errors#error-codes). * The `401` message names a credential: an API key or a session token. * API keys no longer expire. A key stays valid until it is revoked, and close code `1008` on a key's stream means the key was revoked. * Every key belongs to an organization, which can have up to 10 active keys. * New: the [Rust SDK](/sdks/rust), a typed client for every REST endpoint and the stream. **Transfers, candle filters and credits** New channel, filters and error code * New channel: [`spot.transfers`](/reference/streams/spot-transfers) streams transfers between wallets, filtered by token, wallet, sender, recipient, amount or token state. * `spot.candles` accepts the [filter language](/streams/filters). One subscription can follow many tokens, pools and timeframes, and filter buckets by volume, trade count, price change or token state. * Each `spot.candles` update names its `chain`, `token`, `pool` and `timeframe`. * `spot.candles` takes `metric` and `denomination` beside `filters`, and accepts `throttleMs` and `closedOnly`. * `spot.candles` rejects the `chain` + `token` + `timeframe` filter. See [Unsupported filters](/reference/streams/spot-candles#unsupported-filters). * A `spot.candles` filter that names addresses costs one unit of the [address limit](/streams/filters#address-limits) per address. * An organization that has used its plan's credits for the billing period receives `402 CREDITS_EXHAUSTED`, and its open streams close with code `4402`. See [Credits](/concepts/errors#credits). **Token holders** New endpoint and channel * New endpoint: [`GET /v1/tokens/{chain}/{address}/holders`](/reference/rest/token-holders) returns a token's current holders, sorted by largest balance first, with each wallet's trading figures for the token. * New channel: [`spot.holders`](/reference/streams/spot-holders) streams a holder's row each time it changes. * The `period` parameter selects the span the figures cover: `lifetime` (the default) or `cycle` (the open round trip). **Stream filters and wallets** New filters, channels and endpoints * `spot.tokens` and `spot.trades` accept a [filter language](/streams/filters). `{}` matches every token or trade on every chain. * `spot.trades` rejects the `chain` + `token`, `chain` + `wallet` and `identity` filters. See [Unsupported filters](/reference/streams/spot-trades#unsupported-filters). * `spot.tokens` rejects `chain` and `token`; use `chains` and `tokens` instead. See [Unsupported filters](/reference/streams/spot-tokens#unsupported-filters). * Streamed trades include `flags`, `platforms` and `identities` on every subscription. * `spot.tokens` sends an `exit` frame when a token stops matching, and accepts `throttleMs`. * New channels: [`wallet.balances`](/reference/streams/wallet-balances) and [`spot.positions`](/reference/streams/spot-positions). * New endpoints: [`GET /v1/wallets/balances`](/reference/rest/wallet-balances) and [`GET /v1/positions`](/reference/rest/positions). * Stream limits are 20 connections, 20 subscriptions and 2,000 addresses per key, down from 100 connections and 100 subscriptions per connection. * The request limit is 10 per second, shared by every key of one organization, unless your plan sets another rate. It replaces 12,000 per minute per key, and no limit is counted per IP address. * A `401` response no longer includes `X-RateLimit-Remaining`. * A client frame larger than 1 MiB closes the connection. * A revoked or expired key closes its open streams with code `1008`. * Discovery accepts `dexPaid`, `excludeAnnotations`, `bundlerSupplyPercent`, `insiderSupplyPercent`, `proTraderCount` and `globalFeesPaidNative`. **Arc** New chain * Added the `arc` chain to every token, trade, candle, discovery and stream path. Arc pays gas in USDC, so `native` and `usd` values on Arc are nearly identical. **v1.0.0** First release * Token details, OHLCV candles, token trades, identity trades and discovery boards. * Live streams: `spot.trades`, `spot.candles` and `spot.tokens`. * Bearer API keys on every request and on the stream handshake. * Chains: `solana`, `base`, `bsc` and `robinhood`. # Glossary Source: https://docs.metastreams.io/resources/glossary Definitions of wallet classifications, holder groups, launchpad terms and market terms. Definitions for the wallet classifications, holder groups, launchpad terms and market terms used across the API. ## Wallet classifications These values appear in the `flags` field of trades and holders, the `flags` query parameter, and the `flags` filters of `spot.trades` and `spot.holders`. A wallet can have several flags. Time windows are counted in slots on Solana and in blocks on EVM chains, and the exact rules can differ slightly between chains. | Value | Meaning | | - | - | | `dev` | Wallet that created the token | | `sniper` | Wallet that bought the token within two slots of its first pool | | `insider` | Wallet that bought the token within three slots of its first pool. Every sniper is also an insider. | | `bundler` | Wallet that bought the token in a slot or block that contains four or more transactions on the token. Every buyer in that slot or block is flagged, the first ones included. On Solana, only trades on a launchpad count. | | `fresh` | Wallet funded less than seven days before it traded. The flag is removed once this no longer holds. | | `whale` | Wallet that made a single trade worth \$10,000 or more | | `kol` | Wallet labelled as a key opinion leader by a wallet-label source | | `pro_trader` | Wallet that has traded through a known trading terminal | | `fomo` | Wallet that has traded through the fomo.family terminal on the chain. On the [Trades](/reference/rest/trades#filters) endpoint, `fomo` also selects trades routed through the terminal. The `fomo` feed of [Trades](/reference/rest/trades#what-to-read) covers the `fomo` wallets that have a fomo.family profile. | | `phishing` | Wallet identified by a security source as a malicious actor involved in phishing, scams, rug pulls or hacks | A holder's `flags` can also include `liquidity_pool` for a pool, `locker` for a token locker and `system` for a system account. A trader's or holder's `flags` can include `marketplace` for a wallet listed for sale on a wallet marketplace, and `proxima` for a wallet that traded through a transaction built by the Proxima bundler. Neither flag is removed later. No `flags` filter accepts these values. ## Holder groups A token's `holders` object reports the share of supply each group currently holds, on a 0–100 scale, and the number of wallets that have ever belonged to the group on that token. | Field | Group | | - | - | | `count` | Number of wallets that hold the token now | | `top10Pct` | 10 largest current holders. Can exceed 100 when supply data drifts. | | `devPct` | Token creator | | `sniperPct`, `sniperCount` | Wallets flagged `sniper` | | `bundlerPct`, `bundlerCount` | Wallets flagged `bundler` | | `insiderPct`, `insiderCount` | Wallets flagged `insider` | | `freshWalletPct`, `freshWalletCount` | Wallets flagged `fresh` | | `proTraderPct`, `proTraderCount` | Wallets flagged `pro_trader` | | `fomoPct`, `fomoCount` | Wallets flagged `fomo` | | `phishingPct`, `phishingCount` | Wallets flagged `phishing` | | `fundedByCexPct` | Share of current holders, not of supply, that a known exchange funded | Each `Count` field includes every wallet that has ever had the flag on the token, so it never decreases. Pools, lockers and system accounts are not counted as holders. ## Launchpad terms | Term | Meaning | | - | - | | Launchpad | Venue that launches new tokens and sells them from a bonding curve, such as Pump.fun. A token's `launchpad` field holds its name. | | Bonding curve | Launchpad's pricing contract, whose price rises as the curve fills | | `bondingCurvePct` | Bonding curve progress, 0–100 | | Graduation | Moment a token leaves its launchpad and its liquidity moves to a regular pool. `graduatedAt` is the time of graduation, and `graduatedToPool` and `graduatedToDex` identify the destination. | | New pairs | Launchpad tokens below 40% bonding-curve progress | | Graduating | Launchpad tokens at 40% bonding-curve progress or more that have not yet graduated | | Graduated | Launchpad tokens that have graduated or have no bonding-curve reading | ## Market terms | Term | Meaning | | - | - | | Native unit | Chain's gas asset: SOL on Solana, BNB on BNB Smart Chain, ETH on Robinhood Chain, HYPE on Elysium | | Anchor (quote asset) | Asset that a token's deepest pool prices it against, such as WSOL or USDC, given by `anchorSymbol` and `anchorAddress` | | Market cap | Price multiplied by total supply | | Liquidity | Value held in the token's pools | # Support Source: https://docs.metastreams.io/resources/support How to contact support and what details to include. Contact the support team in the [Telegram developer group](https://t.me/metastreamsdevs) or at [contact@metastreams.io](mailto:contact@metastreams.io). ## Contact details Include the following in your message: * **The request ID.** Every response includes an `X-Request-ID` header, which lets us find the exact request. * **Your key's prefix**, such as `meta_9tK2vQx`. Never send the full key. * **What you sent:** the method, the path and query, and the body or subscribe frame. * **What you received:** the status, the error `code` and `message`, or the stream close code. * **When it happened,** with the time zone. ## Before contacting support | Symptom | What to check | | - | - | | `401 UNAUTHORIZED` | [Authentication](/get-started/authentication): the header form, and whether the key was revoked | | `429 RATE_LIMITED` | [Limits](/concepts/errors#limits): a retry loop without backoff, or leaked stream connections | | `400 VALIDATION_ERROR` | The `details` list names the field and the problem | | Stream closes with `4008` | Your client is reading too slowly. See [Close codes](/streams/overview#close-codes). | | A number looks wrong | [Response format](/concepts/reading-responses): `native` and `usd` prices, percentages on 0–100, and decimal strings | ## Security issues Report a suspected security issue, including a leaked key, to [security@metastreams.io](mailto:security@metastreams.io). To disable a leaked key, see [Revoke a leaked key](/get-started/api-keys#revoke-a-leaked-key). # Rust SDK Source: https://docs.metastreams.io/sdks/rust A typed Rust client for the REST endpoints and the WebSocket stream. The Rust SDK is a typed client for the `/v1` REST endpoints and the `/v1/stream` WebSocket. It consists of two crates, published from the [`metastreams-sdk`](https://github.com/metastreams/metastreams-sdk) repository: | Crate | Contents | | - | - | | `metastreams-types` | Every request and response of the API as serde types, without an HTTP or WebSocket dependency | | `metastreams-sdk` | `MetastreamsProvider`, with one method per REST endpoint listed under [Methods](#methods), and `StreamConnection`, with typed stream subscriptions. It re-exports the types crate as `metastreams_sdk::types`. | The API uses the same types, so they match its responses field for field. ## Installation The crates are not on crates.io yet. Add them as a git dependency pinned to a tag. This page describes version 0.4.0: ```toml Cargo.toml theme={null} [dependencies] metastreams-sdk = { git = "https://github.com/metastreams/metastreams-sdk", tag = "v0.4.0" } tokio = { version = "1", features = ["rt-multi-thread", "macros"] } futures = "0.3" # StreamExt, for subscriptions ``` Each release is tagged on the repository; its notes list the changes. To track a commit between releases, pin a `rev` instead of a `tag`. The minimum supported Rust version is 1.93. TLS uses rustls with the webpki root certificates, so you don't install a crypto provider yourself. ## Provider `MetastreamsProvider::new(key)` creates a client for the production API, and `MetastreamsProvider::new_with_base_url(key, url)` creates one for another origin. The provider implements `Clone`, and its `Debug` output hides the key. Each method sends one request, with a 30-second request timeout and a 10-second connect timeout. A method never retries. ```rust theme={null} use metastreams_sdk::types::token::TokensQuery; use metastreams_sdk::{MetastreamsProvider, MultiChainAddress, SpotChain}; #[tokio::main] async fn main() -> Result<(), Box> { let provider = MetastreamsProvider::new(std::env::var("API_KEY")?)?; let bonk: MultiChainAddress = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263".parse()?; let query = TokensQuery { tokens: vec![bonk], chains: Some(vec![SpotChain::Solana]) }; for token in provider.tokens(&query).await? { println!("{} {:?}", token.card.symbol, token.card.price.usd); } Ok(()) } ``` The examples in the SDK repository read the key from `METASTREAMS_API_KEY`. The samples on this page read it from `API_KEY`, as the rest of these docs do. ### Methods | Method | Endpoint | Returns | | - | - | - | | `tokens(&TokensQuery)` | [`GET /v1/tokens`](/reference/rest/token-details) | `Vec` | | `ohlcv(&CandleSeriesQuery)` | [`GET /v1/ohlcv`](/reference/rest/token-ohlcv) | `Vec` | | `trades(&TradesQuery)` | [`GET /v1/trades`](/reference/rest/trades) | `UiSpotTrades` | | `holders(&HolderSeriesQuery)` | [`GET /v1/holders`](/reference/rest/token-holders) | `Vec` | | `wallet_balances(&WalletBalancesQuery)` | [`GET /v1/balances`](/reference/rest/wallet-balances) | `UiWalletBalances` | | `wallet_portfolio(&PortfolioQuery)` | [`GET /v1/portfolio`](/reference/rest/portfolio) | `UiPortfolioResponse` | | `positions(&PositionsQuery)` | [`GET /v1/positions`](/reference/rest/positions) | `UiSpotPositions` | | `native_prices(&NativePricesQuery)` | [`GET /v1/native-prices`](/reference/rest/native-prices) | `Vec` | | `discovery_board(&SpotPulseSubscriptionConfig)` | [`POST /v1/discovery`](/reference/rest/discovery) | `Vec` | | `trending_board(&SpotTrendingFilter)` | [`POST /v1/trending`](/reference/rest/trending) | `Vec` | | `session_token_create(&CreateSessionTokenRequest)` | [`POST /v1/session-tokens`](/reference/rest/session-tokens) | `UiSessionToken` | | `connect()` | [`POST /v1/stream/connect`](/reference/rest/stream-connect), then the [stream](/streams/overview) on the direct route | `StreamConnection` | | `connect_via(route)` | The [stream](/streams/overview) on the chosen [route](#routes) | `StreamConnection` | When a query leaves `chains` at `None`, the SDK sends every chain it knows. Version 0.4.0 has no method for `GET /v1/search` or `POST /v1/trades`. Call those endpoints over HTTP, as their reference pages show. Set `chains` explicitly on a stream filter, so the stream sends only chains this version can decode. A `UiSpotToken` contains the token card in its `card` field, so the symbol is `token.card.symbol`. `decimals` and `supply` are fields of the token itself. ### Pagination A paginated response carries `has_more` and `next_cursor`. Copy `next_cursor` into the query to read the next page: ```rust theme={null} use metastreams_sdk::types::trade::TradesQuery; use metastreams_sdk::{MetastreamsProvider, MultiChainAddress, SpotChain}; #[tokio::main] async fn main() -> Result<(), Box> { let provider = MetastreamsProvider::new(std::env::var("API_KEY")?)?; let bonk: MultiChainAddress = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263".parse()?; let mut query = TradesQuery { tokens: Some(vec![bonk]), chains: Some(vec![SpotChain::Solana]), limit: Some(100), ..Default::default() }; loop { let page = provider.trades(&query).await?; for trade in &page.trades { println!("{} {:?} {:?}", trade.id, trade.side, trade.volume.usd); } if !page.has_more { break; } query.cursor = page.next_cursor; } Ok(()) } ``` ### Session tokens A backend creates a [session token](/get-started/authentication#session-tokens) for a browser user with `session_token_create`: ```rust theme={null} use metastreams_sdk::MetastreamsProvider; use metastreams_sdk::types::session::CreateSessionTokenRequest; #[tokio::main] async fn main() -> Result<(), Box> { let provider = MetastreamsProvider::new(std::env::var("API_KEY")?)?; let request = CreateSessionTokenRequest { origins: vec!["https://app.example.com".into()], subject: Some("user-42".into()), ttl_seconds: Some(900), }; let session = provider.session_token_create(&request).await?; println!("expires at {}", session.expires_at.0); Ok(()) } ``` ## Streams `provider.connect()` opens one WebSocket, which carries many subscriptions. The filter type selects the channel and the payload types: | Filter | Channel | `Exit` payload | | - | - | - | | `TradeFilter` | [`spot.trades`](/reference/streams/spot-trades) | None | | `TransferFilter` | [`spot.transfers`](/reference/streams/spot-transfers) | None | | `CandleFilter` | [`spot.candles`](/reference/streams/spot-candles) | None | | `TokenFilter` | [`spot.tokens`](/reference/streams/spot-tokens) | `UiTokenExit` | | `WalletBalancesFilter` | [`wallet.balances`](/reference/streams/wallet-balances) | None | | `SpotPositionsFilter` | [`spot.positions`](/reference/streams/spot-positions) | None | | `SpotHoldersFilter` | [`spot.holders`](/reference/streams/spot-holders) | None | | `NativePricesFilter` | [`chain.nativePrices`](/reference/streams/native-prices) | None | | `SpotTrendingFilter` | [`spot.trending`](/reference/streams/spot-trending) | None | | `SpotPulseSubscriptionConfig` | [`spot.discovery`](/reference/streams/spot-discovery) | None | `TradeFilter`, `TransferFilter`, `CandleFilter` and `TokenFilter` are in `metastreams_sdk::types::filter`. `SpotTrendingFilter` is in `metastreams_sdk::types::trending`, `SpotPulseSubscriptionConfig` is in `metastreams_sdk::types::discovery`, and the other filter types are in `metastreams_sdk::types::stream`. Each subscription is a `futures::Stream` of `Event`s. An `Event::Update` contains one payload, and an `Event::Exit` means a token the subscription matched no longer matches, or that the subscription stopped tracking it at its [10,000-token limit](/concepts/errors#limits). A channel without exits uses an empty exit type, so its `Exit` arm is `match exit {}`. ```rust theme={null} use futures::StreamExt; use metastreams_sdk::types::filter::TradeFilter; use metastreams_sdk::{Event, MetastreamsProvider, MultiChainAddress, SpotChain}; #[tokio::main] async fn main() -> Result<(), Box> { let provider = MetastreamsProvider::new(std::env::var("API_KEY")?)?; let bonk: MultiChainAddress = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263".parse()?; let connection = provider.connect().await?; let filter = TradeFilter { chains: vec![SpotChain::Solana], tokens: Some(vec![bonk]), ..Default::default() }; let mut trades = connection.subscribe(&filter).await?; while let Some(event) = trades.next().await { match event? { Event::Update(trade) => println!("{:?} {} {}", trade.side, trade.amount, trade.symbol), Event::Exit(exit) => match exit {}, } } Ok(()) } ``` ### Routes `provider.connect()` takes the [direct route](/streams/overview#routes): it sends `POST /v1/stream/connect`, then opens the connection on the returned URL. It falls back to the proxied route, `wss://api.metastreams.io/v1/stream`, in these cases: * The connect request returns `404` or fails for any reason other than `401`, `402` or `429`. * The direct handshake fails or takes longer than 3 seconds. A `401`, `402` or `429` on the connect request is returned at once. On a plan without streams, the connect request returns `403`, the SDK falls back to the proxied route, and that handshake fails with `403` too. To always use the proxied route, call `connect_via`: ```rust theme={null} use metastreams_sdk::StreamRoute; let connection = provider.connect_via(StreamRoute::Proxied).await?; ``` `StreamRoute::Direct` is what `connect()` uses. Subscriptions work the same on both routes. ### Subscription options `subscribe_throttled(&filter, Duration)` sets [`throttleMs`](/streams/overview#client-messages) on a `TokenFilter` or `CandleFilter`, rounded up to whole milliseconds. The SDK cannot set `throttleMs` on a `SpotPositionsFilter`, so a positions subscription gets the server's default of one update per second. Exits are never throttled. `subscribe_candles(&CandleFilter, CandleOptions)` also sets the candle `metric`, `denomination` and `closed_only`. ### Subscription lifecycle The stream sends no snapshot, except on `spot.trending` and `spot.discovery`, whose first updates contain the full board. On other channels, read the REST endpoint after `subscribe` returns, as [Initial snapshot](/streams/overview#initial-snapshot) describes. `id()` returns the subscription ID the server assigned, and dropping a subscription unsubscribes it. A subscription ends with one `Err(MetastreamsError::Closed(reason))`, followed by `None`. A payload that fails to decode yields `Err(MetastreamsError::FrameDecode { .. })`, and the subscription continues. `connection.closed()` resolves to the `CloseReason` when the socket closes. `connection.close()` closes the socket normally, and each subscription then ends with `CloseReason::Client`. The SDK sends a ping every 15 seconds and treats the socket as lost after 45 seconds without a frame. Each subscription buffers up to 1,024 unread events. When the buffer is full, the SDK closes that subscription with `CloseReason::Lagged` and leaves the others open. ### Close reasons | `CloseReason` | Cause | Transient | | - | - | - | | `ServerRestarting` | Close code `1001` | Yes | | `SlowConsumer` | Close code `4008` | Yes | | `KeyRevoked` | Close code `1008` | No | | `CreditsExhausted` | Close code `4402` | No | | `Lagged` | The subscription's buffer filled | Yes | | `Lost(LostCause)` | The socket ended without a close code, or went silent | Yes | | `Other { code, reason }` | A close code this SDK version does not name, including `4403` when the organization's plan does not include streams | Yes, except after `4403` | | `Failed(Box)` | The server ended only this subscription, with an `error` frame that identifies it | Only when the code is `INTERNAL_ERROR` or `SERVICE_UNAVAILABLE` | | `Client` | You closed the connection | Yes | ### Reconnection The SDK does not reconnect. Subscriptions end with their connection, and missed updates are not replayed. After a transient close, connect, subscribe again and re-read the snapshot from REST. Reconnect at once after `ServerRestarting`, and back off after other transient reasons. After `KeyRevoked`, `CreditsExhausted` or an `Other` close with code `4403`, stop. See [Reconnection](/streams/overview#reconnection). ## Errors Every method returns `metastreams_sdk::Result`, whose error is `MetastreamsError`: | Variant | Cause | | - | - | | `Api { status, error, request_id }` | The API refused the request with an [error envelope](/concepts/errors). Match on `error.code`, never on `error.message`. | | `RateLimited { retry_after, request_id }` | A `429`, including a stream handshake past the connection limit, with the `Retry-After` wait | | `Rejected { channel, error }` | The server rejected a subscribe request with an `error` frame | | `Closed(CloseReason)` | A subscription ended | | `FrameDecode { channel, source }` | A stream payload did not decode | | `Http`, `WebSocket` | A transport failure | | `Decode`, `Unexpected` | A response body the SDK could not read | | `Url`, `UnsupportedScheme`, `InvalidKey` | The base URL or the key cannot be used | `error.code` is an `ErrorCode` from `metastreams_sdk::types::error`. A code that this SDK version does not know becomes `ErrorCode::Unknown`. `is_transient()` reports whether the same call can succeed later: a transport failure, a `429`, a `5xx`, or a transient close. The example below retries transient errors and waits for `Retry-After` on a `429`: ```rust theme={null} use std::time::Duration; use metastreams_sdk::types::token::{TokensQuery, UiSpotToken}; use metastreams_sdk::{MetastreamsError, MetastreamsProvider}; async fn tokens_with_retries( provider: &MetastreamsProvider, query: &TokensQuery, attempts: u32, ) -> metastreams_sdk::Result> { let mut attempt = 0; loop { match provider.tokens(query).await { Err(error) if error.is_transient() && attempt + 1 < attempts => { let delay = match &error { MetastreamsError::RateLimited { retry_after: Some(wait), .. } => *wait, _ => Duration::from_millis((1000 * 2u64.pow(attempt.min(5))).min(30_000)), }; tokio::time::sleep(delay).await; attempt += 1; } result => return result, } } } ``` The sample also needs the `time` feature of `tokio`. # Filtering streams Source: https://docs.metastreams.io/streams/filters How spot.tokens, spot.trades, spot.transfers and spot.candles filters combine keys, lists and ranges, and how filters count against address limits. [`spot.tokens`](/reference/streams/spot-tokens), [`spot.trades`](/reference/streams/spot-trades), [`spot.transfers`](/reference/streams/spot-transfers) and [`spot.candles`](/reference/streams/spot-candles) use the same filter language. This page describes the rules these channels share; each channel page lists its own keys. ## Combining filters * `{}` matches everything: every token, trade, transfer or candle bucket, on every chain. Each key you add narrows the set. * An item must match every key, but within a list, one matching value is enough. * To combine keys with OR, open a second subscription. * `exclude` removes an item that matches any of its values, even when every other key matches it. ```jsonc theme={null} // A spot.tokens filter: Solana or BSC tokens, launched on pump.fun or four.meme, with no mayhem mode. { "chains": ["solana", "bsc"], "protocols": ["pumpfun", "four_meme"], "exclude": { "annotations": ["mayhem_mode"] } } ``` ## Ranges A range is `{ "min": …, "max": … }`. Both bounds are inclusive, and you can omit either one. * Money values and percentages are [decimal strings](/concepts/reading-responses#decimals), such as `"100000"`. On these four channels, percentage keys end in `Pct`. The `spot.trending` and `spot.discovery` filters take the [discovery filter](/reference/rest/discovery) keys instead, such as `devHoldingPercent`. * Counts, basis points and milliseconds are integers, such as `3600000`. * Percentages use the same 0–100 scale as the payload. * Every `…Usd` key has a `…Native` counterpart, denominated in the chain's gas asset. * A `min` greater than `max` is rejected. **An unknown value never matches a range.** A price, market cap, liquidity, supply or holder count of zero means the value has not been measured yet, so it does not match any range. For example, a filter of `{ "max": "5000000" }` does not match a token with no market cap. ## Names and addresses * EVM addresses are case-insensitive. Solana addresses must match exactly. * Launchpad, DEX and platform names are case-insensitive. An unknown name is accepted but matches nothing, so a misspelled venue produces no updates and no error. * An unknown chain, flag, stage, anchor, annotation, social or funding kind is rejected. * Each address in a top-level `tokens`, `wallets`, `pools`, `senders` or `recipients` list must belong to a chain included in `chains`. When `chains` is omitted, every chain is included, so a single EVM address matches on every EVM chain. * A list can contain at most 100 values, and `tokens` on `spot.tokens` takes 1 to 100. The top-level address lists on `spot.trades`, `spot.transfers` and `spot.candles` have no limit of their own; only the address limit applies. ## Address limits Each API key can hold 20 subscriptions across all of its connections. Those subscriptions share a single limit of 2,000 addresses. | Subscription | Cost | | - | - | | A `spot.tokens`, `spot.trades`, `spot.transfers` or `spot.candles` filter that includes addresses | One per address in its top-level `tokens`, `wallets`, `pools`, `senders` or `recipients` lists. An address repeated in one list counts once; an address in two lists counts twice. | | A `spot.tokens`, `spot.trades`, `spot.transfers` or `spot.candles` filter with no addresses | One | | `spot.holders` | One | | `chain.nativePrices`, `spot.trending` or `spot.discovery` | One | | `wallet.balances` or `spot.positions` | One per wallet | Other address keys do not count against the limit: `devAddresses`, `fundingAddresses`, every `exclude` list, and the lists inside a `token` key. Each subscription counts its own addresses, so two subscriptions that name the same address use two units. A subscribe request that exceeds either limit returns a `VALIDATION_ERROR` whose message identifies the limit. When closing subscriptions would free capacity, the message also reports the key's current usage. ## Errors A rejected filter returns an `error` frame, and the connection stays open. | Code | When | | - | - | | `UNSUPPORTED_CHAIN` | Unsupported [chain](/concepts/chains) | | `VALIDATION_ERROR` | An unknown key, a value of the wrong type or outside the allowed set, a range with `min` above `max`, a list over its limit, an address in the wrong format, or an exceeded subscription or address limit | The error's `details[].field` is the path of the failing key, such as `stats.5m.buys`, `exclude.wallets` or `flags[0]`. An error from the subscription limit has the field `channel`, and an error from the address limit has the field `filters`. ```json theme={null} { "type": "error", "id": "screener", "code": "VALIDATION_ERROR", "message": "One or more parameters are invalid.", "details": [{ "field": "stats.5m.buyz", "message": "No filter key is named `buyz`." }] } ``` # WebSocket streams Source: https://docs.metastreams.io/streams/overview Open a WebSocket connection, subscribe to channels, and reconnect after the connection closes. A single WebSocket connection streams trades, transfers, candles, tokens, wallet balances, positions, holders, native prices, trending boards and the discovery board to you as they change. ```text theme={null} URL wss://api.metastreams.io/v1/stream or the direct URL from POST /v1/stream/connect (see Routes) Auth Authorization: Bearer $API_KEY (handshake header) or subprotocols metastreams.v1 + session token (browsers) Frames JSON text; client frames up to 1 MiB Per API key 20 open connections, 20 subscriptions and 2,000 addresses across all of them Billing one third of a credit per update frame; the handshake costs no credit Timing ?timing=true on the handshake adds send times to each update ``` ## Connect ```typescript Node.js (ws) theme={null} import WebSocket from "ws"; const socket = new WebSocket("wss://api.metastreams.io/v1/stream", { headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); // A refused handshake arrives as an `error` event. Without a listener, Node exits. socket.on("error", (error) => console.error("stream error:", error.message)); ``` ```rust Rust (tokio-tungstenite) theme={null} use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; #[tokio::main] async fn main() -> Result<(), Box> { let mut request = "wss://api.metastreams.io/v1/stream".into_client_request()?; let auth = format!("Bearer {}", std::env::var("API_KEY")?); request.headers_mut().insert("Authorization", auth.parse()?); // A refused handshake returns `Error::Http` with the response status. let (socket, _) = connect_async(request).await?; Ok(()) } ``` Browsers cannot set the `Authorization` header on a WebSocket. A browser instead passes `metastreams.v1` and a [session token](/get-started/authentication#session-tokens) as subprotocols, and the server selects `metastreams.v1`. An API key is not accepted in the subprotocol list. ```typescript Browser theme={null} const socket = new WebSocket("wss://api.metastreams.io/v1/stream", ["metastreams.v1", sessionToken]); ``` Each session token has its own 20 connections, 20 subscriptions and 2,000 addresses, counted separately from its key. All the session tokens of one key share a limit of 10,000 open connections. | Handshake response | Cause | Retry | | - | - | - | | `400 VALIDATION_ERROR` | The subprotocol list includes a session token but not `metastreams.v1` | No | | `401 UNAUTHORIZED` | Missing or invalid key, or an expired or invalid session token | No. For a session token, request a new one from your backend. | | `402 CREDITS_EXHAUSTED` | The organization has used the credits its plan includes this billing period. See [Credits](/concepts/errors#credits). | Not until the next billing period or a plan change | | `403 FORBIDDEN` | The organization's plan does not include streams. The free plan has none. | Not until the organization moves to a plan with streams | | `403 ORIGIN_NOT_ALLOWED` | A session token used from an origin that the token does not allow, or without an `Origin` header | No | | `429 RATE_LIMITED` | The key or session token already has 20 open connections, the key's session tokens already have 10,000, or the request budget is used up | After `Retry-After` | | `503 SERVICE_UNAVAILABLE` | The key could not be verified | With backoff | | Plain-text `4xx` | Missing WebSocket upgrade headers | No | ## Routes A connection can use one of two routes. Frames, limits and billing are the same on both. | Route | How to connect | Credential | | - | - | - | | Proxied | Open `wss://api.metastreams.io/v1/stream`, as in [Connect](#connect). A proxy relays the connection to the server. | API key or session token | | Direct | Send [`POST /v1/stream/connect`](/reference/rest/stream-connect), then open the `url` it returns within 30 seconds | API key for the request, then the returned `metaconnect_` token for the handshake | The direct route connects to the server with no proxy between. The connect request costs no credit, and one token opens connections, within the key's connection limit, until it expires. Browsers and session tokens use the proxied route only. ```typescript Node.js (ws) theme={null} import WebSocket from "ws"; const response = await fetch("https://api.metastreams.io/v1/stream/connect", { method: "POST", headers: { Authorization: `Bearer ${process.env.API_KEY}` }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const { url, token } = await response.json(); const socket = new WebSocket(url, { headers: { Authorization: `Bearer ${token}` } }); socket.on("error", (error) => console.error("stream error:", error.message)); ``` ```rust Rust (reqwest, tokio-tungstenite) theme={null} use serde_json::Value; use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; #[tokio::main] async fn main() -> Result<(), Box> { let answer: Value = reqwest::Client::new() .post("https://api.metastreams.io/v1/stream/connect") .bearer_auth(std::env::var("API_KEY")?) .send() .await? .error_for_status()? .json() .await?; let mut request = answer["url"].as_str().ok_or("no url")?.into_client_request()?; let token = answer["token"].as_str().ok_or("no token")?; request.headers_mut().insert("Authorization", format!("Bearer {token}").parse()?); let (socket, _) = connect_async(request).await?; Ok(()) } ``` When the connect request returns `404 NOT_FOUND`, no direct URL is available; use the proxied route. When it or the direct handshake fails for another reason, the proxied route is a safe fallback. A `401`, `402`, `403` or `429` is returned on both routes, so do not retry it on the other one. Neither route is faster from every location. Measure both from where your client runs. The [Rust SDK](/sdks/rust#routes) takes the direct route by default and falls back to the proxied route on its own. ## Channels | Channel | `filters` | `data` in each update | | - | - | - | | [`spot.trades`](/reference/streams/spot-trades) | `{ chains?, tokens?, wallets?, pools?, flags?, … }` | One [trade](/reference/rest/trades) | | [`spot.transfers`](/reference/streams/spot-transfers) | `{ chains?, tokens?, wallets?, senders?, recipients?, … }` | One transfer between two wallets | | [`spot.candles`](/reference/streams/spot-candles) | `{ chains?, tokens?, pools?, timeframes?, … }` | One [candle](/reference/rest/token-ohlcv) in its current state, with its `chain`, `token`, `pool` and `timeframe` | | [`spot.tokens`](/reference/streams/spot-tokens) | `{ chains?, tokens?, protocols?, marketCapUsd?, … }` | One [token](/reference/rest/token-details) | | [`wallet.balances`](/reference/streams/wallet-balances) | `{ chain, wallets }` | One wallet's [balance](/reference/rest/wallet-balances) of one asset | | [`spot.positions`](/reference/streams/spot-positions) | `{ chain, wallets }` | One wallet's [position](/reference/rest/positions) in one token | | [`spot.holders`](/reference/streams/spot-holders) | `{ chain, token, flags?, period? }` | One holder's [row](/reference/rest/token-holders) on one token, without `rank` | | [`chain.nativePrices`](/reference/streams/native-prices) | `{ chains? }` | The USD [price](/reference/rest/native-prices) of one chain's gas asset | | [`spot.trending`](/reference/streams/spot-trending) | `{ chains, window?, limit?, filters? }` | The changed rows of one [trending board](/reference/rest/trending) | | [`spot.discovery`](/reference/streams/spot-discovery) | `{ chains, newPairs?, graduating?, graduated? }` | The changed rows of one column of the [discovery board](/reference/rest/discovery) | * `?` marks an optional key, so `{}` matches every trade, transfer, candle or token, and `…` means the channel takes more keys. Each channel page lists all of them. * `spot.trades`, `spot.transfers`, `spot.candles` and `spot.tokens` share one filter language, described in [Filtering streams](/streams/filters). * `spot.tokens` also sends an `exit` frame when a token stops matching. `spot.tokens`, `spot.candles` and `spot.positions` accept `throttleMs` alongside `filters`, up to 60,000. Each channel page gives its default. `spot.candles` also accepts `metric`, `denomination` and `closedOnly`. * No REST endpoint returns transfers. Every other `data` object has the same shape as the matching REST response, with two exceptions. A streamed candle also includes its `chain`, `token`, `pool` and `timeframe`. A streamed holder has no `rank`. A streamed position is priced the same way as `GET /v1/positions`. ## Frames ### Client messages ```jsonc theme={null} // Open a subscription. `id` is optional; the ack, or an error about this subscribe, echoes it. { "action": "subscribe", "channel": "spot.trades", "filters": { "chains": ["solana"], "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] }, "id": "r1" } // `throttleMs` is optional, and only `spot.tokens`, `spot.candles` and `spot.positions` take it. { "action": "subscribe", "channel": "spot.tokens", "filters": { "chains": ["solana"] }, "throttleMs": 1000 } // `metric`, `denomination` and `closedOnly` are optional, and only `spot.candles` takes them. { "action": "subscribe", "channel": "spot.candles", "filters": { "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"], "timeframes": ["1m"] }, "metric": "price", "closedOnly": true } // Close one subscription. { "action": "unsubscribe", "channel": "spot.trades", "subscriptionId": "5f0c6d1e-8a2b-4c3d-9e4f-1a2b3c4d5e6f" } // Close every subscription on a channel. The ack carries no `subscriptionId`. { "action": "unsubscribe", "channel": "spot.trades" } // Check the connection is alive. { "action": "ping" } ``` ### Server messages ```jsonc theme={null} // A subscribe or unsubscribe took effect. { "type": "ack", "channel": "spot.trades", "subscriptionId": "5f0c6d1e-8a2b-4c3d-9e4f-1a2b3c4d5e6f", "id": "r1", "status": "success", "message": "subscribe successful" } // One payload for one subscription. { "type": "update", "channel": "spot.trades", "subscriptionId": "5f0c6d1e-8a2b-4c3d-9e4f-1a2b3c4d5e6f", "data": { } } // A token stopped matching a `spot.tokens` filter. { "type": "exit", "channel": "spot.tokens", "subscriptionId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "data": { "chain": "solana", "address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" } } // A frame was rejected. With a `subscriptionId`, that subscription has ended. { "type": "error", "id": "r1", "code": "VALIDATION_ERROR", "message": "One or more parameters are invalid.", "details": [ { "field": "throttleMs", "message": "`spot.trades` takes no `throttleMs`." } ] } // The answer to a ping. { "type": "pong" } ``` * Use `subscriptionId` to route updates and to unsubscribe. The subscribe ack returns it, and every update includes it. * The ack for a subscription always arrives before its first update, and the ack for an unsubscribe arrives after that subscription's last update. ## Frame timing Add `timing=true` to the handshake URL, such as `wss://api.metastreams.io/v1/stream?timing=true`, to measure delivery latency. Every `update` frame on that connection then includes a `timing` object beside `data`. Other frames never include it, and it costs no credit. ```json theme={null} { "type": "update", "channel": "spot.trades", "subscriptionId": "5f0c6d1e-8a2b-4c3d-9e4f-1a2b3c4d5e6f", "data": { }, "timing": { "receivedAt": 1789632015081, "sentAt": 1789632015093 } } ``` | Field | Description | | - | - | | `sentAt` | Time the server started to write the frame, in Unix milliseconds. Always present. | | `receivedAt` | Time the data was first read from the chain, in Unix milliseconds. Present on `spot.trades`, `spot.transfers`, `spot.tokens`, `spot.candles`, `spot.holders`, `wallet.balances` and `chain.nativePrices` updates when the time is known. | `sentAt` minus `receivedAt` is the server's processing time, plus any delay that `throttleMs` or `closedOnly` adds. Compare `sentAt` with the time your client reads the frame to measure the network leg. The two clocks are not synchronized, so treat a small negative difference as zero. The parameter works on both [routes](#routes). ## Initial snapshot A stream only sends changes that happen after you subscribe. `spot.trending` and `spot.discovery` are the exceptions: their first updates contain the full board. To build a complete view on any other channel: 1. **Subscribe** and buffer the updates. 2. **Read the snapshot** from the REST endpoint, with the parameters that match the stream: `hideLowLiquidity=false` on [`GET /v1/positions`](/reference/rest/positions), because the stream includes low-liquidity positions, and the subscription's `period`, `lifetime` by default, on [`GET /v1/holders`](/reference/rest/token-holders), with a `limit` of up to 150. 3. **Apply** the buffered updates, and then each new update, on top of the snapshot. Repeat all three steps after every reconnect. Use the key and rule below to merge each object type. | Object | Key | Merge rule | | - | - | - | | Trade | `id` | Keep the first copy and skip a repeated `id`. | | Candle | `chain` + `token` + `pool` + `timeframe` + `time` | Keep the latest copy and append a new key. | | Token | `chain` + `address` | Keep the later `updatedAt`, and drop the token on an `exit`. | | Balance | `chain` + `wallet` + `asset` | Keep the higher `blockNumber`, then the higher `txIndex`. | | Position | `chain` + `walletAddress` + token address | Keep an update whose `version` is equal to or higher than yours. See [`spot.positions`](/reference/streams/spot-positions#message-format). | | Holder | `chain` + token + `address` | Keep the later update, and drop a holder whose `balance` is `0`. | > [!NOTE] > > A subscription survives a server-side interruption, but missed updates are not replayed and no frame marks the gap. If you need every row, also re-read the snapshot on a schedule. ## Errors When a frame is rejected, the server returns an `error` frame with a REST [error code](/concepts/errors), and the connection stays open. A rejected frame's error has no `subscriptionId`. An `error` frame with a `subscriptionId` ends that subscription and frees its slot and addresses. No public channel sends one, but a client can handle it: drop the subscription's state, and subscribe again only when the code is `INTERNAL_ERROR` or `SERVICE_UNAVAILABLE`. | Code | Cause | | - | - | | `VALIDATION_ERROR` | The frame is not JSON, has no known `action`, or has a missing or mistyped field; the filters do not fit the channel; or the key already has 20 subscriptions or has used up its [address limit](/streams/filters#address-limits) | | `UNSUPPORTED_CHAIN` | A chain in the filter is not [supported](/concepts/chains) | | `NOT_FOUND` | The channel does not exist, or the unsubscribe refers to a subscription that this connection does not hold | The error includes the `id` of the frame that caused it. It has no `id` when that frame is not JSON, has no string `id`, or is an unsubscribe. ## Heartbeat Send `{"action": "ping"}` about every 30 seconds. Reconnect when no `pong` has arrived for 45 seconds. The examples below check this at each ping. The server never closes an idle connection and sends no pings of its own. ## Close codes | Close code | Cause | Action | | - | - | - | | `1001` | `server restarting`, for example during maintenance | Reconnect immediately. | | `1008` | The key was revoked, with the reason `key revoked`, or the session token that opened the connection expired, with the reason `token expired`. A revoked key closes its connections within about 30 seconds. | After `key revoked`, stop and do not reuse the key. After `token expired`, request a new token from your backend and reconnect. | | `4402` | `credits exhausted`: the organization has used the credits its plan includes this billing period. The cutoff applies within about 10 seconds. | Stop. The handshake returns `402` until the next billing period or a plan change. | | `4403` | `plan excludes streams`: the organization moved to a plan without streams, such as the free plan. The close applies within about 30 seconds of the move. | Stop. The handshake returns `403` until the organization moves to a plan with streams. | | `4008` | `slow consumer`: 1,024 frames were waiting to be sent, or one frame waited 10 seconds | Reconnect, and read faster or subscribe to less. | | None | You sent a frame larger than 1 MiB, or your client read no close frame within 5 seconds | Reconnect, and send smaller frames. | | Any other | The network dropped or the connection failed | Reconnect with backoff. | Subscriptions do not survive a reconnect. Send your subscribe frames again, then fill the gap with a fresh [snapshot](#initial-snapshot). ### Reconnection The examples below resubscribe after every close. They reconnect immediately after `1001`, back off after any other close, and stop on `401`, `402`, `403`, `1008`, `4402` or `4403`. They connect with an API key. A browser client with a session token requests a new token from its backend and reconnects after a `1008` close with the reason `token expired`. ```typescript Node.js (ws) theme={null} import WebSocket from "ws"; const URL = "wss://api.metastreams.io/v1/stream"; const subscriptions = [ { action: "subscribe", channel: "spot.trades", filters: { chains: ["solana"], tokens: ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] } }, ]; function connect(attempt = 0) { const socket = new WebSocket(URL, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }); let lastPong = Date.now(); let heartbeat: NodeJS.Timeout | undefined; let unauthorized = false; // A refused handshake arrives here too. Without an `error` listener, Node exits. socket.on("error", (error) => { unauthorized = /Unexpected server response: 40[123]/.test(error.message); console.error("stream error:", error.message); }); socket.on("open", () => { attempt = 0; for (const frame of subscriptions) socket.send(JSON.stringify(frame)); heartbeat = setInterval(() => { if (Date.now() - lastPong > 45_000) return socket.terminate(); socket.send(JSON.stringify({ action: "ping" })); }, 30_000); }); socket.on("message", (raw) => { const frame = JSON.parse(raw.toString()); if (frame.type === "pong") lastPong = Date.now(); if (frame.type === "update") handleUpdate(frame); if (frame.type === "error") console.error(frame.code, frame.message); }); socket.on("close", (code) => { clearInterval(heartbeat); if (unauthorized || [1008, 4402, 4403].includes(code)) return console.error("The API key was refused. Not reconnecting."); const delay = code === 1001 ? 0 : Math.min(30_000, 1000 * 2 ** attempt) + Math.random() * 1000; setTimeout(() => connect(attempt + 1), delay); }); } function handleUpdate(frame: { channel: string; data: unknown }) { console.log(frame.channel, frame.data); } connect(); ``` ```rust Rust (tokio-tungstenite) theme={null} use std::time::Duration; use futures_util::{SinkExt, StreamExt}; use rand::Rng; use serde_json::{Value, json}; use tokio::time::{Instant, interval, sleep}; use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::{Error, Message, client::IntoClientRequest}; const URL: &str = "wss://api.metastreams.io/v1/stream"; #[tokio::main] async fn main() -> Result<(), Box> { let key = std::env::var("API_KEY")?; let subscriptions = [ json!({ "action": "subscribe", "channel": "spot.trades", "filters": { "chains": ["solana"], "tokens": ["DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"] } }), ]; let mut attempt = 0; loop { let close_code = match run(&key, &subscriptions, &mut attempt).await { Ok(code) => code, Err(Error::Http(response)) if matches!(response.status().as_u16(), 401 | 402 | 403) => { return Err("The API key was refused. Not reconnecting.".into()); } Err(error) => { eprintln!("stream error: {error}"); None } }; match close_code { Some(1008 | 4402 | 4403) => return Err("The API key was refused. Not reconnecting.".into()), Some(1001) => continue, _ => {} } let backoff = (1000 * 2u64.pow(attempt.min(5))).min(30_000); sleep(Duration::from_millis(backoff + rand::rng().random_range(0..1000))).await; attempt += 1; } } /// Runs one connection until it closes, and returns the server's close code. async fn run(key: &str, subscriptions: &[Value], attempt: &mut u32) -> Result, Error> { let mut request = URL.into_client_request()?; let auth = format!("Bearer {key}").parse().expect("the key is a valid header value"); request.headers_mut().insert("Authorization", auth); let (mut socket, _) = connect_async(request).await?; *attempt = 0; for frame in subscriptions { socket.send(Message::text(frame.to_string())).await?; } let mut heartbeat = interval(Duration::from_secs(30)); let mut last_pong = Instant::now(); loop { tokio::select! { _ = heartbeat.tick() => { if last_pong.elapsed() > Duration::from_secs(45) { return Ok(None); } socket.send(Message::text(json!({ "action": "ping" }).to_string())).await?; } message = socket.next() => match message.transpose()? { None => return Ok(None), Some(Message::Close(close)) => return Ok(close.map(|close| close.code.into())), Some(Message::Text(text)) => { let Ok(frame) = serde_json::from_str::(&text) else { continue }; match frame["type"].as_str() { Some("pong") => last_pong = Instant::now(), Some("update") => println!("{} {}", frame["channel"], frame["data"]), Some("error") => eprintln!("{} {}", frame["code"], frame["message"]), _ => {} } } Some(_) => {} } } } } ```