Metadata-Version: 2.4
Name: zenith-trade-client
Version: 0.2.1
Summary: Python client for accessing Zenith-Trade backend
Author-email: Shubham Pandey <shubhampandey@teesta.co>
License: MIT
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Requires-Dist: websockets>=12.0
Requires-Dist: pydantic>=1.10
Dynamic: license-file

# Zenith Trade Client

Python client for the **Zenith-Trade** market data backend: find data, check where it is,
download it, stream it live, and replay history.

It is built for both interactive use (readable `print()` output) and scripts / workflows
(plain data via `.to_dict()`, typed errors, no prompts).

```bash
pip install -U zenith-trade-client
```

## Quickstart

```python
from zenith_trade_client import ZenithTradeClient

zt = ZenithTradeClient()

avail = zt.check_availability(
    exchange="binance",
    symbols=["BTCUSDT", "ETHUSDT"],
    data_types=["trades", "book_snapshot_25"],
    from_date="2026-09-01",
    to_date="2026-09-07",
)
print(avail)
```

```
binance · 2026-09-01 → 2026-09-07 (7 days)
Status: partial

  Symbol   Data type         Status   Days  Where
  BTCUSDT  trades            ready    7/7   server SSD
  BTCUSDT  book_snapshot_25  ready    7/7   server SSD
  ETHUSDT  trades            partial  1/7   server SSD
  ETHUSDT  book_snapshot_25  missing  0/7   Tardis (downloadable)

Files: 15 (readable here)  →  avail.files
Downloadable from Tardis: ~114 MB, ~3 - 5 sec  →  avail.download()
```

## Contents

- [Connecting](#connecting)
- [Discover: `exchanges()`, `exchange_info()`, `symbols()`](#discover)
- [Check availability: `check_availability()`](#check-availability)
- [Download: `download()`, `DownloadJob`, `my_downloads()`](#download)
- [Live data: `stream_live()`](#live-data)
- [Replay history: `replay()`](#replay-history)
- [Using results in scripts and workflows](#using-results-in-scripts-and-workflows)
- [Errors](#errors)
- [Upgrading](#upgrading)

---

## Connecting

```python
ZenithTradeClient(host=None, port=None, user=None, quiet=False, timeout=30.0)
```

| Argument | Default | Meaning |
|---|---|---|
| `host` | found automatically | Backend host name or IP, or a full URL (`"https://…"`) |
| `port` | `8000` | Backend port |
| `user` | your OS login | Name to show in Zenith's request history for requests from the server itself |
| `quiet` | `False` | Don't print the connection line or download progress |
| `timeout` | `30.0` | Seconds to wait for each HTTP request |

The client prints one line saying where results can be used:

```
Connected to Zenith, all data paths (SSD + NAS + ClickHouse + Postgres) are readable here.
```

```
Connected to Zenith over Tailscale. You're not on the server, so file/NAS paths in results
refer to the server; SQL queries run wherever ClickHouse/Postgres are reachable.
```

To connect to a specific address, pass `host=` / `port=` or set the `ZENITH_URL` environment
variable (e.g. `export ZENITH_URL=http://<host>:<port>`).

```python
zt = ZenithTradeClient(quiet=True)          # no output (e.g. in a scheduled job)
zt = ZenithTradeClient(host="<host>")       # a specific backend
```

---

## Discover

### `exchanges()`

All exchanges Zenith knows, as a sorted list of names.

```python
zt.exchanges()
# ['binance', 'binance-futures', 'bybit', 'deribit', ...]
```

### `exchange_info(exchange)`

A summary of one exchange across all of Zenith's sources.

| Key | Meaning |
|---|---|
| `exchange` | Exchange name |
| `data_types` | Data types available for the exchange |
| `available_since`, `available_to` | Date range (`"YYYY-MM-DD"`) |
| `sources` | Where data comes from: `tardis` (downloadable), `internal` (Zenith's own collection), `postgres` |
| `symbols_count` | Number of symbols |

```python
info = zt.exchange_info("binance")
print(info["data_types"], info["available_since"], "→", info["available_to"])
# ['book_snapshot_25', 'book_snapshot_5', 'book_ticker', 'incremental_book_L2', 'quotes', 'trades'] 2019-03-30 → 2026-09-30
```

An unknown name raises `InvalidRequestError` with close matches.

### `symbols(exchange, search="", limit=100)`

Symbols on an exchange with their data types and date range.

| Argument | Meaning |
|---|---|
| `exchange` | Exchange name, e.g. `"binance"` |
| `search` | Filter by part of the symbol (for Polymarket: market question, event or outcome) |
| `limit` | Maximum results |

Returns a list of dicts: `id`, `data_types`, `available_since`, `available_to`
(Polymarket results also carry a readable `label`).

```python
for s in zt.symbols("binance", search="BTCUSDT", limit=3):
    print(s["id"], s["data_types"], s["available_since"], "→", s["available_to"])
```

---

## Check availability

### `check_availability(exchange, symbols, data_types, from_date, to_date)`

Where the requested data is, per symbol and data type, and how to get it.
**Checking never downloads anything.**

| Argument | Meaning |
|---|---|
| `exchange` | Exchange name |
| `symbols` | One symbol or a list |
| `data_types` | One data type or a list, e.g. `"trades"`, `"book_snapshot_25"`, `"incremental_book_L2"` |
| `from_date`, `to_date` | `"YYYY-MM-DD"`, `date` or `datetime` (inclusive) |

Returns an `Availability`:

| Field / method | What it gives |
|---|---|
| `print(avail)` | Readable table per symbol and data type |
| `avail.is_ready` | `True` when everything is available for the whole range |
| `avail.status` | `"ready"`, `"partial"`, `"missing"` or `"unavailable"` |
| `avail.items` | One dict per symbol × data type: `symbol`, `data_type`, `status`, `source`, `days_available`, `days_total`, `missing_dates`, `files`, `can_download` |
| `avail.files` | Paths of stored files (on the server / NAS) |
| `avail.queries` | SQL only, per database: `{"clickhouse": [...], "postgres": [...], "duckdb": [...]}` |
| `avail.connections` | Where those queries run, e.g. `{"postgres": {"host", "port", "database"}}` |
| `avail.duckdb_python` | Python (DuckDB) code for Parquet files on the NAS, when there are any |
| `avail.missing_dates` | Days missing for at least one item |
| `avail.can_download` | Whether Tardis can supply what's missing |
| `avail.download_estimate` | `{"size_mb", "time"}` for downloading what's missing |
| `avail.paths_readable_here` | Whether the file paths exist on this machine |
| `avail.download()` | Start downloading what's missing (see below) |
| `avail.to_dict()` | Everything as JSON-serializable data |

Example — use stored files:

```python
avail = zt.check_availability(exchange="binance", symbols="BTCUSDT", data_types="trades",
                              from_date="2026-09-01", to_date="2026-09-07")
if avail.is_ready:
    for path in avail.files:
        print(path)
```

Example — data held in databases:

```python
avail = zt.check_availability(exchange="<exchange>", symbols=["<symbol>"],
                              data_types=["trades", "orderbook"],
                              from_date="2026-09-20", to_date="2026-09-21")
sql = avail.queries["clickhouse"][0]         # plain SQL, ready to run
conn = avail.connections["clickhouse"]       # where to run it
```

Example — per-item detail:

```python
for item in avail.items:
    if item["status"] != "ready":
        print(item["symbol"], item["data_type"], "missing:", item["missing_dates"])
```

---

## Download

Downloads fetch data from Tardis onto the server; days already stored are skipped.
Exchanges Zenith collects itself are served from its databases instead (use `avail.queries`).

### `avail.download()` / `download(exchange, symbols, data_types, from_date, to_date)`

Both start a download and return a `DownloadJob`. `avail.download()` downloads exactly
what you checked; `zt.download(...)` takes the same arguments as `check_availability()`.

```python
avail = zt.check_availability(exchange="binance", symbols="ETHUSDT", data_types="trades",
                              from_date="2026-09-01", to_date="2026-09-07")
if not avail.is_ready and avail.can_download:
    job = avail.download()
    job.wait()
    print(job.files)
```

```python
job = zt.download(exchange="binance", symbols="ETHUSDT", data_types="trades",
                  from_date="2026-09-01", to_date="2026-09-07")
```

### `DownloadJob`

| Field / method | What it does |
|---|---|
| `job.wait(poll_seconds=2, timeout=None, show_progress=None)` | Block until finished (progress on stderr unless `quiet`); raises if the download failed |
| `job.status` | `"queued"`, `"downloading"`, `"completed"`, `"failed"`, `"canceled"` |
| `job.is_done` | Finished (successfully or not) |
| `job.files_done`, `job.files_total` | Progress |
| `job.refresh()` | Fetch the latest status |
| `job.cancel()` | Stop the download |
| `job.retry()` | Run a failed or canceled download again |
| `job.files` | Stored file paths once complete |
| `job.to_dict()` | The job as JSON-serializable data |

### `my_downloads(limit=20)`

Your recent downloads, newest first, as `DownloadJob`s.

```python
for job in zt.my_downloads(limit=5):
    print(job.to_dict())
```

---

## Live data

### `stream_live(exchange, symbols, data=("trades", "book"), book_depth=20, book_interval_ms=100, bars=None)`

Real-time data for one exchange. Iterate the result with `for` (or `async for`).

| Argument | Meaning |
|---|---|
| `exchange` | Exchange name |
| `symbols` | One symbol or a list |
| `data` | Any of `"trades"`, `"book"`, `"best_bid_ask"`, `"funding"`, `"liquidations"`, `"options"`; types an exchange doesn't offer are skipped with a notice |
| `book_depth` | Order book levels per side (with `"book"`) |
| `book_interval_ms` | Order book refresh interval (with `"book"`) |
| `bars` | Also build price bars from trades: `"1s"`, `"1m"`, `"1h"` |

```python
for msg in zt.stream_live(exchange="binance-futures", symbols="BTCUSDT", data=["trades", "book"]):
    if msg["type"] == "trade":
        print(msg["symbol"], "trade", msg["price"], msg["amount"], msg["side"])
    elif msg["type"] == "book_snapshot" and msg["bids"] and msg["asks"]:
        print(msg["symbol"], "bid", msg["bids"][0]["price"], "ask", msg["asks"][0]["price"])
```

The stream object also has `stream.status` (latest engine status), `stream.delay_seconds`
(for exchanges fed from Zenith's collectors: how far events trail the exchange) and
`stream.close()`. Leaving the `for` loop closes it.

```python
import asyncio

async def main():
    async for msg in zt.stream_live(exchange="binance", symbols="BTCUSDT", data="trades"):
        print(msg["price"])

asyncio.run(main())
```

---

## Replay history

### `replay(exchange, symbols, from_time, to_time, data=("trades", "book"), speed="max", book_depth=20, book_interval_ms=100, bars=None)`

Stored history played back in time order, with the same messages as live data, so code
written for one runs on the other.

| Argument | Meaning |
|---|---|
| `from_time`, `to_time` | Dates (`"2026-09-28"` = whole day) or times (`"2026-09-28 06:30"`), UTC |
| `data` | Any of `"trades"`, `"book"`, `"quotes"`, `"best_bid_ask"`, `"funding"`, `"liquidations"`, `"options"` |
| `speed` | `"max"` (as fast as possible — for backtests), `1` (real time), `10`, ... |
| others | As for `stream_live()` |

```python
with zt.replay(exchange="binance", symbols="BTCUSDT",
               from_time="2026-09-28 00:00", to_time="2026-09-28 06:00",
               data=["trades", "book"], speed="max") as replay:
    for msg in replay:
        ...
print(replay.progress)   # 1.0 when finished
```

Controls, usable while iterating:

| Method / field | What it does |
|---|---|
| `replay.pause()`, `replay.resume()` | Pause and continue |
| `replay.set_speed(10)` | Change speed (`"max"`, `1`, `10`, ...) |
| `replay.seek("2026-09-28 03:00")` | Jump to a time |
| `replay.step(seconds=1)` | While paused, advance by some market time |
| `replay.stop()` | End the replay |
| `replay.progress` | 0.0 – 1.0 through the range |
| `replay.position` | Current market time (ISO, UTC) |

---

## Messages

Live and replay messages use the [tardis normalized format](https://docs.tardis.dev/tardis-machine/data-types):
`trade`, `book_snapshot`, `trade_bar`, `derivative_ticker`, `liquidation`, `book_ticker`,
`option_summary`. Each is a dict with `type`, `symbol`, `exchange`, `timestamp`, `localTimestamp`
and type-specific fields (e.g. `price`, `amount`, `side` for trades; `bids`, `asks` for books).

---

## Using results in scripts and workflows

- `avail.to_dict()` and `job.to_dict()` return plain, JSON-serializable data.
- `avail.queries` contain SQL only; connection details are separate in `avail.connections`.
- `quiet=True` keeps stdout/stderr clean; errors are raised, never printed.
- Everything accepts a single value or a list for `symbols` / `data_types`.

```python
import json
from zenith_trade_client import ZenithTradeClient, ZenithTradeError

zt = ZenithTradeClient(quiet=True)
try:
    avail = zt.check_availability(exchange="binance", symbols=["BTCUSDT", "ETHUSDT"],
                                  data_types="trades", from_date="2026-09-01", to_date="2026-09-07")
    if not avail.is_ready and avail.can_download:
        avail.download().wait()
        avail = zt.check_availability(exchange="binance", symbols=["BTCUSDT", "ETHUSDT"],
                                      data_types="trades", from_date="2026-09-01", to_date="2026-09-07")
    print(json.dumps(avail.to_dict()))
except ZenithTradeError as e:
    raise SystemExit(f"zenith: {e}")
```

---

## Errors

All errors derive from `ZenithTradeError`:

| Error | When |
|---|---|
| `ZenithConnectionError` | The backend can't be reached |
| `InvalidRequestError` | Unknown exchange or symbol, bad dates, ... (message from the backend) |
| `NotAvailableError` | E.g. downloading data that isn't on Tardis |

Invalid arguments (bad date format, unknown data name) raise `ValueError` / `TypeError`
before anything is sent.

---

## Upgrading

0.1 and 0.2.0 code keeps working.

| Before | Now |
|---|---|
| `ZenithTradeClient(mode="localhost")` / `(mode="tailscale", tailscale_host=...)` | `ZenithTradeClient()` (old arguments still accepted) |
| `list_exchanges()` | `exchanges()` |
| `get_exchange_info(exchange)` | `exchange_info(exchange)`; `symbols(exchange)` for per-symbol detail |
| `check_data_availability(...)` — also started downloads | `check_availability(...)` to look, `.download()` to fetch |
| 0.2.0: `check_availability(..., start=, end=)` | `from_date=`, `to_date=` (`start` / `end` still accepted) |
| 0.2.0: `replay(..., start=, end=)` | `from_time=`, `to_time=` (`start` / `end` still accepted) |

`check_data_availability()` keeps its old behaviour, including starting downloads, and warns
when used.
