# bpx — Backpack Exchange CLI

The official command-line interface for [Backpack Exchange](https://backpack.exchange). Trade, monitor markets, and manage your account — all from the comfort of your terminal, where no one can judge your position sizing.

**v2.0** — Full API coverage (40+ commands), live TUI dashboard with real-time WebSocket feeds, interactive trading, latency monitoring, funding rate scanner, borrow/lend tracking, and enough keyboard shortcuts to make vim users feel at home.

## Install

**From GitHub releases (recommended):**

```sh
curl -sSf https://raw.githubusercontent.com/backpack-exchange/bpx-cli/main/install.sh | sh
```

You can set `BPX_INSTALL_DIR` to override the install location (default: `~/.local/bin`).

**With Cargo:**

```sh
cargo install bpx-cli
```

**From source:**

```sh
git clone https://github.com/backpack-exchange/bpx-cli
cd bpx-cli
cargo install --path .
```

## Quick Start

```sh
# No setup required for public data
bpx markets list
bpx markets ticker SOL_USDC

# Configure your API key for trading
bpx setup

# Check connectivity and auth
bpx status

# Trade
bpx order buy SOL_USDC 10 --price 175
bpx order list
bpx account balances

# Launch the dashboard (where the real magic happens)
bpx dashboard
```

## Commands

### Markets (public, no auth required)

| Command | Description |
|---------|-------------|
| `bpx markets list` | List all markets (filter with `--type SPOT\|PERP`) |
| `bpx markets ticker <SYMBOL>` | 24h ticker for a symbol |
| `bpx markets tickers` | All tickers |
| `bpx markets depth <SYMBOL>` | Order book depth |
| `bpx markets assets` | List all supported assets |
| `bpx markets trades <SYMBOL>` | Recent trades |
| `bpx markets history <SYMBOL>` | Historical trades |
| `bpx markets klines <SYMBOL> <INTERVAL>` | Candlestick data |
| `bpx markets funding <SYMBOL>` | Funding interval rates (perps) |
| `bpx markets mark-prices` | All mark prices |

### Orders (auth required)

| Command | Description |
|---------|-------------|
| `bpx order buy <SYMBOL> <QTY> [--price P]` | Buy (market or limit) |
| `bpx order sell <SYMBOL> <QTY> [--price P]` | Sell (market or limit) |
| `bpx order list [--symbol S]` | Open orders |
| `bpx order get <SYMBOL> --id <ID>` | Get a specific order |
| `bpx order cancel <SYMBOL> --id <ID>` | Cancel an order |
| `bpx order cancel-all <SYMBOL>` | Cancel all orders (with confirmation) |
| `bpx order batch [--file F]` | Execute multiple orders from JSON |

Order flags: `--tif`, `--post-only`, `--reduce-only`, `--trigger-price`, `--trigger-by`, `--stop-loss`, `--take-profit`, `--self-trade-prevention`, `--slippage-tolerance`, and more. See `bpx order buy --help` for all options.

### Account (auth required)

| Command | Description |
|---------|-------------|
| `bpx account info` | Account settings (fees, limits, automation) |
| `bpx account balances` | Asset balances |
| `bpx account collateral` | Collateral summary and breakdown |
| `bpx account max-borrow <SYMBOL>` | Max borrow quantity |
| `bpx account max-order <SYMBOL> <SIDE>` | Max order quantity |
| `bpx account max-withdrawal <SYMBOL>` | Max withdrawal quantity |
| `bpx account update` | Update settings (auto-lend, leverage, etc.) |
| `bpx account dust [--symbol S]` | Convert dust balances |

### Capital (auth required)

| Command | Description |
|---------|-------------|
| `bpx capital deposits` | Deposit history |
| `bpx capital deposit-address <CHAIN>` | Get deposit address |
| `bpx capital withdrawals` | Withdrawal history |
| `bpx capital withdraw <SYMBOL> <QTY> <ADDR> <CHAIN>` | Request withdrawal (with confirmation) |

### Positions (auth required)

| Command | Description |
|---------|-------------|
| `bpx positions list` | Open futures positions |

### Fills (auth required)

| Command | Description |
|---------|-------------|
| `bpx fills list [--symbol S]` | Fill history (supports `--order-id`, `--fill-type`, `--sort`) |

### Borrow/Lend (auth required)

| Command | Description |
|---------|-------------|
| `bpx borrow positions` | Borrow/lend positions |

### RFQ (auth required)

| Command | Description |
|---------|-------------|
| `bpx rfq submit <SYMBOL> <SIDE> <QTY>` | Submit a request for quote |
| `bpx rfq cancel <ID>` | Cancel an RFQ |
| `bpx rfq refresh <ID>` | Refresh an RFQ |
| `bpx rfq quote <RFQ_ID> <BID> <ASK>` | Submit a quote |
| `bpx rfq accept <RFQ_ID> <QUOTE_ID>` | Accept a quote |

### Profiles & Utility

| Command | Description |
|---------|-------------|
| `bpx setup` | Interactive config wizard |
| `bpx status` | API health check + auth verification |
| `bpx profile list` | List all configured profiles |
| `bpx profile current` | Show active profile |
| `bpx dashboard [--symbol S]` | Live TUI dashboard |
| `bpx completions <SHELL>` | Generate shell completions (bash/zsh/fish) |

### Command Aliases

For faster access: `bpx m` (markets), `bpx o` (order), `bpx a` (account), `bpx pos` (positions).

## Global Flags

```
-o, --output table|json    Output format (default: table)
-p, --profile <NAME>       Config profile (default: default)
--no-color                 Disable colored output
--api-secret <KEY>         Override API secret
--base-url <URL>           Override API base URL
```

## Configuration

Config is stored at `~/.config/backpack/config.toml` with `600` permissions:

```toml
[default]
api_secret = "base64-ed25519-secret"

[subaccount-2]
api_secret = "different-key"

[testnet]
api_secret = "testnet-key"
base_url = "https://api-testnet.backpack.exchange"
ws_url = "wss://ws-testnet.backpack.exchange"
```

Switch between profiles (e.g. subaccounts) with `--profile`:

```sh
bpx --profile subaccount-2 account balances
bpx --profile testnet status
```

Priority: CLI flags > environment variables (`BPX_API_SECRET`, `BPX_BASE_URL`) > config file.

## JSON Output

Every command supports `-o json` for scripting and agent integration:

```sh
bpx markets tickers -o json | jq '.[0]'
bpx account balances -o json | jq 'to_entries[] | select(.value.available | tonumber > 0)'
bpx profile list -o json
```

Errors in JSON mode also output structured JSON to stdout:

```json
{"error": "Not authenticated", "kind": "error"}
```

Exit codes: `0` success, `1` general, `2` auth, `3` input validation, `4` network.

## Dashboard

`bpx dashboard` launches a real-time TUI powered by WebSocket streams. Think Bloomberg Terminal, but you built it yourself and it runs in your terminal. Your co-workers will be suspicious.

### What You Get

- **Live ticker bar** — price, 24h change, high/low, volume, funding rate, open interest, and ping RTT. Everything updating in real-time so you can watch your PnL tick by tick instead of doing actual work.
- **Order book depth** — full bid/ask ladder with cumulative size. Watch the walls get pulled and pretend you saw it coming.
- **Recent trades** — live trade feed with size and direction. Useful for spotting when someone fat-fingers a market order.
- **Candlestick chart** — ASCII art charting across 6 intervals (1m, 5m, 15m, 1h, 4h, 1d). Switch with `[` and `]`.
- **Funding rate scanner** — all perps sorted by absolute funding rate, with APR, basis spread, countdown to next funding, 24h volume, and open interest. Your basis trade radar.
- **Account panel** — net equity, margin health (IMF/MMF), unrealized PnL, and collateral breakdown. Borrow/lend positions with live rates and hourly earnings shown inline.
- **Balances** — all asset balances including collateral-only assets (yes, your USDC shows up even when it's fully locked as margin).
- **Open orders & positions** — live updates via private WebSocket. Cancel orders with `d`, close positions with `x`.
- **Symbol search** — press `/` to fuzzy-search across spot and perps markets with volume data. Tab to switch categories.
- **Latency monitoring** — toggle with `Shift+L` to see network latency, engine processing delay, and ping RTT with sparkline graphs. For when you need to blame the exchange instead of your strategy.

### Keyboard Shortcuts

| Key | Action |
|-----|--------|
| `Tab` / `Shift+Tab` | Cycle panels |
| `1`-`5` | Jump to panel |
| `j` / `k` | Scroll down / up |
| `g` / `G` | Jump to top / bottom |
| `[` / `]` | Change chart interval |
| `o` | Open order form |
| `d` | Cancel selected order |
| `x` | Close selected position |
| `/` | Symbol search |
| `:` | Command bar |
| `Shift+L` | Toggle latency panel |
| `?` | Toggle help overlay |
| `q` / `Ctrl-C` | Quit |

### Command Bar

Press `:` to open the command bar. Type any built-in command or `bpx` CLI subcommand:

| Command | Description |
|---------|-------------|
| `:symbol SOL_USDC` | Switch symbol |
| `:switch SOL_USDC` | Switch symbol (alias) |
| `:interval 5m` | Change chart interval (1m, 5m, 15m, 1h, 4h, 1d) |
| `:panel orders` | Jump to panel (orderbook, trades, orders, positions, balances) |
| `:order` | Open order form |
| `:cancel` | Cancel selected order |
| `:close` | Close selected position |
| `:refresh` | Force data refresh |
| `:q` | Quit |

Unrecognized commands are passed through to the `bpx` CLI as a subprocess. For example, `:fills list --symbol SOL_USDC` runs `bpx fills list --symbol SOL_USDC` and shows the output in a scrollable drawer. Prefix with `!` to force CLI passthrough (e.g., `!help`).

### Trading Commands

Type directly into the command bar for fast order entry without navigating the order form UI:

```
:buy 10                     # Market buy 10 units
:sell 0.5 at 180            # Limit sell 0.5 @ $180
:buy 100$ at best           # Buy $100 worth at best bid
:sell 25% reduce            # Sell 25% of max order size, reduce-only
:buy 1 at +2                # Limit at mark price + $2
:buy 1 at -1%               # Limit at mark price - 1%
:close                      # Close full position (market, reduce-only)
:close 50%                  # Close 50% of current position
:nuke orders                # Cancel all open orders on current symbol
:nuke positions             # Close all positions across all symbols
:nuke all                   # Cancel all orders AND close all positions
:flatten                    # Alias for nuke all
```

**Size specifiers:** plain number = units, `$` suffix = dollar amount (resolved at mark price), `%` suffix = percentage of max order size.

**Price specifiers:** `at <price>` = absolute limit, `at +N` / `at -N` = offset from mark, `at +N%` / `at -N%` = percentage offset from mark, `best` = best bid (buy) / best ask (sell), omitted = market order.

**Modifiers:** `reduce` = reduce-only, `stop <price>` = stop-loss trigger (same offset/% syntax as `at`).

All trade commands show a confirmation dialog before execution.

### Custom Keybindings

Bind any key to an action or CLI command at runtime via the command bar:

```
:bind Ctrl+f :fills list           # Bind Ctrl+F to run fills list
:bind Ctrl+b :balances list        # Bind Ctrl+B to show balances
:bind F1 toggle_help               # Bind F1 to toggle help
:unbind Ctrl+f                     # Remove a binding
:unbind all                        # Reset all custom bindings
:bind list                         # Show all bindings
```

Bindings are persisted to the `[keybindings]` section of your config file and survive restarts:

```toml
[keybindings]
"Ctrl+f" = ":fills list"
"Ctrl+b" = ":balances list"
"F1" = "toggle_help"
```

Available actions: `quit`, `toggle_help`, `symbol_search`, `command_bar`, `scroll_down`, `scroll_up`, `scroll_to_top`, `scroll_to_bottom`, `cancel_order`, `close_position`, `order_form`, `chart_prev`, `chart_next`, `next_panel`, `prev_panel`, `panel_1`..`panel_5`. Prefix with `:` to bind to a CLI command (e.g., `":fills summary"`).

### Interactive Trading

Press `o` to open the order form. Quick size presets: type `1`-`4` in the quantity field for 25/50/75/100% of available balance. Supports limit and market orders, post-only, reduce-only, and all time-in-force options. Every order requires confirmation before execution, because we believe in second chances.

## Development

```sh
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
cargo build --release
```

## Disclaimer

This software is provided for **educational and informational purposes only**. It has not been independently audited and may contain bugs or errors. Use at your own risk — the authors and Backpack Exchange are not responsible for any financial losses incurred through use of this tool. Always verify orders and positions through the official [Backpack Exchange](https://backpack.exchange) interface.

## License

Apache-2.0
