Browse documentation
WebSocket streams
Instead of polling REST endpoints for fresh filings, earnings, news, concalls, and alerts, open a single WebSocket connection and subscribe to the products you care about. Drishti pushes structured events as soon as they are published — useful for watchlist monitors, research desks, and agent workflows that need to react quickly.
How it works
- Use a paid plan. WebSocket streams require Starter, Pro, or Enterprise. Copy an API key from the Drishti platform console.
- Open a connection to
wss://developers.manasija.in/v1/wswith your API key. - Subscribe within 60 seconds. Send one
subscribemessage per product. A socket with no accepted subscription is closed after 60 seconds. - Read every message by its shape. The server sends subscribe confirmations, data events, errors, heartbeats, and access-change notices on the same socket. See Server messages.
- Reconnect, resubscribe, and catch up. Subscriptions do not survive a disconnect and there is no replay buffer. Resubscribe on every new connection and use REST to fill the gap. See Reconnect and catch up.
The SDK websocket helper handles steps 2, 3, and the reconnect part of step 5 for you.
Message flow
A typical session, in order:
client → connect wss://developers.manasija.in/v1/ws (X-API-Key header or ?api_key=)
client → {"op":"subscribe","product":"earnings","symbols":["RELIANCE","TCS"]}
server ← {"status":"subscribed","product":"earnings","tier":"starter_100",...}
server ← {"type":"heartbeat","sent_at":"2026-10-16T09:30:00+00:00"} every 30 s
server ← {"channel":"earnings","event":"earnings.ready","data":{...}} when a filing is published
server ← {"channel":"earnings","event":"earnings.updated","data":{...}} when the same quarter changes
… connection drops …
client → reconnect, send the same subscribe messages, call REST to catch upEndpoint and authentication
wss://developers.manasija.in/v1/wsUse the same API key as REST. The connection request accepts either:
| Method | Value | Use it for |
|---|---|---|
| Header | X-API-Key: <key> | Server clients (Node ws, Python websockets, the SDKs). |
| Query string | ?api_key=<key> | Runtimes that cannot set headers, such as the browser WebSocket API. |
A missing or invalid key is rejected during the handshake with HTTP 403, so the socket never opens. A key revoked while connected closes the socket with code 4401. WebSocket access is checked separately from REST access: a key that can call REST can still be rejected at subscribe time. See Authentication.
SDK websocket helper
Use client.websocket() from the official SDK instead of managing raw sockets yourself. The session client connects in the background, sends subscribe messages for you, replays every subscription after a reconnect, watches heartbeats to detect dead connections, and keeps retrying until you call close().
Install
pnpm add drishti-sdkpip install drishti-sdkcomposer require manasija/drishti-sdkFor Java, add Maven io.github.techmanasija:drishti-sdk (see the Java SDK page). For .NET, run dotnet add package Manasija.Drishti (see the C# / .NET SDK page).
JavaScript / TypeScript
Create a session from any DrishtiClient instance, subscribe to one or more products, then handle events with callbacks or an async iterator:
import { DrishtiClient } from "drishti-sdk"
const client = new DrishtiClient({ apiKey: process.env.DRISHTI_API_KEY! })
const ws = client.websocket({
onAnnouncements: (announcement) => {
console.log(announcement.symbol, announcement.summary)
},
})
await ws.subscribe({ product: "announcements", symbols: ["RELIANCE", "TCS"] })Prefer for await when you want one loop that also sees subscribe confirmations and socket errors:
const ws = client.websocket()
await ws.subscribe({ product: "announcements", symbols: ["RELIANCE"], detailed: false })
for await (const event of ws.events()) {
if (event.kind === "subscribed") {
console.log(event.product, event.tier)
continue
}
if (event.kind === "data") console.log(event.channel, event.data)
if (event.kind === "error") console.error(event.message)
}Channel listeners are also available via ws.on("announcements", handler) and product-specific helpers such as ws.onAnnouncements(handler), ws.onNews(handler), ws.onBlockDeals(handler), and ws.onAlerts(handler). Use ws.on("heartbeat", handler) if you want to observe heartbeats yourself.
Python
The Python helper is async-first. The session connects on the first subscribe, events, or async with call:
import asyncio
import os
from drishti_sdk import DrishtiClient
async def main() -> None:
client = DrishtiClient(api_key=os.environ["DRISHTI_API_KEY"])
async with client.websocket(
on_announcements=lambda row: print(row.get("symbol"), row.get("summary")),
) as ws:
await ws.subscribe("announcements", symbols=["RELIANCE", "TCS"])
await asyncio.Event().wait()
asyncio.run(main())Use async for event in ws.events() when you want subscribe confirmations and delivery events in one stream:
async with client.websocket() as ws:
await ws.subscribe("announcements", symbols=["RELIANCE"], detailed=False)
async for event in ws.events():
if event.kind == "subscribed":
print(event.product, event.tier)
continue
if event.kind == "data":
print(event.channel, event.data)
if event.kind == "error":
print(event.message)PHP
The PHP helper is blocking and is meant for a long-running CLI worker (supervisord, systemd, or a framework console command), not a web request. Register handlers and subscriptions, then call run():
use Drishti\DrishtiClient;
$client = new DrishtiClient(apiKey: getenv('DRISHTI_API_KEY'));
$ws = $client->websocket();
$ws->onAnnouncements(function (array $row): void {
echo $row['symbol'] ?? '', ' ', $row['summary'] ?? '', PHP_EOL;
});
$ws->subscribe('announcements', symbols: ['RELIANCE', 'TCS']);
$ws->run(); // blocks until $ws->stop()Use on('message', ...) when you want subscribe confirmations, delivery events, heartbeats, and errors in one handler:
$ws->on('message', function ($event): void {
$e = $event->toArray();
match ($e['kind']) {
'subscribed' => print("{$e['product']} {$e['tier']}\n"),
'data' => print($e['channel'] . PHP_EOL),
'error' => print($e['message'] . PHP_EOL),
default => null,
};
});Java
The Java session is blocking, like PHP, but it can also run on a background thread inside a web app or service. Register handlers and subscriptions, then call run() (blocking) or start() (background):
DrishtiWebSocketSession ws = DrishtiClient.fromEnvironment().websocket()
.onSubscribed(ack -> System.out.println(ack.product() + " " + ack.tier()))
.onAnnouncements(row -> System.out.println(row.path("symbol").asText() + " " + row.path("summary").asText()))
.onError(error -> System.err.println(error.message()));
ws.subscribe("announcements", List.of("RELIANCE", "TCS"));
ws.start(); // background daemon thread; call ws.close() on shutdownUse onMessage(handler) when you want subscribe confirmations, delivery events, heartbeats, and errors in one handler. Events are a sealed WebSocketEvent type: SubscribedEvent, DataEvent, ErrorEvent, HeartbeatEvent, and RawEvent.
C# / .NET
The .NET session is async and fits a BackgroundService or console app. Register handlers and subscriptions, then await RunAsync (until cancelled) or call StartAsync (background):
using Manasija.Drishti;
using Manasija.Drishti.WebSocket;
using var client = DrishtiClient.FromEnvironment();
await using var session = client.CreateWebSocketSession();
session
.OnSubscribed(ack => { Console.WriteLine($"{ack.Product} {ack.Tier}"); return Task.CompletedTask; })
.OnAnnouncements(a => Console.WriteLine($"{a.Symbol} {a.Summary}"))
.OnError(e => { Console.Error.WriteLine(e.Message); return Task.CompletedTask; });
await session.SubscribeAsync(new SubscribeOptions("announcements") { Symbols = ["RELIANCE", "TCS"] });
await session.RunAsync(stoppingToken); // until cancelledUse ReadEventsAsync(cancellationToken) when you want delivery events and errors in one await foreach loop. Events are WebSocketEvent records: DataEvent, ErrorEvent, SubscribedEvent, HeartbeatEvent, and RawEvent.
Session API
| Method | JavaScript / TypeScript | Python | PHP | Description |
|---|---|---|---|---|
| Create session | client.websocket(options?) | client.websocket(...) | $client->websocket(...) | Prepares a managed WebSocket session tied to the client API key. |
| Subscribe | await ws.subscribe({ product, symbols, detailed?, categories? }) | await ws.subscribe(product, symbols=..., detailed=..., categories=...) | $ws->subscribe($product, symbols: ..., categories: ..., detailed: ...); sent when run() connects, or right away (throwing on rejection) when called from a handler on a live connection | Sends the subscribe message. Before the socket is open (the usual case at startup), it returns at once, the SDK sends it on connect, and a rejection arrives in onError / on_error. On a live connection, it waits for the server's reply and throws on rejection. Read the confirmation (tier, symbols, full_feed, detailed, categories) from a subscribed event or onSubscribed / on_subscribed. |
| Event stream | for await (const event of ws.events()) | async for event in ws.events() | $ws->on('message', $handler) | Yields subscribed, data, heartbeat, and error events from one loop. |
| Channel listeners | ws.on(channel, handler) / ws.onAnnouncements(handler) | on_announcements=..., on_news=..., etc. | $ws->on(channel, $handler) / $ws->onAnnouncements($handler) | Product-specific callbacks for data deliveries. |
| Lifecycle hooks | onSubscribed, onError, onOpen, onReconnectAttempt | on_subscribed, on_error, on_open, on_reconnect_attempt | onSubscribed:, onError:, onOpen:, onReconnectAttempt: | onOpen / on_open runs after every successful connect, once subscriptions have been replayed — the right place for catch-up. |
| Close | await ws.close() | async with exit / await ws.close() | $ws->stop() (ends run()) | Stops reconnect attempts and closes the socket. |
SDK behavior worth knowing:
- Heartbeat watchdog. If no message (including heartbeats) arrives for 90 seconds, the JavaScript, Java, PHP, and C# SDKs treat the connection as dead and reconnect. Tune it with
heartbeatTimeoutMs(JavaScript),heartbeatTimeout(Java and PHP), orHeartbeatTimeout(C#). The Python SDK sends WebSocket pings every 20 seconds instead. - Handle subscribe errors in `onError`. Rejections with code
forbidden,bad_request, orunauthorizedarrive inonError/on_error. The SDK keeps the subscription and tries again on every reconnect, so close the session (close(), orstop()in Java and PHP) when the error cannot fix itself, such as a missing add-on or a revoked key. - The SDK does not backfill. Reconnects restore live delivery only. Run the catch-up step from
onOpen/on_open.
Products
Every product can share one connection. Send one subscribe message per product; each product keeps its own symbols and settings.
| Product | Stream | REST equivalent |
|---|---|---|
news | News updates | `GET /v1/news` |
block-deals | Block-deal updates | Stream only |
announcements | Corporate announcements | `GET /v1/announcements` |
earnings | Earnings filings | `GET /v1/earnings` |
concalls | Conference-call updates | `GET /v1/concalls` |
alerts | Market alerts | `GET /v1/alerts` |
Subscribe message
subscribe is the only message the server accepts. There is no unsubscribe or ping message: to stop a product, close the connection and reconnect without it.
{"op":"subscribe","product":"announcements","symbols":["RELIANCE","TCS"],"detailed":true}| Field | Type | Required | Description |
|---|---|---|---|
op | string | Yes | Must be subscribe. |
product | string | Yes | One of news, block-deals, announcements, earnings, concalls, or alerts. The SDKs call block deals block_deals (for example onBlockDeals / on_block_deals) and convert it for you. |
symbols | string[] | Yes on Starter and Pro | NSE symbols to receive events for. Symbols are uppercased and deduplicated. Starter and Pro must send at least one symbol. An empty array requests the full feed and needs a full-market (Enterprise) entitlement. |
detailed | boolean | No | Defaults to true. false sends the smaller REST list-row shape on announcements, earnings, and concalls. Must be a JSON boolean, not a string. |
categories | string[] | Only on the announcement category plan | Primary announcement categories to receive, for accounts on the 15-category announcements plan. Up to 15 distinct categories across all your connections; reusing a category on another connection does not use another slot. Names must match announcement categories. Omit it on every other plan. |
Rules:
- Re-subscribing replaces. A second
subscribefor the same product on the same connection replaces that product's symbols,detailedmode, and categories. Other products are not affected. - Symbol caps are account-wide. Active symbols are counted across every open connection and product. A second connection that adds new symbols can be rejected even if each connection is under the cap on its own.
- Filtering. A symbol-filtered subscription receives an event when the event's
symbol(or symbol list) matches one of your subscribed symbols.
Server messages
Every message the server sends is a JSON object. Tell them apart by their keys, not by order:
| Message | How to recognize it | What to do |
|---|---|---|
| Subscribe confirmation | status is subscribed | Record the accepted tier, symbols, and full_feed. |
| Data event | Has channel, data, and usually event | Hand off to your handler. SDKs expose the name as event.event. |
| Error | Has error | Log it. The connection stays open unless a close code follows. |
| Heartbeat | type is heartbeat | Ignore it, or use it to detect a dead connection. Sent every 30 seconds. |
| Access changed | status is entitlements_changed or entitlement_expired | The server closes with 4003 right after. Reconnect and resubscribe. |
Subscribe confirmation
{"status":"subscribed","product":"announcements","tier":"starter_100","full_feed":false,"symbols":["RELIANCE","TCS"],"detailed":true}| Field | Description |
|---|---|
status | Always subscribed. |
product | The product that was configured. |
tier | Your WebSocket tier for that product: starter_100, pro_1000, or scale. |
full_feed | true when you receive every event for the product; false when delivery is limited to symbols. |
symbols | The accepted symbol list after uppercasing and deduplication. Empty when full_feed is true. |
detailed | The accepted detail mode. |
categories | Only present on the announcement category plan: the accepted categories. |
Data events
Every data event has the same top-level shape:
| Field | Type | Description |
|---|---|---|
channel | string | The product that produced the event — same value as product in your subscribe message. |
event | string | Optional. What happened, when the producer names it. See Event names. |
data | object | The resource payload. Shape depends on channel and your detailed setting. |
{
"channel": "announcements",
"data": {
"id": "6a015e446ec560b11681e3c9",
"symbol": "RELIANCE",
"summary": "The board approved the quarterly financial results.",
"category": "Board Meeting"
}
}Shapes by channel
| Channel | data when detailed=true | data when detailed=false |
|---|---|---|
news | NewsItem | NewsItem |
block-deals | BlockDealItem | BlockDealItem |
announcements | AnnouncementDetail | AnnouncementListItem |
earnings | EarningsDetail | EarningsListItem |
concalls | ConcallDetail | ConcallListItem |
alerts | Alert | Alert |
- Shapes match the REST list and detail rows for the same product.
- Announcement events never include
title,headline, or attachment URLs. Usesummaryfor display text. - Earnings events may include
attachment_url, so you do not need a separate attachments call for live events. - Block-deal events never include upstream headline text.
- Alerts use the public
Alertshape and keeptype/alert_typecompatibility. Each event has a UTCtimestampfor when the alert was created; price alerts also include delayedprice.value, signedprice.change_percent, andprice.as_offor the price observation time. - Known public alert
typevalues:52w_high,52w_low,earnings,high_growth_concalls,price_alert,rvol_alert,volume_alert.
Event names
event | Channel | Meaning |
|---|---|---|
earnings.ready | earnings | First published result for a company and quarter. |
earnings.updated | earnings | A later change to the same company and quarter, such as a results table that finished late or a later filing. Replace the row you stored from earnings.ready. |
concall.ready | concalls | First analysis of a conference call. |
concall.updated | concalls | The same call was analysed again, for example from the official transcript after the audio. Replace the row you stored from concall.ready. |
news.published | news | A new news item. |
block_deals.published | block-deals | A new block deal. |
Other channels may not set event. Treat it as optional and do not fail when it is missing or has a value you do not recognize.
Handling repeat events for the same symbol
A symbol can produce several events over time — for example earnings.ready followed by earnings.updated when the results table lands, or concall.ready followed by concall.updated when the official transcript replaces the audio. Pick one approach:
- Upsert by `data.id` — store the latest version of each record. This is the right default and also makes catch-up after a reconnect safe.
- Notify only on first sight — alert users on
earnings.ready/concall.readyand silently update onearnings.updated/concall.updated. - Process every event — when latency matters more than deduplication.
Examples by product
Product examples
Loading websocket examples...
Errors
A rejected message gets an error reply on the same socket. The connection stays open, so you can fix the request and send it again.
{"error":"The Starter plan allows at most 100 symbols","code":"forbidden"}error is a readable message. code is present on access and limit errors; validation errors only have error.
error (example) | code | Cause |
|---|---|---|
Invalid JSON | — | The message is not valid JSON. |
Unsupported operation | — | op is missing or is not subscribe. |
Missing product | — | product is missing or empty. |
symbols must be an array | — | symbols is a string or object instead of an array. |
categories must be an array of strings | — | categories has the wrong type. |
detailed must be a boolean | — | detailed was sent as a string such as "true". |
WebSocket addon '<product>' is not enabled for this key | forbidden | Your plan or key does not include this product. |
The <plan> plan allows at most <n> symbols | forbidden | Too many symbols in one subscribe. |
The <plan> plan requires at least one symbol | forbidden | Empty symbols on a plan without full-feed access. |
Tier allows at most <n> active symbols | symbol_limit_exceeded | The account-wide symbol cap is reached across all connections. |
After 5 rejected subscribes on a connection with nothing accepted, the server closes the socket with 4403.
Close codes
When the server ends the connection, it uses one of these codes. Where a reason message is sent first, it arrives as an error or access-change message just before the close.
| Code | Reason | Cause | Reconnect? |
|---|---|---|---|
4401 | — | API key missing, invalid, or inactive. | No. Fix the key first. |
4429 | websocket_connection_limit | Too many simultaneous connections for the account. | Not until you close another connection. |
4408 | websocket_subscribe_timeout | No subscription was accepted within 60 seconds of connecting. | Yes, and send subscribe messages straight away. |
4403 | websocket_subscribe_rejected | 5 rejected subscribes with nothing accepted. | No. Fix the subscribe message or plan first. |
4003 | websocket_entitlements_changed / websocket_entitlement_expired | Your plan or WebSocket access changed or expired. | Yes. Reconnect to pick up your current access. |
1000–1015 | — | Normal closure, network drop, proxy timeout, or server restart. | Yes, with backoff. |
Limits
| Plan | WebSocket access | Symbol cap | Simultaneous connections | Full feed |
|---|---|---|---|---|
| Sandbox | Not available | — | 0 | — |
| Starter | All products | 100 active symbols account-wide | 5 | No |
| Pro | All products | 1,000 active symbols account-wide | 5 | No |
| Enterprise | By agreement | Full market | By agreement | Yes — send empty symbols |
- Connections count as soon as they open, whether or not they have subscribed. Close sockets you no longer use.
- Subscribe within 60 seconds of connecting, or the socket is closed with
4408. - Full-feed accounts can still filter. Sending symbols on a full-feed tier gives a filtered subscription.
- No REST credits are charged for WebSocket delivery on paid plans.
Reconnect and catch up
Connections drop because of network interruptions, proxy timeouts, deploys, or access changes. Subscriptions belong to the connection, and there is no server-side replay: events published while you were disconnected are not resent.
On every reconnect:
- Back off. Wait before reconnecting, doubling the delay up to about 30 seconds. Do not reconnect after
4401or4403. - Resubscribe. Send the same subscribe messages again. The SDK does this for you and then calls
onOpen/on_open. - Catch up over REST. For each product, call its REST list endpoint for your symbols and keep rows newer than the last
data.dateyou processed. - Upsert by `data.id` so records you already have are not processed twice.
const ws = client.websocket({
// Runs after every connect, once subscriptions are replayed
onOpen: async () => {
const missed = await client.getAnnouncements({ symbols: WATCHLIST, limit: 100 })
for (const row of missed.data) {
if (row.date > lastSeenDate) await upsertById(row)
}
},
})Production checklist
- Use the SDK session client when you can. It handles reconnects, resubscribes, and heartbeat checks.
- Handle every message type. Heartbeats, confirmations, errors, and access-change notices share the socket with data events.
- Keep handlers fast. Parse the message, enqueue heavy work, and return. Slow consumers back up the connection.
- Catch up after every reconnect using REST, and upsert by
data.id. - Stay under the limits. Watch the account-wide symbol cap and the 5-connection limit — staging and production on the same account share them.
- Keep your API key out of client bundles. Query-string keys are visible in browser DevTools. Run subscribers on your backend and push to browsers yourself.
- Use `wss://`, never
ws://.
Troubleshooting
The handshake fails with HTTP `403`, or the socket closes with `4401`. The API key is missing, wrong, or revoked. Check the key in the platform console.
Socket closes immediately with `4429`. The account already has 5 open connections. Look for old processes, other environments, or reconnect loops that never close the previous socket.
Subscribe returns `WebSocket addon ... is not enabled`. The account is on Sandbox or the plan does not include that product. Check Get account profile for enabled WebSocket products.
Socket closes after 60 seconds with `4408`. No subscribe was accepted. Send subscribe messages right after connecting and check the error replies.
No events arrive after a successful subscribe. Markets are quiet between filings. Confirm the symbols in the confirmation are the ones you expect and use the REST list endpoint to check that recent data exists for them.
Events stop after a while with no close. The connection may be half-open. If you see no heartbeat for over 90 seconds, close and reconnect.
Events stop after a deploy or network blip. Raw sockets lose subscriptions on disconnect. Resubscribe after every reconnect, or switch to the SDK.
Next steps
- How to set up WebSockets — step-by-step walkthrough with a working subscriber.
- Authentication — API key setup for REST and WebSocket.
- JavaScript / TypeScript SDK — websocket session client reference.
- Python SDK — async websocket client reference.
- Java SDK — blocking or background websocket session reference.
- PHP SDK — blocking websocket worker reference.
- C# / .NET SDK — async websocket session reference.
- Pricing — compare symbol limits and plan tiers.