> ## 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, US Derivatives (Futures), and US
equities, manage portfolios, check prices, and convert currencies on Coinbase Advanced
Trade. Use when the user wants to check crypto or derivative prices, place or preview orders
(spot, futures, or equities), 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/api-keys/secret](https://portal.cdp.coinbase.com/api-keys/secret) (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. Under **Advanced Settings** > **Coinbase App & Advanced Trade**:
   * Under **Accounts**, select the portfolio for the agent to trade from. US Derivatives (Futures) only work in your **default** portfolio — include it in the key scope if the agent will trade US Derivatives (Futures).
   * Enable **Trade** and **Transfer** (View is enabled by default)
   * Check **Opt out of IP allowlisting** if you haven't configured specific IP addresses, or set your IP range to allowlist them
5. 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                                                                                                               |
| `coinbase products list product_type=FUTURE`             | CFM dated futures contracts (e.g. `BIT-28AUG26-CDE`) — codes roll on a schedule, so discover the live one instead of hardcoding it |
| `coinbase products list product_type=EQUITY`             | US equities (S\&P 500 only) — product ID is `TICKER-QUOTE`, e.g. `AAPL-USD` or `AAPL-USDC`                                         |

**Equities note:** `products ticker`, `products book`, `products candles`, and `products best-bid-ask` aren't available for equities yet.

### 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]'
```

## Remote MCP (no install required)

If your agent runs inside a supported chat client, you can connect directly to `https://agents.coinbase.com/mcp` via OAuth — no CLI or API key needed.

**Supported platforms:** ChatGPT, Grok, Perplexity Computer, Claude, and Claude Code.

Setup instructions for each platform: [https://docs.cdp.coinbase.com/coinbase-for-agents/overview](https://docs.cdp.coinbase.com/coinbase-for-agents/overview)

Use the CLI setup below if your platform isn't listed, if you need the most reliable order execution across models, or if you're building a custom agent.

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

## Install agent skills

Install skills so the agent has step-by-step guidance for common Coinbase workflows (trading, market data, watch, convert, portfolios):

```bash theme={null}
coinbase skills add
```

If non-interactive, pass the skills directory explicitly:

```bash theme={null}
coinbase skills add --dir <skills-directory>
```

Skills auto-update on future `npm install -g @coinbase/coinbase-cli` upgrades.

## Permissions

By default agents prompt before each `coinbase` command. To reduce or remove those prompts, allow-list commands in your agent's permission settings. Offer the user two tiers:

* **Read-only** — never prompted for safe reads (prices, balances, history); still prompted before any order or transfer. Good default.
* **Everything** — never prompted at all, including orders and transfers. Confirm explicitly before enabling.

Allow-list rules for each tier:

| Tier       | Rules                                                                                                                                                                                                         |
| :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Read-only  | `coinbase balance`, `coinbase products *`, `coinbase orders list`, `coinbase orders get *`, `coinbase orders fills`, `coinbase fees`, `coinbase env`, `coinbase portfolios list`, `coinbase portfolios get *` |
| Everything | `coinbase *`                                                                                                                                                                                                  |

How to apply depends on the agent. For Claude Code, add the rules to `permissions.allow` in settings.json (e.g. `Bash(coinbase products *)`) — `~/.claude/settings.json` for all projects or `.claude/settings.json` to share with a team. Other agents have their own allow-list mechanism.

## Gotchas

* **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.
* **Futures orders need `base_size`, not `quote_size`.** CFM dated-futures market orders reject `quote_size` — use `base_size` (number of contracts). They're available only in your default portfolio, so configure the API key to include that portfolio; a key scoped only to an isolated agent portfolio cannot place futures orders. Preview the order first and read back `predicted_liquidation_price`.
* **Equities use `TICKER-QUOTE` as the product ID, and coverage is S\&P 500 only.** `AAPL-USD` / `AAPL-USDC`. Only S\&P 500 tickers are currently supported; other tickers are rejected. Orders trade regular market hours by default; set `equity_trading_session=PRE_MARKET|AFTER_HOURS|OVERNIGHT|MULTI_SESSION` to trade outside them — each of those four sessions accepts only whole-share limit orders (market orders, `quote_size`, and fractional sizing are rejected). See the Market Data table above for which equity data commands work today.
* **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`                                | Expired or invalid credentials                                                                              | Create a new API key in the [CDP Portal](https://portal.cdp.coinbase.com/api-keys/secret)                                       |
| `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                                                                                     |
| `PERMISSION_DENIED` on an order           | Order omitted the portfolio and fell back to your **default** portfolio, which isn't in the key/grant scope | Specify the intended portfolio on the order (or tell the agent which portfolio to trade from) instead of relying on the default |
| `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                                                                                                     |
