├── .gitignore ├── LICENSE ├── README.md ├── dist └── kiteconnect.jar ├── kiteconnect ├── libs │ ├── commons-codec-1.11.jar │ ├── gson-2.8.9.jar │ ├── json-20230227.jar │ ├── kotlin-stdlib-1.6.21.jar │ ├── logging-interceptor-4.4.0.jar │ ├── nv-websocket-client-2.3.jar │ ├── okhttp-4.4.0.jar │ ├── okio-3.4.0.jar │ ├── okio-jvm-3.4.0.jar │ └── super-csv-2.4.0.jar └── src │ └── com │ └── zerodhatech │ ├── kiteconnect │ ├── KiteConnect.java │ ├── Routes.java │ ├── kitehttp │ │ ├── KiteRequestHandler.java │ │ ├── KiteResponseHandler.java │ │ ├── SessionExpiryHook.java │ │ ├── exceptions │ │ │ ├── DataException.java │ │ │ ├── GeneralException.java │ │ │ ├── HoldingException.java │ │ │ ├── InputException.java │ │ │ ├── KiteException.java │ │ │ ├── MarginException.java │ │ │ ├── NetworkException.java │ │ │ ├── OrderException.java │ │ │ ├── PermissionException.java │ │ │ ├── TokenException.java │ │ │ └── package-info.java │ │ └── package-info.java │ ├── package-info.java │ └── utils │ │ ├── Constants.java │ │ └── package-info.java │ ├── models │ ├── AuctionInstrument.java │ ├── BulkOrderError.java │ ├── BulkOrderResponse.java │ ├── CombinedMarginData.java │ ├── ContractNote.java │ ├── ContractNoteParams.java │ ├── Depth.java │ ├── GTT.java │ ├── GTTParams.java │ ├── HistoricalData.java │ ├── Holding.java │ ├── Instrument.java │ ├── LTPQuote.java │ ├── MFHolding.java │ ├── MFInstrument.java │ ├── MFOrder.java │ ├── MFSIP.java │ ├── Margin.java │ ├── MarginCalculationData.java │ ├── MarginCalculationParams.java │ ├── MarketDepth.java │ ├── OHLC.java │ ├── OHLCQuote.java │ ├── Order.java │ ├── OrderParams.java │ ├── Position.java │ ├── Profile.java │ ├── Quote.java │ ├── Tick.java │ ├── TokenSet.java │ ├── Trade.java │ ├── TriggerRange.java │ ├── User.java │ └── package-info.java │ └── ticker │ ├── KiteTicker.java │ ├── OnConnect.java │ ├── OnDisconnect.java │ ├── OnError.java │ ├── OnOrderUpdate.java │ ├── OnTicks.java │ └── package-info.java ├── pom.xml └── sample └── src ├── Examples.java └── Test.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.idea 2 | *.iml 3 | !target/ 4 | target/* 5 | !/src/test/ 6 | /src/test/* 7 | !sample/out 8 | sample/out/* 9 | out/* 10 | !sample/.idea/ 11 | sample/.idea/* 12 | production/* 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Zerodha Technology Pvt. Ltd. (India) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # The Kite Connect 3.5.0 API Java client 3 | The official Java client for communicating with [Kite Connect API](https://kite.trade). 4 | 5 | Kite Connect 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 portfolio, stream live market data (WebSockets), and more, with the simple HTTP API collection. 6 | 7 | [Zerodha Technology Pvt Ltd](http://rainmatter.com) (c) 2019. Licensed under the MIT License. 8 | 9 | ## Documentation 10 | - [Kite Connect HTTP API documentation](https://kite.trade/docs/connect/v3/) 11 | - [Java library documentation](https://kite.trade/docs/javakiteconnect/) 12 | 13 | ## Usage 14 | - [Download Kite Connect 3 jar file](https://github.com/zerodhatech/javakiteconnect/tree/master/dist) and include it in your build path. 15 | 16 | - Include com.zerodhatech.kiteconnect into build path from maven. Use version 3.5.0 17 | 18 | - To use javakiteconnect in **Android**, you need to include jar file in the libs directory and add the following line in you module's gradle file ``` compile files('libs/kiteconnect.jar') ``` 19 | 20 | ## API usage 21 | ```java 22 | // Initialize Kiteconnect using apiKey. 23 | KiteConnect kiteSdk = new KiteConnect("your_apiKey"); 24 | 25 | // Set userId. 26 | kiteSdk.setUserId("your_userId"); 27 | 28 | /* First you should get request_token, public_token using kitconnect login and then use request_token, public_token, api_secret to make any kiteconnect api call. 29 | Get login url. Use this url in webview to login user, after authenticating user you will get requestToken. Use the same to get accessToken. */ 30 | String url = kiteSdk.getLoginUrl(); 31 | 32 | // Get accessToken as follows, 33 | User user = kiteSdk.generateSession("request_token", "your_apiSecret"); 34 | 35 | // Set request token and public token which are obtained from login process. 36 | kiteSdk.setAccessToken(userModel.accessToken); 37 | kiteSdk.setPublicToken(userModel.publicToken); 38 | 39 | // Set session expiry callback. 40 | kiteSdk.setSessionExpiryHook(new SessionExpiryHook() { 41 | @Override 42 | public void sessionExpired() { 43 | System.out.println("session expired"); 44 | } 45 | }); 46 | 47 | // Get margins returns margin model, you can pass equity or commodity as arguments to get margins of respective segments. 48 | Margin margins = kiteSdk.getMargins("equity"); 49 | System.out.println(margins.available.cash); 50 | System.out.println(margins.utilised.debits); 51 | 52 | /** Place order method requires a orderParams argument which contains, 53 | * tradingsymbol, exchange, transaction_type, order_type, quantity, product, price, trigger_price, disclosed_quantity, validity 54 | * squareoff_value, stoploss_value, trailing_stoploss 55 | * and variety (value can be regular, bo, co, amo) 56 | * place order will return order model which will have only orderId in the order model 57 | * Following is an example param for LIMIT order, 58 | * if a call fails then KiteException will have error message in it 59 | * Success of this call implies only order has been placed successfully, not order execution. */ 60 | 61 | OrderParams orderParams = new OrderParams(); 62 | orderParams.quantity = 1; 63 | orderParams.orderType = Constants.ORDER_TYPE_LIMIT; 64 | orderParams.tradingsymbol = "ASHOKLEY"; 65 | orderParams.product = Constants.PRODUCT_CNC; 66 | orderParams.exchange = Constants.EXCHANGE_NSE; 67 | orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; 68 | orderParams.validity = Constants.VALIDITY_DAY; 69 | orderParams.price = 122.2; 70 | orderParams.triggerPrice = 0.0; 71 | orderParams.tag = "myTag"; //tag is optional and it cannot be more than 8 characters and only alphanumeric is allowed 72 | 73 | Order order = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR); 74 | System.out.println(order.orderId); 75 | ``` 76 | For more details, take a look at Examples.java in sample directory. 77 | 78 | ## WebSocket live streaming data 79 | ```java 80 | /** To get live price use websocket connection. 81 | * It is recommended to use only one websocket connection at any point of time and make sure you stop connection, once user goes out of app. 82 | * custom url points to new endpoint which can be used till complete Kite Connect 3 migration is done. */ 83 | KiteTicker tickerProvider = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey()); 84 | 85 | tickerProvider.setOnConnectedListener(new OnConnect() { 86 | @Override 87 | public void onConnected() { 88 | /** Subscribe ticks for token. 89 | * By default, all tokens are subscribed for modeQuote. 90 | * */ 91 | tickerProvider.subscribe(tokens); 92 | tickerProvider.setMode(tokens, KiteTicker.modeFull); 93 | } 94 | }); 95 | 96 | tickerProvider.setOnDisconnectedListener(new OnDisconnect() { 97 | @Override 98 | public void onDisconnected() { 99 | // your code goes here 100 | } 101 | }); 102 | 103 | /** Set listener to get order updates.*/ 104 | tickerProvider.setOnOrderUpdateListener(new OnOrderUpdate() { 105 | @Override 106 | public void onOrderUpdate(Order order) { 107 | System.out.println("order update "+order.orderId); 108 | } 109 | }); 110 | 111 | tickerProvider.setOnTickerArrivalListener(new OnTicks() { 112 | @Override 113 | public void onTicks(ArrayList ticks) { 114 | NumberFormat formatter = new DecimalFormat(); 115 | System.out.println("ticks size "+ticks.size()); 116 | if(ticks.size() > 0) { 117 | System.out.println("last price "+ticks.get(0).getLastTradedPrice()); 118 | System.out.println("open interest "+formatter.format(ticks.get(0).getOi())); 119 | System.out.println("day high OI "+formatter.format(ticks.get(0).getOpenInterestDayHigh())); 120 | System.out.println("day low OI "+formatter.format(ticks.get(0).getOpenInterestDayLow())); 121 | System.out.println("change "+formatter.format(ticks.get(0).getChange())); 122 | System.out.println("tick timestamp "+ticks.get(0).getTickTimestamp()); 123 | System.out.println("tick timestamp date "+ticks.get(0).getTickTimestamp()); 124 | System.out.println("last traded time "+ticks.get(0).getLastTradedTime()); 125 | System.out.println(ticks.get(0).getMarketDepth().get("buy").size()); 126 | } 127 | } 128 | }); 129 | 130 | tickerProvider.setTryReconnection(true); 131 | //maximum retries and should be greater than 0 132 | tickerProvider.setMaximumRetries(10); 133 | //set maximum retry interval in seconds 134 | tickerProvider.setMaximumRetryInterval(30); 135 | 136 | /** connects to com.zerodhatech.com.zerodhatech.ticker server for getting live quotes*/ 137 | tickerProvider.connect(); 138 | 139 | /** You can check, if websocket connection is open or not using the following method.*/ 140 | boolean isConnected = tickerProvider.isConnectionOpen(); 141 | System.out.println(isConnected); 142 | 143 | /** set mode is used to set mode in which you need tick for list of tokens. 144 | * Ticker allows three modes, modeFull, modeQuote, modeLTP. 145 | * For getting only last traded price, use modeLTP 146 | * For getting last traded price, last traded quantity, average price, volume traded today, total sell quantity and total buy quantity, open, high, low, close, change, use modeQuote 147 | * For getting all data with depth, use modeFull*/ 148 | tickerProvider.setMode(tokens, KiteTicker.modeLTP); 149 | 150 | // Unsubscribe for a token. 151 | tickerProvider.unsubscribe(tokens); 152 | 153 | // After using com.zerodhatech.com.zerodhatech.ticker, close websocket connection. 154 | tickerProvider.disconnect(); 155 | 156 | ``` 157 | For more details about the different mode of quotes and subscribing for them, take a look at Examples in sample directory. 158 | 159 | ## Breaking changes from 3.2.1 to 3.3.1 160 | 161 | #### Margin calculation data 162 | 163 | | version 3.3.1 | version 3.2.1 | 164 | | :---: | :---:| 165 | | option_premium(double) | optionPremium(double) | 166 | 167 | ## Breaking changes from 3.1.14 to 3.2.1 168 | 169 | #### Holding (model) 170 | 171 | | version 3.1.14 | version 3.2.1 | 172 | | :---: | :---:| 173 | | lastPrice(String) | lastPrice(Double) | 174 | | t1Quantity(String) | t1Quantity(int) | 175 | | pnl(String) | pnl(Double) | 176 | | quantity(String) | quantity(int) | 177 | | averagePrice(String) | averagePrice(Double) | 178 | 179 | * Removed: 180 | 181 | | version 3.1.14 | version 3.2.1 | 182 | | :---: | :---: | 183 | | accountId | **NA** | 184 | 185 | ##### Tick (model) 186 | 187 | | version 3.1.14 | version 3.2.1 | 188 | | :---: | :---:| 189 | | volumeTradedToday(double) | volumeTradedToday(long) | 190 | 191 | * Change attribute for indices tick will have change percent value against 192 | the previously sent absolute change value. 193 | 194 | #### Order (model) 195 | 196 | * Removed: 197 | 198 | | version 3.1.14 | version 3.2.1 | 199 | | :---: | :---: | 200 | | userId | **NA** | 201 | | symbol | **NA** | 202 | 203 | 204 | 205 | ## Breaking changes from version 2 to version 3 206 | 207 | #### Place order (bracket order) parameters 208 | 209 | | version 2 | version 3 | 210 | | :---: | :---:| 211 | | squareoff_value | squareoff | 212 | | stoploss_value | stoploss | 213 | 214 | #### Model name changes 215 | 216 | | version 2 | version 3 | 217 | | :---: | :---:| 218 | | MfHolding | MFHolding | 219 | | MfInstrument | MFInstrument | 220 | | MfOrder | MFOrder | 221 | | MfSip | MFSIP | 222 | 223 | ##### Order (model) 224 | 225 | * The orderTimestamp is now Date type. 226 | * The exchangeTimestamp is now Date type. 227 | 228 | #### Trades (model) 229 | 230 | * The orderTimestamp is now fillTimestamp. 231 | * The exchangeTimestamp is now Date type. 232 | 233 | #### MFOrder (model) 234 | 235 | * The orderTimestamp is now Date type. 236 | * The exchangeTimestamp is now Date type. 237 | 238 | #### MFSIP (model) 239 | 240 | * The created is now Date type. 241 | * The Date is now Date type. 242 | 243 | #### MFInstrument (model) 244 | 245 | * The purchase_allowed is now boolean type. 246 | * The redemption_allowed is now boolean type. 247 | * The last_price_date is now Date type. 248 | 249 | #### Instrument (model) 250 | 251 | * The expiry is now Date type. 252 | 253 | #### Package name changes 254 | 255 | | version 2 | version 3 | 256 | | :---: | :---: | 257 | |com.rainmatter.kitehttp|com.zerodhatech.kiteconnect.kitehttp| 258 | |com.rainmatter.utils|com.zerodhatech.kiteconnect.utils| 259 | |com.rainmatter.kiteconnect|com.zerodhatech.kiteconnect| 260 | |com.rainmatter.ticker|com.zerodhatech.kiteconnect| 261 | |com.rainmatter.models|com.zerodhatech.models| 262 | 263 | #### Method name changes 264 | 265 | | version 2 | version 3 | 266 | | :---: | :---: | 267 | | requestAccessToken | generateSession | 268 | | modifyProduct | convertPosition | 269 | | getOrder | getOrderHistory | 270 | | getTrades(order_id) | getOrderTrades(order_id) | 271 | | getMfOrders | getMFOrders | 272 | | getMfOrder | getMFOrder | 273 | | getMfSips | getMFSIPs | 274 | | getMfSip | getMFSIP | 275 | | modifySip | modifySIP | 276 | | cancelSip | cancelSIP | 277 | | getMfInstruments | getMFInstruments | 278 | 279 | #### Method with signature change 280 | 281 | | version 2 | 282 | | :---: | 283 | | placeOrder | 284 | | modifyOrder | 285 | | cancelOrder | 286 | | convertPosition | 287 | | getTriggerRange | 288 | | getHistoricalData | 289 | | placeMFOrder | 290 | | placeMFSIP | 291 | | modifyMFSIP | 292 | 293 | For more details about each method go to [KiteConnect.java](https://github.com/zerodhatech/javakiteconnect/blob/kite3/kiteconnect/src/com/zerodhatech/kiteconnect/KiteConnect.java) 294 | 295 | #### Funds (model) 296 | 297 | | version 2 | version 3 | 298 | | :---: | :---: | 299 | | Margins | Margin | 300 | 301 | #### User (model) 302 | 303 | * UserModel is now User. 304 | 305 | | version 2 | version 3 | 306 | | :---: | :---: | 307 | | product | products | 308 | | exchange | exchanges | 309 | | orderType | orderTypes | 310 | | passwordReset | **NA** | 311 | | memberId | **NA** | 312 | | **NA** | apiKey | 313 | 314 | * loginTime is now of Date type. 315 | 316 | #### Position (model) 317 | 318 | Added new fields 319 | 320 | | version 3 | 321 | | :---: | 322 | | dayBuyQuantity | 323 | | daySellQuantity | 324 | | dayBuyPrice | 325 | | daySellPrice | 326 | | dayBuyValue | 327 | | daySellValue | 328 | | value | 329 | 330 | #### Kite Ticker (Websockets) 331 | 332 | * Kite Ticker is now authenticated using access_token and not public_token. 333 | 334 | Version 2: 335 | ```java 336 | KiteConnect kiteSdk = new KiteConnect("your_apiKey"); 337 | ``` 338 | Version 3: 339 | ```java 340 | KiteTicker tickerProvider = new KiteTicker(kiteConnect.getUserId(), kiteConnect.getAccessToken(), kiteConnect.getApiKey()); 341 | ``` 342 | * Order postbacks are now streamed on Kite Ticker. 343 | 344 | * Added new fields in full mode. 345 | 346 | | version 3 | 347 | | :---: | 348 | | lastTradedTime | 349 | | openInterest | 350 | | oiDayHigh | 351 | | oiDayLow | 352 | | tickTimestamp | 353 | 354 | * Changes: 355 | 356 | | version 2 | version 3 | 357 | | :---: | :---: | 358 | | OnTick | OnTicks | 359 | | setTimeIntervalForReconnection | **NA** | 360 | | **NA** | setMaximumRetryInterval | 361 | | netPriceChangeFromClosingPrice | change | 362 | 363 | #### Quote 364 | 365 | * Quote will accept multiple params and returns a map of Quote model. 366 | * Added new fields open interest, tick timestamp, last traded time, average price, day high OI, day low OI. 367 | * lastTradedPrice is now lastPrice. 368 | 369 | | version 3 | 370 | | :---: | 371 | | instrumentToken | 372 | | timestamp | 373 | | averagePrice | 374 | | oiDayHigh | 375 | | oiDayLow | 376 | 377 | * Changes: 378 | 379 | | version 2 | version 3 | 380 | | :---: | :---: | 381 | | lastTime(String) | lastTradedTime(Date) | 382 | | changePercent | **NA** | 383 | | depth(Map>) | depth(MarketDepth type) | 384 | 385 | 386 | * Removed: 387 | 388 | | version 2 | version 3 | 389 | | :---: | :---: | 390 | | IndicesQuote | **NA** | 391 | 392 | #### Profile 393 | 394 | * Added new profile API call to fetch user details. 395 | 396 | #### Trigger range 397 | 398 | * Trigger range API supports fetching trigger range for multiple instruments in one request. 399 | 400 | #### TriggerRange (model) 401 | 402 | | version 2 | version 3 | 403 | | :---: | :---: | 404 | | start | lower | 405 | | end | upper | 406 | | percent | percentage | 407 | -------------------------------------------------------------------------------- /dist/kiteconnect.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/dist/kiteconnect.jar -------------------------------------------------------------------------------- /kiteconnect/libs/commons-codec-1.11.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/commons-codec-1.11.jar -------------------------------------------------------------------------------- /kiteconnect/libs/gson-2.8.9.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/gson-2.8.9.jar -------------------------------------------------------------------------------- /kiteconnect/libs/json-20230227.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/json-20230227.jar -------------------------------------------------------------------------------- /kiteconnect/libs/kotlin-stdlib-1.6.21.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/kotlin-stdlib-1.6.21.jar -------------------------------------------------------------------------------- /kiteconnect/libs/logging-interceptor-4.4.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/logging-interceptor-4.4.0.jar -------------------------------------------------------------------------------- /kiteconnect/libs/nv-websocket-client-2.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/nv-websocket-client-2.3.jar -------------------------------------------------------------------------------- /kiteconnect/libs/okhttp-4.4.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/okhttp-4.4.0.jar -------------------------------------------------------------------------------- /kiteconnect/libs/okio-3.4.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/okio-3.4.0.jar -------------------------------------------------------------------------------- /kiteconnect/libs/okio-jvm-3.4.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/okio-jvm-3.4.0.jar -------------------------------------------------------------------------------- /kiteconnect/libs/super-csv-2.4.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zerodha/javakiteconnect/3ebbd2c4b2b9e3aec6260d30125a492914421d22/kiteconnect/libs/super-csv-2.4.0.jar -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/Routes.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Generates endpoints for all api calls. 8 | * 9 | * Here all the routes are translated into a Java Map. 10 | * 11 | */ 12 | public class Routes { 13 | 14 | /* 15 | 16 | "parameters": "/parameters", 17 | "api.validate": "/session/token", 18 | "api.invalidate": "/session/token", 19 | "user.margins": "/user/margins/{segment}", 20 | 21 | "orders": "/orders", 22 | "trades": "/trades", 23 | "orders.info": "/orders/{order_id}", 24 | 25 | "orders.place": "/orders/{variety}", 26 | "orders.modify": "/orders/{variety}/{order_id}", 27 | "orders.cancel": "/orders/{variety}/{order_id}", 28 | "orders.trades": "/orders/{order_id}/trades", 29 | 30 | "portfolio.positions": "/portfolio/positions", 31 | "portfolio.holdings": "/portfolio/holdings", 32 | "portfolio.positions.modify": "/portfolio/positions", 33 | 34 | "market.instruments.all": "/instruments", 35 | "market.instruments": "/instruments/{exchange}", 36 | "market.quote": "/instruments/{exchange}/{tradingsymbol}", 37 | "market.historical": "/instruments/historical/{instrument_token}/{interval}", 38 | "market.trigger_range": "/instruments/{exchange}/{tradingsymbol}/trigger_range" 39 | */ 40 | 41 | public Map routes; 42 | private static String _rootUrl = "https://api.kite.trade"; 43 | private static String _loginUrl = "https://kite.trade/connect/login"; 44 | private static String _wsuri = "wss://ws.kite.trade/"+"?access_token=:access_token&api_key=:api_key"; 45 | 46 | // Initialize all routes, 47 | public Routes(){ 48 | routes = new HashMap(){{ 49 | put("parameters", "/parameters"); 50 | put("api.validate", "/session/token"); 51 | put("api.invalidate", "/session/token"); 52 | put("user.margins.segment", "/user/margins/:segment"); 53 | put("user.margins", "/user/margins"); 54 | put("user.profile", "/user/profile"); 55 | put("api.refresh", "/session/refresh_token"); 56 | 57 | put("instruments.margins", "/margins/:segment"); 58 | 59 | put("orders", "/orders"); 60 | put("order", "/orders/:order_id"); 61 | put("trades", "/trades"); 62 | put("orders.info", "/orders/:order_id"); 63 | put("orders.place", "/orders/:variety"); 64 | put("orders.modify", "/orders/:variety/:order_id"); 65 | put("orders.cancel", "/orders/:variety/:order_id"); 66 | put("orders.trades", "/orders/:order_id/trades"); 67 | 68 | put("gtt", "/gtt/triggers"); 69 | put("gtt.place", "/gtt/triggers"); 70 | put("gtt.info", "/gtt/triggers/:id"); 71 | put("gtt.modify", "/gtt/triggers/:id"); 72 | put("gtt.delete", "/gtt/triggers/:id"); 73 | 74 | put("portfolio.positions", "/portfolio/positions"); 75 | put("portfolio.holdings", "/portfolio/holdings"); 76 | put("portfolio.positions.modify", "/portfolio/positions"); 77 | put("portfolio.auctions.instruments", "/portfolio/holdings/auctions"); 78 | 79 | put("market.instruments.all", "/instruments"); 80 | put("market.instruments", "/instruments/:exchange"); 81 | put("market.quote", "/quote"); 82 | put("market.historical", "/instruments/historical/:instrument_token/:interval"); 83 | put("market.trigger_range", "/instruments/trigger_range/:transaction_type"); 84 | 85 | put("quote.ohlc", "/quote/ohlc"); 86 | put("quote.ltp", "/quote/ltp"); 87 | 88 | put("mutualfunds.orders", "/mf/orders"); 89 | put("mutualfunds.orders.place", "/mf/orders"); 90 | put("mutualfunds.cancel_order", "/mf/orders/:order_id"); 91 | put("mutualfunds.order", "/mf/orders/:order_id"); 92 | 93 | put("mutualfunds.sips", "/mf/sips"); 94 | put("mutualfunds.sips.place", "/mf/sips"); 95 | put("mutualfunds.cancel_sips", "/mf/sips/:sip_id"); 96 | put("mutualfunds.sips.modify", "/mf/sips/:sip_id"); 97 | put("mutualfunds.sip", "/mf/sips/:sip_id"); 98 | 99 | put("mutualfunds.instruments", "/mf/instruments"); 100 | put("mutualfunds.holdings", "/mf/holdings"); 101 | 102 | put("api.token", "/session/token"); 103 | 104 | put("margin.calculation.order", "/margins/orders"); 105 | put("margin.calculation.basket", "/margins/basket"); 106 | put("contractnote", "/charges/orders"); 107 | }}; 108 | } 109 | 110 | public String get(String key){ 111 | return _rootUrl + routes.get(key); 112 | } 113 | 114 | public String getWsuri(){ 115 | return _wsuri; 116 | } 117 | 118 | public String getLoginUrl(){ 119 | return _loginUrl; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp; 2 | 3 | import com.zerodhatech.kiteconnect.KiteConnect; 4 | import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; 5 | import okhttp3.*; 6 | import okhttp3.logging.HttpLoggingInterceptor; 7 | import org.json.JSONArray; 8 | import org.json.JSONException; 9 | import org.json.JSONObject; 10 | 11 | import java.io.IOException; 12 | import java.net.Proxy; 13 | import java.util.Map; 14 | import java.util.concurrent.TimeUnit; 15 | 16 | /** 17 | * Request handler for all Http requests 18 | */ 19 | public class KiteRequestHandler { 20 | 21 | private OkHttpClient client; 22 | private String USER_AGENT = "javakiteconnect/3.1.14"; 23 | 24 | /** Initialize request handler. 25 | * @param proxy to be set for making requests.*/ 26 | public KiteRequestHandler(Proxy proxy) { 27 | OkHttpClient.Builder builder = new OkHttpClient.Builder(); 28 | builder.connectTimeout(10000, TimeUnit.MILLISECONDS); 29 | if(proxy != null) { 30 | builder.proxy(proxy); 31 | } 32 | 33 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 34 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 35 | if(KiteConnect.ENABLE_LOGGING) { 36 | client = builder.addInterceptor(logging).build(); 37 | }else { 38 | client = builder.build(); 39 | } 40 | } 41 | 42 | /** Makes a GET request. 43 | * @return JSONObject which is received by Kite Trade. 44 | * @param url is the endpoint to which request has to be sent. 45 | * @param apiKey is the api key of the Kite Connect app. 46 | * @param accessToken is the access token obtained after successful login process. 47 | * @throws IOException is thrown when there is a connection related error. 48 | * @throws KiteException is thrown for all Kite Trade related errors. 49 | * @throws JSONException is thrown for parsing errors.*/ 50 | public JSONObject getRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 51 | Request request = createGetRequest(url, apiKey, accessToken); 52 | Response response = client.newCall(request).execute(); 53 | String body = response.body().string(); 54 | JSONObject json = new KiteResponseHandler().handle(response, body); 55 | response.close(); 56 | return json; 57 | } 58 | 59 | /** Makes a GET request. 60 | * @return JSONObject which is received by Kite Trade. 61 | * @param url is the endpoint to which request has to be sent. 62 | * @param apiKey is the api key of the Kite Connect app. 63 | * @param accessToken is the access token obtained after successful login process. 64 | * @param params is the map of params which has to be sent as query params. 65 | * @throws IOException is thrown when there is a connection related error. 66 | * @throws KiteException is thrown for all Kite Trade related errors. 67 | * @throws JSONException is thrown for parsing errors.*/ 68 | public JSONObject getRequest(String url, Map params, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 69 | Request request = createGetRequest(url, params, apiKey, accessToken); 70 | Response response = client.newCall(request).execute(); 71 | String body = response.body().string(); 72 | JSONObject json = new KiteResponseHandler().handle(response, body); 73 | response.close(); 74 | return json; 75 | } 76 | 77 | /** Makes a POST request. 78 | * @return JSONObject which is received by Kite Trade. 79 | * @param url is the endpoint to which request has to be sent. 80 | * @param apiKey is the api key of the Kite Connect app. 81 | * @param accessToken is the access token obtained after successful login process. 82 | * @param params is the map of params which has to be sent in the body. 83 | * @throws IOException is thrown when there is a connection related error. 84 | * @throws KiteException is thrown for all Kite Trade related errors. 85 | * @throws JSONException is thrown for parsing errors.*/ 86 | public JSONObject postRequest(String url, Map params, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 87 | Request request = createPostRequest(url, params, apiKey, accessToken); 88 | Response response = client.newCall(request).execute(); 89 | String body = response.body().string(); 90 | JSONObject json = new KiteResponseHandler().handle(response, body); 91 | response.close(); 92 | return json; 93 | } 94 | 95 | /** Make a JSON POST request. 96 | * @param url is the endpoint to which request has to be sent. 97 | * @param apiKey is the api key of the Kite Connect app. 98 | * @param accessToken is the access token obtained after successful login process. 99 | * @param jsonArray is the JSON array of params which has to be sent in the body. 100 | * @throws IOException is thrown when there is a connection related error. 101 | * @throws KiteException is thrown for all Kite Trade related errors. 102 | * @throws JSONException is thrown for parsing errors. 103 | * */ 104 | public JSONObject postRequestJSON(String url, JSONArray jsonArray, Map queryParams, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 105 | Request request = createJsonPostRequest(url, jsonArray, queryParams, apiKey, accessToken); 106 | Response response = client.newCall(request).execute(); 107 | String body = response.body().string(); 108 | JSONObject json = new KiteResponseHandler().handle(response, body); 109 | response.close(); 110 | return json; 111 | } 112 | 113 | /** Makes a PUT request. 114 | * @return JSONObject which is received by Kite Trade. 115 | * @param url is the endpoint to which request has to be sent. 116 | * @param apiKey is the api key of the Kite Connect app. 117 | * @param accessToken is the access token obtained after successful login process. 118 | * @param params is the map of params which has to be sent in the body. 119 | * @throws IOException is thrown when there is a connection related error. 120 | * @throws KiteException is thrown for all Kite Trade related errors. 121 | * @throws JSONException is thrown for parsing errors.*/ 122 | public JSONObject putRequest(String url, Map params, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 123 | Request request = createPutRequest(url, params, apiKey, accessToken); 124 | Response response = client.newCall(request).execute(); 125 | String body = response.body().string(); 126 | JSONObject json = new KiteResponseHandler().handle(response, body); 127 | response.close(); 128 | return json; 129 | } 130 | 131 | /** Makes a DELETE request. 132 | * @return JSONObject which is received by Kite Trade. 133 | * @param url is the endpoint to which request has to be sent. 134 | * @param apiKey is the api key of the Kite Connect app. 135 | * @param accessToken is the access token obtained after successful login process. 136 | * @param params is the map of params which has to be sent in the query params. 137 | * @throws IOException is thrown when there is a connection related error. 138 | * @throws KiteException is thrown for all Kite Trade related errors. 139 | * @throws JSONException is thrown for parsing errors.*/ 140 | public JSONObject deleteRequest(String url, Map params, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 141 | Request request = createDeleteRequest(url, params, apiKey, accessToken); 142 | Response response = client.newCall(request).execute(); 143 | String body = response.body().string(); 144 | JSONObject json = new KiteResponseHandler().handle(response, body); 145 | response.close(); 146 | return json; 147 | } 148 | 149 | /** Makes a GET request. 150 | * @return JSONObject which is received by Kite Trade. 151 | * @param url is the endpoint to which request has to be sent. 152 | * @param apiKey is the api key of the Kite Connect app. 153 | * @param accessToken is the access token obtained after successful login process. 154 | * @param commonKey is the key that has to be sent in query param for quote calls. 155 | * @param values is the values that has to be sent in query param like 265, 256265, NSE:INFY. 156 | * @throws IOException is thrown when there is a connection related error. 157 | * @throws KiteException is thrown for all Kite Trade related errors. 158 | * @throws JSONException is thrown for parsing errors. 159 | * */ 160 | public JSONObject getRequest(String url, String commonKey, String[] values, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 161 | Request request = createGetRequest(url, commonKey, values, apiKey, accessToken); 162 | Response response = client.newCall(request).execute(); 163 | String body = response.body().string(); 164 | JSONObject json = new KiteResponseHandler().handle(response, body); 165 | response.close(); 166 | return json; 167 | } 168 | 169 | /** Makes GET request to fetch CSV dump. 170 | * @return String which is received from server. 171 | * @param url is the endpoint to which request has to be done. 172 | * @param apiKey is the api key of the Kite Connect app. 173 | * @param accessToken is the access token obtained after successful login process. 174 | * @throws IOException is thrown when there is a connection related error. 175 | * @throws KiteException is thrown for all Kite Trade related errors. 176 | * */ 177 | public String getCSVRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException { 178 | Request request = new Request.Builder().url(url).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); 179 | Response response = client.newCall(request).execute(); 180 | String body = response.body().string(); 181 | String data = new KiteResponseHandler().handle(response, body, "csv"); 182 | response.close(); 183 | return data; 184 | } 185 | 186 | /** Creates a GET request. 187 | * @param url is the endpoint to which request has to be done. 188 | * @param apiKey is the api key of the Kite Connect app. 189 | * @param accessToken is the access token obtained after successful login process. 190 | * */ 191 | public Request createGetRequest(String url, String apiKey, String accessToken) { 192 | HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); 193 | return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); 194 | } 195 | 196 | /** Creates a GET request. 197 | * @param url is the endpoint to which request has to be done. 198 | * @param apiKey is the api key of the Kite Connect app. 199 | * @param accessToken is the access token obtained after successful login process. 200 | * @param params is the map of data that has to be sent in query params. 201 | * */ 202 | public Request createGetRequest(String url, Map params, String apiKey, String accessToken) { 203 | HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); 204 | for(Map.Entry entry: params.entrySet()){ 205 | httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); 206 | } 207 | return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); 208 | } 209 | 210 | /** Creates a GET request. 211 | * @param url is the endpoint to which request has to be done. 212 | * @param apiKey is the api key of the Kite Connect app. 213 | * @param accessToken is the access token obtained after successful login process. 214 | * @param commonKey is the key that has to be sent in query param for quote calls. 215 | * @param values is the values that has to be sent in query param like 265, 256265, NSE:INFY. 216 | * */ 217 | public Request createGetRequest(String url, String commonKey, String[] values, String apiKey, String accessToken) { 218 | HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); 219 | for(int i = 0; i < values.length; i++) { 220 | httpBuilder.addQueryParameter(commonKey, values[i]); 221 | } 222 | return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); 223 | } 224 | 225 | /** Creates a POST request. 226 | * @param url is the endpoint to which request has to be done. 227 | * @param apiKey is the api key of the Kite Connect app. 228 | * @param accessToken is the access token obtained after successful login process. 229 | * @param params is the map of data that has to be sent in the body. 230 | * */ 231 | public Request createPostRequest(String url, Map params, String apiKey, String accessToken) { 232 | FormBody.Builder builder = new FormBody.Builder(); 233 | for(Map.Entry entry: params.entrySet()){ 234 | builder.add(entry.getKey(), entry.getValue().toString()); 235 | } 236 | 237 | RequestBody requestBody = builder.build(); 238 | Request request = new Request.Builder().url(url).post(requestBody).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); 239 | return request; 240 | } 241 | 242 | /** Create a POST request with body type JSON. 243 | * @param url is the endpoint to which request has to be done. 244 | * @param apiKey is the api key of the Kite Connect app. 245 | * @param accessToken is the access token obtained after successful login process. 246 | * @param jsonArray is the JSONArray of data that has to be sent in the body. 247 | * */ 248 | public Request createJsonPostRequest(String url, JSONArray jsonArray, Map queryParams, String apiKey, String accessToken) { 249 | MediaType JSON = MediaType.parse("application/json; charset=utf-8"); 250 | 251 | HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); 252 | if(queryParams.size() > 0) { 253 | for (Map.Entry entry : queryParams.entrySet()) { 254 | httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); 255 | } 256 | } 257 | 258 | RequestBody body = RequestBody.create(jsonArray.toString(), JSON); 259 | Request request; 260 | request = queryParams.size() > 0? new Request.Builder() 261 | .url(httpBuilder.build()) 262 | .header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken) 263 | .post(body) 264 | .build() : new Request.Builder() 265 | .url(url) 266 | .header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken) 267 | .post(body) 268 | .build(); 269 | return request; 270 | } 271 | 272 | /** Creates a PUT request. 273 | * @param url is the endpoint to which request has to be done. 274 | * @param apiKey is the api key of the Kite Connect app. 275 | * @param accessToken is the access token obtained after successful login process. 276 | * @param params is the map of data that has to be sent in the body. 277 | * */ 278 | public Request createPutRequest(String url, Map params, String apiKey, String accessToken){ 279 | FormBody.Builder builder = new FormBody.Builder(); 280 | for(Map.Entry entry: params.entrySet()){ 281 | builder.add(entry.getKey(), entry.getValue().toString()); 282 | } 283 | RequestBody requestBody = builder.build(); 284 | Request request = new Request.Builder().url(url).put(requestBody).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); 285 | return request; 286 | } 287 | 288 | /** Creates a DELETE request. 289 | * @param url is the endpoint to which request has to be done. 290 | * @param apiKey is the api key of the Kite Connect app. 291 | * @param accessToken is the access token obtained after successful login process. 292 | * @param params is the map of data that has to be sent in the query params. 293 | * */ 294 | public Request createDeleteRequest(String url, Map params, String apiKey, String accessToken){ 295 | HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); 296 | for(Map.Entry entry: params.entrySet()){ 297 | httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); 298 | } 299 | 300 | Request request = new Request.Builder().url(httpBuilder.build()).delete().header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); 301 | return request; 302 | } 303 | } -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp; 2 | 3 | import com.zerodhatech.kiteconnect.KiteConnect; 4 | import com.zerodhatech.kiteconnect.kitehttp.exceptions.*; 5 | import okhttp3.Response; 6 | import org.json.JSONException; 7 | import org.json.JSONObject; 8 | 9 | import java.io.IOException; 10 | 11 | /** 12 | * Response handler for handling all the responses. 13 | */ 14 | public class KiteResponseHandler { 15 | 16 | public JSONObject handle(Response response, String body) throws IOException, KiteException, JSONException { 17 | // added a check to handle empty response from the backend. 18 | if (body.length() > 0 && response.header("Content-Type").contains("json")) { 19 | JSONObject jsonObject = new JSONObject(body); 20 | if(jsonObject.has("error_type")) { 21 | throw dealWithException(jsonObject, response.code()); 22 | } 23 | return jsonObject; 24 | } else { 25 | throw new DataException("Unexpected content type received from server: "+ response.header("Content-Type")+" "+body, 502); 26 | } 27 | } 28 | 29 | public String handle(Response response, String body, String type) throws IOException, KiteException, JSONException { 30 | if (response.header("Content-Type").contains("csv")) { 31 | return body; 32 | } else if(response.header("Content-Type").contains("json")){ 33 | throw dealWithException(new JSONObject(body), response.code()); 34 | } else { 35 | throw new DataException("Unexpected content type received from server: "+ response.header("Content-Type")+" "+body, 502); 36 | } 37 | } 38 | 39 | 40 | private KiteException dealWithException(JSONObject jsonObject, int code) throws JSONException { 41 | String exception = jsonObject.getString("error_type"); 42 | 43 | switch (exception){ 44 | // if there is a token exception, generate a signal to logout the user. 45 | case "TokenException": 46 | if(KiteConnect.sessionExpiryHook != null) { 47 | KiteConnect.sessionExpiryHook.sessionExpired(); 48 | } 49 | return new TokenException(jsonObject.getString("message"), code); 50 | 51 | case "DataException": return new DataException(jsonObject.getString("message"), code); 52 | 53 | case "GeneralException": return new GeneralException(jsonObject.getString("message"), code); 54 | 55 | case "InputException": return new InputException(jsonObject.getString("message"), code); 56 | 57 | case "OrderException": return new OrderException(jsonObject.getString("message"), code); 58 | 59 | case "NetworkException": return new NetworkException(jsonObject.getString("message"), code); 60 | 61 | case "PermissionException": return new PermissionException(jsonObject.getString("message"), code); 62 | 63 | case "MarginException": return new MarginException(jsonObject.getString("message"), code); 64 | 65 | case "HoldingException": return new HoldingException(jsonObject.getString("message"), code); 66 | 67 | default: return new KiteException(jsonObject.getString("message"), code); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/SessionExpiryHook.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp; 2 | 3 | /** 4 | * A callback whenever there is a token expiry 5 | */ 6 | public interface SessionExpiryHook { 7 | 8 | 9 | public void sessionExpired(); 10 | } 11 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/DataException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * Exceptions raised when invalid data is returned from kite trade. 5 | */ 6 | 7 | public class DataException extends KiteException { 8 | 9 | // initialize 2fa exception and call constructor of Base Exception 10 | public DataException(String message, int code){ 11 | super(message, code); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/GeneralException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * An unclassified, general error. Default code is 500 5 | */ 6 | public class GeneralException extends KiteException { 7 | // initialize and call the base class 8 | public GeneralException(String message, int code){ 9 | super(message, code); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/HoldingException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * There are insufficient units in the holdings. 5 | * */ 6 | public class HoldingException extends KiteException{ 7 | public HoldingException(String message, int code) { 8 | super(message, code); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/InputException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * Represents user input errors such as missing and invalid parameters. 5 | * Default code is 400. 6 | */ 7 | public class InputException extends KiteException { 8 | // initialize and call base exception constructor 9 | public InputException(String message, int code){ 10 | super(message, code); 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/KiteException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * This is the base exception class which has a publicly accessible message and code that 5 | * is received from Kite Connect api. 6 | */ 7 | 8 | public class KiteException extends Throwable { 9 | 10 | // variables 11 | public String message; 12 | public int code; 13 | 14 | // constructor that sets the message 15 | public KiteException(String message){ 16 | this.message = message; 17 | } 18 | 19 | // constructor that sets the message and code 20 | public KiteException(String message, int code){ 21 | this.message = message; 22 | this.code = code; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/MarginException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * There are insufficient funds in the account. 5 | * */ 6 | public class MarginException extends KiteException{ 7 | public MarginException(String message, int code) { 8 | super(message, code); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/NetworkException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * Represents a network issue between Kite and the backend Order Management System (OMS). 5 | * Default code is 503. 6 | */ 7 | 8 | public class NetworkException extends KiteException { 9 | 10 | // initialize Kite Network exception and call Base Exception constructor 11 | public NetworkException(String message, int code){ 12 | super(message, code); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/OrderException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * Represents all order placement and manipulation errors. 5 | * Default code is 500. 6 | */ 7 | 8 | public class OrderException extends KiteException { 9 | 10 | // initialize Order Exception and call base exception constructor 11 | public OrderException(String message, int code){ 12 | super(message, code); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/PermissionException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * Represents permission denied exceptions for certain calls. 5 | * Default code is 403 6 | */ 7 | public class PermissionException extends KiteException { 8 | public PermissionException(String message, int code){ 9 | super(message, code); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/TokenException.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; 2 | 3 | /** 4 | * Denotes session is expired. 5 | */ 6 | public class TokenException extends KiteException { 7 | public TokenException(String message, int code) { 8 | super(message, code); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/exceptions/package-info.java: -------------------------------------------------------------------------------- 1 | /**Different exceptions that kite connect deals with.*/ 2 | package com.zerodhatech.kiteconnect.kitehttp.exceptions; -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/package-info.java: -------------------------------------------------------------------------------- 1 | /**Wrapper classes for making API call to server and callback for session expiry event.*/ 2 | package com.zerodhatech.kiteconnect.kitehttp; -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/package-info.java: -------------------------------------------------------------------------------- 1 | /** Offers all functionality that Kite Connect can provide for building a platform.*/ 2 | package com.zerodhatech.kiteconnect; -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/utils/Constants.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.kiteconnect.utils; 2 | 3 | /** 4 | * Contains all the Strings that are being used in the Kite Connect library. 5 | */ 6 | public class Constants { 7 | 8 | /** Product types. */ 9 | public static final String PRODUCT_MIS = "MIS"; 10 | public static final String PRODUCT_CNC = "CNC"; 11 | public static final String PRODUCT_NRML = "NRML"; 12 | public static final String PRODUCT_MTF = "MTF"; 13 | 14 | /** Order types. */ 15 | public static final String ORDER_TYPE_MARKET = "MARKET"; 16 | public static final String ORDER_TYPE_LIMIT = "LIMIT"; 17 | public static final String ORDER_TYPE_SL = "SL"; 18 | public static final String ORDER_TYPE_SLM = "SL-M"; 19 | 20 | /** Variety types. */ 21 | public static final String VARIETY_REGULAR = "regular"; 22 | public static final String VARIETY_BO = "bo"; 23 | public static final String VARIETY_CO = "co"; 24 | public static final String VARIETY_AMO = "amo"; 25 | public static final String VARIETY_ICEBERG = "iceberg"; 26 | public static final String VARIETY_AUCTION = "auction"; 27 | 28 | /** Transaction types. */ 29 | public static final String TRANSACTION_TYPE_BUY = "BUY"; 30 | public static final String TRANSACTION_TYPE_SELL = "SELL"; 31 | 32 | /** Position types. */ 33 | public static final String POSITION_DAY = "day"; 34 | public static final String POSITION_OVERNIGHT = "overnight"; 35 | 36 | /** Validity types. */ 37 | public static final String VALIDITY_DAY = "DAY"; 38 | public static final String VALIDITY_IOC = "IOC"; 39 | public static final String VALIDITY_TTL = "TTL"; 40 | 41 | /** Exchanges. */ 42 | public static final String EXCHANGE_NSE = "NSE"; 43 | public static final String EXCHANGE_BSE = "BSE"; 44 | public static final String EXCHANGE_NFO = "NFO"; 45 | public static final String EXCHANGE_BFO = "BFO"; 46 | public static final String EXCHANGE_MCX = "MCX"; 47 | public static final String EXCHANGE_CDS = "CDS"; 48 | 49 | /** Margin segments. */ 50 | public static final String MARGIN_EQUITY = "equity"; 51 | public static final String MARGIN_COMMODITY = "commodity"; 52 | 53 | /** Instruments segments. */ 54 | public static final String INSTRUMENTS_SEGMENTS_EQUITY = "equity"; 55 | public static final String INSTRUMENTS_SEGMENTS_COMMODITY = "commodity"; 56 | public static final String INSTRUMENTS_SEGMENTS_FUTURES = "futures"; 57 | public static final String INSTRUMENTS_SEGMENTS_CURRENCY = "currency"; 58 | 59 | /* GTT status */ 60 | public static final String ACTIVE = "active"; 61 | public static final String TRIGGERED = "triggered"; 62 | public static final String DISABLED = "disabled"; 63 | public static final String EXPIRED = "expired"; 64 | public static final String CANCELLED = "cancelled"; 65 | public static final String REJECTED = "rejected"; 66 | public static final String DELETED = "deleted"; 67 | 68 | 69 | /* GTT trigger type */ 70 | public static final String OCO = "two-leg"; 71 | public static final String SINGLE = "single"; 72 | 73 | /*These are commonly used order statuses but there are many other order statuses. 74 | * Some of the statuses are only intermediate. */ 75 | public static final String ORDER_CANCELLED = "CANCELLED"; 76 | public static final String ORDER_REJECTED = "REJECTED"; 77 | public static final String ORDER_COMPLETE = "COMPLETE"; 78 | public static final String ORDER_OPEN = "OPEN"; 79 | public static final String ORDER_LAPSED = "LAPSED"; 80 | public static final String ORDER_TRIGGER_PENDING = "TRIGGER PENDING"; 81 | } 82 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/kiteconnect/utils/package-info.java: -------------------------------------------------------------------------------- 1 | /**Commonly used constants are defined here.*/ 2 | package com.zerodhatech.kiteconnect.utils; -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/AuctionInstrument.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | public class AuctionInstrument { 6 | @SerializedName("tradingsymbol") 7 | public String tradingSymbol; 8 | @SerializedName("exchange") 9 | public String exchange; 10 | @SerializedName("instrument_token") 11 | public long instrumentToken; 12 | @SerializedName("isin") 13 | public String isin; 14 | @SerializedName("product") 15 | public String product; 16 | @SerializedName("price") 17 | public double price; 18 | @SerializedName("quantity") 19 | public int quantity; 20 | @SerializedName("t1_quantity") 21 | public int t1Quantity; 22 | @SerializedName("realised_quantity") 23 | public int realisedQuantity; 24 | @SerializedName("authorised_quantity") 25 | public int authorisedQuantity; 26 | @SerializedName("authorised_date") 27 | public String authorisedDate; 28 | @SerializedName("opening_quantity") 29 | public String openingQuantity; 30 | @SerializedName("collateral_quantity") 31 | public int collateralQuantity; 32 | @SerializedName("collateral_type") 33 | public String collateralType; 34 | @SerializedName("discrepancy") 35 | public boolean discrepancy; 36 | @SerializedName("average_price") 37 | public double averagePrice; 38 | @SerializedName("last_price") 39 | public double lastPrice; 40 | @SerializedName("close_price") 41 | public double closePrice; 42 | @SerializedName("pnl") 43 | public double pnl; 44 | @SerializedName("day_change") 45 | public double dayChange; 46 | @SerializedName("day_change_percentage") 47 | public double dayChangePercentage; 48 | @SerializedName("auction_number") 49 | public String auctionNumber; 50 | } 51 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/BulkOrderError.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | public class BulkOrderError { 6 | @SerializedName("code") 7 | public int code; 8 | @SerializedName("error_type") 9 | public String errorType; 10 | @SerializedName("message") 11 | public String message; 12 | } 13 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/BulkOrderResponse.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for place auto slice order response. 7 | */ 8 | public class BulkOrderResponse { 9 | @SerializedName("order_id") 10 | public String orderId; 11 | @SerializedName("error") 12 | public BulkOrderError bulkOrderError; 13 | } 14 | 15 | 16 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/CombinedMarginData.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | import java.util.List; 5 | 6 | /** 7 | * A wrapper for basket margin calculation response data. 8 | */ 9 | 10 | public class CombinedMarginData { 11 | @SerializedName("initial") 12 | public MarginCalculationData initialMargin; 13 | 14 | @SerializedName("final") 15 | public MarginCalculationData finalMargin; 16 | 17 | @SerializedName("orders") 18 | public List orders; 19 | } -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/ContractNote.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for virtual contract note response data. 7 | */ 8 | public class ContractNote { 9 | @SerializedName("transaction_type") 10 | public String transactionType; 11 | @SerializedName("tradingsymbol") 12 | public String tradingSymbol; 13 | @SerializedName("exchange") 14 | public String exchange; 15 | @SerializedName("variety") 16 | public String variety; 17 | @SerializedName("product") 18 | public String product; 19 | @SerializedName("order_type") 20 | public String orderType; 21 | @SerializedName("quantity") 22 | public int quantity = 0; 23 | @SerializedName("price") 24 | public double price = 0.0; 25 | @SerializedName("charges") 26 | public MarginCalculationData.Charges charges; 27 | } 28 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/ContractNoteParams.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | /** 4 | * A wrapper for virtual contract note API's params to be sent while sending request. 5 | */ 6 | public class ContractNoteParams { 7 | /** 8 | * order ID that is received in the orderbook. 9 | */ 10 | public String orderID; 11 | /** 12 | * Tradingsymbol of the instrument (ex. RELIANCE, INFY). 13 | */ 14 | public String tradingSymbol; 15 | /** 16 | * Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). 17 | */ 18 | public String exchange; 19 | /** 20 | * Transaction type (BUY or SELL). 21 | */ 22 | public String transactionType; 23 | 24 | /** Variety (regular, co, amo, iceberg)*/ 25 | public String variety; 26 | /** 27 | * Product code (NRML, MIS, CNC). 28 | */ 29 | public String product; 30 | /** 31 | * Order type (LIMIT, SL, SL-M, MARKET). 32 | */ 33 | public String orderType; 34 | /** 35 | * Order quantity. 36 | */ 37 | public int quantity; 38 | /** 39 | * Average price of the order. 40 | */ 41 | public double averagePrice; 42 | } 43 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Depth.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for market depth. 7 | */ 8 | public class Depth { 9 | 10 | @SerializedName("quantity") 11 | private int quantity; 12 | @SerializedName("price") 13 | private double price; 14 | @SerializedName("orders") 15 | private int orders; 16 | 17 | public int getQuantity() { 18 | return quantity; 19 | } 20 | 21 | public void setQuantity(int quantity) { 22 | this.quantity = quantity; 23 | } 24 | 25 | public double getPrice() { 26 | return price; 27 | } 28 | 29 | public void setPrice(double price) { 30 | this.price = price; 31 | } 32 | 33 | public int getOrders() { 34 | return orders; 35 | } 36 | 37 | public void setOrders(int orders) { 38 | this.orders = orders; 39 | } 40 | } -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/GTT.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | * Created by sujith on 9/21/19. 9 | */ 10 | public class GTT { 11 | @SerializedName("id") 12 | public int id; 13 | 14 | @SerializedName("condition") 15 | public Condition condition; 16 | 17 | @SerializedName("type") 18 | public String triggerType; 19 | 20 | @SerializedName("orders") 21 | public List orders; 22 | 23 | @SerializedName("status") 24 | public String status; 25 | 26 | @SerializedName("created_at") 27 | public String createdAt; 28 | 29 | @SerializedName("updated_at") 30 | public String updatedAt; 31 | 32 | @SerializedName("expires_at") 33 | public String expiresAt; 34 | 35 | @SerializedName("meta") 36 | public GTTMeta meta; 37 | 38 | public class GTTMeta { 39 | @SerializedName("rejection_reason") 40 | public String rejectionReason; 41 | } 42 | 43 | public class Condition { 44 | @SerializedName("instrument_token") 45 | public int instrumentToken; 46 | 47 | @SerializedName("exchange") 48 | public String exchange; 49 | 50 | @SerializedName("tradingsymbol") 51 | public String tradingSymbol; 52 | 53 | @SerializedName("trigger_values") 54 | public List triggerValues; 55 | 56 | @SerializedName("last_price") 57 | public double lastPrice; 58 | } 59 | 60 | public class GTTOrder { 61 | @SerializedName("transaction_type") 62 | public String transactionType; 63 | 64 | @SerializedName("product") 65 | public String product; 66 | 67 | @SerializedName("order_type") 68 | public String orderType; 69 | 70 | @SerializedName("quantity") 71 | public int quantity; 72 | 73 | @SerializedName("price") 74 | public double price; 75 | 76 | @SerializedName("result") 77 | public GTTResult result; 78 | } 79 | 80 | public class GTTResult { 81 | @SerializedName("order_result") 82 | public GTTOrderResult orderResult; 83 | 84 | @SerializedName("timestamp") 85 | public String timestamp = "-"; 86 | 87 | @SerializedName("triggered_at") 88 | public double triggeredAtPrice; 89 | } 90 | 91 | public class GTTOrderResult { 92 | @SerializedName("order_id") 93 | public String orderId = "-"; 94 | 95 | @SerializedName("rejection_reason") 96 | public String reason; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/GTTParams.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Created by sujith on 9/23/19. 7 | */ 8 | public class GTTParams { 9 | /** 10 | * Tradingsymbol of the instrument (ex. RELIANCE, INFY). 11 | */ 12 | public String tradingsymbol; 13 | /** 14 | * Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). 15 | */ 16 | public String exchange; 17 | /** A unique instrument token which is assigned to each instrument, can be found in the instrument master dump.*/ 18 | public int instrumentToken; 19 | 20 | public String triggerType; 21 | 22 | public double lastPrice; 23 | 24 | /** List of target or stop-loss orders*/ 25 | public List orders; 26 | 27 | public List triggerPrices; 28 | 29 | public class GTTOrderParams{ 30 | /** 31 | * Order quantity 32 | */ 33 | public int quantity; 34 | /** 35 | * Order Price 36 | */ 37 | public double price; 38 | /** 39 | * Order type (LIMIT, SL, SL-M, MARKET). 40 | */ 41 | public String orderType; 42 | /** 43 | * Product code (NRML, MIS, CNC). 44 | */ 45 | public String product; 46 | 47 | /** Transaction type (BUY, SELL) 48 | * */ 49 | public String transactionType; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/HistoricalData.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONException; 5 | import org.json.JSONObject; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | /** 11 | * A wrapper for historical data. 12 | */ 13 | public class HistoricalData { 14 | 15 | public String timeStamp; 16 | public double open; 17 | public double high; 18 | public double low; 19 | public double close; 20 | public long volume; 21 | public long oi; 22 | public List dataArrayList = new ArrayList<>(); 23 | 24 | public void parseResponse(JSONObject response) throws JSONException { 25 | JSONObject data = response.getJSONObject("data"); 26 | JSONArray candleArray = data.getJSONArray("candles"); 27 | for(int i = 0; i < candleArray.length(); i++){ 28 | JSONArray itemArray = candleArray.getJSONArray(i); 29 | HistoricalData historicalData = new HistoricalData(); 30 | historicalData.timeStamp = itemArray.getString(0); 31 | historicalData.open = itemArray.getDouble(1); 32 | historicalData.high = itemArray.getDouble(2); 33 | historicalData.low = itemArray.getDouble(3); 34 | historicalData.close = itemArray.getDouble(4); 35 | historicalData.volume = itemArray.getLong(5); 36 | if(itemArray.length() > 6) 37 | historicalData.oi = itemArray.getLong(6); 38 | dataArrayList.add(historicalData); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Holding.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * A wrapper for holdings. 9 | */ 10 | public class Holding { 11 | 12 | @SerializedName("product") 13 | public String product; 14 | @SerializedName("last_price") 15 | public Double lastPrice; 16 | @SerializedName("price") 17 | public String price; 18 | @SerializedName("tradingsymbol") 19 | public String tradingSymbol; 20 | @SerializedName("t1_quantity") 21 | public int t1Quantity; 22 | @SerializedName("collateral_quantity") 23 | public String collateralQuantity; 24 | @SerializedName("collateral_type") 25 | public String collateraltype; 26 | @SerializedName("isin") 27 | public String isin; 28 | @SerializedName("pnl") 29 | public Double pnl; 30 | @SerializedName("quantity") 31 | public int quantity; 32 | @SerializedName("realised_quantity") 33 | public String realisedQuantity; 34 | @SerializedName("average_price") 35 | public Double averagePrice; 36 | @SerializedName("exchange") 37 | public String exchange; 38 | @SerializedName("instrument_token") 39 | public String instrumentToken; 40 | @SerializedName("used_quantity") 41 | public int usedQuantity; 42 | @SerializedName("authorised_quantity") 43 | public int authorisedQuantity; 44 | @SerializedName("authorised_date") 45 | public Date authorisedDate; 46 | @SerializedName("discrepancy") 47 | public boolean discrepancy; 48 | @SerializedName("day_change") 49 | public double dayChange; 50 | @SerializedName("day_change_percentage") 51 | public double dayChangePercentage; 52 | } 53 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Instrument.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * A wrapper for Instrument. 7 | */ 8 | public class Instrument { 9 | public long instrument_token,exchange_token; 10 | public String tradingsymbol,name; 11 | public double last_price, tick_size; 12 | public String instrument_type,segment,exchange, strike; 13 | public int lot_size; 14 | public Date expiry; 15 | 16 | 17 | public long getInstrument_token() { 18 | return instrument_token; 19 | } 20 | 21 | public void setInstrument_token(long instrument_token) { 22 | this.instrument_token = instrument_token; 23 | } 24 | 25 | public long getExchange_token() { 26 | return exchange_token; 27 | } 28 | 29 | public void setExchange_token(long exchange_token) { 30 | this.exchange_token = exchange_token; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | public String getTradingsymbol() { 42 | return tradingsymbol; 43 | } 44 | 45 | public void setTradingsymbol(String tradingsymbol) { 46 | this.tradingsymbol = tradingsymbol; 47 | } 48 | 49 | public double getLast_price() { 50 | return last_price; 51 | } 52 | 53 | public void setLast_price(double last_price) { 54 | this.last_price = last_price; 55 | } 56 | 57 | public double getTick_size() { 58 | return tick_size; 59 | } 60 | 61 | public void setTick_size(double tick_size) { 62 | this.tick_size = tick_size; 63 | } 64 | 65 | public Date getExpiry() { 66 | return expiry; 67 | } 68 | 69 | public void setExpiry(Date expiry) { 70 | this.expiry = expiry; 71 | } 72 | 73 | public String getInstrument_type() { 74 | return instrument_type; 75 | } 76 | 77 | public void setInstrument_type(String instrument_type) { 78 | this.instrument_type = instrument_type; 79 | } 80 | 81 | public String getSegment() { 82 | return segment; 83 | } 84 | 85 | public void setSegment(String segment) { 86 | this.segment = segment; 87 | } 88 | 89 | public String getExchange() { 90 | return exchange; 91 | } 92 | 93 | public void setExchange(String exchange) { 94 | this.exchange = exchange; 95 | } 96 | 97 | public String getStrike() { 98 | return strike; 99 | } 100 | 101 | public void setStrike(String strike) { 102 | this.strike = strike; 103 | } 104 | 105 | public int getLot_size() { 106 | return lot_size; 107 | } 108 | 109 | public void setLot_size(int lot_size) { 110 | this.lot_size = lot_size; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/LTPQuote.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for instrument token, OHLC data. 7 | */ 8 | public class LTPQuote { 9 | 10 | @SerializedName("instrument_token") 11 | public long instrumentToken; 12 | @SerializedName("last_price") 13 | public double lastPrice; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/MFHolding.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for mutual funds holding. 7 | */ 8 | public class MFHolding { 9 | @SerializedName("quantity") 10 | public double quantity; 11 | @SerializedName("fund") 12 | public String fund; 13 | @SerializedName("folio") 14 | public String folio; 15 | @SerializedName("average_price") 16 | public double averagePrice; 17 | @SerializedName("tradingsymbol") 18 | public String tradingsymbol; 19 | @SerializedName("last_price") 20 | public double lastPrice; 21 | @SerializedName("pnl") 22 | public double pnl; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/MFInstrument.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * A wrapper for mutual funds instrument. 7 | */ 8 | public class MFInstrument { 9 | public String tradingsymbol, amc, name; 10 | public boolean purchase_allowed, redemption_allowed; 11 | public double minimum_purchase_amount, purchase_amount_multiplier, minimum_additional_purchase_amount, minimum_redemption_quantity; 12 | public double redemption_quantity_multiplier, last_price; 13 | public String dividend_type, scheme_type, plan, settlement_type; 14 | public Date last_price_date; 15 | 16 | public String getTradingsymbol() { 17 | return tradingsymbol; 18 | } 19 | 20 | public void setTradingsymbol(String tradingsymbol) { 21 | this.tradingsymbol = tradingsymbol; 22 | } 23 | 24 | public String getAmc() { 25 | return amc; 26 | } 27 | 28 | public void setAmc(String amc) { 29 | this.amc = amc; 30 | } 31 | 32 | public String getName() { 33 | return name; 34 | } 35 | 36 | public void setName(String name) { 37 | this.name = name; 38 | } 39 | 40 | public boolean getPurchase_allowed() { 41 | return purchase_allowed; 42 | } 43 | 44 | public void setPurchase_allowed(boolean purchase_allowed) { 45 | this.purchase_allowed = purchase_allowed; 46 | } 47 | 48 | public boolean getRedemption_allowed() { 49 | return redemption_allowed; 50 | } 51 | 52 | public void setRedemption_allowed(boolean redemption_allowed) { 53 | this.redemption_allowed = redemption_allowed; 54 | } 55 | 56 | public double getMinimum_purchase_amount() { 57 | return minimum_purchase_amount; 58 | } 59 | 60 | public void setMinimum_purchase_amount(double minimum_purchase_amount) { 61 | this.minimum_purchase_amount = minimum_purchase_amount; 62 | } 63 | 64 | public double getPurchase_amount_multiplier() { 65 | return purchase_amount_multiplier; 66 | } 67 | 68 | public void setPurchase_amount_multiplier(double purchase_amount_multiplier) { 69 | this.purchase_amount_multiplier = purchase_amount_multiplier; 70 | } 71 | 72 | public double getMinimum_additional_purchase_amount() { 73 | return minimum_additional_purchase_amount; 74 | } 75 | 76 | public void setMinimum_additional_purchase_amount(double minimum_additional_purchase_amount) { 77 | this.minimum_additional_purchase_amount = minimum_additional_purchase_amount; 78 | } 79 | 80 | public double getMinimum_redemption_quantity() { 81 | return minimum_redemption_quantity; 82 | } 83 | 84 | public void setMinimum_redemption_quantity(double minimum_redemption_quantity) { 85 | this.minimum_redemption_quantity = minimum_redemption_quantity; 86 | } 87 | 88 | public double getRedemption_quantity_multiplier() { 89 | return redemption_quantity_multiplier; 90 | } 91 | 92 | public void setRedemption_quantity_multiplier(double redemption_quantity_multiplier) { 93 | this.redemption_quantity_multiplier = redemption_quantity_multiplier; 94 | } 95 | 96 | public double getLast_price() { 97 | return last_price; 98 | } 99 | 100 | public void setLast_price(double last_price) { 101 | this.last_price = last_price; 102 | } 103 | 104 | public String getDividend_type() { 105 | return dividend_type; 106 | } 107 | 108 | public void setDividend_type(String dividend_type) { 109 | this.dividend_type = dividend_type; 110 | } 111 | 112 | public String getScheme_type() { 113 | return scheme_type; 114 | } 115 | 116 | public void setScheme_type(String scheme_type) { 117 | this.scheme_type = scheme_type; 118 | } 119 | 120 | public String getPlan() { 121 | return plan; 122 | } 123 | 124 | public void setPlan(String plan) { 125 | this.plan = plan; 126 | } 127 | 128 | public String getSettlement_type() { 129 | return settlement_type; 130 | } 131 | 132 | public void setSettlement_type(String settlement_type) { 133 | this.settlement_type = settlement_type; 134 | } 135 | 136 | public Date getLast_price_date() { 137 | return last_price_date; 138 | } 139 | 140 | public void setLast_price_date(Date last_price_date) { 141 | this.last_price_date = last_price_date; 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/MFOrder.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * A wrapper for mutual funds order. 9 | */ 10 | public class MFOrder { 11 | @SerializedName("status_message") 12 | public String statusMessage; 13 | @SerializedName("purchase_type") 14 | public String purchaseType; 15 | @SerializedName("placed_by") 16 | public String placedBy; 17 | @SerializedName("amount") 18 | public double amount; 19 | @SerializedName("quantity") 20 | public double quantity; 21 | @SerializedName("settlement_id") 22 | public String settlementId; 23 | @SerializedName("order_timestamp") 24 | public Date orderTimestamp; 25 | @SerializedName("average_price") 26 | public double averagePrice; 27 | @SerializedName("transaction_type") 28 | public String transactionType; 29 | @SerializedName("exchange_order_id") 30 | public Date exchangeOrderId; 31 | @SerializedName("exchange_timestamp") 32 | public Date exchangeTimestamp; 33 | @SerializedName("fund") 34 | public String fund; 35 | @SerializedName("variety") 36 | public String variety; 37 | @SerializedName("folio") 38 | public String folio; 39 | @SerializedName("tradingsymbol") 40 | public String tradingsymbol; 41 | @SerializedName("tag") 42 | public String tag; 43 | @SerializedName("order_id") 44 | public String orderId; 45 | @SerializedName("status") 46 | public String status; 47 | @SerializedName("last_price") 48 | public double lastPrice; 49 | 50 | } 51 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/MFSIP.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * A wrapper for mutual funds sip. 9 | */ 10 | public class MFSIP { 11 | @SerializedName("dividend_type") 12 | public String dividendType; 13 | @SerializedName("pending_instalments") 14 | public int pendingInstalments; 15 | @SerializedName("created") 16 | public Date created; 17 | @SerializedName("last_instalment") 18 | public Date lastInstalment; 19 | @SerializedName("transaction_type") 20 | public String transactionType; 21 | @SerializedName("frequency") 22 | public String frequency; 23 | @SerializedName("instalment_date") 24 | public int instalmentDate; 25 | @SerializedName("fund") 26 | public String fund; 27 | @SerializedName("sip_id") 28 | public String sipId; 29 | @SerializedName("tradingsymbol") 30 | public String tradingsymbol; 31 | @SerializedName("tag") 32 | public String tag; 33 | @SerializedName("instalment_amount") 34 | public int instalmentAmount; 35 | @SerializedName("instalments") 36 | public int instalments; 37 | @SerializedName("status") 38 | public String status; 39 | @SerializedName("order_id") 40 | public String orderId; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Margin.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | /** 4 | * A wrapper for funds. 5 | */ 6 | 7 | import com.google.gson.annotations.SerializedName; 8 | 9 | 10 | public class Margin { 11 | 12 | 13 | public Margin(){}; 14 | public Available available; 15 | public Utilised utilised; 16 | 17 | 18 | // Serialized names are the actual keys in json response 19 | @SerializedName("net") 20 | public String net; 21 | 22 | /** 23 | * Class available is a wrapper around available cash margins used by GSON. 24 | * 25 | */ 26 | public static class Available{ 27 | 28 | @SerializedName("cash") 29 | public String cash; 30 | 31 | @SerializedName("intraday_payin") 32 | public String intradayPayin; 33 | 34 | @SerializedName("adhoc_margin") 35 | public String adhocMargin; 36 | 37 | @SerializedName("collateral") 38 | public String collateral; 39 | 40 | @SerializedName("live_balance") 41 | public String liveBalance; 42 | 43 | } 44 | 45 | /** 46 | * Utilised is a wrapper around utilised margins, used by GSON. 47 | */ 48 | 49 | public static class Utilised{ 50 | @SerializedName("m2m_unrealised") 51 | public String m2mUnrealised; 52 | 53 | @SerializedName("m2m_realised") 54 | public String m2mRealised; 55 | 56 | @SerializedName("debits") 57 | public String debits; 58 | 59 | @SerializedName("span") 60 | public String span; 61 | 62 | @SerializedName("option_premium") 63 | public String optionPremium; 64 | 65 | @SerializedName("holding_sales") 66 | public String holdingSales; 67 | 68 | @SerializedName("exposure") 69 | public String exposure; 70 | 71 | @SerializedName("turnover") 72 | public String turnover; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/MarginCalculationData.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for margin calculation response data. 7 | */ 8 | public class MarginCalculationData { 9 | @SerializedName("type") 10 | public String type; 11 | @SerializedName("exchange") 12 | public String exchange; 13 | @SerializedName("tradingsymbol") 14 | public String tradingSymbol; 15 | @SerializedName("span") 16 | public double span; 17 | @SerializedName("exposure") 18 | public double exposure; 19 | @SerializedName("option_premium") 20 | public double optionPremium; 21 | @SerializedName("additional") 22 | public double additional; 23 | @SerializedName("bo") 24 | public double bo; 25 | @SerializedName("cash") 26 | public double cash; 27 | @SerializedName("var") 28 | public double var; 29 | @SerializedName("pnl") 30 | public PnL pnl; 31 | @SerializedName("total") 32 | public double total; 33 | @SerializedName("charges") 34 | public Charges charges; 35 | @SerializedName("leverage") 36 | public double leverage; 37 | 38 | public class PnL { 39 | @SerializedName("realised") 40 | public double realised; 41 | @SerializedName("unrealised") 42 | public double unrealised; 43 | } 44 | 45 | public class Charges{ 46 | @SerializedName("transaction_tax") 47 | public double transactionTax; 48 | @SerializedName("transaction_tax_type") 49 | public String transactionTaxType; 50 | @SerializedName("exchange_turnover_charge") 51 | public double exchangeTurnoverCharge; 52 | @SerializedName("sebi_turnover_charge") 53 | public double SEBITurnoverCharge; 54 | @SerializedName("brokerage") 55 | public double brokerage; 56 | @SerializedName("stamp_duty") 57 | public double stampDuty; 58 | @SerializedName("gst") 59 | public GST gst; 60 | @SerializedName("total") 61 | public double total; 62 | } 63 | 64 | public class GST{ 65 | @SerializedName("igst") 66 | public double IGST; 67 | @SerializedName("cgst") 68 | public double CGST; 69 | @SerializedName("sgst") 70 | public double SGST; 71 | @SerializedName("total") 72 | public double total; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/MarginCalculationParams.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | /** 4 | * A wrapper for margin calculation API's params to be sent while sending request. 5 | */ 6 | public class MarginCalculationParams { 7 | /** 8 | * Tradingsymbol of the instrument (ex. RELIANCE, INFY). 9 | */ 10 | public String tradingSymbol; 11 | /** 12 | * Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). 13 | */ 14 | public String exchange; 15 | /** 16 | * Transaction type (BUY or SELL). 17 | */ 18 | public String transactionType; 19 | /** Variety (regular, co, amo)*/ 20 | public String variety; 21 | /** 22 | * Product code (NRML, MIS, CNC). 23 | */ 24 | public String product; 25 | /** 26 | * Order type (LIMIT, SL, SL-M, MARKET). 27 | */ 28 | public String orderType; 29 | /** 30 | * Order quantity 31 | */ 32 | public int quantity; 33 | /** 34 | * Order Price 35 | */ 36 | public double price; 37 | /** 38 | * Trigger price 39 | */ 40 | public double triggerPrice; 41 | } 42 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/MarketDepth.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * A wrapper for market depth data. 9 | */ 10 | public class MarketDepth { 11 | @SerializedName("buy") 12 | public List buy; 13 | @SerializedName("sell") 14 | public List sell; 15 | } 16 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/OHLC.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for open, high, low, close. 7 | */ 8 | public class OHLC { 9 | 10 | @SerializedName("high") 11 | public double high; 12 | @SerializedName("low") 13 | public double low; 14 | @SerializedName("close") 15 | public double close; 16 | @SerializedName("open") 17 | public double open; 18 | } 19 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/OHLCQuote.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for open, high, low, close, instrument token and last price 7 | */ 8 | public class OHLCQuote { 9 | 10 | @SerializedName("instrument_token") 11 | public long instrumentToken; 12 | @SerializedName("last_price") 13 | public double lastPrice; 14 | @SerializedName("ohlc") 15 | public OHLC ohlc; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Order.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.Date; 6 | import java.util.Map; 7 | 8 | /** 9 | * A wrapper for order. 10 | */ 11 | public class Order { 12 | 13 | @SerializedName("exchange_order_id") 14 | public String exchangeOrderId; 15 | @SerializedName("disclosed_quantity") 16 | public String disclosedQuantity; 17 | @SerializedName("validity") 18 | public String validity; 19 | @SerializedName("tradingsymbol") 20 | public String tradingSymbol; 21 | @SerializedName("variety") 22 | public String orderVariety; 23 | @SerializedName("order_type") 24 | public String orderType; 25 | @SerializedName("trigger_price") 26 | public String triggerPrice; 27 | @SerializedName("status_message") 28 | public String statusMessage; 29 | @SerializedName("price") 30 | public String price; 31 | @SerializedName("status") 32 | public String status; 33 | @SerializedName("product") 34 | public String product; 35 | @SerializedName("placed_by") 36 | public String accountId; 37 | @SerializedName("exchange") 38 | public String exchange; 39 | @SerializedName("order_id") 40 | public String orderId; 41 | @SerializedName("pending_quantity") 42 | public String pendingQuantity; 43 | @SerializedName("order_timestamp") 44 | public Date orderTimestamp; 45 | @SerializedName("exchange_timestamp") 46 | public Date exchangeTimestamp; 47 | @SerializedName("exchange_update_timestamp") 48 | public Date exchangeUpdateTimestamp; 49 | @SerializedName("average_price") 50 | public String averagePrice; 51 | @SerializedName("transaction_type") 52 | public String transactionType; 53 | @SerializedName("filled_quantity") 54 | public String filledQuantity; 55 | @SerializedName("quantity") 56 | public String quantity; 57 | @SerializedName("parent_order_id") 58 | public String parentOrderId; 59 | @SerializedName("tag") 60 | public String tag; 61 | @SerializedName("guid") 62 | public String guid; 63 | @SerializedName("validity_ttl") 64 | public int validityTTL; 65 | @SerializedName("meta") 66 | public Map meta; 67 | @SerializedName("auction_number") 68 | public String auctionNumber; 69 | } 70 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/OrderParams.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | /** A wrapper for order params to be sent while placing an order.*/ 4 | public class OrderParams { 5 | /** 6 | * Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). 7 | */ 8 | public String exchange; 9 | 10 | /** 11 | * Tradingsymbol of the instrument (ex. RELIANCE, INFY). 12 | */ 13 | public String tradingsymbol; 14 | 15 | /** 16 | * Transaction type (BUY or SELL). 17 | */ 18 | public String transactionType; 19 | 20 | /** 21 | * Order quantity 22 | */ 23 | public Integer quantity; 24 | 25 | /** 26 | * Order Price 27 | */ 28 | public Double price; 29 | 30 | /** 31 | * Product code (NRML, MIS, CNC). 32 | */ 33 | public String product; 34 | 35 | /** 36 | * Order type (LIMIT, SL, SL-M, MARKET). 37 | */ 38 | public String orderType; 39 | 40 | /** 41 | * Order validity (DAY, IOC). 42 | */ 43 | public String validity; 44 | 45 | /** 46 | * Disclosed quantity 47 | */ 48 | public Integer disclosedQuantity; 49 | 50 | /** 51 | * Trigger price 52 | */ 53 | public Double triggerPrice; 54 | 55 | /** 56 | * Square off value (only for bracket orders) 57 | */ 58 | public Double squareoff; 59 | 60 | /** 61 | * Stoploss value (only for bracket orders) 62 | */ 63 | public Double stoploss; 64 | 65 | /** 66 | * Trailing stoploss value (only for bracket orders) 67 | */ 68 | public Double trailingStoploss; 69 | 70 | /** 71 | * Tag: field for users to tag orders. It accepts alphanumeric 20 character String values. 72 | */ 73 | public String tag; 74 | 75 | /** 76 | * Parent order id is used to send order modify request. 77 | */ 78 | public String parentOrderId; 79 | 80 | /** 81 | * Custom validity user can enter which denotes time to live in minutes. 82 | */ 83 | public int validityTTL; 84 | 85 | /** 86 | * Split quantity for each iceberg leg order. 87 | */ 88 | public int icebergQuantity; 89 | 90 | /** 91 | * Total number of legs for iceberg order type. (number of legs per Iceberg should be between 2 and 10) 92 | */ 93 | public int icebergLegs; 94 | 95 | /** 96 | * Auction number 97 | * */ 98 | public String auctionNumber; 99 | 100 | /** 101 | * Market protection is allowed only for MARKET and SL-M (stoploss market) orders. 102 | * Users can send preferred market protection value, it can be anything between 0 and 1. For Ex: 0.2, 0.9 103 | * If users want to place order without market protection then value must be 0 104 | * For market protection to be applied automatically by kite 105 | * backend users can send -1 106 | * */ 107 | public double marketProtection = 0; 108 | } -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Position.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for position. 7 | */ 8 | public class Position { 9 | 10 | @SerializedName("product") 11 | public String product; 12 | @SerializedName("exchange") 13 | public String exchange; 14 | @SerializedName("sell_value") 15 | public Double sellValue; 16 | @SerializedName("last_price") 17 | public Double lastPrice; 18 | @SerializedName("unrealised") 19 | public Double unrealised; 20 | @SerializedName("buy_price") 21 | public Double buyPrice; 22 | @SerializedName("sell_price") 23 | public Double sellPrice; 24 | @SerializedName("m2m") 25 | public Double m2m; 26 | @SerializedName("tradingsymbol") 27 | public String tradingSymbol; 28 | @SerializedName("quantity") 29 | public int netQuantity; 30 | @SerializedName("sell_quantity") 31 | public int sellQuantity; 32 | @SerializedName("realised") 33 | public Double realised; 34 | @SerializedName("buy_quantity") 35 | public int buyQuantity; 36 | @SerializedName("net_value") 37 | public Double netValue; 38 | @SerializedName("buy_value") 39 | public Double buyValue; 40 | @SerializedName("multiplier") 41 | public Double multiplier; 42 | @SerializedName("instrument_token") 43 | public String instrumentToken; 44 | @SerializedName("close_price") 45 | public Double closePrice; 46 | @SerializedName("pnl") 47 | public Double pnl; 48 | @SerializedName("overnight_quantity") 49 | public int overnightQuantity; 50 | @SerializedName("buy_m2m") 51 | public double buym2m; 52 | @SerializedName("sell_m2m") 53 | public double sellm2m; 54 | @SerializedName("day_buy_quantity") 55 | public double dayBuyQuantity; 56 | @SerializedName("day_sell_quantity") 57 | public double daySellQuantity; 58 | @SerializedName("day_buy_price") 59 | public double dayBuyPrice; 60 | @SerializedName("day_sell_price") 61 | public double daySellPrice; 62 | @SerializedName("day_buy_value") 63 | public double dayBuyValue; 64 | @SerializedName("day_sell_value") 65 | public double daySellValue; 66 | @SerializedName("value") 67 | public double value; 68 | @SerializedName("average_price") 69 | public double averagePrice; 70 | } 71 | 72 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Profile.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for profile response. 7 | */ 8 | public class Profile { 9 | 10 | @SerializedName("user_type") 11 | public String userType; 12 | @SerializedName("email") 13 | public String email; 14 | @SerializedName("user_name") 15 | public String userName; 16 | @SerializedName("user_shortname") 17 | public String userShortname; 18 | @SerializedName("broker") 19 | public String broker; 20 | @SerializedName("exchanges") 21 | public String[] exchanges; 22 | @SerializedName("products") 23 | public String[] products; 24 | @SerializedName("order_types") 25 | public String[] orderTypes; 26 | @SerializedName("avatar_url") 27 | public String avatarURL; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Quote.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * A wrapper for quote. 9 | */ 10 | public class Quote { 11 | 12 | @SerializedName("volume") 13 | public double volumeTradedToday; 14 | @SerializedName("last_quantity") 15 | public double lastTradedQuantity; 16 | @SerializedName("last_trade_time") 17 | public Date lastTradedTime; 18 | @SerializedName("net_change") 19 | public double change; 20 | @SerializedName("oi") 21 | public double oi; 22 | @SerializedName("sell_quantity") 23 | public double sellQuantity; 24 | @SerializedName("last_price") 25 | public double lastPrice; 26 | @SerializedName("buy_quantity") 27 | public double buyQuantity; 28 | @SerializedName("ohlc") 29 | public OHLC ohlc; 30 | @SerializedName("instrument_token") 31 | public long instrumentToken; 32 | @SerializedName("timestamp") 33 | public Date timestamp; 34 | @SerializedName("average_price") 35 | public double averagePrice; 36 | @SerializedName("oi_day_high") 37 | public double oiDayHigh; 38 | @SerializedName("oi_day_low") 39 | public double oiDayLow; 40 | @SerializedName("depth") 41 | public MarketDepth depth; 42 | @SerializedName("lower_circuit_limit") 43 | public double lowerCircuitLimit; 44 | @SerializedName("upper_circuit_limit") 45 | public double upperCircuitLimit; 46 | } 47 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Tick.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | /** 4 | * A wrapper for tick. 5 | */ 6 | 7 | import com.google.gson.annotations.SerializedName; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Date; 11 | import java.util.Map; 12 | 13 | public class Tick { 14 | 15 | @SerializedName("mode") 16 | private String mode; 17 | @SerializedName("tradable") 18 | private boolean tradable; 19 | @SerializedName("token") 20 | private long instrumentToken; 21 | @SerializedName("lastTradedPrice") 22 | private double lastTradedPrice; 23 | @SerializedName("highPrice") 24 | private double highPrice; 25 | @SerializedName("lowPrice") 26 | private double lowPrice; 27 | @SerializedName("openPrice") 28 | private double openPrice; 29 | @SerializedName("closePrice") 30 | private double closePrice; 31 | @SerializedName("change") 32 | private double change; 33 | @SerializedName("lastTradeQuantity") 34 | private double lastTradedQuantity; 35 | @SerializedName("averageTradePrice") 36 | private double averageTradePrice; 37 | @SerializedName("volumeTradedToday") 38 | private long volumeTradedToday; 39 | @SerializedName("totalBuyQuantity") 40 | private double totalBuyQuantity; 41 | @SerializedName("totalSellQuantity") 42 | private double totalSellQuantity; 43 | @SerializedName("lastTradedTime") 44 | private Date lastTradedTime; 45 | @SerializedName("oi") 46 | private double oi; 47 | @SerializedName("openInterestDayHigh") 48 | private double oiDayHigh; 49 | @SerializedName("openInterestDayLow") 50 | private double oiDayLow; 51 | @SerializedName("tickTimestamp") 52 | private Date tickTimestamp; 53 | 54 | @SerializedName("depth") 55 | private Map> depth; 56 | 57 | public Date getLastTradedTime() { 58 | return lastTradedTime; 59 | } 60 | 61 | public void setLastTradedTime(Date lastTradedTime) { 62 | this.lastTradedTime = lastTradedTime; 63 | } 64 | 65 | public double getOi() { 66 | return oi; 67 | } 68 | 69 | public void setOi(double oi) { 70 | this.oi = oi; 71 | } 72 | 73 | public double getOpenInterestDayHigh() { 74 | return oiDayHigh; 75 | } 76 | 77 | public void setOpenInterestDayHigh(double dayHighOpenInterest) { 78 | this.oiDayHigh = dayHighOpenInterest; 79 | } 80 | 81 | public double getOpenInterestDayLow() { 82 | return oiDayLow; 83 | } 84 | 85 | public void setOpenInterestDayLow(double dayLowOpenInterest) { 86 | this.oiDayLow = dayLowOpenInterest; 87 | } 88 | 89 | public Date getTickTimestamp() { 90 | return tickTimestamp; 91 | } 92 | 93 | public void setTickTimestamp(Date tickTimestamp) { 94 | this.tickTimestamp = tickTimestamp; 95 | } 96 | 97 | public String getMode() { 98 | return mode; 99 | } 100 | 101 | public void setMode(String mode) { 102 | this.mode = mode; 103 | } 104 | 105 | public boolean isTradable() { 106 | return tradable; 107 | } 108 | 109 | public void setTradable(boolean tradable) { 110 | this.tradable = tradable; 111 | } 112 | 113 | public long getInstrumentToken() { 114 | return instrumentToken; 115 | } 116 | 117 | public void setInstrumentToken(long token) { 118 | this.instrumentToken = token; 119 | } 120 | 121 | public double getLastTradedPrice() { 122 | return lastTradedPrice; 123 | } 124 | 125 | public void setLastTradedPrice(double lastTradedPrice) { 126 | this.lastTradedPrice = lastTradedPrice; 127 | } 128 | 129 | public double getHighPrice() { 130 | return highPrice; 131 | } 132 | 133 | public void setHighPrice(double highPrice) { 134 | this.highPrice = highPrice; 135 | } 136 | 137 | public double getLowPrice() { 138 | return lowPrice; 139 | } 140 | 141 | public void setLowPrice(double lowPrice) { 142 | this.lowPrice = lowPrice; 143 | } 144 | 145 | public double getOpenPrice() { 146 | return openPrice; 147 | } 148 | 149 | public void setOpenPrice(double openPrice) { 150 | this.openPrice = openPrice; 151 | } 152 | 153 | public double getClosePrice() { 154 | return closePrice; 155 | } 156 | 157 | public void setClosePrice(double closePrice) { 158 | this.closePrice = closePrice; 159 | } 160 | 161 | public double getChange() { 162 | return change; 163 | } 164 | 165 | public void setNetPriceChangeFromClosingPrice(double netPriceChangeFromClosingPrice) { 166 | this.change = netPriceChangeFromClosingPrice; 167 | } 168 | 169 | public double getLastTradedQuantity() { 170 | return lastTradedQuantity; 171 | } 172 | 173 | public void setLastTradedQuantity(double lastTradedQuantity) { 174 | this.lastTradedQuantity = lastTradedQuantity; 175 | } 176 | 177 | public double getAverageTradePrice() { 178 | return averageTradePrice; 179 | } 180 | 181 | public void setAverageTradePrice(double averageTradePrice) { 182 | this.averageTradePrice = averageTradePrice; 183 | } 184 | 185 | public long getVolumeTradedToday() { 186 | return volumeTradedToday; 187 | } 188 | 189 | public void setVolumeTradedToday(long volumeTradedToday) { 190 | this.volumeTradedToday = volumeTradedToday; 191 | } 192 | 193 | public double getTotalBuyQuantity() { 194 | return totalBuyQuantity; 195 | } 196 | 197 | public void setTotalBuyQuantity(double totalBuyQuantity) { 198 | this.totalBuyQuantity = totalBuyQuantity; 199 | } 200 | 201 | public double getTotalSellQuantity() { 202 | return totalSellQuantity; 203 | } 204 | 205 | public void setTotalSellQuantity(double totalSellQuantity) { 206 | this.totalSellQuantity = totalSellQuantity; 207 | } 208 | 209 | public Map> getMarketDepth() { 210 | return depth; 211 | } 212 | 213 | public void setMarketDepth(Map> marketDepth) { 214 | this.depth = marketDepth; 215 | } 216 | 217 | } 218 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/TokenSet.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for user id, access token, refresh token. 7 | */ 8 | public class TokenSet { 9 | 10 | @SerializedName("user_id") 11 | public String userId; 12 | @SerializedName("access_token") 13 | public String accessToken; 14 | @SerializedName("refresh_token") 15 | public String refreshToken; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/Trade.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * A wrapper for trade. 9 | */ 10 | public class Trade { 11 | @SerializedName("trade_id") 12 | public String tradeId; 13 | @SerializedName("order_id") 14 | public String orderId; 15 | @SerializedName("exchange_order_id") 16 | public String exchangeOrderId; 17 | @SerializedName("tradingsymbol") 18 | public String tradingSymbol; 19 | @SerializedName("exchange") 20 | public String exchange; 21 | @SerializedName("instrument_token") 22 | public String instrumentToken; 23 | @SerializedName("product") 24 | public String product; 25 | @SerializedName("average_price") 26 | public String averagePrice; 27 | @SerializedName("quantity") 28 | public String quantity; 29 | @SerializedName("fill_timestamp") 30 | public Date fillTimestamp; 31 | @SerializedName("exchange_timestamp") 32 | public Date exchangeTimestamp; 33 | @SerializedName("transaction_type") 34 | public String transactionType; 35 | } 36 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/TriggerRange.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | 5 | /** 6 | * A wrapper for trigger range. 7 | */ 8 | public class TriggerRange { 9 | 10 | @SerializedName("lower") 11 | public double lower; 12 | @SerializedName("upper") 13 | public double upper; 14 | @SerializedName("percentage") 15 | public double percentage; 16 | } 17 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/User.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.models; 2 | 3 | import com.google.gson.*; 4 | import com.google.gson.annotations.SerializedName; 5 | import org.json.JSONArray; 6 | import org.json.JSONException; 7 | import org.json.JSONObject; 8 | 9 | import java.lang.reflect.Type; 10 | import java.text.ParseException; 11 | import java.text.SimpleDateFormat; 12 | import java.util.Date; 13 | 14 | /** 15 | * A wrapper for user and session details. 16 | */ 17 | public class User { 18 | 19 | public String[] products; 20 | @SerializedName("user_name") 21 | public String userName; 22 | @SerializedName("broker") 23 | public String broker; 24 | @SerializedName("access_token") 25 | public String accessToken; 26 | @SerializedName("public_token") 27 | public String publicToken; 28 | @SerializedName("user_type") 29 | public String userType; 30 | @SerializedName("user_id") 31 | public String userId; 32 | @SerializedName("login_time") 33 | public Date loginTime; 34 | @SerializedName("api_key") 35 | public String apiKey; 36 | public String[] exchanges; 37 | public String[] orderTypes; 38 | @SerializedName("email") 39 | public String email; 40 | @SerializedName("refresh_token") 41 | public String refreshToken; 42 | @SerializedName("user_shortname") 43 | public String shortName; 44 | @SerializedName("avatar_url") 45 | public String avatarURL; 46 | 47 | /** Parses user details response from server. 48 | * @param response is the json response from server. 49 | * @throws JSONException is thrown when there is error while parsing response. 50 | * @return User is the parsed data. 51 | * */ 52 | public User parseResponse(JSONObject response) throws JSONException { 53 | GsonBuilder gsonBuilder = new GsonBuilder(); 54 | gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() { 55 | 56 | @Override 57 | public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { 58 | try { 59 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 60 | return format.parse(jsonElement.getAsString()); 61 | } catch (ParseException e) { 62 | return null; 63 | } 64 | } 65 | }); 66 | Gson gson = gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss").create(); 67 | User user = gson.fromJson(String.valueOf(response.get("data")), User.class); 68 | user = parseArray(user, response.getJSONObject("data")); 69 | return user; 70 | } 71 | 72 | /** Parses array details of product, exchange and order_type from json response. 73 | * @param response is the json response from server. 74 | * @param user is the object to which data is copied to from json response. 75 | * @return User is the pojo of parsed data. 76 | * */ 77 | public User parseArray(User user, JSONObject response) throws JSONException { 78 | JSONArray productArray = response.getJSONArray("products"); 79 | user.products = new String[productArray.length()]; 80 | for(int i = 0; i < productArray.length(); i++) { 81 | user.products[i] = productArray.getString(i); 82 | } 83 | 84 | JSONArray exchangesArray = response.getJSONArray("exchanges"); 85 | user.exchanges = new String[exchangesArray.length()]; 86 | for (int j = 0; j < exchangesArray.length(); j++){ 87 | user.exchanges[j] = exchangesArray.getString(j); 88 | } 89 | 90 | JSONArray orderTypeArray = response.getJSONArray("order_types"); 91 | user.orderTypes = new String[orderTypeArray.length()]; 92 | for(int k = 0; k < orderTypeArray.length(); k++){ 93 | user.orderTypes[k] = orderTypeArray.getString(k); 94 | } 95 | 96 | return user; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/models/package-info.java: -------------------------------------------------------------------------------- 1 | /**All the models that Kite Connect uses are here.*/ 2 | package com.zerodhatech.models; -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/ticker/KiteTicker.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.ticker; 2 | 3 | /** 4 | * Created by H1ccup on 10/09/16. 5 | */ 6 | 7 | import com.google.gson.*; 8 | import com.neovisionaries.ws.client.*; 9 | import com.zerodhatech.kiteconnect.Routes; 10 | import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; 11 | import com.zerodhatech.models.Depth; 12 | import com.zerodhatech.models.Order; 13 | import com.zerodhatech.models.Tick; 14 | import org.json.JSONArray; 15 | import org.json.JSONException; 16 | import org.json.JSONObject; 17 | 18 | import java.io.IOException; 19 | import java.lang.reflect.Type; 20 | import java.nio.ByteBuffer; 21 | import java.nio.ByteOrder; 22 | import java.text.ParseException; 23 | import java.text.SimpleDateFormat; 24 | import java.util.*; 25 | 26 | /** 27 | * Ticker provider sends tokens to com.zerodhatech.com.zerodhatech.ticker server and get ticks from com.zerodhatech.com.zerodhatech.ticker server. Ticker server sends data in bytes. This Class 28 | * gets ticks and converts into readable format which includes our own business logic. 29 | */ 30 | public class KiteTicker { 31 | 32 | private String wsuri ; 33 | private OnTicks onTickerArrivalListener; 34 | private OnConnect onConnectedListener; 35 | private OnDisconnect onDisconnectedListener; 36 | private OnError onErrorListener; 37 | private WebSocket ws; 38 | private OnOrderUpdate orderUpdateListener; 39 | 40 | public final int NseCM = 1, 41 | NseFO = 2, 42 | NseCD = 3, 43 | BseCM = 4, 44 | BseFO = 5, 45 | BseCD = 6, 46 | McxFO = 7, 47 | McxSX = 8, 48 | Indices = 9; 49 | 50 | private final String mSubscribe = "subscribe", 51 | mUnSubscribe = "unsubscribe", 52 | mSetMode = "mode"; 53 | 54 | public static String modeFull = "full", // Full quote inludes Quote items, market depth, OI, day high OI, day low OI, last traded time, tick timestamp. 55 | modeQuote = "quote", // Quote includes last traded price, last traded quantity, average traded price, volume, total bid(buy quantity), total ask(sell quantity), open, high, low, close. 56 | modeLTP = "ltp"; // Only LTP. 57 | 58 | private long lastPongAt = 0; 59 | private Set subscribedTokens = new HashSet<>(); 60 | private int maxRetries = 10; 61 | private int count = 0; 62 | private Timer timer = null; 63 | private boolean tryReconnection = false; 64 | private final int pingInterval = 2500; 65 | private final int pongCheckInterval = 2500; 66 | private int nextReconnectInterval = 0; 67 | private int maxRetryInterval = 30000; 68 | private Map modeMap; 69 | private Timer canReconnectTimer = null; 70 | /** Used to reconnect after the specified delay.*/ 71 | private boolean canReconnect = true; 72 | 73 | /** Initialize Kite Ticker. 74 | * @param accessToken is the token received after successful login process. 75 | * @param apiKey is the api key of the app which is received after creating an app on developers console.*/ 76 | public KiteTicker(String accessToken, String apiKey) { 77 | 78 | if (wsuri == null) { 79 | createUrl(accessToken, apiKey); 80 | } 81 | 82 | try { 83 | ws = new WebSocketFactory().createSocket(wsuri); 84 | } catch (IOException e) { 85 | if(onErrorListener != null) { 86 | onErrorListener.onError(e); 87 | } 88 | return; 89 | } 90 | ws.addListener(getWebsocketAdapter()); 91 | modeMap = new HashMap<>(); 92 | } 93 | 94 | /** Returns task which performs check every second for reconnection. 95 | * @return TimerTask returns timer task which will be invoked after user defined interval and tries reconnect. */ 96 | private TimerTask getTask(){ 97 | TimerTask checkForRestartTask = new TimerTask() { 98 | @Override 99 | public void run() { 100 | if (lastPongAt == 0) return; 101 | 102 | Date currentDate = new Date(); 103 | long timeInterval = (currentDate.getTime() - lastPongAt); 104 | if (timeInterval >= 2 * pingInterval) { 105 | doReconnect(); 106 | } 107 | } 108 | }; 109 | return checkForRestartTask; 110 | } 111 | 112 | /** Performs reconnection after a particular interval if count is less than maximum retries.*/ 113 | public void doReconnect() { 114 | if(!tryReconnection) return; 115 | 116 | if(nextReconnectInterval == 0){ 117 | nextReconnectInterval = (int)(2000 * Math.pow(2, count)); 118 | } else { 119 | nextReconnectInterval = (int)(nextReconnectInterval * Math.pow(2, count)); 120 | } 121 | 122 | if(nextReconnectInterval > maxRetryInterval){ 123 | nextReconnectInterval = maxRetryInterval; 124 | } 125 | if(count <= maxRetries) { 126 | if(canReconnect) { 127 | count++; 128 | reconnect(new ArrayList<>(subscribedTokens)); 129 | canReconnect = false; 130 | canReconnectTimer = new Timer(); 131 | canReconnectTimer.schedule(new TimerTask() { 132 | @Override 133 | public void run() { 134 | canReconnect = true; 135 | } 136 | }, nextReconnectInterval); 137 | } 138 | }else if(count > maxRetries) { 139 | // if number of tries exceeds maximum number of retries then stop timer. 140 | if(timer != null) { 141 | timer.cancel(); 142 | timer = null; 143 | } 144 | } 145 | } 146 | 147 | /** Set tryReconnection, to instruct KiteTicker that it has to reconnect, if com.zerodhatech.ticker is disconnected. 148 | * @param retry will denote whether reconnection should be tried or not. */ 149 | public void setTryReconnection(boolean retry){ 150 | tryReconnection = retry; 151 | } 152 | 153 | /** Set error listener. 154 | * @param listener of type OnError which listens to all the type of errors that may arise in Kite Ticker class. */ 155 | public void setOnErrorListener(OnError listener){ 156 | onErrorListener = listener; 157 | } 158 | 159 | /** Set max number of retries for reconnection, for infinite retries set value as -1. 160 | * @param maxRetries denotes maximum number of retries that the com.zerodhatech.ticker can perform. 161 | * @throws KiteException when maximum retries is less than 0. 162 | * */ 163 | public void setMaximumRetries(int maxRetries) throws KiteException { 164 | if(maxRetries > 0) { 165 | this.maxRetries = maxRetries; 166 | }else { 167 | throw new KiteException("Maximum retries can't be less than 0"); 168 | } 169 | } 170 | 171 | /* Set a maximum interval for every retry.*/ 172 | public void setMaximumRetryInterval(int interval) throws KiteException { 173 | if(interval >= 5) { 174 | //convert to milliseconds 175 | maxRetryInterval = interval * 1000; 176 | } else { 177 | throw new KiteException("Maximum retry interval can't be less than 0"); 178 | } 179 | } 180 | 181 | /** Creates url for websocket connection.*/ 182 | private void createUrl(String accessToken, String apiKey){ 183 | wsuri = new Routes().getWsuri().replace(":access_token", accessToken).replace(":api_key", apiKey); 184 | } 185 | /** Set listener for listening to ticks. 186 | * @param onTickerArrivalListener is listener which listens for each tick.*/ 187 | public void setOnTickerArrivalListener(OnTicks onTickerArrivalListener){ 188 | this.onTickerArrivalListener = onTickerArrivalListener; 189 | } 190 | 191 | /** Set listener for on connection established. 192 | * @param listener is used to listen to onConnected event. */ 193 | public void setOnConnectedListener(OnConnect listener){ 194 | onConnectedListener = listener; 195 | } 196 | 197 | /** Set listener for on connection is disconnected. 198 | * @param listener is used to listen to onDisconnected event.*/ 199 | public void setOnDisconnectedListener(OnDisconnect listener){ 200 | onDisconnectedListener = listener; 201 | } 202 | 203 | /** Set listener for order updates. 204 | * @param listener is used to listen to order updates.*/ 205 | public void setOnOrderUpdateListener(OnOrderUpdate listener) { 206 | orderUpdateListener = listener; 207 | } 208 | 209 | /** Establishes a web socket connection. 210 | * */ 211 | public void connect() { 212 | try { 213 | ws.setPingInterval(pingInterval); 214 | ws.connect(); 215 | } catch (WebSocketException e){ 216 | e.printStackTrace(); 217 | if(onErrorListener != null) { 218 | onErrorListener.onError(e); 219 | } 220 | if(tryReconnection) { 221 | if (timer == null) { 222 | // this is to handle reconnection first time 223 | if (lastPongAt == 0) { 224 | lastPongAt = 1; 225 | } 226 | timer = new Timer(); 227 | timer.scheduleAtFixedRate(getTask(), 0, pongCheckInterval); 228 | } 229 | } 230 | } 231 | } 232 | 233 | /** Returns a WebSocketAdapter to listen to ticker related events.*/ 234 | public WebSocketAdapter getWebsocketAdapter(){ 235 | return new WebSocketAdapter() { 236 | 237 | @Override 238 | public void onConnected(WebSocket websocket, Map> headers) { 239 | count = 0; 240 | nextReconnectInterval = 0; 241 | 242 | if (onConnectedListener != null) { 243 | onConnectedListener.onConnected(); 244 | } 245 | 246 | if (tryReconnection) { 247 | if (timer != null) { 248 | timer.cancel(); 249 | } 250 | timer = new Timer(); 251 | timer.scheduleAtFixedRate(getTask(), 0, pongCheckInterval); 252 | 253 | } 254 | } 255 | 256 | @Override 257 | public void onTextMessage(WebSocket websocket, String message) { 258 | parseTextMessage(message); 259 | } 260 | 261 | @Override 262 | public void onBinaryMessage(WebSocket websocket, byte[] binary) { 263 | try { 264 | super.onBinaryMessage(websocket, binary); 265 | } catch (Exception e) { 266 | e.printStackTrace(); 267 | if(onErrorListener != null) { 268 | onErrorListener.onError(e); 269 | } 270 | } 271 | 272 | ArrayList tickerData = parseBinary(binary); 273 | 274 | if (onTickerArrivalListener != null) { 275 | onTickerArrivalListener.onTicks(tickerData); 276 | } 277 | } 278 | 279 | @Override 280 | public void onPongFrame(WebSocket websocket, WebSocketFrame frame) { 281 | try { 282 | super.onPongFrame(websocket, frame); 283 | Date date = new Date(); 284 | lastPongAt = date.getTime(); 285 | } catch (Exception e) { 286 | e.printStackTrace(); 287 | if(onErrorListener != null) { 288 | onErrorListener.onError(e); 289 | } 290 | } 291 | } 292 | 293 | /** 294 | * On disconnection, return statement ensures that the thread ends. 295 | * 296 | * @param websocket 297 | * @param serverCloseFrame 298 | * @param clientCloseFrame 299 | * @param closedByServer 300 | * @throws Exception 301 | */ 302 | @Override 303 | public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) { 304 | if (onDisconnectedListener != null) { 305 | onDisconnectedListener.onDisconnected(); 306 | } 307 | return; 308 | } 309 | 310 | @Override 311 | public void onError(WebSocket websocket, WebSocketException cause) { 312 | try { 313 | super.onError(websocket, cause); 314 | } catch (Exception e) { 315 | e.printStackTrace(); 316 | if(onErrorListener != null) { 317 | onErrorListener.onError(e); 318 | } 319 | } 320 | } 321 | 322 | }; 323 | } 324 | 325 | /** Disconnects websocket connection.*/ 326 | public void disconnect(){ 327 | if(timer != null){ 328 | timer.cancel(); 329 | } 330 | if (ws != null && ws.isOpen()) { 331 | ws.disconnect(); 332 | subscribedTokens = new HashSet<>(); 333 | modeMap.clear(); 334 | } 335 | } 336 | 337 | /** Disconnects websocket connection only for internal use*/ 338 | private void nonUserDisconnect(){ 339 | if(ws != null) { 340 | ws.disconnect(); 341 | } 342 | } 343 | 344 | /** Returns true if websocket connection is open. 345 | * @return boolean*/ 346 | public boolean isConnectionOpen(){ 347 | if(ws != null) { 348 | if (ws.isOpen()){ 349 | return true; 350 | } 351 | } 352 | return false; 353 | } 354 | 355 | /** 356 | * Setting different modes for an arraylist of tokens. 357 | * @param tokens an arraylist of tokens 358 | * @param mode the mode that needs to be set. Scroll up to see different 359 | * kind of modes 360 | */ 361 | public void setMode(ArrayList tokens, String mode){ 362 | JSONObject jobj = new JSONObject(); 363 | try { 364 | // int a[] = {256265, 408065, 779521, 738561, 177665, 25601}; 365 | JSONArray list = new JSONArray(); 366 | JSONArray listMain = new JSONArray(); 367 | listMain.put(0, mode); 368 | for(int i=0; i< tokens.size(); i++){ 369 | list.put(i, tokens.get(i)); 370 | } 371 | listMain.put(1, list); 372 | jobj.put("a", mSetMode); 373 | jobj.put("v", listMain); 374 | for(int i = 0; i < tokens.size(); i++){ 375 | modeMap.put(tokens.get(i), mode); 376 | } 377 | } catch (JSONException e) { 378 | e.printStackTrace(); 379 | } 380 | 381 | if(ws != null) { 382 | ws.sendText(jobj.toString()); 383 | } 384 | } 385 | 386 | /** Subscribes for list of tokens. 387 | * @param tokens is list of tokens to be subscribed for. 388 | * */ 389 | public void subscribe(ArrayList tokens) { 390 | if(ws != null) { 391 | if (ws.isOpen()) { 392 | createTickerJsonObject(tokens, mSubscribe); 393 | ws.sendText(createTickerJsonObject(tokens, mSubscribe).toString()); 394 | subscribedTokens.addAll(tokens); 395 | for(int i = 0; i < tokens.size(); i++){ 396 | modeMap.put(tokens.get(i), modeQuote); 397 | } 398 | }else { 399 | if(onErrorListener != null) { 400 | onErrorListener.onError(new KiteException("ticker is not connected", 504)); 401 | } 402 | } 403 | }else { 404 | if(onErrorListener != null) { 405 | onErrorListener.onError(new KiteException("ticker is null not connected", 504)); 406 | } 407 | } 408 | } 409 | 410 | /** Create a JSONObject to send message to server. */ 411 | private JSONObject createTickerJsonObject(ArrayList tokens, String action) { 412 | JSONObject jobj = new JSONObject(); 413 | try { 414 | JSONArray list = new JSONArray(); 415 | for (int i = 0; i < tokens.size(); i++) { 416 | list.put(i, tokens.get(i)); 417 | } 418 | jobj.put("v", list); 419 | jobj.put("a", action); 420 | } 421 | catch (JSONException e){ 422 | } 423 | 424 | return jobj; 425 | } 426 | 427 | /** Unsubscribes ticks for list of tokens. 428 | * @param tokens is the list of tokens that needs to be unsubscribed. */ 429 | public void unsubscribe(ArrayList tokens){ 430 | if(ws != null) { 431 | if (ws.isOpen()) { 432 | ws.sendText(createTickerJsonObject(tokens, mUnSubscribe).toString()); 433 | subscribedTokens.removeAll(tokens); 434 | for(int i = 0; i < tokens.size(); i++){ 435 | modeMap.remove(tokens.get(i)); 436 | } 437 | } 438 | } 439 | } 440 | 441 | /* 442 | * This method parses binary data got from kite server to get ticks for each token subscribed. 443 | * we have to keep a main Array List which is global and keep deleting element in the list and add new data element in that place and call notify data set changed. 444 | * @return List of parsed ticks. 445 | */ 446 | private ArrayList parseBinary(byte [] binaryPackets) { 447 | ArrayList ticks = new ArrayList(); 448 | ArrayList packets = splitPackets(binaryPackets); 449 | for (int i = 0; i < packets.size(); i++) { 450 | byte[] bin = packets.get(i); 451 | byte[] t = Arrays.copyOfRange(bin, 0, 4); 452 | int x = ByteBuffer.wrap(t).getInt(); 453 | 454 | //int token = x >> 8; 455 | int segment = x & 0xff; 456 | 457 | int dec1 = (segment == NseCD) ? 10000000 : (segment == BseCD)? 10000 : 100; 458 | 459 | if(bin.length == 8) { 460 | Tick tick = getLtpQuote(bin, x, dec1, segment != Indices); 461 | ticks.add(tick); 462 | }else if(bin.length == 28 || bin.length == 32) { 463 | Tick tick = getIndeciesData(bin, x, segment != Indices); 464 | ticks.add(tick); 465 | }else if(bin.length == 44) { 466 | Tick tick = getQuoteData(bin, x, dec1, segment != Indices); 467 | ticks.add(tick); 468 | } else if(bin.length == 184) { 469 | Tick tick = getQuoteData(bin, x, dec1, segment != Indices); 470 | tick.setMode(modeFull); 471 | ticks.add(getFullData(bin, dec1, tick)); 472 | } 473 | } 474 | return ticks; 475 | } 476 | 477 | /** Parses NSE indices data. 478 | * @return Tick is the parsed index data. */ 479 | private Tick getIndeciesData(byte[] bin, int x, boolean tradable){ 480 | int dec = 100; 481 | Tick tick = new Tick(); 482 | tick.setMode(modeQuote); 483 | tick.setTradable(tradable); 484 | tick.setInstrumentToken(x); 485 | double lastTradedPrice = convertToDouble(getBytes(bin, 4, 8)) / dec; 486 | tick.setLastTradedPrice(lastTradedPrice); 487 | tick.setHighPrice(convertToDouble(getBytes(bin, 8, 12)) / dec); 488 | tick.setLowPrice(convertToDouble(getBytes(bin, 12, 16)) / dec); 489 | tick.setOpenPrice(convertToDouble(getBytes(bin, 16, 20)) / dec); 490 | double closePrice = convertToDouble(getBytes(bin, 20, 24)) / dec; 491 | tick.setClosePrice(closePrice); 492 | // here exchange is sending absolute value, hence we change that to %change 493 | //tick.setNetPriceChangeFromClosingPrice(convertToDouble(getBytes(bin, 24, 28)) / dec); 494 | setChangeForTick(tick, lastTradedPrice, closePrice); 495 | if(bin.length > 28) { 496 | tick.setMode(modeFull); 497 | long tickTimeStamp = convertToLong(getBytes(bin, 28, 32)) * 1000; 498 | if(isValidDate(tickTimeStamp)) { 499 | tick.setTickTimestamp(new Date(tickTimeStamp)); 500 | } else { 501 | tick.setTickTimestamp(null); 502 | } 503 | } 504 | return tick; 505 | } 506 | 507 | /** Parses LTP data.*/ 508 | private Tick getLtpQuote(byte[] bin, int x, int dec1, boolean tradable){ 509 | Tick tick1 = new Tick(); 510 | tick1.setMode(modeLTP); 511 | tick1.setTradable(tradable); 512 | tick1.setInstrumentToken(x); 513 | tick1.setLastTradedPrice(convertToDouble(getBytes(bin, 4, 8)) / dec1); 514 | return tick1; 515 | } 516 | 517 | /** Get quote data (last traded price, last traded quantity, average traded price, volume, total bid(buy quantity), total ask(sell quantity), open, high, low, close.) */ 518 | private Tick getQuoteData(byte[] bin, int x, int dec1, boolean tradable){ 519 | Tick tick2 = new Tick(); 520 | tick2.setMode(modeQuote); 521 | tick2.setInstrumentToken(x); 522 | tick2.setTradable(tradable); 523 | double lastTradedPrice = convertToDouble(getBytes(bin, 4, 8)) / dec1; 524 | tick2.setLastTradedPrice(lastTradedPrice); 525 | tick2.setLastTradedQuantity(convertToDouble(getBytes(bin, 8, 12))); 526 | tick2.setAverageTradePrice(convertToDouble(getBytes(bin, 12, 16)) / dec1); 527 | tick2.setVolumeTradedToday(convertToLong(getBytes(bin, 16, 20))); 528 | tick2.setTotalBuyQuantity(convertToDouble(getBytes(bin, 20, 24))); 529 | tick2.setTotalSellQuantity(convertToDouble(getBytes(bin, 24, 28))); 530 | tick2.setOpenPrice(convertToDouble(getBytes(bin, 28, 32)) / dec1); 531 | tick2.setHighPrice(convertToDouble(getBytes(bin, 32, 36)) / dec1); 532 | tick2.setLowPrice(convertToDouble(getBytes(bin, 36, 40)) / dec1); 533 | double closePrice = convertToDouble(getBytes(bin, 40, 44)) / dec1; 534 | tick2.setClosePrice(closePrice); 535 | setChangeForTick(tick2, lastTradedPrice, closePrice); 536 | return tick2; 537 | } 538 | 539 | private void setChangeForTick(Tick tick, double lastTradedPrice, double closePrice){ 540 | if (closePrice != 0) 541 | tick.setNetPriceChangeFromClosingPrice((lastTradedPrice - closePrice) * 100 / closePrice); 542 | else 543 | tick.setNetPriceChangeFromClosingPrice(0); 544 | 545 | } 546 | 547 | /** Parses full mode data.*/ 548 | private Tick getFullData(byte[] bin, int dec, Tick tick){ 549 | long lastTradedtime = convertToLong(getBytes(bin, 44, 48)) * 1000; 550 | if(isValidDate(lastTradedtime)) { 551 | tick.setLastTradedTime(new Date(lastTradedtime)); 552 | }else { 553 | tick.setLastTradedTime(null); 554 | } 555 | tick.setOi(convertToDouble(getBytes(bin, 48, 52))); 556 | tick.setOpenInterestDayHigh(convertToDouble(getBytes(bin, 52, 56))); 557 | tick.setOpenInterestDayLow(convertToDouble(getBytes(bin, 56, 60))); 558 | long tickTimeStamp = convertToLong(getBytes(bin, 60, 64)) * 1000; 559 | if(isValidDate(tickTimeStamp)) { 560 | tick.setTickTimestamp(new Date(tickTimeStamp)); 561 | } else { 562 | tick.setTickTimestamp(null); 563 | } 564 | tick.setMarketDepth(getDepthData(bin, dec, 64, 184)); 565 | return tick; 566 | } 567 | 568 | /** Reads all bytes and returns map of depth values for offer and bid*/ 569 | private Map> getDepthData(byte[] bin, int dec, int start, int end){ 570 | byte[] depthBytes = getBytes(bin, start, end); 571 | int s = 0; 572 | ArrayList buy = new ArrayList(); 573 | ArrayList sell = new ArrayList(); 574 | for (int k = 0; k < 10; k++) { 575 | s = k * 12; 576 | Depth depth = new Depth(); 577 | depth.setQuantity((int)convertToDouble(getBytes(depthBytes, s, s + 4))); 578 | depth.setPrice(convertToDouble(getBytes(depthBytes, s + 4, s + 8))/dec); 579 | depth.setOrders((int)convertToDouble(getBytes(depthBytes, s + 8, s + 10))); 580 | 581 | if (k < 5) { 582 | buy.add(depth); 583 | } else { 584 | sell.add(depth); 585 | } 586 | } 587 | Map> depthMap = new HashMap>(); 588 | depthMap.put("buy", buy); 589 | depthMap.put("sell", sell); 590 | return depthMap; 591 | } 592 | 593 | /** Each byte stream contains many packets. This method reads first two bits and calculates number of packets in the byte stream and split it. */ 594 | private ArrayList splitPackets(byte[] bin){ 595 | 596 | ArrayList packets = new ArrayList(); 597 | int noOfPackets = getLengthFromByteArray(getBytes(bin, 0, 2)); //in.read(bin, 0, 2); 598 | int j = 2; 599 | 600 | for(int i = 0; i < noOfPackets; i++){ 601 | int sizeOfPacket = getLengthFromByteArray(getBytes(bin, j, j + 2));//in.read(bin, j, j+2); 602 | byte[] packet = Arrays.copyOfRange(bin, j + 2, j + 2 + sizeOfPacket); 603 | packets.add(packet); 604 | j = j + 2 + sizeOfPacket; 605 | } 606 | return packets; 607 | } 608 | 609 | /** Reads values of specified position in byte array. */ 610 | private byte[] getBytes(byte[] bin, int start, int end){ 611 | return Arrays.copyOfRange(bin, start, end); 612 | } 613 | 614 | /** Convert binary data to double datatype*/ 615 | private double convertToDouble(byte[] bin){ 616 | ByteBuffer bb = ByteBuffer.wrap(bin); 617 | bb.order(ByteOrder.BIG_ENDIAN); 618 | if(bin.length < 4) 619 | return bb.getShort(); 620 | else if(bin.length < 8) 621 | return bb.getInt(); 622 | else 623 | return bb.getDouble(); 624 | } 625 | 626 | /* Convert binary data to long datatype*/ 627 | private long convertToLong(byte[] bin){ 628 | ByteBuffer bb = ByteBuffer.wrap(bin); 629 | bb.order(ByteOrder.BIG_ENDIAN); 630 | return bb.getInt(); 631 | } 632 | 633 | /** Returns length of packet by reading byte array values. */ 634 | private int getLengthFromByteArray(byte[] bin){ 635 | ByteBuffer bb = ByteBuffer.wrap(bin); 636 | bb.order(ByteOrder.BIG_ENDIAN); 637 | return bb.getShort(); 638 | } 639 | 640 | /** Disconnects and reconnects com.zerodhatech.ticker. */ 641 | private void reconnect(final ArrayList tokens) { 642 | nonUserDisconnect(); 643 | try { 644 | ws = new WebSocketFactory().createSocket(wsuri); 645 | } catch (IOException e) { 646 | if(onErrorListener != null) { 647 | onErrorListener.onError(e); 648 | } 649 | return; 650 | } 651 | ws.addListener(getWebsocketAdapter()); 652 | connect(); 653 | final OnConnect onUsersConnectedListener = this.onConnectedListener; 654 | setOnConnectedListener(new OnConnect() { 655 | @Override 656 | public void onConnected() { 657 | if(subscribedTokens.size() > 0) { 658 | //take a backup of mode map as it will be overriden to modeQuote after subscribe 659 | Map backupModeMap = new HashMap<>(); 660 | backupModeMap.putAll(modeMap); 661 | ArrayList tokens = new ArrayList<>(); 662 | tokens.addAll(subscribedTokens); 663 | subscribe(tokens); 664 | 665 | Map> modes = new HashMap<>(); 666 | for (Map.Entry item: backupModeMap.entrySet()){ 667 | if(!modes.containsKey(item.getValue())){ 668 | modes.put(item.getValue(), new ArrayList()); 669 | } 670 | modes.get(item.getValue()).add(item.getKey()); 671 | } 672 | for(Map.Entry> modeArrayItem: modes.entrySet()){ 673 | setMode(modeArrayItem.getValue(), modeArrayItem.getKey()); 674 | } 675 | } 676 | lastPongAt = 0; 677 | count = 0; 678 | nextReconnectInterval = 0; 679 | onConnectedListener = onUsersConnectedListener; 680 | } 681 | }); 682 | } 683 | 684 | private boolean isValidDate(long date) { 685 | if(date <= 0){ 686 | return false; 687 | } 688 | Calendar calendar = Calendar.getInstance(); 689 | calendar.setLenient(false); 690 | calendar.setTimeInMillis(date); 691 | try { 692 | calendar.getTime(); 693 | return true; 694 | } catch (Exception e) { 695 | return false; 696 | } 697 | } 698 | 699 | /** Parses incoming text message.*/ 700 | private void parseTextMessage(String message) { 701 | JSONObject data; 702 | try { 703 | data = new JSONObject(message); 704 | if(!data.has("type")){ 705 | return; 706 | } 707 | 708 | String type = data.getString("type"); 709 | if(type.equals("order")) { 710 | if(orderUpdateListener != null) { 711 | orderUpdateListener.onOrderUpdate(getOrder(data)); 712 | } 713 | } 714 | 715 | if(type.equals("error")) { 716 | if(onErrorListener != null) { 717 | onErrorListener.onError(data.getString("data")); 718 | } 719 | } 720 | 721 | }catch (JSONException e) { 722 | e.printStackTrace(); 723 | } 724 | } 725 | 726 | public Order getOrder(JSONObject data) { 727 | GsonBuilder gsonBuilder = new GsonBuilder(); 728 | gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() { 729 | 730 | @Override 731 | public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { 732 | try { 733 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 734 | return format.parse(jsonElement.getAsString()); 735 | } catch (ParseException e) { 736 | return null; 737 | } 738 | } 739 | }); 740 | Gson gson = gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss").create(); 741 | return gson.fromJson(String.valueOf(data.get("data")), Order.class); 742 | } 743 | 744 | } -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/ticker/OnConnect.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.ticker; 2 | 3 | /** 4 | * Callback to listen to com.zerodhatech.ticker websocket connected event. 5 | */ 6 | public interface OnConnect { 7 | void onConnected(); 8 | } 9 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/ticker/OnDisconnect.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.ticker; 2 | 3 | /** 4 | * Callback to listen to com.zerodhatech.ticker websocket disconnected event. 5 | */ 6 | public interface OnDisconnect { 7 | void onDisconnected(); 8 | } 9 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/ticker/OnError.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.ticker; 2 | 3 | import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; 4 | 5 | /** 6 | * Created by sujith on 11/21/17. 7 | */ 8 | public interface OnError { 9 | 10 | public void onError(Exception exception); 11 | 12 | public void onError(KiteException kiteException); 13 | 14 | void onError(String error); 15 | } 16 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/ticker/OnOrderUpdate.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.ticker; 2 | 3 | import com.zerodhatech.models.Order; 4 | 5 | /** 6 | * Created by sujith on 12/26/17. 7 | */ 8 | public interface OnOrderUpdate { 9 | void onOrderUpdate(Order order); 10 | } 11 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/ticker/OnTicks.java: -------------------------------------------------------------------------------- 1 | package com.zerodhatech.ticker; 2 | 3 | import com.zerodhatech.models.Tick; 4 | 5 | import java.util.ArrayList; 6 | 7 | /** 8 | * Callback to listen to com.zerodhatech.ticker websocket on tick arrival event. 9 | */ 10 | 11 | /** OnTicks interface is called once ticks arrive.*/ 12 | public interface OnTicks { 13 | void onTicks(ArrayList ticks); 14 | } 15 | -------------------------------------------------------------------------------- /kiteconnect/src/com/zerodhatech/ticker/package-info.java: -------------------------------------------------------------------------------- 1 | /**Websocket connection related components for getting live quotes.*/ 2 | package com.zerodhatech.ticker; -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.zerodhatech.kiteconnect 8 | kiteconnect 9 | 3.5.0 10 | jar 11 | 12 | 13 | 14 | ossrh 15 | https://oss.sonatype.org/content/repositories/snapshots 16 | 17 | 18 | ossrh 19 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 20 | 21 | 22 | 23 | com.zerodhatech.kiteconnect:kiteconnect 24 | Kite Connect is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. 25 | https://github.com/rainmattertech/kiteconnectjava 26 | 27 | 28 | 29 | MIT License 30 | http://www.opensource.org/licenses/mit-license.php 31 | 32 | 33 | 34 | 35 | 36 | Sujith K S 37 | sujith@zerodha.com 38 | Rainmatter 39 | http://rainmatter.com/ 40 | 41 | 42 | 43 | 44 | scm:git:git:github.com/zerodhatech/kiteconnectjava.git 45 | scm:git:ssh:github.com/zerodhatech/kiteconnectjava.git 46 | https://github.com/zerodhatech/javakiteconnect/tree/kite3 47 | 48 | 49 | 50 | 51 | 52 | org.apache.maven.plugins 53 | maven-compiler-plugin 54 | 3.1 55 | 56 | 1.8 57 | 1.8 58 | 59 | 60 | 61 | org.apache.maven.plugins 62 | maven-source-plugin 63 | 2.2.1 64 | 65 | 66 | attach-sources 67 | 68 | jar-no-fork 69 | 70 | 71 | 72 | 73 | 74 | org.apache.maven.plugins 75 | maven-gpg-plugin 76 | 1.6 77 | 78 | 79 | sign-artifacts 80 | verify 81 | 82 | sign 83 | 84 | 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-javadoc-plugin 90 | 2.9.1 91 | 92 | 93 | attach-javadocs 94 | 95 | jar 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | commons-codec 106 | commons-codec 107 | 1.11 108 | 109 | 110 | net.sf.supercsv 111 | super-csv 112 | 2.4.0 113 | 114 | 115 | com.neovisionaries 116 | nv-websocket-client 117 | 2.3 118 | 119 | 120 | org.json 121 | json 122 | 20230227 123 | 124 | 125 | com.squareup.okhttp3 126 | okhttp 127 | 4.4.0 128 | 129 | 130 | com.squareup.okio 131 | okio 132 | 3.4.0 133 | 134 | 135 | com.squareup.okio 136 | okio-jvm 137 | 3.4.0 138 | 139 | 140 | com.squareup.okhttp3 141 | logging-interceptor 142 | 4.4.0 143 | 144 | 145 | org.jetbrains.kotlin 146 | kotlin-stdlib 147 | 1.6.21 148 | 149 | 150 | com.google.code.gson 151 | gson 152 | 2.8.9 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /sample/src/Examples.java: -------------------------------------------------------------------------------- 1 | import com.neovisionaries.ws.client.WebSocketException; 2 | import com.zerodhatech.kiteconnect.KiteConnect; 3 | import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; 4 | import com.zerodhatech.kiteconnect.utils.Constants; 5 | import com.zerodhatech.models.*; 6 | import com.zerodhatech.ticker.*; 7 | import org.json.JSONObject; 8 | import com.zerodhatech.models.Margin; 9 | 10 | import java.io.IOException; 11 | import java.text.DecimalFormat; 12 | import java.text.NumberFormat; 13 | import java.text.ParseException; 14 | import java.text.SimpleDateFormat; 15 | import java.util.*; 16 | 17 | /** 18 | * Created by sujith on 15/10/16. 19 | */ 20 | public class Examples { 21 | 22 | 23 | public void getProfile(KiteConnect kiteConnect) throws IOException, KiteException { 24 | Profile profile = kiteConnect.getProfile(); 25 | System.out.println(profile.userName); 26 | } 27 | 28 | /**Gets Margin.*/ 29 | public void getMargins(KiteConnect kiteConnect) throws KiteException, IOException { 30 | // Get margins returns margin model, you can pass equity or commodity as arguments to get margins of respective segments. 31 | //Margins margins = kiteConnect.getMargins("equity"); 32 | Margin margins = kiteConnect.getMargins("equity"); 33 | System.out.println(margins.available.cash); 34 | System.out.println(margins.utilised.debits); 35 | System.out.println(margins.utilised.m2mUnrealised); 36 | } 37 | 38 | public void getMarginCalculation(KiteConnect kiteConnect) throws IOException, KiteException { 39 | MarginCalculationParams param = new MarginCalculationParams(); 40 | param.exchange = "NSE"; 41 | param.tradingSymbol = "INFY"; 42 | param.orderType = "MARKET"; 43 | param.quantity = 1; 44 | param.product = "MIS"; 45 | param.variety = "regular"; 46 | param.transactionType = Constants.TRANSACTION_TYPE_BUY; 47 | List params = new ArrayList<>(); 48 | params.add(param); 49 | List data = kiteConnect.getMarginCalculation(params); 50 | System.out.println(data.get(0).total); 51 | System.out.println(data.get(0).leverage); 52 | } 53 | 54 | public void getCombinedMarginCalculation(KiteConnect kiteConnect) throws IOException, KiteException{ 55 | List params = new ArrayList<>(); 56 | 57 | MarginCalculationParams param = new MarginCalculationParams(); 58 | param.exchange = "NFO"; 59 | param.tradingSymbol = "NIFTY21MARFUT"; 60 | param.orderType = "LIMIT"; 61 | param.quantity = 75; 62 | param.product = "MIS"; 63 | param.variety = "regular"; 64 | param.transactionType = "BUY"; 65 | param.price = 141819; 66 | 67 | MarginCalculationParams param2 = new MarginCalculationParams(); 68 | param2.exchange = "NFO"; 69 | param2.tradingSymbol = "NIFTY21MAR15000PE"; 70 | param2.orderType = "LIMIT"; 71 | param2.quantity = 75; 72 | param2.product = "MIS"; 73 | param2.variety = "regular"; 74 | param.transactionType = "BUY"; 75 | param2.price = 300; 76 | 77 | params.add(param); 78 | params.add(param2); 79 | 80 | CombinedMarginData combinedMarginData = kiteConnect.getCombinedMarginCalculation(params, true, false); 81 | System.out.println(combinedMarginData.initialMargin.total); 82 | } 83 | 84 | /**Get virtual contract note.*/ 85 | public void getVirtualContractNote(KiteConnect kiteConnect) throws KiteException, IOException { 86 | List virtualContractNoteParams = new ArrayList(); 87 | ContractNoteParams contractNoteParams = new ContractNoteParams(); 88 | contractNoteParams.orderID = "230727202226518"; 89 | contractNoteParams.tradingSymbol = "ITC"; 90 | contractNoteParams.exchange = Constants.EXCHANGE_NSE; 91 | contractNoteParams.product = Constants.PRODUCT_CNC; 92 | contractNoteParams.orderType = Constants.ORDER_TYPE_MARKET; 93 | contractNoteParams.variety = Constants.VARIETY_REGULAR; 94 | contractNoteParams.transactionType = Constants.TRANSACTION_TYPE_SELL; 95 | contractNoteParams.quantity = 1; 96 | contractNoteParams.averagePrice = 470.05; 97 | virtualContractNoteParams.add(contractNoteParams); 98 | 99 | List data = kiteConnect.getVirtualContractNote(virtualContractNoteParams); 100 | System.out.println(data.size()); 101 | 102 | System.out.println(data.get(0).charges.total); 103 | } 104 | 105 | /**Place order.*/ 106 | public void placeOrder(KiteConnect kiteConnect) throws KiteException, IOException { 107 | /** Place order method requires a orderParams argument which contains, 108 | * tradingsymbol, exchange, transaction_type, order_type, quantity, product, price, trigger_price, disclosed_quantity, validity 109 | * squareoff_value, stoploss_value, trailing_stoploss 110 | * and variety (value can be regular, bo, co, amo) 111 | * place order will return order model which will have only orderId in the order model 112 | * 113 | * Following is an example param for LIMIT order, 114 | * if a call fails then KiteException will have error message in it 115 | * Success of this call implies only order has been placed successfully, not order execution. */ 116 | 117 | OrderParams orderParams = new OrderParams(); 118 | orderParams.quantity = 1; 119 | orderParams.orderType = Constants.ORDER_TYPE_LIMIT; 120 | orderParams.tradingsymbol = "ASHOKLEY"; 121 | orderParams.product = Constants.PRODUCT_CNC; 122 | orderParams.exchange = Constants.EXCHANGE_NSE; 123 | orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; 124 | orderParams.validity = Constants.VALIDITY_DAY; 125 | orderParams.price = 122.2; 126 | orderParams.triggerPrice = 0.0; 127 | orderParams.tag = "myTag"; //tag is optional and it cannot be more than 8 characters and only alphanumeric is allowed 128 | 129 | Order order = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR); 130 | System.out.println(order.orderId); 131 | } 132 | 133 | /** Place iceberg order.*/ 134 | public void placeIcebergOrder(KiteConnect kiteConnect) throws KiteException, IOException { 135 | /** Iceberg order:- following is example param for iceberg order with ttl validity. 136 | * Minimum number of legs is 2 and maximum number of legs is 10. 137 | * TTL validity is always sent as integer wherein number denotes number of minutes an order can be alive. 138 | */ 139 | OrderParams orderParams = new OrderParams(); 140 | orderParams.quantity = 10; 141 | orderParams.orderType = Constants.ORDER_TYPE_LIMIT; 142 | orderParams.price = 1440.0; 143 | orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; 144 | orderParams.tradingsymbol = "INFY"; 145 | orderParams.exchange = Constants.EXCHANGE_NSE; 146 | orderParams.validity = Constants.VALIDITY_TTL; 147 | orderParams.product = Constants.PRODUCT_MIS; 148 | orderParams.validityTTL = 10; 149 | orderParams.icebergLegs = 2; 150 | orderParams.icebergQuantity = 5; 151 | Order order10 = kiteConnect.placeOrder(orderParams, Constants.VARIETY_ICEBERG); 152 | System.out.println(order10.orderId); 153 | } 154 | 155 | /** Place cover order.*/ 156 | public void placeCoverOrder(KiteConnect kiteConnect) throws KiteException, IOException { 157 | /** Cover Order:- following is an example param for the cover order 158 | * key: quantity value: 1 159 | * key: price value: 0 160 | * key: transaction_type value: BUY 161 | * key: tradingsymbol value: HINDALCO 162 | * key: exchange value: NSE 163 | * key: validity value: DAY 164 | * key: trigger_price value: 157 165 | * key: order_type value: MARKET 166 | * key: variety value: co 167 | * key: product value: MIS 168 | */ 169 | OrderParams orderParams = new OrderParams(); 170 | orderParams.price = 0.0; 171 | orderParams.quantity = 1; 172 | orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; 173 | orderParams.orderType = Constants.ORDER_TYPE_MARKET; 174 | orderParams.tradingsymbol = "SOUTHBANK"; 175 | orderParams.exchange = Constants.EXCHANGE_NSE; 176 | orderParams.validity = Constants.VALIDITY_DAY; 177 | orderParams.triggerPrice = 30.5; 178 | orderParams.product = Constants.PRODUCT_MIS; 179 | 180 | Order order11 = kiteConnect.placeOrder(orderParams, Constants.VARIETY_CO); 181 | System.out.println(order11.orderId); 182 | } 183 | 184 | /** Place order with automatic slicing on*/ 185 | public void placeAutoSliceOrder(KiteConnect kiteConnect) throws KiteException, IOException { 186 | OrderParams orderParams = new OrderParams(); 187 | orderParams.price = 1.0; 188 | orderParams.quantity = 5925; 189 | orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; 190 | orderParams.orderType = Constants.ORDER_TYPE_LIMIT; 191 | orderParams.tradingsymbol = "NIFTY2543025800CE"; 192 | orderParams.exchange = Constants.EXCHANGE_NFO; 193 | orderParams.validity = Constants.VALIDITY_DAY; 194 | orderParams.product = Constants.PRODUCT_MIS; 195 | 196 | List orders = kiteConnect.placeAutoSliceOrder(orderParams, Constants.VARIETY_REGULAR); 197 | for (BulkOrderResponse order : orders) { 198 | if (order.orderId!=null) { 199 | System.out.println(order.orderId); 200 | } else { 201 | System.out.println(order.bulkOrderError.code); 202 | System.out.println(order.bulkOrderError.message); 203 | } 204 | } 205 | } 206 | 207 | public void placeMarketProtectionOrder(KiteConnect kiteConnect) throws KiteException, IOException{ 208 | OrderParams orderParams = new OrderParams(); 209 | orderParams.price = 0.0; 210 | orderParams.quantity = 1; 211 | orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; 212 | orderParams.orderType = Constants.ORDER_TYPE_MARKET; 213 | orderParams.tradingsymbol = "INFY"; 214 | orderParams.exchange = Constants.EXCHANGE_NSE; 215 | orderParams.validity = Constants.VALIDITY_DAY; 216 | orderParams.product = Constants.PRODUCT_MIS; 217 | // for custom market protection value send any value between 0 and 1 like 0.2 or 0.3 218 | // -1 indicates kite backend will auto apply the market protection value. 219 | orderParams.marketProtection = -1; 220 | 221 | Order order11 = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR); 222 | System.out.println(order11.orderId); 223 | } 224 | 225 | /** Get trigger range.*/ 226 | public void getTriggerRange(KiteConnect kiteConnect) throws KiteException, IOException { 227 | // You need to send transaction_type, exchange and tradingsymbol to get trigger range. 228 | String[] instruments = {"BSE:INFY", "NSE:APOLLOTYRE", "NSE:SBIN"}; 229 | Map triggerRangeMap = kiteConnect.getTriggerRange(instruments, Constants.TRANSACTION_TYPE_BUY); 230 | System.out.println(triggerRangeMap.get("NSE:SBIN").lower); 231 | System.out.println(triggerRangeMap.get("NSE:APOLLOTYRE").upper); 232 | System.out.println(triggerRangeMap.get("BSE:INFY").percentage); 233 | } 234 | 235 | /** Get ongoing auction instruments available for the day and it usually starts at 2 PM on a trading day.*/ 236 | public void getAuctionInstruments(KiteConnect kiteConnect) throws KiteException, IOException{ 237 | List auctions = kiteConnect.getAuctionInstruments(); 238 | for (int i =0; i< auctions.size(); i++){ 239 | System.out.println(auctions.get(i).tradingSymbol+" "+auctions.get(i).quantity); 240 | } 241 | } 242 | 243 | /** Place an auction order. Only sell is allowed.*/ 244 | public void placeAuctionOrder(KiteConnect kiteConnect) throws KiteException, IOException{ 245 | OrderParams orderParams = new OrderParams(); 246 | orderParams.price = 365.5; 247 | orderParams.quantity = 1; 248 | orderParams.transactionType = Constants.TRANSACTION_TYPE_SELL; 249 | orderParams.orderType = Constants.ORDER_TYPE_LIMIT; 250 | orderParams.tradingsymbol = "ITC"; 251 | orderParams.exchange = Constants.EXCHANGE_NSE; 252 | orderParams.validity = Constants.VALIDITY_DAY; 253 | orderParams.product = Constants.PRODUCT_CNC; 254 | orderParams.auctionNumber= "2559"; 255 | kiteConnect.placeOrder(orderParams, Constants.VARIETY_AUCTION); 256 | } 257 | 258 | /** Get orderbook.*/ 259 | public void getOrders(KiteConnect kiteConnect) throws KiteException, IOException { 260 | // Get orders returns order model which will have list of orders inside, which can be accessed as follows, 261 | List orders = kiteConnect.getOrders(); 262 | for(int i = 0; i< orders.size(); i++){ 263 | System.out.println(orders.get(i).tradingSymbol+" "+orders.get(i).orderId+" "+orders.get(i).parentOrderId+ 264 | " "+orders.get(i).orderType+" "+orders.get(i).averagePrice+" "+orders.get(i).exchangeTimestamp+" "+orders.get(i).exchangeUpdateTimestamp+" "+orders.get(i).guid); 265 | } 266 | // Read iceberg params 267 | /** Map meta = orders.get(0).meta; 268 | Map icebergObject = (Map) meta.get("iceberg"); 269 | System.out.println(icebergObject.keySet());*/ 270 | 271 | System.out.println("list of orders size is "+orders.size()); 272 | } 273 | 274 | /** Get order details*/ 275 | public void getOrder(KiteConnect kiteConnect) throws KiteException, IOException { 276 | List orders = kiteConnect.getOrderHistory("180111000561605"); 277 | for(int i = 0; i< orders.size(); i++){ 278 | System.out.println(orders.get(i).orderId+" "+orders.get(i).status); 279 | } 280 | System.out.println("list size is "+orders.size()); 281 | } 282 | 283 | /** Get tradebook*/ 284 | public void getTrades(KiteConnect kiteConnect) throws KiteException, IOException { 285 | // Returns tradebook. 286 | List trades = kiteConnect.getTrades(); 287 | for (int i=0; i < trades.size(); i++) { 288 | System.out.println(trades.get(i).tradingSymbol+" "+trades.size()); 289 | } 290 | System.out.println(trades.size()); 291 | } 292 | 293 | /** Get trades for an order.*/ 294 | public void getTradesWithOrderId(KiteConnect kiteConnect) throws KiteException, IOException { 295 | // Returns trades for the given order. 296 | List trades = kiteConnect.getOrderTrades("180111000561605"); 297 | System.out.println(trades.size()); 298 | } 299 | 300 | /** Modify order.*/ 301 | public void modifyOrder(KiteConnect kiteConnect) throws KiteException, IOException { 302 | // Order modify request will return order model which will contain only order_id. 303 | OrderParams orderParams = new OrderParams(); 304 | orderParams.quantity = 1; 305 | orderParams.orderType = Constants.ORDER_TYPE_LIMIT; 306 | orderParams.tradingsymbol = "ASHOKLEY"; 307 | orderParams.product = Constants.PRODUCT_CNC; 308 | orderParams.exchange = Constants.EXCHANGE_NSE; 309 | orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; 310 | orderParams.validity = Constants.VALIDITY_DAY; 311 | orderParams.price = 122.25; 312 | 313 | Order order21 = kiteConnect.modifyOrder("180116000984900", orderParams, Constants.VARIETY_REGULAR); 314 | System.out.println(order21.orderId); 315 | } 316 | 317 | /** Cancel an order*/ 318 | public void cancelOrder(KiteConnect kiteConnect) throws KiteException, IOException { 319 | // Order modify request will return order model which will contain only order_id. 320 | // Cancel order will return order model which will only have orderId. 321 | Order order2 = kiteConnect.cancelOrder("180116000727266", Constants.VARIETY_REGULAR); 322 | System.out.println(order2.orderId); 323 | } 324 | 325 | public void exitBracketOrder(KiteConnect kiteConnect) throws KiteException, IOException { 326 | Order order = kiteConnect.cancelOrder("180116000812153","180116000798058", Constants.VARIETY_BO); 327 | System.out.println(order.orderId); 328 | } 329 | 330 | /**Get all gtts. */ 331 | public void getGTTs(KiteConnect kiteConnect) throws KiteException, IOException { 332 | List gtts = kiteConnect.getGTTs(); 333 | System.out.println(gtts.get(0).createdAt); 334 | System.out.println(gtts.get(0).condition.exchange); 335 | System.out.println(gtts.get(0).orders.get(0).price); 336 | } 337 | 338 | /** Get a particular GTT. */ 339 | public void getGTT(KiteConnect kiteConnect) throws IOException, KiteException { 340 | GTT gtt = kiteConnect.getGTT(177574); 341 | System.out.println(gtt.condition.tradingSymbol); 342 | } 343 | 344 | /** Place a GTT (Good till trigger)*/ 345 | public void placeGTT(KiteConnect kiteConnect) throws IOException, KiteException { 346 | GTTParams gttParams = new GTTParams(); 347 | gttParams.triggerType = Constants.OCO; 348 | gttParams.exchange = "NSE"; 349 | gttParams.tradingsymbol = "SBIN"; 350 | gttParams.lastPrice = 302.95; 351 | 352 | List triggerPrices = new ArrayList<>(); 353 | triggerPrices.add(290d); 354 | triggerPrices.add(320d); 355 | gttParams.triggerPrices = triggerPrices; 356 | 357 | /** Only sell is allowed for OCO or two-leg orders. 358 | * Single leg orders can be buy or sell order. 359 | * Passing a last price is mandatory. 360 | * A stop-loss order must have trigger and price below last price and target order must have trigger and price above last price. 361 | * Only limit order type and CNC product type is allowed for now. 362 | * */ 363 | 364 | /** Stop-loss or lower trigger. */ 365 | GTTParams.GTTOrderParams order1Params = gttParams. new GTTOrderParams(); 366 | order1Params.orderType = Constants.ORDER_TYPE_LIMIT; 367 | order1Params.price = 290; 368 | order1Params.product = Constants.PRODUCT_CNC; 369 | order1Params.transactionType = Constants.TRANSACTION_TYPE_SELL; 370 | order1Params.quantity = 0; 371 | 372 | GTTParams.GTTOrderParams order2Params = gttParams. new GTTOrderParams(); 373 | order2Params.orderType = Constants.ORDER_TYPE_LIMIT; 374 | order2Params.price = 320; 375 | order2Params.product = Constants.PRODUCT_CNC; 376 | order2Params.transactionType = Constants.TRANSACTION_TYPE_SELL; 377 | order2Params.quantity = 1; 378 | 379 | /** Target or upper trigger. */ 380 | List ordersList = new ArrayList(); 381 | ordersList.add(order1Params); 382 | ordersList.add(order2Params); 383 | gttParams.orders = ordersList; 384 | 385 | GTT gtt = kiteConnect.placeGTT(gttParams); 386 | System.out.println(gtt.id); 387 | } 388 | 389 | /** Modify a GTT (Good till trigger)*/ 390 | public void modifyGTT(KiteConnect kiteConnect) throws IOException, KiteException { 391 | GTTParams gttParams = new GTTParams(); 392 | gttParams.triggerType = Constants.OCO; 393 | gttParams.exchange = "NSE"; 394 | gttParams.tradingsymbol = "SBIN"; 395 | gttParams.lastPrice = 302.95; 396 | 397 | List triggerPrices = new ArrayList<>(); 398 | triggerPrices.add(290d); 399 | triggerPrices.add(320d); 400 | gttParams.triggerPrices = triggerPrices; 401 | 402 | GTTParams.GTTOrderParams order1Params = gttParams. new GTTOrderParams(); 403 | order1Params.orderType = Constants.ORDER_TYPE_LIMIT; 404 | order1Params.price = 290; 405 | order1Params.product = Constants.PRODUCT_CNC; 406 | order1Params.transactionType = Constants.TRANSACTION_TYPE_SELL; 407 | order1Params.quantity = 1; 408 | 409 | GTTParams.GTTOrderParams order2Params = gttParams. new GTTOrderParams(); 410 | order2Params.orderType = Constants.ORDER_TYPE_LIMIT; 411 | order2Params.price = 320; 412 | order2Params.product = Constants.PRODUCT_CNC; 413 | order2Params.transactionType = Constants.TRANSACTION_TYPE_SELL; 414 | order2Params.quantity = 1; 415 | 416 | List ordersList = new ArrayList(); 417 | ordersList.add(order1Params); 418 | ordersList.add(order2Params); 419 | gttParams.orders = ordersList; 420 | 421 | GTT gtt = kiteConnect.modifyGTT(176036, gttParams); 422 | System.out.println(gtt.id); 423 | } 424 | 425 | /** Cancel a GTT.*/ 426 | public void cancelGTT(KiteConnect kiteConnect) throws IOException, KiteException { 427 | GTT gtt = kiteConnect.cancelGTT(175859); 428 | System.out.println(gtt.id); 429 | } 430 | 431 | /** Get all positions.*/ 432 | public void getPositions(KiteConnect kiteConnect) throws KiteException, IOException { 433 | // Get positions returns position model which contains list of positions. 434 | Map> position = kiteConnect.getPositions(); 435 | System.out.println(position.get("net").size()); 436 | System.out.println(position.get("day").size()); 437 | System.out.println(position.get("net").get(0).averagePrice); 438 | } 439 | 440 | /** Get holdings.*/ 441 | public void getHoldings(KiteConnect kiteConnect) throws KiteException, IOException { 442 | // Get holdings returns holdings model which contains list of holdings. 443 | List holdings = kiteConnect.getHoldings(); 444 | System.out.println(holdings.size()); 445 | System.out.println(holdings.get(0).tradingSymbol); 446 | System.out.println(holdings.get(0).dayChange); 447 | System.out.println(holdings.get(0).dayChangePercentage); 448 | } 449 | 450 | /** Converts position*/ 451 | public void converPosition(KiteConnect kiteConnect) throws KiteException, IOException { 452 | //Modify product can be used to change MIS to NRML(CNC) or NRML(CNC) to MIS. 453 | JSONObject jsonObject6 = kiteConnect.convertPosition("ASHOKLEY", Constants.EXCHANGE_NSE, Constants.TRANSACTION_TYPE_BUY, Constants.POSITION_DAY, Constants.PRODUCT_MIS, Constants.PRODUCT_CNC, 1); 454 | System.out.println(jsonObject6); 455 | } 456 | 457 | /** Get all instruments that can be traded using kite connect.*/ 458 | public void getAllInstruments(KiteConnect kiteConnect) throws KiteException, IOException { 459 | // Get all instruments list. This call is very expensive as it involves downloading of large data dump. 460 | // Hence, it is recommended that this call be made once and the results stored locally once every morning before market opening. 461 | List instruments = kiteConnect.getInstruments(); 462 | System.out.println(instruments.size()); 463 | } 464 | 465 | /** Get instruments for the desired exchange.*/ 466 | public void getInstrumentsForExchange(KiteConnect kiteConnect) throws KiteException, IOException { 467 | // Get instruments for an exchange. 468 | List nseInstruments = kiteConnect.getInstruments("CDS"); 469 | System.out.println(nseInstruments.size()); 470 | } 471 | 472 | /** Get quote for a scrip.*/ 473 | public void getQuote(KiteConnect kiteConnect) throws KiteException, IOException { 474 | // Get quotes returns quote for desired tradingsymbol. 475 | String[] instruments = {"256265","BSE:INFY", "NSE:APOLLOTYRE", "NSE:NIFTY 50", "24507906"}; 476 | Map quotes = kiteConnect.getQuote(instruments); 477 | System.out.println(quotes.get("NSE:APOLLOTYRE").instrumentToken+""); 478 | System.out.println(quotes.get("NSE:APOLLOTYRE").oi +""); 479 | System.out.println(quotes.get("NSE:APOLLOTYRE").depth.buy.get(4).getPrice()); 480 | System.out.println(quotes.get("NSE:APOLLOTYRE").timestamp); 481 | System.out.println(quotes.get("NSE:APOLLOTYRE").lowerCircuitLimit+""); 482 | System.out.println(quotes.get("NSE:APOLLOTYRE").upperCircuitLimit+""); 483 | System.out.println(quotes.get("24507906").oiDayHigh); 484 | System.out.println(quotes.get("24507906").oiDayLow); 485 | } 486 | 487 | /* Get ohlc and lastprice for multiple instruments at once. 488 | * Users can either pass exchange with tradingsymbol or instrument token only. For example {NSE:NIFTY 50, BSE:SENSEX} or {256265, 265}*/ 489 | public void getOHLC(KiteConnect kiteConnect) throws KiteException, IOException { 490 | String[] instruments = {"256265","BSE:INFY", "NSE:INFY", "NSE:NIFTY 50"}; 491 | System.out.println(kiteConnect.getOHLC(instruments).get("256265").lastPrice); 492 | System.out.println(kiteConnect.getOHLC(instruments).get("NSE:NIFTY 50").ohlc.open); 493 | } 494 | 495 | /** Get last price for multiple instruments at once. 496 | * USers can either pass exchange with tradingsymbol or instrument token only. For example {NSE:NIFTY 50, BSE:SENSEX} or {256265, 265}*/ 497 | public void getLTP(KiteConnect kiteConnect) throws KiteException, IOException { 498 | String[] instruments = {"256265","BSE:INFY", "NSE:INFY", "NSE:NIFTY 50"}; 499 | System.out.println(kiteConnect.getLTP(instruments).get("256265").lastPrice); 500 | } 501 | 502 | /** Get historical data for an instrument.*/ 503 | public void getHistoricalData(KiteConnect kiteConnect) throws KiteException, IOException { 504 | /** Get historical data dump, requires from and to date, intrument token, interval, continuous (for expired F&O contracts), oi (open interest) 505 | * returns historical data object which will have list of historical data inside the object.*/ 506 | SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 507 | Date from = new Date(); 508 | Date to = new Date(); 509 | try { 510 | from = formatter.parse("2019-09-20 09:15:00"); 511 | to = formatter.parse("2019-09-20 15:30:00"); 512 | }catch (ParseException e) { 513 | e.printStackTrace(); 514 | } 515 | HistoricalData historicalData = kiteConnect.getHistoricalData(from, to, "54872327", "15minute", false, true); 516 | System.out.println(historicalData.dataArrayList.size()); 517 | System.out.println(historicalData.dataArrayList.get(0).volume); 518 | System.out.println(historicalData.dataArrayList.get(historicalData.dataArrayList.size() - 1).volume); 519 | System.out.println(historicalData.dataArrayList.get(0).oi); 520 | } 521 | 522 | /** Logout user.*/ 523 | public void logout(KiteConnect kiteConnect) throws KiteException, IOException { 524 | /** Logout user and kill session. */ 525 | JSONObject jsonObject10 = kiteConnect.logout(); 526 | System.out.println(jsonObject10); 527 | } 528 | 529 | /** Retrieve mf instrument dump */ 530 | public void getMFInstruments(KiteConnect kiteConnect) throws KiteException, IOException { 531 | List mfList = kiteConnect.getMFInstruments(); 532 | System.out.println("size of mf instrument list: "+mfList.size()); 533 | } 534 | 535 | /* Get all mutualfunds holdings */ 536 | public void getMFHoldings(KiteConnect kiteConnect) throws KiteException, IOException { 537 | List MFHoldings = kiteConnect.getMFHoldings(); 538 | System.out.println("mf holdings "+ MFHoldings.size()); 539 | } 540 | 541 | /* Place a mutualfunds order */ 542 | public void placeMFOrder(KiteConnect kiteConnect) throws KiteException, IOException { 543 | System.out.println("place order: "+ kiteConnect.placeMFOrder("INF174K01LS2", Constants.TRANSACTION_TYPE_BUY, 5000, 0, "myTag").orderId); 544 | } 545 | 546 | /* cancel mutualfunds order */ 547 | public void cancelMFOrder(KiteConnect kiteConnect) throws KiteException, IOException { 548 | kiteConnect.cancelMFOrder("668604240868430"); 549 | System.out.println("cancel order successful"); 550 | } 551 | 552 | /* retrieve all mutualfunds orders */ 553 | public void getMFOrders(KiteConnect kiteConnect) throws KiteException, IOException { 554 | List MFOrders = kiteConnect.getMFOrders(); 555 | System.out.println("mf orders: "+ MFOrders.size()); 556 | } 557 | 558 | /* retrieve individual mutualfunds order */ 559 | public void getMFOrder(KiteConnect kiteConnect) throws KiteException, IOException { 560 | System.out.println("mf order: "+ kiteConnect.getMFOrder("106580291331583").tradingsymbol); 561 | } 562 | 563 | /* place mutualfunds sip */ 564 | public void placeMFSIP(KiteConnect kiteConnect) throws KiteException, IOException { 565 | System.out.println("mf place sip: "+ kiteConnect.placeMFSIP("INF174K01LS2", "monthly", 1, -1, 5000, 1000).sipId); 566 | } 567 | 568 | /* modify a mutual fund sip */ 569 | public void modifyMFSIP(KiteConnect kiteConnect) throws KiteException, IOException { 570 | kiteConnect.modifyMFSIP("weekly", 1, 5, 1000, "active", "504341441825418"); 571 | } 572 | 573 | /* cancel a mutualfunds sip */ 574 | public void cancelMFSIP(KiteConnect kiteConnect) throws KiteException, IOException { 575 | kiteConnect.cancelMFSIP("504341441825418"); 576 | System.out.println("cancel sip successful"); 577 | } 578 | 579 | /* retrieve all mutualfunds sip */ 580 | public void getMFSIPS(KiteConnect kiteConnect) throws KiteException, IOException { 581 | List sips = kiteConnect.getMFSIPs(); 582 | System.out.println("mf sips: "+ sips.size()); 583 | } 584 | 585 | /* retrieve individual mutualfunds sip */ 586 | public void getMFSIP(KiteConnect kiteConnect) throws KiteException, IOException { 587 | System.out.println("mf sip: "+ kiteConnect.getMFSIP("291156521960679").instalments); 588 | } 589 | 590 | /** Demonstrates com.zerodhatech.ticker connection, subcribing for instruments, unsubscribing for instruments, set mode of tick data, com.zerodhatech.ticker disconnection*/ 591 | public void tickerUsage(KiteConnect kiteConnect, ArrayList tokens) throws IOException, WebSocketException, KiteException { 592 | /** To get live price use websocket connection. 593 | * It is recommended to use only one websocket connection at any point of time and make sure you stop connection, once user goes out of app. 594 | * custom url points to new endpoint which can be used till complete Kite Connect 3 migration is done. */ 595 | final KiteTicker tickerProvider = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey()); 596 | 597 | tickerProvider.setOnConnectedListener(new OnConnect() { 598 | @Override 599 | public void onConnected() { 600 | /** Subscribe ticks for token. 601 | * By default, all tokens are subscribed for modeQuote. 602 | * */ 603 | tickerProvider.subscribe(tokens); 604 | tickerProvider.setMode(tokens, KiteTicker.modeFull); 605 | } 606 | }); 607 | 608 | tickerProvider.setOnDisconnectedListener(new OnDisconnect() { 609 | @Override 610 | public void onDisconnected() { 611 | // your code goes here 612 | } 613 | }); 614 | 615 | /** Set listener to get order updates.*/ 616 | tickerProvider.setOnOrderUpdateListener(new OnOrderUpdate() { 617 | @Override 618 | public void onOrderUpdate(Order order) { 619 | System.out.println("order update "+order.orderId); 620 | } 621 | }); 622 | 623 | /** Set error listener to listen to errors.*/ 624 | tickerProvider.setOnErrorListener(new OnError() { 625 | @Override 626 | public void onError(Exception exception) { 627 | //handle here. 628 | } 629 | 630 | @Override 631 | public void onError(KiteException kiteException) { 632 | //handle here. 633 | } 634 | 635 | @Override 636 | public void onError(String error) { 637 | System.out.println(error); 638 | } 639 | }); 640 | 641 | tickerProvider.setOnTickerArrivalListener(new OnTicks() { 642 | @Override 643 | public void onTicks(ArrayList ticks) { 644 | NumberFormat formatter = new DecimalFormat(); 645 | System.out.println("ticks size " + ticks.size()); 646 | if(ticks.size() > 0) { 647 | System.out.println("last price " + ticks.get(0).getLastTradedPrice()); 648 | System.out.println("open interest " + formatter.format(ticks.get(0).getOi())); 649 | System.out.println("day high OI " + formatter.format(ticks.get(0).getOpenInterestDayHigh())); 650 | System.out.println("day low OI " + formatter.format(ticks.get(0).getOpenInterestDayLow())); 651 | System.out.println("change " + formatter.format(ticks.get(0).getChange())); 652 | System.out.println("tick timestamp " + ticks.get(0).getTickTimestamp()); 653 | System.out.println("last traded time " + ticks.get(0).getLastTradedTime()); 654 | System.out.println(ticks.get(0).getMarketDepth().get("buy").size()); 655 | } 656 | } 657 | }); 658 | // Make sure this is called before calling connect. 659 | tickerProvider.setTryReconnection(true); 660 | //maximum retries and should be greater than 0 661 | tickerProvider.setMaximumRetries(10); 662 | //set maximum retry interval in seconds 663 | tickerProvider.setMaximumRetryInterval(30); 664 | 665 | /** connects to com.zerodhatech.com.zerodhatech.ticker server for getting live quotes*/ 666 | tickerProvider.connect(); 667 | 668 | /** You can check, if websocket connection is open or not using the following method.*/ 669 | boolean isConnected = tickerProvider.isConnectionOpen(); 670 | System.out.println(isConnected); 671 | 672 | /** set mode is used to set mode in which you need tick for list of tokens. 673 | * Ticker allows three modes, modeFull, modeQuote, modeLTP. 674 | * For getting only last traded price, use modeLTP 675 | * For getting last traded price, last traded quantity, average price, volume traded today, total sell quantity and total buy quantity, open, high, low, close, change, use modeQuote 676 | * For getting all data with depth, use modeFull*/ 677 | tickerProvider.setMode(tokens, KiteTicker.modeLTP); 678 | 679 | // Unsubscribe for a token. 680 | tickerProvider.unsubscribe(tokens); 681 | 682 | // After using com.zerodhatech.com.zerodhatech.ticker, close websocket connection. 683 | tickerProvider.disconnect(); 684 | } 685 | } -------------------------------------------------------------------------------- /sample/src/Test.java: -------------------------------------------------------------------------------- 1 | import com.neovisionaries.ws.client.WebSocketException; 2 | import com.zerodhatech.kiteconnect.KiteConnect; 3 | import com.zerodhatech.kiteconnect.kitehttp.SessionExpiryHook; 4 | import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; 5 | import com.zerodhatech.models.User; 6 | import org.json.JSONException; 7 | 8 | import java.io.IOException; 9 | import java.util.ArrayList; 10 | 11 | /** 12 | * Created by sujith on 7/10/16. 13 | * This class has example of how to initialize kiteSdk and make rest api calls to place order, get orders, modify order, cancel order, 14 | * get positions, get holdings, convert positions, get instruments, logout user, get historical data dump, get trades 15 | */ 16 | public class Test { 17 | 18 | public static void main(String[] args){ 19 | try { 20 | // First you should get request_token, public_token using kitconnect login and then use request_token, public_token, api_secret to make any kiteConnect api call. 21 | // Initialize KiteSdk with your apiKey. 22 | KiteConnect kiteConnect = new KiteConnect("xxxxyyyyzzzz"); 23 | 24 | //If you wish to enable debug logs send true in the constructor, this will log request and response. 25 | //KiteConnect kiteConnect = new KiteConnect("xxxxyyyyzzzz", true); 26 | 27 | // If you wish to set proxy then pass proxy as a second parameter in the constructor with api_key. syntax:- new KiteConnect("xxxxxxyyyyyzzz", proxy). 28 | //KiteConnect kiteConnect = new KiteConnect("xxxxyyyyzzzz", userProxy, false); 29 | 30 | // Set userId 31 | kiteConnect.setUserId("xxxxx"); 32 | 33 | // Get login url 34 | String url = kiteConnect.getLoginURL(); 35 | 36 | // Set session expiry callback. 37 | kiteConnect.setSessionExpiryHook(new SessionExpiryHook() { 38 | @Override 39 | public void sessionExpired() { 40 | System.out.println("session expired"); 41 | } 42 | }); 43 | 44 | /* The request token can to be obtained after completion of login process. Check out https://kite.trade/docs/connect/v3/user/#login-flow for more information. 45 | A request token is valid for only a couple of minutes and can be used only once. An access token is valid for one whole day. Don't call this method for every app run. 46 | Once an access token is received it should be stored in preferences or database for further usage. 47 | */ 48 | User user = kiteConnect.generateSession("xxxxxtttyyy", "xxxxxxxyyyyy"); 49 | kiteConnect.setAccessToken(user.accessToken); 50 | kiteConnect.setPublicToken(user.publicToken); 51 | 52 | Examples examples = new Examples(); 53 | 54 | examples.getProfile(kiteConnect); 55 | 56 | examples.getMargins(kiteConnect); 57 | 58 | examples.getMarginCalculation(kiteConnect); 59 | 60 | examples.placeOrder(kiteConnect); 61 | 62 | examples.modifyOrder(kiteConnect); 63 | 64 | examples.cancelOrder(kiteConnect); 65 | 66 | examples.getAuctionInstruments(kiteConnect); 67 | 68 | examples.placeAuctionOrder(kiteConnect); 69 | 70 | examples.placeAutoSliceOrder(kiteConnect); 71 | 72 | examples.placeMarketProtectionOrder(kiteConnect); 73 | 74 | examples.getTriggerRange(kiteConnect); 75 | 76 | examples.placeCoverOrder(kiteConnect); 77 | 78 | examples.converPosition(kiteConnect); 79 | 80 | examples.getHistoricalData(kiteConnect); 81 | 82 | examples.getOrders(kiteConnect); 83 | 84 | examples.getOrder(kiteConnect); 85 | 86 | examples.getTrades(kiteConnect); 87 | 88 | examples.getTradesWithOrderId(kiteConnect); 89 | 90 | examples.getPositions(kiteConnect); 91 | 92 | examples.getHoldings(kiteConnect); 93 | 94 | examples.getAllInstruments(kiteConnect); 95 | 96 | examples.getInstrumentsForExchange(kiteConnect); 97 | 98 | examples.getQuote(kiteConnect); 99 | 100 | examples.getOHLC(kiteConnect); 101 | 102 | examples.getLTP(kiteConnect); 103 | 104 | examples.getGTTs(kiteConnect); 105 | 106 | examples.getGTT(kiteConnect); 107 | 108 | examples.placeGTT(kiteConnect); 109 | 110 | examples.modifyGTT(kiteConnect); 111 | 112 | examples.cancelGTT(kiteConnect); 113 | 114 | examples.getMFInstruments(kiteConnect); 115 | 116 | examples.placeMFOrder(kiteConnect); 117 | 118 | examples.cancelMFOrder(kiteConnect); 119 | 120 | examples.getMFOrders(kiteConnect); 121 | 122 | examples.getMFOrder(kiteConnect); 123 | 124 | examples.placeMFSIP(kiteConnect); 125 | 126 | examples.modifyMFSIP(kiteConnect); 127 | 128 | examples.cancelMFSIP(kiteConnect); 129 | 130 | examples.getMFSIPS(kiteConnect); 131 | 132 | examples.getMFSIP(kiteConnect); 133 | 134 | examples.getMFHoldings(kiteConnect); 135 | 136 | examples.logout(kiteConnect); 137 | 138 | ArrayList tokens = new ArrayList<>(); 139 | tokens.add(Long.parseLong("256265")); 140 | examples.tickerUsage(kiteConnect, tokens); 141 | } catch (KiteException e) { 142 | System.out.println(e.message+" "+e.code+" "+e.getClass().getName()); 143 | } catch (JSONException e) { 144 | e.printStackTrace(); 145 | }catch (IOException e) { 146 | e.printStackTrace(); 147 | } catch (WebSocketException e) { 148 | e.printStackTrace(); 149 | } 150 | } 151 | } --------------------------------------------------------------------------------