APIs9 min read

PHP Stock Market API for India: NSE and BSE Data in Laravel

By Deion DSouza
PHP and Laravel code fetching NSE and BSE company announcements through the Drishti SDK

A PHP stock market API for India should hand you National Stock Exchange of India (NSE) and BSE company data as plain PHP arrays, from a Composer package you can bind once in Laravel's service container. Drishti's PHP software development kit (SDK), manasija/drishti-sdk, covers announcements, earnings, concalls, news and alerts over REST (plain HTTP request and response) and WebSocket (a persistent live connection). Below: install, a first call, then a scheduled Artisan command that stores new filings and emails your team.

Drishti is our product, so weigh that when you read this comparison.

Key takeaways

  • Install with composer require manasija/drishti-sdk. It needs PHP 8.2+ and works with Guzzle 7 or Guzzle 8.
  • Every endpoint is a method with camelCase named arguments, such as getAnnouncements(symbols: [...], from: ...), and returns an associative array.
  • Bind DrishtiClient as a singleton and read the key from config('services.drishti.key'), which reads DRISHTI_API_KEY from .env.
  • Catch Drishti\Exception\DrishtiApiException for API errors; the client already retries 408, 409, 425, 429, 500, 502, 503 and 504 responses.
  • Live streams need a long-running command-line process under Supervisor, not a PHP-FPM (FastCGI Process Manager) request.

On this page

Choosing a PHP stock market API for India

Start with the data your app needs. Tick and OHLC (open, high, low, close) prices, company filings and research screens are different products.

If your build needsConsiderWhy it may fitCheck before choosing
Company announcements, earnings, concalls and news as structured data in PHPDrishtiPHP SDK on Packagist, REST and WebSocket, AI summaries and extracted fieldsPlan symbol limits; Sandbox has no WebSocket
Real-time tick and historical prices for NSE, BSE and Multi Commodity Exchange (MCX)TrueDataAuthorised vendor with WebSocket, TCP and REST APIs (JSON)API pricing not published; redistribution needs exchange approval
Real-time, delayed or historical prices with PHP sample codeGlobal DatafeedsAuthorised vendor with WebSocket, REST and Financial Information eXchange (FIX); PHP sample codePricing on request; confirm the product's update rate
A research and alerts UI for your own investingTijori FinanceFilings timeline, results, screener and alerts; free to ₹3,500/yearPublic developer APIs limited; no self-serve SDK
Screeners, scores and Excel workflowsTrendlyneDVM (durability, valuation, momentum) scores, alerts and Excel Connect; business-to-business data for brokeragesNo self-serve public API docs found
Ready-made scans for results, announcements and initial public offerings (IPOs)StockScansScans, watchlists and Research AI; data from CMOTS; free tierNo public developer API listed

This is a product-fit comparison, not a ranking. If you need to place orders, use a broker API such as Kite Connect, Upstox or DhanHQ.

Drishti is an independent market-intelligence API built on official exchange-backed sources. It does not scrape NSE or BSE websites. Drishti does not provide tick-by-tick prices or submit orders, so pair it with a price vendor when a page needs live quotes.

Install the SDK with Composer

The package declares php >=8.2, ext-json and guzzlehttp/guzzle ^7.8 || ^8.0, so it fits an existing Laravel 12 or 13 app without a Guzzle upgrade. Install it and add the key to .env:

Code
composer require manasija/drishti-sdk
echo "DRISHTI_API_KEY=your-key-from-the-dashboard" >> .env

Keep the key on the server, never in Blade templates or front-end JavaScript.

Make your first NSE API PHP call

Check the response shape from a plain script first. This fetches seven days of announcements for two NSE symbols:

Code
<?php
require __DIR__ . '/vendor/autoload.php';

use Drishti\DrishtiClient;

$client = new DrishtiClient(apiKey: getenv('DRISHTI_API_KEY'));

$result = $client->getAnnouncements(
    symbols: ['RELIANCE', 'TCS'],
    from: gmdate('Y-m-d', strtotime('-7 days')),
    limit: 20,
);

foreach ($result['data'] as $row) {
    printf("%s %-10s %s\n", $row['date'], $row['symbol'], $row['category']);
    echo '  ', $row['summary'], "\n";
}

echo $result['has_next'] ? "More pages available\n" : "Done\n";

The array matches the announcements API reference: data plus has_next. Rows carry id, symbol, company_name, date (ingestion time, UTC), summary and category. A basic row costs 1 credit; detailed: true costs 2 and adds long_summary and extracted_information.

Laravel stock market API setup

Register one client for the whole app. The constructor rejects a blank key with InvalidArgumentException, so a missing .env value fails loudly at the first resolve instead of sending unauthenticated requests.

Code
// config/services.php
'drishti' => [
    'key' => env('DRISHTI_API_KEY'),
    'watchlist' => explode(',', env('DRISHTI_WATCHLIST', 'RELIANCE,TCS,INFY')),
    'alert_email' => env('DRISHTI_ALERT_EMAIL'),
],

// app/Providers/AppServiceProvider.php
use Drishti\DrishtiClient;

public function register(): void
{
    $this->app->singleton(DrishtiClient::class, fn () => new DrishtiClient(
        apiKey: config('services.drishti.key'),
        maxRetries: 3,
        timeout: 30.0,
    ));
}

Type-hint DrishtiClient in any controller, job or command and the container injects the shared instance.

Build a 15-minute announcements watcher

Every 15 minutes the scheduler runs an Artisan command. It calls the SDK, Eloquent deduplicates on Drishti's id, and a Laravel Notification emails each new filing.

Laravel scheduler runs an Artisan command every 15 minutes, which calls the Drishti PHP SDK, stores new announcements through Eloquent and sends a mail or Slack notification

The Artisan command and schedule

Since Laravel 11, the schedule lives in routes/console.php beside closure commands. A 30-minute lookback catches filings a skipped run missed, and firstOrCreate makes the overlap harmless.

Code
// routes/console.php
use App\Models\Announcement;
use App\Notifications\NewAnnouncement;
use Drishti\DrishtiClient;
use Illuminate\Support\Facades\{Artisan, Notification, Schedule};

Artisan::command('drishti:announcements', function (DrishtiClient $client) {
    $from = now('UTC')->subMinutes(30)->toIso8601String();
    $page = 1;
    do {
        $result = $client->getAnnouncements(
            symbols: config('services.drishti.watchlist'),
            from: $from, page: $page++, limit: 50,
        );
        foreach ($result['data'] as $row) {
            $item = Announcement::firstOrCreate(['drishti_id' => $row['id']], [
                'symbol' => $row['symbol'], 'category' => $row['category'],
                'summary' => $row['summary'], 'published_at' => $row['date'],
            ]);
            if ($item->wasRecentlyCreated) {
                Notification::route('mail', config('services.drishti.alert_email'))
                    ->notify(new NewAnnouncement($item));
            }
        }
    } while ($result['has_next']);
})->purpose('Store and notify new watchlist announcements');

Schedule::command('drishti:announcements')->everyFifteenMinutes()->withoutOverlapping();

One request accepts up to 20 symbols, so array_chunk() a larger watchlist. Re-fetched rows still cost credits, so keep the lookback short.

The Eloquent model and notification

The migration needs a unique drishti_id, symbol, nullable category, text summary and a published_at timestamp:

Code
// app/Models/Announcement.php
class Announcement extends Model
{
    protected $fillable = ['drishti_id', 'symbol', 'category', 'summary', 'published_at'];
    protected $casts = ['published_at' => 'datetime'];
}

// app/Notifications/NewAnnouncement.php
class NewAnnouncement extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(public Announcement $item) {}

    public function via(object $notifiable): array { return ['mail']; }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject("{$this->item->symbol}: {$this->item->category}")
            ->line($this->item->summary);
    }
}

Swap mail for slack after installing laravel/slack-notification-channel, or add database for an in-app inbox. Queued notifications keep a slow mail server from blocking the command.

Handle errors and rate limits

The client retries 408, 409, 425, 429, 500, 502, 503 and 504 responses and network errors with exponential backoff, twice by default. Anything that still fails surfaces as Drishti\Exception\DrishtiApiException, with the HTTP status and the parsed error body:

Code
use Drishti\Exception\DrishtiApiException;

try {
    $result = $client->getAnnouncements(symbols: ['RELIANCE'], limit: 20);
} catch (DrishtiApiException $e) {
    Log::warning('Drishti request failed', [
        'status' => $e->getStatusCode(),
        'body' => $e->getBody(),
    ]);
    return 1;
}

Wrap the scheduled command's loop this way so a 403 logs a clear reason, not a stack trace. Network failures that outlast the retries surface as Guzzle exceptions. Sandbox allows 10 requests per minute and 1,000 REST requests per day, enough for 96 runs a day on a small watchlist.

Stream announcements from a long-running worker

Polling suits an email digest. For alerts within seconds, use the WebSocket. PHP-FPM cannot hold a socket open, so run an Artisan command under Supervisor, like queue:work:

Code
// routes/console.php (StoreAnnouncement is your own queued job)
Artisan::command('drishti:listen', function (DrishtiClient $client) {
    $session = $client->websocket(logger: Log::channel('stack'));
    $session->onAnnouncements(fn (array $item) => StoreAnnouncement::dispatch($item));
    $session->subscribe('announcements', symbols: config('services.drishti.watchlist'));
    $session->run();
});

run() blocks until stop() is called, or pass seconds, as in run(300.0), for a bounded run. The session reconnects with backoff, resubscribes after each reconnect, and treats the connection as dead if no message arrives within heartbeatTimeout, 90 seconds by default. Rejected subscribes are retried on the next reconnect; a subscribe sent from inside a handler throws Drishti\Exception\DrishtiWebSocketException, whose getErrorCode() returns codes such as forbidden. WebSocket access starts on the Starter plan; the WebSocket guide lists the products and message shapes.

Map each Laravel piece to an SDK call

Laravel pieceSDK call or classWhat it does
config/services.php and AppServiceProvidernew DrishtiClient(apiKey: ..., maxRetries: ..., timeout: ...)One shared client with your retry and timeout settings
Scheduled Artisan commandgetAnnouncements(symbols:, from:, page:, limit:)Pulls new filings and follows has_next
Eloquent Announcement model$row['id'] from the responseDeduplicates overlapping runs
Category filter in an admin formgetAnnouncementsCategories()Lists current category names for categories:
Results page on a content sitegetEarnings(symbols:, quarter:, detailed:)Earnings rows, with tables when detailed
try / catch in jobs and commandsDrishtiApiException::getStatusCode(), getBody()Status and error body after retries
Supervisor-managed workerwebsocket(), onAnnouncements(), subscribe(), run()Live announcements with reconnect

Frequently asked questions

Is there a Composer package for NSE and BSE company data?

Yes. composer require manasija/drishti-sdk installs Drishti's PHP SDK from Packagist. It covers announcements, earnings, concalls, news, alerts and block deals for NSE and BSE listed companies, not price feeds.

How do I use a BSE API from PHP with scrip codes?

Pass BSE scrip codes with the scripCodes named argument, for example getAnnouncements(scripCodes: ['500325'], limit: 20). You can combine symbols and scripCodes in one request, up to 20 of each.

Can I call it from WordPress or a shared PHP host?

Yes for REST calls, from a cron job or plugin on PHP 8.2+, with the key kept server-side. The WebSocket stream needs a process that stays running, which most shared hosts do not allow.

Does the free Sandbox work with the Laravel scheduler?

Yes. Sandbox includes 1,000 one-time trial credits, 10 requests per minute and 1,000 REST requests per day, but no WebSocket access. Starter costs ₹2,000/month and adds WebSocket monitoring for 100 symbols.

Can I get live prices or place orders with this SDK?

No. Use an authorised price vendor such as TrueData or Global Datafeeds for ticks and candles, and a broker API for orders. Drishti covers the company events around those prices.

Run it against your own watchlist

Create a free key at Sandbox signup, run the first-call script for two symbols, then add the Artisan command with your real watchlist. The PHP SDK docs list every method and option, and the SDK comparison hub compares it with the Python, TypeScript, Java and C# SDKs.

Product pages, package registries and documentation checked on 21 October 2026. Prices and features change, so confirm on each provider's site before you buy. This article is not investment advice.

Keep exploring