The official .Net client for communicating with the Upstox API.
Upstox API is a set of rest APIs that provide data required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (using Websocket), and more, with the easy to understand API collection.
-
API version: v2
-
Build package: io.swagger.codegen.v3.generators.dotnet.CSharpClientCodegen
This .Net package is automatically generated by the Swagger Codegen project:
-
.NET 4.0 or later
-
Windows Phone 7.1 (Mango)
-
RestSharp - 105.1.0 or later
-
Json.NET - 7.0.0 or later
-
JsonSubTypes - 1.2.0 or later
The DLLs included in the package may not be the latest version. We recommend using NuGet to obtain the latest version of the packages:
Install-Package RestSharp
Install-Package Newtonsoft.Json
Install-Package JsonSubTypes
NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See RestSharp#742
Run nuget install upstox-dotnet-sdk
to install the SDK from Nuget.
Run the following command to generate the DLL
-
[Mac/Linux]
/bin/sh build.sh
-
[Windows]
build.bat
Then include the DLL (under the bin
folder) in the C# project, and use the namespaces:
using UpstoxClient.Api;
using UpstoxClient.Client;
using UpstoxClient.Model;
A .nuspec
is included with the project. You can follow the Nuget quickstart to create and publish packages.
This .nuspec
uses placeholders from the .csproj
, so build the .csproj
directly:
nuget pack -Build -OutputDirectory out UpstoxClient.csproj
Then, publish to a local feed or other host and consume the new package via Nuget as usual.
All URIs are relative to https://api-v2.upstox.com
Class | Method | HTTP request | Description |
---|---|---|---|
ChargeApi | GetBrokerage | GET /charges/brokerage | Brokerage details |
HistoryApi | GetHistoricalCandleData | GET /historical-candle/{instrumentKey}/{interval}/{to_date} | Historical candle data |
HistoryApi | GetHistoricalCandleData1 | GET /historical-candle/{instrumentKey}/{interval}/{to_date}/{from_date} | Historical candle data |
HistoryApi | GetIntraDayCandleData | GET /historical-candle/intraday/{instrumentKey}/{interval} | Intra day candle data |
LoginApi | Authorize | GET /login/authorization/dialog | Authorize API |
LoginApi | Logout | DELETE /logout | Logout |
LoginApi | Token | POST /login/authorization/token | Get token API |
MarketQuoteApi | GetFullMarketQuote | GET /market-quote/quotes | Market quotes and instruments - Full market quotes |
MarketQuoteApi | GetMarketQuoteOHLC | GET /market-quote/ohlc | Market quotes and instruments - OHLC quotes |
MarketQuoteApi | Ltp | GET /market-quote/ltp | Market quotes and instruments - LTP quotes. |
OrderApi | CancelOrder | DELETE /order/cancel | Cancel order |
OrderApi | GetOrderBook | GET /order/retrieve-all | Get order book |
OrderApi | GetOrderDetails | GET /order/history | Get order history |
OrderApi | GetTradeHistory | GET /order/trades/get-trades-for-day | Get trades |
OrderApi | GetTradesByOrder | GET /order/trades | Get trades for order |
OrderApi | ModifyOrder | PUT /order/modify | Modify order |
OrderApi | PlaceOrder | POST /order/place | Place order |
PortfolioApi | ConvertPositions | PUT /portfolio/convert-position | Convert Positions |
PortfolioApi | GetHoldings | GET /portfolio/long-term-holdings | Get Holdings |
PortfolioApi | GetPositions | GET /portfolio/short-term-positions | Get Positions |
TradeProfitAndLossApi | GetProfitAndLossCharges | GET /trade/profit-loss/charges | Get profit and loss on trades |
TradeProfitAndLossApi | GetTradeWiseProfitAndLossData | GET /trade/profit-loss/data | Get Trade-wise Profit and Loss Report Data |
TradeProfitAndLossApi | GetTradeWiseProfitAndLossMetaData | GET /trade/profit-loss/metadata | Get profit and loss meta data on trades |
UserApi | GetProfile | GET /user/profile | Get profile |
UserApi | GetUserFundMargin | GET /user/get-funds-and-margin | Get User Fund And Margin |
WebsocketApi | GetMarketDataFeed | GET /feed/market-data-feed | Market Data Feed |
WebsocketApi | GetMarketDataFeedAuthorize | GET /feed/market-data-feed/authorize | Market Data Feed Authorize |
WebsocketApi | GetPortfolioStreamFeed | GET /feed/portfolio-stream-feed | Portfolio Stream Feed |
WebsocketApi | GetPortfolioStreamFeedAuthorize | GET /feed/portfolio-stream-feed/authorize | Portfolio Stream Feed Authorize |
Connecting to the WebSocket for market and portfolio updates is streamlined through two primary Feeder functions:
- MarketDataStreamer: Offers real-time market updates, providing a seamless way to receive instantaneous information on various market instruments.
- PortfolioDataStreamer: Delivers updates related to the user's orders, enhancing the ability to track order status and portfolio changes effectively.
Both functions are designed to simplify the process of subscribing to essential data streams, ensuring users have quick and easy access to the information they need.
The MarketDataStreamer
interface is designed for effortless connection to the market WebSocket, enabling users to receive instantaneous updates on various instruments. The following example demonstrates how to quickly set up and start receiving market updates for selected instrument keys:
public class MarketFeederTest {
static MarketDataStreamer Streamer;
public static void OnMarketUpdateHandler(MarketUpdate marketUpdate)
{
Console.WriteLine(marketUpdate);
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
HashSet<string> InstrumentKeys = new HashSet<string> { "NSE_INDEX|Nifty 50", "NSE_INDEX|Bank Nifty" };
Mode Mode = Mode.Full;
Streamer = new MarketDataStreamer(InstrumentKeys, Mode);
Streamer.OnMarketUpdate += OnMarketUpdateHandler;
await Streamer.Connect();
}
}
In this example, you first authenticate using an access token, then instantiate MarketDataStreamer with specific instrument keys and a subscription mode. Upon connecting, the streamer listens for market updates, which are logged to the console as they arrive.
Feel free to adjust the access token placeholder and any other specifics to better fit your actual implementation or usage scenario.
- Mode.Ltpc: ltpc provides information solely about the most recent trade, encompassing details such as the last trade price, time of the last trade, quantity traded, and the closing price from the previous day.
- Mode.Full: The full option offers comprehensive information, including the latest trade prices, D5 depth, 1-minute, 30-minute, and daily candlestick data, along with some additional details.
- constructor MarketDataStreamer(): Initializes the streamer.
- constructor MarketDataStreamer(instrumentKeys, mode): Initializes the streamer with instrument keys and mode (
Mode.Full
orMode.Ltpc
). - Connect(): Establishes the WebSocket connection.
- Subscribe(instrumentKeys, mode): Subscribes to updates for given instrument keys in the specified mode. Both parameters are mandatory.
- Unsubscribe(instrumentKeys): Stops updates for the specified instrument keys.
- ChangeMode(instrumentKeys, mode): Switches the mode for already subscribed instrument keys.
- Disconnect(): Ends the active WebSocket connection.
- AutoReconnect(enable): Enable/Disable the auto reconnect capability.
- AutoReconnect(enable, interval, retryCount): Customizes auto-reconnect functionality. Parameters include a flag to enable/disable it, the interval(in seconds) between attempts, and the maximum number of retries.
- OnOpen: Called on successful connection establishment.
- OnClose: Called when WebSocket connection has been closed.
- OnMarketUpdate: Delivers market updates.
- OnError: Signals an error has occurred.
- OnReconnecting: Announced when a reconnect attempt is initiated.
- OnAutoReconnectStopped: Informs when auto-reconnect efforts have ceased after exhausting the retry count.
The following documentation includes examples to illustrate the usage of these functions and events, providing a practical understanding of how to interact with the MarketDataStreamer effectively.
- Subscribing to Market Data on Connection Open with MarketDataStreamer
public class MarketFeederTest {
static MarketDataStreamer Streamer;
public static async void OnOpenHandler()
{
Console.WriteLine("Connection Established");
HashSet<string> InstrumentKeys = new HashSet<string> { "NSE_INDEX|Nifty 50", "NSE_INDEX|Bank Nifty" };
Mode Mode = Mode.Ltpc;
await Streamer.Subscribe(InstrumentKeys, Mode);
}
public static void OnMarketUpdateHandler(MarketUpdate marketUpdate)
{
Console.WriteLine(marketUpdate);
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
Streamer = new MarketDataStreamer();
Streamer.OnOpen += OnOpenHandler;
Streamer.OnMarketUpdate += OnMarketUpdateHandler;
await Streamer.Connect();
}
}
- Subscribing to Instruments with Delays
public class MarketFeederTest {
static MarketDataStreamer Streamer;
public static async void OnOpenHandler()
{
Console.WriteLine("Connection Established");
HashSet<string> InstrumentKeys = new HashSet<string> { "NSE_INDEX|Nifty 50" };
Mode Mode = Mode.Ltpc;
await Streamer.Subscribe(InstrumentKeys, Mode);
await Task.Delay(5000);
InstrumentKeys = new HashSet<string> { "NSE_INDEX|Bank Nifty" };
await Streamer.Subscribe(InstrumentKeys, Mode);
}
public static void OnMarketUpdateHandler(MarketUpdate marketUpdate)
{
Console.WriteLine(marketUpdate);
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
Streamer = new MarketDataStreamer();
Streamer.OnOpen += OnOpenHandler;
Streamer.OnMarketUpdate += OnMarketUpdateHandler;
await Streamer.Connect();
}
}
- Subscribing and Unsubscribing to Instruments
public class MarketFeederTest {
static MarketDataStreamer Streamer;
public static async void OnOpenHandler()
{
Console.WriteLine("Connection Established");
HashSet<string> InstrumentKeys = new HashSet<string> { "NSE_INDEX|Nifty 50" };
Mode Mode = Mode.Ltpc;
await Streamer.Subscribe(InstrumentKeys, Mode);
await Task.Delay(5000);
await Streamer.Unsubscribe(InstrumentKeys);
}
public static void OnMarketUpdateHandler(MarketUpdate marketUpdate)
{
Console.WriteLine(marketUpdate);
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
Streamer = new MarketDataStreamer();
Streamer.OnOpen += OnOpenHandler;
Streamer.OnMarketUpdate += OnMarketUpdateHandler;
await Streamer.Connect();
}
}
- Subscribe, Change Mode and Unsubscribe
public class MarketFeederTest {
static MarketDataStreamer Streamer;
public static async void OnOpenHandler()
{
Console.WriteLine("Connection Established");
HashSet<string> InstrumentKeys = new HashSet<string> { "NSE_INDEX|Nifty 50" };
Mode Mode = Mode.Ltpc;
await Streamer.Subscribe(InstrumentKeys, Mode);
await Task.Delay(5000);
Mode = Mode.Full;
await Streamer.ChangeMode(InstrumentKeys, Mode);
await Task.Delay(5000);
await Streamer.Unsubscribe(InstrumentKeys);
}
public static void OnMarketUpdateHandler(MarketUpdate marketUpdate)
{
Console.WriteLine(marketUpdate);
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
Streamer = new MarketDataStreamer();
Streamer.OnOpen += OnOpenHandler;
Streamer.OnMarketUpdate += OnMarketUpdateHandler;
await Streamer.Connect();
}
}
- Disable Auto-Reconnect
public class MarketFeederTest {
static MarketDataStreamer Streamer;
public static void OnAutoReconnectStoppedHandler(string message)
{
Console.WriteLine(message);
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
Streamer = new MarketDataStreamer();
Streamer.OnAutoReconnectStopped += OnAutoReconnectStoppedHandler;
Streamer.AutoReconnect(false);
await Streamer.Connect();
}
}
- Modify Auto-Reconnect parameters
public class MarketFeederTest {
static MarketDataStreamer Streamer;
public static void OnAutoReconnectStoppedHandler(string message)
{
Console.WriteLine(message);
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
Streamer = new MarketDataStreamer();
Streamer.OnAutoReconnectStopped += OnAutoReconnectStoppedHandler;
Streamer.AutoReconnect(true, 10, 3);
await Streamer.Connect();
}
}
Connecting to the Portfolio WebSocket for real-time order updates is straightforward with the PortfolioDataStreamer class. Below is a concise guide to get you started on receiving updates:
public class PortfolioFeederTest {
static PortfolioDataStreamer Streamer;
public static void OnOrderUpdateHandler(OrderUpdate orderUpdate)
{
Console.WriteLine(orderUpdate.ToString());
}
public static async Task Main(string[] args)
{
Configuration.Default.AccessToken = <ACCESS_TOKEN>;
Streamer = new PortfolioDataStreamer();
Streamer.OnOrderUpdate += OnOrderUpdateHandler;
await Streamer.Connect();
}
}
This example demonstrates initializing the PortfolioDataStreamer, connecting it to the WebSocket, and setting up an event listener to receive and print order updates. Replace <ACCESS_TOKEN> with your valid access token to authenticate the session.
- constructor PortfolioDataStreamer(): Initializes the streamer.
- Connect(): Establishes the WebSocket connection.
- Disconnect(): Ends the active WebSocket connection.
- AutoReconnect(enable): Enable/Disable the auto reconnect capability.
- AutoReconnect(enable, interval, retryCount): Customizes auto-reconnect functionality. Parameters include a flag to enable/disable it, the interval(in seconds) between attempts, and the maximum number of retries.
- OnOpen: Called on successful connection establishment.
- OnClose: Called when WebSocket connection has been closed.
- OnOrderUpdate: Delivers order updates.
- OnError: Signals an error has occurred.
- OnReconnecting: Announced when a reconnect attempt is initiated.
- OnAutoReconnectStopped: Informs when auto-reconnect efforts have ceased after exhausting the retry count.
- Model.ApiGatewayErrorResponse
- Model.BrokerageData
- Model.BrokerageTaxes
- Model.BrokerageWrapperData
- Model.CancelOrderData
- Model.CancelOrderResponse
- Model.ConvertPositionData
- Model.ConvertPositionRequest
- Model.ConvertPositionResponse
- Model.Depth
- Model.DepthMap
- Model.DpPlan
- Model.GetBrokerageResponse
- Model.GetFullMarketQuoteResponse
- Model.GetHistoricalCandleResponse
- Model.GetHoldingsResponse
- Model.GetIntraDayCandleResponse
- Model.GetMarketQuoteLastTradedPriceResponse
- Model.GetMarketQuoteOHLCResponse
- Model.GetOrderBookResponse
- Model.GetOrderResponse
- Model.GetPositionResponse
- Model.GetProfileResponse
- Model.GetProfitAndLossChargesResponse
- Model.GetTradeResponse
- Model.GetTradeWiseProfitAndLossDataResponse
- Model.GetTradeWiseProfitAndLossMetaDataResponse
- Model.GetUserFundMarginResponse
- Model.HistoricalCandleData
- Model.HoldingsData
- Model.IntraDayCandleData
- Model.LogoutResponse
- Model.MarketQuoteOHLC
- Model.MarketQuoteSymbol
- Model.MarketQuoteSymbolLtp
- Model.ModifyOrderData
- Model.ModifyOrderRequest
- Model.ModifyOrderResponse
- Model.OAuthClientException
- Model.OAuthClientExceptionCause
- Model.OAuthClientExceptionCauseStackTrace
- Model.OAuthClientExceptionCauseSuppressed
- Model.Ohlc
- Model.OrderBookData
- Model.OrderData
- Model.OtherTaxes
- Model.PlaceOrderData
- Model.PlaceOrderRequest
- Model.PlaceOrderResponse
- Model.PositionData
- Model.Problem
- Model.ProfileData
- Model.ProfitAndLossChargesData
- Model.ProfitAndLossChargesTaxes
- Model.ProfitAndLossChargesWrapperData
- Model.ProfitAndLossMetaData
- Model.ProfitAndLossMetaDataWrapper
- Model.ProfitAndLossOtherChargesTaxes
- Model.TokenRequest
- Model.TokenResponse
- Model.TradeData
- Model.TradeWiseMetaData
- Model.TradeWiseProfitAndLossData
- Model.UserFundMarginData
- Model.WebsocketAuthRedirectResponse
- Model.WebsocketAuthRedirectResponseData