Skip to content

upstox/upstox-java

Repository files navigation

Upstox Java SDK for API v2

Introduction

The official Java 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

Automatically generated by the Swagger Codegen

Documentation.

Upstox API Documentation

Requirements

Building the API client library requires:

  1. Java 1.7+
  2. Maven/Gradle

Installation

Maven users

Add this dependency to your project's POM:

<dependency>
  <groupId>com.upstox.api</groupId>
  <artifactId>upstox-java-sdk</artifactId>
  <version>1.3.0</version>
  <scope>compile</scope>
</dependency>

Gradle users

Add this dependency to your project's build file:

compile "com.upstox.api:upstox-java-sdk:1.3.0"

Examples

Sample Implementations can be found within /examples folder.

Documentation for API Endpoints

All URIs are relative to https://api.upstox.com/v2

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 details
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 {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        Set<String> instrumentKeys = new HashSet<>();
        instrumentKeys.add("NSE_INDEX|Nifty 50");
        instrumentKeys.add("NSE_INDEX|Bank Nifty");

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final MarketDataStreamer marketDataStreamer = new MarketDataStreamer(defaultClient, instrumentKeys, Mode.FULL);

        marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateListener() {

            @Override
            public void onUpdate(MarketUpdate marketUpdate) {
                System.out.println(marketUpdate);
            }
        });

        marketDataStreamer.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(apiClient): Initializes the streamer.
  2. constructor MarketDataStreamer(apiClient, 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

  • onOpenListener: Called on successful connection establishment.
  • onCloseListener: Called when WebSocket connection has been closed.
  • onMarketUpdateListener: Delivers market updates.
  • onErrorListener: Signals an error has occurred.
  • onReconnectingListener: Announced when a reconnect attempt is initiated.
  • onAutoReconnectStoppedListener: 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 {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final MarketDataStreamer marketDataStreamer = new MarketDataStreamer(defaultClient);

        marketDataStreamer.setOnOpenListener(new OnOpenListener() {

            @Override
            public void onOpen() {
                System.out.println("Connection Established");

                Set<String> instrumentKeys = new HashSet<>();
                instrumentKeys.add("NSE_INDEX|Nifty 50");
                instrumentKeys.add("NSE_INDEX|Bank Nifty");

                marketDataStreamer.subscribe(instrumentKeys, Mode.FULL);

            }
        });

        marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateListener() {

            @Override
            public void onUpdate(MarketUpdate marketUpdate) {
                System.out.println(marketUpdate);
            }
        });

        marketDataStreamer.connect();
    }
}

  1. Subscribing to Instruments with Delays
public class MarketFeederTest {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final MarketDataStreamer marketDataStreamer = new MarketDataStreamer(defaultClient);

        marketDataStreamer.setOnOpenListener(new OnOpenListener() {

            @Override
            public void onOpen() {
                System.out.println("Connection Established");

                Set<String> instrumentKeys1 = new HashSet<>();
                instrumentKeys1.add("NSE_INDEX|Nifty 50");

                marketDataStreamer.subscribe(instrumentKeys1, Mode.FULL);

                ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

                scheduler.schedule(() -> {
                    Set<String> instrumentKeys2 = new HashSet<>();
                    instrumentKeys2.add("NSE_INDEX|Bank Nifty");
                    marketDataStreamer.subscribe(instrumentKeys2, Mode.FULL);
                    scheduler.shutdown();
                }, 5, TimeUnit.SECONDS);

            }
        });

        marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateListener() {

            @Override
            public void onUpdate(MarketUpdate marketUpdate) {
                System.out.println(marketUpdate);
            }
        });

        marketDataStreamer.connect();
    }
}

  1. Subscribing and Unsubscribing to Instruments
public class MarketFeederTest {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final MarketDataStreamer marketDataStreamer = new MarketDataStreamer(defaultClient);

        marketDataStreamer.setOnOpenListener(new OnOpenListener() {

            @Override
            public void onOpen() {
                System.out.println("Connection Established");

                Set<String> instrumentKeys = new HashSet<>();
                instrumentKeys.add("NSE_INDEX|Nifty 50");
                instrumentKeys.add("NSE_INDEX|Bank Nifty");

                marketDataStreamer.subscribe(instrumentKeys, Mode.FULL);

                ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

                scheduler.schedule(() -> {
                    marketDataStreamer.unsubscribe(instrumentKeys);
                    scheduler.shutdown();
                }, 5, TimeUnit.SECONDS);

            }
        });

        marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateListener() {

            @Override
            public void onUpdate(MarketUpdate marketUpdate) {
                System.out.println(marketUpdate);
            }
        });

        marketDataStreamer.connect();
    }
}

  1. Subscribe, Change Mode and Unsubscribe
public class MarketFeederTest {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final MarketDataStreamer marketDataStreamer = new MarketDataStreamer(defaultClient);

        marketDataStreamer.setOnOpenListener(new OnOpenListener() {

            @Override
            public void onOpen() {
                System.out.println("Connection Established");

                Set<String> instrumentKeys = new HashSet<>();
                instrumentKeys.add("NSE_INDEX|Nifty 50");
                instrumentKeys.add("NSE_INDEX|Bank Nifty");

                marketDataStreamer.subscribe(instrumentKeys, Mode.FULL);

                ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

                scheduler.schedule(() -> {
                    marketDataStreamer.changeMode(instrumentKeys, Mode.LTPC);
                    scheduler.shutdown();
                }, 5, TimeUnit.SECONDS);

                scheduler.schedule(() -> {
                    marketDataStreamer.unsubscribe(instrumentKeys);
                    scheduler.shutdown();
                }, 10, TimeUnit.SECONDS);

            }
        });

        marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateListener() {

            @Override
            public void onUpdate(MarketUpdate marketUpdate) {
                System.out.println(marketUpdate);
            }
        });

        marketDataStreamer.connect();
    }
}

  1. Disable Auto-Reconnect
public class MarketFeederTest {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final MarketDataStreamer marketDataStreamer = new MarketDataStreamer(defaultClient);

        marketDataStreamer.setOnAutoReconnectStoppedListener(new OnAutoReconnectStoppedListener() {

            @Override
            public void onHault(String message) {
                System.out.println(message);

            }
        });

        marketDataStreamer.autoReconnect(false);
        marketDataStreamer.connect();
    }
}

  1. Modify Auto-Reconnect parameters
public class MarketFeederTest {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final MarketDataStreamer marketDataStreamer = new MarketDataStreamer(defaultClient);

        marketDataStreamer.autoReconnect(true, 10, 3);
        marketDataStreamer.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 {
    public static void main(String[] args) throws ApiException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
        oAuth.setAccessToken(<ACCESS_TOKEN>);

        final PortfolioDataStreamer portfolioDataStreamer = new PortfolioDataStreamer(defaultClient);

        portfolioDataStreamer.setOnOrderUpdateListener(new OnOrderUpdateListener() {

            @Override
            public void onUpdate(OrderUpdate orderUpdate) {
                System.out.println(orderUpdate);

            }
        });

        portfolioDataStreamer.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(apiClient): 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

  • onOpenListener: Called on successful connection establishment.
  • onCloseListener: Called when WebSocket connection has been closed.
  • onOrderUpdateListener: Delivers order updates.
  • onErrorListener: Signals an error has occurred.
  • onReconnectingListener: Announced when a reconnect attempt is initiated.
  • onAutoReconnectStoppedListener: Informs when auto-reconnect efforts have ceased after exhausting the retry count.

Documentation for Models

Recommendation

It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issues.