PHPackages                             nishantwebdev/nse-stock-data-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. nishantwebdev/nse-stock-data-php

ActiveLibrary[API Development](/categories/api)

nishantwebdev/nse-stock-data-php
================================

A comprehensive PHP library for accessing NSE (National Stock Exchange) India stock market data

v1.0.2(7mo ago)06MITPHPPHP ^8.0

Since Sep 23Pushed 7mo agoCompare

[ Source](https://github.com/nishantwebdev/nse-stock-data-php)[ Packagist](https://packagist.org/packages/nishantwebdev/nse-stock-data-php)[ RSS](/packages/nishantwebdev-nse-stock-data-php/feed)WikiDiscussions nse-stock-data-package Synced 1mo ago

READMEChangelog (2)Dependencies (3)Versions (4)Used By (0)

NSE India API - PHP Library
===========================

[](#nse-india-api---php-library)

A comprehensive PHP library for accessing NSE (National Stock Exchange) India stock market data. This library provides easy-to-use methods to fetch real-time and historical stock data, and more.

Features
--------

[](#features)

- **Real-time Stock Data**: Get current prices, volume, and market data
- **Historical Data**: Fetch historical stock prices and trading data
- **Holiday Calendar**: Check trading holidays and market status
- **Intraday Data**: Access real-time intraday price movements

Installation
------------

[](#installation)

### Using Composer (Recommended)

[](#using-composer-recommended)

```
composer require nishantwebdev/nse-stock-data-php
```

### Manual Installation

[](#manual-installation)

1. Clone this repository:

```
git clone https://github.com/nishantwebdev/nse-stock-data-php.git
cd nse-stock-data-php
```

2. Install dependencies:

```
composer install
```

Quick Start
-----------

[](#quick-start)

```
use NseData\StockClient;
use NseData\DateRange;

// Initialize the NSE client
$nse = new StockClient();

try {
    // Get equity details for a stock
    $equityDetails = $nse->getEquityDetails('TCS');
    echo "Company: " . $equityDetails->info->companyName . "\n";
    echo "Last Price: ₹" . $equityDetails->priceInfo->lastPrice . "\n";
    echo "Change: " . $equityDetails->priceInfo->change . " (" . $equityDetails->priceInfo->pChange . "%)\n";

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
```

Usage Examples
--------------

[](#usage-examples)

### Main Methods

[](#main-methods)

#### `getEquityDetails(string $symbol): EquityDetails`

[](#getequitydetailsstring-symbol-equitydetails)

Get comprehensive equity information including price, volume, and company details.

#### `getEquityHistoricalData(string $symbol, DateRange $range): array`

[](#getequityhistoricaldatastring-symbol-daterange-range-array)

Get historical stock data for a specified date range.

#### `getEquityIntradayData(string $symbol, bool $isPreOpenData = false): IntradayData`

[](#getequityintradaydatastring-symbol-bool-ispreopendata--false-intradaydata)

Get real-time intraday price data.

#### `getIndexOptionChain(string $indexSymbol): OptionChainData`

[](#getindexoptionchainstring-indexsymbol-optionchaindata)

Get option chain data for indices (NIFTY, BANKNIFTY, etc.).

#### `getEquityOptionChain(string $symbol): OptionChainData`

[](#getequityoptionchainstring-symbol-optionchaindata)

Get option chain data for individual stocks.

#### `getDerivativeData(string $symbol): array`

[](#getderivativedatastring-symbol-array)

Get futures and options data for a stock.

#### `checkHoliday(DateTime $date): bool`

[](#checkholidaydatetime-date-bool)

Check if a given date is a trading holiday.

#### `getAllStockSymbols(): array`

[](#getallstocksymbols-array)

Get list of all available stock symbols.

#### `getHolidayData(): array`

[](#getholidaydata-array)

Get holiday data for the current year (cached automatically).

#### `getHolidayDataForYear(int $year): array`

[](#getholidaydataforyearint-year-array)

Get holiday data for a specific year.

#### `clearHolidayCache(?int $year = null): bool`

[](#clearholidaycacheint-year--null-bool)

Clear holiday cache for a specific year or all years.

### Complete Method Documentation

[](#complete-method-documentation)

#### Holiday and Market Status Methods

[](#holiday-and-market-status-methods)

##### `checkHoliday(DateTime $date): bool`

[](#checkholidaydatetime-date-bool-1)

Check if a given date is a trading holiday. Returns `true` if the date is a holiday (weekend or trading holiday), `false` otherwise.

**Parameters:**

- `$date` (DateTime): The date to check

**Returns:** bool - `true` if holiday, `false` if trading day

**Example:**

```
$testDate = new DateTime('2024-01-26'); // Republic Day
$isHoliday = $nse->checkHoliday($testDate);
echo "Is " . $testDate->format('Y-m-d') . " a holiday? " . ($isHoliday ? 'Yes' : 'No');
```

##### `getMarketStatus(): MarketStatus`

[](#getmarketstatus-marketstatus)

Get current market status including market state, trade date, and other market information.

**Returns:** MarketStatus - Object containing market status details

**Example:**

```
$marketStatus = $nse->getMarketStatus();
```

#### Index Methods

[](#index-methods)

##### `getAllIndices(): array`

[](#getallindices-arrayindex)

Get all available market indices with their current values and changes.

**Returns:** array - Array of Index objects containing index information

**Example:**

```
$indices = $nse->getAllIndices();
```

##### `getEquityStockIndices(string $index): IndexDetails`

[](#getequitystockindicesstring-index-indexdetails)

Get detailed information for a specific equity stock index.

**Parameters:**

- `$index` (string): The index symbol (e.g., 'NIFTY 50', 'BANK NIFTY')

**Returns:** IndexDetails - Object containing detailed index information

**Example:**

```
$niftyDetails = $nse->getEquityStockIndices('NIFTY 50');
```

#### Equity Information Methods

[](#equity-information-methods)

##### `getEquityDetails(string $symbol): EquityDetails`

[](#getequitydetailsstring-symbol-equitydetails-1)

Get comprehensive equity information including price, volume, company details, and market data.

**Parameters:**

- `$symbol` (string): Stock symbol (e.g., 'TCS', 'RELIANCE')

**Returns:** EquityDetails - Object containing complete equity information

**Example:**

```
$equityDetails = $nse->getEquityDetails('TCS');
echo "Company: " . $equityDetails->info->companyName;
echo "Last Price: ₹" . $equityDetails->priceInfo->lastPrice;
echo "Change: " . $equityDetails->priceInfo->change;
```

##### `getEquityTradeInfo(string $symbol): EquityTradeInfo`

[](#getequitytradeinfostring-symbol-equitytradeinfo)

Get detailed trade information for a specific equity including volume, value, and trade statistics.

**Parameters:**

- `$symbol` (string): Stock symbol

**Returns:** EquityTradeInfo - Object containing trade information

**Example:**

```
$tradeInfo = $nse->getEquityTradeInfo('TCS');
```

##### `getEquityCorporateInfo(string $symbol): EquityCorporateInfo`

[](#getequitycorporateinfostring-symbol-equitycorporateinfo)

Get corporate information for a specific equity including company details, announcements, and corporate actions.

**Parameters:**

- `$symbol` (string): Stock symbol

**Returns:** EquityCorporateInfo - Object containing corporate information

**Example:**

```
$corporateInfo = $nse->getEquityCorporateInfo('TCS');
```

##### `getEquityIntradayData(string $symbol, bool $isPreOpenData = false): IntradayData`

[](#getequityintradaydatastring-symbol-bool-ispreopendata--false-intradaydata-1)

Get real-time intraday price data for a specific equity.

**Parameters:**

- `$symbol` (string): Stock symbol
- `$isPreOpenData` (bool, optional): Whether to fetch pre-open market data (default: false)

**Returns:** IntradayData - Object containing intraday price data

**Example:**

```
// Regular intraday data
$intradayData = $nse->getEquityIntradayData('TCS');

// Pre-open market data
$preOpenData = $nse->getEquityIntradayData('TCS', true);
```

#### Historical Data Methods

[](#historical-data-methods)

##### `getEquityHistoricalData(string $symbol, DateRange $range = null): array`

[](#getequityhistoricaldatastring-symbol-daterange-range--null-arrayequityhistoricaldata)

Get historical stock data for a specified date range. If no range is provided, defaults to the last month.

**Parameters:**

- `$symbol` (string): Stock symbol
- `$range` (DateRange, optional): Date range for historical data

**Returns:** array - Array of historical data objects

**Example:**

```
use NseData\DateRange;

$startDate = new DateTime('2024-01-01');
$endDate = new DateTime('2024-01-31');
$dateRange = new DateRange(['start' => $startDate, 'end' => $endDate]);

$historicalData = $nse->getEquityHistoricalData('TCS', $dateRange);

foreach ($historicalData as $data) {
    foreach ($data->data as $record) {
        echo "Date: " . $record->CH_TIMESTAMP;
        echo "Open: ₹" . $record->CH_OPENING_PRICE;
        echo "High: ₹" . $record->CH_TRADE_HIGH_PRICE;
        echo "Low: ₹" . $record->CH_TRADE_LOW_PRICE;
        echo "Close: ₹" . $record->CH_CLOSING_PRICE;
        echo "Volume: " . $record->CH_TOT_TRADED_QTY;
    }
}
```

##### `getEquityPriceByDate(string $symbol, DateTime $date): int|float`

[](#getequitypricebydatestring-symbol-datetime-date-intfloat)

Get the closing price of a stock for a specific date. If the date is a holiday, returns the price from the last trading day.

**Parameters:**

- `$symbol` (string): Stock symbol
- `$date` (DateTime): The date to get price for

**Returns:** int|float - The closing price for the specified date

**Throws:** Exception if no data is found for the given date

**Example:**

```
$priceDate = new DateTime('2024-01-15');
$price = $nse->getEquityPriceByDate('TCS', $priceDate);
echo "TCS price on " . $priceDate->format('Y-m-d') . ": ₹" . $price;
```

##### `getIndexHistoricalData(string $index, DateRange $range): array`

[](#getindexhistoricaldatastring-index-daterange-range-arrayindexhistoricaldata)

Get historical data for a specific index over a date range.

**Parameters:**

- `$index` (string): Index symbol (e.g., 'NIFTY 50', 'BANK NIFTY')
- `$range` (DateRange): Date range for historical data

**Returns:** array - Array of historical index data

**Example:**

```
use NseData\DateRange;

$startDate = new DateTime('2024-01-01');
$endDate = new DateTime('2024-01-31');
$dateRange = new DateRange(['start' => $startDate, 'end' => $endDate]);

$indexData = $nse->getIndexHistoricalData('NIFTY 50', $dateRange);
```

#### Holiday Data Management Methods

[](#holiday-data-management-methods)

##### `getHolidayData(): array`

[](#getholidaydata-array-1)

Get holiday data for the current year. Data is automatically cached to improve performance.

**Returns:** array - Array of holiday dates in 'd-M-Y' format

**Example:**

```
$holidays = $nse->getHolidayData();
foreach ($holidays as $holiday) {
    echo "Holiday: " . $holiday;
}
```

##### `clearHolidayCache(?int $year = null): bool`

[](#clearholidaycacheint-year--null-bool-1)

Clear cached holiday data for a specific year or all years.

**Parameters:**

- `$year` (int|null, optional): Year to clear cache for. If null, clears all cached data.

**Returns:** bool - `true` if cache was cleared successfully

**Example:**

```
// Clear cache for specific year
$nse->clearHolidayCache(2024);

// Clear all cached holiday data
$nse->clearHolidayCache();
```

Data Models
-----------

[](#data-models)

The library provides strongly-typed data models for all API responses:

- `EquityDetails`: Complete equity information
- `EquityHistoricalData`: Historical price data
- `OptionChainData`: Option chain information
- `IntradayData`: Real-time price data
- `DateRange`: Date range specification

Error Handling
--------------

[](#error-handling)

The library throws exceptions for various error conditions:

```
try {
    $equityDetails = $nse->getEquityDetails('INVALID_SYMBOL');
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

Rate Limiting
-------------

[](#rate-limiting)

The library includes built-in rate limiting and connection management to respect NSE's API limits. It automatically handles:

- Connection pooling
- Request throttling
- Cookie management
- Retry logic

Requirements
------------

[](#requirements)

- PHP 8.0 or higher

Examples
--------

[](#examples)

Check the `examples/` directory for more detailed usage examples:

- `basic_usage.php`: Basic stock data retrieval
- `historical_data.php`: Historical data analysis
- `option_chain_analysis.php`: Option chain analysis

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Disclaimer
----------

[](#disclaimer)

This library is for educational and research purposes. Please ensure compliance with NSE's terms of service and applicable regulations when using this library for commercial purposes.

Support
-------

[](#support)

For issues and questions:

- Create an issue on GitHub
- Check the examples directory

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for a list of changes and version history.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance62

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

237d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9cbb3eff2cce38cac9d91bea36e21e4ecee5fa7565368be745ff432a1088e434?d=identicon)[nishantwebdev](/maintainers/nishantwebdev)

---

Top Contributors

[![nishantwebdev](https://avatars.githubusercontent.com/u/24542622?v=4)](https://github.com/nishantwebdev "nishantwebdev (7 commits)")

---

Tags

apiphp-sdkfinanceindiatradingstockmarketnsestock-datanse-indianse-india-stock-data

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nishantwebdev-nse-stock-data-php/health.svg)

```
[![Health](https://phpackages.com/badges/nishantwebdev-nse-stock-data-php/health.svg)](https://phpackages.com/packages/nishantwebdev-nse-stock-data-php)
```

###  Alternatives

[scheb/yahoo-finance-api

PHP library for accessing Yahoo Finance data

318204.8k5](/packages/scheb-yahoo-finance-api)[smodav/mpesa

M-Pesa API implementation

16363.7k1](/packages/smodav-mpesa)[bunq/sdk_php

bunq PHP SDK

89222.7k2](/packages/bunq-sdk-php)[jeffreyhyer/alpaca-trade-api-php

PHP SDK for the Alpaca trade API

285.0k](/packages/jeffreyhyer-alpaca-trade-api-php)[signnow/api-php-sdk

Library to communicate with SignNow API

11138.0k](/packages/signnow-api-php-sdk)[leapfu/cloud-printer

高扩展性云小票打印SDK，支持飞鹅云、芯烨云、易联云、快递100、映美云、佳博云、中午云、优声云等主流云打印服务，兼容 Laravel、ThinkPHP 等主流框架，统一API，易集成，易扩展。

104.5k](/packages/leapfu-cloud-printer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
