How hsliuping/tradingagents-cn works
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: services Services · tradingagents Trading Core · main.py API Entry · dataflows Dataflows
Components 22
Clients
Primary and secondary user interfaces
Backend
FastAPI API and orchestration layer
- API Entry · Backend application entry points and startup wiring
app/main.py - Core Layer · Configuration, startup validation, logging, Redis/Mongo helpers, response utilities, and cross-cutting middleware
app/core - Routers · HTTP API surface grouped by analysis, stocks, screening, sync, config, database, scheduler, notifications, logs, queue, and system
app/routers - Services · Business workflows bridging routers to the shared engine and persistence
app/services - Worker · Background execution for analysis and data sync jobs
app/worker - Progress · Redis-backed progress tracking and streamed status updates
app/services/progress - Queue · Queue and scheduler coordination for long-running tasks
app/services/queue_service.py
Engine
Shared analysis and data core
- Trading Core · Shared multi-agent analysis engine reused by backend, CLI, web, examples, and tests
tradingagents - Agents · Analyst, manager, researcher, risk, and trader roles
tradingagents/agents - Graph · Analysis graph, conditional logic, propagation, reflection, and signal processing
tradingagents/graph - Dataflows · Unified data access, caching, providers, news, and technical data
tradingagents/dataflows - LLM Layer · Provider-agnostic model clients and openai-compatible adapters
tradingagents/llm_clients - Tools · Reusable indicators, news tools, and tool logging
tradingagents/tools
State
Persistent, transient, and file-backed state
- MongoDB · Main application store for config, artifacts, stock data, logs, users, and metadata
- Redis · Rate limiting, queue/progress state, session-like state, and realtime tracking
- Files · Report exports, cached data, and analysis result files
data
Integrations
External provider families
- LLM APIs · OpenAI-compatible and regional model providers consumed through adapters
- Market Data · AkShare, BaoStock, Tushare, US/HK data providers, and news sources
Connections 27
- 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