Metadata-Version: 2.4
Name: trading-cli
Version: 0.3.0
Summary: Trade any exchange from the command line — agent-native trading CLI
Author: FastBooks
License: MIT
Keywords: trading,cli,crypto,exchange,agent,fastbooks
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.0
Requires-Dist: requests>=2.28
Provides-Extra: standalone
Requires-Dist: ccxt>=4.0; extra == "standalone"
Provides-Extra: mcp
Requires-Dist: mcp>=1.0; extra == "mcp"
Provides-Extra: agent
Requires-Dist: ccxt>=4.0; extra == "agent"
Requires-Dist: mcp>=1.0; extra == "agent"
Provides-Extra: strategies
Requires-Dist: fastbooks-clistrategies; extra == "strategies"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: ccxt>=4.0; extra == "dev"
Requires-Dist: mcp>=1.0; extra == "dev"
Dynamic: license-file

```
   ███████╗ █████╗ ███████╗████████╗██████╗  ██████╗  ██████╗ ██╗  ██╗███████╗
   ██╔════╝██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗██╔═══██╗██║ ██╔╝██╔════╝
   █████╗  ███████║███████╗   ██║   ██████╔╝██║   ██║██║   ██║█████╔╝ ███████╗
   ██╔══╝  ██╔══██║╚════██║   ██║   ██╔══██╗██║   ██║██║   ██║██╔═██╗ ╚════██║
   ██║     ██║  ██║███████║   ██║   ██████╔╝╚██████╔╝╚██████╔╝██║  ██╗███████║
   ╚═╝     ╚═╝  ╚═╝╚══════╝   ╚═╝   ╚═════╝  ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝
        trade the entire market — crypto · stocks · forex · perps · predictions
              one CLI · every venue · human-readable or --json for agents
```

<h1 align="center">FastBooks CLI</h1>

<p align="center">
  <b>Every market on Earth, one command line.</b><br/>
  Live data and execution across crypto, equities, forex, perps, commodities,
  on-chain DEXes, tokenized assets, and prediction markets — built for humans <i>and</i> agents.
</p>

---

Trade any market from the command line — and from agents. One interface over
crypto exchanges, brokers, forex, and prediction markets, with **dual output**:
human-readable tables by default, machine-readable JSON with `--json`.

> **For agents / LLMs:** see [SKILL.md](SKILL.md) for the structured skill
> definition (command grammar, JSON schemas, env vars). This file is the
> human guide.

---

## Install

Once published, it's a one-liner:

```bash
pipx install fastbooks-cli      # recommended (isolated); or: pip install fastbooks-cli
fastbooks --help
```

From a checkout (development):

```bash
cd cli && pip install -e .      # installs the `fastbooks` command
```

Requires Python ≥ 3.10. Runtime deps are just `click` and `requests`.

## Talking to the backend

The CLI is a thin client over two HTTP services:

| Service | Default | Env var |
|---------|---------|---------|
| Routing API (markets, execution, keys) | `http://localhost:3002` | `FASTBOOKS_ROUTING_URL` |
| Bots service (deploy, forward-test)    | `http://localhost:8003` | `FASTBOOKS_BOTS_URL` |

```bash
fastbooks config show       # show resolved URLs
fastbooks config doctor     # ping both services
```

Auth: FastBooks platform keys (`apikey`) are **fully self-service — no admin
token**. The only token you may need is `FASTBOOKS_API_TOKEN` (a JWT), and only
for storing exchange keys & saved backtests.

---

## Quickstart — the four core flows

```bash
# 1. Create a FastBooks API key (self-service, no admin token; free, read-only, 5 req/sec)
fastbooks apikey create --label my-bot
fastbooks apikey limits                 # see the default limits
fastbooks apikey info  fb_live_xxx      # inspect your key   (present the key itself)
fastbooks apikey revoke fb_live_xxx     # revoke your key    (present the key itself)

# 2. Get market data
fastbooks markets tickers --category crypto
fastbooks markets orderbook binance BTC/USDT
fastbooks markets ohlcv binance BTC/USDT -t 1h -n 100
fastbooks apikey verify fb_live_xxx     # market data via the public API key

# 3. Deploy a bot on FastBooks paper
fastbooks bots deploy -n "Paper Momentum" -v alpaca -s momentum -c 50000 --paper
fastbooks bots list
fastbooks bots stop <bot_id>

# 4. Connect an exchange, then forward-test (paper) or go live
export FASTBOOKS_API_TOKEN=<your jwt>
fastbooks wallet add binance -k <KEY> -s <SECRET>
fastbooks backtest forward-test --venue alpaca --capital 50000 --paper
# ...same command with --live once you're confident
```

Add `--json` to any command for agent-friendly output.

---

## Command groups

| Group | Status | Purpose |
|-------|--------|---------|
| `markets`  | ✅ live | Orderbooks, tickers, OHLCV, symbols, options |
| `execute`  | ✅ live | Place/cancel/list orders, balance, positions, leverage, quote |
| `bots`     | ✅ live | Create/deploy, start/stop/pause, monitor, emergency-stop |
| `backtest` | ✅ live | Historical sims + single-cycle forward tests |
| `apikey`   | ✅ live | Self-service FastBooks platform keys (create/limits/verify) |
| `wallet`   | ✅ live | Exchange API-key management (`add`/`list`/`test`/`remove`) |
| `config`   | ✅ live | Show config, health-check services |
| `repl`     | ✅ live | Interactive session |
| `strategy` | ✅ live | Run a bundled local strategy directly (e.g. Hyperliquid momentum) |
| `swap`     | 🧪 experimental | On-chain swaps — requires a swap router not enabled on all deployments |
| `dex`      | 🧪 experimental | DEX perps (GMX/dYdX/Aevo) — requires a dex router not enabled on all deployments |
| `polymarket` | 🧪 experimental | Prediction-market trading — requires the Polymarket router |

`fastbooks <group> --help` lists every subcommand and flag.

See [EXCHANGES.md](EXCHANGES.md) for per-venue setup, auth, and symbol formats.

---

## Capabilities at a glance

- **Unified market data** across crypto, equities, ETFs, forex, indices, commodities, on-chain (DEX), tokenized assets, and prediction markets — one ticker model, one set of commands.
- **Order execution** on CEXes, Hyperliquid perps, brokers (Alpaca, IBKR), forex (OANDA/Saxo), and paper — venue-agnostic place/cancel/list/balance/positions/leverage/quote.
- **Bots**: deploy on FastBooks paper or live, start/stop/pause, monitor (events/logs/report), emergency-stop.
- **Backtesting**: historical sims + single-cycle forward tests across any supported venue.
- **Self-service API keys** for the public read API (free, 5 req/sec).
- **Agent-native**: `--json` on everything; one result object or `{"error",...}` per call.

## Market data coverage

| Asset class | Category filter | Example venues / source |
|-------------|-----------------|--------------------------|
| Crypto spot | `crypto` / `spot` | Binance, Bybit, OKX, Kraken, Coinbase, KuCoin |
| Crypto perps | `perpetuals` | Hyperliquid (+ experimental GMX/dYdX/Aevo) |
| Stocks & ETFs | `stocks` | US + global equities (region universes below) |
| Forex | `forex` | major/minor FX pairs |
| Indices | `index` | global indices |
| Commodities | `commodity` | metals, energy, ags |
| On-chain (DEX) | `dex` | Solana/EVM pools |
| Tokenized assets | `tokenized` | tokenized equities/RWAs |
| Prediction | `prediction` | Polymarket, Limitless |
| Options | — | `markets options <underlying>` (e.g. Deribit) |

**Data endpoints (via `fastbooks markets`):**

| Command | What you get |
|---------|--------------|
| `tickers [--category] [--exchange] [--search] [--page] [--limit]` | Unified live tickers (price, 24h change/volume), paginated & searchable |
| `orderbook <exchange> <symbol>` | L2 order book |
| `orderbooks [--category all\|spot\|perpetuals]` | Aggregated multi-venue books |
| `ohlcv <exchange> <symbol> [-t TF] [-n N]` | OHLCV candles — timeframes `1m,5m,15m,30m,1h,4h,1d,1w` |
| `symbols [-r REGION] [-s SECTOR] [-n N]` | Regional equity universe — regions `us,ca,uk,au,eu,jp,asia` |
| `options <underlying>` | Options chain |

### Getting full ticker lists (handy for agents)

`--all` auto-paginates the entire universe in one command; `--export` writes it
to `.json` or `.csv` (inferred from the extension):

```bash
# The whole universe, no manual paging
fastbooks --json markets tickers --all > universe.json
fastbooks markets tickers --all --export universe.csv

# Per asset class (export each)
fastbooks markets tickers --all --category crypto --export crypto.csv
fastbooks markets tickers --all --category stocks --export stocks.csv
fastbooks markets tickers --all --category forex  --export forex.csv
fastbooks markets tickers --all --category index  --export indices.csv

# Per exchange, or search by symbol/name
fastbooks --json markets tickers --all --exchange binance > binance.json
fastbooks markets tickers --search AAPL

# Full regional equity universes
for r in us ca uk eu jp asia au; do
  fastbooks --json markets symbols -r "$r" -n 5000 > "symbols_$r.json"
done

# 5-minute candles + history (served from the server-side OHLCV cache)
fastbooks --json markets ohlcv binance BTC/USDT -t 5m -n 1000
```

**Server-side OHLCV cache.** Candle responses are cached in the routing API
per `(exchange, symbol, timeframe, limit)` with a timeframe-derived TTL (e.g.
5m ≈ 60s), so repeated chart/bot/agent reads are served from memory and don't
re-hit upstream providers. A cache hit is marked `"cached": true` in the JSON.
Tune with `OHLCV_CACHE_MAX` / `OHLCV_CACHE_DISABLED`.

> **Roadmap:** durable cross-restart deep-history warehousing (immutable bars in
> Postgres/object storage with scheduled backfill) — today deep history is the
> file-based `history_cache/` populated by `gather_history.py`, and the in-memory
> cache above accelerates live reads.

---

## JSON mode (agents)

```bash
fastbooks --json execute balance binance
# {"balances": [{"asset": "BTC", "free": "0.5", "total": "0.5"}, ...]}
```

Every command emits either a result object or `{"error": "...", "details": ...}`
on failure, with a non-zero exit code. See [SKILL.md](SKILL.md) for schemas.

---

## Tests

```bash
python3 -m pytest -q                       # offline; no backend needed
FASTBOOKS_E2E=1 python3 -m pytest -q        # live smoke against running services
```

See [tests/README.md](tests/README.md). The capability suite asserts the CLI
hits the correct backend endpoints (method + path + auth) for the four flows.

---

## Publishing to PyPI

The package builds from `pyproject.toml` (PEP 621, setuptools backend) — no
Poetry needed. One-time tooling:

```bash
pip install --upgrade build twine
```

Release steps (run from `cli/`):

```bash
# 1. Bump the version in pyproject.toml  (e.g. 0.2.0 -> 0.2.1)
# 2. Build sdist + wheel into dist/
python3 -m build

# 3. Sanity-check the metadata
twine check dist/*

# 4. Upload to TestPyPI first (recommended), then verify the install
twine upload --repository testpypi dist/*
pipx install --index-url https://test.pypi.org/simple/ fastbooks-cli

# 5. Upload to real PyPI
twine upload dist/*
```

Auth uses an API token (create at https://pypi.org/manage/account/token/). Put it in
`~/.pypirc` or pass it as the password with username `__token__`:

```ini
# ~/.pypirc
[pypi]
  username = __token__
  password = pypi-AgEN...your-token...
[testpypi]
  username = __token__
  password = pypi-AgEN...your-testpypi-token...
```

Notes:
- The project name `fastbooks-cli` must be free on PyPI (check
  https://pypi.org/project/fastbooks-cli/); the `fastbooks` command name is unaffected by that.
- `MANIFEST.in` ships `README.md`, `SKILL.md`, `EXCHANGES.md`, `LICENSE`, and `examples/`
  in the sdist. Only the `fastbooks_cli` package is included — **no strategy logic**.
- Each upload version is immutable; bump the version for every release.
- For automated releases, use the PyPI **Trusted Publisher** (OIDC) GitHub Action
  instead of a long-lived token.
- The proprietary `fastbooks-clistrategies` package is built the same way but
  published privately (or installed from a Git URL), never to public PyPI.
