api_connect_nodejs 1.0.1 → 2.0.1

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