National Stock Exchange - India (Unofficial)
A comprehensive package and API server for accessing equity/index details and historical data from the National Stock Exchange of India. This project provides both an NPM package for direct integration and a full-featured GraphQL/REST API server.
📚 Documentation | 🚀 Examples
✨ Features
- 📦 NPM Package - Direct integration into your Node.js projects
- 🔌 GraphQL API - Modern GraphQL interface with Apollo Server
- 🌐 REST API - Comprehensive REST endpoints with Swagger documentation
- 🤖 MCP Server - Model Context Protocol server for AI assistants
- 💻 CLI Tool - Command-line interface for quick data access
- 🐳 Docker Support - Containerized deployment
- 🔒 CORS Configuration - Configurable cross-origin resource sharing
- 📊 Real-time Data - Live market data and historical information
- 📈 Multiple Data Types - Equity, Index, Commodity, and Options data
🚀 Quick Start
⚠️ Prerequisites: Node.js 18+ required
As an NPM Package
npm install stock-nse-india
import { NseIndia } from "stock-nse-india";
const nseIndia = new NseIndia();
// Get all stock symbols
const symbols = await nseIndia.getAllStockSymbols();
console.log(symbols);
// Get equity details
const details = await nseIndia.getEquityDetails('IRCTC');
console.log(details);
// Get historical data
const range = {
start: new Date("2020-01-01"),
end: new Date("2023-12-31")
};
const historicalData = await nseIndia.getEquityHistoricalData('IRCTC', range);
console.log(historicalData);
As an API Server
# Clone and setup
git clone https://github.com/hi-imcodeman/stock-nse-india.git
cd stock-nse-india
npm install
# Start the server
npm start
🌐 Server URLs:
- Main App: http://localhost:3000
- GraphQL Playground: http://localhost:3000/graphql
- API Documentation: http://localhost:3000/api-docs
📦 Installation
Prerequisites
- Node.js: Version 18 or higher
- npm: Version 8 or higher (comes with Node.js 18+)
NPM Package
npm install stock-nse-india
# or
yarn add stock-nse-india
CLI Tool
npm install -g stock-nse-india
Server Setup
git clone https://github.com/hi-imcodeman/stock-nse-india.git
cd stock-nse-india
npm install
npm start
🔌 GraphQL API
The project now includes a powerful GraphQL API for flexible data querying:
Example Queries
# Get equity information
query GetEquity {
equities(symbolFilter: { symbols: ["IRCTC", "RELIANCE"] }) {
symbol
details {
info {
companyName
industry
isFNOSec
}
metadata {
listingDate
status
}
}
}
}
# Get indices data
query GetIndices {
indices(filter: { filterBy: "NIFTY" }) {
key
index
last
variation
percentChange
}
}
GraphQL Schema
The API includes schemas for:
- Equity - Stock information, metadata, and details
- Indices - Market index data and performance
- Filters - Flexible query filtering options
🤖 MCP Server
The project includes a Model Context Protocol (MCP) server that allows AI assistants to access NSE India stock market data:
What is MCP?
Model Context Protocol (MCP) is a standard for AI assistants to communicate with external data sources and tools. This MCP server exposes all NSE India functions as tools that AI models can use.
Architecture
The MCP implementation is built with a modular architecture for maintainability and consistency:
src/mcp/mcp-tools.ts: Common tools configuration and handler functions shared across all implementationssrc/mcp/server/mcp-server.ts: Stdio-based MCP server for local AI assistant integrationsrc/mcp/client/mcp-client.ts: OpenAI Functions-based MCP client for natural language queries
All components share the same tool definitions and business logic, ensuring consistency and making maintenance easier.
Benefits of Common Tools Configuration
- 🔄 Consistency: All server implementations use identical tool definitions and behavior
- 🛠️ Maintainability: Single source of truth for tool configurations and business logic
- 📝 Easy Updates: Add new tools or modify existing ones in one place
- 🧪 Testing: Unified testing approach across all server implementations
- 📚 Documentation: Centralized tool documentation and examples
Available Tools
The MCP server provides 30 tools covering:
- Equity Data - Stock details, trade info, corporate info, intraday data, historical data, technical indicators
- Index Data - Market indices, intraday data, option chains, contract information
- Market Data - Market status, turnover, pre-open data, all indices
- Reports - Circulars, daily reports for capital/derivatives/debt markets
- Commodity Data - Option chain data for commodities
- Analysis Tools - Top gainers/losers, most active equities
OpenAI Functions MCP Client
The project includes an advanced MCP client that uses OpenAI's native function calling feature for intelligent query processing:
Features
- 🤖 Natural Language Processing: Query data using plain English
- 🔧 Automatic Tool Selection: AI intelligently chooses the right NSE API tools
- 📊 Real-time Data: Access live market data, historical information, and more
- 🎯 Smart Parameter Extraction: Automatically extracts symbols, dates, and other parameters
- 📈 Comprehensive Coverage: Access to all 30 NSE India API endpoints
- 🔄 Multiple Query Types: Support for both simple and complex multi-step queries
Query Methods
processQuery(): Single-round query processing for straightforward requestsprocessQueryWithMultipleFunctions(): Multi-step query processing for complex analysis
Example Usage
import { mcpClient } from './mcp/client/mcp-client'
// Simple query
const response = await mcpClient.processQuery({
query: "What is the current price of TCS stock?",
model: "gpt-4o-mini"
})
// Complex multi-step query
const complexResponse = await mcpClient.processQueryWithMemory({
query: "Compare the performance of Reliance and TCS over the last month and analyze their trends"
})
Usage
Standard I/O (stdio) Server
# Start the stdio MCP server
npm run start:mcp
# Test the stdio MCP server
npm run test:mcp
Configuration
Option 1: Using npx (Recommended for users who have installed the package)
Installation Steps:
-
Prerequisites: Ensure Node.js 18+ is installed on your system
node --version # Should be v18.0.0 or higher -
Install the package (optional but recommended for faster startup):
npm install -g stock-nse-indiaNote: If you don't install globally,
npxwill automatically download and cache the package on first use, which may take a few moments.
Configuration:
{
"mcpServers": {
"npx-stock-nse-india": {
"command": "npx",
"args": ["stock-nse-india", "mcp"],
"env": {
"NODE_ENV": "production"
}
}
}
}
Option 2: Using local build (For developers with source code)
{
"mcpServers": {
"nse-india-stdio": {
"command": "node",
"args": ["build/mcp/server/mcp-server-stdio.js"],
"env": {
"NODE_ENV": "production"
}
}
}
}
Configuring in Cursor IDE
- Open Cursor Settings: Press
Cmd+,(Mac) orCtrl+,(Windows/Linux) to open settings - Navigate to MCP Settings: Go to Settings → Features → Model Context Protocol
- Add Server Configuration: Add either of the configurations above to your MCP settings
- Restart Cursor: Restart Cursor IDE to load the MCP server
Alternatively, you can directly edit the Cursor configuration file:
- Mac/Linux:
~/.cursor/mcp.jsonor in your workspace settings - Windows:
%APPDATA%\Cursor\mcp.json
After configuration, the MCP server will be available in Cursor's AI assistant, allowing you to query NSE India stock market data directly from the chat interface.
For detailed MCP documentation, see MCP_README.md.
🌐 REST API
Comprehensive REST endpoints with automatic Swagger documentation:
Core Endpoints
GET /- Market statusGET /api/marketStatus- Market status informationGET /api/glossary- NSE glossaryGET /api/equity/:symbol- Equity detailsGET /api/equity/:symbol/historical- Historical dataGET /api/indices- Market indicesGET /api-docs- Interactive API documentation
MCP Client Endpoints
POST /api/mcp/query- Natural language query using OpenAI FunctionsPOST /api/mcp/query-multiple- Multi-step natural language queries
API Documentation
Visit http://localhost:3000/api-docs for complete interactive API documentation powered by Swagger UI.
💻 CLI Usage
Basic Commands
# Get help
nseindia --help
# Get market status
nseindia
# Get equity details
nseindia equity IRCTC
# Get historical data
nseindia historical IRCTC
# Get indices information
nseindia index
# Get specific index details
nseindia index "NIFTY AUTO"
CLI Features
- Real-time data - Live market information
- Historical analysis - Historical price data
- Index tracking - Market index performance
- Interactive charts - ASCII-based data visualization
🐳 Docker
Quick Start
# Pull and run from Docker Hub
docker run --rm -d -p 3001:3001 imcodeman/nseindia
# Or build locally
docker build -t nseindia . && docker run --rm -d -p 3001:3001 nseindia:latest
Docker Hub
Image: imcodeman/nseindia
Registry: Docker Hub
Container URLs
- Main App: http://localhost:3001
- GraphQL: http://localhost:3001/graphql
- API Docs: http://localhost:3001/api-docs
⚙️ Configuration
Environment Variables
# Server Configuration
PORT=3000
HOST_URL=http://localhost:3000
NODE_ENV=development
# CORS Configuration
CORS_ORIGINS=https://myapp.com,https://admin.myapp.com
CORS_METHODS=GET,POST,OPTIONS
CORS_HEADERS=Content-Type,Authorization,X-Requested-With
CORS_CREDENTIALS=true
CORS Settings
- Origins: Comma-separated list of allowed domains
- Methods: HTTP methods (default: GET,POST,PUT,DELETE,OPTIONS)
- Headers: Allowed request headers
- Credentials: Enable/disable credentials (default: true)
- Localhost: Always allowed for development
📊 API Methods
Core Methods
getAllStockSymbols()- Get all NSE stock symbolsgetData()- Generic data retrievalgetDataByEndpoint()- Get data by specific NSE API endpoints
Equity Methods
getEquityDetails(symbol)- Get equity informationgetEquityHistoricalData(symbol, range)- Historical price datagetEquityIntradayData(symbol)- Intraday trading datagetEquityOptionChain(symbol)- Options chain datagetEquityCorporateInfo(symbol)- Corporate informationgetEquityTradeInfo(symbol)- Trading statistics
Index Methods
getEquityStockIndices()- Get all market indicesgetIndexIntradayData(index)- Index intraday datagetIndexOptionChain(index)- Index options datagetIndexOptionChainContractInfo(indexSymbol)- Get option chain contract information (expiry dates and strike prices)
Commodity Methods
getCommodityOptionChain(symbol)- Commodity options data
Helper Methods
getGainersAndLosersByIndex(index)- Top gainers and losersgetMostActiveEquities()- Most actively traded stocks
🏃♂️ Development
⚠️ Prerequisites: Node.js 18+ required
Local Development
# Clone repository
git clone https://github.com/hi-imcodeman/stock-nse-india.git
cd stock-nse-india
# Install dependencies
npm install
# Development mode with auto-reload
npm run start:dev
# Build project
npm run build
# Run tests
npm test
# Generate documentation
npm run docs
Development Scripts
npm start- Start production servernpm run start:dev- Development mode with auto-reloadnpm run build- Build TypeScript to JavaScriptnpm test- Run test suite with coveragenpm run docs- Generate TypeDoc documentationnpm run lint- Run ESLint
MCP Scripts
npm run start:mcp- Start stdio MCP servernpm run test:mcp- Test stdio MCP server
🧪 Testing
# Run all tests
npm test
# Run tests with coverage
npm test -- --coverage
# Run specific test file
npm test -- utils.spec.ts
📚 Documentation
- 📖 API Reference - Complete API documentation
- 🔍 Examples - Code examples and use cases
- 📋 Interfaces - TypeScript interface definitions
- 🏗️ Modules - Module documentation
🤝 Contributing
We welcome contributions! Please see our contributing guidelines and feel free to submit issues and pull requests.
Development Setup
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👥 Contributors
🔗 Links
- 🌐 Website: https://hi-imcodeman.github.io/stock-nse-india
- 📦 NPM: https://www.npmjs.com/package/stock-nse-india
- 🐳 Docker Hub: https://hub.docker.com/r/imcodeman/nseindia
- 🐛 Issues: https://github.com/hi-imcodeman/stock-nse-india/issues
⭐ Star this repository if you find it helpful!
