Skip to main content
Glama
cactus001

TradingAgent

by cactus001

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 dev

2 — 設定

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 — 認証する

  1. dashboard.ngrok.com/get-started/your-authtoken にアクセスします

  2. 自分のauthtokenをコピーします

  3. 以下を実行します:

ngrok config add-authtoken YOUR_REAL_TOKEN_HERE

ステップ3 — Webサーバーを起動する

uv run python -m src.webapp --mock

ステップ4 — トンネルを開く(別のターミナルで)

ngrok http 8000

ngrokは次のようなパブリックURLを表示します:

Forwarding  https://oboe-routing-difficult.ngrok-free.app → http://localhost:8000

そのURLを共有してください — リンクがあれば誰でも、セットアップ不要で、任意のブラウザからTradingAgentのチャットインターフェースを開いてリアルタイムに操作できます。

オプションD — Docker(Redis + Web UI)

Docker Composeは2つのサービスを起動します:

  • redisredis:7-alpine、名前付きボリュームに永続化し、エージェント起動前にヘルスチェックされます

  • trading-agentDockerfileからビルドし、ポート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 を開きます — チャット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 -v

Web 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

get_account, get_positions, get_orders, place_order, cancel_order, cancel_all_orders, get_portfolio_history, get_asset_info

market-data

get_quote, get_bars, get_news, get_market_status, search_symbol

sentiment

get_sentiment, get_market_mood, explain_sentiment

watchlist

set_price_alert, get_active_alerts, cancel_alert, get_trade_history


セーフティ

すべての注文に対して5層のガードレールパイプラインが実行されます:

レイヤー

検出内容

入力ガード

ユーザーメッセージ内のプロンプトインジェクションパターン

LLMガード

ニュース見出しに隠されたインジェクション指示。システムプロンプトを強化

ツールガード

無効なティッカー形式、負の数量、必須価格の欠落、妥当性の上限

実行ガード

単一注文がポートフォリオの20%超、日次損失5%超、10件/時間超の注文、ウォッシュトレード(5分未満)、サーキットブレーカー(SPYが5%以上下落)

出力ガード

ブローカーによる拒否、約定後の集中リスク警告

place_orderは必須の2段階フローを強制します: confirm=False(プレビュー)を先に呼び、その後でconfirm=True(執行)を呼ぶ必要があります。会話内でユーザーが明示的に確認しない限り、注文がブローカーに送信されることはありません。


本番サービスとしてのFinBERT

src/models/finbert.pyは、FinBERT(ProsusAI/finbert)を単独スクリプトから、本番で呼び出し可能なMCPサービスとして利用できるようにします:

パターン

実装

シングルトン

モジュールレベルの_instance、プロセスごとに1つのモデル

レイジーローディング

最初のanalyze()呼び出しまでモデルを読み込まない

チェック付きダブルロック

threading.Lockと、ロック内でチェックされるif self._loaded

デバイス自動検出

CUDA → Apple MPS → CPU、環境設定不要

バッチ推論

ニュースリストをBATCH_SIZE=16のチャンクに分割し、OOMを回避

正規化スコア

pos_prob − neg_prob[-1.0, +1.0]の範囲で返す

Redisキャッシュ

sha256(headline)キー、TTL 1時間 — 同じ見出しがGPUに2回ヒットしない

部分ヒットパターン

バッチごとにキャッシュをチェック。ミスのみ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

説明

ANTHROPIC_API_KEY

Yes

Claude APIキー — console.anthropic.com

ALPACA_API_KEY

No

Alpaca ペーパートレーディングキー — alpaca.markets

ALPACA_SECRET_KEY

No

Alpaca ペーパートレーディングのシークレット

REDIS_URL

No

redis://localhost:6379

Redis接続文字列 — docker-composeにより自動設定されます

MAX_ORDER_PCT

No

0.20

ポートフォリオに対する単一注文の最大割合

DAILY_LOSS_LIMIT

No

-0.05

日次P&Lがこの値を下回った場合に買いを停止

VELOCITY_LIMIT

No

10

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

F
license - not found
Not graded
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

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

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables 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
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables 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.
    54
    3
    ISC
  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables 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
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables 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

View all related MCP servers

Related MCP Connectors

View all MCP Connectors

Latest Blog Posts

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