alpaca-trading-mcp-server
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAlpaca Trading MCP Server
Alpaca Trading MCP Server
Skill by ara.so — MCP Skills collection.
The Alpaca MCP Server is an official Model Context Protocol server that enables AI assistants to execute trades, analyze market data, and build trading strategies using natural language. It supports stocks, ETFs, crypto, and options trading through Alpaca's Trading API, with built-in support for paper trading and live trading modes.
由ara.so开发的Skill — MCP Skills合集。
Alpaca MCP Server是官方的Model Context Protocol服务器,可让AI助手通过自然语言执行交易、分析市场数据并构建交易策略。它通过Alpaca的Trading API支持股票、ETF、加密货币和期权交易,内置支持模拟交易(paper trading)和实盘交易模式。
Prerequisites
前置要求
- Python 3.10 or higher
- package installer
uv - Alpaca Trading API keys (free paper trading account available)
- An MCP-compatible client (Claude Desktop, Cursor, VS Code, etc.)
- Python 3.10或更高版本
- 包管理器
uv - Alpaca Trading API密钥(可免费获取模拟交易账户)
- 兼容MCP的客户端(Claude Desktop、Cursor、VS Code等)
Getting API Keys
获取API密钥
- Visit Alpaca Dashboard
- Create a free paper trading account
- Navigate to API Keys section and generate new keys
- Save both and
API_KEYsecurelySECRET_KEY
- 访问Alpaca控制台
- 创建免费的模拟交易账户
- 进入API密钥板块并生成新密钥
- 安全保存和
API_KEYSECRET_KEY
Installation & Configuration
安装与配置
Claude Desktop
Claude Desktop
Edit your Claude Desktop config file:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
json
{
"mcpServers": {
"alpaca": {
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key",
"ALPACA_PAPER_TRADE": "true"
}
}
}
}编辑你的Claude Desktop配置文件:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
json
{
"mcpServers": {
"alpaca": {
"command": "uvx",
"args": ["alpaca-mcp-server"],
"env": {
"ALPACA_API_KEY": "your_alpaca_api_key",
"ALPACA_SECRET_KEY": "your_alpaca_secret_key",
"ALPACA_PAPER_TRADE": "true"
}
}
}
}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",
"ALPACA_PAPER_TRADE": "true"
}
}
}
}添加配置到:
~/.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",
"ALPACA_PAPER_TRADE": "true"
}
}
}
}VS Code
VS Code
Create in your project root:
.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",
"ALPACA_PAPER_TRADE": "true"
}
}
}
}
}在项目根目录创建:
.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",
"ALPACA_PAPER_TRADE": "true"
}
}
}
}
}Docker Deployment
Docker部署
bash
undefinedbash
undefinedClone repository
克隆仓库
git clone https://github.com/alpacahq/alpaca-mcp-server.git
cd alpaca-mcp-server
git clone https://github.com/alpacahq/alpaca-mcp-server.git
cd alpaca-mcp-server
Build image
构建镜像
docker build -t mcp/alpaca:latest .
docker build -t mcp/alpaca:latest .
Add to MCP client config
添加到MCP客户端配置
{
"mcpServers": {
"alpaca": {
"command": "docker",
"args": [
"run", "--rm", "-i",
"-e", "ALPACA_API_KEY",
"-e", "ALPACA_SECRET_KEY",
"-e", "ALPACA_PAPER_TRADE=true",
"mcp/alpaca:latest"
]
}
}
}
undefined{
"mcpServers": {
"alpaca": {
"command": "docker",
"args": [
"run", "--rm", "-i",
"-e", "ALPACA_API_KEY",
"-e", "ALPACA_SECRET_KEY",
"-e", "ALPACA_PAPER_TRADE=true",
"mcp/alpaca:latest"
]
}
}
}
undefinedEnvironment Variables
环境变量
| Variable | Required | Default | Description |
|---|---|---|---|
| Yes | — | Your Alpaca API key |
| Yes | — | Your Alpaca secret key |
| No | | Use paper trading ( |
| No | all | Comma-separated toolsets to enable |
| 变量名 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|
| 是 | — | 你的Alpaca API密钥 |
| 是 | — | 你的Alpaca密钥 |
| 否 | | 使用模拟交易( |
| 否 | all | 启用的工具集,用逗号分隔 |
Toolset Filtering
工具集过滤
Restrict available tools by setting :
ALPACA_TOOLSETSjson
{
"env": {
"ALPACA_API_KEY": "...",
"ALPACA_SECRET_KEY": "...",
"ALPACA_TOOLSETS": "account,trading,stock-data"
}
}Available toolsets:
- — Account info, balances, portfolio history
account - — Orders, positions, exercise options
trading - — Manage watchlists
watchlists - — Asset lookup, option contracts, calendar
assets - — Stock quotes, bars, trades, screeners
stock-data - — Crypto quotes, bars, trades, orderbooks
crypto-data - — Option chains, Greeks, quotes
options-data - — Corporate action announcements
corporate-actions - — Stock and crypto news
news
通过设置限制可用工具:
ALPACA_TOOLSETSjson
{
"env": {
"ALPACA_API_KEY": "...",
"ALPACA_SECRET_KEY": "...",
"ALPACA_TOOLSETS": "account,trading,stock-data"
}
}可用工具集:
- — 账户信息、余额、投资组合历史
account - — 订单、持仓、期权行权
trading - — 管理关注列表
watchlists - — 资产查询、期权合约、交易日历
assets - — 股票报价、K线、交易数据、筛选器
stock-data - — 加密货币报价、K线、交易数据、订单簿
crypto-data - — 期权链、希腊值、报价
options-data - — 公司行动公告
corporate-actions - — 股票和加密货币新闻
news
Switching to Live Trading
切换到实盘交易
WARNING: Live trading uses real money. Test thoroughly in paper trading first.
Update 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 after changing configuration.
警告:实盘交易使用真实资金。请先在模拟交易中充分测试。
更新你的MCP客户端配置:
json
{
"env": {
"ALPACA_API_KEY": "your_live_api_key",
"ALPACA_SECRET_KEY": "your_live_secret_key",
"ALPACA_PAPER_TRADE": "false"
}
}修改配置后重启MCP客户端。
Natural Language Examples
自然语言示例
Once configured, you can use natural language prompts with your AI assistant:
配置完成后,你可以向AI助手发送自然语言指令:
Account Management
账户管理
- "What's my current account balance and buying power?"
- "Show me my portfolio history for the last week"
- "What trades did I make today?"
- "我的当前账户余额和购买力是多少?"
- "显示我过去一周的投资组合历史"
- "我今天进行了哪些交易?"
Stock Trading
股票交易
- "Buy 10 shares of AAPL at market price"
- "Place a limit order to sell 50 shares of TSLA at $250"
- "What's the current price of NVDA?"
- "Show me a 5-minute price chart for SPY from yesterday"
- "以市价买入10股AAPL"
- "设置限价单,以250美元卖出50股TSLA"
- "NVDA当前价格是多少?"
- "显示昨天SPY的5分钟价格走势图"
Crypto Trading
加密货币交易
- "What's the current Bitcoin price?"
- "Buy $500 worth of Ethereum"
- "Show me the order book for BTC/USD"
- "比特币当前价格是多少?"
- "买入价值500美元的以太坊"
- "显示BTC/USD的订单簿"
Options Trading
期权交易
- "Find call options for AAPL expiring next month with strike price $180"
- "What are the Greeks for SPY 450 calls expiring this Friday?"
- "Buy 1 contract of TSLA 220 call expiring in 30 days"
- "找到AAPL下月到期、行权价180美元的看涨期权"
- "SPY行权价450美元、本周五到期的看涨期权的希腊值是多少?"
- "买入1份TSLA行权价220美元、30天后到期的看涨期权合约"
Market Analysis
市场分析
- "Find stocks with high volume today"
- "Get the latest news about Tesla"
- "What corporate actions are upcoming for my portfolio?"
- "找出今日成交量高的股票"
- "获取特斯拉的最新新闻"
- "我的投资组合即将有哪些公司行动?"
Key Capabilities
核心功能
Market Data Tools
市场数据工具
Stock Data:
- Real-time and historical bars (1min to 1month timeframes)
- Latest quotes and trades
- Snapshot data for multiple symbols
- Stock screeners for discovery
Crypto Data:
- Real-time and historical crypto bars
- Latest quotes and trades
- Order book snapshots
- Support for major crypto pairs
Options Data:
- Option chain lookup by expiration/strike/type
- Real-time Greeks and implied volatility
- Latest quotes and trades
- Exchange code lookups
股票数据:
- 实时和历史K线(1分钟至1个月时间范围)
- 最新报价和交易数据
- 多标的快照数据
- 股票筛选器
加密货币数据:
- 实时和历史加密货币K线
- 最新报价和交易数据
- 订单簿快照
- 支持主流加密货币对
期权数据:
- 按到期日/行权价/类型查询期权链
- 实时希腊值和隐含波动率
- 最新报价和交易数据
- 交易所代码查询
Trading Operations
交易操作
Order Types:
- Market orders
- Limit orders
- Stop orders
- Stop-limit orders
- Trailing-stop orders
Order Management:
- Submit new orders
- Cancel individual or all orders
- Modify existing orders
- Check order status and fills
Position Management:
- View open positions
- Close positions
- Exercise option contracts
- Track realized/unrealized P&L
订单类型:
- 市价单
- 限价单
- 止损单
- 止损限价单
- 跟踪止损单
订单管理:
- 提交新订单
- 取消单个或全部订单
- 修改现有订单
- 查询订单状态和成交情况
持仓管理:
- 查看未平仓头寸
- 平仓
- 期权行权
- 跟踪已实现/未实现盈亏
Account Features
账户功能
Portfolio:
- Current balances and buying power
- Portfolio history with customizable timeframes
- Asset positions and allocations
Activity Tracking:
- Trade confirmations
- Account activities
- Order history
Watchlists:
- Create and manage watchlists
- Add/remove symbols
- Query watchlist contents
投资组合:
- 当前余额和购买力
- 可自定义时间范围的投资组合历史
- 资产头寸和配置
活动跟踪:
- 交易确认
- 账户活动
- 订单历史
关注列表:
- 创建和管理关注列表
- 添加/移除标的
- 查询关注列表内容
Working with the Server Programmatically
通过编程方式与服务器交互
While the MCP server is designed for AI assistants, you can also interact with it programmatically:
虽然MCP服务器是为AI助手设计的,但你也可以通过编程方式与之交互:
Direct Python Integration
直接Python集成
python
import asyncio
from alpaca.trading.client import TradingClient
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime, timedeltapython
import asyncio
from alpaca.trading.client import TradingClient
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime, timedeltaInitialize clients with environment variables
使用环境变量初始化客户端
trading_client = TradingClient(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY'),
paper=os.getenv('ALPACA_PAPER_TRADE', 'true').lower() == 'true'
)
data_client = StockHistoricalDataClient(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
trading_client = TradingClient(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY'),
paper=os.getenv('ALPACA_PAPER_TRADE', 'true').lower() == 'true'
)
data_client = StockHistoricalDataClient(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
Get account information
获取账户信息
account = trading_client.get_account()
print(f"Buying Power: ${account.buying_power}")
print(f"Cash: ${account.cash}")
account = trading_client.get_account()
print(f"购买力: ${account.buying_power}")
print(f"现金: ${account.cash}")
Fetch historical stock data
获取历史股票数据
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_data in bars.items():
print(f"{symbol}: {len(bar_data)} bars")
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_data in bars.items():
print(f"{symbol}: {len(bar_data)}条K线")
undefinedPlacing Orders
下单
python
from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForcepython
from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForceMarket order
市价单
market_order_data = MarketOrderRequest(
symbol="AAPL",
qty=10,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
market_order = trading_client.submit_order(market_order_data)
print(f"Market order placed: {market_order.id}")
market_order_data = MarketOrderRequest(
symbol="AAPL",
qty=10,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
market_order = trading_client.submit_order(market_order_data)
print(f"市价单已提交: {market_order.id}")
Limit order
限价单
limit_order_data = LimitOrderRequest(
symbol="TSLA",
limit_price=250.00,
qty=5,
side=OrderSide.SELL,
time_in_force=TimeInForce.GTC
)
limit_order = trading_client.submit_order(limit_order_data)
print(f"Limit order placed: {limit_order.id}")
undefinedlimit_order_data = LimitOrderRequest(
symbol="TSLA",
limit_price=250.00,
qty=5,
side=OrderSide.SELL,
time_in_force=TimeInForce.GTC
)
limit_order = trading_client.submit_order(limit_order_data)
print(f"限价单已提交: {limit_order.id}")
undefinedWorking with Options
期权操作
python
from alpaca.trading.requests import GetOptionContractsRequest
from alpaca.trading.enums import ContractType
from datetime import datetime, timedeltapython
from alpaca.trading.requests import GetOptionContractsRequest
from alpaca.trading.enums import ContractType
from datetime import datetime, timedeltaFind option contracts
查询期权合约
option_request = GetOptionContractsRequest(
underlying_symbols=["AAPL"],
expiration_date_gte=datetime.now().date(),
expiration_date_lte=(datetime.now() + timedelta(days=60)).date(),
type=ContractType.CALL,
strike_price_gte=170,
strike_price_lte=180
)
contracts = trading_client.get_option_contracts(option_request)
for contract in contracts:
print(f"{contract.symbol}: Strike ${contract.strike_price}, "
f"Expires {contract.expiration_date}")
undefinedoption_request = GetOptionContractsRequest(
underlying_symbols=["AAPL"],
expiration_date_gte=datetime.now().date(),
expiration_date_lte=(datetime.now() + timedelta(days=60)).date(),
type=ContractType.CALL,
strike_price_gte=170,
strike_price_lte=180
)
contracts = trading_client.get_option_contracts(option_request)
for contract in contracts:
print(f"{contract.symbol}: 行权价${contract.strike_price}, "
f"到期日{contract.expiration_date}")
undefinedStreaming Real-Time Data
实时数据流
python
from alpaca.data.live import StockDataStreampython
from alpaca.data.live import StockDataStreamInitialize streaming client
初始化流客户端
stream = StockDataStream(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
stream = StockDataStream(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
Define handlers
定义处理器
async def quote_handler(data):
print(f"{data.symbol}: Bid ${data.bid_price} Ask ${data.ask_price}")
async def trade_handler(data):
print(f"{data.symbol}: Trade ${data.price} Size {data.size}")
async def quote_handler(data):
print(f"{data.symbol}: 买价${data.bid_price} 卖价${data.ask_price}")
async def trade_handler(data):
print(f"{data.symbol}: 成交价${data.price} 成交量{data.size}")
Subscribe to streams
订阅流
stream.subscribe_quotes(quote_handler, "AAPL", "TSLA")
stream.subscribe_trades(trade_handler, "AAPL", "TSLA")
stream.subscribe_quotes(quote_handler, "AAPL", "TSLA")
stream.subscribe_trades(trade_handler, "AAPL", "TSLA")
Run stream
运行流
stream.run()
undefinedstream.run()
undefinedCommon Patterns
常见模式
Building a Simple Trading Bot
构建简单交易机器人
python
from alpaca.trading.client import TradingClient
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
from datetime import datetime, timedelta
import pandas as pd
class SimpleMomentumBot:
def __init__(self, api_key, secret_key, paper=True):
self.trading_client = TradingClient(api_key, secret_key, paper=paper)
self.data_client = StockHistoricalDataClient(api_key, secret_key)
def get_momentum(self, symbol, days=10):
"""Calculate simple momentum indicator"""
request = StockBarsRequest(
symbol_or_symbols=[symbol],
timeframe=TimeFrame.Day,
start=datetime.now() - timedelta(days=days*2),
end=datetime.now()
)
bars = self.data_client.get_stock_bars(request)
df = bars.df.reset_index()
# Calculate momentum: % change over period
current_price = df['close'].iloc[-1]
past_price = df['close'].iloc[-days]
return ((current_price - past_price) / past_price) * 100
def execute_strategy(self, symbol, threshold=5.0):
"""Buy if momentum > threshold, sell if momentum < -threshold"""
momentum = self.get_momentum(symbol)
position = self.get_position(symbol)
if momentum > threshold and position is None:
# Buy signal
order = MarketOrderRequest(
symbol=symbol,
qty=10,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
return self.trading_client.submit_order(order)
elif momentum < -threshold and position is not None:
# Sell signal
return self.trading_client.close_position(symbol)
def get_position(self, symbol):
"""Get current position for symbol"""
try:
return self.trading_client.get_open_position(symbol)
except:
return Nonepython
from alpaca.trading.client import TradingClient
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
from datetime import datetime, timedelta
import pandas as pd
class SimpleMomentumBot:
def __init__(self, api_key, secret_key, paper=True):
self.trading_client = TradingClient(api_key, secret_key, paper=paper)
self.data_client = StockHistoricalDataClient(api_key, secret_key)
def get_momentum(self, symbol, days=10):
"""计算简单动量指标"""
request = StockBarsRequest(
symbol_or_symbols=[symbol],
timeframe=TimeFrame.Day,
start=datetime.now() - timedelta(days=days*2),
end=datetime.now()
)
bars = self.data_client.get_stock_bars(request)
df = bars.df.reset_index()
# 计算动量:期间涨跌幅百分比
current_price = df['close'].iloc[-1]
past_price = df['close'].iloc[-days]
return ((current_price - past_price) / past_price) * 100
def execute_strategy(self, symbol, threshold=5.0):
"""动量>阈值时买入,动量<-阈值时卖出"""
momentum = self.get_momentum(symbol)
position = self.get_position(symbol)
if momentum > threshold and position is None:
# 买入信号
order = MarketOrderRequest(
symbol=symbol,
qty=10,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
return self.trading_client.submit_order(order)
elif momentum < -threshold and position is not None:
# 卖出信号
return self.trading_client.close_position(symbol)
def get_position(self, symbol):
"""获取标的当前持仓"""
try:
return self.trading_client.get_open_position(symbol)
except:
return NoneUsage
使用示例
bot = SimpleMomentumBot(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY'),
paper=True
)
order = bot.execute_strategy("AAPL", threshold=5.0)
undefinedbot = SimpleMomentumBot(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY'),
paper=True
)
order = bot.execute_strategy("AAPL", threshold=5.0)
undefinedPortfolio Analysis
投资组合分析
python
from alpaca.trading.client import TradingClient
import pandas as pd
def analyze_portfolio(api_key, secret_key, paper=True):
"""Analyze current portfolio holdings"""
client = TradingClient(api_key, secret_key, paper=paper)
# Get account and positions
account = client.get_account()
positions = client.get_all_positions()
# Calculate metrics
total_equity = float(account.equity)
positions_data = []
for position in positions:
positions_data.append({
'Symbol': position.symbol,
'Qty': float(position.qty),
'Avg Entry': float(position.avg_entry_price),
'Current Price': float(position.current_price),
'Market Value': float(position.market_value),
'P&L': float(position.unrealized_pl),
'P&L %': float(position.unrealized_plpc) * 100,
'Weight %': (float(position.market_value) / total_equity) * 100
})
df = pd.DataFrame(positions_data)
print(f"\nPortfolio Summary")
print(f"Total Equity: ${total_equity:,.2f}")
print(f"Cash: ${float(account.cash):,.2f}")
print(f"Buying Power: ${float(account.buying_power):,.2f}")
print(f"\nPositions:")
print(df.to_string(index=False))
print(f"\nTotal P&L: ${df['P&L'].sum():,.2f}")
return dfpython
from alpaca.trading.client import TradingClient
import pandas as pd
def analyze_portfolio(api_key, secret_key, paper=True):
"""分析当前投资组合持仓"""
client = TradingClient(api_key, secret_key, paper=paper)
# 获取账户和持仓
account = client.get_account()
positions = client.get_all_positions()
# 计算指标
total_equity = float(account.equity)
positions_data = []
for position in positions:
positions_data.append({
'标的': position.symbol,
'数量': float(position.qty),
'平均入场价': float(position.avg_entry_price),
'当前价格': float(position.current_price),
'市值': float(position.market_value),
'盈亏': float(position.unrealized_pl),
'盈亏%': float(position.unrealized_plpc) * 100,
'权重%': (float(position.market_value) / total_equity) * 100
})
df = pd.DataFrame(positions_data)
print(f"\n投资组合摘要")
print(f"总权益: ${total_equity:,.2f}")
print(f"现金: ${float(account.cash):,.2f}")
print(f"购买力: ${float(account.buying_power):,.2f}")
print(f"\n持仓:")
print(df.to_string(index=False))
print(f"\n总盈亏: ${df['盈亏'].sum():,.2f}")
return dfUsage
使用示例
df = analyze_portfolio(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
undefineddf = analyze_portfolio(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
undefinedRisk Management Helper
风险管理助手
python
from alpaca.trading.client import TradingClient
class RiskManager:
def __init__(self, api_key, secret_key, paper=True):
self.client = TradingClient(api_key, secret_key, paper=paper)
def check_position_limits(self, symbol, qty, max_position_pct=10):
"""Verify position doesn't exceed maximum portfolio percentage"""
account = self.client.get_account()
total_equity = float(account.equity)
# Get current price
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
data_client = StockHistoricalDataClient(
self.client.api_key,
self.client.secret_key
)
request = StockLatestQuoteRequest(symbol_or_symbols=[symbol])
quote = data_client.get_stock_latest_quote(request)[symbol]
position_value = float(qty) * float(quote.ask_price)
position_pct = (position_value / total_equity) * 100
if position_pct > max_position_pct:
raise ValueError(
f"Position would be {position_pct:.1f}% of portfolio, "
f"exceeds {max_position_pct}% limit"
)
return True
def check_buying_power(self, symbol, qty):
"""Verify sufficient buying power for trade"""
account = self.client.get_account()
# Get current price
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
data_client = StockHistoricalDataClient(
self.client.api_key,
self.client.secret_key
)
request = StockLatestQuoteRequest(symbol_or_symbols=[symbol])
quote = data_client.get_stock_latest_quote(request)[symbol]
cost = float(qty) * float(quote.ask_price)
buying_power = float(account.buying_power)
if cost > buying_power:
raise ValueError(
f"Insufficient buying power. Cost: ${cost:.2f}, "
f"Available: ${buying_power:.2f}"
)
return Truepython
from alpaca.trading.client import TradingClient
class RiskManager:
def __init__(self, api_key, secret_key, paper=True):
self.client = TradingClient(api_key, secret_key, paper=paper)
def check_position_limits(self, symbol, qty, max_position_pct=10):
"""验证持仓不超过投资组合最大比例限制"""
account = self.client.get_account()
total_equity = float(account.equity)
# 获取当前价格
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
data_client = StockHistoricalDataClient(
self.client.api_key,
self.client.secret_key
)
request = StockLatestQuoteRequest(symbol_or_symbols=[symbol])
quote = data_client.get_stock_latest_quote(request)[symbol]
position_value = float(qty) * float(quote.ask_price)
position_pct = (position_value / total_equity) * 100
if position_pct > max_position_pct:
raise ValueError(
f"持仓将占投资组合的{position_pct:.1f}%,"
f"超过{max_position_pct}%的限制"
)
return True
def check_buying_power(self, symbol, qty):
"""验证交易有足够的购买力"""
account = self.client.get_account()
# 获取当前价格
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
data_client = StockHistoricalDataClient(
self.client.api_key,
self.client.secret_key
)
request = StockLatestQuoteRequest(symbol_or_symbols=[symbol])
quote = data_client.get_stock_latest_quote(request)[symbol]
cost = float(qty) * float(quote.ask_price)
buying_power = float(account.buying_power)
if cost > buying_power:
raise ValueError(
f"购买力不足。交易成本: ${cost:.2f}, "
f"可用购买力: ${buying_power:.2f}"
)
return TrueUsage
使用示例
risk_mgr = RiskManager(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
try:
risk_mgr.check_position_limits("AAPL", 100, max_position_pct=10)
risk_mgr.check_buying_power("AAPL", 100)
print("Trade passes risk checks")
except ValueError as e:
print(f"Risk check failed: {e}")
undefinedrisk_mgr = RiskManager(
api_key=os.getenv('ALPACA_API_KEY'),
secret_key=os.getenv('ALPACA_SECRET_KEY')
)
try:
risk_mgr.check_position_limits("AAPL", 100, max_position_pct=10)
risk_mgr.check_buying_power("AAPL", 100)
print("交易通过风险检查")
except ValueError as e:
print(f"风险检查失败: {e}")
undefinedTroubleshooting
故障排除
Server Not Appearing in MCP Client
服务器未出现在MCP客户端中
- Verify installation: Run in terminal
uvx alpaca-mcp-server --version - Check config syntax: Validate JSON in your MCP client config file
- Restart client: Completely quit and restart your MCP client
- Check logs:
- Claude Desktop: (Mac) or
~/Library/Logs/Claude/mcp*.log(Windows)%APPDATA%\Claude\logs\ - Cursor/VS Code: Check developer console
- Claude Desktop:
- 验证安装: 在终端运行
uvx alpaca-mcp-server --version - 检查配置语法: 验证MCP客户端配置文件中的JSON格式正确
- 重启客户端: 完全退出并重启MCP客户端
- 查看日志:
- Claude Desktop: Mac路径,Windows路径
~/Library/Logs/Claude/mcp*.log%APPDATA%\Claude\logs\ - Cursor/VS Code: 检查开发者控制台
- Claude Desktop: Mac路径
Authentication Errors
认证错误
Error: Invalid API credentialsSolutions:
- Verify API keys are correct and copied completely
- Check for extra spaces in config file
- Ensure you're using paper trading keys with
ALPACA_PAPER_TRADE=true - Regenerate keys in Alpaca dashboard if needed
Error: Invalid API credentials解决方案:
- 验证API密钥正确且完整复制
- 检查配置文件中是否有多余空格
- 确保使用模拟交易密钥时
ALPACA_PAPER_TRADE=true - 必要时在Alpaca控制台重新生成密钥
Tool Not Found Errors
工具未找到错误
Error: Tool 'xyz' not foundSolutions:
- You may be using V1 tool names with V2 server
- Clear your MCP client cache and restart
- Start a fresh chat/session
- Check if you've restricted available tools
ALPACA_TOOLSETS
Error: Tool 'xyz' not found解决方案:
- 可能是使用了V1工具名称搭配V2服务器
- 清除MCP客户端缓存并重启
- 开启新的聊天/会话
- 如果限制了可用工具,检查配置
ALPACA_TOOLSETS
Rate Limiting
速率限制
Error: Rate limit exceededSolutions:
- Reduce frequency of requests
- Add delays between operations
- Upgrade Alpaca account tier for higher limits
- Use batch operations where available
Error: Rate limit exceeded解决方案:
- 减少请求频率
- 在操作之间添加延迟
- 升级Alpaca账户层级以获得更高限制
- 尽可能使用批量操作
Paper Trading vs Live Trading Confusion
模拟交易与实盘交易混淆
If trades aren't appearing:
- Verify setting matches your intention
ALPACA_PAPER_TRADE - Check you're looking at correct dashboard (paper vs live)
- Confirm API keys match the trading mode
如果交易未显示:
- 验证设置符合你的预期
ALPACA_PAPER_TRADE - 检查是否查看了正确的控制台(模拟 vs 实盘)
- 确认API密钥与交易模式匹配
Docker Issues
Docker问题
Error: Cannot connect to Docker daemonSolutions:
- Ensure Docker Desktop is running
- Check Docker daemon is accessible
- Verify image was built successfully:
docker images | grep alpaca - Check container logs:
docker logs <container_id>
Error: Cannot connect to Docker daemon解决方案:
- 确保Docker Desktop正在运行
- 检查Docker守护进程可访问
- 验证镜像构建成功:
docker images | grep alpaca - 查看容器日志:
docker logs <container_id>
Order Rejection
订单被拒绝
Error: Order rejected - insufficient buying powerSolutions:
- Check account buying power before placing order
- Verify order quantity and price are correct
- Ensure market is open for the asset type
- Check for pending orders that may be reserving funds
Error: Order rejected - insufficient buying power解决方案:
- 下单前检查账户购买力
- 验证订单数量和价格正确
- 确保标的对应的市场处于开放状态
- 检查是否有挂单占用了资金
Best Practices
最佳实践
- Always test in paper trading first: Never use live trading without thorough testing
- Implement risk management: Set position limits and stop losses
- Handle errors gracefully: Market conditions change; be prepared for rejections
- Monitor rate limits: Space out requests to avoid throttling
- Use appropriate timeframes: Match data granularity to your strategy needs
- Validate data: Check for missing bars or stale quotes
- Keep credentials secure: Never commit API keys to version control
- Use environment variables: Store configuration in env vars, not code
- Log operations: Track all trades and decisions for analysis
- Start small: Begin with small position sizes while learning
- 始终先在模拟交易中测试:未经充分测试,切勿使用实盘交易
- 实施风险管理:设置持仓限制和止损
- 优雅处理错误:市场条件会变化,要做好订单被拒绝的准备
- 监控速率限制:分散请求以避免被限流
- 使用合适的时间范围:数据粒度要与策略需求匹配
- 验证数据:检查是否有缺失K线或过期报价
- 安全保存凭证:切勿将API密钥提交到版本控制
- 使用环境变量:将配置存储在环境变量中,而非代码里
- 记录操作:跟踪所有交易和决策用于分析
- 从小规模开始:学习阶段先使用小仓位