api_connect_nodejs 2.0.2 → 2.0.5

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