Content
TradingAgents 🤖📈
> **A Stock Trading Multi-Agent Decision System** — 28-Node Conditional Routing Workflow based on LangGraph with MCP Protocol and Hierarchical Model Routing
[](https://)
[](https://langchain-ai.github.io/langgraphMCP](https://img.shields.io/badge/MCP-Protocol://modelcontextprotocol.io)
[](LICENSE)
---
## Table
- [Overall Architecture](#整体架构)
- [Workflow工作流详解)
- [Core Features](#核心特性)
- Start](#快速开始)
- [Model Routing](#模型路由 [MCP Integration](#mcp-集成)
- [Back](#回测表现)
- [Project Structure](#项目结构 [Interview Guide](#面试指南)
---
## Overall Architecture
```
│
▼
┌────────────────────────────────────────────────────│ 28-Node StateGraph │
│ initialize → build_initial_plan │ │
▼ │
│ ┌─────────────────┐ ┌──────────────────┐ │
│ │ memory_context │ market_data │ │
│ │ portfolio_context│ (Parallel Context Collection) │ │
│ └────────┬────────┘ └────────┬─────────┘│ ▼ ▼ │
│ context_gate (Conditional │
│ │ │
│ ▼ (Pass, Fail → Terminate) │
│ refine_plan│ │ │
│ ▼ │
│ ┌──────────────────────────────────────┐ │
│ │ technical fundamental policy sent │ ← Four Parallel │
│ └──────────────────┬───────────────────┘ │
│ ▼ │
analysis_join → analysis_quality_gate │
│ │ ├─ Pass → bull/bear debate │
│ └─ Insufficient → supplemental_retrieval (Loop Retrieval) │
│ ┌──────────────────┐ │
│ │ Conditional Debate Loop (≤3 Rounds) │ ← bull ↔ bear ↔ judge │
│ └────────┬─────────┘ │
│ ▼ │
│ risk_analyst → trader → decision_validator │
│ │ │
│ ├─ High Risk → human_review (Human Approval) │
│─ Low Risk → final_report │
│ │
│ → memory_quality_gate → save_memory │
└─────────────────────────────────────────────────────┘
```
---
## Workflow Details
### 28
| Stage | Node | Description |
|:---|:---|:---|
| **Initialization** | `initialize` | Assign run_id, reset state, trim pipeline |
| **Planning** | `build` → `refine_plan` | Two-stage planning:, then refine based on data quality |
| **Context Collection `memory` / `portfolio` / `market_data` parallel nodes collect historical memory, account, and market data |
Gate Control** | `context_gate` | Check if market empty, terminate if empty |
| **Professional Analysis** | `technical` / `fundamental` / `policy_news` /iment` | Four types of analysts execute in parallel |
Quality Gate Control** | `analysis_quality_gate` | Ins → supplemental retrieval (up to 2 rounds) |
|ate** | `bull` → `judge` →buttal` / `bear_rebuttal` →ge` | Conditional debate loop (up to 3 rounds **Risk Control** | `risk_analyst` risk assessment |
| **Decision** | `trader `decision_validator` | Generate trading suggestions and validate |
| **Human Approval** | `human_review` | High-risk decisions interrupt for approval |
| **Report** | `final_report` research report |
| **Reflection** | `reflection`memory_quality_gate` → `save_memory` | Quality gate valuable memories |
### Conditional Routing (6 places)
# routing.py core logic
route_context_gate() missing → terminate; normal → refine_plan
route_analysis_nodes # Select analysis nodes based on plan
route_quality_gate() # Insufficient evidence → supplemental retrieval; sufficient → debate
plemental_retrieval()# Retrieval round check → continue or enter debate
route_debate() # Confidence divergence → next or risk control
route_decision_validator() # → human approval; normal → report
```
---
## Core### 🧠 Conditional Debate Loop
Multi-party debate based, fundamental, policy, and sentiment analysis reports. The judge decides whether to continue the debate based on confidence divergence, with a maximum of 3 rounds.
```
Round 1: Bull argument (confidence 0.7) vs Bear argument (confidence 0.6) → large divergence → continue
Round 2: Bull rebuttal (confidence 65) vs Bear rebuttal (confidence 55) → reduced divergence → risk control
```
fixed-round strategies, **reduces approximately 60% of LLM call overhead**.
### 🔍 Evidence Coverage Gate Control
Automat supplemental retrieval (up to 2 rounds) when is insufficient. If still insufficient, mark as `degraded corresponding agent confidence.
### 👤 Human-in-the
High-risk trading decisions (e.g., buying with high) interrupt and wait for human approval. Agents only provide suggestions.
### 🔄 Two-StageFirst, select required modules based on request parameters. Then, refine the plan actual data quality returned by tools. For example, if market fails, automatically disable technical analysis nodes.
---
## Quick### Environment Requirements
- Python 3.11+
- DeepSeek API Key (or other OpenAI compatible API)
###```bash
# Clone repository
git clone https://github.com/yourname/TradingAgents
cd TradingAgents
#
pip install -r requirements.txt
# Configure API Key
echo "DEEPSEEK_API_KEY=sk-your-key"env
```
### Run
```bash
# service
python scripts/serve.py
# Send analysis request
curl -X POST http://localhost:8000/api/v-analysis \
-H "Content-Type: application/json -d '{"symbol": "515880.SH", "company": "Communication ETF"}'
```
---
## Model Routing
a hierarchical model routing strategy, allocating different LLMs task complexity:
| Layer | Model | Agent | Description |
|:---:|:---|:---|:---|
| 🟢 ** deepseek-v4-flash | Technical/fund/sentiment analysts + bull/bear researchers | Data tool calls, simple analysis |
| 🔵 **Pro**seek-v4-pro | Trading decision/risk assessment/ref | Comprehensive reasoning, multi-source information fusion |
Simple tasks-cost models, while complex decisions use high-reasoning, optimizing token consumption while ensuring decision quality.
---
##
The system integrates with the [Model Context Protocol](httpscontextprotocol.io) standard protocol for financial data:
### Consumer Side (MCP Client)
```python
from backend.app.agents.mcp_client import tushare_mcp
# Get ETF market data
data = tushare_mcp.get_fund_daily("515880.SH")
# Get northbound capital
hsgt = tushare.get_moneyflow()
# capital flow
flow = tushare_mcp.get_moneyflow_ind_dc("BK0988")
```
Supports **258 data tools**, covering stock market data, ETFs, financial data, macroeconomic data, etc.
### Provider SideCP Server)
The system also runs as an MCP Server, exposing multi-agent analysis capabilities:
```json
// .mcp.json — supports Cursor, Claude Desktop, etc.
{
cpServers": {
"tushare": {": "https://api.tushare.pro/mcp/" },
"trading-agents": { "commandpython backend/app/agents/mcp_server.py" }
}
```
---
## Backtest Performance
### Backtest Results for Three ETFs (2025/01 — 2026)
| ETF | Total Return | Maximum Drawdown |rawdown Ratio |
|:---|:---:|:---:|:| Communication ETF (515880) | **+9%** | -29.0% | 9.99 |
| Semiconductor ETF (512480) | **+201.8%** | -19.9% |13 |
| Chip ETF (159995) |181.9%** | -21.7%.38 |
### Drawdown Pattern Analysis
Common features of >10% drawdowns based on historical data mining:
the crash:** RSI>75 overbought + >20% + high volume + RSI surges
**Bottom signal:** RSI<35 + selling + large positive line (>3%) rebound (83% probability)
---
## Project Structure
```
TradingAgents/
├── └── app/
│ ├── agents/ core
│ │ ├── graph/ # definition
│ │ ├── subgraphs/ Subgraphs (debate, policy news)
│ ├── builder.py # 28-node graph builder
│ │ ├── routing.py # 6 conditional
│ │ ├── nodes.py # Node│ │ ├── workflow.py # Workflow engine
│ │ ├── llm.py # LLM client
│ │ ├── config.py # Model configuration management
│ │ ├── tools.py # Toolset
│ │ ├── mcp_client.py # MCP client
│ │ └── mcp_server.py server
│ api/ #
│ ├── schemas/ # Pydantic data models
│ ├── services/ # Business services
│ # Tests
├── config/
│ .yaml # Model routing configuration
├── scripts/ scripts
├── data/ # Data storage
└mcp.json # MCP Server configuration
```
Guide
When an interview, highlight the following key points:
| Interview Question | Your Response Direction |
:---|
| **Why use LangGraph?** | conditional routing (evidence gate control, debate loop), linear achieve this |
| **How do multiple agents collaborate | Four types of analysts work in parallel → debate → risk control → decision, structured Pydantic messages |
| **How is reliability ensured?** | Evidence grounding + confidence gate degradation + HITL |
| **What is MCP | Standardized protocol for agent tool calls, similar to USB-C interface |
| **Model selection strategy?** | Hierarchical routing based on task complexity, simple tasks use Flash, complex tasks use Pro |
---
## License
MIT
*Project for Agent Development Internship Preparation · Chengdu University of Information Technology*