forked from vijaykosis/smartapi-java
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathSmartConnect.java
More file actions
866 lines (771 loc) · 28 KB
/
SmartConnect.java
File metadata and controls
866 lines (771 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
package com.angelbroking.smartapi;
import com.angelbroking.smartapi.http.SessionExpiryHook;
import com.angelbroking.smartapi.http.SmartAPIRequestHandler;
import com.angelbroking.smartapi.http.exceptions.SmartAPIException;
import com.angelbroking.smartapi.models.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.Proxy;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import static com.angelbroking.smartapi.utils.Constants.IO_EXCEPTION_ERROR_MSG;
import static com.angelbroking.smartapi.utils.Constants.IO_EXCEPTION_OCCURRED;
import static com.angelbroking.smartapi.utils.Constants.JSON_EXCEPTION_ERROR_MSG;
import static com.angelbroking.smartapi.utils.Constants.JSON_EXCEPTION_OCCURRED;
import static com.angelbroking.smartapi.utils.Constants.SMART_API_EXCEPTION_ERROR_MSG;
import static com.angelbroking.smartapi.utils.Constants.SMART_API_EXCEPTION_OCCURRED;
@Slf4j
public class SmartConnect {
public static SessionExpiryHook sessionExpiryHook = null;
public static boolean ENABLE_LOGGING = false;
private Proxy proxy = null;
private String apiKey;
private String accessToken;
private String refreshToken;
private Routes routes = new Routes();
private String userId;
private SmartAPIRequestHandler smartAPIRequestHandler = new SmartAPIRequestHandler(proxy);
public SmartConnect() {
//setting up TLS min and max version
System.setProperty("https.protocols","TLSv1.2,TLSv1.3");
}
public SmartConnect(String apiKey) {
this.apiKey = apiKey;
}
public SmartConnect(String apiKey, String accessToken, String refreshToken) {
this.apiKey = apiKey;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
/**
* Registers callback for session error.
*
* @param hook can be set to get callback when session is expired.
*/
public void setSessionExpiryHook(SessionExpiryHook hook) {
sessionExpiryHook = hook;
}
/**
* Returns apiKey of the App.
*
* @return String apiKey is returned.
* @throws NullPointerException if _apiKey is not found.
*/
public String getApiKey() throws NullPointerException {
if (apiKey != null)
return apiKey;
else
throw new NullPointerException();
}
/**
* Returns accessToken.
*
* @return String access_token is returned.
* @throws NullPointerException if accessToken is null.
*/
public String getAccessToken() throws NullPointerException {
if (accessToken != null)
return accessToken;
else
throw new NullPointerException();
}
/**
* Returns userId.
*
* @return String userId is returned.
* @throws NullPointerException if userId is null.
*/
public String getUserId() throws NullPointerException {
if (userId != null) {
return userId;
} else {
throw new NullPointerException();
}
}
/**
* Set userId.
*
* @param id is user_id.
*/
public void setUserId(String id) {
userId = id;
}
/**
* Returns publicToken.
*
* @throws NullPointerException if publicToken is null.
* @return String public token is returned.
*/
public String getPublicToken() throws NullPointerException {
if (refreshToken != null) {
return refreshToken;
} else {
throw new NullPointerException();
}
}
/**
* Set the accessToken received after a successful authentication.
*
* @param accessToken is the access token received after sending request token
* and api secret.
*/
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
/**
* Set publicToken.
*
* @param publicToken is the public token received after sending request token
* and api secret.
*/
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
/**
* Retrieves login url
*
* @return String loginUrl is returned.
*/
public String getLoginURL() throws NullPointerException {
String baseUrl = routes.getLoginUrl();
return baseUrl;
}
/**
* Do the token exchange with the `request_token` obtained after the login flow,
* and retrieve the `access_token` required for all subsequent requests.
*
* @param requestToken received from login process.
* @param apiSecret which is unique for each aap.
* @return User is the user model which contains user and session details.
*
*/
public User generateSession(String clientCode, String password, String totp) {
try {
smartAPIRequestHandler = new SmartAPIRequestHandler(proxy);
// Create JSON params object needed to be sent to api.
JSONObject params = new JSONObject();
params.put("clientcode", clientCode);
params.put("password", password);
params.put("totp", totp);
JSONObject loginResultObject = smartAPIRequestHandler.postRequest(this.apiKey, routes.getLoginUrl(),
params);
log.info("login result: {}",loginResultObject);
String jwtToken = loginResultObject.getJSONObject("data").getString("jwtToken");
String refreshToken = loginResultObject.getJSONObject("data").getString("refreshToken");
String feedToken = loginResultObject.getJSONObject("data").getString("feedToken");
String url = routes.get("api.user.profile");
User user = new User().parseResponse(smartAPIRequestHandler.getRequest(this.apiKey, url, jwtToken));
user.setAccessToken(jwtToken);
user.setRefreshToken(refreshToken);
user.setFeedToken(feedToken);
return user;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Get a new access token using refresh token.
*
* @param refreshToken is the refresh token obtained after generateSession.
* @param apiSecret is unique for each app.
* @return TokenSet contains user id, refresh token, api secret.
*
*/
public TokenSet renewAccessToken(String accessToken, String refreshToken) {
try {
String hashableText = this.apiKey + refreshToken + accessToken;
String sha256hex = sha256Hex(hashableText);
JSONObject params = new JSONObject();
params.put("refreshToken", refreshToken);
params.put("checksum", sha256hex);
String url = routes.get("api.refresh");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
accessToken = response.getJSONObject("data").getString("jwtToken");
refreshToken = response.getJSONObject("data").getString("refreshToken");
TokenSet tokenSet = new TokenSet();
tokenSet.setUserId(userId);
tokenSet.setAccessToken(accessToken);
tokenSet.setRefreshToken(refreshToken);
return tokenSet;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Hex encodes sha256 output for android support.
*
* @return Hex encoded String.
* @param str is the String that has to be encrypted.
*/
public String sha256Hex(String str) {
byte[] a = DigestUtils.sha256(str);
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a)
sb.append(String.format("%02x", b));
return sb.toString();
}
/**
* Get the profile details of the use.
*
* @return Profile is a POJO which contains profile related data.
*
*/
public User getProfile() {
try {
String url = routes.get("api.user.profile");
User user = new User().parseResponse(smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken));
return user;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Places an order.
*
* @param orderParams is Order params.
* @param variety variety="regular". Order variety can be bo, co, amo,
* regular.
* @return Order contains only orderId.
*
*/
public Order placeOrder(OrderParams orderParams, String variety) {
try {
String url = routes.get("api.order.place");
JSONObject params = new JSONObject();
if (orderParams.exchange != null)
params.put("exchange", orderParams.exchange);
if (orderParams.tradingsymbol != null)
params.put("tradingsymbol", orderParams.tradingsymbol);
if (orderParams.transactiontype != null)
params.put("transactiontype", orderParams.transactiontype);
if (orderParams.quantity != null)
params.put("quantity", orderParams.quantity);
if (orderParams.price != null)
params.put("price", orderParams.price);
if (orderParams.producttype != null)
params.put("producttype", orderParams.producttype);
if (orderParams.ordertype != null)
params.put("ordertype", orderParams.ordertype);
if (orderParams.duration != null)
params.put("duration", orderParams.duration);
if (orderParams.price != null)
params.put("price", orderParams.price);
if (orderParams.symboltoken != null)
params.put("symboltoken", orderParams.symboltoken);
if (orderParams.squareoff != null)
params.put("squareoff", orderParams.squareoff);
if (orderParams.stoploss != null)
params.put("stoploss", orderParams.stoploss);
if (orderParams.triggerprice != null)
params.put("triggerprice", orderParams.triggerprice);
params.put("variety", variety);
JSONObject jsonObject = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
Order order = new Order();
order.orderId = jsonObject.getJSONObject("data").getString("orderid");
log.info("order : {}",order);
return order;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Modifies an open order.
*
* @param orderParams is Order params.
* @param variety variety="regular". Order variety can be bo, co, amo,
* regular.
* @param orderId order id of the order being modified.
* @return Order object contains only orderId.
*
*/
public Order modifyOrder(String orderId, OrderParams orderParams, String variety) {
try {
String url = routes.get("api.order.modify");
JSONObject params = new JSONObject();
if (orderParams.exchange != null)
params.put("exchange", orderParams.exchange);
if (orderParams.tradingsymbol != null)
params.put("tradingsymbol", orderParams.tradingsymbol);
if (orderParams.symboltoken != null)
params.put("symboltoken", orderParams.symboltoken);
if (orderParams.quantity != null)
params.put("quantity", orderParams.quantity);
if (orderParams.price != null)
params.put("price", orderParams.price);
if (orderParams.producttype != null)
params.put("producttype", orderParams.producttype);
if (orderParams.ordertype != null)
params.put("ordertype", orderParams.ordertype);
if (orderParams.duration != null)
params.put("duration", orderParams.duration);
params.put("variety", variety);
params.put("orderid", orderId);
JSONObject jsonObject = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
Order order = new Order();
order.orderId = jsonObject.getJSONObject("data").getString("orderid");
return order;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Cancels an order.
*
* @param orderId order id of the order to be cancelled.
* @param variety [variety="regular"]. Order variety can be bo, co, amo,
* regular.
* @return Order object contains only orderId.
*
*/
public Order cancelOrder(String orderId, String variety) {
try {
String url = routes.get("api.order.cancel");
JSONObject params = new JSONObject();
params.put("variety", variety);
params.put("orderid", orderId);
JSONObject jsonObject = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
Order order = new Order();
order.orderId = jsonObject.getJSONObject("data").getString("orderid");
return order;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Returns list of different stages an order has gone through.
*
* @return List of multiple stages an order has gone through in the system.
* @throws SmartAPIException is thrown for all Smart API trade related errors.
* @param orderId is the order id which is obtained from orderbook.
*
*/
@SuppressWarnings({})
public JSONObject getOrderHistory(String clientId) {
try {
String url = routes.get("api.order.book");
JSONObject response = smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken);
log.info("Order history : {}",response);
return response;
} catch (Exception | SmartAPIException e) {
log.error("Exception#: {}" , e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* Retrieves last price. User can either pass exchange with tradingsymbol or
* instrument token only. For example {NSE:NIFTY 50, BSE:SENSEX} or {256265,
* 265}.
*
* @return Map of String and LTPQuote.
*
*/
public JSONObject getLTP(String exchange, String tradingSymbol, String symboltoken) {
try {
JSONObject params = new JSONObject();
params.put("exchange", exchange);
params.put("tradingsymbol", tradingSymbol);
params.put("symboltoken", symboltoken);
String url = routes.get("api.ltp.data");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
return response.getJSONObject("data");
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Retrieves list of trades executed.
*
* @return List of trades.
*/
public JSONObject getTrades() {
try {
String url = routes.get("api.order.trade.book");
JSONObject response = smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken);
return response;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Retrieves RMS.
*
* @return Object of RMS.
* @throws SmartAPIException is thrown for all Smart API trade related errors.
* @throws JSONException is thrown when there is exception while parsing
* response.
* @throws IOException is thrown when there is connection error.
*/
public JSONObject getRMS() {
try {
String url = routes.get("api.order.rms.data");
JSONObject response = smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken);
return response.getJSONObject("data");
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Retrieves Holding.
*
* @return Object of Holding.
*
*/
public JSONObject getHolding() {
try {
String url = routes.get("api.order.rms.holding");
JSONObject response = smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken);
return response;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Retrieves All Holdings.
*
* @return Object of Holding.
*
*/
public JSONObject getAllHolding() throws SmartAPIException, IOException {
try {
String url = routes.get("api.order.rms.AllHolding");
return smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken);
} catch (SmartAPIException ex) {
log.error("{} while getting all holdings {}", SMART_API_EXCEPTION_OCCURRED, ex.toString());
throw new SmartAPIException(String.format("%s in getting all holdings %s", SMART_API_EXCEPTION_ERROR_MSG, ex));
} catch (IOException ex) {
log.error("{} while getting all holdings {}", IO_EXCEPTION_OCCURRED, ex.getMessage());
throw new IOException(String.format("%s in getting all holdings %s", IO_EXCEPTION_ERROR_MSG, ex.getMessage()));
} catch (JSONException ex) {
log.error("{} while getting all holdings {}", JSON_EXCEPTION_OCCURRED, ex.getMessage());
throw new JSONException(String.format("%s in getting all holdings %s", JSON_EXCEPTION_ERROR_MSG, ex.getMessage()));
}
}
/**
* Retrieves position.
*
* @return Object of position.
*
*/
public JSONObject getPosition() {
try {
String url = routes.get("api.order.rms.position");
JSONObject response = smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken);
return response;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Retrieves conversion.
*
* @return Object of conversion.
* @throws SmartAPIException is thrown for all Smart API trade related errors.
* @throws JSONException is thrown when there is exception while parsing
* response.
* @throws IOException is thrown when there is connection error.
*/
public JSONObject convertPosition(JSONObject params) {
try {
String url = routes.get("api.order.rms.position.convert");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
return response;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Create a Gtt Rule.
*
* @param gttParams is gtt Params.
* @return Gtt contains only orderId.
*
*/
public Gtt gttCreateRule(GttParams gttParams) {
try {
String url = routes.get("api.gtt.create");
JSONObject params = new JSONObject();
if (gttParams.tradingsymbol != null)
params.put("tradingsymbol", gttParams.tradingsymbol);
if (gttParams.symboltoken != null)
params.put("symboltoken", gttParams.symboltoken);
if (gttParams.exchange != null)
params.put("exchange", gttParams.exchange);
if (gttParams.transactiontype != null)
params.put("transactiontype", gttParams.transactiontype);
if (gttParams.producttype != null)
params.put("producttype", gttParams.producttype);
if (gttParams.price != null)
params.put("price", gttParams.price);
if (gttParams.qty != null)
params.put("qty", gttParams.qty);
if (gttParams.triggerprice != null)
params.put("triggerprice", gttParams.triggerprice);
if (gttParams.disclosedqty != null)
params.put("disclosedqty", gttParams.disclosedqty);
if (gttParams.timeperiod != null)
params.put("timeperiod", gttParams.timeperiod);
JSONObject jsonObject = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
Gtt gtt = new Gtt();
gtt.id = jsonObject.getJSONObject("data").getInt("id");
log.info("gtt : {}",gtt);
return gtt;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Modify a Gtt Rule.
*
* @param gttParams is gtt Params.
* @return Gtt contains only orderId.
*
*/
public Gtt gttModifyRule(Integer id, GttParams gttParams) {
try {
String url = routes.get("api.gtt.modify");
JSONObject params = new JSONObject();
if (gttParams.symboltoken != null)
params.put("symboltoken", gttParams.symboltoken);
if (gttParams.exchange != null)
params.put("exchange", gttParams.exchange);
if (gttParams.price != null)
params.put("price", gttParams.price);
if (gttParams.qty != null)
params.put("qty", gttParams.qty);
if (gttParams.triggerprice != null)
params.put("triggerprice", gttParams.triggerprice);
if (gttParams.disclosedqty != null)
params.put("disclosedqty", gttParams.disclosedqty);
if (gttParams.timeperiod != null)
params.put("timeperiod", gttParams.timeperiod);
params.put("id", id);
JSONObject jsonObject = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
Gtt gtt = new Gtt();
gtt.id = jsonObject.getJSONObject("data").getInt("id");
log.info("gtt : {}",gtt);
return gtt;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Cancel a Gtt Rule.
*
* @param gttParams is gtt Params.
* @return Gtt contains only orderId.
*/
public Gtt gttCancelRule(Integer id, String symboltoken, String exchange) {
try {
JSONObject params = new JSONObject();
params.put("id", id);
params.put("symboltoken", symboltoken);
params.put("exchange", exchange);
String url = routes.get("api.gtt.cancel");
JSONObject jsonObject = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
Gtt gtt = new Gtt();
gtt.id = jsonObject.getJSONObject("data").getInt("id");
log.info("gtt : {}",gtt);
return gtt;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Get Gtt Rule Details.
*
* @param id is gtt rule id.
* @return returns the details of gtt rule.
*/
public JSONObject gttRuleDetails(Integer id) {
try {
JSONObject params = new JSONObject();
params.put("id", id);
String url = routes.get("api.gtt.details");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
log.info("response : {}",response);
return response.getJSONObject("data");
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Get Gtt Rule Details.
*
* @param status is list of gtt rule status.
* @param page is no of page
* @param count is the count of gtt rules
* @return returns the detailed list of gtt rules.
*/
public JSONArray gttRuleList(List<String> status, Integer page, Integer count) {
try {
JSONObject params = new JSONObject();
params.put("status", status);
params.put("page", page);
params.put("count", count);
String url = routes.get("api.gtt.list");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
log.info("response : {}",response);
return response.getJSONArray("data");
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Get Historic Data.
*
* @param params is historic data params.
* @return returns the details of historic data.
*/
public JSONArray candleData(JSONObject params) {
try {
String url = routes.get("api.candle.data");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
log.info("response : {}",response);
return response.getJSONArray("data");
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Get Search Script Data.
*
* @param payload is Search Script params.
* @return returns the details of Search Script data.
*/
public String getSearchScrip(JSONObject payload) throws SmartAPIException, IOException {
try {
String url = routes.get("api.search.script.data");
return smartAPIRequestHandler.postRequestJSONObject(this.apiKey, url, payload, accessToken);
}catch (IOException ex) {
log.error("{} while generating session {}", IO_EXCEPTION_OCCURRED, ex.getMessage());
throw new IOException(String.format("%s in generating Session %s", IO_EXCEPTION_ERROR_MSG, ex.getMessage()));
} catch (JSONException ex) {
log.error("{} while generating session {}", JSON_EXCEPTION_OCCURRED, ex.getMessage());
throw new JSONException(String.format("%s in generating Session %s", JSON_EXCEPTION_ERROR_MSG, ex.getMessage()));
} catch (SmartAPIException ex) {
log.error("{} while generating session {}", SMART_API_EXCEPTION_OCCURRED, ex.toString());
throw new SmartAPIException(String.format("%s in generating Session %s", SMART_API_EXCEPTION_ERROR_MSG, ex));
}
}
/**
* Get Market Data.
*
* @param params is market data params.
* @return returns the details of market data.
*/
public JSONObject marketData(JSONObject params) throws SmartAPIException, IOException {
try{
String url = routes.get("api.market.data");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
return response.getJSONObject("data");
}catch (SmartAPIException ex) {
log.error("{} while placing order {}", SMART_API_EXCEPTION_OCCURRED, ex.toString());
throw new SmartAPIException(String.format("%s in placing order %s", SMART_API_EXCEPTION_ERROR_MSG, ex));
} catch (IOException ex) {
log.error("{} while placing order {}", IO_EXCEPTION_OCCURRED, ex.getMessage());
throw new IOException(String.format("%s in placing order %s", IO_EXCEPTION_ERROR_MSG, ex.getMessage()));
} catch (JSONException ex) {
log.error("{} while placing order {}", JSON_EXCEPTION_OCCURRED, ex.getMessage());
throw new JSONException(String.format("%s in placing order %s", JSON_EXCEPTION_ERROR_MSG, ex.getMessage()));
}
}
/**
* Logs out user by invalidating the access token.
*
* @return JSONObject which contains status
*
*/
public JSONObject logout() {
try {
String url = routes.get("api.user.logout");
JSONObject params = new JSONObject();
params.put("clientcode", this.userId);
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, params, accessToken);
return response;
} catch (Exception | SmartAPIException e) {
log.error(e.getMessage());
return null;
}
}
/**
* Get Margin Data.
*
* @param marginParams is margin data params.
* @return returns the response of margin data.
*/
public JSONObject getMarginDetails(List<MarginParams> marginParams) throws IOException, SmartAPIException {
try {
JSONArray positionsArray = new JSONArray();
for (MarginParams params : marginParams) {
JSONObject position = new JSONObject();
position.put("exchange", params.exchange);
position.put("qty", params.quantity);
position.put("price", params.price);
position.put("productType", params.productType);
position.put("token", params.token);
position.put("tradeType", params.tradeType);
positionsArray.put(position);
}
JSONObject requestBody = new JSONObject();
requestBody.put("positions", positionsArray);
String url = routes.get("api.margin.batch");
JSONObject response = smartAPIRequestHandler.postRequest(this.apiKey, url, requestBody, accessToken);
return response;
} catch (SmartAPIException ex) {
log.error("{} while fetching margin data {}", SMART_API_EXCEPTION_OCCURRED, ex.toString());
throw new SmartAPIException(String.format("%s while fetching margin data %s", SMART_API_EXCEPTION_ERROR_MSG, ex));
} catch (IOException ex) {
log.error("{} while fetching margin data {}", IO_EXCEPTION_OCCURRED, ex.getMessage());
throw new IOException(String.format("%s while fetching margin data %s", IO_EXCEPTION_ERROR_MSG, ex.getMessage()));
} catch (JSONException ex) {
log.error("{} while fetching margin data {}", JSON_EXCEPTION_OCCURRED, ex.getMessage());
throw new JSONException(String.format("%s while fetching margin data %s", JSON_EXCEPTION_ERROR_MSG, ex.getMessage()));
}
}
/** Get Individual Order Details
*
* @return JSONObject which contains order details from Smart API
*
*/
public JSONObject getIndividualOrderDetails(String orderId) throws IOException, SmartAPIException {
try {
String url = routes.get("api.individual.order").concat(orderId);
return smartAPIRequestHandler.getRequest(this.apiKey, url, accessToken);
} catch (SmartAPIException ex) {
log.error("{} while getting individual order {}", SMART_API_EXCEPTION_OCCURRED, ex.toString());
throw new SmartAPIException(String.format("%s in getting individual order %s", SMART_API_EXCEPTION_ERROR_MSG, ex));
} catch (IOException ex) {
log.error("{} while getting individual order {}", IO_EXCEPTION_OCCURRED, ex.getMessage());
throw new IOException(String.format("%s while fetching margin data %s", IO_EXCEPTION_ERROR_MSG, ex.getMessage()));
} catch (JSONException ex) {
log.error("{} while getting individual order {}", JSON_EXCEPTION_OCCURRED, ex.getMessage());
throw new JSONException(String.format("%s while fetching margin data %s", JSON_EXCEPTION_ERROR_MSG, ex.getMessage()));
}
}
}