Skip to main content

交易 CLI

机器翻译译自英文(docs.alpaca.markets)本页 59 段已全部译完

Alpaca 的 CLI 是一个命令行界面,可从终端直接访问 Alpaca 的 Trading 和 Market Data API。交易股票、期权和加密货币,查询市场数据,管理账户并自动化工作流;所有这些都无需编写 HTTP 请求。

Alpha 预览 — 此 CLI 正在积极开发中。命令、标志和输出格式可能会在版本之间未经通知而更改。

GitHub: alpacahq/cli | 许可证: Apache 2.0

你可以做什么

  • 交易:使用显式标志和结构化输出,为股票、期权和加密货币提交、替换和取消订单
  • 市场数据:获取 K 线(bars)、报价、成交、快照、筛选器、新闻、期权链和加密货币订单簿
  • 账户管理:检查余额、持仓、组合历史、活动日志和账户配置
  • 自选列表:按名称或 ID 创建、更新和管理自选列表
  • 自动化:将 JSON 输出通过管道传入脚本、cron 作业、CI 流水线或 AI 智能体会话

安装

Go

go install github.com/alpacahq/cli/cmd/alpaca@latest

确保 $GOPATH/bin(通常为 ~/go/bin)在你的 PATH 中。

Homebrew(macOS / Linux)

brew install alpacahq/tap/cli

验证

alpaca version
alpaca doctor

认证

模拟交易是默认设置。你可以通过两种方式进行身份验证:

OAuth(模拟交易)

打开浏览器进行身份验证。无需 API 密钥、配置文件或环境变量:

alpaca profile login

API 密钥(模拟或实盘)

# Paper trading with API keys
alpaca profile login --api-key

# Live trading with API keys
alpaca profile login --api-key --live

多个配置文件

你可以管理多个配置并在它们之间切换:

alpaca profile list
alpaca profile switch <name>
alpaca profile logout <name>

环境变量(CI / 智能体)

对于脚本和自动化,将 API 密钥设置为环境变量:

export ALPACA_API_KEY=PK...
export ALPACA_SECRET_KEY=...
alpaca account get

配置

变量说明
ALPACA_API_KEYAPI 密钥 ID(与 ALPACA_SECRET_KEY 一起使用)
ALPACA_SECRET_KEY密钥
ALPACA_LIVE_TRADE设置为 true 启用实盘交易
ALPACA_PROFILE活动配置名称
ALPACA_OUTPUT默认格式(json 或 csv)
ALPACA_CONFIG_DIR配置目录覆盖

凭据存储在 ~/.config/alpaca/profiles/ 中,权限为 0600。

输出格式

默认情况下,每条命令都会返回结构化的 JSON。使用标志来重塑输出:

# JSON (default)
alpaca position list

# CSV
alpaca position list --csv

# Filtered JSON with built-in jq (no external jq needed)
alpaca position list --jq '[.[] | {symbol, qty, unrealized_pl}]'

# Quiet mode (suppress non-essential output)
alpaca account get --quiet

命令

账户与投资组合

alpaca account get                  # Account details (equity, buying power)
alpaca account config get           # Account configuration
alpaca account config set           # Update account configuration
alpaca account activity list        # Activity log (fills, dividends, transfers)
alpaca account portfolio            # Portfolio equity and P&L history

订单

alpaca order submit --symbol AAPL --side buy --qty 10 --type market
alpaca order submit --symbol AAPL --side buy --qty 10 --type limit --limit-price 185
alpaca order list                   # List orders (default: open)
alpaca order list --status all      # All orders
alpaca order get --order-id <id>    # Single order
alpaca order replace --order-id <id> --qty 20
alpaca order cancel --order-id <id>
alpaca order cancel-all

# Preview an order without submitting
alpaca order submit --symbol AAPL --side buy --qty 10 --type market --dry-run

头寸

alpaca position list                # All open positions
alpaca position get --symbol AAPL   # Single position
alpaca position close --symbol AAPL # Close a position
alpaca position close-all           # Liquidate entire portfolio

期权

alpaca option contracts --underlying-symbol AAPL
alpaca option get --symbol-or-id AAPL250620C00200000
alpaca option exercise --symbol-or-id <contract>
alpaca option do-not-exercise --symbol-or-id <contract>

市场数据 — 股票

alpaca data bars --symbol AAPL --start 2025-01-01 --timeframe 1Day
alpaca data quotes --symbol AAPL --start 2025-06-01
alpaca data trades --symbol AAPL --start 2025-06-01
alpaca data latest-bar --symbol AAPL
alpaca data latest-quote --symbol AAPL
alpaca data latest-trade --symbol AAPL
alpaca data snapshot --symbol AAPL
alpaca data screener most-actives
alpaca data screener movers

市场数据 — 加密货币

alpaca data crypto bars --symbol BTC/USD --start 2025-01-01 --timeframe 1Day
alpaca data crypto latest-quotes --symbol BTC/USD,ETH/USD
alpaca data crypto snapshots --symbol BTC/USD
alpaca data crypto-orderbook --symbol BTC/USD

市场数据 — 期权

alpaca data option chain --underlying-symbol AAPL
alpaca data option snapshot --symbol AAPL250620C00200000
alpaca data option latest-quotes --symbol AAPL250620C00200000

市场数据 — 其他

alpaca data news --symbol AAPL
alpaca data corporate-actions --symbols AAPL --types dividend
alpaca data forex rates --currency-pairs USD/EUR
alpaca clock                        # Market status and next open/close
alpaca calendar                     # Trading calendar

自选列表

alpaca watchlist list
alpaca watchlist create --name "Tech Stocks" --symbols AAPL,MSFT,NVDA
alpaca watchlist get --watchlist-id <id>
alpaca watchlist add --watchlist-id <id> --symbol GOOGL
alpaca watchlist remove --watchlist-id <id> --symbol GOOGL
alpaca watchlist delete --watchlist-id <id>

资产

alpaca asset list                   # All tradable assets
alpaca asset get --symbol AAPL      # Asset details

原始 API 访问

对于尚未由命名命令覆盖的端点:

alpaca api GET /v2/account
echo '{"symbol":"AAPL","qty":"1","side":"buy","type":"market","time_in_force":"day"}' \
  | alpaca api POST /v2/orders

可发现性

alpaca --help              # Top-level command groups
alpaca --help-all          # Full command tree with all flags
alpaca order submit --help # Per-command flags and descriptions
alpaca order list --schema # Response schema without calling the API

与 AI 智能体配合使用

该 CLI 专为 AI 智能体集成而设计。面向智能体的关键特性:

  • 无确认提示:命令会立即执行。没有交互式的“你确定吗?”对话框。
  • 结构化的 JSON 错误:输出到 stderr,并附带退出码(0 成功,1 错误,2 认证失败)
  • 自动重试:遇到 429/5xx 时自动重试(最多 3 次,遵循 Retry-After)
  • --dry-run:用于预览订单而不执行
  • --schema:用于查看响应结构而不发起 API 调用
  • --quiet:用于抑制非必要输出

幂等订单

可选的 --client-order-id 标志可让你为订单指定唯一标识符(最多 128 个字符)。如果省略,Alpaca 会自动生成一个。

提供后,API 会拒绝具有相同 client_order_id 的重复提交,防止重试逻辑中意外重复下单。

# Generate a client-assigned UUID that you'll use for this order
CLIENT_ORDER_ID="$(uuidgen)"

# Submit with a client-assigned UUID
alpaca order submit --symbol AAPL --side buy --qty 10 --type market \
  --client-order-id "$CLIENT_ORDER_ID"

# Retrieve the order later by that ID
alpaca order get-by-client-id --client-order-id "$CLIENT_ORDER_ID"

在 MCP 客户端中加入白名单

在 Cursor 或 Claude 中通过 AI 智能体使用该 CLI 时,你可以将 CLI 命令加入白名单,以跳过确认提示。请注意,这会移除一层安全机制:拥有白名单订单命令的智能体可以在无人确认的情况下进行交易。

CLI 与 MCP 服务器的区别

两个工具访问相同的 Alpaca API,但它们服务于不同的用例:

方面CLIMCP Server
调用方式每次调用执行一条命令,然后退出在整个会话期间运行的后台进程
上下文成本极小,仅为命令字符串上下文窗口中包含完整的工具模式
输出通过管道传入脚本、文件、其他工具通过 MCP 返回给 AI 模型
需要 AI 宿主不需要,可在任何终端中运行需要,需要 MCP 客户端
最适合脚本、cron、CI、聚焦的智能体操作长时间运行的 AI 会话、多工具编排

自我更新

alpaca update              # Check for updates and prompt to upgrade
alpaca update --yes        # Non-interactive upgrade
alpaca update --check      # Check without upgrading

Shell 补全

alpaca completion bash     # Bash completions
alpaca completion zsh      # Zsh completions
alpaca completion fish     # Fish completions
alpaca completion powershell # PowerShell completions

按照输出说明为你的 shell 安装补全。

重要注意事项

  • 默认为模拟交易:实盘交易需要显式启用,方法是通过 --live 标志或 ALPACA_LIVE_TRADE=true。忘记启用的脚本会命中模拟环境,而非实盘环境。
  • 无确认提示:像 alpaca order cancel-all 和 alpaca position close-all 这样的命令会立即执行,而不会要求确认。
  • API 密钥安全:请妥善保管你的 API 密钥,切勿分享。像对待密码一样对待它们。
  • 订单执行风险:订单直接通过 Alpaca 的 Trading API 执行。提交前请审阅订单,因为非预期订单可能导致真实的财务损失。
  • 速率限制:Alpaca 的 API 设有每账户速率限制。高频查询可能触发速率限制。

资源

免责声明

由我们的 CLI、MCP 服务器和连接的 AI 智能体生成的见解仅供教育和信息参考,不应被视为投资建议。Alpaca 不推荐任何特定证券或投资策略。模型的过往表现不保证未来结果。在做任何决定之前,请进行你自己的尽职调查。