TradingAgent
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 dev2 — 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 modeHinweis: 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_agentGib 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 ngrokSchritt 2 — Authentifizieren
Kopiere dein persönliches Authtoken
Führe aus:
ngrok config add-authtoken YOUR_REAL_TOKEN_HERESchritt 3 — Den Webserver starten
uv run python -m src.webapp --mockSchritt 4 — Den Tunnel öffnen (in einem zweiten Terminal)
ngrok http 8000ngrok gibt eine öffentliche URL aus, etwa:
Forwarding https://oboe-routing-difficult.ngrok-free.app → http://localhost:8000Teile 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:
redis —
redis:7-alpine, persistiert in einem benannten Volume und wird per Health-Check geprüft, bevor der Agent startettrading-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 -vFühre den CLI-Agenten statt der Web-UI aus:
docker-compose run --rm trading-agent uv run python -m agent.cli_agent --mockBeispiel-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 |
|
market-data |
|
sentiment |
|
watchlist |
|
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 |
Lazy Loading | Modell wird erst beim ersten |
Double-checked Locking |
|
Automatische Geräteerkennung | CUDA → Apple MPS → CPU, keine Umgebungskonfiguration erforderlich |
Batch-Inferenz | Aufteilung der Nachrichtenliste in |
Normalisierter Score | Gibt |
Redis-Cache |
|
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.exampleTests
uv run pytest tests/ -v
# 22 passedUmgebungsvariablen
Variable | Erforderlich | Standard | Elemente |
| Ja | — | Claude-API-Schlüssel — console.anthropic.com |
| Nein | — | Alpaca-Paper-Trading-Schlüssel — alpaca.markets |
| Nein | — | Alpaca-Paper-Trading-Passwort |
| Nein |
| Redis-Verbindungszeichenfolge — automatisch von docker-compose gesetzt |
| Nein |
| Maximale Einzelorder als Anteil des Portfolios |
| Nein |
| Halte Käufe an, wenn das Tages-P&L unter diesen Wert fällt |
| Nein |
| Maximale Orders pro Stunde |
Zustands-Persistenz
Der Agent speichert Warnungen, Handelsverlauf und die Velocity-/Wash-Trade-Zähler in:
~/.trading-agent/state.jsonDiese 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 |
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