Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

207 Commits

Repository files navigation

SmartAPI 2.2.0 Java client

The official Java client for communicating with SmartAPI Connect API.

SmartAPI is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real-time, manage user portfolios, stream live market data (WebSockets), and more, with the simple HTTP API collection.

Documentation

Usage

  • Download SmartAPI jar file and include it in your build path.

  • Include com.angelbroking.smartapi into build path from maven. Use version 2.2.0

API usage

// Initialize SamartAPI using Client code, Password, and TOTP.SmartConnectsmartConnect = newSmartConnect();
// Provide your API key heresmartConnect.setApiKey("<api_key>");
// Set session expiry callback.smartConnect.setSessionExpiryHook(newSessionExpiryHook() {
@OverridepublicvoidsessionExpired() {
System.out.println("session expired");
}
});
Useruser = smartConnect.generateSession(<clientId>, <password>, <totp>);
smartConnect.setAccessToken(user.getAccessToken());
smartConnect.setUserId(user.getUserId());
// token re-generateTokenSettokenSet = smartConnect.renewAccessToken(user.getAccessToken(),
user.getRefreshToken());
smartConnect.setAccessToken(tokenSet.getAccessToken());
/** CONSTANT Details *//* VARIETY *//* * VARIETY_NORMAL: Normal Order (Regular)  * VARIETY_AMO: After Market Order * VARIETY_STOPLOSS: Stop loss order  * VARIETY_ROBO: ROBO (Bracket) Order *//* TRANSACTION TYPE *//* * TRANSACTION_TYPE_BUY: Buy TRANSACTION_TYPE_SELL: Sell *//* ORDER TYPE *//* * ORDER_TYPE_MARKET: Market Order(MKT)  * ORDER_TYPE_LIMIT: Limit Order(L) * ORDER_TYPE_STOPLOSS_LIMIT: Stop Loss Limit Order(SL) * ORDER_TYPE_STOPLOSS_MARKET: Stop Loss Market Order(SL-M) *//* PRODUCT TYPE *//* * PRODUCT_DELIVERY: Cash & Carry for equity (CNC)  * PRODUCT_CARRYFORWARD: Normal * for futures and options (NRML)  * PRODUCT_MARGIN: Margin Delivery * PRODUCT_INTRADAY: Margin Intraday Squareoff (MIS)  * PRODUCT_BO: Bracket Order * (Only for ROBO) *//* DURATION *//* * DURATION_DAY: Valid for a day  * DURATION_IOC: Immediate or Cancel *//* EXCHANGE *//* * EXCHANGE_BSE: BSE Equity  * EXCHANGE_NSE: NSE Equity  * EXCHANGE_NFO: NSE Future and Options  * EXCHANGE_CDS: NSE Currency  * EXCHANGE_NCDEX: NCDEX Commodity * EXCHANGE_MCX: MCX Commodity *//** Place order. */publicvoidplaceOrder(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
OrderParamsorderParams = newOrderParams();
orderParams.variety = "NORMAL";
orderParams.quantity = 1;
orderParams.symboltoken = "3045";
orderParams.exchange = Constants.EXCHANGE_NSE;
orderParams.ordertype = Constants.ORDER_TYPE_LIMIT;
orderParams.tradingsymbol = "SBIN-EQ";
orderParams.producttype = Constants.PRODUCT_INTRADAY;
orderParams.duration = Constants.VALIDITY_DAY;
orderParams.transactiontype = Constants.TRANSACTION_TYPE_BUY;
orderParams.price = 122.2;
orderParams.squareoff = "0";
orderParams.stoploss = "0";
Orderorder = smartConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR);
}
/** Modify order. */publicvoidmodifyOrder(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
// Modify order request will return the order model which will contain order_id.OrderParamsorderParams = newOrderParams();
orderParams.quantity = 1;
orderParams.ordertype = Constants.ORDER_TYPE_LIMIT;
orderParams.tradingsymbol = "ASHOKLEY";
orderParams.symboltoken = "3045";
orderParams.producttype = Constants.PRODUCT_DELIVERY;
orderParams.exchange = Constants.EXCHANGE_NSE;
orderParams.duration = Constants.VALIDITY_DAY;
orderParams.price = 122.2;
StringorderId = "201216000755110";
Orderorder = smartConnect.modifyOrder(orderId, orderParams, Constants.VARIETY_REGULAR);
}
/** Cancel order */publicvoidcancelOrder(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
// Cancel order will return the order model which will have orderId.StringorderId = "201216000755110";
Orderorder = smartConnect.cancelOrder(orderId, Constants.VARIETY_REGULAR);
}
/** Get order details */publicvoidgetOrder(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
List<Order> orders = smartConnect.getOrderHistory(smartConnect.getUserId());
for (inti = 0; i < orders.size(); i++) {
System.out.println(orders.get(i).orderId + " " + orders.get(i).status);
}
}
/** * Get the last price for multiple instruments at once. Users can either pass * exchange with tradingsymbol or instrument token only. For example {NSE:NIFTY * 50, BSE:SENSEX} or {256265, 265} */publicvoidgetLTP(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
Stringexchange = "NSE";
StringtradingSymbol = "SBIN-EQ";
Stringsymboltoken = "3045";
JSONObjectltpData = smartConnect.getLTP(exchange, tradingSymbol, symboltoken);
}
/** Get tradebook */publicvoidgetTrades(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
// Returns tradebook.List<Trade> trades = smartConnect.getTrades();
for (inti = 0; i < trades.size(); i++) {
System.out.println(trades.get(i).tradingSymbol + " " + trades.size());
}
}
/** Get Margin in trading account*/publicvoidgetRMS(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
// Returns RMS.JSONObjectresponse = smartConnect.getRMS();
}
/** Get Holdings */publicvoidgetHolding(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
// Returns Holding.JSONObjectresponse = smartConnect.getHolding();
}
/** Get All Holdings */publicvoidgetAllHolding(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
// Returns Holdings.JSONObjectresponse = smartConnect.getAllHolding();
}
/** Get Position */publicvoidgetPosition(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
// Returns Position.JSONObjectresponse = smartConnect.getPosition();
}
/** convert Position */publicvoidconvertPosition(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
JSONObjectrequestObejct = newJSONObject();
requestObejct.put("exchange", "NSE");
requestObejct.put("oldproducttype", "DELIVERY");
requestObejct.put("newproducttype", "MARGIN");
requestObejct.put("tradingsymbol", "SBIN-EQ");
requestObejct.put("transactiontype", "BUY");
requestObejct.put("quantity", 1);
requestObejct.put("type", "DAY");
JSONObjectresponse = smartConnect.convertPosition(requestObejct);
}
/** Create Gtt Rule*/publicvoidcreateRule(SmartConnectsmartConnect)throwsSmartAPIException,IOException{
GttParamsgttParams= newGttParams();
gttParams.tradingsymbol="SBIN-EQ";
gttParams.symboltoken="3045";
gttParams.exchange="NSE";
gttParams.producttype="MARGIN";
gttParams.transactiontype="BUY";
gttParams.price= 100000.01;
gttParams.qty=10;
gttParams.disclosedqty=10;
gttParams.triggerprice=20000.1;
gttParams.timeperiod=300;
Gttgtt = smartConnect.gttCreateRule(gttParams);
}
/** Modify Gtt Rule */publicvoidmodifyRule(SmartConnectsmartConnect)throwsSmartAPIException,IOException{
GttParamsgttParams= newGttParams();
gttParams.tradingsymbol="SBIN-EQ";
gttParams.symboltoken="3045";
gttParams.exchange="NSE";
gttParams.producttype="MARGIN";
gttParams.transactiontype="BUY";
gttParams.price= 100000.1;
gttParams.qty=10;
gttParams.disclosedqty=10;
gttParams.triggerprice=20000.1;
gttParams.timeperiod=300;
Integerid= 1000051;
Gttgtt = smartConnect.gttModifyRule(id,gttParams);
}
/** Cancel Gtt Rule */publicvoidcancelRule(SmartConnectsmartConnect)throwsSmartAPIException, IOException{
Integerid=1000051;
Stringsymboltoken="3045";
Stringexchange="NSE";
Gttgtt = smartConnect.gttCancelRule(id,symboltoken,exchange);
}
/** Gtt Rule Details */publicvoidruleDetails(SmartConnectsmartConnect)throwsSmartAPIException, IOException{
Integerid=1000051;
JSONObjectgtt = smartConnect.gttRuleDetails(id);
}
/** Gtt Rule Lists */publicvoidruleList(SmartConnectsmartConnect)throwsSmartAPIException, IOException{
List<String> status=newArrayList<String>(){{
add("NEW");
add("CANCELLED");
add("ACTIVE");
add("SENTTOEXCHANGE");
add("FORALL");
}};
Integerpage=1;
Integercount=10;
JSONArraygtt = smartConnect.gttRuleList(status,page,count);
}
/** Historic Data */publicvoidgetCandleData(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
JSONObjectrequestObejct = newJSONObject();
requestObejct.put("exchange", "NSE");
requestObejct.put("symboltoken", "3045");
requestObejct.put("interval", "ONE_MINUTE");
requestObejct.put("fromdate", "2021-03-08 09:00");
requestObejct.put("todate", "2021-03-09 09:20");
Stringresponse = smartConnect.candleData(requestObejct);
}
/** Search Scrip Data */publicvoidgetSearchScrip(SmartConnectsmartConnect) throwsSmartAPIException{
JSONObjectpayload = newJSONObject();
payload.put("exchange", "MCX");
payload.put("searchscrip", "Crude");
Stringresponse = smartConnect.getSearchScrip(payload);
}
/** Logout user. *//** Market Data FULL*/publicvoidgetMarketData(SmartConnectsmartConnect) {
JSONObjectpayload = newJSONObject();
payload.put("mode", "FULL");
JSONObjectexchangeTokens = newJSONObject();
JSONArraynseTokens = newJSONArray();
nseTokens.put("3045");
exchangeTokens.put("NSE", nseTokens);
payload.put("exchangeTokens", exchangeTokens);
JSONObjectresponse = smartConnect.marketData(payload);
}
/** Market Data OHLC*/publicvoidgetMarketData(SmartConnectsmartConnect) {
JSONObjectpayload = newJSONObject();
payload.put("mode", "OHLC");
JSONObjectexchangeTokens = newJSONObject();
JSONArraynseTokens = newJSONArray();
nseTokens.put("3045");
exchangeTokens.put("NSE", nseTokens);
payload.put("exchangeTokens", exchangeTokens);
JSONObjectresponse = smartConnect.marketData(payload);
}
/** Market Data LTP*/publicvoidgetMarketData(SmartConnectsmartConnect) {
JSONObjectpayload = newJSONObject();
payload.put("mode", "LTP");
JSONObjectexchangeTokens = newJSONObject();
JSONArraynseTokens = newJSONArray();
nseTokens.put("3045");
exchangeTokens.put("NSE", nseTokens);
payload.put("exchangeTokens", exchangeTokens);
JSONObjectresponse = smartConnect.marketData(payload);
}
/** Logout user. */publicvoidlogout(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
/** Logout user and kill the session. */JSONObjectjsonObject = smartConnect.logout();
}
/** Margin data. */publicvoidgetMarginDetails(SmartConnectsmartConnect) throwsSmartAPIException, IOException {
List<MarginParams> marginParamsList = newArrayList<>();
MarginParamsmarginParams = newMarginParams();
marginParams.quantity = 1;
marginParams.token = "12740";
marginParams.exchange = Constants.EXCHANGE_NSE;
marginParams.productType = Constants.PRODUCT_DELIVERY;
marginParams.price = 0.0;
marginParams.tradeType = Constants.TRADETYPE_BUY;
marginParamsList.add(marginParams);
JSONObjectjsonObject = smartConnect.getMarginDetails(marginParamsList);
System.out.println(jsonObject);
}
/** Get Individual Order */publicvoidgetIndividualOrder(SmartConnectsmartConnect, StringorderId) throwsSmartAPIException, IOException {
JSONObjectjsonObject = smartConnect.getIndividualOrderDetails(orderId);
}
}

WebSocket live streaming data

/* SmartAPITicker */StringclientId = "<clientId>";
Useruser = smartConnect.generateSession("<clientId>", "<password>", "<totp>");
StringfeedToken = user.getFeedToken();
StringstrWatchListScript = "nse_cm|2885&nse_cm|1594&nse_cm|11536&mcx_fo|221658";
Stringtask = "mw";
examples.tickerUsage(clientId, feedToken, strWatchListScript, task);
/*	* String jwtToken = user.getAccessToken(); 	* String apiKey = "<api_key>";	* String actionType = "subscribe"; String feedType = "order_feed";	* 	* examples.smartWebSocketUsage(clientId, jwtToken, apiKey, actionType,	* feedType);	* 	*/publicvoidtickerUsage(StringclientId, StringfeedToken, StringstrWatchListScript, Stringtask)
throwsSmartAPIException {
SmartAPITickertickerProvider = newSmartAPITicker(clientId, feedToken, strWatchListScript, task);
tickerProvider.setOnConnectedListener(newOnConnect() {
@OverridepublicvoidonConnected() {
System.out.println("subscribe() called!");
tickerProvider.subscribe();
}
});
tickerProvider.setOnTickerArrivalListener(newOnTicks() {
@OverridepublicvoidonTicks(JSONArrayticks) {
System.out.println("ticker data: " + ticks.toString());
}
});
/** * connects to SmartAPI ticker server for getting live quotes */tickerProvider.connect();
/** * You can check, if websocket connection is open or not using the following * method. */booleanisConnected = tickerProvider.isConnectionOpen();
System.out.println(isConnected);
// After using the SmartAPI ticker, close websocket connection.// tickerProvider.disconnect();
}
publicvoidsmartWebSocketUsage(StringclientId, StringjwtToken, StringapiKey, StringactionType, StringfeedType)
throwsSmartAPIException {
SmartWebsocketsmartWebsocket = newSmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType);
smartWebsocket.setOnConnectedListener(newSmartWSOnConnect() {
@OverridepublicvoidonConnected() {
smartWebsocket.runscript();
}
});
smartWebsocket.setOnDisconnectedListener(newSmartWSOnDisconnect() {
@OverridepublicvoidonDisconnected() {
System.out.println("onDisconnected");
}
});
/** Set error listener to listen to errors. */smartWebsocket.setOnErrorListener(newSmartWSOnError() {
@OverridepublicvoidonError(Exceptionexception) {
System.out.println("onError: " + exception.getMessage());
}
@OverridepublicvoidonError(SmartAPIExceptionsmartAPIException) {
System.out.println("onError: " + smartAPIException.getMessage());
}
@OverridepublicvoidonError(Stringerror) {
System.out.println("onError: " + error);
}
});
smartWebsocket.setOnTickerArrivalListener(newSmartWSOnTicks() {
@OverridepublicvoidonTicks(JSONArrayticks) {
System.out.println("ticker data: " + ticks.toString());
}
});
/** * connects to SmartAPI ticker server for getting live quotes */smartWebsocket.connect();
/** * You can check, if websocket connection is open or not using the following * method. */booleanisConnected = smartWebsocket.isConnectionOpen();
System.out.println(isConnected);
// After using the SmartAPI ticker, close websocket connection.// smartWebsocket.disconnect();
}

For more details, take a look at Examples.java in the sample directory.

Order Websocket Data

/* Order Websocket */StringuserClientId = "<clientId>";
UseruserGenerateSession = smartConnect.generateSession("<clientId>", "<password>", "<totp>");
smartConnect.setAccessToken(userGenerateSession.getAccessToken());
smartConnect.setUserId(userGenerateSession.getUserId());
StringaccessToken = userGenerateSession.getAccessToken();
examples.orderUpdateUsage(accessToken);
/** * Order update websocket * * To retrieve order update websocket data * @param accessToken */publicvoidorderUpdateUsage(StringaccessToken){
OrderUpdateWebsocketorderUpdateWebsocket = newOrderUpdateWebsocket(accessToken, newOrderUpdateListner() {
/** * Check if the websocket is connected or not */@OverridepublicvoidonConnected() {
log.info("order update websocket connected");
}
/** * Handle the onDisconnected event */@OverridepublicvoidonDisconnected() {
log.info("order update websocket disconnected");
}
/** * Handle the onError event * @param error */@OverridepublicvoidonError(SmartStreamErrorerror) {
log.info("on error event");
}
/** * Handle the onPong event */@OverridepublicvoidonPong() {
log.info("or pong event");
}
/** * Handle the onOrderUpdate event * @param data */@OverridepublicvoidonOrderUpdate(Stringdata) {
log.info("order update data {} ",data);
}});
}

For more details, take a look at Examples.java in the sample directory.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages