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.
Automatically generated by the Swagger Codegen
Building the API client library requires:
Add this dependency to your project’s POM:
<dependency>
<groupId>com.upstox.api</groupId>
<artifactId>upstox-java-sdk</artifactId>
<version>1.18</version>
<scope>compile</scope>
</dependency>
Add this dependency to your project’s build file:
compile "com.upstox.api:upstox-java-sdk:1.18"
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 ID for order tracking and management. When provided, the SDK will pass the algo ID as X-Algo-Id
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 AlgoIdExample {
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 identifier for tracking
String algoId = "my-trading-algorithm-v1.0";
try {
// Place order with algo_id parameter
PlaceOrderV3Response result = orderApiV3.placeOrder(body, algoId);
System.out.println("Order placed with Algo ID: " + result);
} catch (ApiException e) {
System.err.println("Exception when calling OrderApiV3#placeOrder with algo_id");
e.printStackTrace();
}
}
}
Other order methods (modify, cancel, etc.) follow the same pattern by accepting an optional algo_id
as the last parameter.
To learn more about the sandbox environment and the available sandbox APIs, please visit the Upstox API documentation - Sandbox.
Sample Implementations can be found within /examples
folder.
All URIs are relative to https://api.upstox.com/v2
Class | Method | HTTP request | Description |
---|---|---|---|
ChargeApi | getBrokerage | GET /v2/charges/brokerage | Brokerage details |
ChargeApi | postMargin | POST /v2/charges/margin | Calculate Margin |
ExpiredInstrumentApi | getExpiredFutureContracts | GET /v2/expired-instruments/future/contract | Expired instruments - Get future contracts |
ExpiredInstrumentApi | getExpiredHistoricalCandleData | GET /v2/expired-instruments/historical-candle/{expired_instrument_key}/{interval}/{to_date}/{from_date} | Expired Historical candle data |
ExpiredInstrumentApi | getExpiredOptionContracts | GET /v2/expired-instruments/option/contract | Get expired option contracts |
ExpiredInstrumentApi | getExpiries | GET /v2/expired-instruments/expiries | Expired instruments - Get expiries |
HistoryApi | getHistoricalCandleData2 | GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date} | Historical candle data |
HistoryApi | getHistoricalCandleData3 | GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date}/{from_date} | Historical candle data |
HistoryApi | getIntraDayCandleData1 | GET /v2/historical-candle/intraday/{instrumentKey}/{interval} | Intra day candle data |
HistoryV3Api | getHistoricalCandleData | GET /v3/historical-candle/{instrumentKey}/{unit}/{interval}/{to_date} | Historical candle data |
HistoryV3Api | getHistoricalCandleData1 | GET /v3/historical-candle/{instrumentKey}/{unit}/{interval}/{to_date}/{from_date} | Historical candle data |
HistoryV3Api | getIntraDayCandleData | GET /v3/historical-candle/intraday/{instrumentKey}/{unit}/{interval} | Intra day candle data |
LoginApi | authorize | GET /v2/login/authorization/dialog | Authorize API |
LoginApi | autoLogin | GET /v2/auth/auto-login | Auto Login |
LoginApi | logout | DELETE /v2/logout | Logout |
LoginApi | token | POST /v2/login/authorization/token | Get token API |
MarketHolidaysAndTimingsApi | getExchangeTimings | GET /v2/market/timings/{date} | Get Exchange Timings on particular date |
MarketHolidaysAndTimingsApi | getHoliday | GET /v2/market/holidays/{date} | Get Holiday on particular date |
MarketHolidaysAndTimingsApi | getHolidays | GET /v2/market/holidays | Get Holiday list of current year |
MarketHolidaysAndTimingsApi | getMarketStatus | GET /v2/market/status/{exchange} | Get Market status for particular exchange |
MarketQuoteApi | getFullMarketQuote | GET /v2/market-quote/quotes | Market quotes and instruments - Full market quotes |
MarketQuoteApi | getMarketQuoteOHLC | GET /v2/market-quote/ohlc | Market quotes and instruments - OHLC quotes |
MarketQuoteApi | ltp | GET /v2/market-quote/ltp | Market quotes and instruments - LTP quotes. |
MarketQuoteV3Api | getLtp | GET /v3/market-quote/ltp | Market quotes and instruments - LTP quotes. |
MarketQuoteV3Api | getMarketQuoteOHLC | GET /v3/market-quote/ohlc | Market quotes and instruments - OHLC quotes |
MarketQuoteV3Api | getMarketQuoteOptionGreek | GET /v3/market-quote/option-greek | Market quotes and instruments - Option Greek |
OptionsApi | getOptionContracts | GET /v2/option/contract | Get option contracts |
OptionsApi | getPutCallOptionChain | GET /v2/option/chain | Get option chain |
OrderApi | cancelMultiOrder | DELETE /v2/order/multi/cancel | Cancel multi order |
OrderApi | cancelOrder | DELETE /v2/order/cancel | Cancel order |
OrderApi | exitPositions | POST /v2/order/positions/exit | Exit all positions |
OrderApi | getOrderBook | GET /v2/order/retrieve-all | Get order book |
OrderApi | getOrderDetails | GET /v2/order/history | Get order history |
OrderApi | getOrderStatus | GET /v2/order/details | Get order details |
OrderApi | getTradeHistory | GET /v2/order/trades/get-trades-for-day | Get trades |
OrderApi | getTradesByOrder | GET /v2/order/trades | Get trades for order |
OrderApi | modifyOrder | PUT /v2/order/modify | Modify order |
OrderApi | placeMultiOrder | POST /v2/order/multi/place | Place multi order |
OrderApi | placeOrder1 | POST /v2/order/place | Place order |
OrderApiV3 | cancelOrder | DELETE /v3/order/cancel | |
OrderApiV3 | modifyOrder | PUT /v3/order/modify | |
OrderApiV3 | placeOrder | POST /v3/order/place | |
PortfolioApi | convertPositions | PUT /v2/portfolio/convert-position | Convert Positions |
PortfolioApi | getHoldings | GET /v2/portfolio/long-term-holdings | Get Holdings |
PortfolioApi | getMtfPositions | GET /v3/portfolio/mtf-positions | Get MTF positions |
PortfolioApi | getPositions | GET /v2/portfolio/short-term-positions | Get Positions |
PostTradeApi | getTradesByDateRange | GET /v2/charges/historical-trades | Get historical trades |
TradeProfitAndLossApi | getProfitAndLossCharges | GET /v2/trade/profit-loss/charges | Get profit and loss on trades |
TradeProfitAndLossApi | getTradeWiseProfitAndLossData | GET /v2/trade/profit-loss/data | Get Trade-wise Profit and Loss Report Data |
TradeProfitAndLossApi | getTradeWiseProfitAndLossMetaData | GET /v2/trade/profit-loss/metadata | Get profit and loss meta data on trades |
UserApi | getProfile | GET /v2/user/profile | Get profile |
UserApi | getUserFundMargin | GET /v2/user/get-funds-and-margin | Get User Fund And Margin |
WebsocketApi | getMarketDataFeed | GET /v2/feed/market-data-feed | Market Data Feed |
WebsocketApi | getMarketDataFeedAuthorize | GET /v2/feed/market-data-feed/authorize | Market Data Feed Authorize |
WebsocketApi | getPortfolioStreamFeed | GET /v2/feed/portfolio-stream-feed | Portfolio Stream Feed |
WebsocketApi | getPortfolioStreamFeedAuthorize | GET /v2/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:
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.FULL
, Mode.LTPC
, Mode.FULL_D30
or Mode.OPTION_GREEKS
).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.
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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
It’s recommended to create an instance of ApiClient
per thread in a multithreaded environment to avoid any potential issues.