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.
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Web UI โโโโโโโถโ LangChain โโโโโโโถโ MCP Server โ
โ (Streamlit) โ โ Agent (LLM) โ โ (FastAPI) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโ
โ Upstox API โ
โโโโโโโโโโโโโโโโโ
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
- ๐ฌ 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
-
Upstox Account & Developer Credentials
- Sign up at Upstox
- Create a developer app at Developer Console
-
AI Model API Key (choose one)
- OpenRouter API Key - Recommended (100+ models)
- OpenAI API Key (GPT-4o)
- Anthropic API Key (Claude 3.5 Sonnet)
- Google API Key (Gemini)
-
Python 3.9+
# 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# 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# 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 AgentNavigate to http://localhost:8501 ๐
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)
# Build and run
docker-compose up -d
# View logs
docker-compose logs -f
# Stop
docker-compose down- RSI, MACD, Moving Averages, Bollinger Bands
- Trading signals with confidence scores
- XGBoost price direction forecasting (UP/DOWN)
- Pattern recognition (Double Top/Bottom, trends)
- Support/Resistance level detection
- Feature importance analysis
- Personalized trade recommendations with entry/exit points
- Risk-adjusted position sizing (Kelly Criterion)
- Stop-loss and take-profit targets
- Portfolio rebalancing suggestions
- 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
- 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)
- 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
- Never commit
.envfiles - Use sandbox mode for testing
- Orders require confirmation
- See SECURITY.md for more
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