多智能体自动交易平台

该产品是一个由4个AI交易代理驱动的自动化交易平台,集成6个MCP服务器与44个工具,提供实时仪表盘、投资组合分析和持久化存储,适用于金融市场的自动交易模拟与生产部署。

  • by hao-hoang
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 hao-hoang/trading-floor-agent

使用说明

Trading Floor Agent 📈

A production-ready autonomous trading floor with 4 AI agents making autonomous trades, powered by 6 MCP servers and 44 tools. This application demonstrates advanced agentic AI capabilities with real-time trading simulation, comprehensive monitoring, and professional deployment infrastructure.

Features

  • 🤖 4 Autonomous Trading Agents: Warren (Value), George (Macro), Ray (Systematic), Cathie (Crypto)
  • 🔌 6 MCP Servers: Accounts, Market Data, Push Notifications, Fetch, Brave Search, Memory
  • 📊 Real-time Dashboard: Beautiful Streamlit UI with live portfolio tracking
  • 💾 Persistent Storage: SQLite database for accounts, transactions, and market data
  • 🔄 Automated Trading: Configurable trading cycles with market hours awareness
  • 📈 Portfolio Analytics: Real-time P&L tracking, holdings, and transaction history
  • 🐳 Docker Support: Fully containerized for easy deployment
  • 🧪 Test Coverage: Comprehensive test suite with TDD approach
  • ⚙️ Production Ready: Environment configuration, logging, error handling

Architecture

The Trading Floor consists of:

  1. 4 Trading Agents: Each with unique investment strategies

    • Warren: Value-oriented, long-term investor
    • George: Aggressive macro trader
    • Ray: Systematic risk parity approach
    • Cathie: Innovation and crypto ETF focus
  2. 6 MCP Servers:

    • Accounts Server: Manages trader accounts and transactions
    • Market Server: Provides stock price data (Polygon API)
    • Push Server: Sends notifications (Pushover)
    • Fetch Server: Web page fetching
    • Brave Search Server: Web search capabilities
    • Memory Server: Persistent knowledge graph storage
  3. Core Components:

    • Account Management: Balance, holdings, transactions
    • Market Data: Real-time and EOD stock prices
    • Trading Logic: Buy/sell execution with spread simulation
    • Logging & Tracing: Comprehensive activity tracking

Prerequisites

  • Python 3.10, 3.11, or 3.12
  • UV package manager
  • Docker and Docker Compose (for containerized deployment)
  • Node.js and npm (for MCP servers)
  • API Keys:
    • OpenAI API key (required)
    • Polygon API key (for market data)
    • Brave API key (for web search)
    • Pushover credentials (optional, for notifications)

Quick Start

Option 1: Using Docker (Recommended)

  1. Clone the repository:

    git clone <repository-url>
    cd trading-floor-agent
    
  2. Set up environment variables:

    cp env.template .env
    # Edit .env and add your API keys
    
  3. Build and run with Docker Compose:

    docker-compose up --build
    
  4. Access the application:

    • Open your browser to http://localhost:8501

Option 2: Local Development

  1. Install UV (if not already installed):

    pip install uv
    
  2. Install dependencies:

    make install
    # Or with dev dependencies:
    make dev-install
    
  3. Set up environment variables:

    cp env.template .env
    # Edit .env and add your API keys:
    # - OPENAI_API_KEY (required)
    # - POLYGON_API_KEY (for market data)
    # - BRAVE_API_KEY (for research)
    # - PUSHOVER_USER and PUSHOVER_TOKEN (optional)
    
  4. Run the Streamlit app:

    make run
    # Or directly:
    streamlit run src/trading_floor_agent/app.py
    
  5. Run trading floor in background:

    python -m trading_floor_agent.trading_floor
    

Environment Variables

Create a .env file in the root directory with the following variables:

Required

  • OPENAI_API_KEY: Your OpenAI API key for LLM access

Optional (but recommended)

  • POLYGON_API_KEY: Polygon API key for market data
  • POLYGON_PLAN: Polygon plan type (free, paid, or realtime)
  • BRAVE_API_KEY: Brave Search API key for web research
  • DEEPSEEK_API_KEY: DeepSeek API key (for multi-model support)
  • GOOGLE_API_KEY: Google API key for Gemini models
  • GROK_API_KEY: Grok API key
  • OPENROUTER_API_KEY: OpenRouter API key

Optional (Notifications)

  • PUSHOVER_USER: Pushover user key for push notifications
  • PUSHOVER_TOKEN: Pushover token for push notifications

Configuration

  • RUN_EVERY_N_MINUTES: Trading cycle interval (default: 60)
  • RUN_EVEN_WHEN_MARKET_IS_CLOSED: Run trading even when market is closed (default: false)
  • USE_MANY_MODELS: Use different models for each trader (default: false)
  • STREAMLIT_PORT: Port for Streamlit app (default: 8501)
  • DB_PATH: Database file path (default: accounts.db)
  • INITIAL_BALANCE: Starting balance for each trader (default: 10000.0)
  • SPREAD: Trading spread percentage (default: 0.002)

Project Structure

trading-floor-agent/
├── src/
│   └── trading_floor_agent/
│       ├── __init__.py
│       ├── app.py                  # Streamlit UI
│       ├── trading_floor.py        # Main trading floor logic
│       ├── traders.py              # Trader agent implementation
│       ├── models/
│       │   ├── __init__.py
│       │   └── account.py          # Account and Transaction models
│       ├── mcp_servers/
│       │   ├── __init__.py
│       │   ├── accounts_server.py  # Accounts MCP server
│       │   ├── market_server.py   # Market data MCP server
│       │   ├── push_server.py     # Push notifications MCP server
│       │   └── accounts_client.py # Accounts MCP client
│       └── utils/
│           ├── __init__.py
│           ├── database.py         # Database utilities
│           ├── market.py          # Market data utilities
│           ├── templates.py        # Agent instruction templates
│           ├── tracers.py         # Logging and tracing
│           ├── mcp_params.py       # MCP server configuration
│           └── strategies.py      # Trading strategies
├── tests/
│   ├── __init__.py
│   ├── conftest.py                # Pytest fixtures
│   ├── test_account.py            # Account model tests
│   ├── test_market.py             # Market data tests
│   ├── test_traders.py            # Trader tests
│   └── test_integration.py       # Integration tests
├── scripts/                       # Utility scripts
├── memory/                        # Memory database files
├── output/                        # Generated output files
├── data/                          # Data files
├── Dockerfile
├── docker-compose.yml
├── pyproject.toml
├── pytest.ini
├── Makefile
├── env.template
└── README.md

Usage

Using the Streamlit UI

  1. Start the application (see Quick Start)
  2. Open the web interface at http://localhost:8501
  3. View real-time portfolio data for all 4 traders
  4. Use the sidebar to:
    • Reset all traders
    • Start/stop automated trading
    • View configuration

Using the Command Line

# Run trading floor
python -m trading_floor_agent.trading_floor

# Reset all traders
python -c "from trading_floor_agent.utils.strategies import reset_traders; reset_traders()"

Development

Running Tests

# Run all tests
make test

# Run with coverage
make test-cov

# Run specific test file
pytest tests/test_account.py

# Run with markers
pytest -m unit
pytest -m integration

Code Quality

# Format code
make format

# Lint code
make lint

Docker Commands

# Build Docker image
make docker-build

# Start container
make docker-up

# Stop container
make docker-down

# View logs
make docker-logs

# Run tests in container
make docker-test

# Open shell in container
make docker-shell

Testing

The project includes comprehensive tests:

  • Unit Tests: Test individual components (accounts, market, traders)
  • Integration Tests: Test full workflows and MCP server interactions
  • Test Coverage: Aim for high coverage of core functionality

Run tests with:

pytest

Configuration

Trading Strategies

Edit src/trading_floor_agent/utils/strategies.py to customize trader strategies.

MCP Server Configuration

Edit src/trading_floor_agent/utils/mcp_params.py to configure MCP servers.

Agent Instructions

Edit src/trading_floor_agent/utils/templates.py to customize agent instructions.

Troubleshooting

Common Issues

  1. API Key Errors: Ensure all required API keys are set in .env
  2. MCP Server Errors: Check that Node.js and npm are installed
  3. Database Errors: Ensure the database directory is writable
  4. Memory Errors: Check that the memory directory is writable
  5. Docker Issues: Ensure Docker is running and ports are available
  6. Import Errors: Make sure dependencies are installed with make install

Debug Mode

Run with verbose logging:

# Set environment variable
export PYTHONUNBUFFERED=1

# Or in .env
PYTHONUNBUFFERED=1

Market Data Issues

If Polygon API is unavailable:

  • The system will fall back to random prices for testing
  • Ensure POLYGON_API_KEY is set correctly
  • Check Polygon API status and rate limits

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

[Add your license here]

Support

For issues, questions, or contributions:

  • Open an issue on GitHub
  • Check the documentation
  • Review the test files for usage examples

Acknowledgments

Built with:

Roadmap

  • [ ] Add more trading strategies
  • [ ] Support for options trading
  • [ ] Risk management features
  • [ ] Performance analytics
  • [ ] Backtesting capabilities
  • [ ] Multi-exchange support
  • [ ] Real-time alerts
  • [ ] Portfolio optimization