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
Building the API client library requires:
- Java 1.7+
- Maven/Gradle
Add this dependency to your project's POM:
<dependency>
<groupId>com.upstox.api</groupId>
<artifactId>upstox-java-sdk</artifactId>
<version>1.21</version>
<scope>compile</scope>
</dependency>Add this dependency to your project's build file:
compile "com.upstox.api:upstox-java-sdk:1.21"We recommend using the sandbox environment for testing purposes. To enable sandbox mode, set the sandbox flag to True in the ApiClient object.
import com.upstox.ApiClient;
import com.upstox.ApiException;
import com.upstox.Configuration;
import com.upstox.api.*;
import com.upstox.auth.OAuth;
import io.swagger.client.api.OrderApiV3;
public class Main{
public static void main(String[] args) {
boolean sandbox = true;
ApiClient sandboxClient = new ApiClient(sandbox);
OAuth OAUTH2 = (OAuth) sandboxClient.getAuthentication("OAUTH2");
OAUTH2.setAccessToken("SANDBOX_ACCESS_TOKEN");
Configuration.setDefaultApiClient(sandboxClient);
OrderApiV3 orderApiV3 = new OrderApiV3();
PlaceOrderV3Request body = new PlaceOrderV3Request();
body.setQuantity(10);
body.setProduct(PlaceOrderV3Request.ProductEnum.D);
body.setValidity(PlaceOrderV3Request.ValidityEnum.DAY);
body.setPrice(9F);
body.setTag("string");
body.setInstrumentToken("NSE_EQ|INE669E01016");
body.orderType(PlaceOrderV3Request.OrderTypeEnum.LIMIT);
body.setTransactionType(PlaceOrderV3Request.TransactionTypeEnum.BUY);
body.setDisclosedQuantity(0);
body.setTriggerPrice(0F);
body.setIsAmo(false);
body.setSlice(true);
try {
PlaceOrderV3Response result = orderApiV3.placeOrder(body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrderApi#placeOrder ");
e.printStackTrace();
}
}
}The SDK supports passing an algorithm name for order tracking and management. When provided, the SDK will pass the algo name as X-Algo-Name header.
import com.upstox.ApiClient;
import com.upstox.ApiException;
import com.upstox.Configuration;
import com.upstox.api.*;
import com.upstox.auth.OAuth;
import io.swagger.client.api.OrderApiV3;
public class AlgoNameExample {
public static void main(String[] args) {
boolean sandbox = true;
ApiClient sandboxClient = new ApiClient(sandbox);
OAuth OAUTH2 = (OAuth) sandboxClient.getAuthentication("OAUTH2");
OAUTH2.setAccessToken("SANDBOX_ACCESS_TOKEN");
Configuration.setDefaultApiClient(sandboxClient);
OrderApiV3 orderApiV3 = new OrderApiV3();
PlaceOrderV3Request body = new PlaceOrderV3Request();
body.setQuantity(1);
body.setProduct(PlaceOrderV3Request.ProductEnum.D);
body.setValidity(PlaceOrderV3Request.ValidityEnum.DAY);
body.setPrice(100F);
body.setTag("algo_strategy_v1");
body.setInstrumentToken("NSE_EQ|INE669E01016");
body.orderType(PlaceOrderV3Request.OrderTypeEnum.LIMIT);
body.setTransactionType(PlaceOrderV3Request.TransactionTypeEnum.BUY);
body.setDisclosedQuantity(0);
body.setTriggerPrice(0F);
body.setIsAmo(false);
// Custom algo name for tracking
String algoName = "my-trading-algorithm-v1.0";
try {
// Place order with algo_name parameter
PlaceOrderV3Response result = orderApiV3.placeOrder(body, algoName);
System.out.println("Order placed with Algo Name: " + result);
} catch (ApiException e) {
System.err.println("Exception when calling OrderApiV3#placeOrder with algo_name");
e.printStackTrace();
}
}
}Other order methods (modify, cancel, etc.) follow the same pattern by accepting an optional algo_name as the last parameter.
To learn more about the sandbox environment and the available sandbox APIs, please visit the Upstox API documentation - Sandbox.
The examples/ folder contains ready-to-run scripts covering common API use cases:
| Folder | Description |
|---|---|
examples/login/ |
OAuth2 authorization flow and access token generation |
examples/orders/ |
Place, modify, cancel, and retrieve orders |
examples/market-quote/ |
Fetch live quotes, OHLC, and market depth |
examples/portfolio/ |
View holdings, positions, and P&L |
examples/strategies/ |
33 options trading strategies across four categories |
The examples/strategies/ folder is organized by market outlook:
| Category | Strategies |
|---|---|
| Bullish | Buy Call, Sell Put, Bull Call Spread, Bull Put Spread, Bull Butterfly, Bull Condor, Long Calendar with Calls, Long Synthetic Future, Call Ratio Back Spread, Range Forward |
| Bearish | Buy Put, Sell Call, Bear Call Spread, Bear Put Spread, Bear Butterfly, Bear Condor, Long Calendar with Puts, Short Synthetic Future, Put Ratio Back Spread, Risk Reversal |
| Neutral | Short Straddle, Short Strangle, Iron Butterfly, Batman, Short Iron Condor |
| Others | Long Straddle, Long Strangle, Call Ratio Spread, Put Ratio Spread, Long Iron Butterfly, Long Iron Condor, Strip, Strap |
Each strategy script automatically selects the correct Nifty 50 strikes using InstrumentsApi.searchInstrument() and places orders via OrderApiV3. Just set your ACCESS_TOKEN and run.
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 MarketDataStreamerV3 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|Nifty Bank");
OAuth oAuth = (OAuth) defaultClient.getAuthentication("OAUTH2");
oAuth.setAccessToken(<ACESS_TOKEN>);
final MarketDataStreamerV3 marketDataStreamer = new MarketDataStreamerV3(defaultClient, instrumentKeys, Mode.FULL_D30);
marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateV3Listener() {
@Override
public void onUpdate(MarketUpdateV3 marketUpdate) {
System.out.println(marketUpdate);
}
});
marketDataStreamer.connect();
}
}In this example, you first authenticate using an access token, then instantiate MarketDataStreamerV3 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.
- Mode.FULL_D30: full_d30 includes Full mode data plus 30 market level quotes.
- Mode.OPTION_GREEKS: Contains only option greeks.
- constructor MarketDataStreamerV3(apiClient): Initializes the streamer.
- constructor MarketDataStreamerV3(apiClient, instrumentKeys, mode): Initializes the streamer with instrument keys and mode (
Mode.FULL,Mode.LTPC,Mode.FULL_D30orMode.OPTION_GREEKS). - 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.
- onOpenListener: Called on successful connection establishment.
- onCloseListener: Called when WebSocket connection has been closed.
- OnMarketUpdateV3Listener: 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 MarketDataStreamerV3 effectively.
- Subscribing to Market Data on Connection Open with MarketDataStreamerV3
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 MarketDataStreamerV3 marketDataStreamer = new MarketDataStreamerV3(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|Nifty Bank");
marketDataStreamer.subscribe(instrumentKeys, Mode.FULL);
}
});
marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateV3Listener() {
@Override
public void onUpdate(MarketUpdateV3 marketUpdate) {
System.out.println(marketUpdate);
}
});
marketDataStreamer.connect();
}
}- 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 MarketDataStreamerV3 marketDataStreamer = new MarketDataStreamerV3(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|Nifty Bank");
marketDataStreamer.subscribe(instrumentKeys2, Mode.FULL);
scheduler.shutdown();
}, 5, TimeUnit.SECONDS);
}
});
marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateV3Listener() {
@Override
public void onUpdate(MarketUpdateV3 marketUpdate) {
System.out.println(marketUpdate);
}
});
marketDataStreamer.connect();
}
}- 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 MarketDataStreamerV3 marketDataStreamer = new MarketDataStreamerV3(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|Nifty Bank");
marketDataStreamer.subscribe(instrumentKeys, Mode.FULL);
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.schedule(() -> {
marketDataStreamer.unsubscribe(instrumentKeys);
scheduler.shutdown();
}, 5, TimeUnit.SECONDS);
}
});
marketDataStreamer.setOnMarketUpdateListener(new OnMarketUpdateV3Listener() {
@Override
public void onUpdate(MarketUpdateV3 marketUpdate) {
System.out.println(marketUpdate);
}
});
marketDataStreamer.connect();
}
}- 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 MarketDataStreamerV3 marketDataStreamer = new MarketDataStreamerV3(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|Nifty Bank");
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 OnMarketUpdateV3Listener() {
@Override
public void onUpdate(MarketUpdateV3 marketUpdate) {
System.out.println(marketUpdate);
}
});
marketDataStreamer.connect();
}
}- 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 MarketDataStreamerV3 marketDataStreamer = new MarketDataStreamerV3(defaultClient);
marketDataStreamer.setOnAutoReconnectStoppedListener(new OnAutoReconnectStoppedListener() {
@Override
public void onHault(String message) {
System.out.println(message);
}
});
marketDataStreamer.autoReconnect(false);
marketDataStreamer.connect();
}
}- 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 MarketDataStreamerV3 marketDataStreamer = new MarketDataStreamerV3(defaultClient);
marketDataStreamer.autoReconnect(true, 10, 3);
marketDataStreamer.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 {
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();
}
}Position, holding, GTT updates can be enabled by setting the corresponding flag to true in the constructor of the PortfolioDataStreamer class.
import com.upstox.feeder.HoldingUpdate;
import com.upstox.feeder.PositionUpdate;
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, true, true, true, true);
portfolioDataStreamer.setOnOrderUpdateListener(new OnOrderUpdateListener() {
@Override
public void onUpdate(OrderUpdate orderUpdate) {
System.out.println(orderUpdate);
}
});
portfolioDataStreamer.setOnHoldingUpdateListener(new OnHoldingUpdateListener() {
@Override
public void onUpdate(HoldingUpdate holdingUpdate) {
System.out.println(holdingUpdate);
}
});
portfolioDataStreamer.setOnPositionUpdateListener(new OnPositionUpdateListener() {
@Override
public void onUpdate(PositionUpdate positionUpdate) {
System.out.println(positionUpdate);
}
});
portfolioDataStreamer.setOnGttUpdateListener(new OnGttUpdateListener() {
@Override
public void onUpdate(GttUpdate gttUpdate) {
System.out.println(gttUpdate);
}
});
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 with your valid access token to authenticate the session.
- constructor PortfolioDataStreamer(apiClient): 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.
- 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.
It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issues.