Content
# 🤖 Autonomous Trader
> An AI-powered trading simulation built with Python, the OpenAI Agents SDK, and MCP (Model Context Protocol). Four AI trader agents — each with a unique investment persona — autonomously research markets, make decisions, and execute simulated trades.
⚠️ **For educational purposes only. Not financial advice. Do not use for real trading.**
---
## 📋 Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Architecture](#architecture)
- [Technologies](#technologies)
- [How It Works](#how-it-works)
- [Setup](#setup)
- [Usage](#usage)
- [Project Structure](#project-structure)
- [Interview Explanation](#interview-explanation)
---
## Overview
Autonomous Trader demonstrates how to build a **multi-agent AI system** where:
- Multiple AI agents run concurrently, each with a different persona and investment strategy
- Agents use **MCP (Model Context Protocol)** to interact with external tools (accounts, market data, notifications)
- A **sub-agent (Researcher)** is used as a tool by the main **Trader agent** — the "agent-as-tool" pattern
- Agent activity is **traced and logged** in real time, visible in a Streamlit dashboard
The four traders are:
| Trader | Inspired By | Strategy |
|--------|-------------|----------|
| Warren | Warren Buffett | Value investing, long-term holds |
| George | George Soros | Aggressive macro trading |
| Ray | Ray Dalio | Systematic risk parity |
| Cathie | Cathie Wood | Innovation + crypto ETFs |
---
## Features
- ✅ **Multi-agent architecture** — Trader agent + Researcher sub-agent
- ✅ **MCP integration** — Custom MCP servers for accounts, market data, notifications
- ✅ **Persistent memory** — Each Researcher builds a knowledge graph across sessions
- ✅ **Multi-model support** — Run different traders on GPT, DeepSeek, Gemini, or Grok
- ✅ **Real-time dashboard** — Streamlit UI with live portfolio charts and activity logs
- ✅ **Push notifications** — Agents send summaries to your phone via Pushover
- ✅ **Agent tracing** — Full audit trail of every tool call and decision
- ✅ **Market data** — Real prices via Polygon.io (free and paid tiers)
- ✅ **Alternating modes** — Trade → Rebalance → Trade (agents evolve over time)
---
## Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ User Interface │
│ Streamlit Dashboard (app.py) │
│ Portfolio charts · Holdings · Logs · Transactions │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ Scheduler (main.py) │
│ Runs all 4 traders concurrently every N minutes │
└──────────────────────────┬──────────────────────────────────┘
│
┌─────────────────┼──────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Warren │ │ George │ │ Cathie │ ...
│ (Agent) │ │ (Agent) │ │ (Agent) │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
└────────────────┼─────────────────┘
│
┌───────────────┴────────────────┐
│ │
▼ ▼
┌─────────────────┐ ┌──────────────────────┐
│ Researcher │ │ Trader MCP Servers │
│ Sub-Agent │ │ │
│ (as a Tool) │ │ accounts_server.py │
│ │ │ → buy/sell/balance │
│ MCP Servers: │ │ │
│ • mcp-fetch │ │ market_server.py │
│ • brave-search │ │ → stock prices │
│ • memory │ │ │
└─────────────────┘ │ notification_server │
│ → push alerts │
└──────────────────────┘
│
┌──────────▼──────────┐
│ Services Layer │
│ portfolio_service │
│ market_service │
│ database (SQLite) │
└─────────────────────┘
```
---
## Technologies
| Technology | Role |
|------------|------|
| **Python 3.12** | Core language |
| **OpenAI Agents SDK** | Multi-agent framework (agents, tools, tracing) |
| **MCP (Model Context Protocol)** | Standard protocol for agent tools |
| **FastMCP** | Simplified MCP server creation |
| **Streamlit** | Real-time web dashboard |
| **Plotly** | Interactive portfolio charts |
| **Pydantic v2** | Data validation and serialization |
| **SQLite** | Persistent storage (accounts, logs, market cache) |
| **Polygon.io API** | Real stock market data |
| **Brave Search API** | Web search for the Researcher agent |
| **Pushover API** | Push notifications to mobile |
| **OpenAI GPT-4o-mini** | Default LLM for agents |
| **DeepSeek / Gemini / Grok** | Optional alternative LLMs |
---
## How It Works
### 1. MCP Servers (the "tools")
MCP (Model Context Protocol) servers are **separate processes** that expose tools to AI agents via a standard protocol. Instead of hardcoding API calls inside the agent, tools are exposed as MCP tools that any agent can discover and call.
**Our custom MCP servers:**
```python
# accounts_server.py — exposes trading operations as tools
@mcp.tool()
async def buy_shares(name: str, symbol: str, quantity: int, rationale: str) -> str:
"""Execute a buy order for a given stock."""
return Account.get(name).buy_shares(symbol, quantity, rationale)
```
The agent doesn't call `buy_shares()` directly — it sends a JSON message to the MCP server, which calls the function and returns the result.
### 2. Agent-as-Tool Pattern
The Researcher agent is not called directly by the user — it's wrapped as a **tool** that the Trader can invoke:
```python
# researcher_agent.py
researcher = Agent(name="Researcher", instructions=..., mcp_servers=research_servers)
# Convert to a tool the Trader can call
researcher_tool = researcher.as_tool(
tool_name="Researcher",
tool_description="Search the web for financial news and opportunities."
)
# trader_agent.py — Researcher is just another tool
trader = Agent(
name="Warren",
tools=[researcher_tool], # Researcher appears as a tool
mcp_servers=trader_mcp_servers, # Direct access to trading tools
)
```
This is the **agent-as-tool** pattern: when the Trader needs market intelligence, it calls the Researcher tool, which spins up a full agent session with web search capabilities, and returns a comprehensive research summary.
### 3. Trader Workflow
Each time a trader runs:
```
1. Read account state (balance, holdings, P&L) via MCP resource
2. Read investment strategy from database
3. Call Researcher tool → get market news and opportunities
4. Use market data tools → check relevant stock prices
5. Make decision → execute trades via buy_shares / sell_shares tools
6. Send push notification with trade summary
7. Toggle mode (trade → rebalance next time)
```
### 4. Persistent Memory
The Researcher agent uses a knowledge graph (LibSQL/SQLite-backed) to remember:
- Companies it has researched before
- Useful website URLs for financial data
- Market conditions and insights from previous sessions
This means the Researcher gets smarter over time — building expertise across sessions.
### 5. Tracing
Every agent action is traced using OpenAI's tracing system and written to SQLite via a custom `LogTracer`. The Streamlit dashboard polls this table to show a live activity feed.
```python
# ai_agents/tracer.py
class LogTracer(TracingProcessor):
def on_span_start(self, span):
# Write to SQLite → visible in Streamlit dashboard
write_log(trader_name, span.type, f"Started: {span.name}")
```
---
## Setup
### Prerequisites
- Python 3.12+
- Node.js 18+ (for MCP servers that use `npx`)
- `uv` package manager (`pip install uv`)
### 1. Clone the repository
```bash
git clone https://github.com/yourusername/autonomous-trader.git
cd autonomous-trader
```
### 2. Install dependencies
```bash
pip install -r requirements.txt
```
### 3. Configure environment
```bash
cp .env.example .env
```
Edit `.env` and add your API keys:
```env
OPENAI_API_KEY=sk-your-key-here
POLYGON_API_KEY=your-polygon-key
POLYGON_PLAN=free
# Optional but recommended
BRAVE_API_KEY=your-brave-key
PUSHOVER_USER=your-pushover-user
PUSHOVER_TOKEN=your-pushover-token
```
### 4. Initialize trader accounts
```bash
python scripts/reset_accounts.py
```
### 5. Run the dashboard
```bash
streamlit run app.py
```
### 6. Start the trading simulation
In a separate terminal:
```bash
python main.py
```
Traders will run every 60 minutes by default. To test immediately:
```bash
RUN_EVEN_WHEN_MARKET_CLOSED=true RUN_EVERY_N_MINUTES=1 python main.py
```
### 7. Run tests
```bash
pytest tests/ -v
```
---
## Usage
### Dashboard
Open `http://localhost:8501` after running `streamlit run app.py`.
The dashboard shows:
- Portfolio value chart for each trader
- Current holdings (symbols + quantities)
- Recent transactions with agent rationale
- Live activity log (updates every 30 seconds)
### Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `RUN_EVERY_N_MINUTES` | `60` | How often traders run |
| `RUN_EVEN_WHEN_MARKET_CLOSED` | `false` | Run outside trading hours |
| `USE_MANY_MODELS` | `false` | Use different LLMs per trader |
| `POLYGON_PLAN` | `free` | `free` / `paid` / `realtime` |
---
## Project Structure
```
autonomous-trader/
│
├── app.py # Streamlit dashboard
├── main.py # Application runner / scheduler
├── requirements.txt
├── .env.example
│
├── ai_agents/ # AI agent definitions
│ ├── trader_agent.py # Main Trader agent (decision-making)
│ ├── researcher_agent.py # Researcher sub-agent (web research)
│ ├── prompts.py # All system prompts and user messages
│ └── tracer.py # Custom tracing → SQLite logging
│
├── mcp_servers/ # MCP server implementations
│ ├── accounts_server.py # Buy/sell/balance tools + account resources
│ ├── market_server.py # Stock price lookup tool
│ └── notification_server.py # Push notification tool
│
├── mcp_client/ # MCP client utilities
│ └── client.py # Read MCP resources (account, strategy)
│
├── services/ # Business logic layer
│ ├── portfolio_service.py # Account model, trading operations
│ ├── market_service.py # Polygon API + price caching
│ └── database.py # SQLite read/write operations
│
├── config/
│ └── mcp_config.py # MCP server connection parameters
│
├── scripts/
│ └── reset_accounts.py # Initialize trader accounts
│
├── tests/
│ └── test_portfolio.py # Unit tests for portfolio logic
│
└── memory/ # Auto-created: agent knowledge graphs
├── warren.db
├── george.db
├── ray.db
└── cathie.db
```
---
## Interview Explanation
### "Tell me about a project you've built"
> I built an AI-powered trading simulation called Autonomous Trader. It has four AI agents, each with a different investment persona — one is value-oriented like Buffett, another is aggressive macro like Soros. Each agent autonomously researches market news, makes trading decisions, and executes simulated trades against a $10,000 starting portfolio.
### Key Technical Talking Points
**Why MCP (Model Context Protocol)?**
> MCP is like a plugin system for AI agents. Instead of hardcoding tool calls inside the agent, I exposed the trading operations (buy/sell/check balance) as MCP tools running in separate processes. This follows the MCP standard, which means any MCP-compatible agent or framework can use these tools without changing the server code. It's also more secure — the agent can't directly access the database; it has to go through the MCP server.
**Why multi-agent architecture?**
> The Trader agent is great at reasoning and decision-making, but web research is a different task. I created a specialized Researcher agent that's tuned for information gathering — it has web search and memory tools. The Trader calls the Researcher as a tool (the "agent-as-tool" pattern from OpenAI Agents SDK). This separation of concerns makes each agent easier to test, debug, and improve independently.
**Why persistent memory?**
> Between runs, agents forget everything. I added a knowledge graph (using LibSQL, which is SQLite-compatible) for the Researcher. It stores what it has learned about companies, useful URLs, and market conditions. Over time, the Researcher builds expertise — like a junior analyst who remembers previous research.
**Why tracing?**
> In production AI systems, you need to audit what the agent did and why, especially for financial decisions. OpenAI's tracing captures every tool call, LLM response, and decision. I extended this with a custom LogTracer that writes events to SQLite, which feeds the live activity log in the Streamlit dashboard.
**What would you improve?**
> For a real system, I'd add: (1) paper trading via a real brokerage API like Alpaca, (2) risk management rules (position limits, stop losses), (3) better backtesting before going live, and (4) PostgreSQL instead of SQLite for concurrent access at scale.
---
## License
MIT — feel free to use this for learning and portfolio purposes.
---
*Built as a learning project to explore multi-agent AI systems, MCP tooling, and autonomous decision-making.*
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available