Skip to content

upstox/upstox-dotnet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Upstox .Net SDK for API v2

Introduction

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:

Documentation.

Upstox API Documentation

Frameworks supported

  • .NET 4.0 or later

  • Windows Phone 7.1 (Mango)

Dependencies

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

Installation

Nuget

Run nuget install upstox-dotnet-sdk to install the SDK from Nuget.

Github

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;

Packaging

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.

Documentation for API Endpoints

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

Documentation for Feeder Interfaces

Connecting to the WebSocket for market and portfolio updates is streamlined through two primary Feeder functions:

  1. MarketDataStreamer: Offers real-time market updates, providing a seamless way to receive instantaneous information on various market instruments.
  2. 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.

Detailed Explanation of Feeder Interfaces

MarketDataStreamer

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.

Exploring the MarketDataStreamer Functionality

Modes

  • 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.

Functions

  1. constructor MarketDataStreamer(): Initializes the streamer.
  2. constructor MarketDataStreamer(instrumentKeys, mode): Initializes the streamer with instrument keys and mode (Mode.Full or Mode.Ltpc).
  3. Connect(): Establishes the WebSocket connection.
  4. Subscribe(instrumentKeys, mode): Subscribes to updates for given instrument keys in the specified mode. Both parameters are mandatory.
  5. Unsubscribe(instrumentKeys): Stops updates for the specified instrument keys.
  6. ChangeMode(instrumentKeys, mode): Switches the mode for already subscribed instrument keys.
  7. Disconnect(): Ends the active WebSocket connection.
  8. AutoReconnect(enable): Enable/Disable the auto reconnect capability.
  9. 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.

Events Listeners

  • 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.


  1. 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();
        }
}

  1. 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();
        }
}

  1. 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();
        }
}

  1. 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();
        }
}

  1. 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();
        }
}

  1. 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();
        }
}

PortfolioDataStreamer

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.

Exploring the PortfolioDataStreamer Functionality

Functions

  1. constructor PortfolioDataStreamer(): Initializes the streamer.
  2. Connect(): Establishes the WebSocket connection.
  3. Disconnect(): Ends the active WebSocket connection.
  4. AutoReconnect(enable): Enable/Disable the auto reconnect capability.
  5. 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.

Events Listeners

  • 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.

Documentation for Models