alpaca-mcp-server-trading
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAlpaca MCP Server Trading
Alpaca MCP Server Trading
Overview
概述
Alpaca MCP Server is an official Model Context Protocol server that enables AI assistants to trade stocks, ETFs, crypto, and options through natural language. Built with FastMCP and OpenAPI, it exposes Alpaca's Trading API as MCP tools in Claude Desktop, Cursor, VS Code, PyCharm, and other MCP clients.
Key capabilities:
- Real-time market data (quotes, trades, bars, snapshots)
- Order management (market, limit, stop, trailing-stop orders)
- Options trading (single-leg and multi-leg strategies)
- Crypto trading (BTC, ETH, and more)
- Account and portfolio management
- Watchlists and corporate actions
- Paper trading by default, live trading supported
Alpaca MCP Server是官方的Model Context Protocol服务器,可让AI助手通过自然语言进行股票、ETF、加密货币和期权交易。它基于FastMCP和OpenAPI构建,将Alpaca的交易API以MCP工具的形式开放给Claude Desktop、Cursor、VS Code、PyCharm及其他MCP客户端。
核心功能:
- 实时市场数据(报价、交易、K线、快照)
- 订单管理(市价单、限价单、止损单、跟踪止损单)
- 期权交易(单腿和多腿策略)
- 加密货币交易(BTC、ETH等)
- 账户与投资组合管理
- 关注列表与公司行动
- 默认支持模拟交易,同时支持实盘交易
Installation
安装
Prerequisites
前置条件
- Python 3.10+
- uv package manager
- Alpaca API keys (free paper trading account at alpaca.markets)
- Python 3.10+
- uv包管理器
- Alpaca API密钥(可在alpaca.markets免费注册模拟交易账户获取)
Get API Keys
获取API密钥
- Sign up at Alpaca Dashboard
- Create a paper trading account
- Generate API keys from the dashboard
- 在Alpaca控制台注册账号
- 创建模拟交易账户
- 从控制台生成API密钥
Configuration by MCP Client
通过MCP客户端配置
Claude Desktop
Claude Desktop
Edit (macOS) or (Windows):
~/Library/Application Support/Claude/claude_desktop_config.json%APPDATA%\Claude\claude_desktop_config.jsonjson
{
"mcpServers": {
"alpaca": {
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key"
}
}
}
}Restart Claude Desktop.
编辑(macOS)或(Windows):
~/Library/Application Support/Claude/claude_desktop_config.json%APPDATA%\Claude\claude_desktop_config.jsonjson
{
"mcpServers": {
"alpaca": {
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key"
}
}
}
}重启Claude Desktop。
Cursor
Cursor
Add to :
~/.cursor/mcp.jsonjson
{
"mcpServers": {
"alpaca": {
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key"
}
}
}
}Restart Cursor.
添加配置到:
~/.cursor/mcp.jsonjson
{
"mcpServers": {
"alpaca": {
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key"
}
}
}
}重启Cursor。
VS Code
VS Code
Create in your project:
.vscode/mcp.jsonjson
{
"mcp": {
"servers": {
"alpaca": {
"type": "stdio",
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key"
}
}
}
}
}Reload window.
在项目中创建:
.vscode/mcp.jsonjson
{
"mcp": {
"servers": {
"alpaca": {
"type": "stdio",
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key"
}
}
}
}
}重新加载窗口。
PyCharm
PyCharm
- Go to File → Settings → Tools → Model Context Protocol (MCP)
- Add new server:
- Type: stdio
- Command:
uvx - Arguments:
alpaca-mcp-server
- Set environment variables:
ALPACA_API_KEY=your_alpaca_api_key ALPACA_SECRET_KEY=your_alpaca_secret_key
- 依次进入File → Settings → Tools → Model Context Protocol (MCP)
- 添加新服务器:
- 类型:stdio
- 命令:
uvx - 参数:
alpaca-mcp-server
- 设置环境变量:
ALPACA_API_KEY=your_alpaca_api_key ALPACA_SECRET_KEY=your_alpaca_secret_key
Docker
Docker
bash
git clone https://github.com/alpacahq/alpaca-mcp-server.git
cd alpaca-mcp-server
docker build -t mcp/alpaca:latest .Add to MCP client config:
json
{
"mcpServers": {
"alpaca": {
"command": "docker",
"args": [
"run", "--rm", "-i",
"-e", "ALPACA_API_KEY",
"-e", "ALPACA_SECRET_KEY",
"-e", "ALPACA_PAPER_TRADE=true",
"mcp/alpaca:latest"
]
}
}
}bash
git clone https://github.com/alpacahq/alpaca-mcp-server.git
cd alpaca-mcp-server
docker build -t mcp/alpaca:latest .添加到MCP客户端配置:
json
{
"mcpServers": {
"alpaca": {
"command": "docker",
"args": [
"run", "--rm", "-i",
"-e", "ALPACA_API_KEY",
"-e", "ALPACA_SECRET_KEY",
"-e", "ALPACA_PAPER_TRADE=true",
"mcp/alpaca:latest"
]
}
}
}Configuration
配置
All configuration is via environment variables in your MCP client config:
| Variable | Required | Default | Description |
|---|---|---|---|
| Yes | — | Alpaca API key |
| Yes | — | Alpaca secret key |
| No | | Set to |
| No | all | Comma-separated toolsets to enable |
所有配置通过MCP客户端配置中的环境变量完成:
| 变量 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|
| 是 | — | Alpaca API密钥 |
| 是 | — | Alpaca密钥 |
| 否 | | 设置为 |
| 否 | all | 启用的工具集,以逗号分隔 |
Switching to Live Trading
切换到实盘交易
⚠️ WARNING: Live trading uses real money. Test thoroughly in paper trading first.
Update env vars in your MCP client config:
json
{
"env": {
"ALPACA_API_KEY": "your_live_api_key",
"ALPACA_SECRET_KEY": "your_live_secret_key",
"ALPACA_PAPER_TRADE": "false"
}
}Restart your MCP client.
⚠️ 警告:实盘交易使用真实资金,请先在模拟交易中充分测试。
更新MCP客户端配置中的环境变量:
json
{
"env": {
"ALPACA_API_KEY": "your_live_api_key",
"ALPACA_SECRET_KEY": "your_live_secret_key",
"ALPACA_PAPER_TRADE": "false"
}
}重启MCP客户端。
Toolset Filtering
工具集过滤
Limit the server to specific capabilities by setting :
ALPACA_TOOLSETSjson
{
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key",
"ALPACA_TOOLSETS": "stock-data,trading,account"
}
}Available toolsets:
- — Account info, balances, portfolio history
account - — Orders, positions, option exercises
trading - — Watchlist management
watchlists - — Asset lookup, option contracts, market calendar
assets - — Stock bars, quotes, trades, snapshots, screeners
stock-data - — Crypto bars, quotes, trades, orderbooks
crypto-data - — Option bars, quotes, Greeks, chain data
options-data - — Corporate action announcements
corporate-actions - — News articles for stocks and crypto
news
通过设置限制服务器的特定功能:
ALPACA_TOOLSETSjson
{
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key",
"ALPACA_TOOLSETS": "stock-data,trading,account"
}
}可用工具集:
- — 账户信息、余额、投资组合历史
account - — 订单、持仓、期权行权
trading - — 关注列表管理
watchlists - — 资产查询、期权合约、市场日历
assets - — 股票K线、报价、交易、快照、筛选器
stock-data - — 加密货币K线、报价、交易、订单簿
crypto-data - — 期权K线、报价、希腊值、链数据
options-data - — 公司行动公告
corporate-actions - — 股票和加密货币的新闻文章
news
Common Usage Patterns
常见使用场景
Getting Account Information
获取账户信息
Natural language prompts that work:
- "What's my account balance?"
- "Show my portfolio history for the last week"
- "What's my buying power?"
The AI will use tools like and .
get_account_infoget_portfolio_history有效的自然语言指令:
- "我的账户余额是多少?"
- "显示我过去一周的投资组合历史"
- "我的购买力是多少?"
AI会使用和等工具。
get_account_infoget_portfolio_historyTrading Stocks
股票交易
Market order:
Buy 10 shares of AAPL at market priceLimit order:
Buy 5 shares of TSLA with a limit price of $250Stop-loss:
Sell 3 shares of NVDA with a stop price of $800Bracket order:
Buy 10 shares of GOOGL at market with a take-profit at $150 and stop-loss at $140市价单:
以市价买入10股AAPL限价单:
以250美元的限价买入5股TSLA止损单:
以800美元的止损价卖出3股NVDA括号单:
以市价买入10股GOOGL,设置止盈价150美元、止损价140美元Trading Crypto
加密货币交易
Buy 0.1 BTC at market pricePlace a limit order to buy 1 ETH at $3000以市价买入0.1 BTC设置限价单以3000美元买入1 ETHTrading Options
期权交易
Find contracts:
Show me call options for SPY expiring next Friday with strikes near $450Place option trade:
Buy 1 call option for AAPL with strike $180 expiring in 30 daysMulti-leg strategy:
Create an iron condor for SPY with the following legs: buy 1 put at $440, sell 1 put at $445, sell 1 call at $455, buy 1 call at $460, all expiring next Friday查找合约:
显示下周五到期、行权价接近450美元的SPY看涨期权下单交易:
买入1份30天后到期、行权价180美元的AAPL看涨期权多腿策略:
为SPY创建铁鹰策略:买入1份行权价440美元的看跌期权,卖出1份行权价445美元的看跌期权,卖出1份行权价455美元的看涨期权,买入1份行权价460美元的看涨期权,所有合约均在下周五到期Market Data
市场数据
Real-time quote:
Get the current price of AAPLHistorical bars:
Show me daily price bars for TSLA for the last monthSnapshot:
Get a snapshot of NVDA including latest quote, trade, and daily barOption chain:
Show me the option chain for SPY expiring in 7 days实时报价:
获取AAPL当前价格历史K线:
显示TSLA过去一个月的日K线快照:
获取NVDA的快照,包括最新报价、交易和日K线期权链:
显示7天后到期的SPY期权链Watchlists
关注列表
Create a watchlist called "Tech Stocks" with AAPL, MSFT, GOOGLShow me all my watchlistsAdd TSLA to my "Tech Stocks" watchlist创建名为"科技股"的关注列表,包含AAPL、MSFT、GOOGL显示我所有的关注列表将TSLA添加到我的"科技股"关注列表Programmatic Usage (Python SDK)
程序化使用(Python SDK)
While the MCP server is designed for natural language use, you can also use the Alpaca Python SDK directly:
python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
import os虽然MCP服务器专为自然语言使用设计,但你也可以直接使用Alpaca Python SDK:
python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
import osInitialize client
初始化客户端
client = TradingClient(
api_key=os.environ["ALPACA_API_KEY"],
secret_key=os.environ["ALPACA_SECRET_KEY"],
paper=True # Use paper trading
)
client = TradingClient(
api_key=os.environ["ALPACA_API_KEY"],
secret_key=os.environ["ALPACA_SECRET_KEY"],
paper=True # 使用模拟交易
)
Get account info
获取账户信息
account = client.get_account()
print(f"Buying power: ${account.buying_power}")
account = client.get_account()
print(f"购买力: ${account.buying_power}")
Place market order
提交市价单
order_data = MarketOrderRequest(
symbol="AAPL",
qty=10,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
order = client.submit_order(order_data)
print(f"Order submitted: {order.id}")
order_data = MarketOrderRequest(
symbol="AAPL",
qty=10,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
order = client.submit_order(order_data)
print(f"订单已提交: {order.id}")
Get all positions
获取所有持仓
positions = client.get_all_positions()
for position in positions:
print(f"{position.symbol}: {position.qty} shares @ ${position.avg_entry_price}")
positions = client.get_all_positions()
for position in positions:
print(f"{position.symbol}: {position.qty} 股 @ ${position.avg_entry_price}")
Cancel all orders
取消所有订单
client.cancel_orders()
For market data:
```python
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime, timedeltaclient.cancel_orders()
获取市场数据:
```python
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime, timedeltaInitialize data client (no auth needed for free data)
初始化数据客户端(免费数据无需授权)
data_client = StockHistoricalDataClient(
api_key=os.environ["ALPACA_API_KEY"],
secret_key=os.environ["ALPACA_SECRET_KEY"]
)
data_client = StockHistoricalDataClient(
api_key=os.environ["ALPACA_API_KEY"],
secret_key=os.environ["ALPACA_SECRET_KEY"]
)
Get historical bars
获取历史K线
request_params = StockBarsRequest(
symbol_or_symbols=["AAPL", "TSLA"],
timeframe=TimeFrame.Day,
start=datetime.now() - timedelta(days=30),
end=datetime.now()
)
bars = data_client.get_stock_bars(request_params)
for symbol, bar_set in bars.items():
print(f"\n{symbol}:")
for bar in bar_set:
print(f" {bar.timestamp}: O=${bar.open} H=${bar.high} L=${bar.low} C=${bar.close}")
undefinedrequest_params = StockBarsRequest(
symbol_or_symbols=["AAPL", "TSLA"],
timeframe=TimeFrame.Day,
start=datetime.now() - timedelta(days=30),
end=datetime.now()
)
bars = data_client.get_stock_bars(request_params)
for symbol, bar_set in bars.items():
print(f"\n{symbol}:")
for bar in bar_set:
print(f" {bar.timestamp}: 开盘=${bar.open} 最高=${bar.high} 最低=${bar.low} 收盘=${bar.close}")
undefinedExample Prompts
示例指令
Account & Portfolio
账户与投资组合
- "What's my current portfolio value?"
- "Show me my trading activity from yesterday"
- "What's my day trade count?"
- "我当前的投资组合价值是多少?"
- "显示我昨天的交易活动"
- "我的日内交易次数是多少?"
Orders
订单
- "Cancel all my pending orders"
- "Show me all open orders for AAPL"
- "Replace my TSLA order with a new limit price of $245"
- "取消我所有待处理的订单"
- "显示我所有AAPL的未成交订单"
- "将我的TSLA订单替换为245美元的新限价"
Positions
持仓
- "What positions do I currently hold?"
- "Close my entire NVDA position"
- "What's my average entry price for MSFT?"
- "我当前持有哪些仓位?"
- "平掉我所有的NVDA仓位"
- "我MSFT的平均入场价是多少?"
Market Data
市场数据
- "Get the latest trade for BTC/USD"
- "Show me hourly bars for SPY from last week"
- "What's the bid-ask spread for AAPL?"
- "获取BTC/USD的最新交易价格"
- "显示SPY上周的小时K线"
- "AAPL的买卖价差是多少?"
Options
期权
- "Show me put options for QQQ with delta around -0.30"
- "Get Greeks for SPY call option with strike 450 expiring next Friday"
- "What are the latest option trade prices for AAPL?"
- "显示Delta约为-0.30的QQQ看跌期权"
- "获取下周五到期、行权价450美元的SPY看涨期权的希腊值"
- "AAPL的最新期权交易价格是多少?"
Watchlists
关注列表
- "Delete my 'Old Stocks' watchlist"
- "Remove TSLA from my 'Tech' watchlist"
- "Update my watchlist to include COIN"
- "删除我的'旧股票'关注列表"
- "从我的'科技股'关注列表中移除TSLA"
- "更新我的关注列表,加入COIN"
Troubleshooting
故障排除
Tools not appearing in MCP client
MCP客户端中未显示工具
- Restart your MCP client after updating config
- Start a fresh chat/session to clear cached tool lists
- Verify config syntax — JSON must be valid (use a JSON validator)
- Check logs — Claude Desktop: View → Developer → Server Logs
- Test uvx — Run in terminal to verify installation
uvx alpaca-mcp-server --help
- 更新配置后重启MCP客户端
- 开启新的对话/会话以清除缓存的工具列表
- 验证配置语法——JSON必须有效(可使用JSON验证工具)
- 查看日志——Claude Desktop:View → Developer → Server Logs
- 测试uvx——在终端运行验证安装
uvx alpaca-mcp-server --help
Authentication errors
认证错误
Error: Invalid API credentialsSolution:
- Verify and
ALPACA_API_KEYare set correctlyALPACA_SECRET_KEY - Ensure no extra quotes or whitespace in env vars
- Check if using paper keys with or live keys with
ALPACA_PAPER_TRADE=truefalse - Regenerate keys in Alpaca dashboard if needed
Error: Invalid API credentials解决方案:
- 确认和
ALPACA_API_KEY设置正确ALPACA_SECRET_KEY - 确保环境变量中没有多余的引号或空格
- 检查是否模拟交易密钥对应,实盘密钥对应
ALPACA_PAPER_TRADE=truefalse - 必要时在Alpaca控制台重新生成密钥
Live trading not working
实盘交易无法使用
Error: This endpoint is not available for paper tradingSolution:
- Set in env vars
ALPACA_PAPER_TRADE=false - Use live trading API keys (not paper keys)
- Restart MCP client after changing config
Error: This endpoint is not available for paper trading解决方案:
- 在环境变量中设置
ALPACA_PAPER_TRADE=false - 使用实盘交易API密钥(而非模拟交易密钥)
- 修改配置后重启MCP客户端
Specific tools not available
特定工具不可用
If certain tools are missing (e.g., options tools):
Solution:
- Remove or update to include the toolset you need
ALPACA_TOOLSETS - Default is all toolsets — if you've filtered, add back missing ones:
json
{ "env": { "ALPACA_TOOLSETS": "account,trading,stock-data,options-data" } }
如果某些工具缺失(如期权工具):
解决方案:
- 删除或更新,包含你需要的工具集
ALPACA_TOOLSETS - 默认启用所有工具集——如果进行了过滤,添加回缺失的工具集:
json
{ "env": { "ALPACA_TOOLSETS": "account,trading,stock-data,options-data" } }
Order placement fails
下单失败
Error: Insufficient buying powerSolution:
- Check account balance with "What's my buying power?"
- Reduce order quantity
- In paper trading, you have $100k virtual cash by default
Error: Symbol not foundSolution:
- Verify symbol is correct (e.g., "AAPL" not "APPLE")
- Check if asset is tradable: "Is AAPL tradable?"
- Some assets may not be available in paper trading
Error: Insufficient buying power解决方案:
- 通过“我的购买力是多少?”查询账户余额
- 减少订单数量
- 模拟交易默认提供10万美元虚拟资金
Error: Symbol not found解决方案:
- 确认代码正确(如“AAPL”而非“APPLE”)
- 查询资产是否可交易:“AAPL是否可交易?”
- 部分资产可能在模拟交易中不可用
Rate limiting
速率限制
Error: Rate limit exceededSolution:
- Alpaca has rate limits (200 requests/minute for paper, varies for live)
- Add delays between rapid requests
- Use batch endpoints where available (e.g., get multiple positions at once)
Error: Rate limit exceeded解决方案:
- Alpaca有速率限制(模拟交易200次请求/分钟,实盘有所不同)
- 在频繁请求之间添加延迟
- 尽可能使用批量接口(如一次性获取多个仓位)
Upgrading from V1
从V1版本升级
If you used alpaca-mcp-server V1:
- V2 is a complete rewrite — tool names and parameters have changed
- Remove old config — Delete any files or
.envcommands from V1 setupinit - Update MCP client config — Use the V2 config format shown above
- Clear caches — Restart MCP client and start fresh sessions
- Update prompts — Remove references to V1-specific tool names
- To stay on V1: Pin to in config
uvx alpaca-mcp-server==1.x.x serve
如果你使用过alpaca-mcp-server V1:
- V2是完全重写版本——工具名称和参数已更改
- 移除旧配置——删除V1设置中的所有文件或
.env命令init - 更新MCP客户端配置——使用上述V2配置格式
- 清除缓存——重启MCP客户端并开启新会话
- 更新指令——移除所有V1特定工具名称的引用
- **保留V1版本:**在配置中固定版本为
uvx alpaca-mcp-server==1.x.x serve
Docker issues
Docker问题
Error: Cannot connect to Docker daemonSolution:
- Ensure Docker is running
- On macOS/Windows: Start Docker Desktop
- Test with
docker ps
Error: Cannot connect to Docker daemon解决方案:
- 确保Docker正在运行
- macOS/Windows:启动Docker Desktop
- 使用测试连接
docker ps
Testing
测试
The MCP server exposes tools dynamically — test by asking your AI assistant:
List all available Alpaca toolsOr verify directly with the MCP inspector (if your client supports it).
For paper trading, you can freely test all operations without risk. Recommended test flow:
- "What's my account balance?"
- "Buy 1 share of AAPL at market price"
- "Show my current positions"
- "Get a quote for AAPL"
- "Cancel all orders"
- "Close my AAPL position"
MCP服务器会动态暴露工具——可通过向AI助手提问进行测试:
列出所有可用的Alpaca工具或者直接通过MCP检查器验证(如果客户端支持)。
模拟交易中,你可以无风险地测试所有操作。推荐测试流程:
- "我的账户余额是多少?"
- "以市价买入1股AAPL"
- "显示我当前的持仓"
- "获取AAPL的报价"
- "取消所有订单"
- "平掉我的AAPL仓位"
Resources
资源
Disclosure
披露
This is a trading platform. Use paper trading for testing. Live trading involves real money and risk of loss. Past performance does not guarantee future results. Alpaca Securities LLC is a member of FINRA/SIPC. See alpaca.markets/disclosures for important disclosures.
这是一个交易平台。请使用模拟交易进行测试。实盘交易涉及真实资金,存在亏损风险。过往业绩不代表未来结果。Alpaca Securities LLC是FINRA/SIPC成员。重要披露请查看alpaca.markets/disclosures。