api_connect_nodejs 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +30 -30
  2. package/conf/settings.ini +19 -19
  3. package/enums/actionType.js +10 -10
  4. package/enums/assetType.js +25 -25
  5. package/enums/chartExchangeType.js +15 -15
  6. package/enums/chartType.js +13 -13
  7. package/enums/eodIntervalType.js +11 -11
  8. package/enums/exchangeType.js +14 -14
  9. package/enums/intradayIntervalType.js +14 -14
  10. package/enums/marketCapType.js +12 -12
  11. package/enums/orderType.js +21 -21
  12. package/enums/productType.js +24 -24
  13. package/enums/segementsType.js +13 -13
  14. package/enums/streamingConstants.js +11 -11
  15. package/enums/termsType.js +12 -12
  16. package/enums/validity.js +22 -22
  17. package/index.js +3 -3
  18. package/package.json +25 -25
  19. package/src/apiConnect.js +2342 -2430
  20. package/src/apiUtils.js +221 -129
  21. package/src/chart.js +258 -258
  22. package/src/config.js +316 -326
  23. package/src/feed/feed.js +139 -139
  24. package/src/feed/liveNewsFeed.js +112 -112
  25. package/src/feed/ordersFeed.js +124 -124
  26. package/src/feed/quotesFeed.js +121 -121
  27. package/src/http.js +197 -197
  28. package/src/iniparser.js +42 -42
  29. package/src/liveNews.js +362 -362
  30. package/src/logger.js +16 -16
  31. package/src/order.js +48 -48
  32. package/src/researchCalls.js +175 -175
  33. package/src/watchlist.js +378 -378
  34. package/validations/apiConnectValidator.js +521 -508
  35. package/validations/chartValidator.js +85 -85
  36. package/validations/feedStreamerValidator.js +68 -68
  37. package/validations/liveNewsValidator.js +60 -60
  38. package/validations/researchCallsValidator.js +86 -86
  39. package/validations/watchlistValidator.js +60 -60
package/src/apiConnect.js CHANGED
@@ -1,2430 +1,2342 @@
1
- const fs = require("fs");
2
- const readline = require("readline");
3
- const log4js = require("./logger.js");
4
- const Order = require("./order");
5
- const Chart = require("./chart");
6
- const LiveNews = require("./liveNews");
7
- const Watchlist = require("./watchlist");
8
- const ResearchCalls = require("./researchCalls");
9
- const __Constants = require("./apiUtils");
10
- const __Config = require("./config");
11
- const __Http = require("./http");
12
- const pkgJson = require("../package.json");
13
- const Feed = require("./feed/feed");
14
- const QuotesFeed = require("./feed/quotesFeed");
15
- const OrdersFeed = require("./feed/ordersFeed");
16
- const LiveNewsFeed = require("./feed/liveNewsFeed");
17
-
18
- const {
19
- validatePlaceTrade,
20
- validateModifyTrade,
21
- validateCancelPlaceTrade,
22
- validatePlaceGtcGtdTrade,
23
- validatePlaceCoverTrade,
24
- validateModifyCoverTrade,
25
- validateExitCoverTrade,
26
- validatePlaceAMOTrade,
27
- validateModifyAMOTrade,
28
- validateCancelAMOTrade,
29
- validateConvertPosition,
30
- validatePlaceMF,
31
- validateModifyMF,
32
- validateCancelMF,
33
- validatePlaceBracketTrade,
34
- validateExitBracketTrade,
35
- validateOrderDetails,
36
- validateOrderHistory,
37
- validatePositionSquareOff,
38
- validateMFOrderBook,
39
- } = require("../validations/apiConnectValidator");
40
-
41
- const {
42
- validateLiveNewsParams,
43
- validateNewsForResultsAndStocksParams,
44
- validateLatestCorporateActions,
45
- } = require("../validations/liveNewsValidator");
46
- class APIConnect {
47
- /**
48
- * This is **APIConnect** class. Please initialise single instance of this per `api_key`.
49
- * @param {string} apiKey API key provided by APIConnect
50
- * @param {string} password Password provided by APIConnect
51
- * @param {string} reqId Token to be collected post redirection from Login URL using APIConnect credentials
52
- * @param {string} downloadContract If this is set to `True` then It will download all the contracts and return the records in dictionary `instruments`
53
- */
54
- constructor(apiKey, password, reqId, downloadContract) {
55
- this.version = pkgJson.version;
56
- this.downloadContract = downloadContract;
57
- this.instruments = [];
58
- this.mfInstruments = [];
59
- this.__constants.ApiKey = apiKey;
60
- this.apiKey = apiKey;
61
- this.password = password;
62
- this.reqId = reqId;
63
- this.fileName = "data_" + apiKey + ".txt";
64
- this.__http.fileName = this.fileName;
65
- this.feedObject = null;
66
- }
67
-
68
- /**
69
- * Login with the given user and initialize all the properties
70
- * @returns Promise that resolves when everything is setup and rejects when there is an error
71
- */
72
- Init = () => {
73
- log4js.info("IN INIT");
74
- return new Promise((resolve, reject) => {
75
- let count = 0;
76
- const checkDone = (res) => {
77
- count = count - 1;
78
- if (count == 0) {
79
- resolve(res);
80
- }
81
- };
82
- const readFilePromise = new Promise((resolve, reject) => {
83
- fs.readFile(this.fileName, "utf8", (err, data) => {
84
- if (err) {
85
- //var promises=[]
86
- // if file doesn't exist, then generate it
87
- // these two functions will fill the __constants and generate ${fileName}
88
- // promises.push(this.__GenerateVendorSession(this.apiKey, this.password, this.reqId));
89
- // promises.push(this.__GetAuthorization(this.reqId));
90
- count++;
91
- // Promise.all(promises).then(checkDone()).catch(reject());
92
- this.__GenerateVendorSession(this.apiKey, this.password, this.reqId)
93
- .then((res) => {
94
- this.__GetAuthorization(this.reqId)
95
- .then((res) => {
96
- checkDone(res);
97
- resolve(true);
98
- })
99
- .catch((err) => reject(err));
100
- })
101
- .catch((err) => reject(err));
102
- } else {
103
- const j = JSON.parse(data);
104
- this.__constants.VendorSession = j.vt;
105
- this.__constants.JSession = j.auth;
106
- this.__constants.eqAccId = j.eqaccid;
107
- this.__constants.coAccId = j.coaccid;
108
- this.__constants.Data = j.data;
109
- this.__constants.AppIdKey = j.appidkey;
110
- this.__constants.profileId = j.data.data.lgnData.accs.prfId;
111
- count++;
112
- checkDone();
113
- resolve(true);
114
- }
115
- });
116
- });
117
-
118
- // Check if ${fileName} exists
119
- readFilePromise
120
- .then((res) => {
121
- count++;
122
- this.__CheckUpdate().then(checkDone).catch(reject);
123
- this.feedObject = new Feed();
124
- this.__Instruments()
125
- .then((res) => {
126
- //console.log("instrument then");
127
- checkDone(res);
128
- })
129
- .catch((err) => reject(err));
130
- })
131
- .catch((err) => reject(err));
132
- });
133
- };
134
-
135
- /**
136
- * Download the contract files and place the scrips in iterable format
137
- */
138
- __Instruments = () => {
139
- return new Promise((resolve, reject) => {
140
- if (this.downloadContract) {
141
- const readInstruments = this.__http
142
- .GetZipFileMethod(this.__config.EquityContractURL, "instruments.csv")
143
- .then(() => this.__readCsv("instruments.csv", this.instruments));
144
-
145
- const readMfInstruments = this.__http
146
- .GetZipFileMethod(this.__config.MFContractURL, "mfInstruments.csv")
147
- .then(() => this.__readCsv("mfInstruments.csv", this.mfInstruments));
148
-
149
- Promise.all([readInstruments, readMfInstruments])
150
- .then(resolve)
151
- .catch(reject);
152
- } else {
153
- resolve();
154
- }
155
- });
156
- };
157
-
158
- __readCsv = (fileName, inst) => {
159
- return new Promise((resolve, reject) => {
160
- try {
161
- const readInterface = readline.createInterface({
162
- input: fs.createReadStream(fileName),
163
- });
164
-
165
- let keys;
166
-
167
- readInterface.on("line", (line) => {
168
- if (keys) {
169
- const rowParts = line.split(",");
170
- const row = {};
171
- keys.forEach((key, i) => (row[key] = rowParts[i]));
172
- inst.push(row);
173
- } else {
174
- keys = line.split(",");
175
- }
176
- });
177
-
178
- readInterface.on("close", resolve);
179
- } catch (e) {
180
- reject(e);
181
- }
182
- });
183
- };
184
-
185
- __CheckUpdate = () => {
186
- let url = this.__config.CheckUpdateURl();
187
- return this.__http
188
- .PostMethod(url, { lib: "EAC_NODE", vsn: this.version })
189
- .then((res) => {
190
- if (res.data.sts) {
191
- if (res.data.msg === "MANDATORY") {
192
- console.log(
193
- "Mandatory Update. New version " +
194
- res.data.vsn +
195
- ". Update to new version to continue."
196
- );
197
- process.exit();
198
- } else if (res.data.msg === "OPTIONAL") {
199
- console.log(
200
- "New version " +
201
- res.data.vsn +
202
- " is available. Stay up to date for better experience"
203
- );
204
- }
205
- return;
206
- } else {
207
- throw res;
208
- }
209
- })
210
- };
211
-
212
- /**
213
- * Get LiveNewsStreaming Object
214
- * @function initLiveNewsStreaming
215
- * @returns LiveNewsStreaming Object, using this object you can call subsribe() and unsubsribe() methods.
216
- */
217
- initLiveNewsStreaming = () => {
218
- let liveNewsFeedObj = {};
219
- try {
220
- liveNewsFeedObj = new LiveNewsFeed(this.feedObject);
221
- } catch (error) {
222
- console.log(error);
223
- }
224
- return liveNewsFeedObj;
225
- };
226
-
227
- /**
228
- * Get QuotesStreaming Object
229
- * @function initQuotesStreaming
230
- * @returns QuotesStreaming Object, using this object you can call subsribe() and unsubsribe() methods.
231
- */
232
- initQuotesStreaming = () => {
233
- let quoteFeedObj = {};
234
- try {
235
- quoteFeedObj = new QuotesFeed(this.feedObject);
236
- } catch (error) {
237
- console.log(error);
238
- }
239
- return quoteFeedObj;
240
- };
241
-
242
- /**
243
- * Get OrdersStreaming Object
244
- * @function initOrdersStreaming
245
- * @param {string} accountId - accid Customer Account ID
246
- * @param {string} userId - User ID
247
- * @returns OrdersStreaming Object, using this object you can call subsribe() and unsubsribe() methods.
248
- */
249
- initOrdersStreaming = (accountId, userId) => {
250
- let orderFeedObj = {};
251
- try {
252
- orderFeedObj = new OrdersFeed(this.feedObject, accountId, userId);
253
- } catch (error) {
254
- console.log(error);
255
- }
256
- return orderFeedObj;
257
- };
258
-
259
- /**
260
- * Get Login info
261
- * @returns Login info
262
- */
263
- GetLoginData = () => {
264
- return this.__constants.Data;
265
- };
266
-
267
- /**
268
- * Generate Vendor Session
269
- * @param {string} apiKey Key provided by APIConnect
270
- * @param {string} password Password provided by APIConnect
271
- * @returns Promise \
272
- * if resolved, then returns object in the form of `{msg: string, success: boolean}` \
273
- * if rejected, returns error
274
- */
275
- __GenerateVendorSession = (apiKey, password) => {
276
- return this.__Login(apiKey, password);
277
- };
278
-
279
- /**
280
- * Get Login Info
281
- * @param {string} reqId Request ID generated during redirection to a url
282
- */
283
- __GetAuthorization = (reqId) => {
284
- return this.__Token(reqId);
285
- };
286
-
287
- /**
288
- * This method will retrieve watchlist for a particular client.
289
- * @function getWatchlistGroups
290
- * @returns Promise that resolves to Watchlist Groups of client \
291
- * Typical watchlist response will be a nested JSON containing below fields
292
- * - defGr - Defined groups for all users ex: My Positions,Strategies etc
293
- * - usrGr - List of User Defined Groups
294
- * - idxGr - List of Indices Groups
295
- * - usrTbs - List of User Tabs
296
- */
297
- getWatchlistGroups = () => {
298
- let res = {};
299
- log4js.info("Inside getWatchlistGroup method");
300
- const watchlistObj = new Watchlist(
301
- this.__http,
302
- this.__config,
303
- this.__constants
304
- );
305
- res = watchlistObj.getWatchlistGroups();
306
- return res;
307
- };
308
-
309
- /**
310
- * Get Scrips details of a watchlist
311
- * @function getWatchlistScrips
312
- * @param {string} groupName Watchlist name of getGroups response
313
- * @returns Promise that resolves to Scrips details of watchlist \
314
- * Typical watchlist scrips response will be a nested JSON containing below fields
315
- * - syLst - Scrips list
316
- */
317
- getWatchlistScrips = (groupName) => {
318
- let res = {};
319
- log4js.info("Inside getWatchlistScrips method");
320
- const watchlistObj = new Watchlist(
321
- this.__http,
322
- this.__config,
323
- this.__constants
324
- );
325
- res = watchlistObj.getWatchlistScrips(groupName);
326
- return res;
327
- };
328
-
329
- /**
330
- * Create new group for a particular client
331
- * @param {string} groupName - Watchlist Name
332
- * @param {array[]} symLst - Symbol List
333
- * @returns Promise that resolves to create new group of watchlist \
334
- * Typical create new group response will be a nested JSON containing below fields
335
- * - sts - status
336
- * - msg - message
337
- * - rearrangeTab
338
- * - updatedOn - created time of group(Unix Timestamp)
339
- */
340
- createWatchlistGroup = (groupName, symLst) => {
341
- let res = {};
342
- log4js.info("Inside createWatchlistGroup method");
343
- const watchlistObj = new Watchlist(
344
- this.__http,
345
- this.__config,
346
- this.__constants
347
- );
348
- res = watchlistObj.createWatchlistGroup(groupName, symLst);
349
- return res;
350
- };
351
-
352
- /**
353
- * Add Symbol in group of watchlist for a particular client
354
- * @function addSymbolWatchlist
355
- * @param {string} groupName - Watchlist Name
356
- * @param {array[]} symLst - Array of symbols
357
- * @returns Promise that resolves to add symbol in group of watchlist \
358
- * Typical add new symbol in watchlist group response will be a nested JSON containing below fields
359
- * - type - string
360
- * - msg - string
361
- * - rearrangeTab - boolean
362
- * - sts - boolean
363
- * - updatedOn - number(unix timeStamp)
364
- *
365
- */
366
- addSymbolWatchlist = (groupName, symLst) => {
367
- let res = {};
368
- log4js.info("Inside addSymbolWatchlist method");
369
- const watchlistObj = new Watchlist(
370
- this.__http,
371
- this.__config,
372
- this.__constants
373
- );
374
- res = watchlistObj.addSymbolWatchlist(groupName, symLst);
375
- return res;
376
- };
377
-
378
- /**
379
- * Delete Symbol in group of watchlist for a particular client
380
- * @function deleteSymbolWatchlist
381
- * @param {string} groupName
382
- * @param {array[]} symLst
383
- * @returns Promise that resolves to delete symbol in group of watchlist \
384
- * Typical delet symbol of watchlist response will be a nested JSON containing below fields
385
- * - type - string
386
- * - msg - string
387
- * - rearrangeTab - boolean
388
- * - sts - boolean
389
- */
390
- deleteSymbolWatchlist = (groupName, symLst) => {
391
- let res = {};
392
- log4js.info("Inside deleteSymbolWatchlist method");
393
- const watchlistObj = new Watchlist(
394
- this.__http,
395
- this.__config,
396
- this.__constants
397
- );
398
- res = watchlistObj.deleteSymbolWatchlist(groupName, symLst);
399
- return res;
400
- };
401
-
402
- /**
403
- * Deletes multiple groups for a particular user
404
- * @function deleteWatchlistGroups
405
- * @param {array[]} groups - Array of group names
406
- * @returns Promise that resolves to delete groups of watchlist \
407
- * Typical delete watchlist groups response will be a nested JSON containing below fields
408
- * - msg - string
409
- * - rearrangeTab - boolean
410
- * - sts - boolean
411
- * - updatedOn -
412
- */
413
- deleteWatchlistGroups = (groups) => {
414
- let res = {};
415
- log4js.info("Inside deleteWatchlistGroups method");
416
- const watchlistObj = new Watchlist(
417
- this.__http,
418
- this.__config,
419
- this.__constants
420
- );
421
- res = watchlistObj.deleteWatchlistGroups(groups);
422
- return res;
423
- };
424
-
425
- /**
426
- * Rename Watchlist Group
427
- * @function renameWatchlistGroup
428
- * @param {string} groupName - old group name
429
- * @param {string} newGroupName - new group name
430
- * @returns Promise that resolves to rename group of watchlist \
431
- * Typical rename watchlist group response will be a nested JSON containing below fields
432
- * - type - string
433
- * - msg - string
434
- * - rearrangeTab - boolean
435
- * - sts - boolean
436
- */
437
- renameWatchlistGroup = (groupName, newGroupName) => {
438
- let res = {};
439
- log4js.info("renameWatchlistGroup method is called.");
440
- const watchlistObj = new Watchlist(
441
- this.__http,
442
- this.__config,
443
- this.__constants
444
- );
445
- res = watchlistObj.renameWatchlistGroup(groupName, newGroupName);
446
- return res;
447
- };
448
- /**
449
- *
450
- * @param {"M1" | "M3" | "M5" | "M15" | "M30" | "H1"} interval
451
- * @param {"FUTSTK" | "FUTIDX" | "FUTCUR" | "FUTCOM" | "OPTIDX" | "OPTSTK" | "OPTCUR" | "OPTFUT" | "EQUITY" | "INDEX"} assetType
452
- * @param {string} symbol
453
- * @param {"NSE" | "BSE" | "NFO" | "NFO" | "MCX" | "NCDEX" | "INDEX"} exchangeType
454
- * @param {string} tillDate yyyy-MM-dd
455
- * @param {boolean} includeContinuousFuture
456
- * @returns
457
- */
458
- getIntradayChart = (
459
- interval,
460
- assetType,
461
- symbol,
462
- exchangeType,
463
- tillDate = null,
464
- includeContinuousFuture = false
465
- ) => {
466
- let response = {};
467
- log4js.info("getIntradayChart method is called.");
468
- const chartObj = new Chart(this.__http, this.__config, this.__constants);
469
- response = chartObj.getIntradayChartAPI(
470
- interval,
471
- assetType,
472
- symbol,
473
- exchangeType,
474
- tillDate,
475
- includeContinuousFuture
476
- );
477
-
478
- return response;
479
- };
480
-
481
- /**
482
- *
483
- * @param {"D1" | "W1" | "MN1"} interval
484
- * @param {"FUTSTK" | "FUTIDX" | "FUTCUR" | "FUTCOM" | "OPTIDX" | "OPTSTK" | "OPTCUR" | "OPTFUT" | "EQUITY" | "INDEX"} assetType
485
- * @param {string} symbol
486
- * @param {"NSE" | "BSE" | "NFO" | "NFO" | "MCX" | "NCDEX" | "INDEX"} exchangeType
487
- * @param {string} tillDate yyyy-MM-dd
488
- * @param {boolean} includeContinuousFuture
489
- * @returns
490
- */
491
- getEODChart = (
492
- interval,
493
- assetType,
494
- symbol,
495
- exchangeType,
496
- tillDate = null,
497
- includeContinuousFuture = false
498
- ) => {
499
- log4js.info("getEODChart method is called.");
500
- let response = {};
501
- const chartObj = new Chart(this.__http, this.__config, this.__constants);
502
- response = chartObj.getEODChartAPI(
503
- interval,
504
- assetType,
505
- symbol,
506
- exchangeType,
507
- tillDate,
508
- includeContinuousFuture
509
- );
510
-
511
- return response;
512
- };
513
-
514
- //Get News Categories
515
- getNewsCategories = () => {
516
- log4js.info("Inside getNewsCategories method");
517
- const liveNewsObj = new LiveNews(
518
- this.fileName,
519
- this.__http,
520
- this.__config,
521
- this.__constants
522
- );
523
- return liveNewsObj.getNewsCategories(true);
524
- };
525
-
526
- getLiveNews = async (
527
- category,
528
- searchText = "",
529
- holdings = false,
530
- pageNumber = 0
531
- ) => {
532
- log4js.info("Inside getLiveNews method");
533
- let response = {};
534
- const liveNewsObj = new LiveNews(
535
- this.fileName,
536
- this.__http,
537
- this.__config,
538
- this.__constants
539
- );
540
-
541
- const newsCategories = await liveNewsObj.getNewsCategories(false);
542
- if (newsCategories.hasOwnProperty("data")) {
543
- const data = newsCategories.data;
544
- if (
545
- data.hasOwnProperty("categories") &&
546
- data.hasOwnProperty("excAndincCategories")
547
- ) {
548
- const categories = data.categories;
549
- const excAndincCategories = data.excAndincCategories;
550
- const validateParamsResponse = validateLiveNewsParams(
551
- category,
552
- holdings,
553
- searchText,
554
- pageNumber,
555
- categories
556
- );
557
-
558
- //Validation on params
559
- if (validateParamsResponse.error) {
560
- log4js.debug(
561
- "getLiveNews params error - " + validateParamsResponse.error.details
562
- );
563
- return Promise.reject(validateParamsResponse.error.details);
564
- }
565
-
566
- //If Holdings false then call generalNewsData
567
- if (!holdings) {
568
- response = await liveNewsObj.getGeneralNewsData(
569
- category,
570
- searchText,
571
- pageNumber
572
- );
573
- } else {
574
- //If Holdings true then call equity Holdings
575
- response = await liveNewsObj.getEqHoldings(searchText, pageNumber);
576
- }
577
- //Before Return filter response
578
- return await liveNewsObj.filterLiveNewsResponse(
579
- category,
580
- excAndincCategories[category],
581
- response,
582
- holdings
583
- );
584
- }
585
- }
586
- };
587
-
588
- getResultsAndStocksNews = async (
589
- searchText = "",
590
- holdings = false,
591
- pageNumber = 0
592
- ) => {
593
- log4js.info("Inside getResultsAndStocksNews method");
594
- let response = {};
595
-
596
- //Validation on Params
597
- const validateParamsResponse = validateNewsForResultsAndStocksParams(
598
- holdings,
599
- searchText,
600
- pageNumber
601
- );
602
- if (validateParamsResponse.error) {
603
- log4js.debug(
604
- "getResultsAndStocksNews params error - " +
605
- validateParamsResponse.error.details
606
- );
607
- return Promise.reject(validateParamsResponse.error.details);
608
- }
609
-
610
- const liveNewsObj = new LiveNews(
611
- this.fileName,
612
- this.__http,
613
- this.__config,
614
- this.__constants
615
- );
616
-
617
- //If Holdings false then call generalNews for Result and STOCK_IN_NEWS
618
- if (!holdings) {
619
- response = await liveNewsObj.getNewsForResultsAndStocks(
620
- searchText,
621
- pageNumber
622
- );
623
- } else {
624
- //If Holdings true then call equity Holding
625
- response = await liveNewsObj.getEqHoldings(searchText, pageNumber);
626
- }
627
-
628
- //Filter Response before return
629
- return await liveNewsObj.filterNewsForResultsAndStocks(response, holdings);
630
- };
631
-
632
- getCorporateAction = async (symbol) => {
633
- log4js.info("Inside getCorporateAction method");
634
- const validateResponse = validateLatestCorporateActions(symbol);
635
- if (validateResponse.error) {
636
- log4js.debug(
637
- "getCorporateAction params error - " + validateResponse.error.details
638
- );
639
- return Promise.reject(validateResponse.error.details);
640
- }
641
-
642
- let response = {};
643
- const liveNewsObj = new LiveNews(
644
- this.fileName,
645
- this.__http,
646
- this.__config,
647
- this.__constants
648
- );
649
- response = await liveNewsObj.getLatestCorporateActions(symbol);
650
- return response;
651
- };
652
-
653
- /**
654
- * Get all active research calls
655
- * @async
656
- * @function getActiveResearchCalls
657
- * @param {EQ | FNO | CUR | COM} segments - Segments can be EQ | FNO | CUR | COM
658
- * @param {LONGTERM | SHORTTERM | MIDTERM} terms - Terms can be LONGTERM | SHORTTERM | MIDTERM
659
- * @param {Large | Medium | Small} marketCap - MarketCap can be Large | Medium | Small, Only For Segment "ËQ"
660
- * @returns Promise that resolves/rejects to the Get Active ResearchCalls response
661
- */
662
- getActiveResearchCalls = async (segment, term, marketCap) => {
663
- log4js.info("getActiveResearchCalls method is called.");
664
- let response = {};
665
- const researchCallsObj = new ResearchCalls(
666
- this.__http,
667
- this.__config,
668
- this.__constants
669
- );
670
-
671
- response = await researchCallsObj.getActiveResearchCalls(
672
- segment,
673
- term,
674
- marketCap
675
- );
676
- return response;
677
- };
678
-
679
- /**
680
- * Get closed research calls
681
- * @async
682
- * @function getCloseResearchCalls
683
- * @param {EQ | FNO | CUR | COM} segments - Segments can be EQ | FNO | CUR | COM
684
- * @param {LONGTERM | SHORTTERM | MIDTERM} terms - Terms can be LONGTERM | SHORTTERM | MIDTERM
685
- * @param {string} action - Action can be BUY | SELL
686
- * @param {string} fromDate - Filtering fromDate. In format : YYYY-MM-dd
687
- * @param {string} toDate - Filtering toDate. In format : YYYY-MM-dd
688
- * @param {string} recommendationType - Filtering based on recommendation type
689
- * @param {Large | Medium | Small} marketCap - MarketCap can be Large | Medium | Small, Only For Segment "ËQ"
690
- * @returns Promise that resolves/rejects to the Get Closed ResearchCalls response
691
- */
692
- getClosedResearchCalls = async (
693
- segment,
694
- term,
695
- action,
696
- fromDate,
697
- toDate,
698
- recommendationType,
699
- marketCap
700
- ) => {
701
- log4js.info("getClosedResearchCalls method is called.");
702
- let response = {};
703
- const researchCallsObj = new ResearchCalls(
704
- this.__http,
705
- this.__config,
706
- this.__constants
707
- );
708
-
709
- response = await researchCallsObj.getClosedResearchCalls(
710
- segment,
711
- term,
712
- action,
713
- fromDate,
714
- toDate,
715
- recommendationType,
716
- marketCap
717
- );
718
- return response;
719
- };
720
-
721
- /**
722
- * This method will retrieve the equity Order Book.
723
- * @returns Promise that resolves to Equity Orderbook of client \
724
- * Typical order book response will be aan array of objects containing below fields
725
- * - Symbol
726
- * - Product Type
727
- * - Order type
728
- * - Quantity
729
- * - Price
730
- * - Validity
731
- * - Order ID
732
- * - Order Status
733
- */
734
- OrderBook = () => {
735
- log4js.info("Inside OrderBook method");
736
- const accTyp = this.__constants.Data.data.lgnData.accTyp;
737
- const eqUrl =
738
- accTyp == "EQ" || accTyp == "COMEQ"
739
- ? this.__config.OrderBookURL(this.__constants.eqAccId)
740
- : undefined;
741
- const commUrl =
742
- accTyp == "CO" || accTyp == "COMEQ"
743
- ? this.__config.OrderBookURL_comm(this.__constants.coAccId, "COMFNO")
744
- : undefined;
745
- log4js.debug("OrderBook URLS - eq :" + eqUrl + " comm:" + commUrl);
746
- var result = this.__getEqCommData(eqUrl, commUrl);
747
- log4js.debug("OrderBook Result :" + JSON.stringify(result));
748
- return result;
749
- };
750
-
751
- /**
752
- * This method will retrieve the Trade Book.
753
- * @returns Promise that resolves to TradeBook of client \
754
- * Typical trade book response will be a nested JSON containing below fields
755
- * - Symbol
756
- * - Product Type
757
- * - Order type
758
- * - Quantity
759
- * - Price
760
- * - Validity
761
- * - Trade ID
762
- * - Trade Status
763
- */
764
- TradeBook = () => {
765
- log4js.info("Inside TradeBook method");
766
- const accTyp = this.__constants.Data.data.lgnData.accTyp;
767
- const eqUrl =
768
- accTyp == "EQ" || accTyp == "COMEQ"
769
- ? this.__config.TradeBookURL(this.__constants.eqAccId)
770
- : undefined;
771
- const commUrl =
772
- accTyp == "CO" || accTyp == "COMEQ"
773
- ? this.__config.TradeBookURL_comm(this.__constants.coAccId)
774
- : undefined;
775
- log4js.debug("TradeBook URLS - eq :" + eqUrl + " comm:" + commUrl);
776
- var result = this.__getEqCommData(eqUrl, commUrl);
777
- log4js.debug("TradeBook Result :" + JSON.stringify(result));
778
- return result;
779
- };
780
-
781
- /**
782
- * Net position usually is referred to in context of trades placed during the day in case of Equity, or can refer to carry forward positions in case of Derivatives, Currency and Commodity. It indicates the net obligation (either buy or sell) for the given day in a given symbol. Usually you monitor the net positions screen to track the profit or loss made from the given trades and will have options to square off your entire position and book the entire profit and loss.
783
- *
784
- * This method will retrieve the Net position.
785
- *
786
- * @returns Promise that resolves to Net position of client \
787
- * Typical trade book response will be a nested JSON containing below fields
788
- * - Symbol
789
- * - Product Type
790
- * - Order type
791
- * - Quantity
792
- * - Price
793
- * - Validity
794
- * - Trade ID
795
- * - Trade Status
796
- */
797
- NetPosition = () => {
798
- log4js.info("Inside NetPosition method");
799
- const accTyp = this.__constants.Data.data.lgnData.accTyp;
800
- const eqUrl =
801
- accTyp == "EQ" || accTyp == "COMEQ"
802
- ? this.__config.NetPositionURL(this.__constants.eqAccId)
803
- : undefined;
804
- const commUrl =
805
- accTyp == "CO" || accTyp == "COMEQ"
806
- ? this.__config.NetPositionURL_comm(this.__constants.coAccId)
807
- : undefined;
808
- log4js.debug("NetPosition URLS - eq :" + eqUrl + " comm:" + commUrl);
809
- var result = this.__getEqCommData(eqUrl, commUrl);
810
- log4js.debug("NetPosition Result :" + JSON.stringify(result));
811
- return result;
812
- };
813
-
814
- /**
815
- * Use this method to retrive the details of single order.
816
- *
817
- * Response Fields :
818
- * - Symbol
819
- * - Product Type
820
- * - Order type
821
- * - Quantity
822
- * - Price
823
- * - Validity
824
- * - Trade ID
825
- * - Trade Status
826
- * @param {string} orderId ordId from an order in OrderBook method
827
- * @returns Promise that resolves to the details of single order
828
- */
829
- OrderDetails = (orderId, Exchange) => {
830
- const validateResponse = validateOrderDetails(orderId, Exchange);
831
- if (validateResponse.error) {
832
- log4js.debug(
833
- "OrderDetails validation error -" + validateResponse.error.details
834
- );
835
- return Promise.reject(validateResponse.error.details);
836
- }
837
- log4js.info("Inside OrderDetails method");
838
- if (Exchange == "MCX" || Exchange == "NCDEX") {
839
- const url = this.__config.OrderDetailsURL_comm(
840
- this.__constants.coAccId,
841
- orderId
842
- );
843
- log4js.debug("OrderDetails URL -" + url);
844
- var result = this.__http
845
- .GetMethod(url)
846
- .then((comm) => ({ eq: "", comm }));
847
- log4js.debug("OrderDetails Result :" + JSON.stringify(result));
848
- return result;
849
- } else {
850
- const url = this.__config.OrderDetailsURL(
851
- this.__constants.eqAccId,
852
- orderId
853
- );
854
- log4js.debug("OrderDetails URL -" + url);
855
- var result = this.__http.GetMethod(url).then((eq) => ({ eq, comm: "" }));
856
- log4js.debug("OrderDetails Result :" + JSON.stringify(result));
857
- return result;
858
- }
859
- };
860
-
861
- /**
862
- * This method will retrive all the historical orders placed from `StartDate` to `EndDate`
863
- * @param {string} StartDate Start Date of Search
864
- * @param {string} EndDate End Date of Search
865
- * @return Promise that resolves/rejects to order history response
866
- */
867
- OrderHistory = (StartDate, EndDate) => {
868
- log4js.info("Inside OrderHistory method");
869
- const validateResponse = validateOrderHistory(StartDate, EndDate);
870
- if (validateResponse.error) {
871
- log4js.debug(
872
- "OrderHistory validation error -" + validateResponse.error.details
873
- );
874
- return Promise.reject(validateResponse.error.details);
875
- }
876
- const accTyp = this.__constants.Data.data.lgnData.accTyp;
877
- const eqUrl =
878
- accTyp == "EQ" || accTyp == "COMEQ"
879
- ? this.__config.OrderHistoryURL(
880
- this.__constants.eqAccId,
881
- StartDate,
882
- EndDate
883
- )
884
- : undefined;
885
- const commUrl =
886
- accTyp == "CO" || accTyp == "COMEQ"
887
- ? this.__config.OrderHistoryURL_comm(
888
- this.__constants.coAccId,
889
- StartDate,
890
- EndDate
891
- )
892
- : undefined;
893
- log4js.debug("OrderHistory URLS - eq :" + eqUrl + " comm:" + commUrl);
894
- var result = this.__getEqCommData(eqUrl, commUrl);
895
- log4js.debug("OrderHistory Result :" + JSON.stringify(result));
896
- return result;
897
- };
898
-
899
- /**
900
- * Holdings comprises of the user's portfolio of long-term equity delivery stocks. An instrument in a holding's portfolio remains there indefinitely until its sold or is delisted or changed by the exchanges. Underneath it all, instruments in the holdings reside in the user's DEMAT account, as settled by exchanges and clearing institutions.
901
- * @returns Promise that resolves to holdings of user
902
- */
903
- Holdings = () => {
904
- log4js.info("Inside Holdings method");
905
- const accTyp = this.__constants.Data.data.lgnData.accTyp;
906
- const eqUrl =
907
- accTyp == "EQ" || accTyp == "COMEQ"
908
- ? this.__config.HoldingURL(this.__constants.eqAccId)
909
- : undefined;
910
- const commUrl =
911
- accTyp == "CO" || accTyp == "COMEQ"
912
- ? this.__config.HoldingURL_comm(this.__constants.coAccId)
913
- : undefined;
914
- log4js.debug("Holdings URLS - eq :" + eqUrl + " comm:" + commUrl);
915
- var result = this.__getEqCommData(eqUrl, commUrl);
916
- log4js.debug("Holdings Result :" + JSON.stringify(result));
917
- return result;
918
- };
919
-
920
- /**
921
- * Order placement refers to the function by which you as a user can place an order to respective exchanges. Order placement allows you to set various parameters like the symbol, action (buy, sell, stop loss buy, stop loss sell), product type, validity period and few other custom parameters and then finally place the order. Any order placed will first go through a risk validation in our internal systems and will then be sent to exchange. Usually any order successfully placed will have OrderID and ExchangeOrderID fields populated. If ExchangeOrderID is blank it usually means that the order has not been sent and accepted at respective exchange.
922
- * @param {string} Trading_Symbol Trading Symbol of the Scrip
923
- * @param {string} Exchange Exchange
924
- * @param {'BUY' | 'SELL'} Action BUY | SELL
925
- * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
926
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
927
- * @param {number} Quantity Quantity of the Scrip
928
- * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
929
- * @param {number} Limit_Price Limit price of the Scrip
930
- * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
931
- * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
932
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} ProductCode CNC | MIS | NRML | MTF
933
- * @returns Promise that resolves/rejects to Place trade api response
934
- */
935
- PlaceTrade = (
936
- Trading_Symbol,
937
- Exchange,
938
- Action,
939
- Duration,
940
- Order_Type,
941
- Quantity,
942
- Streaming_Symbol,
943
- Limit_Price,
944
- Disclosed_Quantity = "0",
945
- TriggerPrice = "0",
946
- ProductCode = "CNC"
947
- ) => {
948
- log4js.info("Inside PlaceTrade method");
949
- const paramsObj = {
950
- trdSym: Trading_Symbol,
951
- exc: Exchange,
952
- action: Action,
953
- dur: Duration,
954
- ordTyp: Order_Type,
955
- qty: Quantity,
956
- sym: Streaming_Symbol,
957
- lmPrc: Limit_Price,
958
- dscQty: Disclosed_Quantity,
959
- trgPrc: TriggerPrice,
960
- prdCode: ProductCode,
961
- };
962
- const validateResponse = validatePlaceTrade(paramsObj);
963
- if (validateResponse.error) {
964
- log4js.debug(
965
- "PlaceTrade validation error -" + validateResponse.error.details
966
- );
967
- return Promise.reject(validateResponse.error.details);
968
- }
969
-
970
- const data = {
971
- trdSym: Trading_Symbol,
972
- exc: Exchange,
973
- action: Action,
974
- dur: Duration,
975
- ordTyp: Order_Type,
976
- qty: Quantity,
977
- dscQty: Disclosed_Quantity,
978
- sym: Streaming_Symbol,
979
- mktPro: "",
980
- lmPrc: Limit_Price,
981
- trgPrc: TriggerPrice,
982
- prdCode: ProductCode,
983
- posSqr: "N",
984
- minQty: "0",
985
- ordSrc: "API",
986
- vnCode: "",
987
- rmk: "",
988
- flQty: true,
989
- };
990
- log4js.debug("PlaceTrade Data :" + JSON.stringify(data));
991
- if (Exchange == "MCX" || Exchange == "NCDEX") {
992
- const url = this.__config.PlaceTradeURL_comm(this.__constants.coAccId);
993
- log4js.debug("PlaceTrade URL -" + url);
994
- var result = this.__http.PostMethod(url, data);
995
- log4js.debug("PlaceTrade Result :" + JSON.stringify(result));
996
- return result;
997
- } else {
998
- const url = this.__config.PlaceTradeURL(this.__constants.eqAccId);
999
- log4js.debug("PlaceTrade URL -" + url);
1000
- var result = this.__http.PostMethod(url, data);
1001
- log4js.debug("PlaceTrade Result :" + JSON.stringify(result));
1002
- return result;
1003
- }
1004
- };
1005
-
1006
- /**
1007
- * A Cover Order is an order type for intraday trades. A Cover Order lets you to place trades with very high leverage of up to 20 times the available limits (Cash/Stocks collateral limits)
1008
- *
1009
- * Pay a fraction of total order amount (10% or Rs. 20) to own the shares. In case it falls below the following price, sell it off to prevent me losing money from sharp price drops.
1010
- * @param {string} Trading_Symbol Trading Symbol of the Scrip
1011
- * @param {string} Exchange Exchange
1012
- * @param {'BUY' | 'SELL'} Action BUY | SELL
1013
- * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
1014
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1015
- * @param {number} Quantity Quantity of the Scrip
1016
- * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1017
- * @param {number} Limit_Price Limit price of the Scrip
1018
- * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
1019
- * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1020
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} ProductCode CNC | MIS | NRML | MTF
1021
- * @returns Promise that resolves/rejects to Place Cover Order api response
1022
- */
1023
- PlaceCoverTrade = (
1024
- Trading_Symbol,
1025
- Exchange,
1026
- Action,
1027
- Duration,
1028
- Order_Type,
1029
- Quantity,
1030
- Streaming_Symbol,
1031
- Limit_Price,
1032
- Disclosed_Quantity = "0",
1033
- TriggerPrice = "0",
1034
- ProductCode = "CNC"
1035
- ) => {
1036
- log4js.info("Inside PlaceCoverTrade method");
1037
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1038
- console.log("Operation invalid for commodities");
1039
- return Promise.reject(new Error("Operation invalid for commodities"));
1040
- }
1041
- const paramsObj = {
1042
- trdSym: Trading_Symbol,
1043
- exc: Exchange,
1044
- action: Action,
1045
- dur: Duration,
1046
- ordTyp: Order_Type,
1047
- qty: Quantity,
1048
- sym: Streaming_Symbol,
1049
- lmPrc: Limit_Price,
1050
- dscQty: Disclosed_Quantity,
1051
- trgPrc: TriggerPrice,
1052
- prdCode: ProductCode,
1053
- };
1054
- const validateResponse = validatePlaceCoverTrade(paramsObj);
1055
- if (validateResponse.error) {
1056
- log4js.debug(
1057
- "PlaceCoverTrade validation error -" + validateResponse.error.details
1058
- );
1059
- return Promise.reject(validateResponse.error.details);
1060
- }
1061
-
1062
- const data = {
1063
- trdSym: Trading_Symbol,
1064
- exc: Exchange,
1065
- action: Action,
1066
- dur: Duration,
1067
- ordTyp: Order_Type,
1068
- qty: Quantity,
1069
- dscQty: Disclosed_Quantity,
1070
- sym: Streaming_Symbol,
1071
- mktPro: "",
1072
- lmPrc: Limit_Price,
1073
- trgPrc: TriggerPrice,
1074
- prdCode: ProductCode,
1075
- posSqr: "false",
1076
- minQty: "0",
1077
- ordSrc: "API",
1078
- vnCode: "",
1079
- rmk: "",
1080
- flQty: "0",
1081
- };
1082
-
1083
- log4js.debug("PlaceCoverTrade Data :" + JSON.stringify(data));
1084
- const url = this.__config.PlaceCoverTradeURL(this.__constants.eqAccId);
1085
- log4js.debug("PlaceCoverTrade URLS -" + url);
1086
- var result = this.__http.PostMethod(url, data);
1087
- log4js.debug("PlaceCoverTrade Result :" + JSON.stringify(result));
1088
- return result;
1089
- };
1090
-
1091
- /**
1092
- * Good Till Cancel (GTC) orders refers to orders where the validity period of the order is upto execution, cancellation by user or 90 days whichever comes first. This is a validity period used when you want to fire and forget an order and is usually an order placed with a limit price.
1093
- *
1094
- * Good Till Date (GTD) orders are similar to GTC orders, however here the validity period is set by the user (max validity period of 90 days), rest of the functionality is the same, this too is a limit order.
1095
- *
1096
- * GTC order is active until the trade is executed or trader cancels the order. GTD orders remains active until a user specified date/7 days whichever is earlier or it has been filled or cancelled.
1097
- * @param {string} Trading_Symbol Trading Symbol of the Scrip
1098
- * @param {string} Exchange Exchange
1099
- * @param {'BUY' | 'SELL'} Action BUY | SELL
1100
- * @param {'GTC' | 'GTD'} Duration GTC | GTD
1101
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1102
- * @param {number} Quantity Quantity of the Scrip
1103
- * @param {number} Limit_Price Limit price of the Scrip
1104
- * @param {string} streaming_symbol companycode_exchange to be obtained from Contract file downloaded
1105
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} Product_Code CNC | MIS | NRML | MTF
1106
- * @param {string} DTDays Date for GTD Orders in dd/MM/yyyy formaat
1107
- * @returns Promise that resolves/rejects to Place GTC/GTD trade api response
1108
- */
1109
- PlaceGtcGtdTrade = (
1110
- Trading_Symbol,
1111
- Exchange,
1112
- Action,
1113
- Duration,
1114
- Order_Type,
1115
- Quantity,
1116
- Limit_Price,
1117
- streaming_symbol,
1118
- Product_Code,
1119
- DTDays
1120
- ) => {
1121
- log4js.info("Inside PlaceGtcGtdTrade method");
1122
- const paramsObj = {
1123
- trdSym: Trading_Symbol,
1124
- exc: Exchange,
1125
- action: Action,
1126
- dur: Duration,
1127
- ordTyp: Order_Type,
1128
- qty: Quantity,
1129
- lmPrc: Limit_Price,
1130
- sym: streaming_symbol,
1131
- prdCode: Product_Code,
1132
- dtDays: DTDays,
1133
- };
1134
- const validateResponse = validatePlaceGtcGtdTrade(paramsObj);
1135
- if (validateResponse.error) {
1136
- log4js.debug(
1137
- "PlaceGtcGtdTrade validation error -" + validateResponse.error.details
1138
- );
1139
- return Promise.reject(validateResponse.error.details);
1140
- }
1141
-
1142
- const data = {
1143
- trdSym: Trading_Symbol,
1144
- exc: Exchange,
1145
- action: Action,
1146
- dur: Duration,
1147
- ordTyp: Order_Type,
1148
- qty: Quantity,
1149
- lmPrc: Limit_Price,
1150
- prdCode: Product_Code,
1151
- dtDays: DTDays,
1152
- ordSrc: "API",
1153
- vnCode: "",
1154
- oprtn: "<=",
1155
- srcExp: "",
1156
- tgtId: "",
1157
- brnchNm: "",
1158
- vlDt: DTDays,
1159
- sym: streaming_symbol,
1160
- brk: "",
1161
- };
1162
- log4js.debug("PlaceGtcGtdTrade Data :" + JSON.stringify(data));
1163
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1164
- const url = this.__config.PlaceTradeURL_comm(this.__constants.coAccId);
1165
- log4js.debug("PlaceGtcGtdTrade URLS -" + url);
1166
- var result = this.__http.PostMethod(url, data);
1167
- log4js.debug("PlaceGtcGtdTrade Result :" + JSON.stringify(result));
1168
- return result;
1169
- } else {
1170
- const url = this.__config.PlaceGtcGtdTradeURL(this.__constants.eqAccId);
1171
- log4js.debug("PlaceGtcGtdTrade URLS -" + url);
1172
- var result = this.__http.PostMethod(url, data);
1173
- log4js.debug("PlaceGtcGtdTrade Result :" + JSON.stringify(result));
1174
- return result;
1175
- }
1176
- };
1177
-
1178
- /**
1179
- * Modify orders allows a user to change certain aspects of the order once it is placed. Depending on the execution state of the order (i.e. either completely open, partially open) there are various levels of modification allowed. As a user you can edit the product type, order quantity, order validity and certain other parameters. Please note that any modifications made to an order will be sent back to the risk system for validation before being submitted and there are chances that an already placed order may get rejected in case of a modification.
1180
- * @param {string} Trading_Symbol Trading Symbol of the Scrip
1181
- * @param {string} Exchange Exchange
1182
- * @param {'BUY' | 'SELL'} Action BUY | SELL
1183
- * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
1184
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1185
- * @param {number} Quantity Quantity of the Scrip
1186
- * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1187
- * @param {number} Limit_Price Limit price of the Scrip
1188
- * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
1189
- * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1190
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} ProductCode CNC | MIS | NRML | MTF
1191
- * @returns Promise that resolves/rejects to Modify Order api response
1192
- */
1193
- ModifyTrade = (
1194
- Trading_Symbol,
1195
- Exchange,
1196
- Action,
1197
- Duration,
1198
- Order_Type,
1199
- Quantity,
1200
- Streaming_Symbol,
1201
- Limit_Price,
1202
- Order_ID,
1203
- Disclosed_Quantity = "0",
1204
- TriggerPrice = "0",
1205
- ProductCode = "CNC"
1206
- ) => {
1207
- log4js.info("Inside ModifyTrade method");
1208
- const paramsObj = {
1209
- trdSym: Trading_Symbol,
1210
- exc: Exchange,
1211
- action: Action,
1212
- dur: Duration,
1213
- ordTyp: Order_Type,
1214
- qty: Quantity,
1215
- sym: Streaming_Symbol,
1216
- lmPrc: Limit_Price,
1217
- nstOID: Order_ID,
1218
- dscQty: Disclosed_Quantity,
1219
- trgPrc: TriggerPrice,
1220
- prdCode: ProductCode,
1221
- };
1222
- const validateResponse = validateModifyTrade(paramsObj);
1223
- if (validateResponse.error) {
1224
- log4js.debug(
1225
- "ModifyTrade validation error -" + validateResponse.error.details
1226
- );
1227
- return Promise.reject(validateResponse.error.details);
1228
- }
1229
- const data = {
1230
- trdSym: Trading_Symbol,
1231
- exc: Exchange,
1232
- action: Action,
1233
- dur: Duration,
1234
- flQty: "0",
1235
- ordTyp: Order_Type,
1236
- qty: Quantity,
1237
- dscQty: Disclosed_Quantity,
1238
- sym: Streaming_Symbol,
1239
- mktPro: "",
1240
- lmPrc: Limit_Price,
1241
- trgPrc: TriggerPrice,
1242
- prdCode: ProductCode,
1243
- dtDays: "",
1244
- nstOID: Order_ID,
1245
- valid: false,
1246
- };
1247
-
1248
- log4js.debug("ModifyTrade Data :" + JSON.stringify(data));
1249
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1250
- const url = this.__config.ModifyTradeURL_comm(this.__constants.coAccId);
1251
- log4js.debug("ModifyTrade URLS -" + url);
1252
- var result = this.__http.PutMethod(url, data);
1253
- log4js.debug("ModifyTrade Result :" + JSON.stringify(result));
1254
- return result;
1255
- } else {
1256
- const url = this.__config.ModifyTradeURL(this.__constants.eqAccId);
1257
- log4js.debug("ModifyTrade URLS -" + url);
1258
- var result = this.__http.PutMethod(url, data);
1259
- log4js.debug("ModifyTrade Result :" + JSON.stringify(result));
1260
- return result;
1261
- }
1262
- };
1263
-
1264
- /**
1265
- * Modify Cover Order
1266
- * @param {string} Trading_Symbol Trading Symbol of the Scrip
1267
- * @param {string} Exchange Exchange
1268
- * @param {'BUY' | 'SELL'} Action BUY | SELL
1269
- * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
1270
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1271
- * @param {number} Quantity Quantity of the Scrip
1272
- * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1273
- * @param {number} Limit_Price Limit price of the Scrip
1274
- * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
1275
- * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1276
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} ProductCode CNC | MIS | NRML | MTF
1277
- * @returns Promise that resolves/rejects to Modify Cover Order api response
1278
- */
1279
- ModifyCoverTrade = (
1280
- Trading_Symbol,
1281
- Exchange,
1282
- Action,
1283
- Duration,
1284
- Order_Type,
1285
- Quantity,
1286
- Streaming_Symbol,
1287
- Limit_Price,
1288
- Order_ID,
1289
- Disclosed_Quantity = "0",
1290
- TriggerPrice = "0",
1291
- ProductCode = "CNC"
1292
- ) => {
1293
- log4js.info("Inside ModifyCoverTrade method");
1294
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1295
- console.log("Operation invalid for commodities");
1296
- return Promise.reject(new Error("Operation invalid for commodities"));
1297
- }
1298
- const paramsObj = {
1299
- trdSym: Trading_Symbol,
1300
- exc: Exchange,
1301
- action: Action,
1302
- dur: Duration,
1303
- ordTyp: Order_Type,
1304
- qty: Quantity,
1305
- sym: Streaming_Symbol,
1306
- lmPrc: Limit_Price,
1307
- nstOID: Order_ID,
1308
- dscQty: Disclosed_Quantity,
1309
- trgPrc: TriggerPrice,
1310
- prdCode: ProductCode,
1311
- };
1312
- const validateResponse = validateModifyCoverTrade(paramsObj);
1313
- if (validateResponse.error) {
1314
- log4js.debug(
1315
- "ModifyCoverTrade validation error -" + validateResponse.error.details
1316
- );
1317
- return Promise.reject(validateResponse.error.details);
1318
- }
1319
- const data = {
1320
- trdSym: Trading_Symbol,
1321
- exc: Exchange,
1322
- action: Action,
1323
- dur: Duration,
1324
- flQty: "0",
1325
- ordTyp: Order_Type,
1326
- qty: Quantity,
1327
- dscQty: Disclosed_Quantity,
1328
- sym: Streaming_Symbol,
1329
- mktPro: "",
1330
- lmPrc: Limit_Price,
1331
- trgPrc: TriggerPrice,
1332
- prdCode: ProductCode,
1333
- dtDays: "",
1334
- nstOID: Order_ID,
1335
- };
1336
-
1337
- log4js.debug("ModifyCoverTrade Data :" + JSON.stringify(data));
1338
- const url = this.__config.ModifyCoverTradeURL(this.__constants.eqAccId);
1339
- log4js.debug("ModifyCoverTrade URLS -" + url);
1340
- var result = this.__http.PutMethod(url, data);
1341
- log4js.debug("ModifyCoverTrade Result :" + JSON.stringify(result));
1342
- return result;
1343
- };
1344
-
1345
- /**
1346
- * An order can be cancelled, as long as on order is open or pending in the system.
1347
- * @param {string} OrderId Nest OrderId
1348
- * @param {string} Exchange Exchange
1349
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1350
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} ProductCode CNC | MIS | NRML | MTF
1351
- * @returns Promise that resolves/rejects to Cancel Trade api response
1352
- */
1353
- CancelTrade = (OrderId, Exchange, Order_Type, ProductCode) => {
1354
- log4js.info("Inside CancelTrade method");
1355
- const data = {
1356
- nstOID: OrderId,
1357
- exc: Exchange,
1358
- prdCode: ProductCode,
1359
- ordTyp: Order_Type,
1360
- };
1361
- const validateResponse = validateCancelPlaceTrade(data);
1362
- if (validateResponse.error) {
1363
- log4js.debug(
1364
- "CancelTrade validation error -" + validateResponse.error.details
1365
- );
1366
- return Promise.reject(validateResponse.error.details);
1367
- }
1368
- log4js.debug("CancelTrade Data :" + JSON.stringify(data));
1369
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1370
- const url = this.__config.CancelTradeURL_comm(this.__constants.coAccId);
1371
- log4js.debug("CancelTrade URLS -" + url);
1372
- var result = this.__http.PutMethod(url, data);
1373
- log4js.debug("CancelTrade Result :" + JSON.stringify(result));
1374
- return result;
1375
- } else {
1376
- const url = this.__config.CancelTradeURL(this.__constants.eqAccId);
1377
- log4js.debug("CancelTrade URLS -" + url);
1378
- var result = this.__http.PutMethod(url, data);
1379
- log4js.debug("CancelTrade Result :" + JSON.stringify(result));
1380
- return result;
1381
- }
1382
- };
1383
-
1384
- /**
1385
- * This method will retrieve the MF Order Book.
1386
- * @param {string} fromDate From Date
1387
- * @param {string} toDate To Date
1388
- * @returns Promise that resolves to MF Order Book of client \
1389
- * Typical trade book response will be a nested JSON containing below fields
1390
- * - Symbol
1391
- * - Product Type
1392
- * - Order type
1393
- * - Quantity
1394
- * - Price
1395
- * - Validity
1396
- * - Order ID
1397
- * - Order Status
1398
- */
1399
- MFOrderBook = (fromDate, toDate) => {
1400
- log4js.info("Inside MFOrderBook method");
1401
- const validateResponse = validateMFOrderBook(fromDate, toDate);
1402
- if (validateResponse.error) {
1403
- log4js.debug(
1404
- "MFOrderBook validation error -" + validateResponse.error.details
1405
- );
1406
- return Promise.reject(validateResponse.error.details);
1407
- }
1408
- const url = this.__config.OrderBookMFURL(
1409
- this.__constants.eqAccId,
1410
- fromDate,
1411
- toDate
1412
- );
1413
- log4js.debug("MFOrderBook URLS -" + url);
1414
- var result = this.__http.GetMethod(url);
1415
- log4js.debug("MFOrderBook Result :" + JSON.stringify(result));
1416
- return result;
1417
- };
1418
-
1419
- /**
1420
- * This functionality allows you to completely exit a cover order which includes cancelling any unplaced orders and also completely squaring off any executed orders. For the orders which were executed it will usually modify the stop loss order leg and place it as a market order to ensure execution, while any non executed quantity order will get cancelled.
1421
- * @param {string} OrderId Nest OrderId
1422
- * @returns Promise that resolves/rejects to Exit Cover Trade api response
1423
- */
1424
- ExitCoverTrade = (OrderId) => {
1425
- log4js.info("Inside ExitCoverTrade method");
1426
- const validateResponse = validateExitCoverTrade(OrderId);
1427
- if (validateResponse.error) {
1428
- log4js.debug(
1429
- "ExitCoverTrade validation error -" + validateResponse.error.details
1430
- );
1431
- return Promise.reject(validateResponse.error.details);
1432
- }
1433
- const url = this.__config.ExitCoverTradeURL(this.__constants.eqAccId);
1434
- log4js.debug("ExitCoverTrade URLS -" + url);
1435
- var result = this.__http.PutMethod(url, { nstOID: OrderId });
1436
- log4js.debug("ExitCoverTrade Result :" + JSON.stringify(result));
1437
- return result;
1438
- };
1439
-
1440
- /**
1441
- * Similar to Exit Cover order the functionality will ensure that any non executed open order will be cancelled. However for any orders which are executed it will automatically cancel one of the target or stop loss legs and modify the other leg to be placed as a market order. This will ensure that any executed orders will be squared off in position terms.
1442
- * @param {string} Order_Id Mest OrderId
1443
- * @param {string} Syom_Id obtained post placing Bracket Order
1444
- * @param {string} Status Current Status of the Bracket Order
1445
- * @returns Promise that resolves/rejects to Exit Bracket Order api response
1446
- */
1447
- ExitBracketTrade = (Order_Id, Syom_Id, Status) => {
1448
- log4js.info("Inside ExitBracketTrade method");
1449
- const data = { nstOrdNo: Order_Id, syomID: Syom_Id, sts: Status };
1450
- const validateResponse = validateExitBracketTrade(data);
1451
- if (validateResponse.error) {
1452
- log4js.debug(
1453
- "ExitBracketTrade validation error -" + validateResponse.error.details
1454
- );
1455
- return Promise.reject(validateResponse.error.details);
1456
- }
1457
- log4js.debug("ExitBracketTrade Data :" + JSON.stringify(data));
1458
- const url = this.__config.ExitBracketTradeURL(this.__constants.eqAccId);
1459
- log4js.debug("ExitBracketTrade URLS -" + url);
1460
- var result = this.__http.DeleteMethod(url, data);
1461
- log4js.debug("ExitBracketTrade Result :" + JSON.stringify(result));
1462
- return result;
1463
- };
1464
-
1465
- /**
1466
- * Place Bracket Order
1467
- * @param {string} Exchange Exchange
1468
- * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1469
- * @param {string} Transaction_Type Transaction Type
1470
- * @param {number} Quantity Quantity of the Scrip
1471
- * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
1472
- * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
1473
- * @param {number} Limit_Price Limit Price of the Scrip
1474
- * @param {string} Target Absolute Target value
1475
- * @param {string} StopLoss Absolute Stop Loss value
1476
- * @param {'Y' | 'N'} Trailing_Stop_Loss Y | N
1477
- * @param {number} Trailing_Stop_Loss_Value Trailing Stop Loss value
1478
- * @returns Promise that resolves/rejects to Place Bracket Trade api response
1479
- */
1480
- PlaceBracketTrade = (
1481
- Exchange,
1482
- Streaming_Symbol,
1483
- Transaction_Type,
1484
- Quantity,
1485
- Duration,
1486
- Disclosed_Quantity,
1487
- Limit_Price,
1488
- Target,
1489
- StopLoss,
1490
- Trailing_Stop_Loss = "Y",
1491
- Trailing_Stop_Loss_Value = "1"
1492
- ) => {
1493
- log4js.info("Inside PlaceBracketTrade method");
1494
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1495
- console.log("Operation invalid for commodities");
1496
- return Promise.reject(new Error("Operation invalid for commodities"));
1497
- }
1498
- const paramsObj = {
1499
- exc: Exchange,
1500
- sym: Streaming_Symbol,
1501
- trnsTyp: Transaction_Type,
1502
- qty: Quantity,
1503
- dur: Duration,
1504
- dsQty: Disclosed_Quantity,
1505
- prc: Limit_Price,
1506
- sqOffVal: Target,
1507
- slVal: StopLoss,
1508
- trlSl: Trailing_Stop_Loss,
1509
- trlSlVal: Trailing_Stop_Loss_Value,
1510
- };
1511
- const validateResponse = validatePlaceBracketTrade(paramsObj);
1512
- if (validateResponse.error) {
1513
- log4js.debug(
1514
- "PlaceBracketTrade validation error -" + validateResponse.error.details
1515
- );
1516
- return Promise.reject(validateResponse.error.details);
1517
- }
1518
- const data = {
1519
- exc: Exchange,
1520
- sym: Streaming_Symbol,
1521
- trnsTyp: Transaction_Type,
1522
- qty: Quantity,
1523
- dur: Duration,
1524
- dsQty: Disclosed_Quantity,
1525
- prc: Limit_Price,
1526
- trdBsdOn: "LTP",
1527
- sqOffBsdOn: "Absolute",
1528
- sqOffVal: Target,
1529
- slBsdOn: "Absolute",
1530
- slVal: StopLoss,
1531
- trlSl: Trailing_Stop_Loss,
1532
- trlSlVal: Trailing_Stop_Loss_Value,
1533
- ordSrc: "API",
1534
- };
1535
-
1536
- log4js.debug("PlaceBracketTrade Data :" + JSON.stringify(data));
1537
- const url = this.__config.PlaceBracketTradeURL(this.__constants.eqAccId);
1538
- log4js.debug("PlaceBracketTrade URLS -" + url);
1539
- var result = this.__http.PostMethod(url, data);
1540
- return result;
1541
- };
1542
-
1543
- /**
1544
- * Basket order allows user to place multiple orders at one time. User can place orders for multiple scrips all at once. One just creates multiple orders for same or different securities and club these orders together to be placed in one go. This helps save time.
1545
- * @param {Array<Order>} orderlist Array of Orders to be placed
1546
- * @returns Promise that resolves/rejects to Place Basket Trade api response
1547
- */
1548
- PlaceBasketTrade = (orderlist) => {
1549
- log4js.info("Inside PlaceBasketTrade method");
1550
- const validateResponse = validatePlaceBasketTrade(orderlist);
1551
- if (validateResponse.error) {
1552
- log4js.debug(
1553
- "PlaceBasketTrade validation error -" + validateResponse.error.details
1554
- );
1555
- return Promise.reject(validateResponse.error.details);
1556
- }
1557
- let isComm = false;
1558
- const lst = [];
1559
- orderlist.forEach(({ sym, GTDDate, rmk, ...order }) => {
1560
- // remove sym, GTCDate, rmk from order if present because we don't need to pass them in api
1561
- if (order.exc == "MCX" || order.exc == "NCDEX") {
1562
- isComm = true;
1563
- return;
1564
- }
1565
- const data = { ...order, vnCode: "", rmk: "" };
1566
- lst.push(data);
1567
- });
1568
-
1569
- const fd = { ordLst: lst, ordSrc: "API" };
1570
- if (isComm) {
1571
- console.log("Basket Order not available for Commodity");
1572
- }
1573
- const url = this.__config.PlaceBasketTradeURL(this.__constants.eqAccId);
1574
- log4js.debug("PlaceBasketTrade URLS -" + url);
1575
- var result = this.__http.PostMethod(url, fd);
1576
- return result;
1577
- };
1578
-
1579
- /**
1580
- * Limits refers to the cumulative margins available in your account which can be used for trading and investing in various products. Limits is a combination of the free cash you have (i.e. un-utilized cash), cash equivalent securities (usually margin pledged securities), any money which is in transit (T1/T2 day sell transaction values) and others, all of which can be used for placing orders. Usually whenever you place an order in a given asset and product type our risk management system assesses your limits available and then lets the orders go through or blocks the orders. Limits are dynamic in nature and can be influenced by the Mark to Markets in your positions and sometimes even by the LTP of your holdings.
1581
- * @returns Promise that resolves/rejects to the Limits api response
1582
- */
1583
- Limits = () => {
1584
- log4js.info("Inside Limits method");
1585
- const accTyp = this.__constants.Data.data.lgnData.accTyp;
1586
- const eqUrl =
1587
- accTyp == "EQ" || accTyp == "COMEQ"
1588
- ? this.__config.LimitsURL(this.__constants.eqAccId)
1589
- : undefined;
1590
- const commUrl =
1591
- accTyp == "CO" || accTyp == "COMEQ"
1592
- ? this.__config.LimitsURL_comm(this.__constants.coAccId)
1593
- : undefined;
1594
- log4js.debug("Limits URLS - eq :" + eqUrl + " comm:" + commUrl);
1595
- var result = this.__getEqCommData(eqUrl, commUrl);
1596
- log4js.debug("Limits Result :" + JSON.stringify(result));
1597
- return result;
1598
- };
1599
-
1600
- /**
1601
- * Get AMO status
1602
- * @returns Promise that resolves/rejects to the Get AMO Status api response
1603
- */
1604
- GetAMOStxatus = () => {
1605
- log4js.info("Inside GetAMOStxatus method");
1606
- const accTyp = this.__constants.Data.data.lgnData.accTyp;
1607
- const eqUrl =
1608
- accTyp == "EQ" || accTyp == "COMEQ"
1609
- ? this.__config.GetAMOFlag(this.__constants.eqAccId)
1610
- : undefined;
1611
- const commUrl =
1612
- accTyp == "CO" || accTyp == "COMEQ"
1613
- ? this.__config.GetAMOFlag_comm(this.__constants.coAccId)
1614
- : undefined;
1615
- log4js.debug("GetAMOStxatus URLS - eq :" + eqUrl + " comm:" + commUrl);
1616
- var result = this.__getEqCommData(eqUrl, commUrl);
1617
- log4js.debug("GetAMOStxatus Result :" + JSON.stringify(result));
1618
- return result;
1619
- };
1620
-
1621
- /**
1622
- * After market order or AMO in short refers to orders which can be placed once the markets or exchanges are closed for trading. You can place AMO post market hours which will result in the order in question being placed automatically by 9:15 AM - 9:30 AM the next business day. AMO orders usually need to be limit orders in order to prevent inadvertent execution in case of adverse price movement in markets at beginning of day. AMO is a useful way to place your orders in case you do not have time to place orders during market hours.
1623
- * @param {string} Trading_Symbol Trading Symbol of the Scrip
1624
- * @param {string} Exchange Exchange
1625
- * @param {'BUY' | 'SELL'} Action BUY | SELL
1626
- * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
1627
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1628
- * @param {number} Quantity Quantity of the Scrip
1629
- * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1630
- * @param {number} Limit_Price Limit price of Scrip
1631
- * @param {string} Disclosed_Quantity Quantity to be disclosed while order_placement
1632
- * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1633
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} ProductCode CNC | MIS | NRML | MTF
1634
- * @returns Promise that resolves/rejects to the Place AMO Trade api response
1635
- */
1636
- PlaceAMOTrade = (
1637
- Trading_Symbol,
1638
- Exchange,
1639
- Action,
1640
- Duration,
1641
- Order_Type,
1642
- Quantity,
1643
- Streaming_Symbol,
1644
- Limit_Price,
1645
- Disclosed_Quantity = "0",
1646
- TriggerPrice = "0",
1647
- ProductCode = "CNC"
1648
- ) => {
1649
- log4js.info("Inside PlaceAMOTrade method");
1650
- const paramsObj = {
1651
- trdSym: Trading_Symbol,
1652
- exc: Exchange,
1653
- action: Action,
1654
- dur: Duration,
1655
- ordTyp: Order_Type,
1656
- qty: Quantity,
1657
- sym: Streaming_Symbol,
1658
- Limit_Price,
1659
- dscQty: Disclosed_Quantity,
1660
- trgPrc: TriggerPrice,
1661
- prdCode: ProductCode,
1662
- };
1663
- const validateResponse = validatePlaceAMOTrade(paramsObj);
1664
- if (validateResponse.error) {
1665
- log4js.debug(
1666
- "PlaceAMOTrade validation error -" + validateResponse.error.details
1667
- );
1668
- return Promise.reject(validateResponse.error.details);
1669
- }
1670
- const data = {
1671
- trdSym: Trading_Symbol,
1672
- exc: Exchange,
1673
- action: Action,
1674
- dur: Duration,
1675
- flQty: "0",
1676
- ordTyp: Order_Type,
1677
- qty: Quantity,
1678
- dscQty: Disclosed_Quantity,
1679
- sym: Streaming_Symbol,
1680
- mktPro: "",
1681
- lmPrc: Limit_Price,
1682
- trgPrc: TriggerPrice,
1683
- prdCode: ProductCode,
1684
- posSqr: "false",
1685
- minQty: "0",
1686
- ordSrc: "API",
1687
- vnCode: "",
1688
- rmk: "",
1689
- };
1690
-
1691
- log4js.debug("PlaceAMOTrade Data :" + JSON.stringify(data));
1692
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1693
- const url = this.__config.PlaceAMOTrade_comm(this.__constants.coAccId);
1694
- log4js.debug("PlaceAMOTrade URLS -" + url);
1695
- var result = this.__http.PostMethod(url, data);
1696
- log4js.debug("PlaceAMOTrade Result :" + JSON.stringify(result));
1697
- return result;
1698
- } else {
1699
- const url = this.__config.PlaceAMOTrade(this.__constants.eqAccId);
1700
- log4js.debug("PlaceAMOTrade URLS -" + url);
1701
- var result = this.__http.PostMethod(url, data);
1702
- log4js.debug("PlaceAMOTrade Result :" + JSON.stringify(result));
1703
- return result;
1704
- }
1705
- };
1706
-
1707
- /**
1708
- * Modify After Market Order
1709
- * @param {string} Trading_Symbol Trading Symbol of the Scrip
1710
- * @param {string} Exchange Exchange
1711
- * @param {'BUY' | 'SELL'} Action BUY | SELL
1712
- * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
1713
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1714
- * @param {number} Quantity Quantity of the Scrip
1715
- * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1716
- * @param {number} Limit_Price Limit price of Scrip
1717
- * @param {string} Order_ID Nest Order Id
1718
- * @param {string} Disclosed_Quantity Quantity to be disclosed while order_placement
1719
- * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1720
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} ProductCode CNC | MIS | NRML | MTF
1721
- * @returns Promise that resolves/rejects to the Place AMO Trade api response
1722
- */
1723
- ModifyAMOTrade = (
1724
- Trading_Symbol,
1725
- Exchange,
1726
- Action,
1727
- Duration,
1728
- Order_Type,
1729
- Quantity,
1730
- Streaming_Symbol,
1731
- Limit_Price,
1732
- Order_ID,
1733
- Disclosed_Quantity = "0",
1734
- TriggerPrice = "0",
1735
- ProductCode = "CNC"
1736
- ) => {
1737
- log4js.info("Inside ModifyAMOTrade method");
1738
- const paramsObj = {
1739
- trdSym: Trading_Symbol,
1740
- exc: Exchange,
1741
- action: Action,
1742
- dur: Duration,
1743
- ordTyp: Order_Type,
1744
- qty: Quantity,
1745
- sym: Streaming_Symbol,
1746
- lmPrc: Limit_Price,
1747
- nstOID: Order_ID,
1748
- dscQty: Disclosed_Quantity,
1749
- trgPrc: TriggerPrice,
1750
- prdCode: ProductCode,
1751
- };
1752
- const validateResponse = validateModifyAMOTrade(paramsObj);
1753
- if (validateResponse.error) {
1754
- log4js.debug(
1755
- "ModifyAMOTrade validation error -" + validateResponse.error.details
1756
- );
1757
- return Promise.reject(validateResponse.error.details);
1758
- }
1759
- const data = {
1760
- trdSym: Trading_Symbol,
1761
- exc: Exchange,
1762
- action: Action,
1763
- dur: Duration,
1764
- flQty: "0",
1765
- ordTyp: Order_Type,
1766
- qty: Quantity,
1767
- dscQty: Disclosed_Quantity,
1768
- sym: Streaming_Symbol,
1769
- mktPro: "",
1770
- lmPrc: Limit_Price,
1771
- trgPrc: TriggerPrice,
1772
- prdCode: ProductCode,
1773
- dtDays: "",
1774
- nstOID: Order_ID,
1775
- };
1776
-
1777
- log4js.debug("ModifyAMOTrade Data :" + JSON.stringify(data));
1778
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1779
- const url = this.__config.ModifyAMOTrade_comm(this.__constants.coAccId);
1780
- log4js.debug("ModifyAMOTrade URLS" + url);
1781
- var result = this.__http.PutMethod(url, data);
1782
- log4js.debug("ModifyAMOTrade Result :" + JSON.stringify(result));
1783
- return result;
1784
- } else {
1785
- const url = this.__config.ModifyAMOTrade(this.__constants.eqAccId);
1786
- log4js.debug("ModifyAMOTrade URLS" + url);
1787
- var result = this.__http.PutMethod(url, data);
1788
- log4js.debug("ModifyAMOTrade Result :" + JSON.stringify(result));
1789
- return result;
1790
- }
1791
- };
1792
-
1793
- /**
1794
- * Cancel After Market Order
1795
- * @param {string} OrderId Nest Order Id
1796
- * @param {string} Exchange Exchange
1797
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1798
- * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} Product_Code CNC | MIS | NRML | MTF
1799
- * @returns Promise that resolves/rejects to the Cancel AMO Trade api response
1800
- */
1801
- CancelAMOTrade = (OrderId, Exchange, Order_Type, Product_Code) => {
1802
- const data = {
1803
- nstOID: OrderId,
1804
- exc: Exchange,
1805
- prdCode: Product_Code,
1806
- ordTyp: Order_Type,
1807
- };
1808
- log4js.info("Inside CancelAMOTrade method");
1809
- const validateResponse = validateCancelAMOTrade(data);
1810
- if (validateResponse.error) {
1811
- log4js.debug(
1812
- "CancelAMOTrade validation error -" + validateResponse.error.details
1813
- );
1814
- return Promise.reject(validateResponse.error.details);
1815
- }
1816
- log4js.debug("CancelAMOTrade Data :" + JSON.stringify(data));
1817
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1818
- const url = this.__config.CancelAMOTrade_comm(this.__constants.coAccId);
1819
- log4js.debug("CancelAMOTrade URLS -" + url);
1820
- var result = this.__http.PutMethod(url, data);
1821
- log4js.debug("CancelAMOTrade Result :" + JSON.stringify(result));
1822
- return result;
1823
- } else {
1824
- const url = this.__config.CancelAMOTrade(this.__constants.eqAccId);
1825
- log4js.debug("CancelAMOTrade URLS -" + url);
1826
- var result = this.__http.PutMethod(url, data);
1827
- log4js.debug("CancelAMOTrade Result :" + JSON.stringify(result));
1828
- return result;
1829
- }
1830
- };
1831
-
1832
- /**
1833
- * Square off is a term used in intraday and simply means closing all open positions by the end of the trading day.
1834
- * @param {Array<Order>} orderlist List of orders to be Squared Off.
1835
- * @returns Promise that resolves/rejects to the Position Square Off api response
1836
- */
1837
- PositionSquareOff = (orderlist) => {
1838
- const validateResponse = validatePositionSquareOff(orderlist);
1839
- if (validateResponse.error) {
1840
- log4js.debug(
1841
- "PositionSquareOff validation error -" + validateResponse.error.details
1842
- );
1843
- return Promise.reject(validateResponse.error.details);
1844
- }
1845
- const lstEq = [];
1846
- const lstComm = [];
1847
- log4js.info("Inside PositionSquareOff method");
1848
- orderlist.forEach(({ GTDDate, rmk, ...order }) => {
1849
- order["flQty"] = "0";
1850
- order["mktPro"] = "";
1851
- order["dtDays"] = "";
1852
- order["posSqr"] = "true";
1853
- order["minQty"] = "0";
1854
- order["ordSrc"] = "API";
1855
- order["vnCode"] = "";
1856
- order["rmk"] = "";
1857
- const data = order;
1858
- // remove GTCDate, rmk from order if present because we don't need to pass them in api
1859
- // const data = (data = {
1860
- // ...order,
1861
- // flQty: "0",
1862
- // mktPro: "",
1863
- // dtDays: "",
1864
- // posSqr: "true",
1865
- // minQty: "0",
1866
- // ordSrc: "API",
1867
- // vnCode: "",
1868
- // rmk: ""
1869
- // });
1870
-
1871
- order.exc == "MCX" || order.exc == "NCDEX"
1872
- ? lstComm.push(data)
1873
- : lstEq.push(data);
1874
- });
1875
-
1876
- const postEq = lstEq.length
1877
- ? this.__http.PostMethod(
1878
- this.__config.PositionSqOffURL(this.__constants.eqAccId),
1879
- lstEq
1880
- )
1881
- : undefined;
1882
- const postComm = lstComm.length
1883
- ? this.__http.PostMethod(
1884
- this.__config.PositionSqOffURL(this.__constants.coAccId),
1885
- lstComm
1886
- )
1887
- : undefined;
1888
- var result = Promise.all([postEq, postComm]).then(([eq, comm]) => ({
1889
- eq,
1890
- comm,
1891
- }));
1892
- log4js.debug("PositionSquareOff Result :" + JSON.stringify(result));
1893
- return result;
1894
- };
1895
-
1896
- /**
1897
- * Converts your holding position from MIS to CNC and vice-versa
1898
- * @param {string} Order_Id Nest Order Id
1899
- * @param {string} Fill_Id Fill Id of the trade obtained from Trade API
1900
- * @param {string} New_Product_Code New Product code of the trade
1901
- * @param {string} Old_Product_Code Existing Product code of the trade
1902
- * @param {string} Exchange Exchange
1903
- * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} orderType LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1904
- * @returns Promise that resolves/rejects to the Convert Position api response
1905
- */
1906
- ConvertPosition = (
1907
- Order_Id,
1908
- Fill_Id,
1909
- New_Product_Code,
1910
- Old_Product_Code,
1911
- Exchange,
1912
- orderType
1913
- ) => {
1914
- log4js.info("Inside ConvertPosition method");
1915
-
1916
- if (Exchange == "MCX" || Exchange == "NCDEX") {
1917
- const data = {
1918
- nstOID: Order_Id,
1919
- flID: Fill_Id,
1920
- prdCodeCh: New_Product_Code,
1921
- prdCode: Old_Product_Code,
1922
- exc: Exchange,
1923
- ordTyp: orderType,
1924
- };
1925
- log4js.debug("ConvertPosition Data :" + JSON.stringify(data));
1926
- const validateResponse = validateConvertPosition(data);
1927
- if (validateResponse.error) {
1928
- log4js.debug(
1929
- "ConvertPosition validation error -" + validateResponse.error.details
1930
- );
1931
- return Promise.reject(validateResponse.error.details);
1932
- }
1933
- const url = this.__config.ConvertPositionURL_comm(
1934
- this.__constants.coAccId
1935
- );
1936
- log4js.debug("ConvertPosition URLS:" + url);
1937
- var result = this.__http.PutMethod(url, data);
1938
- log4js.debug("ConvertPosition Result :" + JSON.stringify(result));
1939
- return result;
1940
- } else {
1941
- const data = {
1942
- nstOID: Order_Id,
1943
- flID: Fill_Id,
1944
- prdCodeCh: New_Product_Code,
1945
- prdCode: Old_Product_Code,
1946
- };
1947
- log4js.debug("ConvertPosition Data :" + JSON.stringify(data));
1948
- const url = this.__config.ConvertPositionURL(this.__constants.eqAccId);
1949
- log4js.debug("ConvertPosition URLS:" + url);
1950
- var result = this.__http.PutMethod(url, data);
1951
- log4js.debug("ConvertPosition Result :" + JSON.stringify(result));
1952
- return result;
1953
- }
1954
- };
1955
-
1956
- // MF Methods start //
1957
-
1958
- /**
1959
- *
1960
- * @param {string} Token
1961
- * @param {string} ISIN_Code
1962
- * @param {string} Transaction_Type
1963
- * @param {string} Client_Code
1964
- * @param {number} Quantity
1965
- * @param {string} Amount
1966
- * @param {string} ReInv_Flag
1967
- * @param {string} Folio_Number
1968
- * @param {string} Scheme_Name
1969
- * @param {string} Start_Date
1970
- * @param {string} End_Date
1971
- * @param {string} SIP_Frequency
1972
- * @param {string} Generate_First_Order_Today
1973
- * @param {string} Scheme_Plan
1974
- * @param {string} Scheme_Code
1975
- * @returns Promise that resolves/rejects to the Place MF api response
1976
- */
1977
- PlaceMF = (
1978
- Token,
1979
- ISIN_Code,
1980
- Transaction_Type,
1981
- Client_Code,
1982
- Quantity,
1983
- Amount,
1984
- ReInv_Flag,
1985
- Folio_Number,
1986
- Scheme_Name,
1987
- Start_Date,
1988
- End_Date,
1989
- SIP_Frequency,
1990
- Generate_First_Order_Today,
1991
- Scheme_Plan,
1992
- Scheme_Code
1993
- ) => {
1994
- const paramsObj = {
1995
- token: Token,
1996
- isin: ISIN_Code,
1997
- txnTyp: Transaction_Type,
1998
- clientCode: Client_Code,
1999
- qty: Quantity,
2000
- amt: Amount,
2001
- reInvFlg: ReInv_Flag,
2002
- folioNo: Folio_Number,
2003
- schemeName: Scheme_Name,
2004
- strtDt: Start_Date,
2005
- endDt: End_Date,
2006
- sipFrq: SIP_Frequency,
2007
- gfot: Generate_First_Order_Today,
2008
- schemePlan: Scheme_Plan,
2009
- schemeCode: Scheme_Code,
2010
- };
2011
- log4js.info("Inside PlaceMF method");
2012
- const validateResponse = validatePlaceMF(paramsObj);
2013
- if (validateResponse.error) {
2014
- log4js.debug(
2015
- "PlaceMF validation error -" + validateResponse.error.details
2016
- );
2017
- return Promise.reject(validateResponse.error.details);
2018
- }
2019
- const data = {
2020
- currentOrdSts: "",
2021
- token: Token,
2022
- isin: ISIN_Code,
2023
- txnTyp: Transaction_Type,
2024
- clientCode: Client_Code,
2025
- qty: Quantity,
2026
- amt: Amount,
2027
- reInvFlg: ReInv_Flag,
2028
- reqstdBy: this.__constants.eqAccId,
2029
- folioNo: Folio_Number,
2030
- ordTyp: "FRESH",
2031
- txnId: "0",
2032
- schemeName: Scheme_Name,
2033
- rmrk: "",
2034
- mnRdmFlg: "",
2035
- ordSrc: "API",
2036
- strtDy: "1",
2037
- strtDt: Start_Date,
2038
- endDt: End_Date,
2039
- sipFrq: SIP_Frequency,
2040
- gfot: Generate_First_Order_Today,
2041
- tnr: "",
2042
- mdtId: "",
2043
- sipregno: "",
2044
- siporderno: "",
2045
- schemePlan: Scheme_Plan,
2046
- schemeCode: Scheme_Code,
2047
- euinnumber: "",
2048
- dpc: "Y",
2049
- closeAccountFlag: "N",
2050
- kycflag: "1",
2051
- euinflag: "N",
2052
- physicalFlag: "D",
2053
- };
2054
-
2055
- log4js.debug("PlaceMF Data :" + JSON.stringify(data));
2056
- const url = this.__config.PlaceMFURL(this.__constants.eqAccId);
2057
- log4js.debug("PlaceMF URLS -" + url);
2058
- var result = this.__http.PostMethod(url, data);
2059
- log4js.debug("PlaceMF Result :" + JSON.stringify(result));
2060
- return result;
2061
- };
2062
-
2063
- /**
2064
- * Certain attributes of a MF order may be modified., as long as on order is open or pending in the system.
2065
- * @param {string} Token
2066
- * @param {string} ISIN_Code
2067
- * @param {string} Transaction_Type
2068
- * @param {string} Client_Code
2069
- * @param {number} Quantity
2070
- * @param {string} Amount
2071
- * @param {string} ReInv_Flag
2072
- * @param {string} Folio_Number
2073
- * @param {string} Scheme_Name
2074
- * @param {string} Start_Date
2075
- * @param {string} End_Date
2076
- * @param {string} SIP_Frequency
2077
- * @param {string} Generate_First_Order_Today
2078
- * @param {string} Scheme_Plan
2079
- * @param {string} Scheme_Code
2080
- * @param {string} Transaction_Id
2081
- * @returns Promise that resolves/rejects to the Modify MF api response
2082
- */
2083
- ModifyMF = (
2084
- Token,
2085
- ISIN_Code,
2086
- Transaction_Type,
2087
- Client_Code,
2088
- Quantity,
2089
- Amount,
2090
- ReInv_Flag,
2091
- Folio_Number,
2092
- Scheme_Name,
2093
- Start_Date,
2094
- End_Date,
2095
- SIP_Frequency,
2096
- Generate_First_Order_Today,
2097
- Scheme_Plan,
2098
- Scheme_Code,
2099
- Transaction_Id
2100
- ) => {
2101
- log4js.info("Inside ModifyMF method");
2102
- const paramsObj = {
2103
- token: Token,
2104
- isin: ISIN_Code,
2105
- txnTyp: Transaction_Type,
2106
- clientCode: Client_Code,
2107
- qty: Quantity,
2108
- amt: Amount,
2109
- reInvFlg: ReInv_Flag,
2110
- folioNo: Folio_Number,
2111
- schemeName: Scheme_Name,
2112
- strtDt: Start_Date,
2113
- endDt: End_Date,
2114
- sipFrq: SIP_Frequency,
2115
- gfot: Generate_First_Order_Today,
2116
- schemePlan: Scheme_Plan,
2117
- schemeCode: Scheme_Code,
2118
- txnId: Transaction_Id,
2119
- };
2120
- const validateResponse = validateModifyMF(paramsObj);
2121
- if (validateResponse.error) {
2122
- log4js.debug(
2123
- "ModifyMF validation error -" + validateResponse.error.details
2124
- );
2125
- return Promise.reject(validateResponse.error.details);
2126
- }
2127
- const data = {
2128
- currentOrdSts: "ACCEPTED",
2129
- token: Token,
2130
- isin: ISIN_Code,
2131
- txnTyp: Transaction_Type,
2132
- clientCode: Client_Code,
2133
- qty: Quantity,
2134
- amt: Amount,
2135
- reInvFlg: ReInv_Flag,
2136
- reqstdBy: this.__constants.eqAccId,
2137
- folioNo: Folio_Number,
2138
- ordTyp: "MODIFY",
2139
- txnId: Transaction_Id,
2140
- schemeName: Scheme_Name,
2141
- rmrk: "",
2142
- mnRdmFlg: "",
2143
- ordSrc: "API",
2144
- strtDy: "1",
2145
- strtDt: Start_Date,
2146
- endDt: End_Date,
2147
- sipFrq: SIP_Frequency,
2148
- gfot: Generate_First_Order_Today,
2149
- tnr: "",
2150
- mdtId: "",
2151
- sipregno: "",
2152
- siporderno: "",
2153
- schemePlan: Scheme_Plan,
2154
- schemeCode: Scheme_Code,
2155
- euinnumber: "",
2156
- dpc: "Y",
2157
- closeAccountFlag: "N",
2158
- kycflag: "1",
2159
- euinflag: "N",
2160
- physicalFlag: "D",
2161
- };
2162
-
2163
- log4js.debug("ModifyMF Data :" + JSON.stringify(data));
2164
- const url = this.__config.ModifyMFURL(this.__constants.eqAccId);
2165
- log4js.debug("ModifyMF URLS -" + url);
2166
- var result = this.__http.PutMethod(url, data);
2167
- log4js.debug("ModifyMF Result :" + JSON.stringify(result));
2168
- return result;
2169
- };
2170
-
2171
- /**
2172
- *
2173
- * @param {string} Token
2174
- * @param {string} ISIN_Code
2175
- * @param {string} Transaction_Type
2176
- * @param {string} Client_Code
2177
- * @param {number} Quantity
2178
- * @param {string} Amount
2179
- * @param {string} ReInv_Flag
2180
- * @param {string} Folio_Number
2181
- * @param {string} Scheme_Name
2182
- * @param {string} Start_Date
2183
- * @param {string} End_Date
2184
- * @param {string} SIP_Frequency
2185
- * @param {string} Generate_First_Order_Today
2186
- * @param {string} Scheme_Plan
2187
- * @param {string} Scheme_Code
2188
- * @param {string} Transaction_Id
2189
- * @returns Promise that resolves/rejects to Cancel MF api response
2190
- */
2191
- CancelMF = (
2192
- Token,
2193
- ISIN_Code,
2194
- Transaction_Type,
2195
- Client_Code,
2196
- Quantity,
2197
- Amount,
2198
- ReInv_Flag,
2199
- Folio_Number,
2200
- Scheme_Name,
2201
- Start_Date,
2202
- End_Date,
2203
- SIP_Frequency,
2204
- Generate_First_Order_Today,
2205
- Scheme_Plan,
2206
- Scheme_Code,
2207
- Transaction_Id
2208
- ) => {
2209
- log4js.info("Inside CancelMF method");
2210
- const paramsObj = {
2211
- token: Token,
2212
- isin: ISIN_Code,
2213
- txnTyp: Transaction_Type,
2214
- clientCode: Client_Code,
2215
- qty: Quantity,
2216
- amt: Amount,
2217
- reInvFlg: ReInv_Flag,
2218
- folioNo: Folio_Number,
2219
- schemeName: Scheme_Name,
2220
- strtDt: Start_Date,
2221
- endDt: End_Date,
2222
- sipFrq: SIP_Frequency,
2223
- gfot: Generate_First_Order_Today,
2224
- schemePlan: Scheme_Plan,
2225
- schemeCode: Scheme_Code,
2226
- txnId: Transaction_Id,
2227
- };
2228
- const validateResponse = validateCancelMF(paramsObj);
2229
- if (validateResponse.error) {
2230
- log4js.debug(
2231
- "CancelMF validation error -" + validateResponse.error.details
2232
- );
2233
- return Promise.reject(validateResponse.error.details);
2234
- }
2235
- const data = {
2236
- currentOrdSts: "ACCEPTED",
2237
- token: Token,
2238
- isin: ISIN_Code,
2239
- txnTyp: Transaction_Type,
2240
- clientCode: Client_Code,
2241
- qty: Quantity,
2242
- amt: Amount,
2243
- reInvFlg: ReInv_Flag,
2244
- reqstdBy: this.__constants.eqAccId,
2245
- folioNo: Folio_Number,
2246
- ordTyp: "CANCEL",
2247
- txnId: Transaction_Id,
2248
- schemeName: Scheme_Name,
2249
- rmrk: "",
2250
- mnRdmFlg: "",
2251
- ordSrc: "API",
2252
- strtDy: "1",
2253
- strtDt: Start_Date,
2254
- endDt: End_Date,
2255
- sipFrq: SIP_Frequency,
2256
- gfot: Generate_First_Order_Today,
2257
- tnr: "",
2258
- mdtId: "",
2259
- sipregno: "",
2260
- siporderno: "",
2261
- schemePlan: Scheme_Plan,
2262
- schemeCode: Scheme_Code,
2263
- euinnumber: "",
2264
- dpc: "Y",
2265
- closeAccountFlag: "N",
2266
- kycflag: "1",
2267
- euinflag: "N",
2268
- physicalFlag: "D",
2269
- };
2270
-
2271
- log4js.debug("CancelMF Data :" + JSON.stringify(data));
2272
- const url = this.__config.CancelMFURL(this.__constants.eqAccId);
2273
- log4js.debug("CancelMF URLS -" + url);
2274
- var result = this.__http.PutMethod(url, data);
2275
- log4js.debug("CancelMF Result :" + JSON.stringify(result));
2276
- return result;
2277
- };
2278
-
2279
- /**
2280
- *
2281
- * @returns Promise that resolves/rejects to Holdings MF api response
2282
- */
2283
- HoldingsMF = () => {
2284
- log4js.info("Inside HoldingsMF method");
2285
- const url = this.__config.HoldingsMFURL(this.__constants.eqAccId);
2286
- log4js.debug("HoldingsMF URLS -" + url);
2287
- var result = this.__http.GetMethod(url);
2288
- log4js.debug("HoldingsMF Result :" + JSON.stringify(result));
2289
- return result;
2290
- };
2291
-
2292
- // MF Methods end //
2293
-
2294
- /**
2295
- * Login function
2296
- * @param {string} source apiKey provided by APIConnect
2297
- * @param {string} password password provided by APIConnect
2298
- * @returns Promise \
2299
- * if resolved, then returns object in the form of `{msg: string, success: boolean}` \
2300
- * if rejected, returns error
2301
- */
2302
- __Login = function (source, password) {
2303
- let url = this.__config.LoginURL(source);
2304
- return this.__http
2305
- .PostMethod(url, { pwd: password })
2306
- .then((res) => {
2307
- if (res.msg) {
2308
- this.__constants.VendorSession = res.msg;
2309
- return res;
2310
- } else {
2311
- res.msg = "Login: " + res.error.errMsg;
2312
- throw res;
2313
- }
2314
- })
2315
- .catch((err) => {
2316
- //console.log("Error while Loging");
2317
- throw err;
2318
- });
2319
- };
2320
-
2321
- /**
2322
- * Second stage of login. Gets the login data of user
2323
- * @param {string} reqId Token collected after redirection from login
2324
- * @returns response of login
2325
- */
2326
- __Token = function (reqId) {
2327
- let url = this.__config.TokenURL();
2328
- return this.__http
2329
- .PostMethod(url, { reqId: reqId }, false)
2330
- .then((res) => {
2331
- // store data in constants
2332
- this.__constants.Data = res;
2333
- if (res.data.lgnData.accTyp == "EQ") {
2334
- this.__constants.eqAccId = res.data.lgnData.accs.eqAccID;
2335
- } else if (res.data.lgnData.accTyp == "CO") {
2336
- this.__constants.coAccId = res.data.lgnData.accs.coAccID;
2337
- } else if (res.data.lgnData.accTyp == "COMEQ") {
2338
- this.__constants.eqAccId = res.data.lgnData.accs.eqAccID;
2339
- this.__constants.coAccId = res.data.lgnData.accs.coAccID;
2340
- }
2341
- this.__constants.JSession = res.data.auth;
2342
- return res;
2343
- })
2344
- .then((res) => {
2345
- // store data in ${this.fileName} file
2346
- return new Promise((resolve, reject) => {
2347
- fs.writeFile(
2348
- this.fileName,
2349
- JSON.stringify({
2350
- vt: this.__constants.VendorSession,
2351
- auth: this.__constants.JSession,
2352
- eqaccid: this.__constants.eqAccId,
2353
- coaccid: this.__constants.coAccId,
2354
- data: this.__constants.Data,
2355
- appidkey: this.__constants.AppIdKey,
2356
- }),
2357
- (err) => {
2358
- if (err) {
2359
- reject(err);
2360
- return;
2361
- }
2362
-
2363
- resolve(res);
2364
- }
2365
- );
2366
- });
2367
- })
2368
- .catch((err) => {
2369
- if (!err.error) {
2370
- console.log("Error not defined", err);
2371
- } else {
2372
- err.msg = "ReqId: " + err.error.errMsg;
2373
- }
2374
- throw err;
2375
- });
2376
- };
2377
-
2378
- Logout = () => {
2379
- function deleteReadme(res) {
2380
- if (res != "") {
2381
- try {
2382
- fs.unlinkSync(this.fileName);
2383
- } catch {
2384
- } finally {
2385
- this.__constants.Data = "";
2386
- return res;
2387
- }
2388
- }
2389
- }
2390
-
2391
- if (this.__constants.Data.data.lgnData.accTyp == "CO") {
2392
- const url = this.__config.LogoutURL(this.__constants.coAccId);
2393
- return this.__http.PutMethod(url, {}).then(deleteReadme);
2394
- } else if (this.__constants.Data.data.lgnData.accTyp == "EQ") {
2395
- // same for both EQ and COMEQ
2396
- const url = this.__config.LogoutURL(this.__constants.eqAccId);
2397
- return this.__http.PutMethod(url, {}).then(deleteReadme);
2398
- }
2399
- };
2400
-
2401
- __getEqCommData(eqUrl, commUrl) {
2402
- // call api and convert the result into this format
2403
- // {eq: equityData, comm: commodityData}
2404
- if (this.__constants.Data.data.lgnData.accTyp == "EQ") {
2405
- return this.__http.GetMethod(eqUrl).then((eq) => ({ eq, comm: "" }));
2406
- }
2407
-
2408
- if (this.__constants.Data.data.lgnData.accTyp == "CO") {
2409
- return this.__http.GetMethod(commUrl).then((comm) => ({ eq: "", comm }));
2410
- }
2411
-
2412
- if (this.__constants.Data.data.lgnData.accTyp == "COMEQ") {
2413
- return Promise.all([
2414
- this.__http.GetMethod(eqUrl),
2415
- this.__http.GetMethod(commUrl),
2416
- ]).then(([eq, comm]) => {
2417
- return { eq, comm };
2418
- });
2419
- }
2420
- }
2421
- }
2422
-
2423
- APIConnect.prototype.__constants = new __Constants();
2424
- APIConnect.prototype.__config = new __Config();
2425
- APIConnect.prototype.__http = new __Http(
2426
- APIConnect.prototype.__constants,
2427
- APIConnect.prototype.__config.baseurl
2428
- );
2429
-
2430
- module.exports = { APIConnect };
1
+ const fs = require("fs");
2
+ const readline = require("readline");
3
+ const log4js = require("./logger.js");
4
+ const Order = require("./order");
5
+ const Chart = require("./chart");
6
+ const LiveNews = require("./liveNews");
7
+ const Watchlist = require("./watchlist");
8
+ const ResearchCalls = require("./researchCalls");
9
+ const __Constants = require("./apiUtils");
10
+ const __Config = require("./config");
11
+ const __Http = require("./http");
12
+ const pkgJson = require("../package.json");
13
+ const Feed = require("./feed/feed");
14
+ const QuotesFeed = require("./feed/quotesFeed");
15
+ const OrdersFeed = require("./feed/ordersFeed");
16
+ const LiveNewsFeed = require("./feed/liveNewsFeed");
17
+
18
+ const {
19
+ validatePlaceTrade,
20
+ validateModifyTrade,
21
+ validateCancelPlaceTrade,
22
+ validatePlaceGtcGtdTrade,
23
+ validatePlaceAMOTrade,
24
+ validateModifyAMOTrade,
25
+ validateCancelAMOTrade,
26
+ validateConvertPosition,
27
+ validatePlaceMF,
28
+ validateModifyMF,
29
+ validateCancelMF,
30
+ validatePlaceBracketTrade,
31
+ validateExitBracketTrade,
32
+ validateOrderDetails,
33
+ validateOrderHistory,
34
+ validatePositionSquareOff,
35
+ validateMFOrderBook,
36
+ validateGetAMOStxatus,
37
+ validateConvertPositionEQ,
38
+ } = require("../validations/apiConnectValidator");
39
+
40
+ const {
41
+ validateLiveNewsParams,
42
+ validateNewsForResultsAndStocksParams,
43
+ validateLatestCorporateActions,
44
+ } = require("../validations/liveNewsValidator");
45
+ class APIConnect {
46
+ /**
47
+ * This is **APIConnect** class. Please initialise single instance of this per `api_key`.
48
+ * @param {string} apiKey API key provided by APIConnect
49
+ * @param {string} password Password provided by APIConnect
50
+ * @param {string} reqId Token to be collected post redirection from Login URL using APIConnect credentials
51
+ * @param {string} downloadContract If this is set to `True` then It will download all the contracts and return the records in dictionary `instruments`
52
+ */
53
+ constructor(apiKey, password, reqId, downloadContract) {
54
+ this.version = pkgJson.version;
55
+ this.downloadContract = downloadContract;
56
+ this.instruments = [];
57
+ this.mfInstruments = [];
58
+ this.__constants.ApiKey = apiKey;
59
+ this.apiKey = apiKey;
60
+ this.password = password;
61
+ this.reqId = reqId;
62
+ this.fileName = "data_" + apiKey + ".txt";
63
+ this.__http.fileName = this.fileName;
64
+ this.feedObject = new Feed();
65
+ this.excsAndprdDpNm = [];
66
+ }
67
+
68
+ /**
69
+ * Login with the given user and initialize all the properties
70
+ * @returns Promise that resolves when everything is setup and rejects when there is an error
71
+ */
72
+ Init = () => {
73
+ log4js.info("IN INIT");
74
+ return new Promise((resolve, reject) => {
75
+ let count = 0;
76
+ const checkDone = (res) => {
77
+ count = count - 1;
78
+ if (count == 0) {
79
+ resolve(res);
80
+ }
81
+ };
82
+ const readFilePromise = new Promise((resolve, reject) => {
83
+ fs.readFile(this.fileName, "utf8", (err, data) => {
84
+ if (err) {
85
+ //var promises=[]
86
+ // if file doesn't exist, then generate it
87
+ // these two functions will fill the __constants and generate ${fileName}
88
+ // promises.push(this.__GenerateVendorSession(this.apiKey, this.password, this.reqId));
89
+ // promises.push(this.__GetAuthorization(this.reqId));
90
+ count++;
91
+ // Promise.all(promises).then(checkDone()).catch(reject());
92
+ this.__GenerateVendorSession(this.apiKey, this.password, this.reqId)
93
+ .then((res) => {
94
+ this.__GetAuthorization(this.reqId)
95
+ .then((res) => {
96
+ checkDone(res);
97
+ resolve(true);
98
+ })
99
+ .catch((err) => reject(err));
100
+ })
101
+ .catch((err) => reject(err));
102
+ } else {
103
+ const j = JSON.parse(data);
104
+ this.__constants.VendorSession = j.vt;
105
+ this.__constants.JSession = j.auth;
106
+ this.__constants.eqAccId = j.eqaccid;
107
+ this.__constants.coAccId = j.coaccid;
108
+ this.__constants.Data = j.data;
109
+ this.__constants.AppIdKey = j.appidkey;
110
+ this.__constants.profileId = j.data.data.lgnData.accs.prfId;
111
+ this.__constants.prds = j.data.data.lgnData.prds;
112
+ this.excsAndprdDpNm = this.__constants.getProductsAndExchange(
113
+ this.__constants.prds
114
+ );
115
+ count++;
116
+ checkDone();
117
+ resolve(true);
118
+ }
119
+ });
120
+ });
121
+
122
+ // Check if ${fileName} exists
123
+ readFilePromise
124
+ .then((res) => {
125
+ count++;
126
+ this.__CheckUpdate().then(checkDone).catch(reject);
127
+ this.excsAndprdDpNm = this.__constants.getProductsAndExchange(
128
+ this.__constants.prds
129
+ );
130
+ this.__Instruments()
131
+ .then(async (res) => {
132
+ //console.log("instrument then");
133
+ checkDone(res);
134
+ })
135
+ .catch((err) => reject(err));
136
+ })
137
+ .catch((err) => {
138
+ delete this.feedObject;
139
+ reject(err)
140
+ });
141
+ });
142
+ };
143
+
144
+ /**
145
+ * Download the contract files and place the scrips in iterable format
146
+ */
147
+ __Instruments = () => {
148
+ return new Promise((resolve, reject) => {
149
+ if (this.downloadContract) {
150
+ const readInstruments = this.__http
151
+ .GetZipFileMethod(this.__config.EquityContractURL, "instruments.csv")
152
+ .then(() => this.__readCsv("instruments.csv", this.instruments));
153
+
154
+ const readMfInstruments = this.__http
155
+ .GetZipFileMethod(this.__config.MFContractURL, "mfInstruments.csv")
156
+ .then(() => this.__readCsv("mfInstruments.csv", this.mfInstruments));
157
+
158
+ Promise.all([readInstruments, readMfInstruments])
159
+ .then(resolve)
160
+ .catch(reject);
161
+ } else {
162
+ resolve();
163
+ }
164
+ });
165
+ };
166
+
167
+ __readCsv = (fileName, inst) => {
168
+ return new Promise((resolve, reject) => {
169
+ try {
170
+ const readInterface = readline.createInterface({
171
+ input: fs.createReadStream(fileName),
172
+ });
173
+
174
+ let keys;
175
+
176
+ readInterface.on("line", (line) => {
177
+ if (keys) {
178
+ const rowParts = line.split(",");
179
+ const row = {};
180
+ keys.forEach((key, i) => (row[key] = rowParts[i]));
181
+ inst.push(row);
182
+ } else {
183
+ keys = line.split(",");
184
+ }
185
+ });
186
+
187
+ readInterface.on("close", resolve);
188
+ } catch (e) {
189
+ reject(e);
190
+ }
191
+ });
192
+ };
193
+
194
+ __CheckUpdate = () => {
195
+ let url = this.__config.CheckUpdateURl();
196
+ return this.__http
197
+ .PostMethod(url, { lib: "EAC_NODE", vsn: this.version })
198
+ .then((res) => {
199
+ if (res.data.sts) {
200
+ if (res.data.msg === "MANDATORY") {
201
+ console.log(
202
+ "Mandatory Update. New version " +
203
+ res.data.vsn +
204
+ ". Update to new version to continue."
205
+ );
206
+ process.exit();
207
+ } else if (res.data.msg === "OPTIONAL") {
208
+ console.log(
209
+ "New version " +
210
+ res.data.vsn +
211
+ " is available. Stay up to date for better experience"
212
+ );
213
+ }
214
+ return;
215
+ } else {
216
+ throw res;
217
+ }
218
+ })
219
+ };
220
+
221
+ /**
222
+ * Get LiveNewsStreaming Object
223
+ * @function initLiveNewsStreaming
224
+ * @returns LiveNewsStreaming Object, using this object you can call subsribe() and unsubsribe() methods.
225
+ */
226
+ initLiveNewsStreaming = () => {
227
+ let liveNewsFeedObj = {};
228
+ try {
229
+ liveNewsFeedObj = new LiveNewsFeed(this.feedObject);
230
+ } catch (error) {
231
+ console.log(error);
232
+ }
233
+ return liveNewsFeedObj;
234
+ };
235
+
236
+ /**
237
+ * Get QuotesStreaming Object
238
+ * @function initQuotesStreaming
239
+ * @returns QuotesStreaming Object, using this object you can call subsribe() and unsubsribe() methods.
240
+ */
241
+ initQuotesStreaming = () => {
242
+ let quoteFeedObj = {};
243
+ try {
244
+ quoteFeedObj = new QuotesFeed(this.feedObject);
245
+ } catch (error) {
246
+ console.log(error);
247
+ }
248
+ return quoteFeedObj;
249
+ };
250
+
251
+ /**
252
+ * Get OrdersStreaming Object
253
+ * @function initOrdersStreaming
254
+ * @param {string} accountId - accid Customer Account ID
255
+ * @param {string} userId - User ID
256
+ * @returns OrdersStreaming Object, using this object you can call subsribe() and unsubsribe() methods.
257
+ */
258
+ initOrdersStreaming = (accountId, userId) => {
259
+ let orderFeedObj = {};
260
+ try {
261
+ orderFeedObj = new OrdersFeed(this.feedObject, accountId, userId);
262
+ } catch (error) {
263
+ console.log(error);
264
+ }
265
+ return orderFeedObj;
266
+ };
267
+
268
+ /**
269
+ * Get Login info
270
+ * @returns Login info
271
+ */
272
+ GetLoginData = () => {
273
+ return this.__constants.Data;
274
+ };
275
+
276
+ /**
277
+ * Generate Vendor Session
278
+ * @param {string} apiKey Key provided by APIConnect
279
+ * @param {string} password Password provided by APIConnect
280
+ * @returns Promise \
281
+ * if resolved, then returns object in the form of `{msg: string, success: boolean}` \
282
+ * if rejected, returns error
283
+ */
284
+ __GenerateVendorSession = (apiKey, password) => {
285
+ return this.__Login(apiKey, password);
286
+ };
287
+
288
+ /**
289
+ * Get Login Info
290
+ * @param {string} reqId Request ID generated during redirection to a url
291
+ */
292
+ __GetAuthorization = (reqId) => {
293
+ return this.__Token(reqId);
294
+ };
295
+
296
+ /**
297
+ * This method will retrieve watchlist for a particular client.
298
+ * @function getWatchlistGroups
299
+ * @returns Promise that resolves to Watchlist Groups of client \
300
+ * Typical watchlist response will be a nested JSON containing below fields
301
+ * - defGr - Defined groups for all users ex: My Positions,Strategies etc
302
+ * - usrGr - List of User Defined Groups
303
+ * - idxGr - List of Indices Groups
304
+ * - usrTbs - List of User Tabs
305
+ */
306
+ getWatchlistGroups = () => {
307
+ let res = {};
308
+ log4js.info("Inside getWatchlistGroup method");
309
+ const watchlistObj = new Watchlist(
310
+ this.__http,
311
+ this.__config,
312
+ this.__constants
313
+ );
314
+ res = watchlistObj.getWatchlistGroups();
315
+ return res;
316
+ };
317
+
318
+ /**
319
+ * Get Scrips details of a watchlist
320
+ * @function getWatchlistScrips
321
+ * @param {string} groupName Watchlist name of getGroups response
322
+ * @returns Promise that resolves to Scrips details of watchlist \
323
+ * Typical watchlist scrips response will be a nested JSON containing below fields
324
+ * - syLst - Scrips list
325
+ */
326
+ getWatchlistScrips = (groupName) => {
327
+ let res = {};
328
+ log4js.info("Inside getWatchlistScrips method");
329
+ const watchlistObj = new Watchlist(
330
+ this.__http,
331
+ this.__config,
332
+ this.__constants
333
+ );
334
+ res = watchlistObj.getWatchlistScrips(groupName);
335
+ return res;
336
+ };
337
+
338
+ /**
339
+ * Create new group for a particular client
340
+ * @param {string} groupName - Watchlist Name
341
+ * @param {array[]} symLst - Symbol List
342
+ * @returns Promise that resolves to create new group of watchlist \
343
+ * Typical create new group response will be a nested JSON containing below fields
344
+ * - sts - status
345
+ * - msg - message
346
+ * - rearrangeTab
347
+ * - updatedOn - created time of group(Unix Timestamp)
348
+ */
349
+ createWatchlistGroup = (groupName, symLst) => {
350
+ let res = {};
351
+ log4js.info("Inside createWatchlistGroup method");
352
+ const watchlistObj = new Watchlist(
353
+ this.__http,
354
+ this.__config,
355
+ this.__constants
356
+ );
357
+ res = watchlistObj.createWatchlistGroup(groupName, symLst);
358
+ return res;
359
+ };
360
+
361
+ /**
362
+ * Add Symbol in group of watchlist for a particular client
363
+ * @function addSymbolWatchlist
364
+ * @param {string} groupName - Watchlist Name
365
+ * @param {array[]} symLst - Array of symbols
366
+ * @returns Promise that resolves to add symbol in group of watchlist \
367
+ * Typical add new symbol in watchlist group response will be a nested JSON containing below fields
368
+ * - type - string
369
+ * - msg - string
370
+ * - rearrangeTab - boolean
371
+ * - sts - boolean
372
+ * - updatedOn - number(unix timeStamp)
373
+ *
374
+ */
375
+ addSymbolWatchlist = (groupName, symLst) => {
376
+ let res = {};
377
+ log4js.info("Inside addSymbolWatchlist method");
378
+ const watchlistObj = new Watchlist(
379
+ this.__http,
380
+ this.__config,
381
+ this.__constants
382
+ );
383
+ res = watchlistObj.addSymbolWatchlist(groupName, symLst);
384
+ return res;
385
+ };
386
+
387
+ /**
388
+ * Delete Symbol in group of watchlist for a particular client
389
+ * @function deleteSymbolWatchlist
390
+ * @param {string} groupName
391
+ * @param {array[]} symLst
392
+ * @returns Promise that resolves to delete symbol in group of watchlist \
393
+ * Typical delet symbol of watchlist response will be a nested JSON containing below fields
394
+ * - type - string
395
+ * - msg - string
396
+ * - rearrangeTab - boolean
397
+ * - sts - boolean
398
+ */
399
+ deleteSymbolWatchlist = (groupName, symLst) => {
400
+ let res = {};
401
+ log4js.info("Inside deleteSymbolWatchlist method");
402
+ const watchlistObj = new Watchlist(
403
+ this.__http,
404
+ this.__config,
405
+ this.__constants
406
+ );
407
+ res = watchlistObj.deleteSymbolWatchlist(groupName, symLst);
408
+ return res;
409
+ };
410
+
411
+ /**
412
+ * Deletes multiple groups for a particular user
413
+ * @function deleteWatchlistGroups
414
+ * @param {array[]} groups - Array of group names
415
+ * @returns Promise that resolves to delete groups of watchlist \
416
+ * Typical delete watchlist groups response will be a nested JSON containing below fields
417
+ * - msg - string
418
+ * - rearrangeTab - boolean
419
+ * - sts - boolean
420
+ * - updatedOn -
421
+ */
422
+ deleteWatchlistGroups = (groups) => {
423
+ let res = {};
424
+ log4js.info("Inside deleteWatchlistGroups method");
425
+ const watchlistObj = new Watchlist(
426
+ this.__http,
427
+ this.__config,
428
+ this.__constants
429
+ );
430
+ res = watchlistObj.deleteWatchlistGroups(groups);
431
+ return res;
432
+ };
433
+
434
+ /**
435
+ * Rename Watchlist Group
436
+ * @function renameWatchlistGroup
437
+ * @param {string} groupName - old group name
438
+ * @param {string} newGroupName - new group name
439
+ * @returns Promise that resolves to rename group of watchlist \
440
+ * Typical rename watchlist group response will be a nested JSON containing below fields
441
+ * - type - string
442
+ * - msg - string
443
+ * - rearrangeTab - boolean
444
+ * - sts - boolean
445
+ */
446
+ renameWatchlistGroup = (groupName, newGroupName) => {
447
+ let res = {};
448
+ log4js.info("renameWatchlistGroup method is called.");
449
+ const watchlistObj = new Watchlist(
450
+ this.__http,
451
+ this.__config,
452
+ this.__constants
453
+ );
454
+ res = watchlistObj.renameWatchlistGroup(groupName, newGroupName);
455
+ return res;
456
+ };
457
+ /**
458
+ *
459
+ * @param {"M1" | "M3" | "M5" | "M15" | "M30" | "H1"} interval
460
+ * @param {"FUTSTK" | "FUTIDX" | "FUTCUR" | "FUTCOM" | "OPTIDX" | "OPTSTK" | "OPTCUR" | "OPTFUT" | "EQUITY" | "INDEX"} assetType
461
+ * @param {string} symbol
462
+ * @param {"NSE" | "BSE" | "NFO" | "NFO" | "MCX" | "NCDEX" | "INDEX"} exchangeType
463
+ * @param {string} tillDate yyyy-MM-dd
464
+ * @param {boolean} includeContinuousFuture
465
+ * @returns
466
+ */
467
+ getIntradayChart = (
468
+ interval,
469
+ assetType,
470
+ symbol,
471
+ exchangeType,
472
+ tillDate = null,
473
+ includeContinuousFuture = false
474
+ ) => {
475
+ let response = {};
476
+ log4js.info("getIntradayChart method is called.");
477
+ const chartObj = new Chart(this.__http, this.__config, this.__constants);
478
+ response = chartObj.getIntradayChartAPI(
479
+ interval,
480
+ assetType,
481
+ symbol,
482
+ exchangeType,
483
+ tillDate,
484
+ includeContinuousFuture
485
+ );
486
+
487
+ return response;
488
+ };
489
+
490
+ /**
491
+ *
492
+ * @param {"D1" | "W1" | "MN1"} interval
493
+ * @param {"FUTSTK" | "FUTIDX" | "FUTCUR" | "FUTCOM" | "OPTIDX" | "OPTSTK" | "OPTCUR" | "OPTFUT" | "EQUITY" | "INDEX"} assetType
494
+ * @param {string} symbol
495
+ * @param {"NSE" | "BSE" | "NFO" | "NFO" | "MCX" | "NCDEX" | "INDEX"} exchangeType
496
+ * @param {string} tillDate yyyy-MM-dd
497
+ * @param {boolean} includeContinuousFuture
498
+ * @returns
499
+ */
500
+ getEODChart = (
501
+ interval,
502
+ assetType,
503
+ symbol,
504
+ exchangeType,
505
+ tillDate = null,
506
+ includeContinuousFuture = false
507
+ ) => {
508
+ log4js.info("getEODChart method is called.");
509
+ let response = {};
510
+ const chartObj = new Chart(this.__http, this.__config, this.__constants);
511
+ response = chartObj.getEODChartAPI(
512
+ interval,
513
+ assetType,
514
+ symbol,
515
+ exchangeType,
516
+ tillDate,
517
+ includeContinuousFuture
518
+ );
519
+
520
+ return response;
521
+ };
522
+
523
+ //Get News Categories
524
+ getNewsCategories = () => {
525
+ log4js.info("Inside getNewsCategories method");
526
+ const liveNewsObj = new LiveNews(
527
+ this.fileName,
528
+ this.__http,
529
+ this.__config,
530
+ this.__constants
531
+ );
532
+ return liveNewsObj.getNewsCategories(true);
533
+ };
534
+
535
+ getLiveNews = async (
536
+ category,
537
+ searchText = "",
538
+ holdings = false,
539
+ pageNumber = 0
540
+ ) => {
541
+ log4js.info("Inside getLiveNews method");
542
+ let response = {};
543
+ const liveNewsObj = new LiveNews(
544
+ this.fileName,
545
+ this.__http,
546
+ this.__config,
547
+ this.__constants
548
+ );
549
+
550
+ const newsCategories = await liveNewsObj.getNewsCategories(false);
551
+ if (newsCategories.hasOwnProperty("data")) {
552
+ const data = newsCategories.data;
553
+ if (
554
+ data.hasOwnProperty("categories") &&
555
+ data.hasOwnProperty("excAndincCategories")
556
+ ) {
557
+ const categories = data.categories;
558
+ const excAndincCategories = data.excAndincCategories;
559
+ const validateParamsResponse = validateLiveNewsParams(
560
+ category,
561
+ holdings,
562
+ searchText,
563
+ pageNumber,
564
+ categories
565
+ );
566
+
567
+ //Validation on params
568
+ if (validateParamsResponse.error) {
569
+ log4js.debug(
570
+ "getLiveNews params error - " + validateParamsResponse.error.details
571
+ );
572
+ return Promise.reject(validateParamsResponse.error.details);
573
+ }
574
+
575
+ //If Holdings false then call generalNewsData
576
+ if (!holdings) {
577
+ response = await liveNewsObj.getGeneralNewsData(
578
+ category,
579
+ searchText,
580
+ pageNumber
581
+ );
582
+ } else {
583
+ //If Holdings true then call equity Holdings
584
+ response = await liveNewsObj.getEqHoldings(searchText, pageNumber);
585
+ }
586
+ //Before Return filter response
587
+ return await liveNewsObj.filterLiveNewsResponse(
588
+ category,
589
+ excAndincCategories[category],
590
+ response,
591
+ holdings
592
+ );
593
+ }
594
+ }
595
+ };
596
+
597
+ getResultsAndStocksNews = async (
598
+ searchText = "",
599
+ holdings = false,
600
+ pageNumber = 0
601
+ ) => {
602
+ log4js.info("Inside getResultsAndStocksNews method");
603
+ let response = {};
604
+
605
+ //Validation on Params
606
+ const validateParamsResponse = validateNewsForResultsAndStocksParams(
607
+ holdings,
608
+ searchText,
609
+ pageNumber
610
+ );
611
+ if (validateParamsResponse.error) {
612
+ log4js.debug(
613
+ "getResultsAndStocksNews params error - " +
614
+ validateParamsResponse.error.details
615
+ );
616
+ return Promise.reject(validateParamsResponse.error.details);
617
+ }
618
+
619
+ const liveNewsObj = new LiveNews(
620
+ this.fileName,
621
+ this.__http,
622
+ this.__config,
623
+ this.__constants
624
+ );
625
+
626
+ //If Holdings false then call generalNews for Result and STOCK_IN_NEWS
627
+ if (!holdings) {
628
+ response = await liveNewsObj.getNewsForResultsAndStocks(
629
+ searchText,
630
+ pageNumber
631
+ );
632
+ } else {
633
+ //If Holdings true then call equity Holding
634
+ response = await liveNewsObj.getEqHoldings(searchText, pageNumber);
635
+ }
636
+
637
+ //Filter Response before return
638
+ return await liveNewsObj.filterNewsForResultsAndStocks(response, holdings);
639
+ };
640
+
641
+ getCorporateAction = async (symbol) => {
642
+ log4js.info("Inside getCorporateAction method");
643
+ const validateResponse = validateLatestCorporateActions(symbol);
644
+ if (validateResponse.error) {
645
+ log4js.debug(
646
+ "getCorporateAction params error - " + validateResponse.error.details
647
+ );
648
+ return Promise.reject(validateResponse.error.details);
649
+ }
650
+
651
+ let response = {};
652
+ const liveNewsObj = new LiveNews(
653
+ this.fileName,
654
+ this.__http,
655
+ this.__config,
656
+ this.__constants
657
+ );
658
+ response = await liveNewsObj.getLatestCorporateActions(symbol);
659
+ return response;
660
+ };
661
+
662
+ /**
663
+ * Get all active research calls
664
+ * @async
665
+ * @function getActiveResearchCalls
666
+ * @param {EQ | FNO | CUR | COM} segments - Segments can be EQ | FNO | CUR | COM
667
+ * @param {LONGTERM | SHORTTERM | MIDTERM} terms - Terms can be LONGTERM | SHORTTERM | MIDTERM
668
+ * @param {Large | Medium | Small} marketCap - MarketCap can be Large | Medium | Small, Only For Segment "ËQ"
669
+ * @returns Promise that resolves/rejects to the Get Active ResearchCalls response
670
+ */
671
+ getActiveResearchCalls = async (segment, term, marketCap) => {
672
+ log4js.info("getActiveResearchCalls method is called.");
673
+ let response = {};
674
+ const researchCallsObj = new ResearchCalls(
675
+ this.__http,
676
+ this.__config,
677
+ this.__constants
678
+ );
679
+
680
+ response = await researchCallsObj.getActiveResearchCalls(
681
+ segment,
682
+ term,
683
+ marketCap
684
+ );
685
+ return response;
686
+ };
687
+
688
+ /**
689
+ * Get closed research calls
690
+ * @async
691
+ * @function getCloseResearchCalls
692
+ * @param {EQ | FNO | CUR | COM} segments - Segments can be EQ | FNO | CUR | COM
693
+ * @param {LONGTERM | SHORTTERM | MIDTERM} terms - Terms can be LONGTERM | SHORTTERM | MIDTERM
694
+ * @param {string} action - Action can be BUY | SELL
695
+ * @param {string} fromDate - Filtering fromDate. In format : YYYY-MM-dd
696
+ * @param {string} toDate - Filtering toDate. In format : YYYY-MM-dd
697
+ * @param {string} recommendationType - Filtering based on recommendation type
698
+ * @param {Large | Medium | Small} marketCap - MarketCap can be Large | Medium | Small, Only For Segment "ËQ"
699
+ * @returns Promise that resolves/rejects to the Get Closed ResearchCalls response
700
+ */
701
+ getClosedResearchCalls = async (
702
+ segment,
703
+ term,
704
+ action,
705
+ fromDate,
706
+ toDate,
707
+ recommendationType,
708
+ marketCap
709
+ ) => {
710
+ log4js.info("getClosedResearchCalls method is called.");
711
+ let response = {};
712
+ const researchCallsObj = new ResearchCalls(
713
+ this.__http,
714
+ this.__config,
715
+ this.__constants
716
+ );
717
+
718
+ response = await researchCallsObj.getClosedResearchCalls(
719
+ segment,
720
+ term,
721
+ action,
722
+ fromDate,
723
+ toDate,
724
+ recommendationType,
725
+ marketCap
726
+ );
727
+ return response;
728
+ };
729
+
730
+ /**
731
+ * This method will retrieve the equity Order Book.
732
+ * @returns Promise that resolves to Equity Orderbook of client \
733
+ * Typical order book response will be aan array of objects containing below fields
734
+ * - Symbol
735
+ * - Product Type
736
+ * - Order type
737
+ * - Quantity
738
+ * - Price
739
+ * - Validity
740
+ * - Order ID
741
+ * - Order Status
742
+ */
743
+ OrderBook = () => {
744
+ log4js.info("Inside OrderBook method");
745
+ const accTyp = this.__constants.Data.data.lgnData.accTyp;
746
+ const eqUrl =
747
+ accTyp == "EQ" || accTyp == "COMEQ"
748
+ ? this.__config.OrderBookURL(this.__constants.eqAccId)
749
+ : undefined;
750
+ const commUrl =
751
+ accTyp == "CO" || accTyp == "COMEQ"
752
+ ? this.__config.OrderBookURL_comm(this.__constants.coAccId, "COMFNO")
753
+ : undefined;
754
+ log4js.debug("OrderBook URLS - eq :" + eqUrl + " comm:" + commUrl);
755
+ var result = this.__getEqCommData(eqUrl, commUrl);
756
+ log4js.debug("OrderBook Result :" + JSON.stringify(result));
757
+ return result;
758
+ };
759
+
760
+ /**
761
+ * This method will retrieve the Trade Book.
762
+ * @returns Promise that resolves to TradeBook of client \
763
+ * Typical trade book response will be a nested JSON containing below fields
764
+ * - Symbol
765
+ * - Product Type
766
+ * - Order type
767
+ * - Quantity
768
+ * - Price
769
+ * - Validity
770
+ * - Trade ID
771
+ * - Trade Status
772
+ */
773
+ TradeBook = () => {
774
+ log4js.info("Inside TradeBook method");
775
+ const accTyp = this.__constants.Data.data.lgnData.accTyp;
776
+ const eqUrl =
777
+ accTyp == "EQ" || accTyp == "COMEQ"
778
+ ? this.__config.TradeBookURL(this.__constants.eqAccId)
779
+ : undefined;
780
+ const commUrl =
781
+ accTyp == "CO" || accTyp == "COMEQ"
782
+ ? this.__config.TradeBookURL_comm(this.__constants.coAccId)
783
+ : undefined;
784
+ log4js.debug("TradeBook URLS - eq :" + eqUrl + " comm:" + commUrl);
785
+ var result = this.__getEqCommData(eqUrl, commUrl);
786
+ log4js.debug("TradeBook Result :" + JSON.stringify(result));
787
+ return result;
788
+ };
789
+
790
+ /**
791
+ * Net position usually is referred to in context of trades placed during the day in case of Equity, or can refer to carry forward positions in case of Derivatives, Currency and Commodity. It indicates the net obligation (either buy or sell) for the given day in a given symbol. Usually you monitor the net positions screen to track the profit or loss made from the given trades and will have options to square off your entire position and book the entire profit and loss.
792
+ *
793
+ * This method will retrieve the Net position.
794
+ *
795
+ * @returns Promise that resolves to Net position of client \
796
+ * Typical trade book response will be a nested JSON containing below fields
797
+ * - Symbol
798
+ * - Product Type
799
+ * - Order type
800
+ * - Quantity
801
+ * - Price
802
+ * - Validity
803
+ * - Trade ID
804
+ * - Trade Status
805
+ */
806
+ NetPosition = () => {
807
+ log4js.info("Inside NetPosition method");
808
+ const accTyp = this.__constants.Data.data.lgnData.accTyp;
809
+ const eqUrl =
810
+ accTyp == "EQ" || accTyp == "COMEQ"
811
+ ? this.__config.NetPositionURL(this.__constants.eqAccId)
812
+ : undefined;
813
+ const commUrl =
814
+ accTyp == "CO" || accTyp == "COMEQ"
815
+ ? this.__config.NetPositionURL_comm(this.__constants.coAccId)
816
+ : undefined;
817
+ log4js.debug("NetPosition URLS - eq :" + eqUrl + " comm:" + commUrl);
818
+ var result = this.__getEqCommData(eqUrl, commUrl);
819
+ log4js.debug("NetPosition Result :" + JSON.stringify(result));
820
+ return result;
821
+ };
822
+
823
+ /**
824
+ * Use this method to retrive the details of single order.
825
+ *
826
+ * Response Fields :
827
+ * - Symbol
828
+ * - Product Type
829
+ * - Order type
830
+ * - Quantity
831
+ * - Price
832
+ * - Validity
833
+ * - Trade ID
834
+ * - Trade Status
835
+ * @param {string} orderId ordId from an order in OrderBook method
836
+ * @returns Promise that resolves to the details of single order
837
+ */
838
+ OrderDetails = (orderId, Exchange) => {
839
+ const validateResponse = validateOrderDetails(
840
+ orderId,
841
+ Exchange,
842
+ this.excsAndprdDpNm
843
+ );
844
+ if (validateResponse.error) {
845
+ log4js.debug(
846
+ "OrderDetails validation error -" + validateResponse.error.details
847
+ );
848
+ return Promise.reject(validateResponse.error.details);
849
+ }
850
+ log4js.info("Inside OrderDetails method");
851
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
852
+ const url = this.__config.OrderDetailsURL_comm(
853
+ this.__constants.coAccId,
854
+ orderId
855
+ );
856
+ log4js.debug("OrderDetails URL -" + url);
857
+ var result = this.__http
858
+ .GetMethod(url)
859
+ .then((comm) => ({ eq: "", comm }));
860
+ log4js.debug("OrderDetails Result :" + JSON.stringify(result));
861
+ return result;
862
+ } else {
863
+ const url = this.__config.OrderDetailsURL(
864
+ this.__constants.eqAccId,
865
+ orderId
866
+ );
867
+ log4js.debug("OrderDetails URL -" + url);
868
+ var result = this.__http.GetMethod(url).then((eq) => ({ eq, comm: "" }));
869
+ log4js.debug("OrderDetails Result :" + JSON.stringify(result));
870
+ return result;
871
+ }
872
+ };
873
+
874
+ /**
875
+ * This method will retrive all the historical orders placed from `StartDate` to `EndDate`
876
+ * @param {string} StartDate Start Date of Search
877
+ * @param {string} EndDate End Date of Search
878
+ * @return Promise that resolves/rejects to order history response
879
+ */
880
+ OrderHistory = (StartDate, EndDate) => {
881
+ log4js.info("Inside OrderHistory method");
882
+ const validateResponse = validateOrderHistory(StartDate, EndDate);
883
+ if (validateResponse.error) {
884
+ log4js.debug(
885
+ "OrderHistory validation error -" + validateResponse.error.details
886
+ );
887
+ return Promise.reject(validateResponse.error.details);
888
+ }
889
+ const accTyp = this.__constants.Data.data.lgnData.accTyp;
890
+ const eqUrl =
891
+ accTyp == "EQ" || accTyp == "COMEQ"
892
+ ? this.__config.OrderHistoryURL(
893
+ this.__constants.eqAccId,
894
+ StartDate,
895
+ EndDate
896
+ )
897
+ : undefined;
898
+ const commUrl =
899
+ accTyp == "CO" || accTyp == "COMEQ"
900
+ ? this.__config.OrderHistoryURL_comm(
901
+ this.__constants.coAccId,
902
+ StartDate,
903
+ EndDate
904
+ )
905
+ : undefined;
906
+ log4js.debug("OrderHistory URLS - eq :" + eqUrl + " comm:" + commUrl);
907
+ var result = this.__getEqCommData(eqUrl, commUrl);
908
+ log4js.debug("OrderHistory Result :" + JSON.stringify(result));
909
+ return result;
910
+ };
911
+
912
+ /**
913
+ * Holdings comprises of the user's portfolio of long-term equity delivery stocks. An instrument in a holding's portfolio remains there indefinitely until its sold or is delisted or changed by the exchanges. Underneath it all, instruments in the holdings reside in the user's DEMAT account, as settled by exchanges and clearing institutions.
914
+ * @returns Promise that resolves to holdings of user
915
+ */
916
+ Holdings = () => {
917
+ log4js.info("Inside Holdings method");
918
+ const accTyp = this.__constants.Data.data.lgnData.accTyp;
919
+ const eqUrl =
920
+ accTyp == "EQ" || accTyp == "COMEQ"
921
+ ? this.__config.HoldingURL(this.__constants.eqAccId)
922
+ : undefined;
923
+ const commUrl =
924
+ accTyp == "CO" || accTyp == "COMEQ"
925
+ ? this.__config.HoldingURL_comm(this.__constants.coAccId)
926
+ : undefined;
927
+ log4js.debug("Holdings URLS - eq :" + eqUrl + " comm:" + commUrl);
928
+ var result = this.__getEqCommData(eqUrl, commUrl);
929
+ log4js.debug("Holdings Result :" + JSON.stringify(result));
930
+ return result;
931
+ };
932
+
933
+ /**
934
+ * Order placement refers to the function by which you as a user can place an order to respective exchanges. Order placement allows you to set various parameters like the symbol, action (buy, sell, stop loss buy, stop loss sell), product type, validity period and few other custom parameters and then finally place the order. Any order placed will first go through a risk validation in our internal systems and will then be sent to exchange. Usually any order successfully placed will have OrderID and ExchangeOrderID fields populated. If ExchangeOrderID is blank it usually means that the order has not been sent and accepted at respective exchange.
935
+ * @param {string} Trading_Symbol Trading Symbol of the Scrip
936
+ * @param {string} Exchange Exchange
937
+ * @param {string} Action BUY | SELL
938
+ * @param {string} Duration DAY | IOC | EOS(for BSE)
939
+ * @param {string} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
940
+ * @param {number} Quantity Quantity of the Scrip
941
+ * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
942
+ * @param {number} Limit_Price Limit price of the Scrip
943
+ * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
944
+ * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
945
+ * @param {string} ProductCode CNC | MIS | NRML | MTF
946
+ * @returns Promise that resolves/rejects to Place trade api response
947
+ */
948
+ PlaceTrade = (
949
+ Trading_Symbol,
950
+ Exchange,
951
+ Action,
952
+ Duration,
953
+ Order_Type,
954
+ Quantity,
955
+ Streaming_Symbol,
956
+ Limit_Price,
957
+ Disclosed_Quantity = "0",
958
+ TriggerPrice = "0",
959
+ ProductCode
960
+ ) => {
961
+ log4js.info("Inside PlaceTrade method");
962
+
963
+ let paramsObj = {
964
+ trdSym: Trading_Symbol,
965
+ exc: Exchange,
966
+ action: Action,
967
+ dur: Duration,
968
+ ordTyp: Order_Type,
969
+ qty: Quantity,
970
+ sym: Streaming_Symbol,
971
+ lmPrc: Limit_Price,
972
+ dscQty: Disclosed_Quantity,
973
+ trgPrc: TriggerPrice,
974
+ prdCode: ProductCode,
975
+ };
976
+ const validateResponse = validatePlaceTrade(paramsObj, this.excsAndprdDpNm);
977
+ if (validateResponse.error) {
978
+ log4js.debug(
979
+ "PlaceTrade validation error -" + validateResponse.error.details
980
+ );
981
+ return Promise.reject(validateResponse.error.details);
982
+ }
983
+
984
+ const data = {
985
+ trdSym: Trading_Symbol,
986
+ exc: Exchange,
987
+ action: Action,
988
+ dur: Duration,
989
+ ordTyp: Order_Type,
990
+ qty: Quantity,
991
+ dscQty: Disclosed_Quantity,
992
+ sym: Streaming_Symbol,
993
+ mktPro: "",
994
+ lmPrc: Limit_Price,
995
+ trgPrc: TriggerPrice,
996
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, ProductCode),
997
+ posSqr: "N",
998
+ minQty: "0",
999
+ ordSrc: "API",
1000
+ vnCode: "",
1001
+ rmk: "",
1002
+ flQty: true,
1003
+ };
1004
+ log4js.debug("PlaceTrade Data :" + JSON.stringify(data));
1005
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1006
+ const url = this.__config.PlaceTradeURL_comm(this.__constants.coAccId);
1007
+ log4js.debug("PlaceTrade URL -" + url);
1008
+ var result = this.__http.PostMethod(url, data);
1009
+ log4js.debug("PlaceTrade Result :" + JSON.stringify(result));
1010
+ return result;
1011
+ } else {
1012
+ const url = this.__config.PlaceTradeURL(this.__constants.eqAccId);
1013
+ log4js.debug("PlaceTrade URL -" + url);
1014
+ var result = this.__http.PostMethod(url, data);
1015
+ log4js.debug("PlaceTrade Result :" + JSON.stringify(result));
1016
+ return result;
1017
+ }
1018
+ };
1019
+
1020
+
1021
+ /**
1022
+ * Good Till Cancel (GTC) orders refers to orders where the validity period of the order is upto execution, cancellation by user or 90 days whichever comes first. This is a validity period used when you want to fire and forget an order and is usually an order placed with a limit price.
1023
+ *
1024
+ * Good Till Date (GTD) orders are similar to GTC orders, however here the validity period is set by the user (max validity period of 90 days), rest of the functionality is the same, this too is a limit order.
1025
+ *
1026
+ * GTC order is active until the trade is executed or trader cancels the order. GTD orders remains active until a user specified date/7 days whichever is earlier or it has been filled or cancelled.
1027
+ * @param {string} Trading_Symbol Trading Symbol of the Scrip
1028
+ * @param {string} Exchange Exchange
1029
+ * @param {string} Action BUY | SELL
1030
+ * @param {string} Duration GTC | GTD
1031
+ * @param {string} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1032
+ * @param {number} Quantity Quantity of the Scrip
1033
+ * @param {number} Limit_Price Limit price of the Scrip
1034
+ * @param {string} streaming_symbol companycode_exchange to be obtained from Contract file downloaded
1035
+ * @param {string} Product_Code CNC | MIS | NRML | MTF
1036
+ * @param {string} DTDays Date for GTD Orders in dd/MM/yyyy formaat
1037
+ * @returns Promise that resolves/rejects to Place GTC/GTD trade api response
1038
+ */
1039
+ PlaceGtcGtdTrade = (
1040
+ Trading_Symbol,
1041
+ Exchange,
1042
+ Action,
1043
+ Duration,
1044
+ Order_Type,
1045
+ Quantity,
1046
+ Limit_Price,
1047
+ streaming_symbol,
1048
+ Product_Code,
1049
+ DTDays
1050
+ ) => {
1051
+ log4js.info("Inside PlaceGtcGtdTrade method");
1052
+ const paramsObj = {
1053
+ trdSym: Trading_Symbol,
1054
+ exc: Exchange,
1055
+ action: Action,
1056
+ dur: Duration,
1057
+ ordTyp: Order_Type,
1058
+ qty: Quantity,
1059
+ lmPrc: Limit_Price,
1060
+ sym: streaming_symbol,
1061
+ prdCode: Product_Code,
1062
+ dtDays: DTDays,
1063
+ };
1064
+ const validateResponse = validatePlaceGtcGtdTrade(
1065
+ paramsObj,
1066
+ this.excsAndprdDpNm
1067
+ );
1068
+ if (validateResponse.error) {
1069
+ log4js.debug(
1070
+ "PlaceGtcGtdTrade validation error -" + validateResponse.error.details
1071
+ );
1072
+ return Promise.reject(validateResponse.error.details);
1073
+ }
1074
+
1075
+ const data = {
1076
+ trdSym: Trading_Symbol,
1077
+ exc: Exchange,
1078
+ action: Action,
1079
+ dur: Duration,
1080
+ ordTyp: Order_Type,
1081
+ qty: Quantity,
1082
+ lmPrc: Limit_Price,
1083
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, Product_Code),
1084
+ dtDays: DTDays,
1085
+ ordSrc: "API",
1086
+ vnCode: "",
1087
+ oprtn: "<=",
1088
+ srcExp: "",
1089
+ tgtId: "",
1090
+ brnchNm: "",
1091
+ vlDt: DTDays,
1092
+ sym: streaming_symbol,
1093
+ brk: "",
1094
+ };
1095
+ log4js.debug("PlaceGtcGtdTrade Data :" + JSON.stringify(data));
1096
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1097
+ const url = this.__config.PlaceTradeURL_comm(this.__constants.coAccId);
1098
+ log4js.debug("PlaceGtcGtdTrade URLS -" + url);
1099
+ var result = this.__http.PostMethod(url, data);
1100
+ log4js.debug("PlaceGtcGtdTrade Result :" + JSON.stringify(result));
1101
+ return result;
1102
+ } else {
1103
+ const url = this.__config.PlaceGtcGtdTradeURL(this.__constants.eqAccId);
1104
+ log4js.debug("PlaceGtcGtdTrade URLS -" + url);
1105
+ var result = this.__http.PostMethod(url, data);
1106
+ log4js.debug("PlaceGtcGtdTrade Result :" + JSON.stringify(result));
1107
+ return result;
1108
+ }
1109
+ };
1110
+
1111
+ /**
1112
+ * Modify orders allows a user to change certain aspects of the order once it is placed. Depending on the execution state of the order (i.e. either completely open, partially open) there are various levels of modification allowed. As a user you can edit the product type, order quantity, order validity and certain other parameters. Please note that any modifications made to an order will be sent back to the risk system for validation before being submitted and there are chances that an already placed order may get rejected in case of a modification.
1113
+ * @param {string} Trading_Symbol Trading Symbol of the Scrip
1114
+ * @param {string} Exchange Exchange
1115
+ * @param {string} Action BUY | SELL
1116
+ * @param {string} Duration DAY | IOC | EOS(for BSE)
1117
+ * @param {string} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1118
+ * @param {number} Quantity Quantity of the Scrip
1119
+ * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1120
+ * @param {number} Limit_Price Limit price of the Scrip
1121
+ * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
1122
+ * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1123
+ * @param {string} ProductCode CNC | MIS | NRML | MTF
1124
+ * @returns Promise that resolves/rejects to Modify Order api response
1125
+ */
1126
+ ModifyTrade = (
1127
+ Trading_Symbol,
1128
+ Exchange,
1129
+ Action,
1130
+ Duration,
1131
+ Order_Type,
1132
+ Quantity,
1133
+ Streaming_Symbol,
1134
+ Limit_Price,
1135
+ Order_ID,
1136
+ Disclosed_Quantity = "0",
1137
+ TriggerPrice = "0",
1138
+ ProductCode
1139
+ ) => {
1140
+ log4js.info("Inside ModifyTrade method");
1141
+ const paramsObj = {
1142
+ trdSym: Trading_Symbol,
1143
+ exc: Exchange,
1144
+ action: Action,
1145
+ dur: Duration,
1146
+ ordTyp: Order_Type,
1147
+ qty: Quantity,
1148
+ sym: Streaming_Symbol,
1149
+ lmPrc: Limit_Price,
1150
+ nstOID: Order_ID,
1151
+ dscQty: Disclosed_Quantity,
1152
+ trgPrc: TriggerPrice,
1153
+ prdCode: ProductCode,
1154
+ };
1155
+ const validateResponse = validateModifyTrade(
1156
+ paramsObj,
1157
+ this.excsAndprdDpNm
1158
+ );
1159
+ if (validateResponse.error) {
1160
+ log4js.debug(
1161
+ "ModifyTrade validation error -" + validateResponse.error.details
1162
+ );
1163
+ return Promise.reject(validateResponse.error.details);
1164
+ }
1165
+ const data = {
1166
+ trdSym: Trading_Symbol,
1167
+ exc: Exchange,
1168
+ action: Action,
1169
+ dur: Duration,
1170
+ flQty: "0",
1171
+ ordTyp: Order_Type,
1172
+ qty: Quantity,
1173
+ dscQty: Disclosed_Quantity,
1174
+ sym: Streaming_Symbol,
1175
+ mktPro: "",
1176
+ lmPrc: Limit_Price,
1177
+ trgPrc: TriggerPrice,
1178
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, ProductCode),
1179
+ dtDays: "",
1180
+ nstOID: Order_ID,
1181
+ valid: false,
1182
+ };
1183
+
1184
+ log4js.debug("ModifyTrade Data :" + JSON.stringify(data));
1185
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1186
+ const url = this.__config.ModifyTradeURL_comm(this.__constants.coAccId);
1187
+ log4js.debug("ModifyTrade URLS -" + url);
1188
+ var result = this.__http.PutMethod(url, data);
1189
+ log4js.debug("ModifyTrade Result :" + JSON.stringify(result));
1190
+ return result;
1191
+ } else {
1192
+ const url = this.__config.ModifyTradeURL(this.__constants.eqAccId);
1193
+ log4js.debug("ModifyTrade URLS -" + url);
1194
+ var result = this.__http.PutMethod(url, data);
1195
+ log4js.debug("ModifyTrade Result :" + JSON.stringify(result));
1196
+ return result;
1197
+ }
1198
+ };
1199
+ /**
1200
+ * An order can be cancelled, as long as on order is open or pending in the system.
1201
+ * @param {string} OrderId Nest OrderId
1202
+ * @param {string} Exchange Exchange
1203
+ * @param {string'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1204
+ * @param {string} ProductCode CNC | MIS | NRML | MTF
1205
+ * @returns Promise that resolves/rejects to Cancel Trade api response
1206
+ */
1207
+ CancelTrade = (OrderId, Exchange, Order_Type, ProductCode) => {
1208
+ log4js.info("Inside CancelTrade method");
1209
+ const data = {
1210
+ nstOID: OrderId,
1211
+ exc: Exchange,
1212
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, ProductCode),
1213
+ ordTyp: Order_Type,
1214
+ };
1215
+ const validateResponse = validateCancelPlaceTrade(
1216
+ data,
1217
+ this.excsAndprdDpNm
1218
+ );
1219
+ if (validateResponse.error) {
1220
+ log4js.debug(
1221
+ "CancelTrade validation error -" + validateResponse.error.details
1222
+ );
1223
+ return Promise.reject(validateResponse.error.details);
1224
+ }
1225
+ log4js.debug("CancelTrade Data :" + JSON.stringify(data));
1226
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1227
+ const url = this.__config.CancelTradeURL_comm(this.__constants.coAccId);
1228
+ log4js.debug("CancelTrade URLS -" + url);
1229
+ var result = this.__http.PutMethod(url, data);
1230
+ log4js.debug("CancelTrade Result :" + JSON.stringify(result));
1231
+ return result;
1232
+ } else {
1233
+ const url = this.__config.CancelTradeURL(this.__constants.eqAccId);
1234
+ log4js.debug("CancelTrade URLS -" + url);
1235
+ var result = this.__http.PutMethod(url, data);
1236
+ log4js.debug("CancelTrade Result :" + JSON.stringify(result));
1237
+ return result;
1238
+ }
1239
+ };
1240
+
1241
+ /**
1242
+ * This method will retrieve the MF Order Book.
1243
+ * @param {string} fromDate From Date
1244
+ * @param {string} toDate To Date
1245
+ * @returns Promise that resolves to MF Order Book of client \
1246
+ * Typical trade book response will be a nested JSON containing below fields
1247
+ * - Symbol
1248
+ * - Product Type
1249
+ * - Order type
1250
+ * - Quantity
1251
+ * - Price
1252
+ * - Validity
1253
+ * - Order ID
1254
+ * - Order Status
1255
+ */
1256
+ MFOrderBook = (fromDate, toDate) => {
1257
+ log4js.info("Inside MFOrderBook method");
1258
+ const validateResponse = validateMFOrderBook(fromDate, toDate);
1259
+ if (validateResponse.error) {
1260
+ log4js.debug(
1261
+ "MFOrderBook validation error -" + validateResponse.error.details
1262
+ );
1263
+ return Promise.reject(validateResponse.error.details);
1264
+ }
1265
+ const url = this.__config.OrderBookMFURL(
1266
+ this.__constants.eqAccId,
1267
+ fromDate,
1268
+ toDate
1269
+ );
1270
+ log4js.debug("MFOrderBook URLS -" + url);
1271
+ var result = this.__http.GetMethod(url);
1272
+ log4js.debug("MFOrderBook Result :" + JSON.stringify(result));
1273
+ return result;
1274
+ };
1275
+
1276
+ /**
1277
+ * Similar to Exit Cover order the functionality will ensure that any non executed open order will be cancelled. However for any orders which are executed it will automatically cancel one of the target or stop loss legs and modify the other leg to be placed as a market order. This will ensure that any executed orders will be squared off in position terms.
1278
+ * @param {string} Order_Id Mest OrderId
1279
+ * @param {string} Syom_Id obtained post placing Bracket Order
1280
+ * @param {string} Status Current Status of the Bracket Order
1281
+ * @returns Promise that resolves/rejects to Exit Bracket Order api response
1282
+ */
1283
+ ExitBracketTrade = (Order_Id, Syom_Id, Status) => {
1284
+ log4js.info("Inside ExitBracketTrade method");
1285
+ const data = { nstOrdNo: Order_Id, syomID: Syom_Id, sts: Status };
1286
+ const validateResponse = validateExitBracketTrade(data);
1287
+ if (validateResponse.error) {
1288
+ log4js.debug(
1289
+ "ExitBracketTrade validation error -" + validateResponse.error.details
1290
+ );
1291
+ return Promise.reject(validateResponse.error.details);
1292
+ }
1293
+ log4js.debug("ExitBracketTrade Data :" + JSON.stringify(data));
1294
+ const url = this.__config.ExitBracketTradeURL(this.__constants.eqAccId);
1295
+ log4js.debug("ExitBracketTrade URLS -" + url);
1296
+ var result = this.__http.DeleteMethod(url, data);
1297
+ log4js.debug("ExitBracketTrade Result :" + JSON.stringify(result));
1298
+ return result;
1299
+ };
1300
+
1301
+ /**
1302
+ * Place Bracket Order
1303
+ * @param {string} Exchange Exchange
1304
+ * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1305
+ * @param {string} Transaction_Type Transaction Type
1306
+ * @param {number} Quantity Quantity of the Scrip
1307
+ * @param {'DAY' | 'IOC' | 'EOS'} Duration DAY | IOC | EOS(for BSE)
1308
+ * @param {string} Disclosed_Quantity Quantity to be disclosed while order placement
1309
+ * @param {number} Limit_Price Limit Price of the Scrip
1310
+ * @param {string} Target Absolute Target value
1311
+ * @param {string} StopLoss Absolute Stop Loss value
1312
+ * @param {'Y' | 'N'} Trailing_Stop_Loss Y | N
1313
+ * @param {number} Trailing_Stop_Loss_Value Trailing Stop Loss value
1314
+ * @returns Promise that resolves/rejects to Place Bracket Trade api response
1315
+ */
1316
+ PlaceBracketTrade = (
1317
+ Exchange,
1318
+ Streaming_Symbol,
1319
+ Transaction_Type,
1320
+ Quantity,
1321
+ Duration,
1322
+ Disclosed_Quantity,
1323
+ Limit_Price,
1324
+ Target,
1325
+ StopLoss,
1326
+ Trailing_Stop_Loss = "Y",
1327
+ Trailing_Stop_Loss_Value = "1"
1328
+ ) => {
1329
+ log4js.info("Inside PlaceBracketTrade method");
1330
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1331
+ console.log("Operation invalid for commodities");
1332
+ return Promise.reject(new Error("Operation invalid for commodities"));
1333
+ }
1334
+ const paramsObj = {
1335
+ exc: Exchange,
1336
+ sym: Streaming_Symbol,
1337
+ trnsTyp: Transaction_Type,
1338
+ qty: Quantity,
1339
+ dur: Duration,
1340
+ dsQty: Disclosed_Quantity,
1341
+ prc: Limit_Price,
1342
+ sqOffVal: Target,
1343
+ slVal: StopLoss,
1344
+ trlSl: Trailing_Stop_Loss,
1345
+ trlSlVal: Trailing_Stop_Loss_Value,
1346
+ };
1347
+ const validateResponse = validatePlaceBracketTrade(
1348
+ paramsObj,
1349
+ this.excsAndprdDpNm
1350
+ );
1351
+ if (validateResponse.error) {
1352
+ log4js.debug(
1353
+ "PlaceBracketTrade validation error -" + validateResponse.error.details
1354
+ );
1355
+ return Promise.reject(validateResponse.error.details);
1356
+ }
1357
+ const data = {
1358
+ exc: Exchange,
1359
+ sym: Streaming_Symbol,
1360
+ trnsTyp: Transaction_Type,
1361
+ qty: Quantity,
1362
+ dur: Duration,
1363
+ dsQty: Disclosed_Quantity,
1364
+ prc: Limit_Price,
1365
+ trdBsdOn: "LTP",
1366
+ sqOffBsdOn: "Absolute",
1367
+ sqOffVal: Target,
1368
+ slBsdOn: "Absolute",
1369
+ slVal: StopLoss,
1370
+ trlSl: Trailing_Stop_Loss,
1371
+ trlSlVal: Trailing_Stop_Loss_Value,
1372
+ ordSrc: "API",
1373
+ };
1374
+
1375
+ log4js.debug("PlaceBracketTrade Data :" + JSON.stringify(data));
1376
+ const url = this.__config.PlaceBracketTradeURL(this.__constants.eqAccId);
1377
+ log4js.debug("PlaceBracketTrade URLS -" + url);
1378
+ var result = this.__http.PostMethod(url, data);
1379
+ return result;
1380
+ };
1381
+
1382
+ /**
1383
+ * Basket order allows user to place multiple orders at one time. User can place orders for multiple scrips all at once. One just creates multiple orders for same or different securities and club these orders together to be placed in one go. This helps save time.
1384
+ * @param {Array<Order>} orderlist Array of Orders to be placed
1385
+ * @returns Promise that resolves/rejects to Place Basket Trade api response
1386
+ */
1387
+ PlaceBasketTrade = async (orderlist) => {
1388
+ log4js.info("Inside PlaceBasketTrade method");
1389
+ let isComm = false;
1390
+ const lst = [];
1391
+ orderlist.forEach(({ sym, GTDDate, rmk, ...order }) => {
1392
+ // remove sym, GTCDate, rmk from order if present because we don't need to pass them in api
1393
+ if (order.exc == "MCX" || order.exc == "NCDEX") {
1394
+ isComm = true;
1395
+ return;
1396
+ }
1397
+ const data = { ...order, vnCode: "", rmk: "" };
1398
+ lst.push(data);
1399
+ });
1400
+
1401
+ const fd = { ordLst: lst, ordSrc: "API" };
1402
+ if (isComm) {
1403
+ console.log("Basket Order not available for Commodity");
1404
+ }
1405
+ const validateResponse = validatePlaceBasketTrade(lst, this.excsAndprdDpNm);
1406
+ await Promise.all(
1407
+ validateResponse.map((item) => {
1408
+ if (item.error) {
1409
+ log4js.debug(
1410
+ "PlaceBasketTrade validation error -" + item.error.details
1411
+ );
1412
+ return Promise.reject(item.error.details);
1413
+ }
1414
+ })
1415
+ );
1416
+ const url = this.__config.PlaceBasketTradeURL(this.__constants.eqAccId);
1417
+ log4js.debug("PlaceBasketTrade URLS -" + url);
1418
+ var result = this.__http.PostMethod(url, fd);
1419
+ return result;
1420
+ };
1421
+
1422
+ /**
1423
+ * Limits refers to the cumulative margins available in your account which can be used for trading and investing in various products. Limits is a combination of the free cash you have (i.e. un-utilized cash), cash equivalent securities (usually margin pledged securities), any money which is in transit (T1/T2 day sell transaction values) and others, all of which can be used for placing orders. Usually whenever you place an order in a given asset and product type our risk management system assesses your limits available and then lets the orders go through or blocks the orders. Limits are dynamic in nature and can be influenced by the Mark to Markets in your positions and sometimes even by the LTP of your holdings.
1424
+ * @returns Promise that resolves/rejects to the Limits api response
1425
+ */
1426
+ Limits = () => {
1427
+ log4js.info("Inside Limits method");
1428
+ const accTyp = this.__constants.Data.data.lgnData.accTyp;
1429
+ const eqUrl =
1430
+ accTyp == "EQ" || accTyp == "COMEQ"
1431
+ ? this.__config.LimitsURL(this.__constants.eqAccId)
1432
+ : undefined;
1433
+ const commUrl =
1434
+ accTyp == "CO" || accTyp == "COMEQ"
1435
+ ? this.__config.LimitsURL_comm(this.__constants.coAccId)
1436
+ : undefined;
1437
+ log4js.debug("Limits URLS - eq :" + eqUrl + " comm:" + commUrl);
1438
+ var result = this.__getEqCommData(eqUrl, commUrl);
1439
+ log4js.debug("Limits Result :" + JSON.stringify(result));
1440
+ return result;
1441
+ };
1442
+
1443
+ /**
1444
+ * Get AMO Status
1445
+ * @param {string} exchange Exchange value from Position book response.
1446
+ * @returns Promise that resolves/rejects to the Get AMO Status api response
1447
+ */
1448
+ GetAMOStxatus = (exchange) => {
1449
+ log4js.info("Inside GetAMOStxatus method");
1450
+ const accTyp = this.__constants.Data.data.lgnData.accTyp;
1451
+ if (accTyp == "CO" || accTyp == "COMEQ") {
1452
+ const validateResponse = validateGetAMOStxatus(
1453
+ exchange,
1454
+ this.excsAndprdDpNm
1455
+ );
1456
+ if (validateResponse.error) {
1457
+ log4js.debug(
1458
+ " GetAMOStxatus validation error - " + validateResponse.error.details
1459
+ );
1460
+ return Promise.reject(validateResponse.error.details);
1461
+ }
1462
+ }
1463
+
1464
+ const eqUrl =
1465
+ accTyp == "EQ" || accTyp == "COMEQ"
1466
+ ? this.__config.GetAMOFlag(this.__constants.eqAccId)
1467
+ : undefined;
1468
+ const commUrl =
1469
+ accTyp == "CO" || accTyp == "COMEQ"
1470
+ ? this.__config.GetAMOFlag_comm(exchange)
1471
+ : undefined;
1472
+ log4js.debug("GetAMOStxatus URLS - eq :" + eqUrl + " comm:" + commUrl);
1473
+ var result = this.__getEqCommData(eqUrl, commUrl);
1474
+ log4js.debug("GetAMOStxatus Result :" + JSON.stringify(result));
1475
+ return result;
1476
+ };
1477
+
1478
+ /**
1479
+ * After market order or AMO in short refers to orders which can be placed once the markets or exchanges are closed for trading. You can place AMO post market hours which will result in the order in question being placed automatically by 9:15 AM - 9:30 AM the next business day. AMO orders usually need to be limit orders in order to prevent inadvertent execution in case of adverse price movement in markets at beginning of day. AMO is a useful way to place your orders in case you do not have time to place orders during market hours.
1480
+ * @param {string} Trading_Symbol Trading Symbol of the Scrip
1481
+ * @param {string} Exchange Exchange value from Position book response.
1482
+ * @param {string} Action BUY | SELL
1483
+ * @param {string} Duration DAY | IOC | EOS(for BSE)
1484
+ * @param {string} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1485
+ * @param {number} Quantity Quantity of the Scrip
1486
+ * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1487
+ * @param {number} Limit_Price Limit price of Scrip
1488
+ * @param {string} Disclosed_Quantity Quantity to be disclosed while order_placement
1489
+ * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1490
+ * @param {string} ProductCode CNC | MIS | NRML | MTF
1491
+ * @returns Promise that resolves/rejects to the Place AMO Trade api response
1492
+ */
1493
+ PlaceAMOTrade = (
1494
+ Trading_Symbol,
1495
+ Exchange,
1496
+ Action,
1497
+ Duration,
1498
+ Order_Type,
1499
+ Quantity,
1500
+ Streaming_Symbol,
1501
+ Limit_Price,
1502
+ Disclosed_Quantity = "0",
1503
+ TriggerPrice = "0",
1504
+ ProductCode
1505
+ ) => {
1506
+ log4js.info("Inside PlaceAMOTrade method");
1507
+ const paramsObj = {
1508
+ trdSym: Trading_Symbol,
1509
+ exc: Exchange,
1510
+ action: Action,
1511
+ dur: Duration,
1512
+ ordTyp: Order_Type,
1513
+ qty: Quantity,
1514
+ sym: Streaming_Symbol,
1515
+ lmPrc: Limit_Price,
1516
+ dscQty: Disclosed_Quantity,
1517
+ trgPrc: TriggerPrice,
1518
+ prdCode: ProductCode,
1519
+ };
1520
+ const validateResponse = validatePlaceAMOTrade(
1521
+ paramsObj,
1522
+ this.excsAndprdDpNm
1523
+ );
1524
+ if (validateResponse.error) {
1525
+ log4js.debug(
1526
+ "PlaceAMOTrade validation error -" + validateResponse.error.details
1527
+ );
1528
+ return Promise.reject(validateResponse.error.details);
1529
+ }
1530
+ const data = {
1531
+ trdSym: Trading_Symbol,
1532
+ exc: Exchange,
1533
+ action: Action,
1534
+ dur: Duration,
1535
+ flQty: "0",
1536
+ ordTyp: Order_Type,
1537
+ qty: Quantity,
1538
+ dscQty: Disclosed_Quantity,
1539
+ sym: Streaming_Symbol,
1540
+ mktPro: "",
1541
+ lmPrc: Limit_Price,
1542
+ trgPrc: TriggerPrice,
1543
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, ProductCode),
1544
+ posSqr: "false",
1545
+ minQty: "0",
1546
+ ordSrc: "API",
1547
+ vnCode: "",
1548
+ rmk: "",
1549
+ };
1550
+
1551
+ log4js.debug("PlaceAMOTrade Data :" + JSON.stringify(data));
1552
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1553
+ const url = this.__config.PlaceAMOTrade_comm(this.__constants.coAccId);
1554
+ log4js.debug("PlaceAMOTrade URLS -" + url);
1555
+ var result = this.__http.PostMethod(url, data);
1556
+ log4js.debug("PlaceAMOTrade Result :" + JSON.stringify(result));
1557
+ return result;
1558
+ } else {
1559
+ const url = this.__config.PlaceAMOTrade(this.__constants.eqAccId);
1560
+ log4js.debug("PlaceAMOTrade URLS -" + url);
1561
+ var result = this.__http.PostMethod(url, data);
1562
+ log4js.debug("PlaceAMOTrade Result :" + JSON.stringify(result));
1563
+ return result;
1564
+ }
1565
+ };
1566
+
1567
+ /**
1568
+ * Modify After Market Order
1569
+ * @param {string} Trading_Symbol Trading Symbol of the Scrip
1570
+ * @param {string} Exchange Exchange value from Position book response.
1571
+ * @param {string} Action BUY | SELL
1572
+ * @param {string} Duration DAY | IOC | EOS(for BSE)
1573
+ * @param {string} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1574
+ * @param {number} Quantity Quantity of the Scrip
1575
+ * @param {string} Streaming_Symbol companycode_exchange to be obtained from Contract file downloaded
1576
+ * @param {number} Limit_Price Limit price of Scrip
1577
+ * @param {string} Order_ID Nest Order Id
1578
+ * @param {string} Disclosed_Quantity Quantity to be disclosed while order_placement
1579
+ * @param {string} TriggerPrice Trigger Price applicable for SL/SL-M Orders
1580
+ * @param {string} ProductCode Product Code of the trade
1581
+ * @returns Promise that resolves/rejects to the Place AMO Trade api response
1582
+ */
1583
+ ModifyAMOTrade = (
1584
+ Trading_Symbol,
1585
+ Exchange,
1586
+ Action,
1587
+ Duration,
1588
+ Order_Type,
1589
+ Quantity,
1590
+ Streaming_Symbol,
1591
+ Limit_Price,
1592
+ Order_ID,
1593
+ Disclosed_Quantity = "0",
1594
+ TriggerPrice = "0",
1595
+ ProductCode
1596
+ ) => {
1597
+ log4js.info("Inside ModifyAMOTrade method");
1598
+ const paramsObj = {
1599
+ trdSym: Trading_Symbol,
1600
+ exc: Exchange,
1601
+ action: Action,
1602
+ dur: Duration,
1603
+ ordTyp: Order_Type,
1604
+ qty: Quantity,
1605
+ sym: Streaming_Symbol,
1606
+ lmPrc: Limit_Price,
1607
+ nstOID: Order_ID,
1608
+ dscQty: Disclosed_Quantity,
1609
+ trgPrc: TriggerPrice,
1610
+ prdCode: ProductCode,
1611
+ };
1612
+ const validateResponse = validateModifyAMOTrade(
1613
+ paramsObj,
1614
+ this.excsAndprdDpNm
1615
+ );
1616
+ if (validateResponse.error) {
1617
+ log4js.debug(
1618
+ "ModifyAMOTrade validation error -" + validateResponse.error.details
1619
+ );
1620
+ return Promise.reject(validateResponse.error.details);
1621
+ }
1622
+ const data = {
1623
+ trdSym: Trading_Symbol,
1624
+ exc: Exchange,
1625
+ action: Action,
1626
+ dur: Duration,
1627
+ flQty: "0",
1628
+ ordTyp: Order_Type,
1629
+ qty: Quantity,
1630
+ dscQty: Disclosed_Quantity,
1631
+ sym: Streaming_Symbol,
1632
+ mktPro: "",
1633
+ lmPrc: Limit_Price,
1634
+ trgPrc: TriggerPrice,
1635
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, ProductCode),
1636
+ dtDays: "",
1637
+ nstOID: Order_ID,
1638
+ };
1639
+
1640
+ log4js.debug("ModifyAMOTrade Data :" + JSON.stringify(data));
1641
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1642
+ const url = this.__config.ModifyAMOTrade_comm(this.__constants.coAccId);
1643
+ log4js.debug("ModifyAMOTrade URLS" + url);
1644
+ var result = this.__http.PutMethod(url, data);
1645
+ log4js.debug("ModifyAMOTrade Result :" + JSON.stringify(result));
1646
+ return result;
1647
+ } else {
1648
+ const url = this.__config.ModifyAMOTrade(this.__constants.eqAccId);
1649
+ log4js.debug("ModifyAMOTrade URLS" + url);
1650
+ var result = this.__http.PutMethod(url, data);
1651
+ log4js.debug("ModifyAMOTrade Result :" + JSON.stringify(result));
1652
+ return result;
1653
+ }
1654
+ };
1655
+
1656
+ /**
1657
+ * Cancel After Market Order
1658
+ * @param {string} OrderId Nest Order Id
1659
+ * @param {string} Exchange Exchange
1660
+ * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} Order_Type LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1661
+ * @param {'CNC' | 'MIS' | 'NRML' | 'MTF'} Product_Code CNC | MIS | NRML | MTF
1662
+ * @returns Promise that resolves/rejects to the Cancel AMO Trade api response
1663
+ */
1664
+ CancelAMOTrade = (OrderId, Exchange, Order_Type, Product_Code) => {
1665
+ const data = {
1666
+ nstOID: OrderId,
1667
+ exc: Exchange,
1668
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, Product_Code),
1669
+ ordTyp: Order_Type,
1670
+ };
1671
+ log4js.info("Inside CancelAMOTrade method");
1672
+ const validateResponse = validateCancelAMOTrade(data, this.excsAndprdDpNm);
1673
+ if (validateResponse.error) {
1674
+ log4js.debug(
1675
+ "CancelAMOTrade validation error -" + validateResponse.error.details
1676
+ );
1677
+ return Promise.reject(validateResponse.error.details);
1678
+ }
1679
+ log4js.debug("CancelAMOTrade Data :" + JSON.stringify(data));
1680
+ if (Exchange == "MCX" || Exchange == "NCDEX") {
1681
+ const url = this.__config.CancelAMOTrade_comm(this.__constants.coAccId);
1682
+ log4js.debug("CancelAMOTrade URLS -" + url);
1683
+ var result = this.__http.PutMethod(url, data);
1684
+ log4js.debug("CancelAMOTrade Result :" + JSON.stringify(result));
1685
+ return result;
1686
+ } else {
1687
+ const url = this.__config.CancelAMOTrade(this.__constants.eqAccId);
1688
+ log4js.debug("CancelAMOTrade URLS -" + url);
1689
+ var result = this.__http.PutMethod(url, data);
1690
+ log4js.debug("CancelAMOTrade Result :" + JSON.stringify(result));
1691
+ return result;
1692
+ }
1693
+ };
1694
+
1695
+ /**
1696
+ * Square off is a term used in intraday and simply means closing all open positions by the end of the trading day.
1697
+ * @param {Array<Order>} orderlist List of orders to be Squared Off.
1698
+ * @returns Promise that resolves/rejects to the Position Square Off api response
1699
+ */
1700
+ PositionSquareOff = async (orderlist) => {
1701
+ const validateResponse = validatePositionSquareOff(
1702
+ orderlist,
1703
+ this.excsAndprdDpNm
1704
+ );
1705
+ console.log("PositionSquareOff", validateResponse);
1706
+ await Promise.all(
1707
+ validateResponse.map((item) => {
1708
+ if (item.error) {
1709
+ log4js.debug(
1710
+ "PositionSquareOff validation error -" + item.error.details
1711
+ );
1712
+ return Promise.reject(item.error.details);
1713
+ }
1714
+ })
1715
+ );
1716
+
1717
+ const lstEq = [];
1718
+ const lstComm = [];
1719
+ log4js.info("Inside PositionSquareOff method");
1720
+ orderlist.forEach(({ GTDDate, rmk, ...order }) => {
1721
+ order["flQty"] = "0";
1722
+ order["mktPro"] = "";
1723
+ order["dtDays"] = "";
1724
+ order["posSqr"] = "true";
1725
+ order["minQty"] = "0";
1726
+ order["ordSrc"] = "API";
1727
+ order["vnCode"] = "";
1728
+ order["rmk"] = "";
1729
+ order["prdCode"] = this.__constants.getValidProductCode(this.fileName, order.exc, order.prdCode);
1730
+ order["lmPrc"] = order.price;
1731
+ const data = order;
1732
+
1733
+ order.exc == "MCX" || order.exc == "NCDEX"
1734
+ ? lstComm.push(data)
1735
+ : lstEq.push(data);
1736
+ });
1737
+
1738
+ const postEq = lstEq.length
1739
+ ? await this.__http.PostMethod(
1740
+ this.__config.PositionSqOffURL(this.__constants.eqAccId),
1741
+ lstEq
1742
+ )
1743
+ : undefined;
1744
+ const postComm = lstComm.length
1745
+ ? await this.__http.PostMethod(
1746
+ this.__config.PositionSqOffURL(this.__constants.coAccId),
1747
+ lstComm
1748
+ )
1749
+ : undefined;
1750
+ var result = Promise.all([postEq, postComm]).then(([eq, comm]) => ({
1751
+ eq,
1752
+ comm,
1753
+ }));
1754
+ log4js.debug("PositionSquareOff Result :" + JSON.stringify(result));
1755
+ return result;
1756
+ };
1757
+
1758
+ /**
1759
+ * Convert a Position partially for Commodity
1760
+ * @param {string} streamingSymbol companycode_exchange to be obtained from Contract file downloaded
1761
+ * @param {string} conversionType Conversion type D-- Daywise and C–carry forward position
1762
+ * @param {string} quantity Quantity to be converted.
1763
+ * @param {string} action Transaction type 'BUY' and 'SELL - SELL .
1764
+ * @param {string} oldProductCode Existing Product Code of the trade.
1765
+ * @param {string} newProductCode New Product code of the trade.
1766
+ * @param {string} exchange Exchange value from Position book response.
1767
+ * @param {string} tradingSymbol Trading Symbol of the Scrip
1768
+ * @returns Promise that resolves/rejects to the Convert Position api response
1769
+ */
1770
+ ConvertPositionCOMM = (
1771
+ streamingSymbol,
1772
+ conversionType,
1773
+ quantity,
1774
+ action,
1775
+ oldProductCode,
1776
+ newProductCode,
1777
+ exchange,
1778
+ tradingSymbol
1779
+ ) => {
1780
+ log4js.info(`ConvertPositionCOMM method is called.`);
1781
+ const data = {
1782
+ sym: streamingSymbol,
1783
+ cnvTyp: conversionType,
1784
+ qty: quantity,
1785
+ action: this.__constants.getAlternateActionName(action),
1786
+ prdCode: this.__constants.getValidProductCode(this.fileName, exchange, oldProductCode),
1787
+ prdCodeCh: this.__constants.getValidProductCode(this.fileName, exchange, newProductCode),
1788
+ ordSrc: "API",
1789
+ exc: exchange,
1790
+ trdSym: tradingSymbol,
1791
+ };
1792
+ const validateResponse = validateConvertPositionCOMM(
1793
+ data,
1794
+ this.excsAndprdDpNm
1795
+ );
1796
+ if (validateResponse.error) {
1797
+ log4js.debug(
1798
+ `ConvertPositionCOMM validation error - ${validateResponse.error.details}`
1799
+ );
1800
+ return Promise.reject(validateResponse.error.details);
1801
+ }
1802
+ log4js.info(
1803
+ `ConvertPositionCOMM method is called with data ${JSON.stringify(data)}`
1804
+ );
1805
+ if (exchange === "MCX" || exchange === "NCDEX") {
1806
+ const url = this.__config.ConvertPositionURL_comm(
1807
+ this.__constants.coAccId
1808
+ );
1809
+ log4js.debug(`ConvertPositionCOMM URLS: ${url}`);
1810
+ var result = this.__http.PutMethod(url, data);
1811
+ log4js.debug(`ConvertPositionCOMM Result : ${JSON.stringify(result)}`);
1812
+ return result;
1813
+ }
1814
+ // else {
1815
+ // const url = this.__config.ConvertPositionURL(this.__constants.eqAccId);
1816
+ // log4js.debug(`ConvertPosition URLS: ${url}`);
1817
+ // var result = this.__http.PutMethod(url, data);
1818
+ // log4js.debug(`ConvertPosition Result : ${JSON.stringify(result)}`);
1819
+ // return result;
1820
+ // }
1821
+ };
1822
+
1823
+ /**
1824
+ * Converts your holding position For Equity
1825
+ * @param {string} Order_Id Nest Order Id
1826
+ * @param {string} Fill_Id Fill Id of the trade obtained from Trade API
1827
+ * @param {string} New_Product_Code New Product code of the trade
1828
+ * @param {string} Old_Product_Code Existing Product code of the trade
1829
+ * @param {string} Exchange Exchange
1830
+ * @param {'LIMIT' | 'MARKET' | 'STOP_LIMIT' | 'STOP_MARKET'} orderType LIMIT | MARKET | STOP_LIMIT | STOP_MARKET
1831
+ * @returns Promise that resolves/rejects to the Convert Position api response
1832
+ */
1833
+ ConvertPosition = (
1834
+ Order_Id,
1835
+ Fill_Id,
1836
+ New_Product_Code,
1837
+ Old_Product_Code,
1838
+ Exchange,
1839
+ orderType
1840
+ ) => {
1841
+ log4js.info(`ConvertPosition method is called.`);
1842
+ const data = {
1843
+ nstOID: Order_Id,
1844
+ flID: Fill_Id,
1845
+ prdCodeCh: this.__constants.getValidProductCode(this.fileName, Exchange, New_Product_Code),
1846
+ prdCode: this.__constants.getValidProductCode(this.fileName, Exchange, Old_Product_Code),
1847
+ exc: Exchange,
1848
+ ordTyp: orderType
1849
+ };
1850
+
1851
+ const validateResponse = validateConvertPositionEQ(data, this.excsAndprdDpNm);
1852
+ if (validateResponse.error) {
1853
+ log4js.debug(
1854
+ `ConvertPosition validation error - ${validateResponse.error.details}`
1855
+ );
1856
+ return Promise.reject(validateResponse.error.details);
1857
+ }
1858
+ log4js.debug(
1859
+ `ConvertPosition method error is called with data ${JSON.stringify(data)}`
1860
+ );
1861
+ const url = this.__config.ConvertPositionURL(this.__constants.eqAccId);
1862
+ log4js.debug(`ConvertPosition URLS: ${url}`);
1863
+ var result = this.__http.PutMethod(url, data);
1864
+ log4js.debug(`ConvertPosition Result : ${JSON.stringify(result)}`);
1865
+ return result;
1866
+ };
1867
+
1868
+ // MF Methods start //
1869
+
1870
+ /**
1871
+ *
1872
+ * @param {string} Token
1873
+ * @param {string} ISIN_Code
1874
+ * @param {string} Transaction_Type
1875
+ * @param {string} Client_Code
1876
+ * @param {number} Quantity
1877
+ * @param {string} Amount
1878
+ * @param {string} ReInv_Flag
1879
+ * @param {string} Folio_Number
1880
+ * @param {string} Scheme_Name
1881
+ * @param {string} Start_Date
1882
+ * @param {string} End_Date
1883
+ * @param {string} SIP_Frequency
1884
+ * @param {string} Generate_First_Order_Today
1885
+ * @param {string} Scheme_Plan
1886
+ * @param {string} Scheme_Code
1887
+ * @returns Promise that resolves/rejects to the Place MF api response
1888
+ */
1889
+ PlaceMF = (
1890
+ Token,
1891
+ ISIN_Code,
1892
+ Transaction_Type,
1893
+ Client_Code,
1894
+ Quantity,
1895
+ Amount,
1896
+ ReInv_Flag,
1897
+ Folio_Number,
1898
+ Scheme_Name,
1899
+ Start_Date,
1900
+ End_Date,
1901
+ SIP_Frequency,
1902
+ Generate_First_Order_Today,
1903
+ Scheme_Plan,
1904
+ Scheme_Code
1905
+ ) => {
1906
+ const paramsObj = {
1907
+ token: Token,
1908
+ isin: ISIN_Code,
1909
+ txnTyp: Transaction_Type,
1910
+ clientCode: Client_Code,
1911
+ qty: Quantity,
1912
+ amt: Amount,
1913
+ reInvFlg: ReInv_Flag,
1914
+ folioNo: Folio_Number,
1915
+ schemeName: Scheme_Name,
1916
+ strtDt: Start_Date,
1917
+ endDt: End_Date,
1918
+ sipFrq: SIP_Frequency,
1919
+ gfot: Generate_First_Order_Today,
1920
+ schemePlan: Scheme_Plan,
1921
+ schemeCode: Scheme_Code,
1922
+ };
1923
+ log4js.info("Inside PlaceMF method");
1924
+ const validateResponse = validatePlaceMF(paramsObj);
1925
+ if (validateResponse.error) {
1926
+ log4js.debug(
1927
+ "PlaceMF validation error -" + validateResponse.error.details
1928
+ );
1929
+ return Promise.reject(validateResponse.error.details);
1930
+ }
1931
+ const data = {
1932
+ currentOrdSts: "",
1933
+ token: Token,
1934
+ isin: ISIN_Code,
1935
+ txnTyp: Transaction_Type,
1936
+ clientCode: Client_Code,
1937
+ qty: Quantity,
1938
+ amt: Amount,
1939
+ reInvFlg: ReInv_Flag,
1940
+ reqstdBy: this.__constants.eqAccId,
1941
+ folioNo: Folio_Number,
1942
+ ordTyp: "FRESH",
1943
+ txnId: "0",
1944
+ schemeName: Scheme_Name,
1945
+ rmrk: "",
1946
+ mnRdmFlg: "",
1947
+ ordSrc: "API",
1948
+ strtDy: "1",
1949
+ strtDt: Start_Date,
1950
+ endDt: End_Date,
1951
+ sipFrq: SIP_Frequency,
1952
+ gfot: Generate_First_Order_Today,
1953
+ tnr: "",
1954
+ mdtId: "",
1955
+ sipregno: "",
1956
+ siporderno: "",
1957
+ schemePlan: Scheme_Plan,
1958
+ schemeCode: Scheme_Code,
1959
+ euinnumber: "",
1960
+ dpc: "Y",
1961
+ closeAccountFlag: "N",
1962
+ kycflag: "1",
1963
+ euinflag: "N",
1964
+ physicalFlag: "D",
1965
+ };
1966
+
1967
+ log4js.debug("PlaceMF Data :" + JSON.stringify(data));
1968
+ const url = this.__config.PlaceMFURL(this.__constants.eqAccId);
1969
+ log4js.debug("PlaceMF URLS -" + url);
1970
+ var result = this.__http.PostMethod(url, data);
1971
+ log4js.debug("PlaceMF Result :" + JSON.stringify(result));
1972
+ return result;
1973
+ };
1974
+
1975
+ /**
1976
+ * Certain attributes of a MF order may be modified., as long as on order is open or pending in the system.
1977
+ * @param {string} Token
1978
+ * @param {string} ISIN_Code
1979
+ * @param {string} Transaction_Type
1980
+ * @param {string} Client_Code
1981
+ * @param {number} Quantity
1982
+ * @param {string} Amount
1983
+ * @param {string} ReInv_Flag
1984
+ * @param {string} Folio_Number
1985
+ * @param {string} Scheme_Name
1986
+ * @param {string} Start_Date
1987
+ * @param {string} End_Date
1988
+ * @param {string} SIP_Frequency
1989
+ * @param {string} Generate_First_Order_Today
1990
+ * @param {string} Scheme_Plan
1991
+ * @param {string} Scheme_Code
1992
+ * @param {string} Transaction_Id
1993
+ * @returns Promise that resolves/rejects to the Modify MF api response
1994
+ */
1995
+ ModifyMF = (
1996
+ Token,
1997
+ ISIN_Code,
1998
+ Transaction_Type,
1999
+ Client_Code,
2000
+ Quantity,
2001
+ Amount,
2002
+ ReInv_Flag,
2003
+ Folio_Number,
2004
+ Scheme_Name,
2005
+ Start_Date,
2006
+ End_Date,
2007
+ SIP_Frequency,
2008
+ Generate_First_Order_Today,
2009
+ Scheme_Plan,
2010
+ Scheme_Code,
2011
+ Transaction_Id
2012
+ ) => {
2013
+ log4js.info("Inside ModifyMF method");
2014
+ const paramsObj = {
2015
+ token: Token,
2016
+ isin: ISIN_Code,
2017
+ txnTyp: Transaction_Type,
2018
+ clientCode: Client_Code,
2019
+ qty: Quantity,
2020
+ amt: Amount,
2021
+ reInvFlg: ReInv_Flag,
2022
+ folioNo: Folio_Number,
2023
+ schemeName: Scheme_Name,
2024
+ strtDt: Start_Date,
2025
+ endDt: End_Date,
2026
+ sipFrq: SIP_Frequency,
2027
+ gfot: Generate_First_Order_Today,
2028
+ schemePlan: Scheme_Plan,
2029
+ schemeCode: Scheme_Code,
2030
+ txnId: Transaction_Id,
2031
+ };
2032
+ const validateResponse = validateModifyMF(paramsObj);
2033
+ if (validateResponse.error) {
2034
+ log4js.debug(
2035
+ "ModifyMF validation error -" + validateResponse.error.details
2036
+ );
2037
+ return Promise.reject(validateResponse.error.details);
2038
+ }
2039
+ const data = {
2040
+ currentOrdSts: "ACCEPTED",
2041
+ token: Token,
2042
+ isin: ISIN_Code,
2043
+ txnTyp: Transaction_Type,
2044
+ clientCode: Client_Code,
2045
+ qty: Quantity,
2046
+ amt: Amount,
2047
+ reInvFlg: ReInv_Flag,
2048
+ reqstdBy: this.__constants.eqAccId,
2049
+ folioNo: Folio_Number,
2050
+ ordTyp: "MODIFY",
2051
+ txnId: Transaction_Id,
2052
+ schemeName: Scheme_Name,
2053
+ rmrk: "",
2054
+ mnRdmFlg: "",
2055
+ ordSrc: "API",
2056
+ strtDy: "1",
2057
+ strtDt: Start_Date,
2058
+ endDt: End_Date,
2059
+ sipFrq: SIP_Frequency,
2060
+ gfot: Generate_First_Order_Today,
2061
+ tnr: "",
2062
+ mdtId: "",
2063
+ sipregno: "",
2064
+ siporderno: "",
2065
+ schemePlan: Scheme_Plan,
2066
+ schemeCode: Scheme_Code,
2067
+ euinnumber: "",
2068
+ dpc: "Y",
2069
+ closeAccountFlag: "N",
2070
+ kycflag: "1",
2071
+ euinflag: "N",
2072
+ physicalFlag: "D",
2073
+ };
2074
+
2075
+ log4js.debug("ModifyMF Data :" + JSON.stringify(data));
2076
+ const url = this.__config.ModifyMFURL(this.__constants.eqAccId);
2077
+ log4js.debug("ModifyMF URLS -" + url);
2078
+ var result = this.__http.PutMethod(url, data);
2079
+ log4js.debug("ModifyMF Result :" + JSON.stringify(result));
2080
+ return result;
2081
+ };
2082
+
2083
+ /**
2084
+ *
2085
+ * @param {string} Token
2086
+ * @param {string} ISIN_Code
2087
+ * @param {string} Transaction_Type
2088
+ * @param {string} Client_Code
2089
+ * @param {number} Quantity
2090
+ * @param {string} Amount
2091
+ * @param {string} ReInv_Flag
2092
+ * @param {string} Folio_Number
2093
+ * @param {string} Scheme_Name
2094
+ * @param {string} Start_Date
2095
+ * @param {string} End_Date
2096
+ * @param {string} SIP_Frequency
2097
+ * @param {string} Generate_First_Order_Today
2098
+ * @param {string} Scheme_Plan
2099
+ * @param {string} Scheme_Code
2100
+ * @param {string} Transaction_Id
2101
+ * @returns Promise that resolves/rejects to Cancel MF api response
2102
+ */
2103
+ CancelMF = (
2104
+ Token,
2105
+ ISIN_Code,
2106
+ Transaction_Type,
2107
+ Client_Code,
2108
+ Quantity,
2109
+ Amount,
2110
+ ReInv_Flag,
2111
+ Folio_Number,
2112
+ Scheme_Name,
2113
+ Start_Date,
2114
+ End_Date,
2115
+ SIP_Frequency,
2116
+ Generate_First_Order_Today,
2117
+ Scheme_Plan,
2118
+ Scheme_Code,
2119
+ Transaction_Id
2120
+ ) => {
2121
+ log4js.info("Inside CancelMF method");
2122
+ const paramsObj = {
2123
+ token: Token,
2124
+ isin: ISIN_Code,
2125
+ txnTyp: Transaction_Type,
2126
+ clientCode: Client_Code,
2127
+ qty: Quantity,
2128
+ amt: Amount,
2129
+ reInvFlg: ReInv_Flag,
2130
+ folioNo: Folio_Number,
2131
+ schemeName: Scheme_Name,
2132
+ strtDt: Start_Date,
2133
+ endDt: End_Date,
2134
+ sipFrq: SIP_Frequency,
2135
+ gfot: Generate_First_Order_Today,
2136
+ schemePlan: Scheme_Plan,
2137
+ schemeCode: Scheme_Code,
2138
+ txnId: Transaction_Id,
2139
+ };
2140
+ const validateResponse = validateCancelMF(paramsObj);
2141
+ if (validateResponse.error) {
2142
+ log4js.debug(
2143
+ "CancelMF validation error -" + validateResponse.error.details
2144
+ );
2145
+ return Promise.reject(validateResponse.error.details);
2146
+ }
2147
+ const data = {
2148
+ currentOrdSts: "ACCEPTED",
2149
+ token: Token,
2150
+ isin: ISIN_Code,
2151
+ txnTyp: Transaction_Type,
2152
+ clientCode: Client_Code,
2153
+ qty: Quantity,
2154
+ amt: Amount,
2155
+ reInvFlg: ReInv_Flag,
2156
+ reqstdBy: this.__constants.eqAccId,
2157
+ folioNo: Folio_Number,
2158
+ ordTyp: "CANCEL",
2159
+ txnId: Transaction_Id,
2160
+ schemeName: Scheme_Name,
2161
+ rmrk: "",
2162
+ mnRdmFlg: "",
2163
+ ordSrc: "API",
2164
+ strtDy: "1",
2165
+ strtDt: Start_Date,
2166
+ endDt: End_Date,
2167
+ sipFrq: SIP_Frequency,
2168
+ gfot: Generate_First_Order_Today,
2169
+ tnr: "",
2170
+ mdtId: "",
2171
+ sipregno: "",
2172
+ siporderno: "",
2173
+ schemePlan: Scheme_Plan,
2174
+ schemeCode: Scheme_Code,
2175
+ euinnumber: "",
2176
+ dpc: "Y",
2177
+ closeAccountFlag: "N",
2178
+ kycflag: "1",
2179
+ euinflag: "N",
2180
+ physicalFlag: "D",
2181
+ };
2182
+
2183
+ log4js.debug("CancelMF Data :" + JSON.stringify(data));
2184
+ const url = this.__config.CancelMFURL(this.__constants.eqAccId);
2185
+ log4js.debug("CancelMF URLS -" + url);
2186
+ var result = this.__http.PutMethod(url, data);
2187
+ log4js.debug("CancelMF Result :" + JSON.stringify(result));
2188
+ return result;
2189
+ };
2190
+
2191
+ /**
2192
+ *
2193
+ * @returns Promise that resolves/rejects to Holdings MF api response
2194
+ */
2195
+ HoldingsMF = () => {
2196
+ log4js.info("Inside HoldingsMF method");
2197
+ const url = this.__config.HoldingsMFURL(this.__constants.eqAccId);
2198
+ log4js.debug("HoldingsMF URLS -" + url);
2199
+ var result = this.__http.GetMethod(url);
2200
+ log4js.debug("HoldingsMF Result :" + JSON.stringify(result));
2201
+ return result;
2202
+ };
2203
+
2204
+ // MF Methods end //
2205
+
2206
+ /**
2207
+ * Login function
2208
+ * @param {string} source apiKey provided by APIConnect
2209
+ * @param {string} password password provided by APIConnect
2210
+ * @returns Promise \
2211
+ * if resolved, then returns object in the form of `{msg: string, success: boolean}` \
2212
+ * if rejected, returns error
2213
+ */
2214
+ __Login = function (source, password) {
2215
+ let url = this.__config.LoginURL(source);
2216
+ return this.__http
2217
+ .PostMethod(url, { pwd: password })
2218
+ .then((res) => {
2219
+ if (res.msg) {
2220
+ this.__constants.VendorSession = res.msg;
2221
+ return res;
2222
+ } else {
2223
+ res.msg = "Login: " + res.error.errMsg;
2224
+ throw res;
2225
+ }
2226
+ })
2227
+ .catch((err) => {
2228
+ //console.log("Error while Loging");
2229
+ throw err;
2230
+ });
2231
+ };
2232
+
2233
+ /**
2234
+ * Second stage of login. Gets the login data of user
2235
+ * @param {string} reqId Token collected after redirection from login
2236
+ * @returns response of login
2237
+ */
2238
+ __Token = function (reqId) {
2239
+ let url = this.__config.TokenURL();
2240
+ return this.__http
2241
+ .PostMethod(url, { reqId: reqId }, false)
2242
+ .then((res) => {
2243
+ // store data in constants
2244
+ this.__constants.Data = res;
2245
+ if (res.data.lgnData.accTyp == "EQ") {
2246
+ this.__constants.eqAccId = res.data.lgnData.accs.eqAccID;
2247
+ } else if (res.data.lgnData.accTyp == "CO") {
2248
+ this.__constants.coAccId = res.data.lgnData.accs.coAccID;
2249
+ } else if (res.data.lgnData.accTyp == "COMEQ") {
2250
+ this.__constants.eqAccId = res.data.lgnData.accs.eqAccID;
2251
+ this.__constants.coAccId = res.data.lgnData.accs.coAccID;
2252
+ }
2253
+ this.__constants.JSession = res.data.auth;
2254
+ return res;
2255
+ })
2256
+ .then((res) => {
2257
+ // store data in ${this.fileName} file
2258
+ return new Promise((resolve, reject) => {
2259
+ fs.writeFile(
2260
+ this.fileName,
2261
+ JSON.stringify({
2262
+ vt: this.__constants.VendorSession,
2263
+ auth: this.__constants.JSession,
2264
+ eqaccid: this.__constants.eqAccId,
2265
+ coaccid: this.__constants.coAccId,
2266
+ data: this.__constants.Data,
2267
+ appidkey: this.__constants.AppIdKey,
2268
+ }),
2269
+ (err) => {
2270
+ if (err) {
2271
+ reject(err);
2272
+ return;
2273
+ }
2274
+
2275
+ resolve(res);
2276
+ }
2277
+ );
2278
+ });
2279
+ })
2280
+ .catch((err) => {
2281
+ if (!err.error) {
2282
+ console.log("Error not defined", err);
2283
+ } else {
2284
+ err.msg = "ReqId: " + err.error.errMsg;
2285
+ }
2286
+ throw err;
2287
+ });
2288
+ };
2289
+
2290
+ Logout = () => {
2291
+ function deleteReadme(res) {
2292
+ if (res != "") {
2293
+ try {
2294
+ fs.unlinkSync(this.fileName);
2295
+ } catch {
2296
+ } finally {
2297
+ this.__constants.Data = "";
2298
+ return res;
2299
+ }
2300
+ }
2301
+ }
2302
+
2303
+ if (this.__constants.Data.data.lgnData.accTyp == "CO") {
2304
+ const url = this.__config.LogoutURL(this.__constants.coAccId);
2305
+ return this.__http.PutMethod(url, {}).then(deleteReadme);
2306
+ } else if (this.__constants.Data.data.lgnData.accTyp == "EQ") {
2307
+ // same for both EQ and COMEQ
2308
+ const url = this.__config.LogoutURL(this.__constants.eqAccId);
2309
+ return this.__http.PutMethod(url, {}).then(deleteReadme);
2310
+ }
2311
+ };
2312
+
2313
+ __getEqCommData(eqUrl, commUrl) {
2314
+ // call api and convert the result into this format
2315
+ // {eq: equityData, comm: commodityData}
2316
+ if (this.__constants.Data.data.lgnData.accTyp == "EQ") {
2317
+ return this.__http.GetMethod(eqUrl).then((eq) => ({ eq, comm: "" }));
2318
+ }
2319
+
2320
+ if (this.__constants.Data.data.lgnData.accTyp == "CO") {
2321
+ return this.__http.GetMethod(commUrl).then((comm) => ({ eq: "", comm }));
2322
+ }
2323
+
2324
+ if (this.__constants.Data.data.lgnData.accTyp == "COMEQ") {
2325
+ return Promise.all([
2326
+ this.__http.GetMethod(eqUrl),
2327
+ this.__http.GetMethod(commUrl),
2328
+ ]).then(([eq, comm]) => {
2329
+ return { eq, comm };
2330
+ });
2331
+ }
2332
+ }
2333
+ }
2334
+
2335
+ APIConnect.prototype.__constants = new __Constants();
2336
+ APIConnect.prototype.__config = new __Config();
2337
+ APIConnect.prototype.__http = new __Http(
2338
+ APIConnect.prototype.__constants,
2339
+ APIConnect.prototype.__config.baseurl
2340
+ );
2341
+
2342
+ module.exports = { APIConnect, Order };