Star 历史趋势
数据来源: GitHub API · 生成自 Stargazers.cn
README.md

Alpaca CLI

CLI for Alpaca Trading API. Trade stocks & crypto, access market data, and manage your account from the command line.

[!WARNING] Alpha Preview — This CLI is under active development. Commands, flags, and output formats may change or be removed without notice between releases. Do not depend on current behavior in production workflows.

Built for agents

This CLI is designed primarily as a tool for AI agents and automation pipelines, not as a general-purpose interactive terminal tool. It has no confirmation prompts, no "are you sure?" dialogs, and no interactive mode. Every command executes immediately and returns structured output.

This means destructive commands are truly destructive. For example:

  • alpaca position close-all will liquidate your entire portfolio instantly
  • alpaca order cancel-all will cancel every open order without listing them first

There are no guardrails — the CLI trusts that the caller (human or agent) knows what it's asking for. If you're using this with live trading credentials, understand that a single mistyped command can have real financial consequences.

Design Philosophy

The CLI is driven by OpenAPI specs — types, clients, param structs, flag definitions, enum completions, and validation are all generated from api/specs/*.json.

Install

Go (recommended):

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

Homebrew (macOS / Linux) — coming soon:

brew install alpacahq/tap/alpaca

Quick Start

# Authenticate alpaca profile login # Check your account alpaca account get # Submit an order alpaca order submit --symbol AAPL --side buy --qty 10 --type market # List your positions alpaca position list # List open orders alpaca order list --status open # Get market data alpaca data bars --symbol AAPL --start 2025-01-01 --timeframe 1Day # Check if market is open alpaca clock

Safety

Paper trading is the default. When you run alpaca profile login, credentials are stored for paper trading (paper-api.alpaca.markets). Live trading requires API keys.

Authentication methods:

  • OAuth (default, paper only)alpaca profile login opens a browser for OAuth authorization. No keys to copy/paste. The CLI starts a temporary localhost server to receive the callback, exchanges the authorization code for a token, and stores it locally. OAuth is currently restricted to paper trading while the OAuth flow is hardened (PKCE support pending).
  • API keys (paper and live)alpaca profile login --api-key prompts for API key + secret. Required for live trading. Recommended for CI/automation where a browser isn't available.

Credential safety:

  • Credentials are stored in ~/.config/alpaca/profiles/ with restricted file permissions (0600).
  • For CI/automation, use environment variables instead of stored profiles — no secrets touch disk:
export ALPACA_API_KEY=PK... export ALPACA_SECRET_KEY=... alpaca position list
  • Passing --secret via flags is discouraged (shell history exposure). Use interactive login or env vars.

OAuth security model: The CLI is a first-party public OAuth client — the embedded client_id and client_secret are app identifiers, not security credentials. This is standard for native CLI apps (RFC 8252 §8.5). The user controls access through the browser consent screen. OAuth is restricted to paper trading while PKCE support is pending; live trading requires API keys.

Commands

Trading

CommandDescription
alpaca order submitSubmit any order type
alpaca order listList orders
alpaca order getGet order by ID
alpaca order get-by-client-idGet order by client order ID
alpaca order cancelCancel an order
alpaca order cancel-allCancel all open orders
alpaca order replaceReplace an existing order
alpaca position listList open positions
alpaca position getGet position for a symbol
alpaca position closeClose a position
alpaca position close-allClose all positions
alpaca option contractsList option contracts
alpaca option getOption contract details
alpaca option exerciseExercise an option
alpaca option do-not-exerciseMark option as do-not-exercise
alpaca clockUS market clock
alpaca clock marketsMulti-market clock
alpaca calendarUS trading calendar
alpaca calendar marketMarket-specific calendar

Market Data

CommandDescription
alpaca data barsHistorical bars (single symbol)
alpaca data quotesHistorical quotes (single symbol)
alpaca data tradesHistorical trades (single symbol)
alpaca data snapshotStock snapshot (single symbol)
alpaca data latest-barLatest bar (single symbol)
alpaca data latest-quoteLatest quote (single symbol)
alpaca data latest-tradeLatest trade (single symbol)
alpaca data multi-barsHistorical bars (multi-symbol)
alpaca data multi-quotesHistorical quotes (multi-symbol)
alpaca data multi-tradesHistorical trades (multi-symbol)
alpaca data multi-snapshotsSnapshots (multi-symbol)
alpaca data latest-barsLatest bars (multi-symbol)
alpaca data latest-quotesLatest quotes (multi-symbol)
alpaca data latest-tradesLatest trades (multi-symbol)
alpaca data auctionStock auction (single symbol)
alpaca data auctionsStock auctions (multi-symbol)
alpaca data crypto barsCrypto historical bars
alpaca data crypto quotesCrypto historical quotes
alpaca data crypto tradesCrypto historical trades
alpaca data crypto snapshotsCrypto snapshots
alpaca data crypto latest-barsLatest crypto bars
alpaca data crypto latest-quotesLatest crypto quotes
alpaca data crypto latest-tradesLatest crypto trades
alpaca data crypto-orderbookLatest crypto orderbooks
alpaca data option barsOption historical bars
alpaca data option tradesOption historical trades
alpaca data option snapshotOption snapshots
alpaca data option chainOption chain (greeks and pricing)
alpaca data option latest-quotesLatest option quotes
alpaca data option latest-tradesLatest option trades
alpaca data option exchangesOption exchanges
alpaca data option conditionsOption trade conditions
alpaca data forex ratesHistorical forex rates
alpaca data forex latestLatest forex rates
alpaca data corporate-actionsCorporate actions (market data)
alpaca data fixed-incomeFixed income prices
alpaca data logoCompany logo URL
alpaca data meta exchangesExchange code reference
alpaca data meta conditionsTrade/quote condition codes
alpaca data screener most-activesMost active stocks
alpaca data screener moversTop market movers
alpaca data newsMarket news

Account & Assets

CommandDescription
alpaca account getAccount details (equity, buying power)
alpaca account config getAccount configuration
alpaca account config setUpdate account settings
alpaca account activity listAccount activity (fills, dividends, etc.)
alpaca account activity list-by-typeActivity filtered by single type
alpaca account portfolioPortfolio equity and P&L history
alpaca asset listBrowse equities and crypto
alpaca asset getAsset details
alpaca asset treasuryUS Treasury bonds
alpaca asset bondUS Corporate bonds
alpaca corporate-action listCorporate action announcements
alpaca corporate-action getGet a specific announcement
alpaca watchlist listList all watchlists
alpaca watchlist getGet watchlist details
alpaca watchlist createCreate a watchlist
alpaca watchlist updateUpdate a watchlist
alpaca watchlist deleteDelete a watchlist
alpaca watchlist addAdd symbol to watchlist
alpaca watchlist removeRemove symbol from watchlist
alpaca watchlist get-by-nameGet watchlist by name
alpaca watchlist update-by-nameUpdate watchlist by name
alpaca watchlist delete-by-nameDelete watchlist by name
alpaca watchlist add-by-nameAdd symbol to watchlist by name
alpaca watchlist remove-by-nameRemove symbol from watchlist by name
alpaca wallet listList crypto wallets
alpaca wallet transfer listList crypto transfers
alpaca wallet transfer getGet a crypto transfer
alpaca wallet transfer createCreate a crypto transfer
alpaca wallet transfer estimateEstimate transfer fees
alpaca wallet whitelist listList whitelisted addresses
alpaca wallet whitelist addAdd a whitelisted address
alpaca wallet whitelist deleteRemove a whitelisted address

Crypto Perpetuals

CommandDescription
alpaca crypto-perp vitalsAccount vitals
alpaca crypto-perp leverageGet leverage settings
alpaca crypto-perp set-leverageSet leverage for an asset
alpaca crypto-perp wallet listList perp funding wallets
alpaca crypto-perp wallet transfer listList perp transfers
alpaca crypto-perp wallet transfer getGet a perp transfer
alpaca crypto-perp wallet transfer createCreate a perp transfer
alpaca crypto-perp wallet transfer estimateEstimate perp transfer fees
alpaca crypto-perp wallet whitelist listList whitelisted perp addresses
alpaca crypto-perp wallet whitelist addAdd a whitelisted perp address
alpaca crypto-perp wallet whitelist deleteRemove a whitelisted perp address
alpaca crypto-perp data latest-barsLatest perp bars
alpaca crypto-perp data latest-futures-pricingLatest futures pricing
alpaca crypto-perp data latest-orderbooksLatest perp orderbooks
alpaca crypto-perp data latest-quotesLatest perp quotes
alpaca crypto-perp data latest-tradesLatest perp trades

Utilities

CommandDescription
alpaca profile loginAuthenticate via browser OAuth (or --api-key)
alpaca profile logout [name]Remove a profile
alpaca profile listList all profiles
alpaca profile switch <name>Switch between profiles
alpaca api [METHOD] <path>Raw API request (GET, POST, PATCH, DELETE)
alpaca doctorCheck config and API connectivity
alpaca updateCheck for updates and show upgrade instructions
alpaca versionPrint version (alpaca --version also works)

Every command supports --help for full flag documentation.

Output Formats

alpaca position list # JSON (default) alpaca position list --csv # CSV for spreadsheets alpaca position list --jq '.[0].symbol' # Filter JSON with jq expressions

Configuration

Profiles

alpaca profile login # OAuth via browser, paper (default) alpaca profile login --api-key # API key/secret, paper alpaca profile login --api-key --live # API key/secret, live trading alpaca profile login --api-key --name live --live # API key for live with custom name alpaca profile login --name staging --base-url https://staging-api.example.com alpaca profile switch live # Switch default profile

Credentials are stored in ~/.config/alpaca/profiles/.

Environment Variables

VariableDescription
ALPACA_API_KEYAPI key (overrides profile)
ALPACA_SECRET_KEYSecret key (overrides profile)
ALPACA_BASE_URLTrading API base URL
ALPACA_DATA_URLMarket data API base URL
ALPACA_PROFILEProfile name to use
ALPACA_OUTPUTDefault output format (json, csv)
ALPACA_CONFIG_DIRConfig directory (default: ~/.config/alpaca)
ALPACA_QUIETSuppress non-data output - warnings, hints, color (any non-empty value)
ALPACA_VERBOSEShow HTTP request summaries on stderr (any non-empty value)
ALPACA_DEBUGShow HTTP request/response headers and bodies on stderr (any non-empty value)
ALPACA_TRACEShow HTTP timing breakdown on stderr - DNS, TLS, TTFB (any non-empty value)
Global flags: --csv, --jq, --profile, --verbose, --debug, --trace, --quiet, --schema, --timeout.

Precedence: flags > env vars > profile config > defaults.

Shell Completions

Bash

mkdir -p ~/.bash_completion.d alpaca completion bash > ~/.bash_completion.d/alpaca source ~/.bash_completion.d/alpaca

Add source ~/.bash_completion.d/alpaca to your ~/.bashrc (or ~/.bash_profile on macOS) to load on every session.

Zsh

# Ensure completions directory is in fpath (add to ~/.zshrc before compinit) alpaca completion zsh > "${fpath[1]}/_alpaca"

If echo $fpath is empty or the directory doesn't exist, create one:

mkdir -p ~/.zsh/completions echo 'fpath=(~/.zsh/completions $fpath)' >> ~/.zshrc echo 'autoload -Uz compinit && compinit' >> ~/.zshrc alpaca completion zsh > ~/.zsh/completions/_alpaca source ~/.zshrc

Fish

alpaca completion fish > ~/.config/fish/completions/alpaca.fish

Fish loads completions automatically from this directory — no restart required.

PowerShell

alpaca completion powershell > alpaca.ps1 . ./alpaca.ps1

To persist, add the output to your PowerShell profile ($PROFILE).

Verify it works

After installing, open a new shell and type:

alpaca <TAB> # Should show subcommands alpaca order submit --symbol AAPL --side <TAB> # Should show buy/sell

If completions don't appear, check that your shell is sourcing the file and that compinit (zsh) or complete (bash) is loaded.

Enum-valued flags auto-complete with valid values (e.g. --sidebuy/sell, --typemarket/limit/stop/etc.).

Agent & Automation

Designed for scripting, CI pipelines, and AI agent integration. For AI agents, see the alpaca-cli Agent Skill for structured install, auth, and usage guidance in Agent Skills format.

Auth (no disk, no prompts)

export ALPACA_API_KEY=PK... export ALPACA_SECRET_KEY=...

Clean Output

JSON is the default output format. Use --quiet to suppress all non-data output (warnings, hints). Use --jq to filter JSON inline without piping to jq:

alpaca position list --quiet alpaca data latest-trade --symbol AAPL --quiet alpaca order list --jq '[.[] | {id, symbol, side, qty}]' --quiet

Structured Errors

Errors are always JSON on stderr:

{"error":"rate limited","code":0,"status":429,"hint":"Rate limited. Reduce request frequency or add delays between calls."}

Unattended Operations

The CLI is fully non-interactive — no TTY detection, no interactive prompts.

Exit Codes

CodeMeaning
0Success
1API or general error
2Authentication error (401)

Diagnostics

Three orthogonal flags for different debugging needs. Combine as needed.

--verbose — request summaries (what happened):

alpaca account get --verbose # stderr: GET https://paper-api.alpaca.markets/v2/account → 200 (142ms)

--trace — timing breakdown (why is it slow):

alpaca account get --trace # stderr: trace: GET https://paper-api.alpaca.markets/v2/account # stderr: dns: 4ms # stderr: tcp: 98ms (35.194.67.18:443) # stderr: tls: 137ms # stderr: ttfb: 125ms # stderr: total: 365ms → 200

--debug — wire-level detail (what was sent/received):

alpaca account get --debug # stderr: → GET https://paper-api.alpaca.markets/v2/account # stderr: → User-Agent: alpaca-cli/0.0.1 # stderr: ← Content-Type: application/json # stderr: ← {"id":"...","equity":"10000.00",...}

Credentials are always scrubbed from stderr output.

Dry Run

Preview an order without submitting:

alpaca order submit --symbol AAPL --side buy --qty 10 --type limit --limit-price 185.00 --dry-run

Stdin Pipe Support

Pipe JSON payloads into alpaca api POST/PATCH:

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

If both --body and stdin are provided, --body takes precedence.

Response Schemas

Any command with OAS-generated flags supports --schema to show the response fields without making an API call:

alpaca order list --schema # Show Order response fields alpaca asset list --schema # Show Asset response fields alpaca data bars --schema # Show bars response fields

Timeout

Override the default 30-second HTTP timeout:

alpaca data bars --symbol AAPL --start 2020-01-01 --end 2025-01-01 --timeout 120

Resilience

The CLI automatically retries on 429 (rate limit) and 5xx errors with exponential backoff (max 3 attempts). The Retry-After header is respected for rate limits.

JSON Output Stability

JSON output mirrors the Alpaca API response directly. Fields will not be removed or renamed without a major version bump. New fields may be added at any time (treat JSON output as forward-compatible).

Example: Agent Workflow

export ALPACA_API_KEY=PK... export ALPACA_SECRET_KEY=... # Check if market is open clock=$(alpaca clock --quiet) is_open=$(echo "$clock" | jq -r '.is_open') # Place order if open if [ "$is_open" = "true" ]; then alpaca order submit --symbol AAPL --side buy --qty 10 --type market --quiet fi # Preview before submitting alpaca order submit --symbol AAPL --side buy --qty 10 --type limit --limit-price 185.00 --dry-run # Pipe complex payloads cat order.json | alpaca api POST /v2/orders --quiet # Handle errors programmatically if ! result=$(alpaca order get --order-id abc123 --quiet 2>err.json); then status=$(jq .status err.json) echo "Failed with HTTP $status" fi

Development

make build # Build binary to bin/alpaca make install # Install to $GOPATH/bin make test # Run unit tests make test-integration # Run integration tests (requires ALPACA_TEST_API_KEY) make lint # Run linter make generate # Regenerate typed API clients from OpenAPI specs make spec-update # Fetch latest OpenAPI specs from Alpaca docs

Integration Tests

export ALPACA_TEST_API_KEY=PK... export ALPACA_TEST_SECRET_KEY=... export ALPACA_TEST_BASE_URL=https://paper-api.alpaca.markets # optional make test-integration

Self-Update

Check for updates explicitly when you want upgrade guidance. The upgrade command is tailored to your install method:

Install methodUpgrade command
go installgo install github.com/alpacahq/cli/cmd/alpaca@latest
Homebrewbrew upgrade alpaca (coming soon)
alpaca update # Check for updates and show upgrade command alpaca update --check # Machine-readable update check (JSON)

License

Apache 2.0

关于 About

CLI for Trading API

语言 Languages

Go99.4%
Makefile0.6%

提交活跃度 Commit Activity

代码提交热力图
过去 52 周的开发活跃度
159
Total Commits
峰值: 47次/周
Less
More

核心贡献者 Contributors