# hsliuping/tradingagents-cn architecture

> Architecture diagram of the GitHub repository hsliuping/tradingagents-cn, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-22). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/hsliuping/tradingagents-cn
- Repository: https://github.com/hsliuping/tradingagents-cn

## Overview

1. **Repository shape**
   - This is a Python monorepo centered on a stock-analysis platform.
   - The main production surfaces are:
     - `app/`: FastAPI backend and API layer.
     - `frontend/`: Vue 3 + Vite + Element Plus SPA.
     - `tradingagents/`: shared domain engine, agent framework, dataflows, LLM clients, and tools.
   - There are also auxiliary surfaces: `web/` (legacy/alternate Streamlit-style UI), `cli/`, `scripts/`, `examples/`, and `tests/`.

2. **Primary runtime boundary**
   - The backend API is the main orchestration boundary. It receives requests from the frontend, CLI, and some scripts.
   - The backend delegates business logic to service modules in `app/services/`, which in turn call the reusable core in `tradingagents/`.
   - Results flow back as API responses, streamed progress updates, notifications, or exported files.

3. **Backend structure**
   - `app/main.py` and `app/__main__.py` are the backend entry points.
   - `app/routers/` contains the API endpoints grouped by domain: analysis, stocks, screening, sync, config, database, scheduler, notifications, logs, queue, and system settings.
   - `app/middleware/` handles cross-cutting concerns such as error handling, request IDs, rate limiting, and operation logging.
   - `app/core/` holds configuration, startup validation, logging setup, Redis/Mongo helpers, and response utilities.

4. **Domain and service layer**
   - `app/services/` is the main business layer. It wraps workflows such as:
     - stock analysis and simple analysis
     - financial/historical/news/quote retrieval
     - screening and favorites
     - notifications, usage statistics, and operation logs
     - scheduler and queue management
     - config and auth services
   - These services are the main bridge between HTTP endpoints and the shared engine/data adapters.

5. **Shared analysis engine**
   - `tradingagents/` is the core engine reused across backend, CLI, web, and tests.
   - Key parts:
     - `agents/`: analyst, manager, researcher, risk, and trader roles.
     - `graph/`: analysis graph, conditional logic, propagation, reflection, and signal processing.
     - `tools/`: reusable analysis tools such as indicators and unified news tools.
     - `llm_clients/` and `llm_adapters/`: provider-agnostic model access, including OpenAI-compatible adapters.
     - `dataflows/`: unified data-access, caching, news, technical data, and provider abstractions.
   - This layer is where the multi-agent analysis workflow actually lives.

6. **Data-source architecture**
   - The project standardizes stock data access through adapters and managers rather than direct API calls from UI or routers.
   - Main provider families include:
     - China: AkShare, BaoStock, Tushare
     - US/HK: dedicated provider modules under `tradingagents/dataflows/providers/us` and `.../hk`
   - `app/services/data_sources/` and `tradingagents/dataflows/data_source_manager.py` coordinate source selection, fallback, and consistency checks.
   - The architecture supports provider priority, multi-source fallback, and data-quality validation.

7. **Persistence and caching**
   - The system uses **MongoDB** as the main durable store for configuration, analysis artifacts, stock data, logs, users, and related metadata.
   - **Redis** is used for transient and coordination concerns: rate limiting, queue/progress state, session-like state, and realtime tracking.
   - There is also file-based persistence for reports and cached data:
     - `data/analysis_results/`
     - `data/reports/`
     - `tradingagents/dataflows/cache/`
   - This creates a three-tier storage pattern: in-memory/Redis for live state, MongoDB for application data, and files for report artifacts.

8. **Analysis workflow**
   - Typical flow: request enters backend → service resolves config/model/data sources → shared agent graph runs analysis → intermediate progress is tracked → reports/results are persisted → frontend retrieves results.
   - Analysis work is often asynchronous and distributed through:
     - `app/services/queue_service.py`
     - `app/services/scheduler_service.py`
     - `app/worker/`
     - `app/services/progress/` and Redis-backed progress trackers
   - This allows long-running analysis and sync jobs to continue without blocking the HTTP request thread.

9. **Realtime updates and operational side channels**
   - Realtime user feedback is handled through SSE/WebSocket-oriented components:
     - `app/routers/sse.py`
     - `app/routers/websocket_notifications.py`
     - `app/services/websocket_manager.py`
     - notification and internal message services
   - Operation logs, request IDs, and progress tracking are part of the same observability path, so the UI can show task state, history, and errors live.

10. **Frontend SPA**
    - `frontend/` is the primary user-facing client.
    - It is organized around:
      - `src/api/`: typed API clients for each backend domain
      - `src/views/`: pages for dashboard, analysis, reports, screening, stocks, settings, queue, tasks, and system management
      - `src/components/`: reusable UI widgets for config, sync, model selection, notifications, and dialogs
      - `src/stores/`: app/auth/notification state
    - The frontend is a pure consumer of backend APIs and does not own business logic.

11. **Legacy/alternate UI path**
    - `web/` appears to be an older or alternate Streamlit-style interface.
    - It contains UI components, session/auth helpers, progress tracking, report export, and some data persistence utilities.
    - For architecture diagrams, treat it as a secondary interface layered over the same backend/data model, not the primary application shell.

12. **Command-line and automation**
    - `cli/` provides command-line entry points for initialization and provider setup.
    - `scripts/` contains operational tooling for:
      - database setup and migrations
      - syncing provider data
      - debugging and diagnostics
      - Docker/portable deployment
      - user and config maintenance
    - These scripts are not just helpers; they are part of the repo’s operational architecture and data migration story.

13. **External dependencies that shape the architecture**
    - The app integrates with multiple LLM providers through adapter/client layers, including OpenAI-compatible endpoints and Chinese providers such as DeepSeek, DashScope, Google AI, Qianfan, and aggregators like AiHubMix.
    - Stock/news data comes from external market-data providers and news sources.
    - The backend is built around Python 3.10+, FastAPI/Uvicorn, MongoDB, Redis, and Docker; the frontend uses Vue 3 + Vite + Element Plus.
    - Docker Compose, Nginx, and GitHub Actions define deployment and publication boundaries.

14. **What to draw in an architecture diagram**
    - Show `frontend` and `web` as client layers.
    - Show `app` as the API/orchestration layer with middleware, routers, services, and workers.
    - Show `tradingagents` as the shared analysis engine beneath the backend.
    - Show MongoDB and Redis as the main state systems, with file storage for reports/caches.
    - Show external LLM providers and market-data providers as separate integrations behind adapter layers.

Main entry points: [`app/services`](https://github.com/hsliuping/tradingagents-cn/tree/main/app/services) (Services), [`tradingagents`](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents) (Trading Core), [`app/main.py`](https://github.com/hsliuping/tradingagents-cn/blob/main/app/main.py) (API Entry), [`tradingagents/dataflows`](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/dataflows) (Dataflows)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_clients["Clients"]
  node_frontend["Frontend<br/>vue spa"]
  node_web["Web UI<br/>legacy ui"]
end

subgraph group_backend["Backend"]
  node_app_entry["API Entry<br/>[main.py]"]
  node_app_mid["Core Layer<br/>config/middleware"]
  node_app_routes["Routers<br/>api domains"]
  node_app_services["Services<br/>business layer"]
  node_app_worker["Worker<br/>async jobs"]
  node_app_progress["Progress<br/>realtime state"]
  node_app_queue["Queue<br/>job coordination<br/>[queue_service.py]"]
end

subgraph group_engine["Engine"]
  node_tr_core["Trading Core<br/>analysis engine"]
  node_tr_agents["Agents<br/>roles"]
  node_tr_graph["Graph"]
  node_tr_dataflows["Dataflows<br/>data layer"]
  node_tr_llm["LLM Layer<br/>model adapters"]
  node_tr_tools["Tools"]
end

subgraph group_storage["State"]
  node_mongo[("MongoDB<br/>durable store")]
  node_redis[("Redis<br/>transient state")]
  node_files["Files<br/>artifacts"]
end

subgraph group_integrations["Integrations"]
  node_llm_providers(("LLM APIs<br/>external providers"))
  node_market_providers(("Market Data<br/>external providers"))
end

subgraph group_ops["Ops"]
  node_cli["CLI<br/>command line"]
  node_scripts["Scripts<br/>automation"]
end

node_frontend -->|"API calls"| node_app_entry
node_web -->|"backend calls"| node_app_entry
node_cli -->|"orchestrates"| node_app_entry
node_scripts -->|"operates"| node_app_entry
node_app_entry -->|"startup"| node_app_mid
node_app_entry -->|"mounts"| node_app_routes
node_app_routes -->|"delegates"| node_app_services
node_app_mid -->|"uses"| node_redis
node_app_mid -->|"uses"| node_mongo
node_app_services -->|"calls"| node_tr_core
node_app_services -->|"persists"| node_mongo
node_app_services -->|"tracks"| node_redis
node_app_services -->|"exports"| node_files
node_app_services -->|"updates"| node_app_progress
node_app_services -->|"enqueues"| node_app_queue
node_app_queue -->|"runs"| node_app_worker
node_app_worker -->|"executes"| node_tr_core
node_tr_core -->|"coordinates"| node_tr_agents
node_tr_core -->|"drives"| node_tr_graph
node_tr_core -->|"reads"| node_tr_dataflows
node_tr_core -->|"queries"| node_tr_llm
node_tr_core -->|"uses"| node_tr_tools
node_tr_llm -->|"adapts"| node_llm_providers
node_tr_dataflows -->|"adapts"| node_market_providers
node_tr_dataflows -->|"caches"| node_mongo
node_tr_dataflows -->|"caches"| node_redis
node_tr_dataflows -->|"stores"| node_files

click node_frontend "https://github.com/hsliuping/tradingagents-cn/tree/main/frontend"
click node_web "https://github.com/hsliuping/tradingagents-cn/tree/main/web"
click node_app_entry "https://github.com/hsliuping/tradingagents-cn/blob/main/app/main.py"
click node_app_mid "https://github.com/hsliuping/tradingagents-cn/tree/main/app/core"
click node_app_routes "https://github.com/hsliuping/tradingagents-cn/tree/main/app/routers"
click node_app_services "https://github.com/hsliuping/tradingagents-cn/tree/main/app/services"
click node_app_worker "https://github.com/hsliuping/tradingagents-cn/tree/main/app/worker"
click node_app_progress "https://github.com/hsliuping/tradingagents-cn/tree/main/app/services/progress"
click node_app_queue "https://github.com/hsliuping/tradingagents-cn/blob/main/app/services/queue_service.py"
click node_tr_core "https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents"
click node_tr_agents "https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/agents"
click node_tr_graph "https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/graph"
click node_tr_dataflows "https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/dataflows"
click node_tr_llm "https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/llm_clients"
click node_tr_tools "https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/tools"
click node_files "https://github.com/hsliuping/tradingagents-cn/tree/main/data"
click node_cli "https://github.com/hsliuping/tradingagents-cn/tree/main/cli"
click node_scripts "https://github.com/hsliuping/tradingagents-cn/tree/main/scripts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_frontend,node_web toneBlue
class node_app_entry,node_app_mid,node_app_routes,node_app_services,node_app_worker,node_app_progress,node_app_queue toneAmber
class node_tr_core,node_tr_agents,node_tr_graph,node_tr_dataflows,node_tr_llm,node_tr_tools toneMint
class node_mongo,node_redis,node_files toneRose
class node_llm_providers,node_market_providers toneIndigo
class node_cli,node_scripts toneTeal
```

## Components

### Clients

Primary and secondary user interfaces

- [Frontend](https://github.com/hsliuping/tradingagents-cn/tree/main/frontend): vue spa · Primary Vue 3 + Vite client for analysis, reports, screening, settings, and system views · `frontend`
- [Web UI](https://github.com/hsliuping/tradingagents-cn/tree/main/web): legacy ui · Secondary Streamlit-style interface layered over the same backend and data model · `web`

### Backend

FastAPI API and orchestration layer

- [API Entry](https://github.com/hsliuping/tradingagents-cn/blob/main/app/main.py): fastapi entry · Backend application entry points and startup wiring · `app/main.py`
- [Core Layer](https://github.com/hsliuping/tradingagents-cn/tree/main/app/core): config/middleware · Configuration, startup validation, logging, Redis/Mongo helpers, response utilities, and cross-cutting middleware · `app/core`
- [Routers](https://github.com/hsliuping/tradingagents-cn/tree/main/app/routers): api domains · HTTP API surface grouped by analysis, stocks, screening, sync, config, database, scheduler, notifications, logs, queue, and system · `app/routers`
- [Services](https://github.com/hsliuping/tradingagents-cn/tree/main/app/services): business layer · Business workflows bridging routers to the shared engine and persistence · `app/services`
- [Worker](https://github.com/hsliuping/tradingagents-cn/tree/main/app/worker): async jobs · Background execution for analysis and data sync jobs · `app/worker`
- [Progress](https://github.com/hsliuping/tradingagents-cn/tree/main/app/services/progress): realtime state · Redis-backed progress tracking and streamed status updates · `app/services/progress`
- [Queue](https://github.com/hsliuping/tradingagents-cn/blob/main/app/services/queue_service.py): job coordination · Queue and scheduler coordination for long-running tasks · `app/services/queue_service.py`

### Engine

Shared analysis and data core

- [Trading Core](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents): analysis engine · Shared multi-agent analysis engine reused by backend, CLI, web, examples, and tests · `tradingagents`
- [Agents](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/agents): roles · Analyst, manager, researcher, risk, and trader roles · `tradingagents/agents`
- [Graph](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/graph): workflow graph · Analysis graph, conditional logic, propagation, reflection, and signal processing · `tradingagents/graph`
- [Dataflows](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/dataflows): data layer · Unified data access, caching, providers, news, and technical data · `tradingagents/dataflows`
- [LLM Layer](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/llm_clients): model adapters · Provider-agnostic model clients and openai-compatible adapters · `tradingagents/llm_clients`
- [Tools](https://github.com/hsliuping/tradingagents-cn/tree/main/tradingagents/tools): analysis tools · Reusable indicators, news tools, and tool logging · `tradingagents/tools`

### State

Persistent, transient, and file-backed state

- **MongoDB**: durable store · Main application store for config, artifacts, stock data, logs, users, and metadata
- **Redis**: transient state · Rate limiting, queue/progress state, session-like state, and realtime tracking
- [Files](https://github.com/hsliuping/tradingagents-cn/tree/main/data): artifacts · Report exports, cached data, and analysis result files · `data`

### Integrations

External provider families

- **LLM APIs**: external providers · OpenAI-compatible and regional model providers consumed through adapters
- **Market Data**: external providers · AkShare, BaoStock, Tushare, US/HK data providers, and news sources

### Ops

Command-line, scripts, and deployment tooling

- [CLI](https://github.com/hsliuping/tradingagents-cn/tree/main/cli): command line · Command-line entry points for initialization and provider setup · `cli`
- [Scripts](https://github.com/hsliuping/tradingagents-cn/tree/main/scripts): automation · Operational tooling for setup, migration, sync, diagnostics, deployment, and maintenance · `scripts`

## Connections

- Frontend → API Entry: API calls · SPA consumes backend endpoints for all user workflows
- Web UI → API Entry: backend calls · Legacy UI also relies on the same API and data model
- CLI → API Entry: orchestrates · CLI actions initialize or drive backend-managed workflows
- Scripts → API Entry: operates · Scripts bootstrap, migrate, sync, and diagnose the platform
- API Entry → Core Layer: startup · App entry wires config, logging, validation, and middleware
- API Entry → Routers: mounts · Backend exposes domain routers
- Routers → Services: delegates · Routers hand off business logic to services
- Core Layer → Redis: uses · Rate limiting, request IDs, and runtime coordination
- Core Layer → MongoDB: uses · Configuration and startup helpers validate durable state
- Services → Trading Core: calls · Services invoke shared analysis and data-engine capabilities
- Services → MongoDB: persists · Services store config, logs, results, and metadata
- Services → Redis: tracks · Services coordinate progress, queue state, and transient runtime data
- Services → Files: exports · Services write reports and cached artifacts to disk
- Services → Progress: updates · Long-running jobs publish live progress
- Services → Queue: enqueues · Async work is dispatched through queue and scheduler coordination
- Queue → Worker: runs · Queued jobs are executed by background workers
- Worker → Trading Core: executes · Workers run analysis and data sync workflows from the shared engine
- Trading Core → Agents: coordinates · Agent roles perform the analysis workflow
- Trading Core → Graph: drives · Graph logic controls the multi-agent execution path
- Trading Core → Dataflows: reads · Engine pulls market, news, cache, and technical data through dataflows
- Trading Core → LLM Layer: queries · Engine uses model clients and adapters for reasoning and tool use
- Trading Core → Tools: uses · Engine invokes indicators and unified analysis tools
- LLM Layer → LLM APIs: adapts · Model clients abstract multiple provider families
- Dataflows → Market Data: adapts · Dataflows standardize access to provider-specific market and news sources
- Dataflows → MongoDB: caches · Dataflows use Mongo-backed persistence and cache adapters
- Dataflows → Redis: caches · Dataflows also use Redis for transient caching and coordination
- Dataflows → Files: stores · File caches and report artifacts are part of the data layer
