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.19</version>
<scope>compile</scope>
</dependency>Add this dependency to your project's build file:
compile "com.upstox.api:upstox-java-sdk:1.19"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.
- Place, Modify, and Cancel Order APIs are relative to
https://api-hft.upstox.com - All other APIs are relative to
https://api.upstox.com
| API Name | HTTP Request | Class | Documentation | Sample Codes |
|---|---|---|---|---|
| Expired Instruments | ||||
| Get Expiries | GET /v2/expired-instruments/expiries | ExpiredInstrumentApi | API Reference | Sample Code |
| Get Expired Option Contracts | GET /v2/expired-instruments/option/contract | ExpiredInstrumentApi | API Reference | Sample Code |
| Get Expired Future Contracts | GET /v2/expired-instruments/future/contract | ExpiredInstrumentApi | API Reference | Sample Code |
| Get Expired Historical Candle Data | GET /v2/expired-instruments/historical-candle/{expired_instrument_key}/{interval}/{to_date}/{from_date} | ExpiredInstrumentApi | API Reference | Sample Code |
| Login | ||||
| Get Token | POST /v2/login/authorization/token | LoginApi | API Reference | Sample Code |
| Access Token Request | POST /v3/login/auth/token/request/{client_id} | LoginApi | API Reference | Sample Code |
| Logout | DELETE /v2/logout | LoginApi | API Reference | Sample Code |
| User | ||||
| Get Profile | GET /v2/user/profile | UserApi | API Reference | Sample Code |
| Get User Fund Margin | GET /v2/user/get-funds-and-margin | UserApi | API Reference | Sample Code |
| Charges | ||||
| Get Brokerage | GET /v2/charges/brokerage | ChargeApi | API Reference | Sample Code |
| Margins | ||||
| Margin | POST /v2/charges/margin | ChargeApi | API Reference | Sample Code |
| Orders | ||||
| Place Order V3 | POST /v3/order/place | OrderApiV3 | API Reference | Sample Code |
| Place Multi Order | POST /v2/order/multi/place | OrderApi | API Reference | Sample Code |
| Modify Order V3 | PUT /v3/order/modify | OrderApiV3 | API Reference | Sample Code |
| Cancel Order V3 | DELETE /v3/order/cancel | OrderApiV3 | API Reference | Sample Code |
| Cancel Multi Order | DELETE /v2/order/multi/cancel | OrderApi | API Reference | Sample Code |
| Exit All Position | POST /v2/order/positions/exit | OrderApi | API Reference | Sample Code |
| Get Order Details | GET /v2/order/details | OrderApi | API Reference | Sample Code |
| Get Order History | GET /v2/order/history | OrderApi | API Reference | Sample Code |
| Get Trades By Order | GET /v2/order/trades | OrderApi | API Reference | Sample Code |
| Get Trade History | GET /v2/order/trades/get-trades-for-day | OrderApi | API Reference | Sample Code |
| GTT Order | ||||
| Place GTT Order | POST /v3/order/gtt/place | OrderApiV3 | API Reference | Sample Code |
| Modify GTT Order | PUT /v3/order/gtt/modify | OrderApiV3 | API Reference | Sample Code |
| Cancel GTT Order | DELETE /v3/order/gtt/cancel | OrderApiV3 | API Reference | Sample Code |
| Get GTT Order Details | GET /v3/order/gtt | OrderApiV3 | API Reference | Sample Code |
| Portfolio | ||||
| Get Positions | GET /v2/portfolio/short-term-positions | PortfolioApi | API Reference | Sample Code |
| Get MTF Positions | GET /v3/portfolio/mtf | PortfolioApi | API Reference | Sample Code |
| Convert Positions | PUT /v2/portfolio/convert-position | PortfolioApi | API Reference | Sample Code |
| Get Holdings | GET /v2/portfolio/long-term-holdings | PortfolioApi | API Reference | Sample Code |
| Trade Profit And Loss | ||||
| Get Report Meta Data | GET /v2/trade/profit-loss/metadata | TradeProfitAndLossApi | API Reference | Sample Code |
| Get Profit And Loss Report | GET /v2/trade/profit-loss/data | TradeProfitAndLossApi | API Reference | Sample Code |
| Get Trade Charges | GET /v2/trade/profit-loss/charges | TradeProfitAndLossApi | API Reference | Sample Code |
| Historical Data | ||||
| Get Historical Candle Data V3 | GET /v3/historical-candle | HistoryV3Api | API Reference | Sample Code |
| Get Intra Day Candle Data V3 | GET /v3/intra-day-candle | HistoryV3Api | API Reference | Sample Code |
| Market Quote | ||||
| Get Full Market Quote | GET /v2/market-quote/quotes | MarketQuoteApi | API Reference | Sample Code |
| Get Market Quote OHLC | GET /v2/market-quote/ohlc | MarketQuoteApi | API Reference | Sample Code |
| LTP V3 | GET /v3/market-quote/ltp | MarketQuoteV3Api | API Reference | Sample Code |
| Option Greek | GET /v3/market-quote/greeks | MarketQuoteV3Api | API Reference | Sample Code |
| Market Information | ||||
| Get Market Holidays | GET /v2/market/holidays | MarketHolidaysAndTimingsApi | API Reference | Sample Code |
| Get Market Timings | GET /v2/market/timings | MarketHolidaysAndTimingsApi | API Reference | Sample Code |
| Get Market Status | GET /v2/market/status | MarketHolidaysAndTimingsApi | API Reference | Sample Code |
| Option Chain | ||||
| Get Option Contracts | GET /v2/option/contract | OptionsApi | API Reference | Sample Code |
| Get PC Option Chain | GET /v2/option/chain | OptionsApi | API Reference | Sample Code |
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.