TradingAgent
TradingAgent
MCP 原生的对话式模拟交易代理,集成 FinBERT 情感分析。
"如果今天 AAPL 跌到 200 美元以下,就买入 10 股" —— 你只需输入这句话,其余交给代理处理。
目录
Related MCP server: Alpaca API MCP Server
架构
┌──────────────────────┐ ┌──────────────────────────────────────┐
│ CLI Agent (REPL) │ │ Web UI (FastAPI) │
│ claude-sonnet-4-6 │ │ Dark chat · WebSocket · marked.js │
│ agentic loop │ │ ngrok → shareable demo URL │
└──────────┬───────────┘ └──────────────────┬───────────────────┘
│ MCP (stdio) │ MCP (stdio, per session)
└──────────────────┬──────────────────┘
│
┌──────────────────▼──────────────────┐
│ FastMCP Server │
│ 20 tools · 4 modules │
└────┬──────────┬──────────┬──────────┘
│ │ │ │
trading market-data sentiment watchlist
8 tools 5 tools FinBERT 4 tools
│ │ │ │
└──────────┴──────────┴──────────┘
│
┌─────────────▼──────────────┐
│ 5-Layer Guardrail │
│ input·llm·tool·exec·output │
└─────────────┬──────────────┘
│
┌─────────────▼──────────────┐
│ Alpaca Paper API │
│ real quotes · fake money │
└─────────────┬──────────────┘
│
┌─────────────▼──────────────┐
│ Alert Daemon │
│ polls prices every 30s │
│ fires conditional orders │
└────────────────────────────┘快速开始
模拟模式无需 Alpaca 账户。
1 — 安装
# Clone and enter project
git clone https://github.com/cactus001/TRADE-AGENT.git
cd TRADE-AGENT
# Install dependencies (Apple Silicon — use Homebrew Python)
uv sync --python /opt/homebrew/bin/python3.12
# Install dev dependencies for tests
uv sync --extra dev2 — 配置
cp .env.example .env打开 .env 并填写:
ANTHROPIC_API_KEY=sk-ant-... # required — get from console.anthropic.com
ALPACA_API_KEY= # optional — paper trading keys from alpaca.markets
ALPACA_SECRET_KEY= # optional — leave blank to use --mock mode注意: 模拟模式无需任何 Alpaca 密钥,并对真实的假新闻标题运行 FinBERT。
运行代理
选项 A — CLI REPL(终端聊天)
# Mock mode (no Alpaca keys needed)
uv run python -m agent.cli_agent --mock
# Live paper trading (requires Alpaca keys in .env)
uv run python -m agent.cli_agent输入自然语言指令即可。按 Ctrl+C 退出——会话记录会自动保存到 transcripts/。
B — Web UI(可共享的聊天界面)
# Mock mode
uv run python -m src.webapp --mock
# Live paper trading
uv run python -m src.webapp在浏览器中打开 http://localhost:8000,你会看到一个深色主题的聊天界面,其中包含:
实时工具调用标签,显示当前正在运行哪些 MCP 工具
推理阶段会展示动画思考指示器
展示投资组合/订单数据的 Markdown 表格
所有订单确认单上的
PAPER TRADING — NO REAL MONEY水印
选项 C — 通过 ngrok 分享(随时随地实时演示)
适用于面试、演示或与互联网上任何人共享。
步骤 1 — 安装 ngrok
brew install ngrok步骤 2 — 认证
复制你的个人 authtoken
运行:
ngrok config add-authtoken YOUR_REAL_TOKEN_HERE步骤 3 — 启动 Web 服务器
uv run python -m src.webapp --mock步骤 4 — 开启隧道(在第二个终端中)
ngrok http 8000ngrok 会打印一个公网 URL,类似:
Forwarding https://oboe-routing-difficult.ngrok-free.app → http://localhost:8000分享该 URL——任何拥有链接的人都可以从任何浏览器实时打开聊天界面,无需任何设置即可与 TradingAgent 互动。
选项 D — Docker(Redis + Web UI)
Docker Compose 会启动两个服务:
redis —
redis:7-alpine,持久化到命名卷,并在 agent 启动前通过健康检查trading-agent — 从
Dockerfile构建,在 8000 端口运行 Web UI,并自动连接 Redis
# Copy env file and add your Anthropic key
cp .env.example .env
# edit .env — add ANTHROPIC_API_KEY (REDIS_URL is set automatically by compose)
# Build and start both services
docker-compose up --build
# Or run detached
docker-compose up --build -d打开 http://localhost:8000 —— 聊天界面已可用。
# Tail logs
docker-compose logs -f trading-agent
# Stop everything
docker-compose down
# Stop and wipe all volumes (resets state + Redis cache)
docker-compose down -v如果要运行 CLI 代理而不是 Web UI:
docker-compose run --rm trading-agent uv run python -m agent.cli_agent --mock对话示例
You: what's my portfolio looking like
Agent: Portfolio — $101,432.20 total (+1.4% today)
TSLA 15 shares $248.20 +$190.50 (+5.4%)
NVDA 5 shares $134.50 -$43.00 (-6.0%)
Cash $94,890.50 available
You: what's the sentiment on NVDA right now
Agent: NVDA Sentiment (last 4h): BEARISH — score -0.41
Top drivers:
• "Analyst cuts NVDA target to $125" (negative, -0.81)
• "Nvidia faces rising competition" (negative, -0.62)
Recommendation: Consider waiting for stabilisation before adding.
You: buy 10 AAPL if it drops below $200 today
Agent: Day Limit Buy Preview [PAPER TRADING — NO REAL MONEY]
10 shares AAPL · Limit @ $200.00
AAPL currently: $212.95
Expires: 4:00 PM ET today · Max cost: $2,000.00
Confirm? (yes/no)
You: yes
Agent: ✅ Order placed (ID: abc-12345)
Limit buy active — AAPL will be purchased automatically if price hits $200.
[PAPER TRADING — NO REAL MONEY]
You: alert me when TSLA drops below 240
Agent: ✅ Alert set — will notify when TSLA < $240.00
Current price: $248.20 (monitoring every 30s)工具
共 20 个工具,分布在 4 个模块中:
模块 | 工具 |
trading |
|
market-data |
|
sentiment |
|
watchlist |
|
安全机制
每笔订单都会经过 5 层防护流水线:
防护层 | 拦截作用 |
输入防护 | 用户消息中的提示注入模式 |
LLM 防护 | 隐藏在新闻标题中的注入指令;强化系统提示词 |
工具防护 | 无效的 ticker 格式、负数量、缺少必要价格、逻辑合理性限制 |
执行防护 | 单笔订单超过投资组合 20%、单日亏损超过 5%、每小时超过 10 笔订单、洗售交易(小于 5 分钟)、熔断机制(SPY 下跌超过 5%) |
输出防护 | 券商拒单、交易后的持仓集中度警告 |
place_order 强制执行必需的两阶段流程:必须先调用 confirm=False(预览),然后才能调用 confirm=True(执行)。只有在对话中获得用户明确确认后,订单才会提交给券商。
FinBERT 生产化服务
src/models/finbert.py 将 FinBERT(ProsusAI/finbert)从独立脚本升级为生产级可调用的 MCP 服务:
模式 | 实现 |
单例 | 模块级 |
懒加载 | 直到首次调用 |
双重检查锁 |
|
设备自动检测 | CUDA → Apple MPS → CPU,无需任何环境配置 |
批量推理 | 将新闻列表按 |
归一化分数 | 返回 |
Redis 缓存 |
|
部分命中模式 | 逐批查缓存;只有未命中的请求才进入 FinBERT,命中请求 1ms 内返回 |
优雅降级 | Redis 不可用时 → 缓存自动降级为 no-op,推理正常运行 |
在 Apple Silicon 上,推理运行在 MPS GPU 上(已确认:device: mps)。当 Redis 处于热缓存状态时,同一新闻周期内重复调用 get_sentiment 会立即返回。
项目结构
TRADE-AGENT/
├── agent/
│ └── cli_agent.py # REPL — manual agentic loop, auto-saves transcripts
├── src/
│ ├── server.py # FastMCP entry point — registers all 4 tool modules
│ ├── webapp.py # FastAPI + WebSocket web interface
│ ├── config.py # Pydantic settings — env vars with defaults
│ ├── state_manager.py # Persistent state (~/.trading-agent/state.json)
│ ├── alert_daemon.py # Background thread — polls prices every 30s
│ ├── models/
│ │ └── finbert.py # FinBERT singleton service (production ML pattern)
│ ├── cache/
│ │ └── redis_cache.py # Redis sentiment cache — partial-hit, 1h TTL, graceful degradation
│ ├── clients/
│ │ └── alpaca_client.py # Thin wrapper around alpaca-py SDK
│ ├── guardrails/
│ │ ├── input_guard.py # Regex injection pattern detection
│ │ ├── llm_guard.py # News sanitisation + system prompt hardening
│ │ ├── tool_guard.py # Symbol/qty/price validation
│ │ ├── execution_guard.py # Size, loss, velocity, wash-trade, circuit-breaker
│ │ ├── output_guard.py # Broker rejection + concentration check
│ │ └── guard_registry.py # Wires all 5 layers into one object
│ ├── tools/
│ │ ├── trading.py # 8 trading tools (place_order confirm gate)
│ │ ├── market_data.py # 5 market data tools
│ │ ├── sentiment.py # 3 FinBERT sentiment tools
│ │ └── watchlist.py # 4 alert/history tools
│ └── static/
│ └── index.html # Dark chat UI (WebSocket, marked.js, tool chips)
├── mock/
│ └── mock_provider.py # MockAlpacaClient — full demo without API keys
├── tests/
│ ├── test_guardrails.py # 15 tests across all 5 guardrail layers
│ └── test_sentiment.py # 7 tests — singleton, batch, device detection
├── transcripts/ # Auto-saved session logs (git-ignored)
├── pyproject.toml
├── docker-compose.yml
├── Dockerfile
└── .env.example测试
uv run pytest tests/ -v
# 22 passed环境变量
变量 | 是否必需 | 默认值 | 说明 |
| 是 | — | Claude API 密钥 — console.anthropic.com |
| 否 | — | Alpaca 模拟交易密钥 — alpaca.markets |
| 否 | — | Alpaca 模拟交易私钥 |
| 否 |
| Redis 连接字符串 — 由 docker-compose 自动设置 |
| 否 |
| 单笔最大订单占投资组合的比例 |
| 否 |
| 当日盈亏低于该值时暂停买入 |
| 否 |
| 每小时最大订单数 |
状态持久化
代理会将提醒、交易历史以及 velocity/檀洗交易计数器持久化到:
~/.trading-agent/state.json该文件位于项目目录之外,绝不会提交到版本库。删除它即可重置所有状态。
技术栈
组件 | 技术 |
Agent SDK | Anthropic Python SDK(claude-sonnet-4-6) |
工具协议 | MCP(Model Context Protocol),基于 FastMCP |
券商 API | Alpaca 模拟交易(alpaca-py) |
情感模型 | ProsusAI/FinBERT(HuggingFace Transformers) |
机器学习运行时 | PyTorch 2.x —— 自动选择 MPS / CUDA / CPU |
推理缓存 | Redis 7 —— sha256 键、1h TTL、优雅降级 |
Web 服务器 | FastAPI + Uvicorn + WebSocket |
前端 | 原生 JavaScript、marked.js、CSS 自定义属性 |
容器化 | Docker + docker-compose(双服务:redis + trading-agent) |
内网穿透 | ngrok(免费版) |
包管理器 | uv |
测试 | pytest + pytest-asyncio |
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables large language models to interact with Alpaca's trading infrastructure using natural language, supporting stock/options trading, portfolio management, watchlist handling, and real-time market data access.MIT
- AlicenseNot gradedqualityDmaintenanceEnables trading and portfolio management through the Alpaca API, allowing users to place orders, manage positions and watchlists, access market data, and retrieve account information through natural language.543ISC
- AlicenseNot gradedqualityFmaintenanceEnables natural language trading operations through Alpaca's API, supporting stocks, options, crypto, portfolio management, and real-time market data with comprehensive order execution and account management capabilities.MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to execute stock trading operations with built-in risk controls and human approval workflows. Supports paper trading simulation, real brokerage integration (Alpaca, Tradier), backtesting, sentiment analysis, and portfolio management while maintaining strict separation between AI intelligence and trade execution.MIT
Related MCP Connectors
Real-time news with bias scoring, live market data, and AI-powered options pricing
Build, backtest, and deploy quantitative trading strategies from your AI agent.
Real-time financial news for AI agents: search by ticker and source, with sentiment and entities.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/cactus001/TRADE-AGENT'
If you have feedback or need assistance with the MCP directory API, please join our Discord server