VinayMuraskar711/SNOWFLAKE-2.2
If you are the rightful owner of SNOWFLAKE-2.2 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.
The SNOWFLAKE ZERODHA MCP SERVER VERSION 2 is a robust model context protocol server designed to facilitate seamless integration and management of machine learning models within various platforms.
Zerodha MCP Server - Ultimate Trading & Analytics Platform
The ULTIMATE Model Context Protocol (MCP) server for professional trading with Zerodha Kite, featuring ADVANCED MARKET INSIGHTS powered by yfinance and OpenBB, real-time data streaming, AI-powered analysis, and institutional-grade analytics.
Now with Professional Market Insights! Get comprehensive technical, fundamental, and sentiment analysis for any stock - just like Bloomberg Terminal!
NEW: Advanced Market Insights
8 Professional Analysis Tools
| Tool | What It Does |
|---|---|
| Market Insights | Complete stock analysis: Technical + Fundamental + Sentiment + AI Recommendation |
| Market Overview | Track NIFTY, SENSEX, S&P500, NASDAQ in real-time |
| Sector Performance | Analyze Tech, Banking, Auto, Pharma, FMCG sectors |
| Technical Indicators | RSI, MACD, Bollinger Bands, Moving Averages + signals |
| Fundamental Metrics | P/E ratio, ROE, profit margins, debt levels, quality score |
| Stock News | Latest news + sentiment analysis |
| Analyst Recommendations | Buy/Hold/Sell consensus from analysts |
| Stock Comparison | Compare multiple stocks across all metrics |
What You Get
Technical Analysis:
- RSI (Relative Strength Index) with oversold/overbought signals
- MACD with bullish/bearish crossovers
- Bollinger Bands for volatility analysis
- Multiple Moving Averages (SMA 20, 50, EMA 12, 26)
- Trend Detection (STRONG_BULLISH to STRONG_BEARISH)
Fundamental Analysis:
- Valuation Ratios (P/E, P/B, EV/EBITDA)
- Profitability Metrics (ROE, Profit Margin, EPS)
- Growth Indicators (Earnings & Revenue Growth)
- Financial Health (Debt-to-Equity, Dividend Yield)
- Quality Score (0-100 rating system)
Sentiment & News:
- Analyst ratings consensus
- News sentiment analysis
- Market sentiment score
- Latest news articles with publisher info
AI Recommendations:
- STRONG BUY / BUY / HOLD / SELL / STRONG SELL
- Confidence levels (HIGH / MEDIUM / LOW)
- Detailed reasoning for each recommendation
- Multi-factor scoring system
|
Core Features
Trading & Execution
Advanced Data Analysis (yfinance)### Advanced Risk Management
-
Unlimited Historical Data - No rate limits, no subscription fees- Position Size Limits - Configurable maximum position sizes
-
Real-time Market Data - Live prices during market hours- Daily Loss Limits - Automatic trading halt on loss thresholds
-
Company Fundamentals - Market cap, P/E ratio, sector info, 52-week highs/lows- Portfolio Concentration - Diversification monitoring
-
International Support - NSE, BSE, and global markets- Correlation Analysis - Detect correlated positions
-
Multiple Timeframes - 1m to max historical data- Volatility Checks - High-volatility stock warnings
-
Margin Utilization - Real-time margin monitoring
Technical Analysis Suite
-
Moving Averages - SMA (20/50/200), EMA (12/26)### Comprehensive Analytics
-
Momentum Indicators - RSI, MACD, Stochastic Oscillator- Portfolio Metrics - Sharpe ratio, drawdown, volatility analysis
-
Volatility Measures - Bollinger Bands, ATR (Average True Range)- Performance Attribution - Identify top/worst performers
-
Volume Analysis - OBV (On-Balance Volume), Volume Ratio- Sector Analysis - Portfolio sector allocation
-
Support/Resistance - Automatic level identification- Risk Decomposition - Factor-based risk analysis
-
Trend Detection - Short, medium, and long-term trends- Correlation Matrix - Position correlation analysis
Automated Trading System### Smart Alerts & Notifications
-
Smart Signal Generation - Multi-indicator consensus scoring- Price Alerts - Custom price target notifications
-
Position Sizing - Risk-based quantity calculation- Risk Alerts - Automated risk threshold warnings
-
Stop Loss Automation - 2x ATR-based stop losses- Performance Alerts - Portfolio milestone notifications
-
Entry/Exit Points - Optimal trade levels- Market Events - Important market movement alerts
-
Risk-Reward Ratios - Automatic R:R calculation
-
Strategy Backtesting - Historical performance testing## Installation & Setup
Zerodha Portfolio Integration### Prerequisites
-
Real-time Holdings - Live portfolio positions- Python 3.10 or higher
-
P&L Tracking - Individual and total profit/loss- Zerodha Kite API credentials
-
Signal Overlay - BUY/SELL signals for your holdings- VS Code with GitHub Copilot
-
Performance Analysis - Win rate, sector allocation
-
Risk Assessment - Position concentration, diversification### 1. Clone and Setup Environment
---```bash
Clone the repository
Installationgit clone
cd zerodha-mcp-server
Prerequisites
-
Python 3.10 or higher# Create virtual environment
-
Zerodha Kite API credentials (for portfolio tracking)python -m venv .venv
Quick Install# Activate virtual environment
Windows:
# Clone repository# Linux/Mac:
git clone <repository-url>source .venv/bin/activate
cd SNOWFLAKE_MCP_SERVER
# Install dependencies
# Create virtual environmentpip install -e .
python -m venv .venv```
# Activate virtual environment### 2. Configure Environment Variables
.venv\Scripts\activate # Windows
source .venv/bin/activate # Linux/Mac```bash
# Copy example environment file
# Install dependenciescp .env.example .env
pip install yfinance pandas numpy scipy scikit-learn matplotlib plotly kiteconnect python-dotenv
```# Edit .env file with your credentials
notepad .env # Windows
### Configure Environmentnano .env # Linux/Mac
Create .env file:
KITE_API_KEY=your_api_key```env
KITE_ACCESS_TOKEN=your_access_tokenZERODHA_API_KEY=your_api_key_here
KITE_API_SECRET=your_api_secretZERODHA_API_SECRET=your_api_secret_here
```ZERODHA_ACCESS_TOKEN=your_access_token_here # Optional
3. Install in VS Code
Quick Start
Create .vscode/mcp.json in your workspace:
1. Analyze Your Portfolio
```bash{
python analyze_portfolio.py "servers": {
``` "zerodha-mcp-server": {
"type": "stdio",
**Output:** "command": "python",
- Complete holdings breakdown "args": ["-m", "zerodha_mcp_server"]
- Individual P&L for each stock }
- Sector allocation }
- Performance metrics}
- Trading recommendations```
### 2. Find Trading Opportunities## Quick Start
```bash### 1. Initialize Session
python quick_trade_scan.py
``````python
# Using the MCP server in VS Code
**Output:**initialize_session({
- Strong BUY/SELL signals (score ≥ 2) "api_key": "your_api_key",
- Entry/exit prices "api_secret": "your_api_secret"
- Target levels})
- Quick actionable recommendations```
### 3. Advanced Stock Analysis### 2. Get Market Data
```bash```python
python yfinance_advanced_trader.py# Get real-time quotes
```get_market_quotes({
"instruments": ["NSE:RELIANCE", "NSE:TCS", "NSE:INFY"]
**Output:**})
- Detailed individual stock analysis
- Complete portfolio analysis with signals# Get historical data
- Multi-stock opportunity scannerget_historical_data({
- Technical indicators for all holdings "symbol": "NSE:RELIANCE",
"from_date": "2024-01-01",
--- "to_date": "2024-12-31",
"interval": "day"
## Usage Examples})
Example 1: Analyze Any Stock
3. Portfolio Analysis
from yfinance_advanced_trader import YFinanceTradingSystem```python
# Calculate portfolio metrics
trader = YFinanceTradingSystem()calculate_portfolio_metrics({
analysis = trader.analyze_stock('RELIANCE') "include_risk_metrics": true,
"include_performance": true,
print(f"Company: {analysis['company']['name']}") "timeframe": "1M"
print(f"Price: ₹{analysis['price']['current']}")})
print(f"Signal: {analysis['signals']['overall']}")
print(f"Score: {analysis['signals']['score']}")# Technical analysis
print(f"\nRecommendation:\n{analysis['recommendation']}")technical_analysis({
``` "symbol": "NSE:RELIANCE",
"indicators": ["RSI", "MACD", "Bollinger", "SMA"],
### Example 2: Scan Your Zerodha Portfolio "period": 20
})
```python```
trader = YFinanceTradingSystem()
portfolio = trader.analyze_portfolio()### 4. Trading Operations
for stock in portfolio:```python
print(f"{stock['symbol']}: {stock['signals']['overall']}")# Place an order
print(f" P&L: ₹{stock['position']['pnl']:.2f} ({stock['position']['pnl_pct']:+.2f}%)")place_order({
print(f" Action: {stock['signals']['action']}") "symbol": "RELIANCE",
``` "exchange": "NSE",
"transaction_type": "BUY",
### Example 3: Find Best Opportunities "order_type": "LIMIT",
"quantity": 10,
```python "price": 2500,
trader = YFinanceTradingSystem() "product": "CNC"
})
# Your watchlist
watchlist = ['RELIANCE', 'TCS', 'INFY', 'HDFCBANK', 'ICICIBANK', 'ITC']# Set stop loss
set_stop_loss({
# Scan for opportunities (minimum score: 3) "symbol": "RELIANCE",
opportunities = trader.scan_for_opportunities(watchlist, min_score=3) "stop_loss_price": 2400,
"quantity": 10
for opp in opportunities:})
print(f"{opp['symbol']}: {opp['signals']['overall']}")```
print(f" Price: ₹{opp['price']['current']} ({opp['price']['change_pct']:+.2f}%)")
print(f" Score: {opp['signals']['score']}")### 5. Strategy Backtesting
---# Backtest a strategy
backtest_strategy({
## Understanding Trading Signals "strategy_name": "SMA_Crossover",
"symbol": "NSE:RELIANCE",
### Signal Strength Scale "start_date": "2024-01-01",
"end_date": "2024-12-31",
| Score | Signal | Meaning | "initial_capital": 100000
|-------|--------|---------|})
| +5 to +7 | **STRONG BUY** | Very bullish - multiple indicators aligned |```
| +2 to +4 | **BUY** | Bullish - good entry opportunity |
| -1 to +1 | **HOLD** | Neutral - wait for clearer signals |## Available Tools
| -2 to -4 | **SELL** | Bearish - consider exit |
| -5 to -7 | **STRONG SELL** | Very bearish - exit recommended |### Authentication
- `initialize_session` - Setup Kite API connection
### Signal Components
### Market Data
Each signal is generated from multiple indicators:- `get_market_quotes` - Real-time market quotes
- `get_historical_data` - Historical OHLC data
- **RSI** - Oversold (<30) = BUY, Overbought (>70) = SELL- `search_instruments` - Find trading instruments
- **MACD** - Above signal line = BUY, Below = SELL
- **Moving Averages** - Price above MAs = BUY, Below = SELL### Trading
- **Bollinger Bands** - Price at lower band = BUY, Upper band = SELL- `place_order` - Place buy/sell orders
- **Stochastic** - <20 = BUY, >80 = SELL- `modify_order` - Modify existing orders
- **Volume** - High volume confirms trend direction- `cancel_order` - Cancel pending orders
---### Analytics
- `calculate_portfolio_metrics` - Portfolio analysis
## Available Tools- `technical_analysis` - Technical indicators
- `check_risk_limits` - Risk assessment
### 1. **yfinance_advanced_trader.py**
**Main trading system with complete analysis**### Strategy
- `backtest_strategy` - Strategy backtesting
Features:- `get_live_signals` - Real-time trading signals
- 15+ technical indicators
- Multi-timeframe trend analysis### Alerts
- Buy/Sell/Hold signals with confidence scores- `setup_price_alert` - Price target alerts
- Portfolio analysis with live P&L
- Opportunity scanner## Configuration Options
Methods:### Risk Management Settings
- `analyze_stock(symbol)` - Complete stock analysis```python
- `analyze_portfolio()` - Analyze all Zerodha holdings{
- `scan_for_opportunities(symbols, min_score)` - Find best trades "max_position_size": 100000, # Maximum position size
- `get_stock_data(symbol, period)` - Historical data with indicators "max_daily_loss": 10000, # Daily loss limit
"max_portfolio_concentration": 20, # Max % in single stock
### 2. **analyze_portfolio.py** "max_leverage": 3.0 # Maximum leverage ratio
**Zerodha portfolio analyzer**}
Features:
-
Holdings breakdown with P&L### Analytics Settings
-
Sector allocation chart```python
-
Performance metrics (win rate, top/worst performers){
-
Risk metrics (concentration, volatility) "enable_streaming": true, # Real-time data streaming
-
Actionable recommendations "enable_analytics": true, # Portfolio analytics
"risk_management": true # Risk checks
3. quick_trade_scan.py}
Fast opportunity scanner```
Features:## Available Resources
-
Quick multi-stock scanning
-
Strong signals only (configurable threshold)Access portfolio and market data through MCP resources:
-
Minimal output for fast decisions
-
Perfect for daily market scans-
zerodha://profile- User profile and account info -
zerodha://portfolio- Holdings and positions
---- zerodha://orders - Order book
zerodha://positions- Current positions
Technical Indicators Explained- zerodha://margins - Available margins
zerodha://analytics/portfolio- Portfolio analytics
Moving Averages (SMA/EMA)- zerodha://analytics/risk - Risk analysis
-
SMA 20 - Short-term trend-
zerodha://market/quotes- Market quotes -
SMA 50 - Medium-term trend
-
SMA 200 - Long-term trend## Testing & Development
-
EMA 12/26 - Used for MACD calculation
Run Tests
Momentum Indicators```bash
-
RSI - Relative Strength Index (0-100)pytest tests/
-
<30 = Oversold (potential buy)```
-
>70 = Overbought (potential sell)
-
Development Mode
-
MACD - Moving Average Convergence Divergence```bash
-
MACD > Signal = Bullish# Install in development mode
-
MACD < Signal = Bearishpip install -e .[dev]
-
-
Stochastic Oscillator - %K and %D lines# Run with debug logging
-
<20 = Oversoldexport LOG_LEVEL=DEBUG
-
>80 = Overboughtpython -m zerodha_mcp_server
-
### Volatility Indicators
- **Bollinger Bands** - Price volatility bands### Code Formatting
- Price near lower band = Potential buy```bash
- Price near upper band = Potential sell# Format code
black src/
- **ATR** - Average True Rangeisort src/
- Used for stop-loss calculation
- Higher ATR = Higher volatility# Type checking
mypy src/
### Volume Indicators```
- **Volume Ratio** - Current vs 20-day average
- >1.5 = High volume (confirms trend)## Security Best Practices
- **OBV** - On-Balance Volume1. **Never commit API credentials** to version control
- Tracks volume flow2. **Use environment variables** for sensitive data
3. **Enable 2FA** on your Zerodha account
---4. **Monitor API usage** regularly
5. **Use paper trading** for testing strategies
## Risk Management6. **Review risk limits** before live trading
### Automatic Position Sizing## Performance Optimization
The system calculates safe position sizes based on:- **Connection pooling** for API requests
- **Async operations** for parallel processing
```python- **Data caching** for frequently accessed data
Risk per trade = 2% of capital (configurable)- **WebSocket streaming** for real-time updates
Risk per share = Entry Price - Stop Loss- **Efficient data structures** for large datasets
Position Size = (Capital × Risk%) / Risk per share
Max Position = 50% of total capital## Troubleshooting
Common Issues
Stop Loss Calculation
- Authentication Failed
Stop Loss = Entry Price - (2 × ATR) - Verify access token validity
``` - Ensure proper environment variables
This ensures stops are placed based on market volatility.2. **Rate Limiting**
- Kite API has rate limits
### Risk-Reward Ratio - Implement request throttling
- Use WebSocket for real-time data
```python
R:R = (Target - Entry) / (Entry - Stop Loss)3. **Data Parsing Errors**
``` - Verify instrument symbols format
- Check date format (YYYY-MM-DD)
Recommended minimum: 1:2 (risk ₹1 to make ₹2) - Validate numerical inputs
---### Debug Mode
```bash
## Trading Strategies# Enable debug logging
export LOG_LEVEL=DEBUG
### 1. Momentum Strategypython -m zerodha_mcp_server
- Buy when: RSI < 40, MACD > Signal, Price > SMA20```
- Sell when: RSI > 60, MACD < Signal, Price < SMA20
- Best for: Trending markets## Contributing
### 2. Mean Reversion Strategy1. Fork the repository
- Buy when: Price touches lower Bollinger Band2. Create a feature branch (`git checkout -b feature/amazing-feature`)
- Sell when: Price touches upper Bollinger Band3. Commit your changes (`git commit -m 'Add amazing feature'`)
- Best for: Range-bound markets4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
### 3. Breakout Strategy
- Buy when: Price breaks resistance with high volume## License
- Sell when: Price breaks support
- Best for: Volatile stocksThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---## Disclaimer
## Project Structure**This software is for educational and research purposes only. Trading in financial markets involves substantial risk of loss. The authors and contributors are not responsible for any financial losses incurred from using this software. Always test strategies thoroughly before using real money.**
```## Resources
SNOWFLAKE_MCP_SERVER/
├── yfinance_advanced_trader.py # Main trading system - [Zerodha Kite API Documentation](https://kite.trade/docs/)
├── analyze_portfolio.py # Portfolio analyzer- [Model Context Protocol](https://modelcontextprotocol.io/)
├── quick_trade_scan.py # Fast opportunity scanner- [MCP Python SDK](https://github.com/modelcontextprotocol/create-python-server)
├── zerodha_mcp_server.py # MCP server for Copilot- [GitHub Copilot Documentation](https://docs.github.com/en/copilot)
├── generate_tokens.py # Token generation utility
├── verify_tokens.py # Token verification## Support
├── .env # Your credentials (DO NOT COMMIT)
├── .env.example # Example configurationFor support and questions:
├── ADVANCED_TRADING_GUIDE.md # Detailed documentation
├── TRADING_TOOLS_SUMMARY.txt # Quick reference1. Check the [FAQ section](#troubleshooting)
└── README.md # This file2. Search [existing issues](../../issues)
```3. Create a [new issue](../../issues/new)
4. Join our [Discord community](#) (coming soon)
---
---
## Security Best Practices
**Built with for the trading community**
1. **Never commit `.env` file** - Contains sensitive API keys
2. **Regenerate tokens daily** - Zerodha tokens expire every 24 hours** Star this repository if you find it useful!**
3. **Test with paper trading** - Validate strategies before live trading
4. **Monitor API usage** - Check for unusual activity
5. **Use 2FA** - Enable on your Zerodha account
---
## Troubleshooting
### Issue: "No data available for symbol"
**Solution:** Check symbol format
- NSE stocks: Add `.NS` suffix (e.g., `RELIANCE.NS`)
- BSE stocks: Add `.BO` suffix (e.g., `RELIANCE.BO`)
### Issue: "Incorrect api_key or access_token"
**Solution:** Regenerate tokens
```bash
python generate_tokens.py
Tokens expire daily and need refresh.
Issue: "Import Error: No module named 'yfinance'"
Solution: Install dependencies
pip install yfinance pandas numpy scipy scikit-learn matplotlib plotly
Issue: Analysis shows old data
Solution: yfinance caches data. Clear cache:
import yfinance as yf
yf.cache.clear()
Documentation
- - Complete API reference
- - Quick reference guide
- - Copilot integration
- - Getting started guide
Real-World Example
Here's what you get when you run the portfolio analyzer:
================================================================================
ZERODHA PORTFOLIO ANALYSIS
================================================================================
Account: Vinay Vilas Muraskar (UQN141)
PORTFOLIO SUMMARY:
Total Holdings: 6
Total Investment: ₹1,499.49
Current Value: ₹1,448.80
Total P&L: ₹-50.69 (-3.38%)
HOLDINGS WITH SIGNALS:
TATASTEEL: +2.73% | Signal: HOLD (Score: 1)
ETERNAL: -8.45% | Signal: HOLD (Score: 1)
IOB: -2.10% | Signal: SELL (Score: -2)
NTPCGREEN: -1.90% | Signal: SELL (Score: -4)
RECOMMENDATIONS:
Consider exiting IOB and NTPCGREEN (SELL signals)
TATASTEEL showing strength - monitor for adding
================================================================================
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the file for details.
Disclaimer
This software is for educational purposes only. Trading involves substantial risk of loss. The authors are not responsible for any financial losses. Always do your own research and test strategies thoroughly before trading with real money.
Star History
If you find this project useful, please star it on GitHub!
Support
For issues and questions:
- Check the Troubleshooting section
- Read the Documentation
- Open an on GitHub
Built with for traders
**Happy Trading! **