MCP-server-stock-market

Shubham0997/MCP-server-stock-market

3.1

If you are the rightful owner of MCP-server-stock-market and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

A comprehensive Model Context Protocol (MCP) server for Indian stock market data queries with intelligent fail-safe mechanisms, automatic parameter correction, and full Zerodha trading integration.

Tools
3
Resources
0
Prompts
0

MCP Stock Market Server

A comprehensive Model Context Protocol (MCP) server for Indian stock market data queries with intelligent fail-safe mechanisms, automatic parameter correction, and full Zerodha trading integration.

🌟 Overview

This MCP server provides a robust interface for querying Indian stock market data through natural language processing. It combines the power of Large Language Models (LLMs) with comprehensive market data APIs and trading capabilities, making it perfect for financial analysis, trading automation, and market research.

🏗️ Architecture

The server follows a clean, modular architecture with clear separation of concerns:

MCP Stock Market Server/
├── src/
│   ├── api/                 # FastAPI server and endpoints
│   ├── core/               # Core business logic and validation
│   ├── services/           # Service layer (LLM, trading, query processing)
│   ├── routes/             # API route handlers
│   └── utils/              # Utility functions and logging
├── main.py                 # Application entry point
├── requirements.txt        # Python dependencies
├── tools.json             # Tool definitions and API endpoints
└── README.md              # This file

✨ Current Features

🛡️ Intelligent Fail-Safe System

  • Automatic Retry Logic: Up to 3 attempts with exponential backoff (1s, 2s, 4s)
  • Smart Parameter Correction: Automatically fixes common parameter issues
    • Symbol case correction (relianceRELIANCE)
    • URL encoding for spaces (NIFTY 50NIFTY%2050)
    • Date format standardization (01/01/20242024-01-01)
    • Boolean parameter conversion ("true"true)
  • Enhanced Error Handling: Context-aware error messages and recovery
  • Comprehensive Logging: Detailed logging for debugging and monitoring

📊 NSE India Market Data Integration

Powered by stock-nse-india

We utilize the excellent stock-nse-india Python package for comprehensive NSE data access:

Market Information
  • Market Status: Real-time market open/close status
  • Market Turnover: Current market turnover data
  • Holiday Calendar: Trading and clearing holidays
  • Circulars: NSE circulars and announcements
  • Glossary: Financial terms and definitions
Equity Data
  • Equity Details: Complete stock information (price, volume, market cap, etc.)
  • Historical Data: Price history with date range filtering
  • Intraday Data: Real-time intraday trading data
  • Options Chain: Complete options data for equities
  • Corporate Information: Company details, board members, etc.
  • Trade Information: Buy/sell orders, circuit limits, etc.
Index Data
  • All Indices: Complete NSE index information
  • Index Details: Specific index performance and data
  • Index Historical: Historical index performance
  • Index Intraday: Real-time index data
  • Index Options: Options chain for indices
Market Analytics
  • Gainers & Losers: Top performing stocks by index
  • Most Active Equities: Most traded stocks
  • Merged Daily Reports: Market segment reports

🏦 Zerodha Trading Integration

Complete OAuth 2.0 integration with Zerodha Kite Connect API:

Authentication
  • OAuth 2.0 Flow: Secure login with Zerodha
  • Session Management: Persistent authentication
  • User Profile: Account information and details
Portfolio Management
  • Mutual Fund Holdings: Complete MF portfolio with P&L
  • Margins: Funds, cash, and margin information
  • Holdings Summary: Portfolio overview and analytics
Trading Operations
  • Order Placement: Multiple order types
    • Regular orders (MARKET, LIMIT, SL, SL-M)
    • After Market Orders (AMO)
    • Cover Orders (CO)
  • Order Management: View, track, and manage orders
  • Trade History: Complete trade execution history
  • Order History: Detailed order progression tracking

🤖 LLM Integration

  • Perplexity API: Advanced language model integration
  • Smart Tool Selection: Automatic tool selection based on user queries
  • Context-Aware Responses: Intelligent answer generation
  • Error Recovery: Enhanced prompts with error context

🔧 Core Components

  1. Query Processor (src/services/query_processor.py)

    • Main workflow orchestration
    • Tool selection and execution
    • Final answer generation
  2. Parameter Corrector (src/core/parameter_corrector.py)

    • Automatic parameter validation and correction
    • Symbol, date, and boolean parameter fixes
  3. Tool Executor (src/services/tool_executor.py)

    • MCP tool execution with retry logic
    • URL building and parameter substitution
  4. LLM Service (src/services/llm_service.py)

    • Perplexity API integration
    • Response parsing and validation
  5. Validation System (src/core/validator.py)

    • Tool result validation
    • Error detection and reporting

🚀 Quick Start

Prerequisites

  • Python 3.8+
  • Perplexity API key
  • Zerodha API credentials (optional, for trading features)

Installation

  1. Clone the repository

    git clone https://github.com/your-username/mcp-stock-market-server.git
    cd mcp-stock-market-server
    
  2. Create virtual environment

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. Install dependencies

    pip install -r requirements.txt
    
  4. Set up environment variables

    # Create .env file
    cat > .env << EOF
    PERPLEXITY_API_KEY=your_perplexity_api_key_here
    ZERODHA_API_KEY=your_zerodha_api_key_here
    ZERODHA_API_SECRET=your_zerodha_api_secret_here
    ZERODHA_REDIRECT_URL=https://localhost:8000/zerodha/callback
    EOF
    

Running the Server

Development Mode
python main.py
Production Mode
uvicorn src.api.server:app --host 0.0.0.0 --port 8000

The server will be available at http://localhost:8000

📡 API Endpoints

Core Endpoints

POST /query

Process natural language queries about stock market data.

Request:

{
  "prompt": "Get current price for RELIANCE stock"
}

Response:

{
  "answer": "The current price of RELIANCE is ₹2,450.50",
  "tool": "get_equity_details",
  "parameters": {"symbol": "RELIANCE"},
  "toolResult": {...},
  "attempts": 1
}
GET /health

Health check endpoint.

GET /tools

Get list of all available tools and their descriptions.

Zerodha Trading Endpoints

Authentication
  • GET /zerodha/login-url - Get Zerodha login URL
  • GET /zerodha/status - Check authentication status
  • GET /zerodha/session - Get session information
  • POST /zerodha/logout - Logout and invalidate session
Portfolio
  • GET /zerodha/profile - Get user profile
  • GET /zerodha/mf/holdings - Get mutual fund holdings
  • GET /zerodha/margins - Get margin information
Trading
  • POST /zerodha/orders/regular - Place regular orders
  • POST /zerodha/orders/amo - Place after market orders
  • POST /zerodha/orders/co - Place cover orders
  • GET /zerodha/orders - Get all orders
  • GET /zerodha/orders/{order_id} - Get order history
  • GET /zerodha/trades - Get all trades
  • GET /zerodha/orders/{order_id}/trades - Get order-specific trades

🧪 Testing

Run the comprehensive test suite:

python tests/test_failsafe.py

Test Scenarios:

  1. ✅ Normal queries (should succeed on first attempt)
  2. 🔄 Symbol case errors (should retry with correction)
  3. 🔄 URL encoding issues (should retry with encoding)
  4. ❌ Non-existent symbols (should fail after retries)
  5. 🔄 Date format errors (should retry with correction)
  6. 🔄 Boolean parameter errors (should retry with correction)
  7. ❌ Non-financial queries (should return error immediately)
  8. ❌ Insufficient tool results (should return error for insufficient data)

🔧 Configuration

Environment Variables

Required
  • PERPLEXITY_API_KEY: Your Perplexity API key
Optional (for Zerodha integration)
  • ZERODHA_API_KEY: Your Zerodha API key
  • ZERODHA_API_SECRET: Your Zerodha API secret
  • ZERODHA_REDIRECT_URL: OAuth redirect URL
Server Configuration
  • FASTAPI_HOST: Server host (default: 0.0.0.0)
  • FASTAPI_PORT: Server port (default: 8000)
  • MCP_SERVER_URL: MCP server URL (default: http://localhost:8000)
Fail-Safe Settings
  • MAX_RETRY_ATTEMPTS: Maximum retry attempts (default: 3)
  • RETRY_DELAYS: Retry delays in seconds (default: [1, 2, 4])
  • REQUEST_TIMEOUT: Request timeout in seconds (default: 30)

📊 Usage Examples

Basic Stock Queries

# Get current stock price
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"prompt": "What is the current price of RELIANCE?"}'

# Get historical data
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Show me RELIANCE stock price from 2024-01-01 to 2024-01-31"}'

# Get market status
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Is the NSE market open right now?"}'

Index Queries

# Get NIFTY 50 details
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"prompt": "What is the current value of NIFTY 50?"}'

# Get top gainers
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Show me top gainers in NIFTY 50"}'

Trading Operations (requires Zerodha authentication)

# Place a buy order
curl -X POST http://localhost:8000/zerodha/orders/regular \
  -H "Content-Type: application/json" \
  -d '{
    "tradingsymbol": "RELIANCE",
    "exchange": "NSE",
    "transaction_type": "BUY",
    "order_type": "MARKET",
    "quantity": 1,
    "product": "CNC"
  }'

# Get portfolio
curl -X GET http://localhost:8000/zerodha/mf/holdings

🔮 Future Features

🎯 Planned Enhancements

Advanced Analytics
  • Technical Indicators: RSI, MACD, Bollinger Bands, Moving Averages
  • Pattern Recognition: Chart pattern detection and analysis
  • Sentiment Analysis: News and social media sentiment scoring
  • Risk Metrics: VaR, Sharpe ratio, beta calculations
  • Portfolio Optimization: Modern portfolio theory implementation
Enhanced Trading Features
  • Algorithmic Trading: Pre-built trading strategies
  • Backtesting: Historical strategy performance testing
  • Paper Trading: Risk-free strategy testing
  • Order Management: Advanced order types (bracket, cover, etc.)
  • Position Sizing: Kelly criterion and risk-based position sizing
Data Sources Expansion
  • BSE Integration: Bombay Stock Exchange data
  • International Markets: US, European, Asian market data
  • Cryptocurrency: Major crypto exchanges integration
  • Commodities: MCX and international commodity data
  • Forex: Currency pair data and analysis
AI/ML Enhancements
  • Predictive Models: Price prediction using ML algorithms
  • Anomaly Detection: Unusual market behavior identification
  • Natural Language Processing: Enhanced query understanding
  • Recommendation Engine: Personalized stock recommendations
  • Market Regime Detection: Bull/bear market identification
User Experience
  • Web Dashboard: Interactive web interface
  • Mobile App: iOS and Android applications
  • Real-time Notifications: Price alerts and market updates
  • Custom Watchlists: Personalized stock monitoring
  • Report Generation: Automated PDF/Excel reports
Integration & APIs
  • Webhook Support: Real-time event notifications
  • GraphQL API: Flexible data querying
  • REST API v2: Enhanced API with better error handling
  • SDK Development: Python, JavaScript, and Java SDKs
  • Third-party Integrations: TradingView, Bloomberg, Reuters
Performance & Scalability
  • Caching Layer: Redis-based response caching
  • Load Balancing: Horizontal scaling support
  • Database Integration: PostgreSQL for data persistence
  • Microservices: Service decomposition for better scalability
  • Container Support: Docker and Kubernetes deployment
Security & Compliance
  • Rate Limiting: API usage throttling
  • Authentication: JWT-based user authentication
  • Audit Logging: Comprehensive activity tracking
  • Data Encryption: End-to-end data encryption
  • Compliance: SEBI and regulatory compliance features

🗓️ Development Roadmap

Phase 1 (Q1 2024)
  • Technical indicators implementation
  • Enhanced error handling
  • Performance optimization
  • Comprehensive test coverage
Phase 2 (Q2 2024)
  • Web dashboard development
  • Advanced trading features
  • BSE integration
  • Mobile app prototype
Phase 3 (Q3 2024)
  • ML-based predictions
  • Algorithmic trading strategies
  • International market data
  • Enterprise features
Phase 4 (Q4 2024)
  • Full mobile app release
  • Advanced analytics suite
  • Third-party integrations
  • Enterprise deployment tools

🤝 Contributing

We welcome contributions! Please see our for details.

Development Setup

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass (python -m pytest)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

Code Style

  • Follow PEP 8 for Python code
  • Use type hints for function parameters and return values
  • Write comprehensive docstrings for all functions and classes
  • Add unit tests for new features
  • Update documentation for API changes

📝 License

This project is licensed under the MIT License - see the file for details.

🙏 Acknowledgments

  • stock-nse-india: Excellent Python package for NSE data access
  • Zerodha: For providing the Kite Connect API
  • Perplexity: For advanced LLM capabilities
  • FastAPI: For the robust web framework
  • Open Source Community: For the amazing tools and libraries

📞 Support

⭐ Star History

Star History Chart


⭐ Star this repository if you find it helpful!

Made with ❤️ for the Indian stock market community