An AI-powered multi-agent trading system for Indian financial markets (NSE, BSE, MCX, Forex). Inspired by recent research in LLM-based financial reasoning and multi-agent collaboration, this system replicates the organizational structure of a professional trading desk — with specialized AI agents for news analysis, technical analysis, risk management, and trade execution — all orchestrated by a coordinator agent that produces transparent, step-by-step reasoning before every decision.
Built with FastAPI, React + TypeScript, and Claude AI (Anthropic).
- Vision
- Research Foundation
- Architecture
- Features
- Current Status
- Roadmap
- Tech Stack
- Getting Started
- Project Structure
- Deployment
- Configuration Reference
- Contributing
- License
Traditional algorithmic trading systems rely on quantitative models that struggle to process the diverse, unstructured information that human traders naturally integrate — news headlines, earnings reports, social sentiment, and macroeconomic context. Meanwhile, deep learning approaches often act as black boxes, making decisions that are impossible to interpret or trust.
AI Trading Agent takes a different approach. Instead of a monolithic model, it deploys a team of specialized AI agents — each with a distinct role, just like a real trading firm:
- A News Analyst reads and interprets market news in real-time
- A Technical Analyst examines charts and computes indicators
- A Risk Manager enforces position limits and portfolio constraints
- An Execution Agent handles order routing to brokers
- A Coordinator orchestrates the team through a structured reasoning chain
Every trade decision is accompanied by a transparent 5-step reasoning chain (Observe → Analyze → Reason → Decide → Risk Assess), so you always know why the system is recommending a particular action.
The long-term goal: A self-improving trading system that learns from its own decisions through reinforcement learning, continuously adapting its strategies to changing market conditions while maintaining full transparency and risk controls.
This project draws inspiration from two lines of research in LLM-based financial systems:
The TradingAgents framework (Xiao et al., 2024) demonstrates that multi-agent systems — where LLMs are assigned specialized roles mimicking real trading firms — can outperform single-model approaches on cumulative returns, Sharpe ratio, and maximum drawdown. Key insights we adopt:
- Specialized agent roles modeled after professional trading desks (analysts, risk managers, traders)
- Structured inter-agent communication rather than unstructured message passing
- Bull/Bear debate dynamics for balanced market assessment
- Risk management as a first-class agent that can veto trade proposals
The Trading-R1 model (Xiao et al., 2025) shows that combining supervised fine-tuning with reinforcement learning produces more disciplined, interpretable trading decisions. Concepts we incorporate:
- Chain-of-thought reasoning applied to financial decisions — generating structured investment theses before acting
- Volatility-adjusted reward signals for reinforcement learning, aligning AI behavior with realistic trading objectives
- Evidence-based decision making — every recommendation grounded in concrete data points (price action, news sentiment, technical signals)
- Xiao, Y. et al. "TradingAgents: Multi-Agents LLM Financial Trading Framework." arXiv:2412.20138, 2024.
- Xiao, Y. et al. "Trading-R1: Financial Trading with LLM Reasoning via Reinforcement Learning." arXiv:2509.11420, 2025.
┌─────────────────────────────────┐
│ Coordinator Agent │
│ (5-Step Reasoning Orchestrator) │
│ │
│ 1. Observe → Gather context │
│ 2. Analyze → Process signals │
│ 3. Reason → Draw conclusions │
│ 4. Decide → Recommend action │
│ 5. Risk → Validate limits │
└────────┬───────────┬─────────────┘
│ │
┌────────────┼───────────┼────────────┐
│ │ │ │
┌─────▼─────┐ ┌───▼───┐ ┌─────▼─────┐ ┌───▼────────┐
│ News │ │ Tech │ │ Risk │ │ Execution │
│ Analyst │ │Analyst│ │ Manager │ │ Agent │
│ │ │ │ │ │ │ │
│ Sentiment │ │ RSI │ │ Position │ │ Paper/Live │
│ analysis │ │ MACD │ │ sizing │ │ trading │
│ via Claude │ │ BB │ │ Stop-loss │ │ via broker │
│ │ │ Chart │ │ Drawdown │ │ APIs │
│ │ │ Vision│ │ checks │ │ │
└─────┬──────┘ └───┬───┘ └─────┬─────┘ └───┬────────┘
│ │ │ │
└────────────┴─────┬─────┴────────────┘
│
┌─────────▼─────────┐
│ Message Bus │
│ (Pub/Sub Topics) │
└─────────┬──────────┘
│
┌─────────────────────────┼─────────────────────────┐
│ │ │
┌────────▼────────┐ ┌──────────▼──────────┐ ┌────────▼────────┐
│ Data Sources │ │ PostgreSQL │ │ WebSocket │
│ │ │ │ │ Server │
│ - yfinance │ │ - Users & Auth │ │ │
│ - NewsAPI/GNews │ │ - Trades & Orders │ │ - Price updates │
│ - RSS feeds │ │ - Portfolios │ │ - Trade alerts │
│ - NSE API │ │ - AI Reasoning logs │ │ - Agent status │
│ - Broker APIs │ │ - Agent performance │ │ - News alerts │
└─────────────────┘ └──────────────────────┘ └─────────────────┘
Agents communicate through a pub/sub Message Bus with predefined topics:
| Topic | Publisher | Subscribers | Payload |
|---|---|---|---|
NEWS_ANALYZED |
News Analyst | Coordinator | Sentiment, affected symbols, confidence |
TECHNICAL_SIGNAL |
Technical Analyst | Coordinator | Indicators, chart patterns, signals |
RISK_APPROVED |
Risk Manager | Execution Agent | Position size, stop-loss, approval status |
TRADE_EXECUTED |
Execution Agent | Coordinator, UI | Order details, fill price, status |
All AI reasoning flows through Claude Sonnet (Anthropic), used for:
| Capability | Method | Description |
|---|---|---|
| News Sentiment | Text API | Analyzes articles for bullish/bearish/neutral sentiment with confidence scores |
| Trade Suggestions | Text API | Generates buy/sell recommendations with structured rationale |
| Reasoning Chains | Text API | Produces the coordinator's 5-step transparent decision process |
| Chart Analysis | Vision API | Reads candlestick charts and identifies patterns (support/resistance, head-and-shoulders, etc.) |
| Strategy Explanation | Text API | Generates human-readable rationale for strategy decisions |
| Learning Insights | Text API | Analyzes performance data to suggest improvements |
Multi-Agent AI System
- 6 specialized agents with standardized interfaces (BaseAgent pattern)
- Asynchronous message bus for agent coordination
- Agent status tracking (IDLE, ACTIVE, PROCESSING, ERROR)
- Performance metrics per agent (success/error counts, processing time)
- Activity logging to database with stack traces on errors
News Intelligence
- Multi-source aggregation: NewsAPI, GNews, Moneycontrol RSS, Economic Times RSS, NSE announcements
- AI-powered sentiment analysis (bullish/bearish/neutral) with confidence scores
- Automatic stock symbol extraction from articles
- Impact assessment (high/medium/low) per article
- Works without paid API keys (falls back to RSS feeds)
Technical Analysis
- Numerical indicators: RSI, MACD, Bollinger Bands, Moving Averages
- Chart generation (Matplotlib) for Claude Vision analysis
- Visual pattern recognition via Claude Vision API (candlestick patterns, support/resistance, trendlines)
- Historical OHLCV data via yfinance
Risk Management
- Position sizing validation (configurable max per position, default 10%)
- Daily loss limit enforcement (default 5%)
- Portfolio drawdown monitoring (max 20%)
- Stop-loss and take-profit calculation
- Concentration risk checks per symbol (max 20%)
Trading
- Paper trading with simulated execution
- Live trading integration with Angel One (SmartAPI) and Zerodha (KiteConnect)
- Order types: Market and Limit
- Position tracking with average price, P&L
- Trade history with full audit trail
Authentication & Security
- JWT authentication with access tokens (30 min) and refresh tokens (7 days)
- Bcrypt password hashing
- Fernet symmetric encryption for broker API credentials
- CORS configuration
- IP-based rate limiting (configurable, default 60 req/min)
Real-Time Updates
- WebSocket server broadcasting price updates, trade executions, agent status, and news alerts
- Connection manager tracking active clients
- Auto-reconnecting frontend WebSocket client with exponential backoff
Background Jobs (APScheduler)
- News fetching and analysis every 15 minutes
- Price updates every 5 minutes during market hours
- Strategy execution checks every minute
- Database persistence for all job outputs
Frontend (React + TypeScript)
- 8 page application: Dashboard, News, Strategies, Settings, History, Analytics, Scanner, Agent Learning
- Dark-themed trading terminal aesthetic
- Recharts for portfolio performance, P&L, and sector allocation visualizations
- Complete REST API integration with automatic token refresh
- Radix UI components with Tailwind CSS
Production Infrastructure
- Docker Compose orchestration (PostgreSQL, FastAPI, Nginx, Certbot)
- Nginx reverse proxy with SSL termination (Let's Encrypt)
- Multi-stage Docker build for optimized images
- Health check endpoints (basic, detailed, readiness, liveness)
- Structured logging with rotating file handlers
- Deployed on AWS EC2 at
trading-agent.sky-ai.in
| Feature | Status | What's Missing |
|---|---|---|
| Coordinator decision logic | Stubbed | Currently defaults to HOLD — needs actual decision algorithm integrating all agent signals |
| Coordinator reasoning chain | Placeholder | Returns generic steps — needs Claude integration for dynamic reasoning |
| Coordinator risk integration | Placeholder | Returns conservative defaults — needs to call RiskManager.analyze() |
| Broker position syncing | Framework only | Background job scaffolded but sync logic not implemented |
| Paper trading prices | Hardcoded | Uses placeholder price instead of live market data for simulated fills |
| Frontend routing | Manual state | Uses page state switching instead of React Router (installed but not wired) |
| Frontend components | Partial | Navigation, Sidebar, ThemeProvider, TradeExecutionModal referenced but not created |
| Scanner page | Demo data | Shows hardcoded opportunities, not connected to real scanning logic |
| Layer | Completion | Notes |
|---|---|---|
| Database & Models | 95% | 17 tables, well-designed schema, proper relationships |
| API Endpoints | 90% | All routes defined and functional |
| News Pipeline | 95% | Multi-source fetching + Claude sentiment analysis fully working |
| Technical Analysis | 90% | Indicators + chart generation + Claude Vision working |
| Risk Manager | 90% | All risk checks implemented and functional |
| Execution Agent | 80% | Paper trading works; live trading code-complete but untested with real credentials |
| Coordinator Agent | 40% | Core orchestration stubbed — decision logic returns HOLD by default |
| Frontend | 60% | All 8 pages built with API integration, but missing shell components and uses mock data in places |
| Infrastructure | 95% | Docker, Nginx, SSL, deployment scripts all production-ready |
| Testing | 70% | Test suite exists but coverage gaps in integration tests |
| CI/CD | 0% | No automated pipeline — deployment is manual |
Bottom line: The system is production-ready for paper trading with AI-powered news and technical analysis. The critical missing piece is the Coordinator's decision-making algorithm — the brain that synthesizes all agent signals into actual BUY/SELL/HOLD decisions.
The highest-priority work to make the system genuinely autonomous:
- Implement Coordinator decision logic — Synthesize news sentiment, technical signals, and market context into actual trade decisions (not hardcoded HOLD)
- Integrate Claude reasoning in Coordinator — Use Claude to generate dynamic, context-aware reasoning chains based on real agent data
- Wire RiskManager into Coordinator — Replace placeholder risk assessment with actual RiskManager.analyze() calls
- Fix paper trading prices — Fetch real market prices for simulated fills instead of hardcoded values
- Wire up React Router — Replace manual page state with proper URL-based routing
- Build missing shell components — Navigation sidebar, theme provider, trade execution modal
- Connect Scanner to real data — Replace demo data with actual market scanning logic
- Add loading states and error boundaries — Proper UX for async operations
- Implement code splitting — Lazy-load pages for better performance
- End-to-end live trading test — Full flow with Angel One or Zerodha sandbox
- Implement broker position syncing — Complete the background job for position/order reconciliation
- Add order modification/cancellation — Support for modifying open orders
- Market hours awareness — Prevent order submission outside trading hours
- Slippage and commission modeling — Realistic execution simulation in paper mode
Inspired by Trading-R1's approach of using RL to produce execution-grade decisions:
- Track suggestion outcomes — Record whether AI suggestions were profitable (partially built in
rl_system.py) - Implement reward calculation — Volatility-adjusted returns as reward signals
- Agent confidence calibration — Adjust confidence scores based on historical accuracy
- Strategy adaptation — Auto-tune strategy parameters based on recent performance
- A/B testing framework — Compare AI decisions against baseline strategies
- Strategy backtesting engine — Test strategies against historical data before deployment
- Bull/Bear debate agents — Inspired by TradingAgents paper; opposing analyst agents that debate before decisions
- Options and derivatives support — Extend beyond equity cash market
- Multi-exchange support — MCX commodities, currency futures
- Social sentiment integration — Twitter/X, Reddit, StockTwits analysis
- Portfolio optimization — Modern Portfolio Theory-based rebalancing
- Alerting system — Email/SMS/push notifications for trade signals and risk events
- CI/CD pipeline — GitHub Actions for automated testing, building, and deployment
- Automated database backups — Scheduled PostgreSQL dumps to S3
- Centralized monitoring — CloudWatch or Grafana dashboards
- Load testing — Verify WebSocket capacity under concurrent users
- API versioning — Stable API contracts for frontend compatibility
- Rate limiting with Redis — Distributed rate limiting for multi-instance deployment
| Technology | Purpose |
|---|---|
| Python 3.13 | Runtime |
| FastAPI | Web framework with auto-generated OpenAPI docs |
| SQLAlchemy 2.0 | ORM with async support |
| PostgreSQL 15 | Primary database |
| Alembic | Database migrations |
| Anthropic SDK | Claude AI (text + vision) |
| yfinance | Market data (NSE/BSE via Yahoo Finance) |
| APScheduler | Background job scheduling |
| SmartAPI | Angel One broker integration |
| KiteConnect | Zerodha broker integration |
| TA-Lib / pandas-ta | Technical indicators |
| Matplotlib | Chart generation for Claude Vision |
| feedparser + BeautifulSoup | News RSS parsing and scraping |
| python-jose + bcrypt | JWT auth and password hashing |
| cryptography (Fernet) | Broker credential encryption |
| Technology | Purpose |
|---|---|
| React 18 | UI framework |
| TypeScript | Type safety |
| Vite | Build tool with HMR |
| Tailwind CSS | Utility-first styling |
| Radix UI | Accessible component primitives |
| Recharts | Charts and visualizations |
| Axios | HTTP client with interceptors |
| React Hook Form + Zod | Form management and validation |
| Lucide React | Icon library |
| Sonner | Toast notifications |
| Technology | Purpose |
|---|---|
| Docker + Docker Compose | Container orchestration |
| Nginx | Reverse proxy, SSL termination, static serving |
| Let's Encrypt (Certbot) | Automated SSL certificates |
| AWS EC2 | Cloud hosting |
- Python 3.13 (or 3.10–3.12)
- pip 26+ recommended (upgrade with
python -m pip install --upgrade pipif needed) - Node.js 20+
- PostgreSQL 15+
- Claude API key from Anthropic Console (required for AI features)
# 1. Clone the repository
git clone https://github.com/yourusername/Trading-Agent.git
cd Trading-Agent
# 2. Set up backend
cd backend
python -m venv venv
.\venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -r requirements_py313.txt # Python 3.13
# python -m pip install -r requirements.txt # Python 3.10-3.12
# 3. Configure environment
cp config_template.txt .env
# Edit .env with your DATABASE_URL, SECRET_KEY, CLAUDE_API_KEY
# 4. Set up database
# Ensure PostgreSQL is running, then:
alembic upgrade head
# 5. Start backend
uvicorn main:app --reload --host 0.0.0.0 --port 8000In a second terminal:
# 6. Set up frontend
cd frontend
npm install
# 7. Start frontend
npm run devOr use the convenience scripts:
.\start-all.ps1 # Opens both in separate windows| Service | URL |
|---|---|
| Frontend | http://localhost:5173 |
| Backend API | http://localhost:8000 |
| API Docs (Swagger) | http://localhost:8000/docs |
| API Docs (ReDoc) | http://localhost:8000/redoc |
| WebSocket | ws://localhost:8000/ws |
| Health Check | http://localhost:8000/health |
Create backend/.env from the template. Required variables:
# Required
DATABASE_URL=postgresql://postgres:yourpassword@127.0.0.1:5432/trading_agent
SECRET_KEY=your-jwt-secret-key-min-32-chars
CLAUDE_API_KEY=sk-ant-api03-your-key-here
# Optional — News APIs (system works without these via RSS feeds)
NEWSAPI_KEY=your-newsapi-key
GNEWS_API_KEY=your-gnews-key
# Optional — Broker APIs (only needed for live trading)
ANGELONE_API_KEY=your-key
ANGELONE_CLIENT_CODE=your-code
ANGELONE_PIN=your-pin
ZERODHA_API_KEY=your-key
ZERODHA_API_SECRET=your-secret
# App config
DEBUG=True
CORS_ORIGINS=http://localhost:5173,http://localhost:3000
LOG_LEVEL=INFOTrading-Agent/
├── backend/
│ ├── agents/ # Multi-agent system
│ │ ├── base_agent.py # Abstract base with status tracking
│ │ ├── coordinator.py # 5-step reasoning orchestrator
│ │ ├── news_analyst.py # News sentiment via Claude
│ │ ├── technical_analyst.py # Chart analysis via Claude Vision
│ │ ├── risk_manager.py # Position sizing and risk checks
│ │ ├── execution_agent.py # Paper/live trade execution
│ │ └── message_bus.py # Pub/sub inter-agent communication
│ ├── api/ # FastAPI route handlers
│ │ ├── auth.py # Registration, login, token refresh
│ │ ├── agents.py # Agent control and status
│ │ ├── market.py # Quotes, history, indicators
│ │ ├── news.py # News fetching and analysis
│ │ ├── broker.py # Credential management
│ │ ├── learning.py # RL metrics and insights
│ │ ├── health.py # Health/readiness/liveness probes
│ │ └── schemas.py # Pydantic request/response models
│ ├── models/ # SQLAlchemy database models
│ │ ├── user.py # User, RefreshToken
│ │ ├── trade.py # Trade, Order
│ │ ├── portfolio.py # Portfolio, Position, Watchlist
│ │ ├── news.py # NewsArticle, AISuggestion, AIReasoning
│ │ ├── broker.py # BrokerCredentials, TradingSettings
│ │ ├── agent.py # AgentConfig, AgentPerformance, AgentLog
│ │ ├── strategy.py # Strategy, StrategyPerformance
│ │ └── market.py # PriceData (OHLCV history)
│ ├── services/ # Core business logic
│ │ ├── claude_service.py # Anthropic SDK (text + vision)
│ │ ├── news_scraper.py # Multi-source news aggregation
│ │ ├── market_data.py # yfinance integration
│ │ ├── broker_integrations.py # Angel One + Zerodha APIs
│ │ ├── background_jobs.py # APScheduler job definitions
│ │ ├── chart_generator.py # Matplotlib chart rendering
│ │ ├── rl_system.py # Reinforcement learning tracking
│ │ └── websocket_server.py # WebSocket connection manager
│ ├── config/settings.py # Pydantic BaseSettings (.env loader)
│ ├── utils/ # Security, logging, rate limiting
│ ├── alembic/ # Database migration scripts
│ ├── tests/ # pytest test suite
│ ├── main.py # FastAPI application entry point
│ ├── Dockerfile # Multi-stage Python build
│ └── requirements_py313.txt # Python 3.13 dependencies
├── frontend/
│ ├── src/
│ │ ├── pages/ # 8 page components
│ │ │ ├── Dashboard.tsx # Portfolio overview, charts, watchlist
│ │ │ ├── News.tsx # AI sentiment analysis feed
│ │ │ ├── Strategies.tsx # Strategy management
│ │ │ ├── Analytics.tsx # Performance metrics and charts
│ │ │ ├── History.tsx # Trade history
│ │ │ ├── Scanner.tsx # Market opportunity scanner
│ │ │ ├── AgentLearning.tsx # AI performance tracking
│ │ │ └── Settings.tsx # Config and broker setup
│ │ ├── components/ui/ # 14 Radix UI component wrappers
│ │ ├── contexts/ # AuthContext (JWT management)
│ │ ├── services/ # Axios API client + WebSocket service
│ │ └── styles/globals.css # Dark theme design tokens
│ ├── package.json
│ └── vite.config.ts
├── nginx/ # Reverse proxy configuration
│ ├── nginx.conf
│ └── conf.d/
│ ├── default.conf # HTTP (development/EC2 IP)
│ └── trading-agent.conf # HTTPS (sky-ai.in production)
├── Researchpapers/ # Reference papers
│ ├── 2412.20138v7.pdf # TradingAgents (multi-agent framework)
│ └── 2509.11420v1.pdf # Trading-R1 (LLM reasoning + RL)
├── docker-compose.yml # Production orchestration
├── deploy.sh # AWS EC2 setup automation
├── setup-ssl.sh # Let's Encrypt certificate setup
├── start-all.ps1 # Windows: start both services
├── start-backend.ps1 # Windows: start backend only
├── start-frontend.ps1 # Windows: start frontend only
└── CLAUDE.md # Developer guidance for Claude Code
The system is configured for deployment at trading-agent.sky-ai.in on AWS EC2.
# 1. SSH into your EC2 instance
ssh -i your-key.pem ubuntu@your-ec2-ip
# 2. Run the setup script (installs Docker, Node.js, configures firewall)
sudo bash deploy.sh
# 3. Clone and configure
cd /opt/trading-agent
git clone https://github.com/yourusername/Trading-Agent.git .
cp .env.production .env
# Edit .env with production secrets
# 4. Build frontend
cd frontend && npm install && npm run build && cd ..
# 5. Launch
docker-compose up -d
# 6. Set up SSL (after DNS is configured)
bash setup-ssl.shInternet → Nginx (80/443) → ┬→ FastAPI Backend (8000)
├→ Static Frontend (dist/)
└→ WebSocket (ws://)
↓
PostgreSQL (5432)
| Endpoint | URL |
|---|---|
| Frontend | https://trading-agent.sky-ai.in |
| API | https://trading-agent.sky-ai.in/api/ |
| API Docs | https://trading-agent.sky-ai.in/docs |
| WebSocket | wss://trading-agent.sky-ai.in/ws |
| Health | https://trading-agent.sky-ai.in/health |
cd backend
# Apply all migrations
alembic upgrade head
# Create a new migration after model changes
alembic revision --autogenerate -m "description"
# Rollback one migration
alembic downgrade -1cd backend
pytest -v # Run all tests
pytest tests/test_agents.py # Run specific test fileStart the backend and visit http://localhost:8000/docs for interactive Swagger documentation covering all endpoints:
/auth/*— Registration, login, token management/agents/*— Agent status, analysis triggers, reasoning chains/market/*— Quotes, historical data, technical indicators/news/*— News fetching and AI sentiment analysis/broker/*— Credential management and connection testing/learning/*— RL performance metrics and insights/health/*— Health, readiness, and liveness probes
This project is under active development. Key areas where contributions are welcome:
- Coordinator decision logic — The most impactful work: implementing the algorithm that synthesizes agent signals into trade decisions
- Frontend polish — Wiring up React Router, building missing components, improving UX
- Strategy backtesting — Building a historical simulation engine
- Additional broker integrations — Expanding beyond Angel One and Zerodha
- CI/CD pipeline — GitHub Actions for automated testing and deployment
- Test coverage — Integration tests for the full trade decision flow
# Backend (with hot reload)
cd backend && .\venv\Scripts\Activate.ps1
uvicorn main:app --reload
# Frontend (with HMR)
cd frontend
npm run dev
# Both at once
.\start-all.ps1This project is proprietary. All rights reserved.
Built with Claude AI by Anthropic | Targeting Indian Markets (NSE, BSE, MCX, Forex)