TradingAgent
TradingAgent
MCPネイティブな対話型ペーパートレーディングエージェント。FinBERTによるセンチメント分析を搭載しています。
"Buy 10 AAPL if it drops below $200 today"— と入力するだけで、エージェントが残りをすべて処理します。
Table of Contents
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 を開きます — ダークテーマのチャットUIが表示され、以下の機能があります:
実行中の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は2つのサービスを起動します:
redis —
redis:7-alpine、名前付きボリュームに永続化し、エージェント起動前にヘルスチェックされます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 -dhttp://localhost:8000 を開きます — チャットUIが起動しています。
# 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 -vWeb UIの代わりにCLIエージェントを実行する:
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)ツール
4つのモジュールにわたる20個のツール:
モジュール | ツール |
trading |
|
market-data |
|
sentiment |
|
watchlist |
|
セーフティ
すべての注文に対して5層のガードレールパイプラインが実行されます:
レイヤー | 検出内容 |
入力ガード | ユーザーメッセージ内のプロンプトインジェクションパターン |
LLMガード | ニュース見出しに隠されたインジェクション指示。システムプロンプトを強化 |
ツールガード | 無効なティッカー形式、負の数量、必須価格の欠落、妥当性の上限 |
実行ガード | 単一注文がポートフォリオの20%超、日次損失5%超、10件/時間超の注文、ウォッシュトレード(5分未満)、サーキットブレーカー(SPYが5%以上下落) |
出力ガード | ブローカーによる拒否、約定後の集中リスク警告 |
place_orderは必須の2段階フローを強制します: confirm=False(プレビュー)を先に呼び、その後でconfirm=True(執行)を呼ぶ必要があります。会話内でユーザーが明示的に確認しない限り、注文がブローカーに送信されることはありません。
本番サービスとしてのFinBERT
src/models/finbert.pyは、FinBERT(ProsusAI/finbert)を単独スクリプトから、本番で呼び出し可能なMCPサービスとして利用できるようにします:
パターン | 実装 |
シングルトン | モジュールレベルの |
レイジーローディング | 最初の |
チェック付きダブルロック |
|
デバイス自動検出 | CUDA → Apple MPS → CPU、環境設定不要 |
バッチ推論 | ニュースリストを |
正規化スコア |
|
Redisキャッシュ |
|
部分ヒットパターン | バッチごとにキャッシュをチェック。ミスのみFinBERTを実行し、ヒット1件以下で応答 |
グレースフルな縮退 | Redisが使えない → キャッシュはnoop、推論は通常どおり実行 |
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環境変数
変数 | Required | Default | 説明 |
| Yes | — | Claude APIキー — console.anthropic.com |
| No | — | Alpaca ペーパートレーディングキー — alpaca.markets |
| No | — | Alpaca ペーパートレーディングのシークレット |
| No |
| Redis接続文字列 — docker-composeにより自動設定されます |
| No |
| ポートフォリオに対する単一注文の最大割合 |
| No |
| 日次P&Lがこの値を下回った場合に買いを停止 |
| No |
| 1時間あたりの最大注文数 |
状態の永続化
エージェントは、アラート、売買履歴、および速度制限/ウォッシュトレード・カウンタを次の場所に保存します:
~/.trading-agent/state.jsonこのファイルはプロジェクトディレクトリ外にあり、コミットされることはありません。削除するとすべての状態がリセットされます。
技術スタック
Component | Technology |
Agent SDK | Anthropic Python SDK (claude-sonnet-4-6) |
Tool protocol | MCP (Model Context Protocol) via FastMCP |
Broker API | Alpaca Paper Trading (alpaca-py) |
Sentiment model | ProsusAI/FinBERT (HuggingFace Transformers) |
ML runtime | PyTorch 2.x — MPS / CUDA / CPU auto |
Inference cache | Redis 7 — sha256-keyed, 1h TTL, graceful degradation |
Web server | FastAPI + Uvicorn + WebSocket |
Frontend | Vanilla JS、marked.js、CSSカスタムプロパティ |
Containers | Docker + docker-compose (2サービス: redis + trading-agent) |
Tunnel | ngrok (free tier) |
Package manager | uv |
Tests | 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