This publication presents NexTrade, a sophisticated multi-agent system designed to automate and optimize stock market trading operations through intelligent agent coordination. Built using LangGraph and LangChain frameworks, the system orchestrates three specialized agents—Research, Portfolio, and Database—under the supervision of a central coordinator to deliver end-to-end trading workflows. The system incorporates human-in-the-loop (HITL) mechanisms for safety, real-time market data integration, and persistent data management through SQLite database storage. NexTrade demonstrates how multi-agent architectures can enhance financial decision-making by combining automated research, intelligent portfolio management, and secure trade execution with comprehensive audit trails. The implementation showcases best practices in agentic AI development including proper agent coordination, tool integration, error handling, and safety mechanisms essential for financial applications.
Modern financial markets present complex challenges for individual and institutional traders:
NexTrade addresses these challenges through a multi-agent architecture that distributes specialized responsibilities across intelligent agents:
Research Agent: Conducts market research, analyzes investment opportunities, and provides data-driven recommendations based on user-specified criteria and market conditions.
Portfolio Agent: Handles stock analysis, trade execution, and portfolio management with built-in human approval mechanisms for all trading operations, ensuring safety and user control.
Database Agent: Manages persistent data storage, order tracking, portfolio position management, and historical trade analytics through SQLite database operations.
Supervisor Agent: Orchestrates workflow coordination, delegates tasks to appropriate specialists, and ensures completion of user requests through intelligent agent handoffs.
NexTrade implements a hierarchical multi-agent architecture using LangGraph's state management and workflow orchestration capabilities:
┌─────────────────────────────────────────────────────────────┐
│ SUPERVISOR AGENT │
│ (Workflow Coordinator) │
│ • Task delegation and routing │
│ • Agent coordination and handoffs │
│ • Request completion tracking │
└─────────────────┬───────────────┬───────────────┬───────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ RESEARCH AGENT │ │ PORTFOLIO AGENT │ │ DATABASE AGENT │
│ │ │ │ │ │
│ • Market research│ │ • Stock analysis│ │ • Order storage │
│ • Company analysis│ │ • Trade execution│ │ • Portfolio track│
│ • Investment recs│ │ • HITL approval │ │ • History mgmt │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ WEB SEARCH │ │ STOCK TOOLS │ │ SQLITE DATABASE │
│ WIKI SEARCH │ │ PLACE ORDER │ │ • Orders │
│ │ │ FETCH DATA │ │ • Positions │
│ │ │ LOOKUP SYMBOL │ │ • Trade History│
└─────────────────┘ └─────────────────┘ └─────────────────┘
The system utilizes modern AI frameworks and best practices:
LangGraph Framework: Provides state management, workflow orchestration, and agent coordination capabilities with built-in checkpointing and persistence.
LangChain Integration: Enables tool integration, prompt management, and LLM interaction patterns with support for multiple model providers.
Model Flexibility: Supports both Azure OpenAI and Groq models with automatic fallback mechanisms for reliability and cost optimization.
Human-in-the-Loop Safety: Implements interrupt-driven approval workflows for all financial transactions, ensuring user control and preventing unauthorized trades.
Data Persistence: SQLite database backend provides reliable data storage with proper transaction management and ACID compliance.
┌─────────────────────────────────────────────────────────────────────────────┐
│ NEXTRADE SYSTEM │
│ Multi-Agent Trading Platform │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ USER INTERFACE LAYER │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ Streamlit Web UI │ │ Command Line CLI │ │
│ │ • Chat Interface │ │ • Test Scripts │ │
│ │ • Visualizations │ │ • Direct Access │ │
│ │ • Configuration │ │ • Automation │ │
│ └─────────────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ SUPERVISOR AGENT LAYER │
│ ┌─────────────────────────────┐ │
│ │ SUPERVISOR AGENT │ │
│ │ • Task Delegation │ │
│ │ • Workflow Coordination │ │
│ │ • Agent Communication │ │
│ │ • Error Handling │ │
│ │ • State Management │ │
│ └─────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│
┌───────────────────────┼───────────────────────┐
▼ ▼ ▼
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ RESEARCH AGENT │ │ PORTFOLIO AGENT │ │ DATABASE AGENT │
│ │ │ │ │ │
│ • Market Research │ │ • Stock Analysis │ │ • Order Storage │
│ • Company Analysis │ │ • Trade Execution │ │ • Portfolio Track │
│ • Investment Recs │ │ • Human Approval │ │ • History Mgmt │
│ • Data Verification │ │ • Risk Assessment │ │ • Data Integrity │
│ │ │ • Position Mgmt │ │ • Analytics │
└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ EXTERNAL TOOLS │ │ TRADING TOOLS │ │ DATA STORAGE │
│ │ │ │ │ │
│ • Web Search │ │ • Stock Lookup │ │ • SQLite Database │
│ • Wikipedia │ │ • Market Data │ │ • Orders Table │
│ • News Sources │ │ • Order Placement │ │ • Positions Table │
│ • Financial APIs │ │ • Price Tracking │ │ • History Table │
└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
User Request
│
▼
┌─────────────────┐
│ SUPERVISOR │ ──────► Analyze Request
│ AGENT │ Determine Required Agents
└─────────────────┘ Route to Specialist
│
▼
┌─────────────────────────────────────────────┐
│ Agent Selection Logic │
│ │
│ Research Needed? ──► RESEARCH AGENT │
│ Trading Required? ──► PORTFOLIO AGENT │
│ Data Operations? ──► DATABASE AGENT │
│ │
└─────────────────────────────────────────────┘
│
▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ RESEARCH │ │ PORTFOLIO │ │ DATABASE │
│ • Search │ ──►│ • Analyze │ ──►│ • Store │
│ • Analyze │ │ • Execute │ │ • Track │
│ • Recommend │ │ • HITL Check │ │ • Report │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└──────────┐ ▼ │
│ ┌─────────────────┐ │
│ │ HUMAN APPROVAL │ │
│ │ • Review Trade │ │
│ │ • Approve/Deny │ │
│ │ • Safety Check │ │
│ └─────────────────┘ │
│ ▼ │
└────────► ┌─────────────────┐ ◄───────────┘
│ FINAL RESPONSE │
│ • Consolidated │
│ • Complete │
│ • Actionable │
└─────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ SQLITE DATABASE │
│ trading_orders.db │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ ORDERS TABLE │ │ PORTFOLIO_POSITIONS │ │ TRADE_HISTORY │
│ │ │ │ │ │
│ • id (PRIMARY) │ │ • id (PRIMARY) │ │ • id (PRIMARY) │
│ • order_id (UNIQUE) │ │ • user_id │ │ • order_id (FK) │
│ • user_id │ │ • symbol │ │ • user_id │
│ • symbol │ │ • shares │ │ • symbol │
│ • action (buy/sell) │ │ • average_price │ │ • action │
│ • shares │ │ • last_updated │ │ • shares │
│ • price │ │ • UNIQUE(user,sym) │ │ • price │
│ • total_amount │ │ │ │ • total_amount │
│ • order_type │ │ │ │ • timestamp │
│ • status │ │ │ │ • commission │
│ • created_at │ │ │ │ │
│ • updated_at │ │ │ │ │
│ • execution_price │ │ │ │ │
│ • notes │ │ │ │ │
└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
│ │ │
└──────────────────────────┼──────────────────────────┘
│
┌─────────────────┐
│ RELATIONSHIPS │
│ │
│ Orders → History│
│ Orders → Positions│
│ User Isolation │
│ ACID Compliance │
└─────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ SAFETY LAYER ARCHITECTURE │
└─────────────────────────────────────────────────────────────────┘
User Trading Request
│
▼
┌─────────────────┐
│ REQUEST │ ──► Validate Parameters
│ VALIDATION │ Check Permissions
└─────────────────┘ Sanitize Inputs
│
▼
┌─────────────────┐
│ PORTFOLIO │ ──► Fetch Market Data
│ AGENT │ Analyze Risk Factors
│ ANALYSIS │ Calculate Exposure
└─────────────────┘
│
▼
┌─────────────────┐ ┌─────────────────────────────┐
│ HITL TRIGGER │ ──►│ HUMAN APPROVAL │
│ • Trade Details │ │ • Complete Trade Summary │
│ • Risk Level │ │ • Market Context │
│ • User Context │ │ • Risk Assessment │
└─────────────────┘ │ • Approve/Deny Decision │
│ └─────────────────────────────┘
▼ │
┌─────────────────┐ ▼
│ APPROVAL │ ◄──── YES ──┌─────────────────┐
│ RECEIVED │ │ USER DECISION │
└─────────────────┘ │ • Approve │
│ │ • Deny │
▼ │ • Modify │
┌─────────────────┐ └─────────────────┘
│ TRADE │ │
│ EXECUTION │ ◄──── NO ─────────────┘
│ • Execute Order │ │
│ • Update Status │ ▼
│ • Log Action │ ┌─────────────────┐
└─────────────────┘ │ TRADE CANCELLED │
│ │ • Log Denial │
▼ │ • Notify User │
┌─────────────────┐ │ • Clean State │
│ DATABASE │ └─────────────────┘
│ PERSISTENCE │
│ • Store Order │
│ • Update Portfolio│
│ • Audit Trail │
└─────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ TOOL INTEGRATION LAYER │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ RESEARCH TOOLS │ │ PORTFOLIO TOOLS │ │ DATABASE TOOLS │
│ │ │ │ │ │
│ web_search() │ │ lookup_symbol() │ │ insert_order() │
│ wiki_search() │ │ fetch_data() │ │ update_status() │
│ │ │ place_order() │ │ get_orders() │
│ │ │ add_history() │ │ get_positions() │
│ │ │ │ │ get_history() │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ EXTERNAL APIs │ │ MARKET DATA │ │ LOCAL DATABASE │
│ │ │ │ │ │
│ • Google Search │ │ • Yahoo Finance │ │ • SQLite │
│ • Wikipedia API │ │ • Alpha Vantage │ │ • Local Files │
│ • News Sources │ │ • Polygon.io │ │ • Memory Store │
│ • Social Media │ │ • IEX Cloud │ │ • Cache Layer │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└───────────────────────┼───────────────────────┘
│
┌─────────────────────────────┐
│ ERROR HANDLING & │
│ RESILIENCE LAYER │
│ │
│ • Retry Logic │
│ • Fallback Mechanisms │
│ • Rate Limiting │
│ • Circuit Breakers │
│ • Graceful Degradation │
└─────────────────────────────┘
The NexTrade codebase follows professional software development practices with clear separation of concerns:
AAIDC-Module2-MultiAgent/
├── README.md # Project documentation
├── pyproject.toml # Python project configuration
├── uv.lock # Dependency lock file
├── langgraph.json # LangGraph configuration
├── streamlit_app.py # Web interface application
├── test_agents.py # Comprehensive testing suite
├── test_database_agent.py # Database-specific tests
├── src/ # Main source code
│ └── agent/ # Agent implementation
│ ├── __init__.py # Package initialization
│ ├── graph.py # Multi-agent system core
│ ├── prompts.py # Agent system prompts
│ ├── tools.py # Trading and research tools
│ ├── database_tools.py # Data persistence tools
│ ├── state.py # System state management
│ ├── context.py # Configuration management
│ └── utils.py # Utility functions
├── data/ # Database storage
│ └── trading_orders.db # SQLite database
├── images/ # Agent visualizations
└── tests/ # Test suite
├── integration_tests/ # End-to-end tests
└── unit_tests/ # Component tests
git clone <repository-url> cd AAIDC-Module2-MultiAgent
# Using uv (recommended - fast and modern) uv venv .venv # Activate the virtual environment source .venv/bin/activate # Linux/Mac # or .venv\Scripts\activate # Windows
# Install project dependencies using uv uv sync # Install LangGraph CLI for advanced features uv add "langgraph-cli[inmem]"
Create a .env
file in the project root:
cp .env.example .env
Configure your API keys in the .env
file:
# Azure OpenAI Configuration (Primary) AZURE_OPENAI_API_KEY=your_azure_openai_key AZURE_OPENAI_ENDPOINT=your_azure_endpoint OPENAI_API_VERSION=2024-12-01-preview AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o # Groq Configuration (Fallback) GROQ_API_KEY=your_groq_api_key # Optional: LangSmith Tracing LANGSMITH_API_KEY=your_langsmith_key
python test_agents.py
You should see all 8 tests pass, confirming the system is properly configured.
# Full automated test suite python test_agents.py # Database-specific tests python test_database_agent.py
python test_agents.py # Select option 2 for interactive mode
Launch the Streamlit application for a user-friendly interface:
streamlit run streamlit_app.py
The web interface provides:
Objective: Validate core system functionality through automated testing
Execution:
python test_agents.py
Test Coverage:
Expected Output:
Objective: Demonstrate user-friendly interface and real-time interactions
Execution:
streamlit run streamlit_app.py
Interface Features:
Test Scenarios:
Expected Behavior:
Objective: Verify safety mechanisms prevent unauthorized trading
Setup: Configure system with simulated approval workflows
Test Cases:
Safety Verification:
Objective: Validate data persistence and portfolio tracking
Execution:
python test_database_agent.py
Database Operations Tested:
Data Verification:
data/trading_orders.db
Date: September 23, 2025, 11:37-11:38 AM (India Standard Time)
Environment: Virtual Environment (.venv)
Test Suite: Complete Automated Test Suite (8 tests)
Result: ✅ ALL TESTS PASSED (8/8)
C:\Tech\AI\ReadyTensor\AAIDC-Module2-MultiAgent\data\trading_orders.db
Purpose: Validate basic supervisor-agent communication
Query: "What is the current time?"
Results:
Purpose: Validate research capabilities and market analysis
Query: "Research the top 3 AI companies for investment opportunities."
Results:
Purpose: Validate stock analysis and market data retrieval
Query: "Check the current price of NVIDIA stock and analyze it."
Results:
Purpose: Validate data persistence and retrieval operations
Query: "Show me my order history and current portfolio positions from the database."
Results:
Purpose: Validate historical data tracking
Query: "Show me my order history and portfolio summary."
Results:
Purpose: Validate safety mechanisms for trading operations
Results:
Purpose: Validate complete trading workflow with human oversight
Query: "Buy 10 shares of NVIDIA at current market price"
Critical HITL Testing Results:
13e61625-9895-4bf2-ad25-a144dd8d7d79
Trade Details:
Purpose: Validate end-to-end investment workflow
Query: "I want you to invest $1,000 into the most promising company in the AI sector. Please research the options, pick the best candidate, and then go ahead and place a buy order for me."
Complete Workflow Results:
Research Phase: ✅ Completed
Analysis Phase: ✅ Completed
Execution Phase: ✅ Completed
Streamlit Interface Results:
Data Integrity:
Scalability Indicators:
NexTrade successfully demonstrates the power and potential of multi-agent systems in financial technology applications. The implementation showcases how intelligent agent coordination can transform complex trading workflows into streamlined, safe, and efficient operations.
Technical Excellence: The system exhibits robust architecture with proper separation of concerns, comprehensive error handling, and scalable design patterns. The use of modern AI frameworks (LangGraph and LangChain) ensures maintainability and extensibility.
Safety Innovation: Human-in-the-loop mechanisms provide essential safety controls for financial operations while maintaining operational efficiency. The interrupt-driven approval system ensures users retain complete control over trading decisions.
Data Management: SQLite integration provides reliable data persistence with ACID compliance, comprehensive audit trails, and efficient query performance. The database design supports complex portfolio analytics and historical reporting.
User Experience: Both command-line and web interfaces demonstrate accessibility for different user preferences and technical skill levels. The conversational interface lowers barriers to entry for sophisticated trading operations.
Multi-Agent Architecture Patterns: NexTrade establishes proven patterns for financial multi-agent systems including specialized agent roles, workflow coordination, and safety mechanisms.
HITL Integration: The implementation provides a template for integrating human oversight into automated financial systems without compromising operational efficiency.
Tool Integration Framework: The system demonstrates effective integration of diverse data sources and APIs within a cohesive multi-agent architecture.
Safety-First Design: The emphasis on human approval and comprehensive logging establishes best practices for responsible AI in financial applications.
The system's architecture and safety features make it suitable for real-world deployment in various contexts:
Individual Traders: Provides sophisticated automation while maintaining complete user control over trading decisions.
Financial Advisors: Offers tools for enhanced client service through automated research and comprehensive portfolio tracking.
Educational Institutions: Serves as a platform for teaching financial technology concepts and multi-agent system development.
Research Organizations: Provides a foundation for investigating advanced trading algorithms and risk management strategies.
Enhanced Analysis: Integration of additional data sources including news sentiment, technical indicators, and economic calendars could improve research quality.
Risk Management: Advanced portfolio risk assessment and position sizing algorithms could enhance trading safety.
Market Expansion: Support for additional asset classes (bonds, options, cryptocurrencies) would broaden system applicability.
Performance Optimization: Caching mechanisms and parallel processing could further improve response times.
NexTrade represents a significant advancement in making sophisticated trading technology accessible to broader audiences. By combining the power of AI automation with essential human oversight, the system addresses critical needs in financial technology while maintaining the safety and control requirements essential for responsible trading.
The open-source nature of the implementation enables community contribution and academic research, potentially accelerating innovation in multi-agent financial systems. The comprehensive documentation and testing framework provide a solid foundation for further development and customization.
This work contributes to the growing body of knowledge in agentic AI systems and demonstrates practical applications that can immediate benefit traders, investors, and financial technology developers. The emphasis on safety, transparency, and user control establishes important precedents for responsible AI development in financial domains.
NexTrade successfully bridges the gap between cutting-edge AI capabilities and practical financial applications, providing a robust platform that prioritizes both innovation and responsibility in equal measure.