Metadata-Version: 2.4
Name: trading-cli
Version: 0.3.1
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

One-liner:

```bash
pipx install "trading-cli[agent]"   # recommended (isolated); base: pip install trading-cli
fastbooks --help
```

`trading-cli` is the base client (`click` + `requests`). The `[agent]` extra adds `ccxt`
(100+ exchanges, standalone) and the MCP server. Commands installed: `fastbooks`, `trading`, `fastbooks-mcp`.
Requires Python ≥ 3.10.

## What runs where

The pip package is a **thin client** — it does **not** run FastBooks' servers. On *your*
machine it runs: the CLI, the standalone **`direct`** engine (ccxt — 100+ exchanges, keyless
public data + trading on *your own* keys, no backend needed), and the **MCP server**.

The **FastBooks platform** (aggregated multi-asset data, unified execution, bots, signals) is a
**hosted service** — the CLI points at it **by default**, no setup needed:

| Service | Default (hosted) | Override env var |
|---------|------------------|------------------|
| Routing API (markets, execution, keys) | `https://app.fastbooks.exchange` | `FASTBOOKS_ROUTING_URL` |
| Bots service (deploy, forward-test)    | `https://app.fastbooks.exchange` | `FASTBOOKS_BOTS_URL` |

> The CLI already targets the hosted FastBooks API — you don't run those services yourself.
> Just mint a key (`fastbooks apikey create`, free) and set `FASTBOOKS_API_KEY`; platform data
> is **metered per key**. For trading you never send exchange keys to the server — the CLI trades
> client-side via `direct` with your own keys. Self-hosting the backend? Override the env vars to
> `http://localhost:3002` / `:8003`.

```bash
fastbooks config show       # show resolved URLs + stored config
fastbooks config health     # ping the hosted services
```

---

## 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.
