Metadata-Version: 2.4
Name: tribulnation-terminal
Version: 0.4.1
Summary: Tribulnation Terminal: a typed async Python client and the tn terminal command line, for your portfolio and market data (read-only)
Project-URL: Homepage, https://app.tribulnation.com
Project-URL: Documentation, https://api.tribulnation.com/docs
Project-URL: API reference (OpenAPI), https://api.tribulnation.com/openapi.json
Project-URL: For agents (llms.txt), https://api.tribulnation.com/llms.txt
Project-URL: API keys, https://app.tribulnation.com/integrations
Author-email: Marcel Claramunt <marcel@tribulnation.com>
License-Expression: MIT
License-File: LICENSE
Keywords: agents,api-client,crypto,funding-rates,market-data,order-book,portfolio,trading
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: lazy-loader
Requires-Dist: pydantic>=2.7
Requires-Dist: typed-core<1,>=0.13
Requires-Dist: typing-extensions>=4.7
Requires-Dist: websockets>=13
Provides-Extra: cli
Requires-Dist: tribulnation-cli<1,>=0.1; extra == 'cli'
Requires-Dist: typer<1,>=0.12; extra == 'cli'
Description-Content-Type: text/markdown

# tribulnation-terminal

Read your [Terminal](https://app.tribulnation.com) portfolio, positions and (with Ultra)
live and historical crypto market data from Python or the command line, for you and your
agents. **Read-only, always**: one API key with `me:read` (and optionally `market:read`),
which can place no order, change nothing and see no exchange key.

- **`from tribulnation.terminal import Terminal`**: a typed, async client.
- **`tn terminal`**: the command line, a thin layer on that client and a plugin of the
  [`tn` launcher](https://github.com/tribulnation/cli) (`tribulnation-cli`), which the
  `cli` extra installs and puts on the PATH as `tn`. It also runs alone as `tn-terminal`.

API docs: [api.tribulnation.com/docs](https://api.tribulnation.com/docs) ·
for agents: [llms.txt](https://api.tribulnation.com/llms.txt) ·
keys: [app.tribulnation.com/integrations](https://app.tribulnation.com/integrations).

## Install

```sh
pip install tribulnation-terminal                  # the Python client
pip install 'tribulnation-terminal[cli]'           # the client and the tn command line
uv tool install 'tribulnation-terminal[cli]'       # tn alone, in its own environment (or pipx install)
```

## Quickstart

**1. A key.** Either sign in from the command line (it prints a code to approve in your
browser and saves the key, mode 600):

```sh
tn terminal auth login                                  # me:read: your own data
tn terminal auth login --scopes me:read,market:read     # with market data (Ultra)
```

or make one on [/integrations](https://app.tribulnation.com/integrations) and export it as
`TN_API_KEY`.

**2. Your portfolio, an order book snapshot and a live stream:**

```python
import asyncio
from datetime import date
from tribulnation.terminal import Terminal


async def main():
  async with Terminal.new() as terminal:  # TN_API_KEY, or the saved login
    overview = await terminal.me.portfolio.get(start=date(2026, 11, 10))
    print(overview['data']['summary']['pnl'])

    # market data: a key with market:read, on Ultra
    book = await terminal.live.book('bitcoin', depth=10)  # fresh, never older than 30 s
    for venue in book['data']['books'][:3]:
      print(venue['segment_id'], venue['bid'], venue['ask'])

    # the live socket, reconnecting by itself
    async for frame in terminal.live.stream('book:bitcoin', depth=5):
      if frame['t'] == 'view':
        print([(b['exchange'], b['bid'], b['ask']) for b in frame['books'][:3]])  # socket frames keep the feed's names
        break


asyncio.run(main())
```

**3. The same from a shell:**

```sh
tn terminal portfolio --window 7d
tn terminal positions --json | jq .
tn terminal funding bitcoin --venue binance,hyperliquid --since 3d
tn terminal watch book:bitcoin --depth 10        # a refreshing top of book per venue
```

## Python

```python
async with Terminal.new() as terminal:
  me = await terminal.me.get()  # the key and your plan
  overview = await terminal.me.portfolio.get(start=date(2026, 11, 10))
  print(overview['data']['summary']['pnl'], overview['meta']['range'])  # every answer is {data, meta}
  for row in overview['data']['assets']:
    print(row['symbol'], row['pos'])  # size per exchange
  funding = await terminal.v1.market.perps.funding.latest(
    assets=['bitcoin', 'ethereum']
  )
  prices = await terminal.v1.prices.latest(assets='bitcoin')  # price: Decimal
```

**The key.** `Terminal.new(api_key=None, *, base_url=None, validate=True, saved=True,
http=None)` takes the key from `api_key`, else `TN_API_KEY`, else the key
`tn terminal auth login` saved. The host is `base_url`, else `TN_API_BASE`, else (for a
key from `TN_API_KEY` or the saved login, never for `api_key`) the saved key's host, else
`https://api.tribulnation.com`. A saved key is only sent to
the host that issued it (`KeyHostError` otherwise). Keys are made on `/integrations`.

**The surface** mirrors the API's paths:

| | |
|---|---|
| `terminal.me` | `.get()`, `.accounts()`, `.profiles()`, `.position(asset)`, `.portfolio.get(start=, end=, profile=)`, `.portfolio.asset(asset, ...)`, `.portfolio.activity(kind, ...)`, `.charts.list()`, `.charts.get(id)` |
| `terminal.v1` | `.assets.list(...)`, `.assets.get(id)`, `.assets.summary(id)`, `.assets.instruments(id)`, `.prices.latest(...)`, `.prices.historical(...)`, `.candles(...)`, `.market.tickers.latest(...)`, `.market.perps.stats.latest(...)`, `.market.perps.funding.latest(...)` / `.historical(...)`, `.earn.latest(...)`, `.earn.historical(...)`, `.earn.facets()`, `.venues.list()` / `.get(id)`, `.networks.list()` / `.get(id)`, `.search(text)` |
| `terminal.v2` | `.series.list()`, `.get(id)`, `.data(id, start=, end=, **filters)`, `.latest(id, **filters)`, `.instances(id, ...)`; `.snapshots.list()`, `.get(id)`, `.data(id, **filters)` |
| `terminal.live` | `.profile(asset, ...)`; `.book(asset, depth=)` and `.asset(asset)`: fresh snapshots (never older than 30 s; `warming` retried for up to `wait=10` s); `.stream(topic, depth=)`: the live socket `wss://<host>/live/<topic>` as an async iterator of `ViewFrame` / `ControlFrame` (`tribulnation.terminal.livestream`), reconnecting at once on the server's once-a-minute close (4001), pinging every 20 s, backing off on other closes and raising `LiveClosed` on 4401 (key revoked), 4003, 4004 |
| `terminal.get(path, **params)` | any `/me`, `/v1/` or `/v2/` read, as raw JSON |

**Answers** are `TypedDict`s (`tribulnation.terminal.me.models`,
`.me.portfolio_models`, `.v1.models`), validated with pydantic: epoch-millisecond and
ISO times become UTC `datetime`s (series arrays stay epoch ms), dates `date`s, decimal
text `Decimal`. Fields the API adds later are kept. `validate=False` (per client or per
call) returns the JSON as the server sent it.

**Errors** subclass the `typed_core` ones: `AuthError` (401), `Forbidden` (403: the scope
or the plan), `NotFound`, `BadRequest`, `RateLimited` (`retry_after`), `Unavailable`
(502-504), all `ApiError` with `status`, `code` and `message` (keys cut out);
`NetworkError` (no answer), `Redirected` (never followed: the key would go along),
`ValidationError` (an unexpected shape), `NotLoggedIn`, `KeyHostError`. A portfolio served
from the stored last answer (the live sync failed or was slow) raises a
`LastAnswerWarning` warning.

## Command line: sign in

```sh
tn terminal auth login                     # me:read, this machine's name
tn terminal auth login --name laptop --scopes me:read,market:read
tn terminal auth login --api https://<another API host>   # e.g. a staging deployment
```

It prints a code like `BCDF-GHJK` and a link to `/integrations/device` (and opens a
browser where there is one). Sign in there, check the code matches, choose the scopes and
the key's expiry (1 year by default) and approve. The command then saves the key and
says so. `--no-browser` only prints the link (on a server, open it on your laptop).
Logging in again replaces the saved key and revokes the old one.

The key is listed on `/integrations` as *Command line* under the device's name, and can be
revoked there at any time. `market:read` is offered only on Ultra; the API checks the plan
again on every market read.

```sh
tn terminal auth status        # the key in use: name, tn_key_ prefix, scopes, source, expiry, plan
tn terminal auth logout        # revoke it on the server, then delete it here
```

How the device login works (RFC 8628, `/oauth/*` on the API host):
[api.tribulnation.com/docs](https://api.tribulnation.com/docs#device-login-and-oauth).

## Commands

Every command takes `--json` (the server's JSON, unchanged: for agents and `jq`) and
`--api URL`. Without `--json` the answer is a table.

| Command | Reads |
|---|---|
| `me` | `GET /me`: the key and your plan |
| `accounts` | `GET /me/accounts`: connected accounts and venues |
| `profiles` | `GET /me/profiles` |
| `portfolio [--window 24h\|7d\|30d\|90d\|1y] [--profile ID] [--asset A]` | `GET /me/portfolio` (`from=`), one asset `GET /me/portfolio/asset` |
| `positions [ASSET] [--profile ID]` | positions per asset and exchange from `/me/portfolio`; one asset `GET /me/position` |
| `charts [ID]` | `GET /me/charts`, `/me/charts/{id}` |
| `funding ASSET [--venue V] [--since T] [--until T] [--interval hour\|day] [--latest]` | `GET /v1/market/perps/funding/historical` (`/latest`) |
| `prices ASSET [--since DATE] [--until DATE] [--currency usd\|eur]` | `GET /v1/prices/latest`, with `--since` `/v1/prices/historical` |
| `candles ASSET [--interval 1h\|4h\|day] [--since DATE] [--until DATE]` | `GET /v1/candles` |
| `assets [--search Q] [--limit N]`, `search QUERY` | `GET /v1/assets`, `/v1/search` |
| `series [ID] [NAME=VALUE ...]`, `snapshots [ID] [NAME=VALUE ...]` | `GET /v2/series[/{id}/data]`, `/v2/snapshots[/{id}/data]` |
| `get PATH [NAME=VALUE ...]` | any `/me`, `/v1/` or `/v2/` path |
| `watch TOPIC [--depth N] [--count N]` | the live socket `wss://<host>/live/<topic>`: a refreshing top of book per venue for `book:<asset>` (bid, sizes, ask, spread), a summary for other topics; `--json` prints one frame per line; reconnects by itself until Ctrl-C |

Times: `--since 7d`, `--since 24h`, `--since 2026-10-01` or an instant with a zone
(`2026-10-01T00:00:00Z`). Asset and venue ids are catalogue ids (`bitcoin`,
`hyperliquid`); `funding` and `prices` take comma lists. Market commands need
`market:read` and Ultra: otherwise a 403 that says so.

```sh
tn terminal portfolio --window 7d
tn terminal positions bitcoin --json | jq .position
tn terminal funding bitcoin --venue binance,hyperliquid --since 3d --interval day
tn terminal get /v1/market/perps/stats/latest assets=bitcoin
tn terminal watch book:bitcoin --depth 10
```

## Exit codes

| Code | Meaning |
|---|---|
| 0 | ok |
| 1 | another API error |
| 2 | usage (a bad option, a non-https `--api`, or an `--api`/`TN_API_BASE` other than the saved key's host) |
| 3 | not logged in, or the key is invalid, expired or revoked (401) |
| 4 | forbidden: the scope or the plan (403) |
| 5 | rate limited (429; the message gives `Retry-After`) |
| 6 | network: unreachable, a redirect refused, or the service unavailable |
| 7 | login denied or expired |

Errors go to stderr as `error: <code>: <message>`, with anything shaped like a key cut out.

## Config and safety

- The key lives in `~/.config/tn/terminal.json` (`$XDG_CONFIG_HOME/tn/terminal.json`):
  the folder mode 700, the file mode 600, written atomically. It holds `api`, `key`,
  `key_id`, `label`, `scopes`, `saved_at`. The CLI refuses a file other users can read, as
  ssh does.
- `TN_API_KEY` and `TN_API_BASE` override the file; `TN_OUTPUT=json` is `--json`. There is
  no `--key` option, so a key never appears on a command line or in shell history.
- **The saved key goes only to the host that issued it.** An `--api` or `TN_API_BASE`
  naming another host is refused (exit 2) rather than sending it there; `auth logout`
  revokes at the issuing host only. A key from `TN_API_KEY` goes to the host given. Any
  host other than `https://api.tribulnation.com` (a staging host too) is named in a
  `warning:` line on stderr, at login and on every read.
- The file must be a regular file owned by you; a crash prints a plain traceback (never
  local variables); server text in tables and errors has control characters removed; the
  browser is only opened on an https approval link.
- The key is never printed: `auth status` shows its `tn_key_` prefix (8 characters).
- https only (plain http only to localhost), TLS verified, no redirects followed (the key
  would go along).

## Develop

```sh
cd python
uv sync
uv run pytest -q
uv run ruff check --config ../.agents/tools/python/ruff.toml . && uv run ruff format --config ../.agents/tools/python/ruff.toml --check .
```

The tests mock the API (`httpx.MockTransport`): the client's key and host resolution,
the request every endpoint sends, the models against answers recorded on the prototype
(`tests/fixtures/`) and against the contracts' field names, errors; and the command line's
login loop (pending, `slow_down`, success), logout, key-file modes, environment overrides,
output, errors and exit codes, and `tn`'s discovery of the `terminal` command.

Modules (`src/tribulnation/terminal/`): `main.py` (`Terminal`), `me/`, `v1/`, `v2/` (the
endpoint groups and their models), `core/` (`base.py` the client root, `auth.py` which key
to which host, `transport.py` HTTP, `exc.py` errors, `config.py` the key file, `device.py`
the device login and logout, `endpoint.py`, `types.py`), `cli/` (`commands.py` the `auth`
commands, `base.py` the Typer apps, the client call and exit codes, `mine.py` your data,
`market.py` market data, `render.py` tables).
