Skip to main content
Glama
cactus001

TradingAgent

by cactus001

TradingAgent

MCP 네이티브 대화형 페이퍼 트레이딩 에이전트 — FinBERT 감정 분석 포함.

"Buy 10 AAPL if it drops below $200 today" — 입력하기만 하면, 에이전트가 나머지를 처리합니다.

목차


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를 누르면 종료되며, 세션 대화록(transcript)은 자동으로 transcripts/에 저장됩니다.

옵션 B — 웹 UI (공유 가능한 채팅 인터페이스)

# Mock mode
uv run python -m src.webapp --mock

# Live paper trading
uv run python -m src.webapp

브라우저에서 http://localhost:8000 을 여세요 — 다음과 같은 다크 테마 채팅 UI가 표시됩니다:

  • 실행 중인 MCP 도구를 보여주는 라이브 도구 호출 칩

  • 추론 중 표시되는 애니메이션 thinking 인디케이터

  • 포트폴리오/주문 데이터를 위한 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단계 — 웹 서버 시작

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 + 웹 UI)

Docker Compose가 두 개의 서비스를 시작합니다:

  • redisredis:7-alpine, 명명된 볼륨에 지속 저장하며 에이전트 시작 전에 health check를 수행

  • trading-agentDockerfile에서 빌드하고 포트 8000에서 웹 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

웹 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계층 가드레일 파이프라인이 적용됩니다:

계층

탐지 대상

입력 가드

사용자 메시지의 프롬프트 주입(prompt injection) 패턴

LLM 가드

뉴스 헤드라인에 숨겨진 주입된 지시문, 시스템 프롬프트 강화

도구 가드

잘못된 티커 형식, 음수 수량, 누락된 필수 가격, 타당성 한계(sanity limit)

실행 가드

단일 주문이 포트폴리오의 20% 초과, 일일 손실 5% 초과, 시간당 10건 이상 워시 트레이드(< 5분), 서킷 브레이커(SPY 5% 이상 하락)

출력 가드

브로커 주문 거부, 거래 후 포트폴리오 집중도 경고

place_order은 반드시 2단계 흐름을 따릅니다. confirm=False(미리보기)가 confirm=True(실행)보다 먼저 호출되어야 합니다. 대화에서 사용자의 명시적 확인 없이 어떤 주문도 브로커에 전달되지 않습니다.


프로덕션 서비스로서의 FinBERT

src/models/finbert.py는 FinBERT(ProsusAI/finbert)를 단독 스크립트에서 프로덕션 수준의 호출 가능한 MCP 서비스로 승격시켜줍니다:

패턴

구현

싱글턴

모듈 레벨 _instance, 프로세스당 모델 하나 로드

지연 로딩

모델이 첫 번째 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) 키, 1시간 TTL, 동일한 헤드라인은 GPU에 다시 요청하지 않음

부분 적중 패턴

배치별 캐시 조회, 해 올의 아니요. FinBERT에는 빈 요청만, 적중은 <1ms로 응답

우아한 성능 저하

Redis를 사용할 수 없으면 캐시는 no-op, 추론은 정상 작동

Apple Silicon에서는 추론이 MPS GPU에서 실행됩니다(device: mps로 확인됨). Redis 캐시가 warm 상태이면 동일한 뉴스 흐름에서 반복 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

환경 변수

Variable

Required

Default

Description

ANTHROPIC_API_KEY

Claude API 키 — console.anthropic.com

ALPACA_API_KEY

아니요

Alpaca 페이퍼 트레이딩 키 — alpaca.markets

ALPACA_SECRET_KEY

아니요

Alpaca 페이퍼 트레이딩 시크릿

REDIS_URL

아니요

redis://localhost:6379

Redis 연결 문자열 — docker-compose가 자동 설정

MAX_ORDER_PCT

아니요

0.20

포트폴리오 대비 단일 주문 최대 비율

DAILY_LOSS_LIMIT

아니요

-0.05

일일 P&L이 이 값 아래로 떨어지면 매수 중단

VELOCITY_LIMIT

아니요

10

시간당 최대 주문 수


상태 저장

에이전트는 알림, 거래 내역, 그리고 속도/워시 트레이드 카운터를 다음 위치에 저장합니다:

~/.trading-agent/state.json

이 파일은 프로젝트 디렉터리 밖에 있어 커밋되지 않습니다. 이 파일을 삭제하면 모든 상태가 재설정됩니다.


기술 스택

컴포넌트

기술

에이전트 SDK

Anthropic Python SDK (claude-sonnet-4-6)

도구 프로토콜

MCP (Model Context Protocol) via FastMCP

브로커 API

Alpaca Paper Trading (alpaca-py)

감정 분석 모델

ProsusAI/FinBERT (HuggingFace Transformers)

ML 런타임

PyTorch 2.x — MPS / CUDA / CPU 자동 감지

추론 캐시

Redis 7 — sha256 키, 1시간 TTL, 우아한 성능 저하

웹 서버

FastAPI + Uvicorn + WebSocket

프론트엔드

Vanilla JS, marked.js, CSS custom properties

컨테이너

Docker + docker-compose (두 서비스: redis + trading-agent)

터널

ngrok (free tier)

패키지 관리자

uv

테스트

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