Browse documentation
C# / .NET SDK
The official C# / .NET SDK for the Drishti API provides an async, thread-safe client with a method for every endpoint, typed parameter records and response models, a managed websocket session that reconnects on its own, and batch job helpers. It plugs into ASP.NET Core and the generic host through AddDrishtiClient, built on IHttpClientFactory, and logs through ILogger.
Requirements
- .NET 8 or later, or any runtime that supports .NET Standard 2.0 (.NET Framework 4.6.2+, Unity, Xamarin). Check with
dotnet --version. - A Drishti API key in the
DRISHTI_API_KEYenvironment variable. See the Quickstart to create one.
Installation
dotnet add package Manasija.Drishti --version 1.0.0The package is `Manasija.Drishti` on NuGet. The examples on this page use C# 12 collection expressions (["TCS"]), the default on .NET 8. On older language versions, use new[] { "TCS" } instead.
Quick start
Create a console app and replace the contents of Program.cs:
using Manasija.Drishti;
using Manasija.Drishti.Params;
using var client = DrishtiClient.FromEnvironment(); // reads DRISHTI_API_KEY
var result = await client.GetAnnouncementsAsync(new AnnouncementsParams
{
Symbols = ["RELIANCE"],
Limit = 3,
Detailed = false,
});
foreach (var item in result!.Data)
{
Console.WriteLine($"{item.Date} | {item.Category} | {item.Summary}");
}Run it:
dotnet runIt prints the three latest RELIANCE announcements, one per line, as date | category | summary.
How the client works:
- Every method is async, returns a
Task, and takes an optionalCancellationToken. - Filters are records from
Manasija.Drishti.Params, set with object initializers. Anything you leave unset is not sent. - Paginated responses have
Data(typed items such asitem.Symbolanditem.Title) andHasNext. - Each response model is a typed view over the JSON the API returned. A missing,
null, or mistyped value reads asnull, so new API fields never break you.model.Jsonis the fullJsonElement, andmodel.Deserialize<T>()maps it onto your own class (snake_case names). Free-form fields such asEarningsTableandExtractedInformationareJsonElement?. - CSV, JSONL, and HTML responses come back as
string, and PDF citations asbyte[]. An empty response (204, or an empty body) comes back asnull. DrishtiClientis thread-safe. Create one and share it.
Configuration
Create a client from the environment, from a key, or from options:
using var fromEnv = DrishtiClient.FromEnvironment(); // DRISHTI_API_KEY, optional DRISHTI_BASE_URL
using var fromKey = new DrishtiClient("<YOUR_API_KEY>");
using var client = new DrishtiClient(new DrishtiClientOptions
{
ApiKey = Environment.GetEnvironmentVariable("DRISHTI_API_KEY")!,
MaxRetries = 3,
InitialRetryDelay = TimeSpan.FromMilliseconds(250),
Timeout = TimeSpan.FromSeconds(30),
});| Option | Default |
|---|---|
MaxRetries | 2 (3 attempts in total) |
InitialRetryDelay, RetryMultiplier, MaxRetryDelay | 300 ms, 2, 5 s (no jitter) |
RetryOnStatuses | 408, 409, 425, 429, 500, 502, 503, 504, plus network errors and timeouts |
Timeout | 60 s per response |
BaseUrl, Headers, UserAgent | https://developers.manasija.in, none, drishti-sdk-dotnet/<version> |
Dependency injection
In ASP.NET Core or a worker service, register the client once and inject IDrishtiClient:
using Manasija.Drishti;
using Manasija.Drishti.DependencyInjection;
using Manasija.Drishti.Params;
// appsettings.json: { "Drishti": { "ApiKey": "...", "Timeout": "00:00:30" } }
builder.Services.AddDrishtiClient(builder.Configuration);
app.MapGet("/news/{symbol}", async (string symbol, IDrishtiClient drishti) =>
(await drishti.GetNewsAsync(new NewsParams { Symbols = [symbol] }))?.Data);Options bind from the Drishti configuration section and are validated at startup, so a missing ApiKey fails fast. Keep the key in user secrets or an environment variable (Drishti__ApiKey), not in a committed appsettings.json. AddDrishtiClient returns the IHttpClientBuilder, so you can add handlers such as a proxy or Polly policies. An overload takes an Action<DrishtiClientOptions> to configure it in code.
Errors
All SDK exceptions extend DrishtiException, in Manasija.Drishti.Exceptions:
using Manasija.Drishti.Exceptions;
try
{
await client.GetAccountAsync();
}
catch (DrishtiApiException ex) when (ex.StatusCode == 429) // rate limited, after retries
{
await Task.Delay(ex.RetryAfter ?? TimeSpan.FromMinutes(1));
}
catch (DrishtiApiException ex) // HTTP error status, after retries
{
Console.Error.WriteLine($"{ex.StatusCode} {ex.ErrorCode}: {ex.Detail}"); // e.g. 401 unauthorized: Invalid API key
}
catch (DrishtiNetworkException) // no response, after retries
{
// connection failure, DNS, or timeout
}| Exception | When |
|---|---|
DrishtiApiException | The API returned 400 or above after retries. Exposes StatusCode, Detail, ErrorCode, BodyJson, BodyText, Headers, and RetryAfter. |
DrishtiNetworkException | No response after all retries (connection failure, DNS, timeout). |
DrishtiWebSocketException | A subscribe was rejected or timed out, or the socket is not connected. Code carries the server code (forbidden, bad_request, …). |
DrishtiException | Base class of the above; also invalid JSON on a success response and batch wait timeouts. |
A blank API key or an empty id list throws ArgumentException before any request is sent.
The client retries 408, 409, 425, 429, 500, 502, 503, and 504 responses, and network errors, up to 2 times with exponential backoff. It follows redirects up to five hops, never sends your API key or custom headers to another host, such as the file storage behind PDF citations, and refuses HTTPS-to-HTTP redirects. See Errors and rate limits for what each status means.
Portfolio summary
var summary = await client.PostDailySummaryAsync(
new DailySummaryRequest
{
Portfolio = [new PortfolioPosition("TCS") { Exposure = 0.6 }, new PortfolioPosition("INFY")],
Mode = "exposure",
},
ContentRetention.None); // optional: ask the API not to retain the request
if (summary?.Status == "success") Console.WriteLine(summary.Summary);The body is sent as given: unset fields are omitted and the API applies its own defaults. Any JSON-serializable object, or a JsonElement, also works as the body. See Generate portfolio summary for modes and statuses.
WebSocket session
CreateWebSocketSession() returns a session that connects, sends your subscriptions, and dispatches events to handlers. It reconnects with backoff (1 s to 30 s, with jitter), resubscribes after every reconnect, and treats a silent connection as dropped after 90 seconds. Live streams need a paid plan.
using Manasija.Drishti.WebSocket;
await using var session = client.CreateWebSocketSession();
session
.OnSubscribed(ack => { Console.WriteLine($"subscribed {ack.Product} on tier {ack.Tier}"); return Task.CompletedTask; })
.OnAnnouncements(a => Console.WriteLine($"{a.Symbol}: {a.Summary}"))
.OnError(e => { Console.Error.WriteLine($"{e.Message} [{e.Code}]"); return Task.CompletedTask; });
await session.SubscribeAsync(new SubscribeOptions("announcements")
{
Symbols = ["RELIANCE", "TCS"],
});
await session.RunAsync(stoppingToken); // runs until the token is cancelledProduct handlers are OnNews, OnBlockDeals, OnAnnouncements, OnEarnings, OnConcalls, and OnAlerts. Products are news, block_deals, announcements, earnings, concalls, and alerts. In a web app or service, call StartAsync() to connect in the background and StopAsync() (or dispose the session) on shutdown.
Or read events as an async stream:
await session.StartAsync();
await foreach (var e in session.ReadEventsAsync(stoppingToken))
{
if (e is DataEvent data) Console.WriteLine($"{data.Channel}: {data.Data}");
if (e is ErrorEvent error) Console.Error.WriteLine(error.Message);
}Handlers run one at a time, off the receive loop. Keep them fast and hand heavy work to a queue. A handler that throws is logged and the session carries on. Every setting, such as HeartbeatTimeout and SubscribeAckTimeout, is on DrishtiWebSocketOptions, passed through CreateWebSocketSession(o => ...).
Batch jobs
Build the JSONL input, submit it, and wait for the results. Each line is one portfolio summary request with a custom_id.
using Manasija.Drishti.Batch;
var jsonl = BatchJsonl.BuildInput(
[
new DailySummaryLine("client-001") { Symbols = ["TCS"], Mode = "news_context" },
new DailySummaryLine("client-002") { Portfolio = [new PortfolioPosition("RELIANCE") { Exposure = 1 }] },
]);
var job = await client.SubmitBatchJobAndWaitAsync(
new BatchJobRequest("watchlist.jsonl", jsonl) { DisplayName = "Nightly run" },
pollInterval: TimeSpan.FromSeconds(5),
timeout: TimeSpan.FromMinutes(30));
if (job.Status is "succeeded" or "partial")
{
foreach (var line in await client.GetBatchJobResultsParsedAsync(job.Id!))
{
Console.WriteLine($"{line.CustomId}: {line.Summary}");
}
}See Batch jobs for the input format and limits.
Helper surface
Method names match the other SDKs, in PascalCase with an Async suffix. Filters go in the endpoint's params record, for example GetNewsAsync(new NewsParams { Symbols = ["TCS"], Limit = 10 }).
API wrappers
| Method | Reference |
|---|---|
GetNewsAsync | `GET /v1/news` |
GetSymbolsMetadataAsync | `GET /v1/symbols/metadata` |
GetSymbolsAsync, GetSymbolsJsonAsync | The full symbol list, as CSV text or typed rows. |
GetAnnouncementsCategoriesAsync | `GET /v1/announcements/categories` |
GetAnnouncementsAsync | `GET /v1/announcements` |
GetAnnouncementsAttachmentsAsync | Attachment URLs for announcement ids. |
GetAnnouncementCitationPdfAsync | The source PDF for one announcement, as byte[]. |
PostDailySummaryAsync | `POST /v1/daily-summary/` |
GetEarningsIndexAsync | `GET /v1/earnings/index` |
GetEarningsAsync | `GET /v1/earnings` |
GetEarningsDetailAsync | `GET /v1/earnings/detail` |
GetEarningsAttachmentsAsync | `GET /v1/earnings/attachments` |
GetEarningsCitationPdfAsync | `GET /v1/earnings/citations/{earnings_id}/pdf` |
GetEarningsCitationPageAsync | `GET /v1/earnings/citations/{earnings_id}/page/{page}` |
GetUpcomingEarningsAsync | `GET /v1/earnings/upcoming` |
GetConcallsAsync | `GET /v1/concalls` |
GetConcallCitationPdfAsync | `GET /v1/concalls/citations/{concall_id}/pdf` |
GetConcallsIndexAsync | `GET /v1/concalls/index` |
GetUpcomingConcallsAsync | `GET /v1/concalls/upcoming` |
GetConcallsDetailAsync | `GET /v1/concalls/detail` |
GetConcallsTranscriptAsync | `GET /v1/concalls/transcript` |
PostConcallsTranscriptsAsync | `POST /v1/concalls/transcripts` |
GetAlertsAsync | `GET /v1/alerts` |
GetAccountAsync | `GET /v1/account` |
GetAccountLimitsAsync | `GET /v1/account/limits` |
GetAccountUsageAsync | `GET /v1/account/usage` |
GetAccountLedgerAsync | `GET /v1/account/ledger` |
PostBatchJobsAsync | `POST /v1/batch/jobs` |
GetBatchJobsAsync | `GET /v1/batch/jobs` |
GetBatchJobAsync | `GET /v1/batch/jobs/{job_id}` |
CancelBatchJobAsync | `DELETE /v1/batch/jobs/{job_id}` |
GetBatchJobResultsAsync | `GET /v1/batch/jobs/{job_id}/results` |
Workflow helpers
| Method | Reference |
|---|---|
GetBatchJobResultsParsedAsync | Downloads the results and parses each JSONL line, with CustomId, Status, and Summary. |
WaitForBatchJobCompletionAsync | Polls GetBatchJobAsync until a terminal job status is reached, or throws DrishtiException on timeout. |
SubmitBatchJobAndWaitAsync | Calls PostBatchJobsAsync, then waits for completion. |
BatchJsonl.BuildInput, BatchJsonl.ParseResults | Build batch input from DailySummaryLine records, or parse a results file you already have. |
Transport helpers
| Method | Reference |
|---|---|
RequestAsync | Any API route: method, path, query, path params, JSON body, and headers. Returns a DrishtiResponse. |
CreateWebSocketSession | WebSocket streams |
AddDrishtiClient | Registers IDrishtiClient with IServiceCollection, on IHttpClientFactory. |
Source and API reference live in the drishti-sdk repository.