Skip to main content
Glama
cactus001

TradingAgent

by cactus001

TradingAgent

MCP-nativer Agent für konversationelles Paper-Trading mit FinBERT-Sentimentanalyse.

"Kaufe 10 AAPL, falls der Kurs heute unter 200 $ fällt" — tippe es ein, der Agent erledigt den Rest.

Inhaltsverzeichnis


Related MCP server: Alpaca API MCP Server

Architektur

┌──────────────────────┐     ┌──────────────────────────────────────┐
│   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   │
                  └────────────────────────────┘

Schnellstart

Für den Mock-Modus wird kein Alpaca-Konto benötigt.

1 — Installation

# 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 — Konfiguration

cp .env.example .env

Öffne .env und fülle aus:

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

Hinweis: Der Mock-Modus funktioniert ohne Alpaca-Schlüssel und führt FinBERT auf echten Fake-News-Schlagzeilen aus.


Den Agenten ausführen

Option A — CLI-REPL (Terminal-Chat)

# 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

Gib Befehle in natürlicher Sprache ein. Drücke Ctrl+C zum Beenden — das Sitzungslogbuch wird automatisch unter transcripts/ gespeichert.

Option B — Web-UI (teilbare Chat-Oberfläche)

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

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

Öffne http://localhost:8000 in deinem Browser — du siehst eine Chat-Oberfläche mit dunklem Design mit:

  • Live-Tool-Chips, die anzeigen, welche MCP-Tools gerade ausgeführt werden

  • Animierter Denk-Indikator während der Inferenz

  • Markdown-Tabellen für Portfolio- und Orderdaten

  • PAPER TRADING — NO REAL MONEY-Wasserzeichen auf allen Orderbestätigungen

Option C — Über ngrok teilen (Live-Demo von überall)

Nutze diese Option für Vorstellungsgespräche, Demos oder um mit beliebigen Personen über das Internet zu teilen.

Schritt 1 — ngrok installieren

brew install ngrok

Schritt 2 — Authentifizieren

  1. Gehe zu dashboard.ngrok.com/get-started/your-authtoken

  2. Kopiere dein persönliches Authtoken

  3. Führe aus:

ngrok config add-authtoken YOUR_REAL_TOKEN_HERE

Schritt 3 — Den Webserver starten

uv run python -m src.webapp --mock

Schritt 4 — Den Tunnel öffnen (in einem zweiten Terminal)

ngrok http 8000

ngrok gibt eine öffentliche URL aus, etwa:

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

Teile diese URL — jeder, der den Link hat, kann die Chat-Oberfläche öffnen und in Echtzeit aus jedem Browser mit TradingAgent interagieren, ganz ohne Einrichtung.

Option D — Docker (Redis + Web-UI)

Docker Compose startet zwei Dienste:

  • redisredis:7-alpine, persistiert in einem benannten Volume und wird per Health-Check geprüft, bevor der Agent startet

  • trading-agent — baut aus Dockerfile, betreibt die Web-UI auf Port 8000 und verbindet sich automatisch mit 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

Öffne http://localhost:8000 — die Chat-UI ist live.

# 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

Führe den CLI-Agenten statt der Web-UI aus:

docker-compose run --rm trading-agent uv run python -m agent.cli_agent --mock

Beispiel-Konversation

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)

Tools

20 Tools in 4 Modulen:

Modul

Tools

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


Sicherheit

Eine 5-stufige Guardrail-Pipeline läuft bei jeder Order:

Ebene

Was abgefangen wird

Eingabe-Guard

Prompt-Injection-Muster in Benutzernachrichten

LLM-Guard

Injizierte Anweisungen in Meldungsschlagzeilen; härtet den System-Prompt

Tool-Guard

Ungültige Tickerformate, negative Mengen, fehlende erforderliche Preise, Sanity-Limits

Ausführungs-Guard

Einzelorder > 20 % des Portfolios, Tagesverlust > 5 %, > 10 Orders/Std., Wash-Trades (< 5 Min.), Circuit-Breaker (SPY fällt > 5 %)

Ausgabe-Guard

Broker-Ablehnungen, Konzentrationswarnungen nach dem Trade

place_order erzwingt einen obligatorischen Zweistufen-Ablauf: confirm=False (Vorschau) muss vor confirm=True (Ausführung) aufgerufen werden. Ohne eine ausdrückliche Benutzerbestätigung im Gespräch erreicht keine Order den Broker.


FinBERT als Produktions-Service

src/models/finbert.py entwickelt FinBERT (ProsusAI/finbert) von einem eigenständigen Skript zu einem produktionsreifen, aufrufbaren MCP-Service weiter:

Muster

Umsetzung

Singleton

Modulweite _instance; ein Modell pro Prozess geladen

Lazy Loading

Modell wird erst beim ersten analyze()-Aufruf geladen

Double-checked Locking

threading.Lock, wobei if self._loaded innerhalb der Sperre geprüft wird

Automatische Geräteerkennung

CUDA → Apple MPS → CPU, keine Umgebungskonfiguration erforderlich

Batch-Inferenz

Aufteilung der Nachrichtenliste in BATCH_SIZE=16 zum Vermeiden von OOM

Normalisierter Score

Gibt pos_prob − neg_prob in [-1.0, +1.0] zurück

Redis-Cache

sha256(headline)-Key, 1h TTL — identische Schlagzeilen erreichen nie zweimal die GPU

Partial-Hit-Muster

Cache-Lookup pro Batch; nur Fehlzugriffe gehen an FinBERT, Treffer werden in <1 ms bedient

Graceful Degradation

Redis nicht verfügbar → Cache ist ein No-op, Inferenz läuft normal

Auf Apple Silicon läuft die Inferenz aus MPS-GPU (bestätigt: device: mps). Mit warmem liefern wiederholte get_sentiment-Aufrufe im selben Nachrichtenzyklus sofort Ergebnisse.

Projektstruktur

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

Tests

uv run pytest tests/ -v
# 22 passed

Umgebungsvariablen

Variable

Erforderlich

Standard

Elemente

ANTHROPIC_API_KEY

Ja

Claude-API-Schlüssel — console.anthropic.com

ALPACA_API_KEY

Nein

Alpaca-Paper-Trading-Schlüssel — alpaca.markets

ALPACA_SECRET_KEY

Nein

Alpaca-Paper-Trading-Passwort

REDIS_URL

Nein

redis://localhost:6379

Redis-Verbindungszeichenfolge — automatisch von docker-compose gesetzt

MAX_ORDER_PCT

Nein

0.20

Maximale Einzelorder als Anteil des Portfolios

DAILY_LOSS_LIMIT

Nein

-0.05

Halte Käufe an, wenn das Tages-P&L unter diesen Wert fällt

VELOCITY_LIMIT

Nein

10

Maximale Orders pro Stunde


Zustands-Persistenz

Der Agent speichert Warnungen, Handelsverlauf und die Velocity-/Wash-Trade-Zähler in:

~/.trading-agent/state.json

Diese Datei befindet sich außerhalb des Projektverzeichnisses und wird niemals geteilt. Lösche sie, um den gesamten Zustand zurückzusetzen.


Tech-Stack

Komponente

Technologie

Agent-SDK

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

Toolprotokoll

MCP (Model Context Protocol) via FastMCP

Broker-API

Alpaca Paper Trading (alpaca-py)

Sentimentmodell

ProsusAI/FinBERT (HuggingFace Transformers)

ML-Laufzeit

PyTorch 2.x — MPS / CUDA / CPU automatisch

Inferenz-Cache

Redis 7 — sha256-Schlüssel, 1h TTL, Graceful Degradation

Webserver

FastAPI + Uvicorn + WebSocket

Frontend

JavaScript, marked.js, CSS custom properties

Container

Docker + docker-compose (zwei Dienste: redis + trading-agent)

Tunnel

ngrok (kostenlose Stufe)

Paketmanager

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