Skip to content

chaitanyakumar-d/upstox-chatbot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

4 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ“ˆ Upstox AI Trading Chatbot

A production-ready AI chatbot that connects to your Upstox trading account using the Model Context Protocol (MCP) architecture. Ask questions in plain English, get portfolio information, fetch quotes, technical analysis, and place ordersโ€”all powered by AI.

๐Ÿ—๏ธ Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Web UI        โ”‚โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚   LangChain      โ”‚โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚   MCP Server    โ”‚
โ”‚  (Streamlit)    โ”‚      โ”‚   Agent (LLM)    โ”‚      โ”‚   (FastAPI)     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                           โ”‚
                                                           โ–ผ
                                                   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                                   โ”‚  Upstox API   โ”‚
                                                   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ“ Project Structure

upstox-chatbot/
โ”œโ”€โ”€ app/
โ”‚   โ”œโ”€โ”€ server.py              # MCP Server (FastAPI) - Port 8000
โ”‚   โ”œโ”€โ”€ agent.py               # CLI Agent with LangChain
โ”‚   โ”œโ”€โ”€ web.py                 # Streamlit Web UI - Port 8501
โ”‚   โ”œโ”€โ”€ auth.py                # Upstox OAuth Authentication
โ”‚   โ””โ”€โ”€ analysis/
โ”‚       โ”œโ”€โ”€ technical.py       # Technical Analysis (RSI, MACD, etc.)
โ”‚       โ”œโ”€โ”€ predictions.py     # ML Predictions (XGBoost)
โ”‚       โ”œโ”€โ”€ suggestions.py     # Smart Trade Suggestions
โ”‚       โ”œโ”€โ”€ alerts.py          # WhatsApp Alerts (Twilio)
โ”‚       โ”œโ”€โ”€ portfolio.py       # Portfolio Analytics (Risk, Diversification)
โ”‚       โ””โ”€โ”€ sentiment.py       # News Sentiment & Market Regime
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ test_agent.py          # Test suite
โ”œโ”€โ”€ scripts/
โ”‚   โ””โ”€โ”€ check_secrets.sh       # Security check script
โ”œโ”€โ”€ run.py                     # Entry point (run.py server|agent|web)
โ”œโ”€โ”€ requirements.txt           # Python dependencies
โ”œโ”€โ”€ Dockerfile                 # Container config
โ””โ”€โ”€ docker-compose.yml         # Multi-service setup

โœจ Features

  • ๐Ÿ’ฌ Natural Language Interface: Ask questions in plain English
  • ๐Ÿ“Š Portfolio Management: View holdings, positions, and funds
  • ๐Ÿ“ˆ Real-time Quotes: Get live market data for any stock
  • ๐Ÿ“‰ Technical Analysis: RSI, MACD, Moving Averages, Bollinger Bands
  • ๐ŸŽฏ Trading Signals: AI-generated BUY/SELL/HOLD recommendations
  • ๐Ÿค– ML Predictions: XGBoost-based price direction forecasting
  • ๐Ÿ’ก Smart Suggestions: Personalized trade recommendations with risk management
  • ๐Ÿ“ฑ WhatsApp Alerts: Real-time price & signal notifications via Twilio
  • ๐Ÿ›’ Order Placement: Place buy/sell orders with AI assistance
  • ๐Ÿ”’ Secure: Token-based authentication, confirmation before orders
  • ๐Ÿณ Docker Ready: Complete containerization support

๐Ÿ“‹ Prerequisites

  1. Upstox Account & Developer Credentials

  2. AI Model API Key (choose one)

  3. Python 3.9+

๐Ÿš€ Quick Start

1. Setup

# Clone and navigate to project
cd upstox-chatbot

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Copy environment file
cp .env.example .env

2. Configure .env

# Upstox credentials
UPSTOX_API_KEY=your_api_key
UPSTOX_APP_SECRET=your_app_secret
UPSTOX_ACCESS_TOKEN=your_access_token

# AI Model (choose one - OpenRouter recommended)
OPENROUTER_API_KEY=your_openrouter_key
OPENROUTER_MODEL=google/gemini-2.0-flash-001

# OR use direct provider keys:
# OPENAI_API_KEY=your_openai_key
# ANTHROPIC_API_KEY=your_anthropic_key
# GOOGLE_API_KEY=your_google_key

3. Run the Application

# Option 1: Use run.py (recommended)
python run.py server    # Start MCP Server (terminal 1)
python run.py web       # Start Web UI (terminal 2)

# Option 2: Run directly
python -m app.server              # MCP Server on :8000
streamlit run app/web.py          # Web UI on :8501
python -m app.agent               # CLI Agent

4. Open in Browser

Navigate to http://localhost:8501 ๐ŸŽ‰

๐ŸŽฏ Usage Examples

You: What are my current holdings?
Bot: You have 50 shares of RELIANCE at avg price โ‚น2,450...

You: Get technical analysis for TCS
Bot: ๐Ÿ“Š TCS Technical Analysis:
     โ€ข RSI: 45.2 (Neutral)
     โ€ข MACD: Bullish crossover
     โ€ข Signal: BUY (72% confidence)
     โ€ข Stop Loss: โ‚น3,380 | Target: โ‚น3,650

You: Predict INFY direction for tomorrow
Bot: ๐ŸŽฏ INFY Prediction:
     โ€ข Direction: UP (68% confidence)
     โ€ข Pattern: Bullish trend detected
     โ€ข Support: โ‚น1,520 | Resistance: โ‚น1,580

You: Get trade suggestions for my portfolio
Bot: ๐Ÿ’ก Suggested Trades:
     1. BUY HDFCBANK - โ‚น1,650 (Position: 5 shares)
        Stop Loss: โ‚น1,600 | Target: โ‚น1,720

You: Alert me when RELIANCE crosses 2500
Bot: โœ… Price alert created! You'll get a WhatsApp 
     message when RELIANCE goes above โ‚น2,500

You: Start the alert service
Bot: ๐Ÿš€ Alert monitoring started! Checking every 60s

You: Analyze my portfolio risk
Bot: ๐Ÿ“Š Portfolio Risk Metrics:
     โ€ข Beta: 1.15 (slightly aggressive)
     โ€ข Sharpe Ratio: 1.45 (good risk-adjusted returns)
     โ€ข VaR (95%): -2.3% daily max loss
     โ€ข Max Drawdown: -12.5%

You: How diversified is my portfolio?
Bot: ๐Ÿ”„ Diversification Analysis:
     โ€ข Sectors: IT 35%, Banking 25%, FMCG 20%
     โ€ข HHI: 1,850 (moderately concentrated)
     โ€ข Avg Correlation: 0.42
     โ€ข Score: 72/100 (Good)

You: What's the news sentiment for RELIANCE?
Bot: ๐Ÿ“ฐ News Sentiment Analysis:
     โ€ข Overall: Bullish (score: 0.45)
     โ€ข Articles: 12 analyzed
     โ€ข Distribution: 8 positive, 3 neutral, 1 negative
     โ€ข Recommendation: Positive sentiment may support price

You: What's the current market regime?
Bot: ๐ŸŸข Market Regime: Moderate Bull Market
     โ€ข Nifty above 20-day, 50-day, 200-day MAs
     โ€ข Volatility: Normal (18.5%)
     โ€ข Implication: Favor long positions

You: Show sector momentum
Bot: ๐Ÿ“ˆ Sector Momentum (20-day):
     Leaders: IT (+8.2%), Banking (+5.1%)
     Laggards: Metals (-3.5%), Realty (-2.8%)
     Advice: Rotate into leading sectors

You: How much funds do I have?
Bot: Available balance: โ‚น45,230.50

You: Buy 10 shares of INFY
Bot: โš ๏ธ Confirming: Buy 10 INFY shares (MARKET). Proceed? (y/n)

๐Ÿณ Docker Deployment

# Build and run
docker-compose up -d

# View logs
docker-compose logs -f

# Stop
docker-compose down

๐Ÿ”ฎ Future Enhancements

Phase 1: Technical Analysis โœ…

  • RSI, MACD, Moving Averages, Bollinger Bands
  • Trading signals with confidence scores

Phase 2: ML-Based Predictions โœ…

  • XGBoost price direction forecasting (UP/DOWN)
  • Pattern recognition (Double Top/Bottom, trends)
  • Support/Resistance level detection
  • Feature importance analysis

Phase 3: Smart Trade Suggestions โœ…

  • Personalized trade recommendations with entry/exit points
  • Risk-adjusted position sizing (Kelly Criterion)
  • Stop-loss and take-profit targets
  • Portfolio rebalancing suggestions

Phase 4: Real-Time WhatsApp Alerts โœ…

  • Price threshold alerts (above/below target)
  • RSI alerts (overbought/oversold conditions)
  • MACD crossover alerts (bullish/bearish)
  • Trading signal notifications via WhatsApp (Twilio)
  • Background alert service with APScheduler

Phase 5: Portfolio Analytics โœ…

  • Risk metrics (Beta, Sharpe Ratio, Sortino Ratio, VaR)
  • Maximum Drawdown and Calmar Ratio
  • Diversification analysis with correlation matrix
  • Sector allocation and concentration metrics (HHI)
  • Performance vs Nifty 50 benchmark (Alpha, Treynor Ratio)

Phase 6: Advanced AI โœ…

  • News sentiment analysis using NLP (TextBlob + keyword scoring)
  • Market regime detection (Bull/Bear/Sideways)
  • Volatility regime identification
  • Sector momentum analysis and rotation signals
  • Market breadth indicators (Advance/Decline, % above MAs)
  • Comprehensive market analysis combining all indicators

๐Ÿ”’ Security

  • Never commit .env files
  • Use sandbox mode for testing
  • Orders require confirmation
  • See SECURITY.md for more

๐Ÿ“š Resources

โš ๏ธ Disclaimer

This is educational software. Trading involves risk. Always verify orders and test in sandbox mode first. Not financial advice.


Built with โค๏ธ using MCP, LangChain, and Streamlit

About

No description, website, or topics provided.

Resources

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages