> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cdp.coinbase.com/llms.txt
> Use this file to discover all available pages before exploring further.

> Install and use the Coinbase CLI to trade crypto, manage portfolios, check prices,
and convert currencies on Coinbase Advanced Trade. Use when the user wants to check
crypto prices, place or preview orders, manage portfolios, transfer funds between
portfolios, convert USDC/USD, or set up headless Coinbase access for an AI agent —
even if they don't explicitly say "CLI."


# Skill

# Coinbase CLI

Headless access to Coinbase Advanced Trade. Install once, authenticate with a CDP API key, trade crypto with JSON output.

## Installation

```bash theme={null}
node --version   # must be >= 22
npm i -g @coinbase/coinbase-cli
coinbase --version   # verify
```

**Linux only** — install keyring support to avoid plaintext secrets:

```bash theme={null}
which secret-tool || sudo apt install -y libsecret-tools
```

**nvm/fnm users:** Upgrading Node versions requires reinstalling global packages. After upgrading, open a new terminal and run `npm i -g @coinbase/coinbase-cli` again.

## Authentication

Create a CDP API key and configure the CLI:

1. Sign in to [https://portal.cdp.coinbase.com/projects/api-keys](https://portal.cdp.coinbase.com/projects/api-keys) (a project is auto-created on first sign-in)
2. Click **Create API Key**
3. Give it a name (e.g., `my-trading-agent`)
4. Click **API restrictions** and enable **Trade** and **Transfer** (View is enabled by default)
5. Click **Advanced settings** and change the key type to **ECDSA** (brokerage rejects Ed25519)
6. Click **Create & Download** — save the JSON key file

```bash theme={null}
coinbase env live --key-file <path-to-key.json>
coinbase env          # verify: "live" appears with key ID
coinbase balance      # verify: returns JSON with account balances
```

## Core Commands

### Market Data

| Command                                                  | What it does                                                             |
| -------------------------------------------------------- | ------------------------------------------------------------------------ |
| `coinbase products get <product_id>`                     | Price, 24h volume/change, size limits                                    |
| `coinbase products list`                                 | All tradeable products (900+ results — use `symbol` or `--jq` to filter) |
| `coinbase products list symbol==USD`                     | Products with USD as base or quote currency                              |
| `coinbase products ticker <product_id>`                  | Recent trades with best bid/ask (default: 100 trades)                    |
| `coinbase products book <product_id>`                    | Full order book: bids + asks                                             |
| `coinbase products candles <product_id> granularity==1h` | OHLCV price history (default: 60 candles at 1h granularity)              |
| `coinbase products best-bid-ask product_ids=BTC-USD`     | Current best bid/ask                                                     |

### Orders

| Command                                                                                           | What it does                                                                                                                  |
| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `coinbase orders preview product_id=BTC-USD side=BUY type=market quote_size=100`                  | Dry-run: returns fill estimate, fees, slippage                                                                                |
| `coinbase orders create product_id=BTC-USD side=BUY type=market quote_size=100`                   | Execute a market buy for \$100 of BTC                                                                                         |
| `coinbase orders create product_id=BTC-USD side=BUY type=limit base_size=0.001 limit_price=50000` | Limit buy 0.001 BTC at \$50,000                                                                                               |
| `coinbase orders create ... client_order_id=<unique-id>`                                          | Idempotent order — retries with same ID return existing order instead of creating duplicate. **Always use for retry safety.** |
| `coinbase orders list`                                                                            | All orders with status, fill %, fees                                                                                          |
| `coinbase orders get <order_id>`                                                                  | Single order detail: fill status, average price, fees                                                                         |
| `coinbase orders fills`                                                                           | List all trade fills with price, size, commission, liquidity indicator                                                        |
| `coinbase orders edit <order_id>`                                                                 | Modify an existing order                                                                                                      |
| `coinbase orders cancel order_ids:='["<id1>","<id2>"]'`                                           | Batch cancel orders                                                                                                           |
| `coinbase orders close-position product_id=<id> size=<size>`                                      | Close an open position                                                                                                        |

### Portfolios & Balances

| Command                                                                   | What it does                                                           |
| ------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `coinbase balance`                                                        | All account balances (crypto + fiat)                                   |
| `coinbase portfolios list`                                                | All portfolios with UUID, name, type                                   |
| `coinbase portfolios get <portfolio_id>`                                  | Portfolio breakdown: balances, positions, allocation %, unrealized PnL |
| `coinbase portfolios create name=<name>`                                  | Create a new portfolio                                                 |
| `coinbase portfolios edit <portfolio_id> name=<new-name>`                 | Rename a portfolio                                                     |
| `coinbase portfolios delete <portfolio_id>`                               | Delete a portfolio (must be empty)                                     |
| `coinbase transfer amount=100 currency=USD from=<src_uuid> to=<dst_uuid>` | Move funds between portfolios                                          |

### Conversions

| Command                                                | What it does                      |
| ------------------------------------------------------ | --------------------------------- |
| `coinbase convert quote from=USDC to=USD amount=100`   | Get conversion quote (rate + fee) |
| `coinbase convert execute <quote_id> from=USDC to=USD` | Execute a quoted conversion       |
| `coinbase convert get <quote_id>`                      | Check conversion status           |

### Info & Session

| Command         | What it does                                             |
| --------------- | -------------------------------------------------------- |
| `coinbase fees` | Fee tier (maker/taker rates), 30-day volume              |
| `coinbase env`  | View/manage credentials across environments              |
| `coinbase mcp`  | Start MCP server (stdio) — exposes all commands as tools |

## Agent-Critical Flags

Use these flags on **any** command. They are the most important features for safe, efficient agent operation.

| Flag          | What it does                                       | When to use                                                                               |
| ------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `--template`  | Print the expected JSON request body, don't send   | **Before every first call to a command** — discover exact field names instead of guessing |
| `--dry-run`   | Assemble the full request and print it, don't send | Before executing any write operation (orders, transfers) to verify what will be sent      |
| `--jq <expr>` | Filter JSON response with a jq expression          | Extract specific fields to save context: `--jq '.price'`, `--jq '.accounts[].currency'`   |
| `-e <env>`    | Override the active environment                    | Switch between `live`, `development`, `staging`, `production`                             |

### Field syntax

| Syntax       | Meaning                                         | Example                      |
| ------------ | ----------------------------------------------- | ---------------------------- |
| `key=value`  | String body field                               | `product_id=BTC-USD`         |
| `key:=value` | Raw JSON body field (arrays, numbers, booleans) | `order_ids:='["abc","def"]'` |
| `key==value` | Query parameter                                 | `product_type==SPOT`         |
| `@file.json` | Load body from JSON file                        | `@order.json`                |

## Workflows

### 1. Check price and preview a trade

```bash theme={null}
# Get current BTC price
coinbase products get BTC-USD --jq '.price'

# Preview a $100 market buy (shows fees + estimated fill price)
coinbase orders preview product_id=BTC-USD side=BUY type=market quote_size=100

# If preview looks good, execute
coinbase orders create product_id=BTC-USD side=BUY type=market quote_size=100 client_order_id=$(uuidgen)

# Check order status
coinbase orders get <order_id>
```

### 2. Sell an asset

```bash theme={null}
# Check how much you hold
coinbase balance --jq '.accounts[] | select(.currency=="DOGE")'

# Preview the sell
coinbase orders preview product_id=DOGE-USD side=SELL type=market base_size=10

# Execute
coinbase orders create product_id=DOGE-USD side=SELL type=market base_size=10 client_order_id=$(uuidgen)
```

### 3. Transfer funds between portfolios

```bash theme={null}
# List portfolios to get UUIDs
coinbase portfolios list --jq '.portfolios[] | {name, uuid}'

# Transfer $100 USD from Default to agent portfolio
coinbase transfer amount=100 currency=USD from=<default_uuid> to=<agent_uuid>
```

### 4. Convert USDC to USD (or vice versa)

```bash theme={null}
# Get a quote
coinbase convert quote from=USD to=USDC amount=50

# Execute the conversion using the quote ID from the response
coinbase convert execute <quote_id> from=USD to=USDC
```

### 5. Discover field names for any command

```bash theme={null}
# Don't know what fields an order takes? Print the template:
coinbase orders create --template

# Then assemble and verify without sending:
coinbase orders create product_id=BTC-USD side=BUY type=market quote_size=10 --dry-run
```

### 6. Filter large result sets

```bash theme={null}
# Find all USD trading pairs
coinbase products list symbol==USD

# Top 10 USD products by 24h volume
coinbase products list symbol==USD --jq '[.products | sort_by(.volume_24h | tonumber) | reverse | .[:10] | .[].product_id]'
```

## MCP Server Setup

The CLI includes an MCP server that exposes every command as a typed tool. If using MCP, the tool schemas are your primary reference — they include full field descriptions and enums.

**Claude Code:**

```bash theme={null}
claude mcp add --scope user --transport stdio coinbase -- coinbase mcp
```

**Other agents** — add to your MCP config:

```json theme={null}
{ "command": "coinbase", "args": ["mcp"], "transport": "stdio" }
```

**Codex users:** Default sandbox can't access OS keychain. Either prompt Codex for "elevated access" or use the MCP server instead of direct CLI commands.

## Gotchas

* **ECDSA keys only.** Brokerage rejects Ed25519. If you get HTTP 401, check key type in CDP portal.
* **Products list returns 900+ items.** Use `symbol==USD` to filter by currency, or `--jq` for custom filters.
* **`client_order_id` prevents duplicate orders.** If your connection drops mid-request, retrying with the same `client_order_id` returns the existing order instead of creating a new one. Always generate one per order attempt.
* **nvm/fnm users:** Upgrading Node versions requires reinstalling global packages. After upgrading, open a new terminal and run `npm i -g @coinbase/coinbase-cli` again.

## Troubleshooting

| Error                                     | Cause                                | Fix                                                           |
| ----------------------------------------- | ------------------------------------ | ------------------------------------------------------------- |
| `HTTP 401`                                | Ed25519 key or expired credentials   | Create new ECDSA key in CDP portal                            |
| `HTTP 403 Missing required scopes`        | API key lacks View/Trade/Transfer    | Check permissions in CDP portal                               |
| `insufficient fund` (on preview or order) | Account balance too low              | Run `coinbase balance` to check available funds               |
| `PERMISSION_DENIED` on portfolio ops      | API key not scoped to that portfolio | Create a key scoped to the target portfolio                   |
| `coinbase: command not found`             | CLI not in PATH                      | Ensure npm global bin is in PATH; reinstall if upgraded Node  |
| `MISSING_FIELDS`                          | Required fields not provided         | Run `coinbase <command> --template` to see expected fields    |
| `INVALID_VALUE`                           | Enum field has wrong value           | Check the error message for accepted values                   |
| `INVALID_FORMAT`                          | Date/time format wrong               | Orders use RFC 3339 with timezone (e.g. 2024-01-01T00:00:00Z) |
| Windows: `coinbase` not found             | npm global bin not in PATH           | Add `%APPDATA%\npm` to PATH                                   |
