# Tribulnation Terminal API Your Terminal portfolio and, on the Ultra plan, live and historical crypto market data across CEX and DEX venues: for scripts, agents and AI assistants. **Read-only, always.** No key can place an order, move funds, change a setting or see an exchange key. - **API host:** `https://api.tribulnation.com` (HTTPS and WebSocket). - **Auth:** `Authorization: Bearer tn_key_…`, keys from https://app.tribulnation.com/integrations. ## Get started ### Hand it to your agent Give an agent this prompt: > Use the Tribulnation Terminal API at https://api.tribulnation.com. Read https://api.tribulnation.com/llms.txt first. My API key is in the TN_API_KEY environment variable: send it only as `Authorization: Bearer $TN_API_KEY` to https://api.tribulnation.com and never print, log or commit it. The API is read-only. - llms.txt: `https://api.tribulnation.com/llms.txt` - Claude Code plugin: `claude plugin marketplace add https://api.tribulnation.com/skills/marketplace.json && claude plugin install terminal@tribulnation` - MCP server: `https://api.tribulnation.com/mcp` - Python: `pip install tribulnation-terminal` ### Quick start 1. **Make a key** on [https://app.tribulnation.com/integrations](https://app.tribulnation.com/integrations): `me:read` for your own data (every plan), `market:read` for market data (Ultra). The secret is shown once. 2. **Keep it in the environment**, never in code or a URL: ```sh read -rs TN_API_KEY && export TN_API_KEY # paste it: not echoed, not in your history ``` 3. **Call the API** with the key in the `Authorization` header: ```sh curl -sH "Authorization: Bearer $TN_API_KEY" https://api.tribulnation.com/me curl -sH "Authorization: Bearer $TN_API_KEY" "https://api.tribulnation.com/me/portfolio?hours=168" curl -sH "Authorization: Bearer $TN_API_KEY" "https://api.tribulnation.com/v1/prices/latest?assets=bitcoin,ethereum" curl -sH "Authorization: Bearer $TN_API_KEY" "https://api.tribulnation.com/live/book/bitcoin?depth=10" ``` `GET /me` answers what the key is: its scopes, expiry and the owner's plan. Start there when something is refused. From your own code, send a `User-Agent` naming your program: Python `urllib`'s default is refused with a plain-text `403` (see Errors). ### Conventions One contract on every surface (`/v1`, `/v2`, `/me`, `/live`): | | | |---|---| | **Answers** | `{ "data", "meta" }`. `meta.as_of` is when the data is current as of (an instant); `meta.currency` is the currency of every money figure, on routes that carry money. Errors are always `{ "error": { "code", "message", "param"?, "details"? } }`. | | **Paging** | A paged route answers `meta.page`: `limit`, `has_more`, `next_cursor` (pass it back as `cursor`; `null` at the end), and on ranked lists `number` and `total` (which also take `page`). | | **Times** | Every instant is an ISO-8601 UTC string with milliseconds (`2026-11-17T19:40:28.036Z`); no epoch numbers (the one exception: a live socket frame's `ts_ms`, below; the OAuth endpoints answer `client_id_issued_at` in epoch seconds and `expires_in` in seconds, as RFC 7591 and RFC 6749 require). `from`/`to` take a date (`2026-11-17`, its 00:00 UTC) or an instant with a zone; windows are half-open, `[from, to)`, `to` defaults to now and `meta.range` echoes the window. A series bucket is labelled by its start, and is in a window when its start is. | | **Parameters** | Every route refuses a parameter it does not take, one given twice, or an empty one, with `400` and `error.param` naming it. Lists are plural and comma-separated (`assets=bitcoin,ethereum`); an id the catalogue does not have is a `400` with `details.unknown`. | | **Ids** | A field holding an id ends in `_id`: `asset_id`, `venue_id`, `quote_asset_id`. Assets are catalogue ids (`bitcoin`; `/v1/search?search=btc` finds them), venues lower case (`binance`). A venue's product family is its `segment` (`spot`, `usdm`, `perp`); `:` (`binance:usdm`) is a `segment_id`. A market's `kind` is `spot` or `perp`. A field holding a display symbol, not an id, ends in `_symbol` (`/me`'s market legs: `quote_symbol` `"USDT"`). | | **Names** | `name` is a thing's own name (`venue_name` names the venue of a row); `icon_url` is an absolute URL. | | **Numbers** | By meaning, never by how a value is stored. **Amounts are decimal strings**: every price, quantity, size, notional, balance, volume, open interest, market cap and P&L, in a currency or an asset (`"64250.5"`), whether it was stored exact or a venue published it as a float. One written form: plain notation, never an exponent (`"0.0000001"`, not `1e-7`), no leading zeros, no trailing zeros after the point (`"5094111182848"`, not `"5094111182848.00"`), `"0"` never `"-0"`; a venue float is written as the shortest decimal that reads back as the same float, never rounded. Everything else is a JSON number: rates are fractions (`0.05` is 5 %, `apr` is a year's), never percent; a figure in basis points ends in `_bps`, a duration in seconds in `_s`; ratios, counts, multipliers and leverage are numbers too. | | **Currency** | US dollars unless `?currency=eur` asks for euros (`meta.currency` says which). A venue price is in its market's quote asset. | | **Methods** | Every route is `GET` (or `HEAD`) except the OAuth endpoints. Redirects are never needed: never follow one with your key. | | **Live sockets** | A WebSocket frame names, types and times every field as the HTTP answers do (`/live/asset/{asset}` answers the same view), with one exception: the frame's build time is `ts_ms`, epoch milliseconds, for programs that compare it with their own clock. It is the only epoch number on the API; every other instant in a frame is ISO. The frame type is `type` (`view` or `control`); `v` is the view format's version, the same on a frame and on `GET /live/book|asset/{asset}`. | | **`/v2`** | The one exception to the names above: the publication records keep their own field names (`market.ticker`'s `bid_size`, `ask_size`, `volume_24h`; `venue.earn`'s `min_amount`, `max_amount`, `lock_seconds`; `interval_s`; ids as `asset`, `venue`, `exchange`), as each record's schema lists them. Their numbers follow the rule above. | ## Auth & keys ### API keys and scopes Every request carries one API key in the `Authorization` header. A key is `tn_key_` and 43 characters. Never put it in a URL. ```http Authorization: Bearer tn_key_… ``` | Scope | Allows | Plan | |---|---|---| | `me:read` | Your own data: accounts, portfolio, positions, fills, funding, saved charts (`/me`) | Every plan | | `me:profiles` | Create and change your portfolio profiles (`POST /me/profiles`, `PATCH /me/profiles/{id}`); off unless you tick it | Every plan | | `market:read` | Market data: `/v1`, `/v2` and `/live` | Ultra (fair use, included) | A key used off Ultra for market data, or without the scope a route needs, gets `403` with the reason. Every key is listed on [https://app.tribulnation.com/integrations](https://app.tribulnation.com/integrations) and revocable there, however it was made. ### Device login (CLI) `tn terminal auth login` asks for a code, prints it with a link, and waits while you approve it in the browser; the key it receives is saved for the CLI and the Python client. Add `--scopes me:read,market:read` on Ultra. Keys read only, with one exception: `me:profiles` lets a key create and change portfolio profiles. Tick it when you create the key; a key without it gets `403` on those writes. Listing profiles needs `me:read`. ```sh uv tool install 'tribulnation-terminal[cli]' tn terminal auth login ``` ### MCP and OAuth sign-in An MCP client (Claude, ChatGPT, Claude Code) connects to `https://api.tribulnation.com/mcp`, signs you in on https://app.tribulnation.com with OAuth 2.1 and receives its own key. See [MCP server](#mcp-server). ### OAuth endpoints For client authors: the device login (RFC 8628) and the MCP clients' authorization code grant (OAuth 2.1, RFC 7591 registration). They take no key, answer in OAuth's own error format (`{error, error_description}`), and are never cached. #### POST /oauth/device/code Start a device login (RFC 8628 §3.1), answered with a device code to poll with and a user code to approve on the app’s /integrations/device. Answer: `DeviceCodeAnswer` ```ts /** What the code request answers (RFC 8628 §3.2). */ export interface DeviceCodeAnswer { /** Secret the client polls `/oauth/token` with. */ device_code: string /** Short code the person confirms in the browser. */ user_code: string /** Where the person approves the code. */ verification_uri: string /** The same page with the code filled in. */ verification_uri_complete: string /** Seconds until the code expires. */ expires_in: number /** Seconds to wait between polls. */ interval: number /** The scopes asked for, space-separated. */ scope: string } ``` ```sh curl -s -X POST https://api.tribulnation.com/oauth/device/code \ -d client_id=tn-cli -d 'scope=me:read market:read' ``` #### POST /oauth/token Exchange an approved device code, or an authorization code with PKCE, for an API key. Device grant (RFC 8628 §3.4): authorization_pending, slow_down, access_denied or expired_token until approved; then the API key, once. Authorization code with PKCE (OAuth 2.1, an MCP client such as Claude or ChatGPT): the code from /oauth/authorize for the API key, once. Answer ```ts type Answer = CodeTokenAnswer | DeviceTokenAnswer ``` ```sh curl -s -X POST https://api.tribulnation.com/oauth/token \ -d grant_type=urn:ietf:params:oauth:grant-type:device_code \ -d client_id=tn-cli -d "device_code=$DEVICE_CODE" ``` #### POST /oauth/register Register a public OAuth client (no secret) with its redirect URIs, answered 201 with its client_id. For MCP clients without a Client ID Metadata Document (RFC 7591). Answer: `RegistrationAnswer` ```ts /** RFC 7591 §3.2.1: what a registration answers. */ export interface RegistrationAnswer { /** The id the client signs in with. */ client_id: string /** When it was issued, epoch seconds. */ client_id_issued_at: number /** The name it registered. */ client_name: string /** Where sign-in may return. */ redirect_uris: string[] /** Grants it may use (`authorization_code`). */ grant_types: ['authorization_code'] /** Response types (`code`). */ response_types: ['code'] /** Always `none`: a public client. */ token_endpoint_auth_method: 'none' /** Its homepage, or absent. */ client_uri?: string } ``` ```sh curl -s -X POST https://api.tribulnation.com/oauth/register \ -H 'Content-Type: application/json' \ -d '{"client_name": "My agent", "redirect_uris": ["http://127.0.0.1:8976/callback"]}' ``` #### POST /oauth/revoke Revoke an API key with the key itself (RFC 7009), answered 200 for any well-formed request. Answer ```ts type Answer = { [key: string]: never } ``` ```sh curl -s -X POST https://api.tribulnation.com/oauth/revoke \ -d client_id=tn-cli -d "token=$TN_API_KEY" ``` ## Plans & quotas ### Plans and scopes | Plan | `me:read` (your data) | `market:read` (`/v1`, `/v2`, `/live`) | |---|---|---| | Free | Yes | No | | Pro | Yes | No | | Ultra | Yes | Yes, fair use, included | ### Fair use and 429 Market data is fair use per account; the API answers `429` with code `rate_limited` before anything breaks. `429` and `503` carry `Retry-After` (seconds): wait that long, then retry. Nothing else is worth retrying: `400`, `401`, `403` and `404` will not change. ### Live freshness Live data is never stale: nothing older than 30 s is handed out as current. A read of an asset nobody is watching starts its build and waits for full books, up to 3.5 s; if none is ready it answers `503` with code `warming` and `Retry-After: 2`. Each read keeps the asset warm for 30 s, so repeated reads answer at once. One account keeps at most 16 assets warm at a time (one more is `429`). ### Socket limits | Limit | Value | |---|---| | Sockets per key | 32 | | Distinct topics per key | 16 | | Sockets per account, across its keys | 32 | | Book depth | 1 to 50 levels a side | | Grant | 60 s, then close 4001: reconnect at once | Over a limit, the socket is refused with `429` and `Retry-After: 10`. ## Your data (/me) Your own portfolio, read with `me:read` on every plan; profiles can also be created and changed with `me:profiles`. Each route answers what the app shows you, for the key's owner only, and is never cached. The portfolio routes take `from` and `to` (a date or an instant with a zone; default: the last 24 hours) and `profile` (default: your default profile). Fills, funding and transfers come a page at a time: pass `meta.page.next_cursor` back as `cursor`. When the portfolio tracker is slow you get its last answer, flagged by the header `X-Portfolio-Last-Answer` (`synced_at=;stored_at=`). ### Create and change profiles With a key that has `me:profiles` (tick **Create and edit profiles** when you create it), `POST /me/profiles` creates a profile and `PATCH /me/profiles/{id}` changes the fields you send and keeps the rest. A rule list you send replaces that list. Profiles are checked the same way as on the Portfolio page: an empty name, an unknown rule or currency, or an unknown field is `400` with the reason. Keys without the scope get `403`. ```sh curl -X POST https://api.tribulnation.com/me/profiles \ -H "Authorization: Bearer $TN_KEY" -H 'Content-Type: application/json' \ -d '{"name": "Bot 1", "include": [":*"]}' ``` ```json { "data": { "id": "bot-1", "name": "Bot 1", "description": "", "include": [":*"], "exclude": [], "builtin": false, "default": false, "created_at": "2026-11-29T10:00:00.000Z", "updated_at": "2026-11-29T10:00:00.000Z", "base_currency": null, "value_collateral": false }, "meta": { "as_of": "2026-11-29T10:00:00.000Z" } } ``` ```sh curl -X PATCH https://api.tribulnation.com/me/profiles/bot-1 \ -H "Authorization: Bearer $TN_KEY" -H 'Content-Type: application/json' \ -d '{"description": "VM 1"}' ``` Rules are the Portfolio page's: `:*` (every market of an account), `:[:]`, `asset:`, `kind:perp` or `kind:spot`; account ids come from `GET /me/accounts`. A profile cannot be deleted, or made your default, with a key: do that in the app. #### GET /me The key itself: its scopes, its source and expiry, and the owner’s plan now. Key: `any key` (Every plan). Answer ```ts type Answer = { data: KeyIntrospection meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me" ``` #### GET /me/accounts Your connected accounts and venues: names, labels and statuses, and the account each connection reads (its wallet address, account index or uid, or sub-account name); never key material. Key: `me:read` (Every plan). Answer ```ts type Answer = { data: { accounts: AccountInfo[] venues: VenueEntry[] warnings: KeyWarning[] default_profile: string } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/accounts" ``` #### GET /me/profiles Your portfolio profiles. Key: `me:read` (Every plan). Answer ```ts type Answer = { data: ProfileInfo[] meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/profiles" ``` #### POST /me/profiles Create a portfolio profile (needs `me:profiles`). Body: `name` (required), `description`, `include` and `exclude` (rules, as on the Portfolio page), `base_currency` (a three-letter code, or null for your Settings currency), `value_collateral`. Its id is made from the name. Answers `201` with the profile. Key: `any key` (Every plan). Answer ```ts type Answer = { data: ProfileInfo meta: { as_of: string | null } } ``` ```sh curl -s -X POST https://api.tribulnation.com/me/profiles \ -H "Authorization: Bearer $TN_API_KEY" -H 'Content-Type: application/json' \ -d '{"name": "Bot 1", "include": ["kind:perp"]}' ``` #### GET /me/portfolio Your portfolio over a window: value, P&L and exposure history, with every position, for a profile (the default one unless `profile` is given). When the tracker is slow, the last answer, flagged by `X-Portfolio-Last-Answer`. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `from` | query | `string` | Window start, inclusive: a date (`2026-11-10`, its 00:00 UTC) or an instant with a zone (default: 24 hours before `to`). | | `to` | query | `string` | Window end, exclusive: a date or an instant with a zone (default: now). | | `profile` | query | `string` | A profile id from `/me/profiles` (default: your default profile). | | `include` | query | `string` | Ad-hoc rules replacing the profile’s, comma-separated; empty: none. | | `exclude` | query | `string` | Ad-hoc exclusions replacing the profile’s, comma-separated; empty: none. | Answer ```ts type Answer = { data: { interval: '1m' | '5m' | '15m' | '1h' | '4h' | '1d' positions_at: string | null selection: Selection exchanges: ExchangeMeta[] accounts: AccountEquity[] account_equity: AccountEquity[] excluded_accounts: string[] equity_history: { [key: string]: { time: string value: Decimal }[] } summary: PortfolioSummary by_exchange: ExchangeSummary[] series: PortfolioSeries delta_by_asset: DeltaSeries[] assets: AssetRow[] asset_options: AssetOption[] fills: FillRow[] transfers: TransferRow[] asset_info: { [key: string]: AssetInfo } prices_at: string | null reference_prices: { [key: string]: string } venue_prices: { [key: string]: VenuePrice } no_price: NoPrice collateral: { asset_id: string symbol: string qty: Decimal price: Decimal usd: Decimal pnl: Decimal exchanges: { [key: string]: Decimal } }[] conns: { [key: string]: Conn } next_sync_at: string | null } meta: { as_of: string | null range?: { from: string to: string } } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/portfolio?from=2026-11-16" ``` #### GET /me/portfolio/summary A profile’s totals over a window (default the last 24 hours) with its risk figures now (leverage, nearest liquidation, free collateral, maintenance margin, daily funding carry), its accounts with their exposure, and how fresh its connections are: `/me/portfolio` without assets, fills, series or transfers, cheap to poll. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `from` | query | `string` | Window start, inclusive: a date (`2026-11-10`, its 00:00 UTC) or an instant with a zone (default: 24 hours before `to`). | | `to` | query | `string` | Window end, exclusive: a date or an instant with a zone (default: now). | | `profile` | query | `string` | A profile id from `/me/profiles` (default: your default profile). | Answer ```ts type Answer = { data: { positions_at: string | null selection: Selection summary: SelectionSummary accounts: AccountEquity[] conns: { [key: string]: Conn } next_sync_at: string | null oldest_synced_at: string | null warnings: KeyWarning[] } meta: { as_of: string | null range?: { from: string to: string } } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/portfolio/summary?profile=dydx" ``` #### GET /me/portfolio/pnl-days A profile’s P&L per UTC day (trading, funding, fees paid) and its equity at each day’s end, over the last `days` days (default 30). While it is computed, 202 with `Retry-After`: ask again then. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `days` | query | `number` | Days back from now, 1 to 3660; the first day starts at that UTC midnight (default 30). | | `profile` | query | `string` | A profile id from `/me/profiles` (default: your default profile). | Answer ```ts type Answer = { data: { stale: boolean days: PnlDay[] } meta: { as_of: string | null range?: { from: string to: string } } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/portfolio/pnl-days?days=3&profile=dydx" ``` #### GET /me/portfolio/asset One asset’s drill-down in a profile. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `asset` (required) | query | `string` | A catalogue asset id (`bitcoin`) or symbol. | | `from` | query | `string` | Window start, inclusive: a date (`2026-11-10`, its 00:00 UTC) or an instant with a zone (default: 24 hours before `to`). | | `to` | query | `string` | Window end, exclusive: a date or an instant with a zone (default: now). | | `profile` | query | `string` | A profile id from `/me/profiles` (default: your default profile). | | `include` | query | `string` | Ad-hoc rules replacing the profile’s, comma-separated; empty: none. | | `exclude` | query | `string` | Ad-hoc exclusions replacing the profile’s, comma-separated; empty: none. | Answer ```ts type Answer = { data: AssetDetail meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/portfolio/asset?asset=bitcoin&from=2026-11-16" ``` #### GET /me/portfolio/fills Every fill of a profile in the window, newest first, a page at a time. `next` is the following page’s `cursor`, which keeps the first page’s window; `format=csv` answers all of them. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `from` | query | `string` | Window start, inclusive: a date (`2026-11-10`, its 00:00 UTC) or an instant with a zone (default: 24 hours before `to`). | | `to` | query | `string` | Window end, exclusive: a date or an instant with a zone (default: now). | | `profile` | query | `string` | A profile id from `/me/profiles` (default: your default profile). | | `include` | query | `string` | Ad-hoc rules replacing the profile’s, comma-separated; empty: none. | | `exclude` | query | `string` | Ad-hoc exclusions replacing the profile’s, comma-separated; empty: none. | | `assets` | query | `string` | Only these assets (ids or symbols), comma-separated. | | `accounts` | query | `string` | Only these accounts, comma-separated. | | `markets` | query | `string` | Only these markets, as the venue names them, comma-separated. | | `segments` | query | `string` | Only these segment ids (`binance:usdm`), comma-separated. | | `side` | query | `'buy' \| 'sell'` | `buy` (received, in) or `sell` (paid, out). | | `search` | query | `string` | Text in the asset’s or market’s symbol. | | `cursor` | query | `string` | The previous page's `meta.page.next_cursor`; it keeps the first page's window. | | `limit` | query | `number` | Rows per page, 1 to 1000 (default 200). | | `format` | query | `'csv'` | `csv`: every matching row of the window, no paging. | Answer ```ts type Answer = { data: FillRow[] meta: { as_of: string | null range?: { from: string to: string } page?: { limit: number has_more: boolean next_cursor: string | null total?: number } assets?: Record } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/portfolio/fills?from=2026-11-10" ``` #### GET /me/portfolio/funding Every funding payment of a profile in the window, paged as the fills are. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `from` | query | `string` | Window start, inclusive: a date (`2026-11-10`, its 00:00 UTC) or an instant with a zone (default: 24 hours before `to`). | | `to` | query | `string` | Window end, exclusive: a date or an instant with a zone (default: now). | | `profile` | query | `string` | A profile id from `/me/profiles` (default: your default profile). | | `include` | query | `string` | Ad-hoc rules replacing the profile’s, comma-separated; empty: none. | | `exclude` | query | `string` | Ad-hoc exclusions replacing the profile’s, comma-separated; empty: none. | | `assets` | query | `string` | Only these assets (ids or symbols), comma-separated. | | `accounts` | query | `string` | Only these accounts, comma-separated. | | `markets` | query | `string` | Only these markets, as the venue names them, comma-separated. | | `segments` | query | `string` | Only these segment ids (`binance:usdm`), comma-separated. | | `side` | query | `'buy' \| 'sell'` | `buy` (received, in) or `sell` (paid, out). | | `search` | query | `string` | Text in the asset’s or market’s symbol. | | `cursor` | query | `string` | The previous page's `meta.page.next_cursor`; it keeps the first page's window. | | `limit` | query | `number` | Rows per page, 1 to 1000 (default 200). | | `format` | query | `'csv'` | `csv`: every matching row of the window, no paging. | Answer ```ts type Answer = { data: FundingPayment[] meta: { as_of: string | null range?: { from: string to: string } page?: { limit: number has_more: boolean next_cursor: string | null total?: number } assets?: Record } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/portfolio/funding?from=2026-11-10" ``` #### GET /me/portfolio/transfers Every on-chain wallet transfer of a profile in the window, paged as the fills are. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `from` | query | `string` | Window start, inclusive: a date (`2026-11-10`, its 00:00 UTC) or an instant with a zone (default: 24 hours before `to`). | | `to` | query | `string` | Window end, exclusive: a date or an instant with a zone (default: now). | | `profile` | query | `string` | A profile id from `/me/profiles` (default: your default profile). | | `include` | query | `string` | Ad-hoc rules replacing the profile’s, comma-separated; empty: none. | | `exclude` | query | `string` | Ad-hoc exclusions replacing the profile’s, comma-separated; empty: none. | | `assets` | query | `string` | Only these assets (ids or symbols), comma-separated. | | `accounts` | query | `string` | Only these accounts, comma-separated. | | `markets` | query | `string` | Only these markets, as the venue names them, comma-separated. | | `segments` | query | `string` | Only these segment ids (`binance:usdm`), comma-separated. | | `side` | query | `'buy' \| 'sell'` | `buy` (received, in) or `sell` (paid, out). | | `search` | query | `string` | Text in the asset’s or market’s symbol. | | `cursor` | query | `string` | The previous page's `meta.page.next_cursor`; it keeps the first page's window. | | `limit` | query | `number` | Rows per page, 1 to 1000 (default 200). | | `format` | query | `'csv'` | `csv`: every matching row of the window, no paging. | Answer ```ts type Answer = { data: TransferRow[] meta: { as_of: string | null range?: { from: string to: string } page?: { limit: number has_more: boolean next_cursor: string | null total?: number } assets?: Record } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/portfolio/transfers?from=2026-11-10" ``` #### GET /me/position One asset’s position and 24h P&L in the default profile. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `asset` (required) | query | `string` | A catalogue asset id (`bitcoin`) or symbol. | Answer ```ts type Answer = { data: PositionAnswer meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/position?asset=bitcoin" ``` #### GET /me/charts Your saved Charts plots (Charts is part of Pro). Key: `me:read` (Every plan). Answer ```ts type Answer = { data: SavedPlot[] meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/charts" ``` #### GET /me/charts/{id} One of your saved Charts plots: its name, kind and configuration. Someone else’s is 404. Key: `me:read` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A saved plot’s id (16 letters and digits). | Answer ```ts type Answer = { data: { plot: SavedPlot } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/me/charts/AbCdEfGh12345678" ``` #### PATCH /me/profiles/{id} Change a portfolio profile (needs `me:profiles`): only the fields given (those of creating one), the rest kept. Its id stays; the built-in `all` cannot be changed. Answers the profile. Key: `any key` (Every plan). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A profile’s id, from `GET /me/profiles`. | Answer ```ts type Answer = { data: ProfileInfo meta: { as_of: string | null } } ``` ```sh curl -s -X PATCH https://api.tribulnation.com/me/profiles/bot-1 \ -H "Authorization: Bearer $TN_API_KEY" -H 'Content-Type: application/json' \ -d '{"description": "VM 1"}' ``` ## Market data (/v1) Prices, candles, tickers, perpetual stats and funding, earn products, and the asset, venue and network directories. Scope `market:read`, Ultra. Every answer is `{ "data", "meta" }` (see [Conventions](#conventions)). `meta.as_of` is the newest observation in `data` (the catalogue's update time on the directories and search; `null`: no row carried one), `meta.currency` the currency of every money figure. Lists page with `limit` and `cursor` (ranked lists also with `page`); pass `meta.page.next_cursor` back as `cursor` until it is `null`. ### Assets & search #### GET /v1/assets Assets ranked by market cap, with their price, the prices 24h and 7d ago and an optional sparkline, paged, filterable by category or search. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `page` | query | `number` | 1-based page number, instead of `cursor`; `meta.page.number` and `meta.page.total` say where you are. | | `limit` | query | `number` | Rows per page, 1 to 1000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | | `currency` | query | `'usd' \| 'eur'` | Currency of the money figures: `usd` (default) or `eur`. | | `categories` | query | `string[]` | Category tags (an open vocabulary: an unknown one matches nothing). Comma-separated, at most 7. | | `search` | query | `string` | Free text matched against asset names and symbols; a comma is just a character. | | `sparkline` | query | `'1'` | | Answer: `RankedAssetEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface RankedAssetEnvelope { /** The answer: one object, or a list of rows. */ data: RankedAsset[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** One row of the market-cap ranking. */ export interface RankedAsset { /** The catalogue asset id (`bitcoin`): what every other route takes. */ id: string /** Ticker symbol (`BTC`). */ symbol: string /** Name to show (`Bitcoin`). */ name: string /** The asset's category, or `null` when the catalogue gives none. */ category: 'crypto' | 'stock' | 'fiat' | 'stablecoin' | 'commodity' | 'rwa' | 'fund' | null /** Icon URL, or `null`. */ icon_url: string | null /** Reference price in `meta.currency`, a decimal string, or `null` when never priced. */ price: Decimal | null /** Market capitalisation in `meta.currency`, a decimal string, or `null`. */ market_cap: Decimal | null /** When `price` was observed (ISO-8601 UTC), or `null`. */ observed_at: string | null /** The price about 24 hours before `observed_at`, or `null` when not known. */ price_24h_ago: Decimal | null /** * The price ~7 days before `observed_at`, or `null` when that is not something we know -- same doctrine as `price24hAgo`, at a wider window. */ price_7d_ago: Decimal | null /** See `PegCurrency`. `null` for anything that is not a resolvable stablecoin. */ peg_currency: string | null sparkline?: Sparkline } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/assets?limit=3" ``` #### GET /v1/assets/{id} One asset: its price, price history, markets, funding, earn products and listings. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | The asset's catalogue id. | | `currency` | query | `'usd' \| 'eur'` | Currency of the money figures: `usd` (default) or `eur`. | Answer: `AssetAggregateEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface AssetAggregateEnvelope { /** The answer: one object, or a list of rows. */ data: AssetAggregate /** About the answer: its freshness, currency, window and page. */ meta: Meta } export interface AssetAggregate { /** The asset and its catalogue copy. */ asset: AssetProfile /** `null` when the sampler has never priced this asset. */ price: LatestPrice | null /** Oldest first. Bounded -- the whole series is `/v1/prices/historical`. */ price_history: PricePoint[] /** * Every ticker for this asset, venue and quote asset resolved to names/icons — see `AssetTicker`. */ tickers: AssetTicker[] /** Every perpetual for this asset, resolved the same way. */ perps: AssetPerpStats[] /** Latest funding of its perpetuals, per venue market. */ funding: Funding[] /** Earn products on the asset. */ earn: EarnInstrument[] /** * The asset's trading pages, ordered by venue, kind and market; empty where the serving path carries none (the retained Supabase handler) — see `AssetInstrument`. */ instruments: AssetInstrument[] /** * Every market the asset trades on, ordered by venue, kind and market; empty where the serving path carries none — see `AssetListing`. */ listings: AssetListing[] } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/assets/bitcoin?currency=usd" ``` #### GET /v1/assets/{id}/summary One asset: its profile and latest price only. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | The asset's catalogue id. | | `currency` | query | `'usd' \| 'eur'` | Currency of the money figures: `usd` (default) or `eur`. | Answer: `AssetSummaryEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface AssetSummaryEnvelope { /** The answer: one object, or a list of rows. */ data: AssetSummary /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** Identity/profile and current price, without history or secondary sections. */ export interface AssetSummary { /** The asset and its catalogue copy. */ asset: AssetProfile /** `null` when the sampler has never priced this asset. */ price: LatestPrice | null } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/assets/bitcoin/summary" ``` #### GET /v1/assets/{id}/instruments One asset's trading pages on each venue. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | The asset's catalogue id. | Answer: `AssetInstrumentEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface AssetInstrumentEnvelope { /** The answer: one object, or a list of rows. */ data: AssetInstrument[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** * One of the asset's instruments with a trading page: the catalogue's `url`, verbatim, for an instrument the asset is the base of (`market.instruments`). Only instruments with a URL are listed; a delisted one, or one on a venue the catalogue has no verified rule for, has none, and a consumer shows no link rather than building one. `venue` is the catalogue platform id, `exchange` the instrument's exchange within it, and `market` the venue's own symbol: the keys every `Ticker` row carries (and the realtime exchange id `:`). */ export interface AssetInstrument { /** The venue (catalogue platform id). */ venue_id: string /** `spot` or `perp`. */ kind: 'spot' | 'perp' /** * The catalogue instrument's `exchange` (the SDK exchange id, `usdm`, `spot`; a Hyperliquid dex), `null` where the catalogue names none. */ segment: string | null /** The venue's own market symbol. */ market: string /** The market's page on the venue. */ url: string } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/assets/bitcoin/instruments" ``` #### GET /v1/search Assets, platforms and networks whose name, symbol or id matches the text, best match first. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `search` (required) | query | `string` | Free text matched against asset names and symbols; a comma is just a character. | Answer: `SearchResultEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface SearchResultEnvelope { /** The answer: one object, or a list of rows. */ data: SearchResult[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } export type SearchResult = { kind: 'asset' id: string symbol: string name: string category: string | null icon_url: string | null } | { kind: 'venue' id: string name: string icon_url: string | null } | { kind: 'network' id: string name: string icon_url: string | null } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/search?search=bitcoin" ``` ### Prices & candles #### GET /v1/candles One asset’s OHLC candles aggregated across venues, by hour, 4 hours or day. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `asset` (required) | query | `string` | The catalogue asset id. | | `interval` | query | `'1h' \| '4h' \| '1d'` | Candle width; each candle is labelled by its start. | | `from` (required) | query | `string` | Start of the window, inclusive: a date (`YYYY-MM-DD`, its 00:00Z) or an ISO-8601 instant with a zone (`Z` or `±HH:MM`). | | `to` | query | `string` | End of the window, exclusive: a date or an ISO-8601 instant with a zone. Defaults to now. | | `limit` | query | `number` | Rows per page, 1 to 10000; `meta.page.next_cursor` reads on. | | `currency` | query | `'usd' \| 'eur'` | Currency of the money figures: `usd` (default) or `eur`. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | Answer: `CandlePointEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface CandlePointEnvelope { /** The answer: one object, or a list of rows. */ data: CandlePoint[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } export interface CandlePoint { /** The catalogue asset id. */ asset_id: string /** Bucket start, ISO-8601 UTC. */ time: string /** Bucket width: `1h`, `4h` or `1d`. */ interval: '1h' | '4h' | '1d' /** * `venues`: the spot asset index. `perpetuals`: an asset that trades only as perpetuals (gold, stocks), from its perpetual markets' trade candles; a chart series carrying their basis and funding, never a valuation price. */ source: 'venues' | 'perpetuals' /** First price of the bucket, a decimal string. */ open: Decimal /** Highest price of the bucket, a decimal string. */ high: Decimal /** Lowest price of the bucket, a decimal string. */ low: Decimal /** Last price of the bucket, a decimal string. */ close: Decimal /** Traded value in the bucket (quote turnover), in `meta.currency`, a decimal string. */ turnover: Decimal /** When this candle was built, an instant. */ built_at: string /** The bucket's period: how much of it was observed and whether it has ended. */ period: { hours: number | null closed: boolean } } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/candles?asset=bitcoin&interval=1d&from=2026-11-10&to=2026-11-17&limit=3" ``` #### GET /v1/prices/latest The latest reference price of each asset asked for. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `assets` (required) | query | `string[]` | Catalogue asset ids. Comma-separated, at most 1000. | | `currency` | query | `'usd' \| 'eur'` | Currency of the money figures: `usd` (default) or `eur`. | Answer: `LatestPriceEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface LatestPriceEnvelope { /** The answer: one object, or a list of rows. */ data: LatestPrice[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** One asset's current price. */ export interface LatestPrice { /** The catalogue asset id. */ asset_id: string /** Reference price in `meta.currency`, a decimal string; `null` when none is known. */ price: Decimal | null /** Market capitalisation in `meta.currency`, a decimal string, or `null`. */ market_cap: Decimal | null /** This row's own observation time; `meta.asOf` is the newest of them. */ observed_at: string | null /** The price about 24 hours before `observed_at`, or `null` when not known. */ price_24h_ago: Decimal | null } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/prices/latest?assets=bitcoin,ethereum" ``` #### GET /v1/prices/historical Daily reference prices of each asset asked for over a window, each day labelled by its start. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `assets` (required) | query | `string[]` | Catalogue asset ids. Comma-separated, at most 1000. | | `from` (required) | query | `string` | Start of the window, inclusive: a date (`YYYY-MM-DD`, its 00:00Z) or an ISO-8601 instant with a zone (`Z` or `±HH:MM`). | | `to` | query | `string` | End of the window, exclusive: a date or an ISO-8601 instant with a zone. Defaults to now. | | `limit` | query | `number` | Rows per page, 1 to 10000; `meta.page.next_cursor` reads on. | | `currency` | query | `'usd' \| 'eur'` | Currency of the money figures: `usd` (default) or `eur`. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | Answer: `PricePointEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface PricePointEnvelope { /** The answer: one object, or a list of rows. */ data: PricePoint[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** One day of one asset's price. */ export interface PricePoint { /** The catalogue asset id. */ asset_id: string /** The day the price is for, labelled by its start (00:00Z), an instant. */ time: string /** The day's reference price in `meta.currency`, a decimal string, or `null`. */ price: Decimal | null /** The day's market capitalisation, a decimal string, or `null`. */ market_cap: Decimal | null /** * Which of the up-to-four price sources won this day, or `PEG_SOURCE` and the id of the asset this one is pegged to 1:1, for a day taken from that asset's history before this one had its own. */ source: string | null /** When the run that wrote this row ran (a cache validator, not a freshness signal). */ fetched_at: string | null } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/prices/historical?assets=bitcoin&from=2026-11-14&to=2026-11-17&limit=3" ``` ### Tickers, perps & funding #### GET /v1/market/tickers/latest Latest spot and perp tickers per venue market. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `kinds` | query | `'spot' \| 'perp' \| 'spot,perp'` | Only these instrument kinds: `spot`, `perp`, comma-separated. | | `assets` | query | `string[]` | Catalogue asset ids. Comma-separated, at most 100. | | `venues` | query | `string[]` | Venue ids. Comma-separated, at most 100. | | `page` | query | `number` | 1-based page number, instead of `cursor`; `meta.page.number` and `meta.page.total` say where you are. | | `limit` | query | `number` | Rows per page, 1 to 1000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | Answer: `LatestRowEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface LatestRowEnvelope { /** The answer: one object, or a list of rows. */ data: LatestRow[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } export type LatestRow = Ticker | PerpStats | Funding export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/market/tickers/latest?assets=bitcoin&limit=3" ``` #### GET /v1/market/perps/stats/latest Latest perp statistics (open interest, volume) per venue market. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `assets` | query | `string[]` | Catalogue asset ids. Comma-separated, at most 100. | | `venues` | query | `string[]` | Venue ids. Comma-separated, at most 100. | | `page` | query | `number` | 1-based page number, instead of `cursor`; `meta.page.number` and `meta.page.total` say where you are. | | `limit` | query | `number` | Rows per page, 1 to 1000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | Answer: `LatestRowEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface LatestRowEnvelope { /** The answer: one object, or a list of rows. */ data: LatestRow[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } export type LatestRow = Ticker | PerpStats | Funding export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/market/perps/stats/latest?assets=bitcoin&limit=3" ``` #### GET /v1/market/perps/funding/latest Latest funding rate per perp market. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `assets` | query | `string[]` | Catalogue asset ids. Comma-separated, at most 100. | | `venues` | query | `string[]` | Venue ids. Comma-separated, at most 100. | | `page` | query | `number` | 1-based page number, instead of `cursor`; `meta.page.number` and `meta.page.total` say where you are. | | `limit` | query | `number` | Rows per page, 1 to 1000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | Answer: `LatestRowEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface LatestRowEnvelope { /** The answer: one object, or a list of rows. */ data: LatestRow[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } export type LatestRow = Ticker | PerpStats | Funding export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/market/perps/funding/latest?assets=bitcoin&limit=3" ``` #### GET /v1/market/perps/funding/historical Funding rate history per perp market, by cursor. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `assets` | query | `string[]` | Catalogue asset ids. Comma-separated, at most 100. | | `venues` | query | `string[]` | Venue ids. Comma-separated, at most 100. | | `markets` | query | `string[]` | Venues' own market symbols (`USDJPYUSDT`), with `venues`: only these markets. Comma-separated, at most 100. | | `from` (required) | query | `string` | Start of the window, inclusive: a date (`YYYY-MM-DD`, its 00:00Z) or an ISO-8601 instant with a zone (`Z` or `±HH:MM`). | | `to` | query | `string` | End of the window, exclusive: a date or an ISO-8601 instant with a zone. Defaults to now. | | `interval` | query | `'1h' \| '1d'` | `1h`: each settlement; `1d`: summed per UTC day, labelled by its start. | | `limit` | query | `number` | Rows per page, 1 to 10000; `meta.page.next_cursor` reads on. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | Answer: `FundingPointEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface FundingPointEnvelope { /** The answer: one object, or a list of rows. */ data: FundingPoint[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** One settled funding payment, or one UTC day of them. */ export interface FundingPoint { /** The catalogue id of the perpetual's base asset. */ asset_id: string /** The venue (catalogue platform id). */ venue_id: string /** The venue's own market symbol. */ market: string /** Settlement instant, or the UTC day it fell in. See above. */ time: string /** * Settled rate; the day's **total** at `interval=day`. Relative units, as every rate on this API is: `0.0001` is 0.01%. See `EarnInstrument.apr`. */ rate: number | null /** Mark-to-index spread; the day's **mean** at `interval=day`. */ premium: number | null /** * The per-side holding rates, each a fraction per interval like `rate` (+ = that side pays; the day's **total** at `interval=day`). `rate` is what a long pays in funding; `funding_short` is what a short pays; `borrow_long` / `borrow_short` are what each side pays the venue or pool to hold, on top of funding. A key is **absent** where the venue does not charge or report it: a one-rate venue's short side is `-rate` and it charges no borrow. Only gTrade carries them today (from 2026-09-01; a borrowing-v1 pair's hours after its one read carry no borrow). gTrade's funding is zero-sum: the earning side is 0 where the paying side held no open interest, and an hour whose payer is unknown has `rate` null and no `funding_short` (its borrow stays). */ funding_short?: number /** Borrow fee a long pays per interval, a fraction (venues that charge one). */ borrow_long?: number /** Borrow fee a short pays per interval, a fraction (venues that charge one). */ borrow_short?: number } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/market/perps/funding/historical?assets=bitcoin&from=2026-11-16T21:00:00Z&to=2026-11-17T21:00:00Z&limit=3" ``` ### Earn #### GET /v1/earn/latest Earn products (staking, savings, lending) across venues. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `assets` | query | `string[]` | Catalogue asset ids. Comma-separated, at most 1000. | | `venues` | query | `string[]` | Venue ids. Comma-separated, at most 1000. | | `types` | query | `string[]` | Product type tags, any of them (an open vocabulary). Comma-separated, at most 1000. | | `region` | query | `'eu' \| 'us'` | Leave out the products not offered in this region (EU/EEA or US). | | `page` | query | `number` | 1-based page number, instead of `cursor`; `meta.page.number` and `meta.page.total` say where you are. | | `limit` | query | `number` | Rows per page, 1 to 1000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | | `currency` | query | `'usd' \| 'eur'` | Currency of the money figures: `usd` (default) or `eur`. | | `sort` | query | `'apr' \| 'earnings'` | | | `stake` | query | `number` | Stake in USD the earnings estimate is for. | Answer: `EarnInstrumentEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface EarnInstrumentEnvelope { /** The answer: one object, or a list of rows. */ data: EarnInstrument[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** One earn product. */ export interface EarnInstrument { /** The venue offering it (catalogue platform id). */ venue_id: string /** The venue's own product id. */ instrument: string /** Catalogue id of the asset earned on. */ asset_id: string | null /** `market.assets.symbol` for `asset_id`, or `null` when there is no asset. */ asset_symbol: string | null /** `market.assets.display_name` for `asset_id` -- `Tether USD`. `null` as above. */ asset_name: string | null /** * `market.assets.icon` for `asset_id`: a path relative to `https://catalogue.tribulnation.com/`, like every other `icon` on this API. */ asset_icon_url: string | null /** `market.platforms.display_name` for `venue` -- `MEXC`, `Binance`. */ venue_name: string | null /** * **An icon to show, not `market.platforms.icon`** -- the same promise `Platform.icon` makes, resolved the same way. */ venue_icon_url: string | null /** * **Where to open this product on the venue's own site**, or `null` when the venue publishes no link for it. */ url: string | null /** **A fraction of one, not percentage points: `0.0123` is 1.23%.** */ apr: number | null /** Lock-up in whole seconds; `null` or 0 for flexible. */ lock_s: number | null /** Product tags (`flexible`, `locked`, `staking`,...). */ tags: Json /** When the offer was read, ISO-8601 UTC. */ observed_at: string | null /** * The smallest and largest amount this product accepts. Both promoted out of `raw` the same way `url` was: `null` on either means the venue publishes no such bound, not that the collector failed to read one. */ min_qty: Decimal | null /** Most you can subscribe, asset units, or `null` for no cap. */ max_qty: Decimal | null price: Decimal | null /** * **What a $1,000 stake earns from this product over 30 days, in US dollars** -- the figure `?sort=earnings` ranks by. */ earnings_1k_30d: Decimal | null earnings_30d: Decimal | null /** * A promotion on top of `apr`, which stays the product's base rate: absent when the product has none. `apr`, `earnings_1k_30d` and the ranking never include it, because a bonus is capped, ends, and is often for new accounts only. */ bonus?: EarnBonus /** * Who may take the product and when: the KYC level, what the venue calls its rate, the offer's dates. Absent when the venue states none (most products); set on new-user products. */ offer?: EarnOffer /** * The regions the product is not offered in: `[]` when none is known, which does not claim it is offered everywhere. */ unavailable_in?: ('eu' | 'us')[] } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/earn/latest?assets=ethereum&limit=3" ``` #### GET /v1/earn/facets The venues, assets and tags earn products can be filtered by. Key: `market:read` (Ultra). Answer ```ts type Answer = { data: EarnFacets meta: { as_of: string | null collected_at: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/earn/facets" ``` #### GET /v1/earn/historical Each earn product of the assets asked for, day by day: its rate and tier ladder. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `assets` (required) | query | `string[]` | Catalogue asset ids. Comma-separated, at most 1000. | | `from` (required) | query | `string` | Start of the window, inclusive: a date (`YYYY-MM-DD`, its 00:00Z) or an ISO-8601 instant with a zone (`Z` or `±HH:MM`). | | `to` | query | `string` | End of the window, exclusive: a date or an ISO-8601 instant with a zone. Defaults to now. | | `venues` | query | `string[]` | Only these venues. Comma-separated, at most 1000. | | `limit` | query | `number` | Rows per page, 1 to 10000; `meta.page.next_cursor` reads on. | | `cursor` | query | `string` | Opaque: the previous page's `meta.page.next_cursor`, bound to the same query. | Answer: `EarnHistoryPointEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface EarnHistoryPointEnvelope { /** The answer: one object, or a list of rows. */ data: EarnHistoryPoint[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** One earn product on one UTC day: its last observation that day. */ export interface EarnHistoryPoint { /** Catalogue id of the asset earned on. */ asset_id: string /** The day, labelled by its start (00:00Z), an instant. */ time: string /** The venue (catalogue platform id). */ venue_id: string /** The product, as `EarnInstrument.instrument` names it. */ instrument: string /** The product's rate as collected (a fraction: `0.05` is 5 %). */ apr: number | null /** APR tiers by amount. */ tiers: EarnTier[] /** Whether `tiers` is a collected ladder, rather than the row as one tier. */ laddered: boolean /** Lock-up in whole seconds; `null` or 0 for flexible. */ lock_s: number | null /** Product tags. */ tags: string[] | null /** Least you can subscribe, asset units, or `null`. */ min_qty: Decimal | null /** Most you can subscribe, asset units, or `null`. */ max_qty: Decimal | null /** The asset's USD price at `observed_at`, or `null`. */ price: Decimal | null /** When the offer was read, ISO-8601 UTC. */ observed_at: string } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/earn/historical?assets=bitcoin&from=2026-11-01T00:00:00Z" ``` ### Directory #### GET /v1/networks The blockchain slice of the venue catalogue. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `search` | query | `string` | Free text matched against asset names and symbols; a comma is just a character. | Answer: `PlatformListEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface PlatformListEnvelope { /** The answer: one object, or a list of rows. */ data: Platform[] /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** * One row of `market.platforms` -- a venue, a chain, or a DEX, discriminated by `kind`. `/v1/platforms` serves every row; */ export interface Platform { /** The catalogue platform id (`binance`). */ id: string /** Name to show. */ name: string /** `cex`, `dex` or `blockchain`. */ kind: 'cex' | 'dex' | 'blockchain' /** * **An icon to show, not `market.platforms.icon`.** 25 of the 97 rows have no icon of their own, and all 25 carry a `native_asset` whose asset row does -- so the API serves that one instead and every platform comes back with an icon. The join is on `native_asset` and the path is taken whole: `morph` borrows `icons/asset/bitget-token.svg`, which contains neither its id nor its kind. */ icon_url: string | null /** About the platform, English Markdown, or `null`. */ about_en: string | null /** About the platform, Catalan Markdown, or `null`. */ about_ca: string | null /** About the platform, Spanish Markdown, or `null`. */ about_es: string | null /** Links as the catalogue holds them. */ urls: Json /** * The catalogue's `BlockchainCategory`, which today has **exactly one value**: `evm`. `null` on every venue and on every chain the catalogue has not labelled — 14 of the 58 chains carry it at 2026-08-21. */ category: string | null /** * The catalogue **asset id** of the chain's gas asset. Set for blockchains only -- 57 of the 97 rows, and the other 40 are every `cex` and every `dex`. */ native_asset_id: string | null /** `market.assets.display_name` for `native_asset` -- "xDAI", "Toncoin", "Bitget Token". */ native_asset_name: string | null /** `market.assets.symbol` for `native_asset` -- "ETH", "BGB", "xDAI". */ native_asset_symbol: string | null /** * `market.assets.icon` for `native_asset` -- the asset's own mark, whatever `icon` above ended up being. */ native_asset_icon_url: string | null /** * A **CAIP-2 namespace**, from the catalogue's `BlockchainNamespace`: `eip155`, `cosmos`, `bip122` or `solana`. `null` on every venue and on a chain the catalogue has not mapped. */ namespace: string | null /** * A chain id, as a **string**. `market.platforms.chain_id` is `text`, deliberately: it is an identifier, not a quantity, and CAIP-2 namespaces treat it as one — `eip155`'s are decimal (`1`, `42161`), `cosmos`'s are names (`cosmoshub-4`, `pacific-1`), `bip122`'s is a genesis block hash and `solana`'s is `mainnet-beta`. */ chain_id: string | null /** * **True when the portfolio can snapshot this venue** — what the connect form offers, minus the credential-schema condition. */ snapshot_supported: boolean } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/networks" ``` #### GET /v1/networks/{id} One network by id. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | The network's id. | Answer: `PlatformEnvelope` ```ts /** Every successful response, so a caller reads `meta` the same way everywhere. */ export interface PlatformEnvelope { /** The answer: one object, or a list of rows. */ data: Platform /** About the answer: its freshness, currency, window and page. */ meta: Meta } /** * One row of `market.platforms` -- a venue, a chain, or a DEX, discriminated by `kind`. `/v1/platforms` serves every row; */ export interface Platform { /** The catalogue platform id (`binance`). */ id: string /** Name to show. */ name: string /** `cex`, `dex` or `blockchain`. */ kind: 'cex' | 'dex' | 'blockchain' /** * **An icon to show, not `market.platforms.icon`.** 25 of the 97 rows have no icon of their own, and all 25 carry a `native_asset` whose asset row does -- so the API serves that one instead and every platform comes back with an icon. The join is on `native_asset` and the path is taken whole: `morph` borrows `icons/asset/bitget-token.svg`, which contains neither its id nor its kind. */ icon_url: string | null /** About the platform, English Markdown, or `null`. */ about_en: string | null /** About the platform, Catalan Markdown, or `null`. */ about_ca: string | null /** About the platform, Spanish Markdown, or `null`. */ about_es: string | null /** Links as the catalogue holds them. */ urls: Json /** * The catalogue's `BlockchainCategory`, which today has **exactly one value**: `evm`. `null` on every venue and on every chain the catalogue has not labelled — 14 of the 58 chains carry it at 2026-08-21. */ category: string | null /** * The catalogue **asset id** of the chain's gas asset. Set for blockchains only -- 57 of the 97 rows, and the other 40 are every `cex` and every `dex`. */ native_asset_id: string | null /** `market.assets.display_name` for `native_asset` -- "xDAI", "Toncoin", "Bitget Token". */ native_asset_name: string | null /** `market.assets.symbol` for `native_asset` -- "ETH", "BGB", "xDAI". */ native_asset_symbol: string | null /** * `market.assets.icon` for `native_asset` -- the asset's own mark, whatever `icon` above ended up being. */ native_asset_icon_url: string | null /** * A **CAIP-2 namespace**, from the catalogue's `BlockchainNamespace`: `eip155`, `cosmos`, `bip122` or `solana`. `null` on every venue and on a chain the catalogue has not mapped. */ namespace: string | null /** * A chain id, as a **string**. `market.platforms.chain_id` is `text`, deliberately: it is an identifier, not a quantity, and CAIP-2 namespaces treat it as one — `eip155`'s are decimal (`1`, `42161`), `cosmos`'s are names (`cosmoshub-4`, `pacific-1`), `bip122`'s is a genesis block hash and `solana`'s is `mainnet-beta`. */ chain_id: string | null /** * **True when the portfolio can snapshot this venue** — what the connect form offers, minus the credential-schema condition. */ snapshot_supported: boolean } export interface Meta { /** * The newest observation the answer reflects (an instant), or the catalogue's applied time for directories and search; `null` when nothing in `data` carries one. Never a calendar date. The ETag is derived from it. */ as_of: string | null /** The currency every money value in `data` is in. Only on routes whose `data` holds money. */ currency?: 'usd' | 'eur' /** * The newest observation in the whole dataset, before any filter or page: with `as_of` it tells "a filter matched nothing" from "never collected". `null` is a statement (the dataset never collected); absent means the route does not report it. */ collected_at?: string | null /** Collection routes: how much of what the venues published the answer holds. */ coverage?: Coverage /** `GET /v1/earn/latest?venues=`: the venue's best non-promotional APR, a fraction. */ best_apr?: number | null /** `GET /v1/earn/latest`: the USD stake `earnings_30d` is about, a decimal string. */ stake?: string /** The interval the series is in, echoed so a caller never assumes it. */ interval?: string /** Windowed routes: the effective half-open window the answer covers. */ range?: Range /** Paginated routes: where this page is and how to read on. */ page?: Page } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v1/networks/ethereum" ``` ## Series & snapshots (/v2) Typed series and snapshots with published contracts: each id names a contract (its fields, key, cadence and guarantees), and `/data` serves its records. `/v2/series` and `/v2/snapshots` list what your key can read. A contract is opened to keys once its redistribution is cleared; until then a read is `403` saying so. Every route below takes an id from the [catalogue](#v2-catalogue). Unlike `/v1`, `/v2` refuses parameters it does not know. #### GET /v2/series Lists only what the caller’s grants admit. Takes no parameters: any parameter is `400 bad_request` naming it, as on every `/v2` route. Key: `market:read` (Ultra). Answer ```ts type Answer = { data: V2SeriesEntry[] meta: V2Meta } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/series" ``` #### GET /v2/series/corrections Reserved and matched before `/v2/series/{id}`. Until the corrections log ships the feed is unavailable, never empty: an empty feed would claim nothing was ever corrected. Key: `market:read` (Ultra). ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/series/corrections" ``` #### GET /v2/series/{id} Only closed intervals are served: an interval appears once it has ended and been built. Retention is the current UTC date and the 89 before it. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A series id from the [catalogue](#v2-catalogue) (`asset.price.candles.1h`). | Answer ```ts type Answer = { data: V2SeriesContract meta: V2Meta } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/series/asset.price.candles.1h" ``` #### GET /v2/series/{id}/data Only closed intervals are served: an interval appears once it has ended and been built. Retention is the current UTC date and the 89 before it. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A series id from the [catalogue](#v2-catalogue) (`asset.price.candles.1h`). | | `assets` | query | `string[]` | Instances whose `asset` is one of these (comma-separated). | | `from` (required) | query | `string` | Inclusive start: a date (its 00:00Z) or an RFC 3339 instant with a zone (`Z` or `±HH:MM`). | | `to` | query | `string` | Exclusive end, a date or an RFC 3339 instant; after `from`. Defaults to now. | | `limit` | query | `number` | Records per page, 1 to 10000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.cursor.next`, bound to the same filters and range. | Answer ```ts type Answer = V2RecordsEnvelope & { data?: AssetPriceCandles1hRecord[] } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/series/bitcoin/data?from=2026-11-01T00:00:00Z" ``` #### GET /v2/series/{id}/latest Only closed intervals are served: an interval appears once it has ended and been built. Retention is the current UTC date and the 89 before it. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A series id from the [catalogue](#v2-catalogue) (`asset.price.candles.1h`). | | `assets` | query | `string[]` | Instances whose `asset` is one of these (comma-separated). | | `limit` | query | `number` | Records per page, 1 to 10000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.cursor.next`, bound to the same filters and range. | Answer ```ts type Answer = V2RecordsEnvelope & { data?: AssetPriceCandles1hRecord[] } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/series/bitcoin/latest" ``` #### GET /v2/series/{id}/instances Only closed intervals are served: an interval appears once it has ended and been built. Retention is the current UTC date and the 89 before it. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A series id from the [catalogue](#v2-catalogue) (`asset.price.candles.1h`). | | `assets` | query | `string[]` | Instances whose `asset` is one of these (comma-separated). | | `limit` | query | `number` | Records per page, 1 to 10000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.cursor.next`, bound to the same filters and range. | Answer ```ts type Answer = V2RecordsEnvelope & { data?: AssetPriceCandles1hInstance[] } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/series/bitcoin/instances" ``` #### GET /v2/snapshots Lists only what the caller’s grants admit. Takes no parameters: any parameter is `400 bad_request` naming it, as on every `/v2` route. Key: `market:read` (Ultra). Answer ```ts type Answer = { data: V2SnapshotEntry[] meta: V2Meta } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/snapshots" ``` #### GET /v2/snapshots/{id} A venue market that the latest successful collection no longer lists is removed. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A snapshot id from the [catalogue](#v2-catalogue) (`market.ticker`). | Answer ```ts type Answer = { data: V2SnapshotContract meta: V2Meta } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/snapshots/market.ticker" ``` #### GET /v2/snapshots/{id}/data A venue market that the latest successful collection no longer lists is removed. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `id` (required) | path | `string` | A snapshot id from the [catalogue](#v2-catalogue) (`market.ticker`). | | `assets` | query | `string[]` | Instances whose `asset` is one of these (comma-separated). | | `venues` | query | `string[]` | Instances whose `venue` is one of these (comma-separated). | | `exchange` | query | `string` | Instances whose `exchange` is this. | | `kind` | query | `string` | Instances whose `kind` is this. | | `market` | query | `string` | Instances whose `market` is this. | | `limit` | query | `number` | Records per page, 1 to 10000. | | `cursor` | query | `string` | Opaque: the previous page's `meta.cursor.next`, bound to the same filters and range. | Answer ```ts type Answer = V2RecordsEnvelope & { data?: MarketTickerSnapshot[] } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/v2/snapshots/market.ticker/data?assets=bitcoin&limit=3" ``` ### Catalogue Every id the `/v2` routes take: `https://api.tribulnation.com/v2/series` and `https://api.tribulnation.com/v2/snapshots` list them with their contracts. ## Live Live order books, markets, rates and opportunities across venues, never older than 30 s. Everything here needs a key with the `market:read` scope; market data over the API is included with Ultra, and a key on another plan is refused with `403`. ### Which to use | You need | Use | Answers | |---|---|---| | Every update as it is built | [WebSocket](#websocket) `wss://api.tribulnation.com/live/` | One frame per build, about every second for books, for as long as the socket is open | | The current book or asset now and then | [Snapshot](#snapshots-over-http) `GET /live/book/{asset}`, `GET /live/asset/{asset}` | The topic's current view, fresh, in one HTTP answer | | Ranked opportunities, funding, profiles | [Live JSON](#live-json) `GET /live/opportunities`, `/live/funding`, … | JSON pages and filters over the same live data | A WebSocket frame and a snapshot carry the same view, with the same field names, types and units as the rest of the API. The socket only adds `type`, `seq`, `v` and `ts_ms`. ### WebSocket ```text wss://api.tribulnation.com/live/[?depth=N] Authorization: Bearer tn_key_… ``` Open the socket with the key in the `Authorization` header, as on every other route. No cookie, `Origin` or subprotocol is needed. Browsers cannot set that header on a WebSocket and the API sends no CORS headers, so connect from a server or a script and keep the key there. Every frame is a whole view of the topic, not a change to the one before. Missing a frame, or reconnecting, loses nothing: the next frame is complete. Frames are JSON text: - **`view`** (`"type": "view"`): the topic's latest build. `seq` is one higher per build, `v` is the frame format (2), and `ts_ms` is the build time in epoch milliseconds (the one epoch number in the API; every other instant is ISO-8601). The fields that do not belong to the topic's kind are `null`, for example `markets` on a `book:` topic. - **`control`** (`"type": "control"`, `state` `reconnecting` or `stale`): the source went away, or nothing new came for 30 s. Treat the last view as old until the next `view` arrives. The socket stays open. - **`pong`**: the bare text answer to your `ping`, not JSON. Send `ping` about every 20 s so proxies do not drop an idle socket. The first `view` comes within a second for a topic someone is already watching. On a book or asset nobody watches, opening the socket starts the build. The first frame then comes from that build, never from an older one, and it can hold top-of-book only (`source: "top"`, `note: "rest_loading"`) until the depth loads a few seconds later. ### Topics | Topic | Frames carry | Built | |---|---|---| | `book:` | `books`: the order book of each of the asset's markets, each venue's main market first, up to 50 `[price, size]` levels a side (decimal strings), with `bid`, `ask`, `levels` (what the venue's feed holds) and `source` | About every second, while someone watches | | `asset:` | `markets` (fees, funding, mark and index, depth curve, maker quotes), `rate` (the asset's USD rate and how it was found) and `rows` (its opportunities) | About every second, while someone watches | | `rates` | `rates`: every asset's USD rate as `[usd, quality, hops, spread_bps, oldest_s, source]` | When the rates are recomputed | | `page:`, `page::` | `rows`: the best 64 opportunities of `funding-carry`, `cash-carry`, `earn-carry`, `hedged-taker` or `hedged-maker`; `:2`, `:3`, … are the next 64 each | About every second | Assets are catalogue ids such as `bitcoin`: `GET /v1/search?search=` finds one. The `rates` topic holds up to 900 assets. Above that it is published in parts instead, `rates:` holding the assets whose id starts with the character `c`. Then open the parts you need; `rates` itself stops updating and turns `stale`. Recorded frames, cut to a few entries (open one): Frame of `book:bitcoin` (`wss://api.tribulnation.com/live/book:bitcoin?depth=5`, recorded 2026-11-25; books cut to 3 of 115, levels cut to 3 a side): ```json { "type": "view", "seq": 9555, "v": 2, "ts_ms": 1795619294902, "topic": "book:bitcoin", "plan": "ultra", "delayed_s": 0, "status": "ok", "rows": [], "truncated": false, "locked": null, "withheld": null, "markets": null, "rate": null, "rates": null, "books": [ { "segment_id": "aster:perp", "market": "BTCUSDT", "kind": "perp", "quote_asset_id": "tether", "settlement_asset_id": "tether", "tier": "core", "source": "stream", "note": null, "error": null, "bid": "58020", "ask": "58020.1", "received_at": "2026-11-25T15:08:14.861Z", "depth_at": "2026-11-25T15:08:14.713Z", "levels": 20, "bids": [ ["58020", "0.026"], ["58018.4", "0.002"], ["58015", "0.002"] ], "asks": [ ["58020.1", "3.415"], ["58020.5", "2.626"], ["58020.9", "0.025"] ] }, { "segment_id": "aster:spot", "market": "BTCUSDT", "kind": "spot", "quote_asset_id": "tether", "tier": "core", "source": "stream", "note": null, "error": null, "bid": "58049.71", "ask": "58050.3", "received_at": "2026-11-25T15:08:14.758Z", "depth_at": "2026-11-25T15:08:14.758Z", "levels": 20, "bids": [ ["58049.71", "0.08986"], ["58045.64", "0.01583"], ["58015.45", "0.00276"] ], "asks": [ ["58050.3", "0.79433"], ["58052.61", "0.29832"], ["58052.62", "0.07778"] ] }, { "segment_id": "binance:spot", "market": "BTCUSDT", "kind": "spot", "quote_asset_id": "tether", "tier": "core", "source": "rest", "note": null, "error": null, "bid": "58050", "ask": "58050.01", "received_at": "2026-11-25T15:08:14.898Z", "depth_at": "2026-11-25T15:08:13.900Z", "levels": 38, "bids": [ ["58050", "0.3566"], ["58045", "4.66259"], ["58040", "9.09131"] ], "asks": [ ["58050.01", "4.33235"], ["58053.29", "1.67685"], ["58053.91", "0.0002"] ] } ], "starting": [] } ``` Frame of `asset:bitcoin` (`wss://api.tribulnation.com/live/asset:bitcoin`, recorded 2026-11-25; rows cut to 1 of 24, markets cut to 1 of 160): ```json { "type": "view", "seq": 5552, "v": 2, "ts_ms": 1795619296164, "topic": "asset:bitcoin", "plan": "ultra", "delayed_s": 0, "status": "ok", "rows": [ { "id": "funding-carry:bitcoin:evedex:perp/BTCUSD+gtrade:polygon-usdc/polygon-usdc:BTC/USD", "strategy": "funding-carry", "asset_id": "bitcoin", "symbol": "BTC", "legs": [ { "segment_id": "evedex:perp", "market": "BTCUSD", "kind": "perp", "side": "buy", "quote_asset_id": "tether", "peg_asset_id": "usd", "settlement_asset_id": "tether", "tier": "extended", "age_s": 0, "funding_interval_s": 3600 } ], "tier": "extended", "age_s": 0, "headline": { "apr": 0.854 }, "rank": 74.82, "edge_bps": -17.7, "edge_usd_bps": -3.7, "basis_bps": -14, "basis": [ "tether", "usd" ], "quote_exposure": null, "kind": "perp", "pair": "bitcoin|gtrade:polygon-usdc|evedex:perp", "long": "evedex:perp", "short": "gtrade:polygon-usdc", "long_market": "BTCUSD", "short_market": "polygon-usdc:BTC/USD", "apr": 0.854, "long_apr": -0.381, "short_apr": 0.473, "entry_bps": -17.7, "entry_bps_usd": -3.7, "cost_bps": 20.3, "cost_bps_usd": 20.3, "breakeven_s": 104400, "breakeven_usd_s": 50400, "size_usd": "100000", "fees_known": true, "premium_bps": -7.5, "premium_bps_usd": 6.5, "short_funding_apr": 0.493, "short_borrow_apr": 0.02 } ], "truncated": false, "locked": null, "withheld": null, "markets": [ { "segment_id": "aster:perp", "market": "BTCU", "kind": "perp", "quote_asset_id": "united-stables", "settlement_asset_id": "united-stables", "tier": "core", "bid": "58012.5", "ask": "58020.1", "bid_qty": "0.368", "ask_qty": "1.68", "mark_price": "58041.3", "index_price": "58062.62511044", "funding_rate": 0.00002239, "funding_interval_s": 28800, "next_funding_at": "2026-11-25T16:00:00.000Z", "open_interest": null, "received_at": "2026-11-25T15:08:16.159Z", "age_s": 0.005, "ctx_age_s": 0.999, "live": true, "taker_fee_bps": 3.5, "maker_fee_bps": 1, "fee_source": "configured", "levels": 20, "depth_age_s": 0.362, "curve": null, "maker": { "bid": "58002.9", "ask": "58010.5", "buy": [ { "quote": "58326.3", "vs_best_bps": 55.76, "join_bps": 55.6, "filled": 1, "hedges": [ "bitfinex:spot", "mexc:spot", "okx:spot" ] } ], "sell": [ { "quote": "57942.5", "vs_best_bps": 11.73, "join_bps": 11.73, "filled": 1, "hedges": [ "mexc:perp", "whitebit:spot" ] } ] } } ], "rate": { "usd": "57967.065", "quality": "ok", "source": "markets", "markets": [ { "segment_id": "binance:spot", "market": "BTCUSD", "hop": 1, "mid": "58028.95" } ], "dropped": [ { "segment_id": "bitfinex:spot", "market": "BTCUSD", "mid": "58146" } ], "hops": 1, "spread_bps": 13.1816230475005, "oldest_s": 7.447 }, "rates": null, "books": null, "starting": null } ``` Frame of `rates` (`wss://api.tribulnation.com/live/rates`, recorded 2026-11-25; rates cut to 3 of 896 assets): ```json { "type": "view", "seq": 51692, "v": 2, "ts_ms": 1795537279462, "topic": "rates", "plan": "ultra", "delayed_s": 0, "status": "ok", "rows": [], "truncated": false, "locked": null, "withheld": null, "markets": null, "rate": null, "rates": { "0x": [ "0.07570733450000001", "ok", 2, 7.56510255951487, 4.251, "markets" ], "1inch": [ "0.05817", "ok", 1, 6.87639676809324, 5.248, "markets" ], "375ai": [ "0.002635", "thin", 1, 0, 5.112, "markets" ] }, "books": null, "starting": null } ``` Frame of `page:funding-carry` (`wss://api.tribulnation.com/live/page:funding-carry`, recorded 2026-11-25; rows cut to 1 of 64): ```json { "type": "view", "seq": 81947, "v": 2, "ts_ms": 1795619273653, "topic": "page:funding-carry", "plan": "ultra", "delayed_s": 0, "status": "ok", "rows": [ { "id": "funding-carry:solayer:bitunix:perp/LAYERUSDT+apex:perp/LAYERUSDT", "strategy": "funding-carry", "asset_id": "solayer", "symbol": "LAYER", "legs": [ { "segment_id": "bitunix:perp", "market": "LAYERUSDT", "kind": "perp", "side": "buy", "quote_asset_id": "tether", "peg_asset_id": "usd", "settlement_asset_id": "tether", "tier": "extended", "age_s": 0.419, "funding_interval_s": 14400 } ], "tier": "extended", "age_s": 1.018, "headline": { "apr": 13.3 }, "rank": 1293.97, "edge_bps": -31.2, "edge_usd_bps": -31.2, "basis_bps": null, "basis": null, "quote_exposure": null, "kind": "perp", "pair": "solayer|apex:perp|bitunix:perp", "long": "bitunix:perp", "short": "apex:perp", "long_market": "LAYERUSDT", "short_market": "LAYERUSDT", "apr": 13.3, "long_apr": -13.5, "short_apr": -0.172, "entry_bps": -31.2, "entry_bps_usd": -31.2, "cost_bps": 69.1, "cost_bps_usd": 69.1, "breakeven_s": 14400, "breakeven_usd_s": 14400, "size_usd": "1000", "fees_known": true, "premium_bps": 3.4, "premium_bps_usd": 3.4, "hedge": 0 } ], "truncated": true, "locked": null, "withheld": null, "markets": null, "rate": null, "rates": null, "books": null, "starting": null } ``` ### Book depth and frame size `?depth=N` cuts every book of a `book:` socket (or snapshot) to its best `N` levels a side, 1 to 50. Without it you get every level the source holds, up to 50. `levels` still says how many the source holds. Depth applies to `book:` topics only; elsewhere it is refused with `400`. A socket that needs the top ten levels receives about half the bytes: | Topic | `depth` | One frame | Holding | |---|---|---|---| | `book:bitcoin` | every level (50) | 141 KB | 115 books | | `book:bitcoin` | 20 | 101 KB | 115 books | | `book:bitcoin` | 10 | 74 KB | 115 books | | `book:bitcoin` | 5 | 56 KB | 115 books | | `book:bitcoin` | 1 | 40 KB | 115 books | | `asset:bitcoin` | – | 140 KB | 160 markets, 24 rows | | `rates` | – | 63 KB | 896 assets | | `page:funding-carry` | – | 75 KB | 64 rows | Measured on the prototype on 2026-11-25; sizes follow the number of markets and levels the venues hold. ### Connection lifecycle Every socket gets a grant of 60 s. When it ends, the server closes the socket with 4001. Reconnect at once: the key, its scope and your plan are checked again, and the first frame after the reconnect is the topic's latest build, so nothing is lost. The slot of the closed socket is freed before the close, so the reconnect never counts against the [limits](#socket-limits) twice. | Close code | Means | Do | |---|---|---| | `4001` | The socket’s one-minute grant ended: every socket gets it about a minute after it opens; your key and plan are checked again on reconnect. | Reconnect at once | | `4401` | The key was revoked. | Stop; the next open is 401 | | `4003` | The topic is not in your plan. | Stop | | `4004` | Unknown topic. | Stop | | `1011` | The server could not build the topic’s view for this socket. | Reconnect with backoff | Any other close, or a dropped connection, means: reconnect with backoff (1 s, doubling to about 30 s, reset after a frame). When a key is revoked on https://app.tribulnation.com/integrations, its sockets stop receiving frames at once and close with 4401 shortly after. After a move off Ultra, open sockets run to the end of their grant and the reconnect is refused with `403`: within about a minute and a half. ### Refusals A socket is refused before it opens, as a plain HTTP answer with the [error body](#errors) every route uses: ```json {"error": {"code": "rate_limited", "message": "this key already holds 32 live sockets (the limits are 32 sockets and 16 topics per key, 32 sockets per account); close one first"}} ``` | Status | `code` | When | Retry? | |---|---|---|---| | `400` | `bad_request` | `depth` is not a whole number from 1 to 50, or is set on a topic other than `book:` | No | | `401` | `unauthorized` | No key, or the key is unknown, expired or revoked | No | | `403` | `forbidden` | The key has no `market:read`, the plan is not Ultra, or the topic is not open to keys | No | | `404` | `not_found` | No such topic (`page:nope`), or an asset the catalogue does not hold | No | | `426` | `upgrade_required` | A plain `GET` on a socket path: use a WebSocket, or a [snapshot](#snapshots-over-http) | No | | `429` | `rate_limited` | Over a [socket limit](#socket-limits) (`Retry-After: 10`), or over your account's fair use (`Retry-After: 60`) | After `Retry-After` | | `503` | `unavailable` | The live service did not answer | After `Retry-After` | Each socket open counts as one request against your account's [fair use](#fair-use-and-429). Frames on an open socket do not count; the bound there is the [socket limits](#socket-limits): 32 sockets and 16 distinct topics per key, 32 sockets per account across all its keys. Several sockets may share one topic. ### Examples The Python client (`tribulnation-terminal` 0.5.0 or later) and the TypeScript client (`@tribulnation/terminal` 0.2.0 or later) do all of the above for you: they send the key, ping, reconnect at once on 4001, back off on other closes, retry `429` and `5xx` after `Retry-After`, and stop with an error on 4401, 4003, 4004 or a refusal that will not change. ```python from tribulnation.terminal import Terminal async with Terminal.new() as t: # reads TN_API_KEY async for frame in t.live.stream('book:bitcoin', depth=10): if frame['type'] == 'view': for b in frame['books'][:3]: print(b['segment_id'], b['bid'], b['ask']) ``` ```ts // Coming to npm: @tribulnation/terminal is not published yet. import { Terminal } from '@tribulnation/terminal' const t = new Terminal() // reads TN_API_KEY for await (const frame of t.live.stream('book:bitcoin', { depth: 10 })) { if (frame.type === 'view') console.log(frame.books?.slice(0, 3).map((b) => [b.segment_id, b.bid, b.ask])) } ``` Without a client, in Python with [`websockets`](https://pypi.org/project/websockets/) (`pip install websockets`): ```python import asyncio, contextlib, json, os from websockets.asyncio.client import connect from websockets.exceptions import ConnectionClosed, InvalidStatus URL = 'wss://api.tribulnation.com/live/book:bitcoin?depth=10' HEADERS = {'Authorization': f'Bearer {os.environ["TN_API_KEY"]}'} STOP = {4401, 4003, 4004} # revoked, not in plan, unknown topic async def ping(ws): with contextlib.suppress(ConnectionClosed): while True: await asyncio.sleep(20) await ws.send('ping') async def main(): delay = 1 while True: code = None try: async with connect(URL, additional_headers=HEADERS, ping_interval=None, max_size=2**22) as ws: pinger = asyncio.create_task(ping(ws)) try: async for text in ws: if text == 'pong': continue frame = json.loads(text) if frame['type'] == 'view': delay = 1 for b in frame['books'][:3]: print(b['segment_id'], b['bid'], b['ask']) except ConnectionClosed: pass finally: pinger.cancel() code = ws.close_code except InvalidStatus as e: # refused before the upgrade r = e.response if r.status_code != 429 and r.status_code < 500: raise SystemExit(f'refused {r.status_code}: {r.body.decode()}') await asyncio.sleep(float(r.headers.get('Retry-After', delay))) continue except OSError: pass # no connection: back off below if code == 4001: continue # the once-a-minute close: reconnect at once if code in STOP: raise SystemExit(f'closed {code}') await asyncio.sleep(delay) delay = min(delay * 2, 30) asyncio.run(main()) ``` In JavaScript on Node 22 or later, whose built-in `WebSocket` takes a `headers` option: ```js const URL = 'wss://api.tribulnation.com/live/book:bitcoin?depth=10' const headers = { Authorization: `Bearer ${process.env.TN_API_KEY}` } const STOP = new Set([4401, 4003, 4004]) // revoked, not in plan, unknown topic let delay = 1000 function open() { const ws = new WebSocket(URL, { headers }) let ping ws.onopen = () => { ping = setInterval(() => ws.send('ping'), 20_000) } ws.onmessage = ({ data }) => { if (data === 'pong') return const frame = JSON.parse(data) if (frame.type !== 'view') return delay = 1000 for (const b of frame.books.slice(0, 3)) console.log(b.segment_id, b.bid, b.ask) } ws.onclose = ({ code }) => { clearInterval(ping) if (code === 4001) return open() // the once-a-minute close: reconnect at once if (STOP.has(code)) return console.error('closed', code) // A refused open also lands here (1006, without its status): the same key on // GET /live/book/bitcoin answers why. setTimeout(open, delay) delay = Math.min(delay * 2, 30_000) } } open() ``` From a shell, `tn terminal watch book:bitcoin --depth 10` prints a refreshing top of book per venue, and `--json` one frame per line ([Command line](#command-line)). The [MCP server](#mcp-server) does not stream: its `order_book` tool reads a fresh book snapshot (depth 10 unless asked), and an agent that needs a stream writes a program against this socket. ### Snapshots over HTTP `GET /live/book/{asset}` and `GET /live/asset/{asset}` answer the topic's current view as `data`, with `age_s` and the header `Data-Delay-Ms: 0`. A read of an asset someone is watching answers at once. A read of one nobody watches starts its build and waits for full books, typically 2 to 4 s, at most 3.5 s; if none is ready by then the answer is `503` with code `warming` and `Retry-After: 2`: retry after that. Each read keeps the asset warm for 30 s, so polling it answers at once. One account keeps at most 16 assets warm at a time; one more is `429` until the oldest expires ([Live freshness](#live-freshness)). Each read counts against your [fair use](#fair-use-and-429). The Python client's `t.live.book(asset, depth=)` and `t.live.asset(asset)` retry `warming` for you. ```sh curl -sH "Authorization: Bearer $TN_API_KEY" "https://api.tribulnation.com/live/book/bitcoin?depth=5" ``` #### GET /live/book/{asset} One asset’s order books, fresh: the read watches book: for 30 s and waits for a full build (≤ 3.5 s, else 503 warming); ?depth=1..50 levels a side (live: the WebSocket /live/book:). Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `asset` (required) | path | `string` | A catalogue asset id (`bitcoin`); `/v1/search` finds it. | | `depth` | query | `number` | Levels a side, 1 to 50 (default: every level). | Answer ```ts type Answer = { data: { age_s: number stale: false v: 2 topic: string plan: 'free' | 'pro' | 'ultra' delayed_s: number status: 'ok' | 'not_ready' locked: Locked | null withheld: Withheld | null books: Book[] | null starting: string[] | null } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/book/bitcoin?depth=3" ``` #### GET /live/asset/{asset} One asset’s markets, rate and rows, fresh as /live/book/{asset} (live: the WebSocket /live/asset:). Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `asset` (required) | path | `string` | A catalogue asset id (`bitcoin`); `/v1/search` finds it. | Answer ```ts type Answer = { data: { age_s: number stale: false v: 2 topic: string plan: 'free' | 'pro' | 'ultra' delayed_s: number status: 'ok' | 'not_ready' rows: (TakerRow | FundingCarryRow | CashCarryRow | EarnCarryRow | MakerRow)[] truncated: boolean locked: Locked | null withheld: Withheld | null markets: Market[] | null rate: Rate | null rates: { [key: string]: CompactRate } | null books: Book[] | null starting: string[] | null } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/asset/bitcoin" ``` ### Live JSON #### GET /live/opportunities Every opportunity the plan sees, ranked. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `limit` | query | `number` | Rows of each strategy per page, 1 to 1000 (default 100). | | `cursor` | query | `string` | The previous page's `meta.page.next_cursor`. | Answer ```ts type Answer = { data: { delayed_s: number plan: 'free' | 'pro' | 'ultra' notionals: Decimal[] stats_notional: Decimal maker_notional: Decimal taker: (TakerRow | FundingCarryRow | CashCarryRow | EarnCarryRow | MakerRow)[] carry: (TakerRow | FundingCarryRow | CashCarryRow | EarnCarryRow | MakerRow)[] earn: (TakerRow | FundingCarryRow | CashCarryRow | EarnCarryRow | MakerRow)[] maker: (TakerRow | FundingCarryRow | CashCarryRow | EarnCarryRow | MakerRow)[] strategies: { 'funding-carry': LiveStrategyState 'cash-carry': LiveStrategyState 'earn-carry': LiveStrategyState 'hedged-taker': LiveStrategyState 'hedged-maker': LiveStrategyState } live: boolean error: null } meta: { as_of: string | null assets?: Record page?: { limit: number has_more: boolean next_cursor: string | null total?: number } } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/opportunities" ``` #### GET /live/opportunities/{asset} One asset: its markets with fees, depth and maker ladder, its rows. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `asset` (required) | path | `string` | A catalogue asset id (`bitcoin`); `/v1/search` finds it. | Answer ```ts type Answer = { data: { asset_id: string plan: 'free' | 'pro' | 'ultra' delayed_s: number markets: Market[] | null rate: Rate | null rows: (TakerRow | FundingCarryRow | CashCarryRow | EarnCarryRow | MakerRow)[] withheld: Withheld | null truncated: boolean live: boolean error: null } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/opportunities/bitcoin" ``` #### GET /live/funding Funding spreads of the perp pairs, filtered (venues, assets, min_apr), ordered (sort) and paged (limit, cursor; 50 a page by default). Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `venues` | query | `string` | Only pairs on these venues, comma-separated catalogue venue ids (a leg's `segment_id` before `:`), at most 200; `venue_match` says whether both legs or one must be on them. Ids in no pair are listed in `meta.unmatched`. | | `venue_match` | query | `'all' \| 'any'` | `all` (default): both legs on a listed venue, pairs the caller can trade there; `any`: at least one leg. | | `assets` | query | `string` | Only these assets, comma-separated catalogue ids, at most 200. | | `min_apr` | query | `number` | Only pairs whose sort figure (`carry` when `sort` is `rank` or `breakeven`) is at least this, a fraction a year (`0.1` = 10 %). | | `sort` | query | `'rank' \| 'carry' \| 'current' \| 'avg_1d' \| 'avg_7d' \| 'avg_30d' \| 'breakeven'` | `rank` (default): the Opportunities page’s order; a figure (`carry`, `current`, `avg_1d`, `avg_7d`, `avg_30d`) highest first; `breakeven` shortest `breakeven_s` first. Pairs without the figure go last. | | `limit` | query | `number` | Pairs per page, 1 to 1000 (default 50); `meta.page.total` says how many pairs match. | | `cursor` | query | `string` | The previous page's `meta.page.next_cursor`, sent with the same filters and `sort` (a cursor of other filters is refused). | Answer ```ts type Answer = { data: { end: string | null pairs: FundingRow[] settlements_error?: string | null locked: Locked | null withheld: Withheld | null others?: { [key: string]: number } filter?: string short?: boolean teaser?: { total: number best: { apr?: number edge_bps?: number } } } meta: { as_of: string | null assets?: Record page?: { limit: number has_more: boolean next_cursor: string | null total?: number } unmatched?: { venues?: string[] assets?: string[] } } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/funding" ``` #### GET /live/funding/history One pair’s hourly funding over 30 days. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `pair` (required) | query | `string` | A pair as `/live/funding` lists it: `\|\|`. | Answer ```ts type Answer = { data: { a: (number | null)[] b: (number | null)[] avg_1d: (number | null)[] avg_7d: (number | null)[] spread: (number | null)[] cumulative: number[] pair: FundingRow settlements_error?: string | null borrow_included?: true other?: { avg_1d: (number | null)[] avg_7d: (number | null)[] spread: (number | null)[] cumulative: number[] pair: FundingRow } } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/funding/history?pair=bitcoin|binance|hyperliquid" ``` #### GET /live/funding/perps Per asset, the perp paying a short the most, filtered (venues, assets, min_apr), ordered (sort) and paged (limit, cursor; 100 a page by default). Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `venues` | query | `string` | Only perps on these venues, comma-separated catalogue venue ids, at most 200. Ids in no perp are listed in `meta.unmatched`. | | `assets` | query | `string` | Only these assets, comma-separated catalogue ids, at most 200. | | `min_apr` | query | `number` | Only perps whose `funding_apr` is at least this, a fraction a year (`0.1` = 10 %). | | `sort` | query | `'rank' \| 'funding_apr'` | `rank` (default): the app’s order; `funding_apr` highest first. | | `limit` | query | `number` | Perps per page, 1 to 1000 (default 100); `meta.page.total` says how many perps match. | | `cursor` | query | `string` | The previous page's `meta.page.next_cursor`, sent with the same filters and `sort` (a cursor of other filters is refused). | Answer ```ts type Answer = { data: { perps: { asset_id: string symbol: string segment_id: string market: string funding_apr: number funding_interval_s: number | null bid_usd: Decimal | null taker_fee_bps: number | null perps: number }[] } meta: { as_of: string | null assets?: Record page?: { limit: number has_more: boolean next_cursor: string | null total?: number } unmatched?: { venues?: string[] assets?: string[] } } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/funding/perps" ``` #### GET /live/spreads/history A pair’s edges, basis and funding over a window. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `pair` (required) | query | `string` | `\|\|`, optionally with `/` after a segment. | | `from` | query | `string` | Window start, inclusive: a date or an instant with a zone (default: 7 days before `to`). | | `to` | query | `string` | Window end, exclusive: a date or an instant with a zone (default: now). | Answer ```ts type Answer = { data: { pair: string asset_id: string symbol: string segment_id_a: string market_a: string segment_id_b: string market_b: string bucket_s: number ab_last_bps: (number | null)[] ab_max_bps: (number | null)[] ba_last_bps: (number | null)[] ba_max_bps: (number | null)[] mid_diff_bps: (number | null)[] index_diff_bps: (number | null)[] premium_diff_bps: (number | null)[] funding_a: (number | null)[] funding_b: (number | null)[] index_a: (Decimal | null)[] index_b: (Decimal | null)[] } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/spreads/history?pair=bitcoin|binance:usdm|hyperliquid:" ``` #### GET /live/exchanges Every exchange the live data covers (spot or perp, CEX or DEX), ranked, with how many markets it lists, trades and pairs. Key: `market:read` (Ultra). Answer ```ts type Answer = { data: ExchangeInfo[] meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/exchanges" ``` #### GET /live/profile A perp market’s funding profile: live index, mark, funding, OI, the venue’s rules, what is missing, history. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `asset` (required) | query | `string` | A catalogue asset id (`bitcoin`). | | `venue` | query | `string` | Only this venue or segment id (`hyperliquid`). | | `market` | query | `string` | Only this venue market symbol (`BTC`). | | `window` | query | `'1d' \| '7d' \| '30d'` | Add one market’s history over this window (give `venue` and `market`). | Answer ```ts type Answer = { data: { asset_id: string markets: MarketProfile[] more: number } meta: { as_of: string | null } } ``` ```sh curl -sH "Authorization: Bearer $TN_API_KEY" \ "https://api.tribulnation.com/live/profile?asset=bitcoin&venue=hyperliquid" ``` ### Socket reference #### GET /live/{topic} The live socket: a WebSocket of a topic’s frames. Send `Upgrade: websocket`; a plain GET is 426. Key: `market:read` (Ultra). | Parameter | In | Type | Description | |---|---|---|---| | `topic` (required) | path | `string` | `book:`, `asset:`, `rates`, `rates:` (a part of `rates` once it splits) or `page:[:]`. | | `depth` | query | `number` | Book topics only: Levels a side, 1 to 50 (default: every level). | Answer: `LiveFrame` ```ts /** * A JSON text frame: a topic’s view (`type: "view"`, one per build) or the hub’s word that its source went away (`type: "control"`). The answer to a `ping` is the bare text `pong`, not JSON. */ export type LiveFrame = { type: 'view' seq: number v: 2 ts_ms: number topic: string plan: 'free' | 'pro' | 'ultra' delayed_s: number status: 'ok' | 'not_ready' rows: (TakerRow | FundingCarryRow | CashCarryRow | EarnCarryRow | MakerRow)[] truncated: boolean locked: Locked | null withheld: Withheld | null markets: Market[] | null rate: Rate | null rates: { [key: string]: CompactRate } | null books: Book[] | null starting: string[] | null } | { type: 'control' state: 'reconnecting' | 'stale' } /** * Free's locked rows: one line, their count and best figure (owner, 2026-10-28). No locked row is sent, not even its asset. */ export interface Locked { /** How many rows are locked. */ count: number /** The best locked row's headline: the teaser line's "up to 42 % APR". */ best: { apr?: number edge_bps?: number } } export interface Withheld { /** How many rows are withheld. */ count: number /** The best withheld row's headline: "up to 38 % APR". */ best: { apr?: number edge_bps?: number } /** The plan that shows them. */ tier: 'extended' } /** One market of an asset, in store units; null is unknown (0.2 item 2). */ export interface Market { /** Exchange id `:`. */ segment_id: string /** The venue's own symbol. */ market: string kind: 'perp' | 'spot' /** Price-tracking quote, a catalogue asset id. */ quote_asset_id: string /** * Differs from `quote_asset_id` where the index tracks another currency than the margin (Lighter BTC: quote tether, settle usd-coin). */ settlement_asset_id?: string /** * The catalogue perpetual's `quanto`: it pays 1 `settlement_asset_id` unit per `quote_asset_id` price point (an HK$-priced Tencent perp settled in USDT), so size x price is in `settlement_asset_id`, not `quote_asset_id`. Absent otherwise. */ quanto?: true /** * The catalogue's base units per contract where not 1: the market is in store units, as the venue sends it, so its prices (bid, ask, mark, index, impact, curve) are per contract and its sizes and `oi` count contracts. Divide prices by it (multiply quantities) for per base unit. */ multiplier?: number tier: 'core' | 'extended' bid: Decimal | null ask: Decimal | null bid_qty: Decimal | null ask_qty: Decimal | null /** Perp context; null on spot. */ mark_price: Decimal | null index_price: Decimal | null /** Funding rate per interval, a fraction. */ funding_rate: number | null funding_interval_s: number | null /** The instant of the next funding. */ next_funding_at: string | null /** Open interest, base units. */ open_interest: Decimal | null /** When the top was received. */ received_at: string | null /** Receive age of the top when the snapshot was built, seconds. */ age_s: number | null /** * Receive age of the perp context (mark, index, funding, interval, next funding, oi) when the snapshot was built, seconds; null without one. The context comes on its own stream or poll and can lag the top. */ ctx_age_s: number | null /** * The venue's impact bid and ask where its context carries them (Hyperliquid's impactPxs); absent elsewhere. */ impact_bid?: Decimal impact_ask?: Decimal /** * One interval's funding rate bounds where the venue states them per market (Binance's and Aster's fundingInfo); absent elsewhere. */ funding_cap?: number funding_floor?: number /** * The short side's own funding rate per interval (+ = shorts pay) where the venue charges each side its own (gTrade; `funding` is then the long side's, + = longs pay); absent elsewhere. */ funding_short?: number /** * The fee per interval a long pays the venue to hold, on top of funding (gTrade's borrowing fee to its vault; + = pays); absent where the venue charges no borrow. */ borrow?: number /** The same for a short; set with `borrow`. */ borrow_short?: number /** The market's feed is connected and its top fresh (not the context: `ctx_age_s`). */ live: boolean /** * The top is the venue's bulk REST data at a coarse cadence, not a stream. Absent: streamed. */ polled?: boolean /** Taker fee, bps of notional; null when VM-live prices the market with no fees. */ taker_fee_bps: number | null /** Maker fee of a buy, bps of notional (negative a rebate); null as `taker_fee_bps`. */ maker_fee_bps: number | null /** * Where the fees come from: `api` the venue's public API, read with its listing; `configured` VM-live's `fees.toml` (its exchange rates or an override); `standard` the venue's published base tier as the collector's universe had it. VM-live holds no account fees. Null with the fees. */ fee_source: 'standard' | 'configured' | 'api' | null /** Book levels held, the deeper side's; null for a feed that keeps tops only. */ levels: number | null /** Receive age of the held levels when the snapshot was built, seconds; null as `levels`. */ depth_age_s: number | null /** * The held book's curve points (0.7 item 7); null without levels or without a rate for the market's quote. Dropped first, extended markets' before core ones, when the snapshot is over its size limit (`fitAsset`). */ curve: MarketCurve | null /** * The market's break-even maker quotes at `MAKER_NOTIONALS`; null when the pricer does not price the market. */ maker: MarketMaker | null } export interface Rate { /** US dollars per unit of the asset. */ usd: Decimal quality: 'ok' | 'thin' | 'peg' | 'ecb' | 'aggregator' source: 'markets' | 'peg' | 'ecb' | 'aggregator' /** Kept estimates, sorted by exchange then market; empty unless `source` is `markets`. */ markets: RateMarket[] /** Outliers dropped, sorted by exchange then market. Ineligible markets are listed nowhere. */ dropped: RateDropped[] /** The largest hop kept; 0 for the fallbacks. */ hops: number /** Range of the kept estimates in bps of `usd`; 0 for one estimate. */ spread_bps: number /** Age in seconds, when the rate is computed, of the oldest input behind the kept estimates. */ oldest_s: number /** ECB reference date `YYYY-MM-DD`; only when `source` is `ecb`. */ ref_date?: string /** * The ECB note: market rate vs ECB rate in bps, only for a fiat priced from markets more than 200 bps from its ECB rate. */ ecb_diff_bps?: number } /** * A rate in compact form: `[usd, quality, hops, spread_bps, oldest_s, source]`. `usd` is the asset's USD price, a decimal string; `oldest_s` the age of its oldest input, seconds. */ export type CompactRate = [Decimal, 'ok' | 'thin' | 'peg' | 'ecb' | 'aggregator', number, number, number, 'markets' | 'peg' | 'ecb' | 'aggregator'] /** One market's order book in a `book:` snapshot. */ export interface Book { /** Exchange id `:`. */ segment_id: string /** The venue's own symbol. */ market: string kind: 'perp' | 'spot' /** Price-tracking quote, a catalogue asset id. */ quote_asset_id: string settlement_asset_id?: string /** As on `Market`: size x price is in `settlement_asset_id`. */ quanto?: true /** As on `Market`: base units per contract where not 1; levels are per contract. */ multiplier?: number tier: 'core' | 'extended' source: 'stream' | 'rest' | 'top' /** Why a `top` book has no levels; null for `stream` and `rest`. */ note: 'tops_only' | 'rest_loading' | 'rest_failed' | 'rest_over_budget' | null /** The last REST read's error when `note` is `rest_failed`; else null. */ error: string | null /** The market's top of book (null when not held). */ bid: Decimal | null ask: Decimal | null /** When the top was received. */ received_at: string | null /** When the levels were received (stream) or read (rest); null for `top`. */ depth_at: string | null /** * Levels the source holds, the deeper side's, before the cut to `bids`/`asks`; null for `top`. */ levels: number | null /** Best first, at most `TOPIC_LIMITS.bookLevels`; empty for `top`. */ bids: [Decimal, Decimal][] asks: [Decimal, Decimal][] } ``` ```sh tn terminal watch book:bitcoin --depth 10 # --json: one frame per line ``` ## Errors Errors are JSON, always the same shape. Branch on `code`, never on `message`: ```json { "error": { "code": "forbidden", "message": "market data needs the Ultra plan" } } ``` | Status | `code` | Meaning | Retry? | |---|---|---|---| | 400 | `bad_request` | A parameter is missing, unknown (`/v2`) or out of range: `message` says which. | No: fix the request | | 401 | `unauthorized` | No key, or the key is unknown, expired or revoked. | No | | 403 | `forbidden` | The key lacks the scope, or the owner’s plan does not include the data. | No | | 404 | `not_found` | No such route, asset, id or pair. | No | | 410 | `gone` | A retired route. | No | | 429 | `rate_limited` | Over the fair-use limit or a socket limit. | Yes, after `Retry-After` | | 503 | `unavailable` | An outage or a build on our side, never your request. | Yes, after `Retry-After` | | 503 | `warming` | A live asset is being built for the first time. | Yes, after `Retry-After` | | 426 | `upgrade_required` | A socket path asked without `Upgrade: websocket`. | No: open a WebSocket | | 500 | `internal` | A bug on our side. | Yes, with backoff | A `503` is an outage or a build on our side, never your key or request. Redirects are never needed: do not follow one with your key. ### User-Agent and plain-text 403 Every API error is the JSON above. A `403` with a plain-text body, such as `error code: 1010`, never reached the API: the network in front of it refused the request, usually for a library's default `User-Agent` (Python's `urllib` sends `Python-urllib/3.x`). Send a `User-Agent` naming your program. `curl`, `requests`, `httpx`, `aiohttp`, Node and the Terminal clients send one already. ```python import json, os, urllib.request req = urllib.request.Request( "https://api.tribulnation.com/me", headers={ "Authorization": f"Bearer {os.environ['TN_API_KEY']}", "User-Agent": "my-script/1.0", }, ) with urllib.request.urlopen(req) as res: print(json.load(res)) ``` ## Clients & tools ### Python [`tribulnation-terminal`](https://pypi.org/project/tribulnation-terminal/) is a typed async client: every route has a method, answers are validated into typed models (money as `Decimal`, times as `datetime`), and the live socket reconnects by itself. ```sh pip install tribulnation-terminal ``` ```python from tribulnation.terminal import Terminal async with Terminal.new() as t: # TN_API_KEY, or the key `tn terminal auth login` saved portfolio = await t.me.portfolio.get(hours=24 * 7) funding = await t.v1.market.perps.funding.latest(assets=['bitcoin']) ``` The client reads `TN_API_KEY`, else the saved login, and sends a saved key only to the host that issued it. A route without a method yet: `await t.get('/v1/earn/historical', asset='bitcoin')`. ### TypeScript `@tribulnation/terminal` is coming to npm soon. `@tribulnation/terminal` has no dependencies and returns the wire JSON as typed, without converting it: money stays a decimal string (`Decimal = string`), times stay as sent. It runs on Node 18+ (REST), and on Node 22+, Deno, Bun and Cloudflare Workers with the socket. Browsers are not supported: a key is a secret, and the API sends no CORS headers. ```ts // Coming to npm: @tribulnation/terminal is not published yet. import { Terminal, pages } from '@tribulnation/terminal' const t = new Terminal() // reads TN_API_KEY const prices = await t.v1.prices.latest({ assets: ['bitcoin', 'ethereum'] }) for await (const page of pages(t.v1.candles, { asset: 'bitcoin', start: '2026-11-01', end: '2026-11-15' })) console.log(page.data.length) ``` ### Command line One install gives `tn terminal`; every command takes `--json`. ```sh uv tool install 'tribulnation-terminal[cli]' tn terminal auth login # approve the code in your browser tn terminal portfolio --window 7d tn terminal positions --json tn terminal funding bitcoin --venue binance,hyperliquid --since 3d tn terminal watch book:bitcoin --depth 10 ``` ### MCP server `https://api.tribulnation.com/mcp` is a remote MCP server (Streamable HTTP, OAuth 2.1 sign-in). The client signs you in on https://app.tribulnation.com and gets its own key, which you can revoke on `/integrations`. - **Claude Code:** `claude mcp add --transport http tribulnation-terminal https://api.tribulnation.com/mcp`, then run `/mcp` and choose *Authenticate*. - **Claude (claude.ai, desktop):** Settings › Connectors › Add custom connector, paste `https://api.tribulnation.com/mcp`, then Connect. - **ChatGPT:** Settings › Apps › Advanced settings, turn on developer mode, then Create app with `https://api.tribulnation.com/mcp` and OAuth. - **Any other MCP client:** add `https://api.tribulnation.com/mcp` as a remote (HTTP) server; it discovers the sign-in from `https://api.tribulnation.com/.well-known/oauth-protected-resource/mcp`. The tools a client sees follow its key's scopes. The server answers; it does not stream: a program that needs a stream opens the [live socket](#websocket). | Tool | Scope | What it answers | |---|---|---| | `me` | any key | Key and plan: What this connection’s key is: its name, scopes (me:read: your own data; me:profiles: create and edit portfolio profiles; market:read: market data, Ultra only), when it expires, and the account’s plan. | | `accounts` | `me:read` | Connected accounts: The exchange and wallet accounts connected to the portfolio, with their venue and sync status. | | `profiles` | `me:read` | Portfolio profiles: The portfolio profiles (named groups of accounts) and which is the default. | | `create_profile` | `me:profiles` | Create a portfolio profile: Create a portfolio profile: a named set of rules choosing which accounts and markets the portfolio counts (as on the Portfolio page). | | `update_profile` | `me:profiles` | Change a portfolio profile: Change a portfolio profile: only the fields given, the rest kept (a rule list given replaces that list). | | `portfolio` | `me:read` | Portfolio P&L: Profit and loss over a trailing window for a profile: total P&L split into trading, funding and fees, volume, fills, equity, net delta and gross notional, the accounts’ margin, then one row per asset with its per-market legs. | | `activity` | `me:read` | Fills, funding and transfers: Every fill (or funding payment, or on-chain wallet transfer) of a profile over a trailing window, newest first, a page at a time: `total` says how many match, `next` is the `cursor` of the following page (null: the last). | | `positions` | `me:read` | Open positions: What is held now: one row per asset and market held (venue, market, quote: what its prices are in, settle: a perp’s settlement currency) with its size (negative is short), mark in the quote, the quote’s USD rate and value in USD, its funding now (APR), margin and liquidation where the venue reports them (liq_px in the quote, liq_distance_pct, margin_mode, margin in settle), the asset’s USD price, its net delta in base units summed over every market (`net`; null where one market’s size in base units is not known) and net value in USD, and when the positions were read. | | `funding_pnl` | `me:read` | Funding P&L per market: Who is bleeding: funding received (+) or paid (-) over a trailing window per asset and market (venue, market, quote, settle), with the size and USD value held now, the market’s funding now as an APR, what the position earns or pays per hour and per day at it, and the window’s funding as an APR on the notional. | | `charts` | `me:read` | Saved charts: The plots saved in Charts (Charts is part of Pro), or one of them with its full definition when `id` is given. | | `search` | `market:read` | Find assets: Find assets, venues (exchanges) and networks by name or symbol. | | `assets` | `market:read` | Asset ranking: The asset ranking by market capitalisation, with price, market cap and 24h and 7d changes. | | `prices` | `market:read` | Asset prices: The latest USD (or EUR) reference price of one or more assets across venues, not any venue’s mark. | | `candles` | `market:read` | Price candles: OHLCV candles of one asset aggregated across venues, by hour, 4 hours or day. | | `funding` | `market:read` | Funding rates: Settled perpetual funding rates per venue market for one or more assets: hourly or daily history over a range (default the last 7 days), or with `latest` the last settled rate per market. | | `funding_spreads` | `market:read` | Funding spreads (live): Live funding-carry opportunities, the Opportunities page’s funding rows: with `view` `pairs` (default) each perp/perp pair (long one leg, short the other) with current funding per leg, 1d/7d/30d average spread, stability, `carry` (the expected spread a year over `carry_window`), round trip cost (bps) and breakeven. | | `market_profile` | `market:read` | Perp market profile: How a perpetual market’s funding works and where it stands: per market of an asset (one venue, or one market) its live index and mark (in the market’s quote), funding per interval and annualized, interval, next funding, open interest and premium. | | `order_book` | `market:read` | Live order books: One asset’s live order books, fresh (at most 30 s old; the read starts the build when the asset is not watched and waits for it): each exchange id’s main market first (perp before spot), its top (`bid`, `ask`), `bids` and `asks` as [price, size] best first cut to `depth` levels a side, `levels` (what the source holds), `source` (stream, rest, or top only with `note` why), `quote` (prices are in it) and `tier`. | | `series` | `market:read` | Data series (v2): The v2 time series this API serves (funding settlements, candles, open interest and more), or one series’ rows when `id` is given, filtered by `params` (as the series lists them, e.g. {"asset": "bitcoin"}). | | `snapshots` | `market:read` | Data snapshots (v2): The v2 snapshots this API serves (tickers, order book depth and more), or one snapshot’s rows when `id` is given, filtered by `params`. | | `get` | `me:read` | Any API read: Any read this API serves to the key, by path: /me... | ### Agent skills Skills teach an agent which command or route answers which question (portfolio, positions, opportunities, markets). For Claude Code, as a plugin: ```sh claude plugin marketplace add https://api.tribulnation.com/skills/marketplace.json claude plugin install terminal@tribulnation ``` They call `tn terminal` and the `tn-api` helper the plugin puts on the PATH. Other agents that read `SKILL.md` folders can unpack them directly: ```sh mkdir -p ~/.claude/skills curl -fsSL https://api.tribulnation.com/skills/tribulnation-terminal-skills-0.5.5.tgz | tar -xz -C ~/.claude/skills --strip-components=2 package/skills ``` More: [https://api.tribulnation.com/skills/](https://api.tribulnation.com/skills/). ### OpenAPI and llms.txt - [OpenAPI 3.1](https://api.tribulnation.com/openapi.json): every route with its parameters, full response schemas and recorded examples, for code generators and tools. - [llms.txt](https://api.tribulnation.com/llms.txt): the index an agent reads first. - [llms-full.txt](https://api.tribulnation.com/llms-full.txt): this whole page as one Markdown file, with a TypeScript type and a curl sample per endpoint. ### Rules for agents - Never print, log, commit or pass a key on a command line; send it only in the `Authorization` header to `https://api.tribulnation.com`. - Everything is read-only by design. A `403` for a write, a scope or a plan is the answer: say so, do not work around it. - Retry only `429` and `503`, after `Retry-After`.