1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', { value: true });
|
4 |
|
5 | var https = require('https');
|
6 | var ws = require('ws');
|
7 |
|
8 | function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
9 |
|
10 | var https__default = _interopDefaultLegacy(https);
|
11 |
|
12 | function queryString(data) {
|
13 | if (data == null)
|
14 | return '';
|
15 | var a = new URLSearchParams();
|
16 | for (var k in data)
|
17 | a.append(k, data[k]);
|
18 | return '?' + a.toString();
|
19 | }
|
20 | function getHttpError(error) {
|
21 | var a = error;
|
22 | a.code = 0;
|
23 | a.response = null;
|
24 | return a;
|
25 | }
|
26 | function getHttpResponseError(error, code, response) {
|
27 | var a = error;
|
28 | a.code = code;
|
29 | a.response = response;
|
30 | return a;
|
31 | }
|
32 | function hasHeader(key, o) {
|
33 | if (o.headers == null)
|
34 | return false;
|
35 | if (o.headers.hasOwnProperty(key))
|
36 | return true;
|
37 | if (o.headers.hasOwnProperty(key.toLowerCase()))
|
38 | return true;
|
39 | return false;
|
40 | }
|
41 | function setHeaders(headers, o) {
|
42 | if (o.body != null && !hasHeader('Content-Type', o)) {
|
43 | headers['content-type'] = 'application/json; charset=utf-8';
|
44 | }
|
45 | if (!hasHeader('Accept', o)) {
|
46 | headers['accept'] = 'application/json, text/*';
|
47 | }
|
48 | }
|
49 | function httpRequest(o) {
|
50 | return new Promise((resolve, reject) => {
|
51 | var { url, method, headers, timeout } = o;
|
52 | setHeaders(headers, o);
|
53 | var req = https__default["default"].request(url, { method, headers, timeout }, res => {
|
54 | var body = '';
|
55 | res.setEncoding('utf8');
|
56 | res.on('error', e => reject(getHttpResponseError(e, res.statusCode, body)));
|
57 | res.on('data', chunk => body += chunk);
|
58 | res.on('end', () => resolve(body));
|
59 | });
|
60 | req.on('error', e => reject(getHttpError(e)));
|
61 | if (o.body != null) {
|
62 | req.useChunkedEncodingByDefault = true;
|
63 | req.write(JSON.stringify(o.body));
|
64 | }
|
65 | req.end();
|
66 | });
|
67 | }
|
68 | function httpRequestText(options) {
|
69 | return httpRequest(options);
|
70 | }
|
71 | async function httpRequestJson(options) {
|
72 | var response = await httpRequest(options);
|
73 | return JSON.parse(response);
|
74 | }
|
75 |
|
76 | const API_URL = 'https://api.fyers.in/api/v2/';
|
77 | const DATA_URL = 'https://api.fyers.in/data-rest/v2/';
|
78 | const SYMBOLS_URL = 'https://public.fyers.in/sym_details/';
|
79 | function requestStep(auth, method, path, query, body) {
|
80 | var url = path + queryString(query);
|
81 | var headers = {};
|
82 | if (auth != null)
|
83 | headers['authorization'] = auth.app_id + ':' + auth.access_token;
|
84 | return { url, method, headers, body };
|
85 | }
|
86 | function requestText(auth, method, path, query, body) {
|
87 | return httpRequestText(requestStep(auth, method, path, query, body));
|
88 | }
|
89 | function requestJson(auth, method, path, query, body) {
|
90 | return httpRequestJson(requestStep(auth, method, path, query, body));
|
91 | }
|
92 | function requestApi(auth, method, path, query, body) {
|
93 | return requestJson(auth, method, API_URL + path, query, body);
|
94 | }
|
95 | function requestData(auth, method, path, query, body) {
|
96 | return requestJson(auth, method, DATA_URL + path, query, body);
|
97 | }
|
98 | function requestSymbols(auth, method, path, query, body) {
|
99 | return requestText(auth, method, SYMBOLS_URL + path, query, body);
|
100 | }
|
101 | function loginStep1$1(options) {
|
102 | return requestStep(null, 'GET', API_URL + 'generate-authcode', options, null);
|
103 | }
|
104 | function loginStep2$1(options) {
|
105 | return requestStep(null, 'POST', API_URL + 'validate-authcode', null, options);
|
106 | }
|
107 | function getProfile$1(auth) {
|
108 | return requestApi(auth, 'GET', 'profile', null, null);
|
109 | }
|
110 | function getFunds$1(auth) {
|
111 | return requestApi(auth, 'GET', 'funds', null, null);
|
112 | }
|
113 | function getHoldings$1(auth) {
|
114 | return requestApi(auth, 'GET', 'holdings', null, null);
|
115 | }
|
116 | function getOrder$1(auth, options) {
|
117 | return requestApi(auth, 'GET', 'orders', options, null);
|
118 | }
|
119 | function getOrders$1(auth) {
|
120 | return requestApi(auth, 'GET', 'orders', null, null);
|
121 | }
|
122 | function getPositions$1(auth) {
|
123 | return requestApi(auth, 'GET', 'positions', null, null);
|
124 | }
|
125 | function getTrades$1(auth) {
|
126 | return requestApi(auth, 'GET', 'tradebook', null, null);
|
127 | }
|
128 | function placeOrder$1(auth, options) {
|
129 | return requestApi(auth, 'POST', 'orders', null, options);
|
130 | }
|
131 | function placeOrders$1(auth, options) {
|
132 | return requestApi(auth, 'POST', 'orders-multi', null, options);
|
133 | }
|
134 | function modifyOrder$1(auth, options) {
|
135 | return requestApi(auth, 'PUT', 'orders', null, options);
|
136 | }
|
137 | function modifyOrders$1(auth, options) {
|
138 | return requestApi(auth, 'PUT', 'orders-multi', null, options);
|
139 | }
|
140 | function cancelOrder$1(auth, options) {
|
141 | return requestApi(auth, 'DELETE', 'orders', null, options);
|
142 | }
|
143 | function cancelOrders$1(auth, options) {
|
144 | return requestApi(auth, 'DELETE', 'orders-multi', null, options);
|
145 | }
|
146 | function exitPosition$1(auth, options) {
|
147 | return requestApi(auth, 'DELETE', 'positions', null, options);
|
148 | }
|
149 | function exitAllPositions$1(auth) {
|
150 | return requestApi(auth, 'DELETE', 'positions', null, {});
|
151 | }
|
152 | function convertPosition$1(auth, options) {
|
153 | return requestApi(auth, 'PUT', 'positions', null, options);
|
154 | }
|
155 | function getMarketStatus$1(auth) {
|
156 | return requestApi(auth, 'GET', 'market-status', null, null);
|
157 | }
|
158 | function getMarketHistory$1(auth, options) {
|
159 | return requestData(auth, 'GET', 'history/', options, null);
|
160 | }
|
161 | function getMarketQuotes$1(auth, options) {
|
162 | return requestData(auth, 'GET', 'quotes/', options, null);
|
163 | }
|
164 | function getMarketDepth$1(auth, options) {
|
165 | return requestData(auth, 'GET', 'depth/', options, null);
|
166 | }
|
167 | function getSymbolMaster$1(auth, options) {
|
168 | var { exchange, segment } = options;
|
169 | return requestSymbols(null, 'GET', exchange + '_' + segment + '.csv', null, null);
|
170 | }
|
171 | function generateEdisTpin$1(auth) {
|
172 | return requestApi(auth, 'GET', 'tpin', null, null);
|
173 | }
|
174 | function getEdisTransactions$1(auth) {
|
175 | return requestApi(auth, 'GET', 'details', null, null);
|
176 | }
|
177 | function submitEdisHoldingsStep$1(auth, options) {
|
178 | return requestStep(auth, 'POST', 'index', null, options);
|
179 | }
|
180 | function inquireEdisTransaction$1(auth, options) {
|
181 | return requestApi(auth, 'POST', 'inquiry', null, options);
|
182 | }
|
183 |
|
184 | var http = Object.freeze({
|
185 | __proto__: null,
|
186 | API_URL: API_URL,
|
187 | DATA_URL: DATA_URL,
|
188 | SYMBOLS_URL: SYMBOLS_URL,
|
189 | loginStep1: loginStep1$1,
|
190 | loginStep2: loginStep2$1,
|
191 | getProfile: getProfile$1,
|
192 | getFunds: getFunds$1,
|
193 | getHoldings: getHoldings$1,
|
194 | getOrder: getOrder$1,
|
195 | getOrders: getOrders$1,
|
196 | getPositions: getPositions$1,
|
197 | getTrades: getTrades$1,
|
198 | placeOrder: placeOrder$1,
|
199 | placeOrders: placeOrders$1,
|
200 | modifyOrder: modifyOrder$1,
|
201 | modifyOrders: modifyOrders$1,
|
202 | cancelOrder: cancelOrder$1,
|
203 | cancelOrders: cancelOrders$1,
|
204 | exitPosition: exitPosition$1,
|
205 | exitAllPositions: exitAllPositions$1,
|
206 | convertPosition: convertPosition$1,
|
207 | getMarketStatus: getMarketStatus$1,
|
208 | getMarketHistory: getMarketHistory$1,
|
209 | getMarketQuotes: getMarketQuotes$1,
|
210 | getMarketDepth: getMarketDepth$1,
|
211 | getSymbolMaster: getSymbolMaster$1,
|
212 | generateEdisTpin: generateEdisTpin$1,
|
213 | getEdisTransactions: getEdisTransactions$1,
|
214 | submitEdisHoldingsStep: submitEdisHoldingsStep$1,
|
215 | inquireEdisTransaction: inquireEdisTransaction$1
|
216 | });
|
217 |
|
218 | const MARKET_DATA_URL = "wss://api.fyers.in/socket/v2/dataSock";
|
219 | const ORDER_UPDATE_URL = "wss://api.fyers.in/socket/v2/orderSock";
|
220 | const MARKET_DATA_QUERY = "user-agent=fyers-api&type=symbolUpdate";
|
221 | const ORDER_UPDATE_QUERY = "user-agent=fyers-api&type=orderUpdate";
|
222 | const PING_INTERVAL = 5000;
|
223 | function writeHeader(a, x, i) {
|
224 | a.token = x.getBigUint64(i + 0);
|
225 | a.tt = x.getUint32(i + 8);
|
226 | a.fyCode = x.getUint16(i + 12);
|
227 | a.marketStat = x.getUint16(i + 14);
|
228 | a.pktlen = x.getUint16(i + 16);
|
229 | a.L2 = x.getUint8(i + 18);
|
230 | }
|
231 | function writeOiData(a, x, i) {
|
232 | a.oi = BigInt(x.getUint32(i + 0));
|
233 | a.pdoi = BigInt(x.getUint32(i + 4));
|
234 | }
|
235 | function writeCommonData(a, x, i, hasOi) {
|
236 | a.price_conv = x.getUint32(i + 0);
|
237 | a.ltp = x.getUint32(i + 4);
|
238 | a.open_price = x.getUint32(i + 8);
|
239 | a.high_price = x.getUint32(i + 12);
|
240 | a.low_price = x.getUint32(i + 16);
|
241 | a.prev_close_price = x.getUint32(i + 20);
|
242 | a.o = x.getUint32(i + 24);
|
243 | a.h = x.getUint32(i + 28);
|
244 | a.l = x.getUint32(i + 32);
|
245 | a.c = x.getUint32(i + 36);
|
246 | a.v = x.getBigUint64(i + 40);
|
247 | if (!hasOi)
|
248 | return;
|
249 | a.oi = x.getBigUint64(i + 48);
|
250 | a.pdoi = x.getBigUint64(i + 56);
|
251 | }
|
252 | function writeL1Data(a, x, i, bidAsk) {
|
253 | a.LTQ = x.getUint32(i + 0);
|
254 | a.L2_LTT = x.getUint32(i + 4);
|
255 | a.ATP = x.getUint32(i + 8);
|
256 | a.volume = x.getUint32(i + 12);
|
257 | a.tot_buy = x.getBigUint64(i + 16);
|
258 | a.tot_sell = x.getBigUint64(i + 24);
|
259 | if (!bidAsk)
|
260 | return;
|
261 | a.bid = x.getUint32(i + 32);
|
262 | a.ask = x.getUint32(i + 36);
|
263 | }
|
264 | function toL2MarketOffer(x, i) {
|
265 | return {
|
266 | price: x.getUint32(i + 0),
|
267 | volume: x.getUint32(i + 4),
|
268 | ord: x.getUint32(i + 8),
|
269 | };
|
270 | }
|
271 | function writeL2Data(a, x, i) {
|
272 | var bids = [], asks = [];
|
273 | for (var j = 0; j < 60; j += 12) {
|
274 | bids.push(toL2MarketOffer(x, i + j));
|
275 | asks.push(toL2MarketOffer(x, i + j + 60));
|
276 | }
|
277 | a.bids = bids;
|
278 | a.asks = asks;
|
279 | }
|
280 | function writeMarketData(a, x, i) {
|
281 | writeHeader(a, x, i + 0);
|
282 | var hasOi = a.fyCode === 7202 || a.fyCode === 31038;
|
283 | var l1Off = hasOi ? 88 : 72;
|
284 | if (a.fyCode === 7202)
|
285 | writeOiData(a, x, i + 24);
|
286 | else
|
287 | writeCommonData(a, x, i + 24, hasOi);
|
288 | if (a.fyCode === 7208 || a.fyCode === 31038)
|
289 | writeL1Data(a, x, i + l1Off, a.L2 !== 1);
|
290 | if (a.L2 === 1)
|
291 | writeL2Data(a, x, i + l1Off + 32);
|
292 | }
|
293 | function toMarketData(x, i) {
|
294 | var a = {
|
295 | token: BigInt(0),
|
296 | tt: 0,
|
297 | fyCode: 0,
|
298 | marketStat: 0,
|
299 | pktlen: 0,
|
300 | L2: 0,
|
301 | price_conv: 0,
|
302 | ltp: 0,
|
303 | open_price: 0,
|
304 | high_price: 0,
|
305 | low_price: 0,
|
306 | prev_close_price: 0,
|
307 | o: 0,
|
308 | h: 0,
|
309 | l: 0,
|
310 | c: 0,
|
311 | v: BigInt(0),
|
312 | oi: BigInt(0),
|
313 | pdoi: BigInt(0),
|
314 | LTQ: 0,
|
315 | L2_LTT: 0,
|
316 | ATP: 0,
|
317 | volume: 0,
|
318 | tot_buy: BigInt(0),
|
319 | tot_sell: BigInt(0),
|
320 | bid: 0,
|
321 | ask: 0,
|
322 | bids: null,
|
323 | asks: null,
|
324 | };
|
325 | writeMarketData(a, x, i);
|
326 | return a;
|
327 | }
|
328 | class Connection extends ws.WebSocket {
|
329 | constructor() {
|
330 | super(...arguments);
|
331 | this.recievers = [];
|
332 | }
|
333 | }
|
334 | function waitResponse(conn) {
|
335 | return new Promise((resolve, reject) => conn.recievers.push({ resolve, reject }));
|
336 | }
|
337 | function connectOrderUpdate$1(auth, fn) {
|
338 | return new Promise((resolve, reject) => {
|
339 | var { app_id, access_token } = auth;
|
340 | var query = `${ORDER_UPDATE_QUERY}&access_token=${app_id}:${access_token}`;
|
341 | var conn = new Connection(`${ORDER_UPDATE_URL}?${query}`);
|
342 | var ping = setInterval(() => {
|
343 | if (conn.readyState !== ws.WebSocket.OPEN)
|
344 | return;
|
345 | conn.send("ping");
|
346 | }, PING_INTERVAL);
|
347 | conn.binaryType = "arraybuffer";
|
348 | conn.onerror = e => {
|
349 | for (var r of conn.recievers)
|
350 | r.reject(e.error);
|
351 | clearInterval(ping);
|
352 | reject(e.error);
|
353 | };
|
354 | conn.onopen = () => resolve(conn);
|
355 | conn.onmessage = e => {
|
356 | if (typeof e.data !== "string")
|
357 | return;
|
358 | if (e.data === "pong")
|
359 | return;
|
360 | var x = JSON.parse(e.data);
|
361 | fn(x);
|
362 | if (x.hasOwnProperty("d") || x.code === 0)
|
363 | return;
|
364 | if (conn.recievers.length > 0)
|
365 | conn.recievers.shift().resolve(x);
|
366 | };
|
367 | });
|
368 | }
|
369 | function subscribeOrderUpdate$1(conn) {
|
370 | var req = { T: "SUB_ORD", SLIST: ["orderUpdate"], SUB_T: 1 };
|
371 | conn.send(JSON.stringify(req));
|
372 | return waitResponse(conn);
|
373 | }
|
374 | function unsubscribeOrderUpdate$1(conn) {
|
375 | var req = { T: "SUB_ORD", SLIST: ["orderUpdate"], SUB_T: 0 };
|
376 | conn.send(JSON.stringify(req));
|
377 | return waitResponse(conn);
|
378 | }
|
379 | function connectMarketData$1(auth, fn) {
|
380 | return new Promise((resolve, reject) => {
|
381 | var { app_id, access_token } = auth;
|
382 | var query = `${MARKET_DATA_QUERY}&access_token=${app_id}:${access_token}`;
|
383 | var conn = new Connection(`${MARKET_DATA_URL}?${query}`);
|
384 | var ping = setInterval(() => {
|
385 | if (conn.readyState !== ws.WebSocket.OPEN)
|
386 | return;
|
387 | conn.send("ping");
|
388 | }, PING_INTERVAL);
|
389 | conn.binaryType = "arraybuffer";
|
390 | conn.onerror = e => {
|
391 | for (var r of conn.recievers)
|
392 | r.reject(e.error);
|
393 | clearInterval(ping);
|
394 | reject(e.error);
|
395 | };
|
396 | conn.onopen = () => resolve(conn);
|
397 | conn.onmessage = e => {
|
398 | if (typeof e.data === "string") {
|
399 | if (e.data === "pong")
|
400 | return;
|
401 | var x = JSON.parse(e.data);
|
402 | fn(x);
|
403 | if (x.hasOwnProperty("d") || x.code === 0)
|
404 | return;
|
405 | if (conn.recievers.length > 0)
|
406 | conn.recievers.shift().resolve(x);
|
407 | }
|
408 | else {
|
409 | var binary = new DataView(e.data);
|
410 | fn({ s: "ok", d: toMarketData(binary, 0) });
|
411 | }
|
412 | };
|
413 | });
|
414 | }
|
415 | function subscribeMarketQuote$1(conn, symbols) {
|
416 | var req = { T: "SUB_DATA", TLIST: symbols, SUB_T: 1 };
|
417 | conn.send(JSON.stringify(req));
|
418 | return waitResponse(conn);
|
419 | }
|
420 | function subscribeMarketDepth$1(conn, symbols) {
|
421 | var req = { T: "SUB_L2", L2LIST: symbols, SUB_T: 1 };
|
422 | conn.send(JSON.stringify(req));
|
423 | return waitResponse(conn);
|
424 | }
|
425 | function unsubscribeMarketQuote$1(conn, symbols) {
|
426 | var req = { T: "SUB_DATA", TLIST: symbols, SUB_T: 0 };
|
427 | conn.send(JSON.stringify(req));
|
428 | return waitResponse(conn);
|
429 | }
|
430 | function unsubscribeMarketDepth$1(conn, symbols) {
|
431 | var req = { T: "SUB_L2", L2LIST: symbols, SUB_T: 0 };
|
432 | conn.send(JSON.stringify(req));
|
433 | return waitResponse(conn);
|
434 | }
|
435 |
|
436 | var websocket = Object.freeze({
|
437 | __proto__: null,
|
438 | MARKET_DATA_URL: MARKET_DATA_URL,
|
439 | ORDER_UPDATE_URL: ORDER_UPDATE_URL,
|
440 | Connection: Connection,
|
441 | connectOrderUpdate: connectOrderUpdate$1,
|
442 | subscribeOrderUpdate: subscribeOrderUpdate$1,
|
443 | unsubscribeOrderUpdate: unsubscribeOrderUpdate$1,
|
444 | connectMarketData: connectMarketData$1,
|
445 | subscribeMarketQuote: subscribeMarketQuote$1,
|
446 | subscribeMarketDepth: subscribeMarketDepth$1,
|
447 | unsubscribeMarketQuote: unsubscribeMarketQuote$1,
|
448 | unsubscribeMarketDepth: unsubscribeMarketDepth$1
|
449 | });
|
450 |
|
451 | const TO_EXCHANGE = new Map([
|
452 | [10, "NSE"],
|
453 | [11, "MCX"],
|
454 | [12, "BSE"],
|
455 | ]);
|
456 | const EXCHANGE_DESCRIPTION = new Map([
|
457 | ["NSE", "National Stock Exchange"],
|
458 | ["MCX", "Multi Commodity Exchange"],
|
459 | ["BSE", "Bombay Stock Exchange"],
|
460 | ]);
|
461 | function toExchange(x) {
|
462 | return TO_EXCHANGE.get(x);
|
463 | }
|
464 | function exchangeDescription(code) {
|
465 | return EXCHANGE_DESCRIPTION.get(code);
|
466 | }
|
467 | function exchange(desc) {
|
468 | if (/bse|native|bombay|mumbai/i.test(desc))
|
469 | return "BSE";
|
470 | if (/\bcom\b|mcx|multi|commodit/i.test(desc))
|
471 | return "MCX";
|
472 | return "NSE";
|
473 | }
|
474 | const TO_SEGMENT = new Map([
|
475 | [10, "CM"],
|
476 | [11, "FO"],
|
477 | [12, "CD"],
|
478 | [20, "COM"],
|
479 | ]);
|
480 | const SEGMENT_DESCRIPTION = new Map([
|
481 | ["CM", "Capital Market"],
|
482 | ["FO", "Equity Derivatives"],
|
483 | ["CD", "Currency Derivatives"],
|
484 | ["COM", "Commodity Derivatives"],
|
485 | ]);
|
486 | function toSegment(x) {
|
487 | return TO_SEGMENT.get(x);
|
488 | }
|
489 | function segmentDescription(code) {
|
490 | return SEGMENT_DESCRIPTION.get(code);
|
491 | }
|
492 | function segment(desc) {
|
493 | if (/\bcom\b|mcx|multi|commodit/i.test(desc))
|
494 | return "COM";
|
495 | if (/\bcd\b|currenc/i.test(desc))
|
496 | return "CD";
|
497 | if (/\bfn?o\b|fut|opt|deriv/i.test(desc))
|
498 | return "FO";
|
499 | return "CM";
|
500 | }
|
501 | const TO_POSITION_SIDE = new Map([
|
502 | [1, "LONG"],
|
503 | [-1, "SHORT"],
|
504 | [0, "CLOSED"],
|
505 | ]);
|
506 | const FROM_POSITION_SIDE = new Map([
|
507 | ["LONG", 1],
|
508 | ["SHORT", -1],
|
509 | ["CLOSED", 0],
|
510 | ]);
|
511 | const POSITION_SIDE_DESCRIPTION = new Map([
|
512 | ["LONG", "Long position"],
|
513 | ["SHORT", "Short position"],
|
514 | ["CLOSED", "Closed position"],
|
515 | ]);
|
516 | function toPositionSide(x) {
|
517 | return TO_POSITION_SIDE.get(x);
|
518 | }
|
519 | function fromPositionSide(x) {
|
520 | return FROM_POSITION_SIDE.get(x);
|
521 | }
|
522 | function positionSideDescription(code) {
|
523 | return POSITION_SIDE_DESCRIPTION.get(code);
|
524 | }
|
525 | function positionSide(desc) {
|
526 | if (/up|buy|long|rally/i.test(desc))
|
527 | return "LONG";
|
528 | if (/down|sell|short|crash/i.test(desc))
|
529 | return "SHORT";
|
530 | return "CLOSED";
|
531 | }
|
532 | const TO_ORDER_SIDE = new Map([
|
533 | [1, "BUY"],
|
534 | [-1, "SELL"],
|
535 | ]);
|
536 | const FROM_ORDER_SIDE = new Map([
|
537 | ["BUY", 1],
|
538 | ["SELL", -1],
|
539 | ]);
|
540 | const ORDER_SIDE_DESCRIPTION = new Map([
|
541 | ["BUY", "Buy"],
|
542 | ["SELL", "Sell"],
|
543 | ]);
|
544 | function toOrderSide(x) {
|
545 | return TO_ORDER_SIDE.get(x);
|
546 | }
|
547 | function fromOrderSide(x) {
|
548 | return FROM_ORDER_SIDE.get(x);
|
549 | }
|
550 | function orderSideDescription(code) {
|
551 | return ORDER_SIDE_DESCRIPTION.get(code);
|
552 | }
|
553 | function orderSide(desc) {
|
554 | return /down|sell|short|crash/i.test(desc) ? "SELL" : "BUY";
|
555 | }
|
556 | const TO_ORDER_SOURCE = new Map([
|
557 | ["M", "MOBILE"],
|
558 | ["W", "WEB"],
|
559 | ["R", "ONE"],
|
560 | ["A", "ADMIN"],
|
561 | ["ITS", "API"],
|
562 | ]);
|
563 | const ORDER_SOURCE_DESCRIPTION = new Map([
|
564 | ["MOBILE", "FYERS Mobile"],
|
565 | ["WEB", "FYERS Web"],
|
566 | ["ONE", "FYERS One"],
|
567 | ["ADMIN", "Admin"],
|
568 | ["API", "FYERS API"],
|
569 | ]);
|
570 | function toOrderSource(x) {
|
571 | return TO_ORDER_SOURCE.get(x);
|
572 | }
|
573 | function orderSourceDescription(code) {
|
574 | return ORDER_SOURCE_DESCRIPTION.get(code);
|
575 | }
|
576 | function orderSource(desc) {
|
577 | if (/its|api|sys/i.test(desc))
|
578 | return "API";
|
579 | if (/one|desk/i.test(desc))
|
580 | return "ONE";
|
581 | if (/mob|app/i.test(desc))
|
582 | return "MOBILE";
|
583 | if (/admin/i.test(desc))
|
584 | return "ADMIN";
|
585 | return "WEB";
|
586 | }
|
587 | const TO_ORDER_STATUS = new Map([
|
588 | [1, "CANCELLED"],
|
589 | [2, "TRADED"],
|
590 | [4, "TRANSIT"],
|
591 | [5, "REJECTED"],
|
592 | [6, "PENDING"],
|
593 | [7, "EXPIRED"],
|
594 | ]);
|
595 | const ORDER_STATUS_DESCRIPTION = new Map([
|
596 | ["CANCELLED", "Cancelled"],
|
597 | ["TRADED", "Traded / Filled"],
|
598 | ["TRANSIT", "Transit"],
|
599 | ["REJECTED", "Rejected"],
|
600 | ["PENDING", "Pending"],
|
601 | ["EXPIRED", "Expired"],
|
602 | ]);
|
603 | const ORDER_STATUS_CODE = new Map([
|
604 | ["C", "CANCELLED"],
|
605 | ["F", "TRADED"],
|
606 | ["T", "TRANSIT"],
|
607 | ["R", "REJECTED"],
|
608 | ["P", "PENDING"],
|
609 | ["E", "EXPIRED"],
|
610 | ]);
|
611 | function toOrderStatus(x) {
|
612 | return TO_ORDER_STATUS.get(x);
|
613 | }
|
614 | function orderStatusDescription(code) {
|
615 | return ORDER_STATUS_DESCRIPTION.get(code);
|
616 | }
|
617 | function orderStatus(desc) {
|
618 | var key = desc.charAt(0).toUpperCase();
|
619 | if (/traded/i.test(desc))
|
620 | key = "F";
|
621 | return ORDER_STATUS_CODE.get(key);
|
622 | }
|
623 | const TO_ORDER_TYPE = new Map([
|
624 | [1, "LIMIT"],
|
625 | [2, "MARKET"],
|
626 | [3, "SL_MARKET"],
|
627 | [4, "SL_LIMIT"],
|
628 | ]);
|
629 | const FROM_ORDER_TYPE = new Map([
|
630 | ["LIMIT", 1],
|
631 | ["MARKET", 2],
|
632 | ["SL_MARKET", 3],
|
633 | ["SL_LIMIT", 4],
|
634 | ]);
|
635 | const ORDER_TYPE_DESCRIPTION = new Map([
|
636 | ["LIMIT", "Limit order"],
|
637 | ["MARKET", "Market order"],
|
638 | ["SL_MARKET", "Stop order (SL-M)"],
|
639 | ["SL_LIMIT", "Stoplimit order (SL-L)"],
|
640 | ]);
|
641 | const ORDER_TYPE_CODE = new Map([
|
642 | ["L", "LIMIT"],
|
643 | ["M", "MARKET"],
|
644 | ["S", "SL_MARKET"],
|
645 | ["R", "SL_LIMIT"],
|
646 | ]);
|
647 | function toOrderType(x) {
|
648 | return TO_ORDER_TYPE.get(x);
|
649 | }
|
650 | function fromOrderType(x) {
|
651 | return FROM_ORDER_TYPE.get(x);
|
652 | }
|
653 | function orderTypeDescription(code) {
|
654 | return ORDER_TYPE_DESCRIPTION.get(code);
|
655 | }
|
656 | function orderType(desc) {
|
657 | var key = desc.charAt(0).toUpperCase();
|
658 | if (/s.+l(?!oss)/i.test(desc))
|
659 | key = "R";
|
660 | return ORDER_TYPE_CODE.get(key);
|
661 | }
|
662 | const ORDER_VALIDITY_DESCRIPTION = new Map([
|
663 | ["DAY", "End of day validity"],
|
664 | ["IOC", "Immediate or Cancel validity"],
|
665 | ]);
|
666 | function toOrderValidity(x) {
|
667 | return x;
|
668 | }
|
669 | function orderValidityDescription(code) {
|
670 | return ORDER_VALIDITY_DESCRIPTION.get(code);
|
671 | }
|
672 | function orderValidity(desc) {
|
673 | return /ioc|cancel|immediate/i.test(desc) ? "IOC" : "DAY";
|
674 | }
|
675 | const OPTION_TYPE_DESCRIPTION = new Map([
|
676 | ["CE", "Call option"],
|
677 | ["PE", "Put option"],
|
678 | ]);
|
679 | function optionTypeDescription(code) {
|
680 | return OPTION_TYPE_DESCRIPTION.get(code);
|
681 | }
|
682 | function optionType(desc) {
|
683 | return /pe|put|sell/i.test(desc) ? "PE" : "CE";
|
684 | }
|
685 | const DERIVATIVE_TYPE_DESCRIPTION = new Map([
|
686 | ["FUT", "Future"],
|
687 | ["CE", "Call option"],
|
688 | ["PE", "Put option"],
|
689 | ]);
|
690 | function derivativeTypeDescription(code) {
|
691 | return DERIVATIVE_TYPE_DESCRIPTION.get(code);
|
692 | }
|
693 | function derivativeType(desc) {
|
694 | return /fut|lat|buy/.test(desc) ? "FUT" : optionType(desc);
|
695 | }
|
696 | const HOLDING_TYPE_DESCRIPTION = new Map([
|
697 | ["T1", "The shares are purchased but not yet delivered to the demat account"],
|
698 | ["HLD", "The shares are purchased and are available in the demat account"],
|
699 | ]);
|
700 | function toHoldingType(x) {
|
701 | return x;
|
702 | }
|
703 | function holdingTypeDescription(code) {
|
704 | return HOLDING_TYPE_DESCRIPTION.get(code);
|
705 | }
|
706 | function holdingType(desc) {
|
707 | return /un|not|pend|t1/i.test(desc) ? "T1" : "HLD";
|
708 | }
|
709 | const PRODUCT_TYPE_DESCRIPTION = new Map([
|
710 | ["CNC", "Cash N Carry or Delivery Order, for equity only"],
|
711 | ["INTRADAY", "Intraday Order, applicable for all segments"],
|
712 | ["MARGIN", "Margin Order, applicable only for derivatives"],
|
713 | ["CO", "Cover Order"],
|
714 | ["BO", "Bracket Order"],
|
715 | ]);
|
716 | const PRODUCT_TYPE_CODE = new Map([
|
717 | ["D", "CNC"],
|
718 | ["I", "INTRADAY"],
|
719 | ["M", "MARGIN"],
|
720 | ["C", "CO"],
|
721 | ["B", "BO"],
|
722 | ]);
|
723 | function toProductType(x) {
|
724 | return x;
|
725 | }
|
726 | function fromProductType(x) {
|
727 | return x;
|
728 | }
|
729 | function productTypeDescription(code) {
|
730 | return PRODUCT_TYPE_DESCRIPTION.get(code);
|
731 | }
|
732 | function productType(desc) {
|
733 | var key = desc.charAt(0).toUpperCase();
|
734 | if (/cnc|cash|carry|deliver/i.test(desc))
|
735 | key = "D";
|
736 | return PRODUCT_TYPE_CODE.get(key);
|
737 | }
|
738 | const TO_INSTRUMENT_TYPE = new Map([
|
739 | [0, "EQ"],
|
740 | [1, "PREFSHARES"],
|
741 | [2, "DEBENTURES"],
|
742 | [3, "WARRANTS"],
|
743 | [4, "MISC"],
|
744 | [10, "INDEX"],
|
745 | [11, "FUTIDX"],
|
746 | [12, "FUTIVX"],
|
747 | [13, "FUTSTK"],
|
748 | [14, "OPTIDX"],
|
749 | [15, "OPTSTK"],
|
750 | [16, "FUTCUR"],
|
751 | [17, "FUTIRT"],
|
752 | [18, "FUTIRC"],
|
753 | [19, "OPTCUR"],
|
754 | [20, "UNDCUR"],
|
755 | [21, "UNDIRC"],
|
756 | [22, "UNDIRT"],
|
757 | [23, "UNDIRD"],
|
758 | [24, "INDEX_CD"],
|
759 | [25, "FUTIRD"],
|
760 | [30, "FUTCOM"],
|
761 | [31, "OPTFUT"],
|
762 | [32, "OPTCOM"],
|
763 | ]);
|
764 | const INSTRUMENT_TYPE_DESCRIPTION = new Map([
|
765 | ["EQ", "Equity Shares"],
|
766 | ["PREFSHARES", "Preference Shares"],
|
767 | ["DEBENTURES", "Collateral-free Debt"],
|
768 | ["WARRANTS", "Warrants on Stock"],
|
769 | ["MISC", "Miscellaneous"],
|
770 | ["INDEX", "Stock Market Index"],
|
771 | ["FUTIDX", "Futures on Index"],
|
772 | ["FUTIVX", "Futures on Volatility Index"],
|
773 | ["FUTSTK", "Futures on Stock"],
|
774 | ["OPTIDX", "Options on Index"],
|
775 | ["OPTSTK", "Options on Stock"],
|
776 | ["FUTCUR", "Futures on Currency"],
|
777 | ["FUTIRT", "Futures on Government of India Treasury Bills"],
|
778 | ["FUTIRC", "Futures on Government of India Bonds"],
|
779 | ["OPTCUR", "Options on Currency"],
|
780 | ["UNDCUR", "Underlying on Currency"],
|
781 | ["UNDIRC", "Underlying on Government of Bonds"],
|
782 | ["UNDIRT", "Underlying on Government of India Treasury Bills"],
|
783 | ["UNDIRD", "Underlying on 10 Year Notional coupon bearing GOI security"],
|
784 | ["INDEX_CD", "Market-indexed Certificate of deposit"],
|
785 | ["FUTIRD", "Futures on 10 Year Notional coupon bearing GOI security"],
|
786 | ["FUTCOM", "Futures on Commodity"],
|
787 | ["OPTFUT", "Options on Commodity Futures"],
|
788 | ["OPTCOM", "Options on Commodity"],
|
789 | ]);
|
790 | function toInstrumentType(x) {
|
791 | return TO_INSTRUMENT_TYPE.get(x);
|
792 | }
|
793 | function instrumentTypeDescription(code) {
|
794 | return INSTRUMENT_TYPE_DESCRIPTION.get(code);
|
795 | }
|
796 | function instrumentType(desc) {
|
797 | var fut = /fut|future/i.test(desc);
|
798 | var opt = /opt|option/i.test(desc);
|
799 | var idx = /idx|index/i.test(desc);
|
800 | var und = /und|underlying/i.test(desc);
|
801 | if (/com(\b|$)|commodit/i.test(desc)) {
|
802 | if (opt)
|
803 | return fut ? "OPTFUT" : "OPTCOM";
|
804 | else if (idx)
|
805 | return "FUTIDX";
|
806 | else
|
807 | return "FUTCOM";
|
808 | }
|
809 | else if (/(^|\b)und|cd(\b|$)|ir[cdt](\b|$)|cur|gov|bond|trea|coup/i.test(desc)) {
|
810 | if (/irc(\b|$)|bond/i.test(desc))
|
811 | return und ? "UNDIRC" : "FUTIRC";
|
812 | else if (/ird(\b|$)|coup/i.test(desc))
|
813 | return und ? "UNDIRD" : "FUTIRD";
|
814 | else if (/irt(\b|$)|trea/i.test(desc))
|
815 | return und ? "UNDIRT" : "FUTIRT";
|
816 | else
|
817 | return idx ? "INDEX_CD" : (opt ? "OPTCUR" : "FUTCUR");
|
818 | }
|
819 | else if (fut || opt) {
|
820 | if (/ivx|volatil/i.test(desc))
|
821 | return "FUTIVX";
|
822 | else if (idx)
|
823 | return opt ? "OPTIDX" : "FUTIDX";
|
824 | else
|
825 | return opt ? "OPTSTK" : "FUTSTK";
|
826 | }
|
827 | else {
|
828 | if (idx)
|
829 | return "INDEX";
|
830 | else if (/misc/i.test(desc))
|
831 | return "MISC";
|
832 | else if (/warrant/i.test(desc))
|
833 | return "WARRANTS";
|
834 | else if (/deb/i.test(desc))
|
835 | return "DEBENTURES";
|
836 | else if (/pref/i.test(desc))
|
837 | return "PREFSHARES";
|
838 | }
|
839 | return "EQ";
|
840 | }
|
841 | const RSYMBOL_NAME = /^\w+:(.+?)-\w+$|^\w+:(.+?)\d{2}\w{3}FUT$|^\w+:(.+?)\d{2}\w{3}[\d\.]+[CP]E$|^\w+:(.+?)\d{2}\w{1}\d{2}[\d\.]+[CP]E$/;
|
842 | function toSymbolDetails(row) {
|
843 | var [token, description, , lotSize, , isin, , , , symbol] = row.split(',');
|
844 | return { symbol, token, description, lotSize: parseInt(lotSize, 10), isin: isin || "" };
|
845 | }
|
846 | function symbolName(code) {
|
847 | var m = RSYMBOL_NAME.exec(code);
|
848 | return m[1] || m[2] || m[3] || m[4];
|
849 | }
|
850 | function symbolExchange(code) {
|
851 | var i = code.indexOf(":");
|
852 | return code.substring(0, i);
|
853 | }
|
854 | function symbolSeries(code) {
|
855 | var i = code.lastIndexOf("-");
|
856 | return i > 0 ? code.substring(i) : null;
|
857 | }
|
858 | function symbolOptionType(code) {
|
859 | var a = code.substring(code.length - 2);
|
860 | return a === "CE" || a === "PE" ? a : null;
|
861 | }
|
862 | function symbolDerivativeType(code) {
|
863 | var m = /(?:FUT|CE|PE)$/.exec(code);
|
864 | return m != null ? m[0] : null;
|
865 | }
|
866 | function symbolStrikePrice(code) {
|
867 | var RSTRIKE = /([\d\.]+)[CP]E$/, m = RSTRIKE.exec(code);
|
868 | return m != null ? parseFloat(m[1]) : 0;
|
869 | }
|
870 | function symbolToken(code, map) {
|
871 | return map.get(code).token;
|
872 | }
|
873 | function symbolDescription(code, map) {
|
874 | return map.get(code).description;
|
875 | }
|
876 | function symbolIsin(code, map) {
|
877 | return map.get(code).isin;
|
878 | }
|
879 | function symbolLotSize(code, map) {
|
880 | return map.get(code).lotSize;
|
881 | }
|
882 | function fromAuthorization(x) {
|
883 | return {
|
884 | app_id: x.appId,
|
885 | access_token: x.accessToken,
|
886 | };
|
887 | }
|
888 | function fromLoginStep1Request(x) {
|
889 | return {
|
890 | client_id: x.appId,
|
891 | redirect_uri: x.redirectUrl,
|
892 | response_type: "code",
|
893 | state: x.state,
|
894 | };
|
895 | }
|
896 | function fromLoginStep2Request(x) {
|
897 | return {
|
898 | grant_type: "authorization_code",
|
899 | appIdHash: x.appHash,
|
900 | code: x.authorizationCode,
|
901 | };
|
902 | }
|
903 | function toProfile(x) {
|
904 | var d = x.data;
|
905 | return {
|
906 | id: d.fy_id,
|
907 | email: d.email_id,
|
908 | name: d.name,
|
909 | pan: d.PAN,
|
910 | };
|
911 | }
|
912 | function toFunds(x) {
|
913 | var e = {};
|
914 | var c = {};
|
915 | for (var l of x.fund_limit) {
|
916 | switch (l.id) {
|
917 | case 9 :
|
918 | e.start = l.equityAmount;
|
919 | c.start = l.commodityAmount;
|
920 | break;
|
921 | case 6 :
|
922 | e.deposits = l.equityAmount;
|
923 | c.deposits = l.commodityAmount;
|
924 | break;
|
925 | case 4 :
|
926 | e.realizedReturns = l.equityAmount;
|
927 | c.realizedReturns = l.commodityAmount;
|
928 | break;
|
929 | case 5 :
|
930 | e.collaterals = l.equityAmount;
|
931 | c.collaterals = l.commodityAmount;
|
932 | break;
|
933 | case 8 :
|
934 | e.adhoc = l.equityAmount;
|
935 | c.adhoc = l.commodityAmount;
|
936 | break;
|
937 | case 2 :
|
938 | e.utilized = l.equityAmount;
|
939 | c.utilized = l.commodityAmount;
|
940 | break;
|
941 | case 7 :
|
942 | e.receivables = l.equityAmount;
|
943 | c.receivables = l.commodityAmount;
|
944 | break;
|
945 | case 10 :
|
946 | e.available = l.equityAmount;
|
947 | c.available = l.commodityAmount;
|
948 | break;
|
949 | case 3 :
|
950 | e.clear = l.equityAmount;
|
951 | c.clear = l.commodityAmount;
|
952 | break;
|
953 | case 1 :
|
954 | e.total = l.equityAmount;
|
955 | c.total = l.commodityAmount;
|
956 | break;
|
957 | }
|
958 | }
|
959 | return { equity: e, commodity: c };
|
960 | }
|
961 | function toHolding(x) {
|
962 | return {
|
963 | isin: x.isin,
|
964 | symbol: x.symbol,
|
965 | token: x.fytoken,
|
966 | exchange: toExchange(x.exchange),
|
967 | type: toHoldingType(x.holdingType),
|
968 | quantity: x.quantity,
|
969 | remainingQuantity: x.remainingQuantity,
|
970 | buyPrice: x.costPrice,
|
971 | buyValue: x.costPrice * x.quantity,
|
972 | currentPrice: x.ltp,
|
973 | currentValue: x.marketVal,
|
974 | returns: x.pl,
|
975 | returnsPercent: x.pl / (x.costPrice * x.quantity),
|
976 | };
|
977 | }
|
978 | function toHoldingsOverall(xs, x) {
|
979 | var settledCount = 0;
|
980 | for (var h of xs)
|
981 | if (h.holdingType === "HLD")
|
982 | settledCount++;
|
983 | return {
|
984 | count: x.count_total,
|
985 | settledCount,
|
986 | investedValue: x.total_investment,
|
987 | currentValue: x.total_current_value,
|
988 | returns: x.total_pl,
|
989 | returnsPercent: x.pnl_perc,
|
990 | };
|
991 | }
|
992 | function toHoldings(x) {
|
993 | return {
|
994 | details: x.holdings.map(toHolding),
|
995 | overall: toHoldingsOverall(x.holdings, x.overall),
|
996 | };
|
997 | }
|
998 | function toOrder(x) {
|
999 | return {
|
1000 | id: x.id,
|
1001 | symbol: x.symbol,
|
1002 | token: x.fytoken,
|
1003 | name: x.ex_sym,
|
1004 | description: x.description,
|
1005 | segment: toSegment(x.segment),
|
1006 | instrument: toInstrumentType(x.instrument),
|
1007 | exchange: toExchange(x.exchange),
|
1008 | type: toOrderType(x.type),
|
1009 | side: toOrderSide(x.side),
|
1010 | productType: toProductType(x.productType),
|
1011 | source: toOrderSource(x.source) || null,
|
1012 | status: toOrderStatus(x.status),
|
1013 | offline: x.offlineOrder === "True",
|
1014 | limitPrice: x.limitPrice,
|
1015 | stopPrice: x.stopPrice,
|
1016 | quantity: x.qty,
|
1017 | remainingQuantity: x.remainingQuantity,
|
1018 | tradedQuantity: x.filledQty,
|
1019 | disclosedQuantity: x.discloseQty,
|
1020 | remainingDisclosedQuantity: x.dqQtyRem,
|
1021 | validity: toOrderValidity(x.orderValidity),
|
1022 | date: x.orderDateTime,
|
1023 | parentId: x.parentId || null,
|
1024 | priceChange: x.ch,
|
1025 | priceChangePercent: x.chp,
|
1026 | currentPrice: x.lp,
|
1027 | tradedPrice: x.tradedPrice,
|
1028 | message: x.message,
|
1029 | pan: x.pan || null,
|
1030 | clientId: x.clientId || null,
|
1031 | };
|
1032 | }
|
1033 | function toOrdersOverall(x) {
|
1034 | var a = {
|
1035 | count: 0,
|
1036 | openCount: 0,
|
1037 | closedCount: 0,
|
1038 | quantity: 0,
|
1039 | remainingQuantity: 0,
|
1040 | tradedQuantity: 0,
|
1041 | disclosedQuantity: 0,
|
1042 | remainingDisclosedQuantity: 0,
|
1043 | };
|
1044 | for (var o of x) {
|
1045 | a.count++;
|
1046 | a.openCount += o.status === 6 || o.status === 4 ? 1 : 0;
|
1047 | a.quantity += o.qty;
|
1048 | a.remainingQuantity += o.remainingQuantity;
|
1049 | a.tradedQuantity += o.filledQty;
|
1050 | a.disclosedQuantity += o.discloseQty;
|
1051 | a.remainingDisclosedQuantity += o.dqQtyRem;
|
1052 | }
|
1053 | a.closedCount = a.count - a.openCount;
|
1054 | return a;
|
1055 | }
|
1056 | function toOrders(x) {
|
1057 | return {
|
1058 | details: x.orderBook.map(toOrder),
|
1059 | overall: toOrdersOverall(x.orderBook),
|
1060 | };
|
1061 | }
|
1062 | function toPosition(x) {
|
1063 | return {
|
1064 | id: x.id,
|
1065 | symbol: x.symbol,
|
1066 | token: x.fytoken,
|
1067 | segment: toSegment(x.segment),
|
1068 | productType: toProductType(x.productType),
|
1069 | side: toPositionSide(x.side),
|
1070 | quantity: x.qty,
|
1071 | quantityMultiplier: x.qtyMulti_com,
|
1072 | buyPrice: x.buyAvg,
|
1073 | buyQuantity: x.buyQty,
|
1074 | buyValue: x.buyVal,
|
1075 | sellPrice: x.sellAvg,
|
1076 | sellQuantity: x.sellQty,
|
1077 | sellValue: x.sellVal,
|
1078 | netPrice: x.netAvg,
|
1079 | netQuantity: x.netQty,
|
1080 | returns: x.pl,
|
1081 | realizedReturns: x.realized_profit,
|
1082 | unrealizedReturns: x.unrealized_profit,
|
1083 | crossCurrency: x.crossCurrency === "Y",
|
1084 | rbiRefRate: x.rbiRefRate,
|
1085 | currentPrice: x.ltp,
|
1086 | };
|
1087 | }
|
1088 | function toPositionsOverall(xs, x) {
|
1089 | var buyValue = 0, sellValue = 0;
|
1090 | for (var p of xs) {
|
1091 | buyValue += p.buyVal;
|
1092 | sellValue += p.sellVal;
|
1093 | }
|
1094 | return {
|
1095 | count: x.count_total,
|
1096 | openCount: x.count_open,
|
1097 | closedCount: x.count_total - x.count_open,
|
1098 | buyValue,
|
1099 | sellValue,
|
1100 | returns: x.pl_total,
|
1101 | realizedReturns: x.pl_realized,
|
1102 | unrealizedReturns: x.pl_unrealized,
|
1103 | };
|
1104 | }
|
1105 | function toPositions(x) {
|
1106 | return {
|
1107 | details: x.netPositions.map(toPosition),
|
1108 | overall: toPositionsOverall(x.netPositions, x.overall),
|
1109 | };
|
1110 | }
|
1111 | function toTrade(x) {
|
1112 | return {
|
1113 | id: x.id,
|
1114 | orderId: x.orderNumber,
|
1115 | symbol: x.symbol,
|
1116 | token: x.fyToken,
|
1117 | segment: toSegment(x.segment),
|
1118 | exchange: toExchange(x.exchange),
|
1119 | side: toOrderSide(x.transactionType),
|
1120 | productType: toProductType(x.productType),
|
1121 | orderType: toOrderType(x.orderType),
|
1122 | orderDate: x.orderDateTime,
|
1123 | price: x.tradePrice,
|
1124 | quantity: x.tradedQty,
|
1125 | value: x.tradeValue,
|
1126 | clientId: x.clientId,
|
1127 | };
|
1128 | }
|
1129 | function toTradesOverall(x) {
|
1130 | var a = {
|
1131 | count: 0,
|
1132 | quantity: 0,
|
1133 | value: 0,
|
1134 | };
|
1135 | for (var t of x) {
|
1136 | a.count++;
|
1137 | a.quantity += t.tradedQty;
|
1138 | a.value += t.tradeValue;
|
1139 | }
|
1140 | return a;
|
1141 | }
|
1142 | function toTrades(x) {
|
1143 | return {
|
1144 | details: x.tradeBook.map(toTrade),
|
1145 | overall: toTradesOverall(x.tradeBook),
|
1146 | };
|
1147 | }
|
1148 | function fromPlaceOrder(x) {
|
1149 | return {
|
1150 | symbol: x.symbol,
|
1151 | type: fromOrderType(x.type || "MARKET"),
|
1152 | side: fromOrderSide(x.side || "BUY"),
|
1153 | productType: x.productType || "CNC",
|
1154 | limitPrice: x.limitPrice || 0,
|
1155 | stopPrice: x.stopPrice || 0,
|
1156 | qty: x.quantity,
|
1157 | disclosedQty: x.disclosedQuantity || 0,
|
1158 | validity: x.validity || "DAY",
|
1159 | offlineOrder: x.offline ? "True" : "False",
|
1160 | stopLoss: x.stopLoss || 0,
|
1161 | takeProfit: x.takeProfit || 0,
|
1162 | };
|
1163 | }
|
1164 | function fromModifyOrder(x) {
|
1165 | return {
|
1166 | id: x.id,
|
1167 | type: fromOrderType(x.type),
|
1168 | qty: x.quantity,
|
1169 | disclosedQty: x.disclosedQuantity,
|
1170 | limitPrice: x.limitPrice,
|
1171 | stopPrice: x.stopPrice,
|
1172 | };
|
1173 | }
|
1174 | function fromConvertPosition(x) {
|
1175 | return {
|
1176 | symbol: x.symbol,
|
1177 | positionSide: fromPositionSide(x.side || "LONG"),
|
1178 | convertQty: x.quantity,
|
1179 | convertFrom: fromProductType(x.fromProductType || "INTRADAY"),
|
1180 | convertTo: fromProductType(x.toProductType || "CNC"),
|
1181 | };
|
1182 | }
|
1183 | function toMarketStatus(x) {
|
1184 | return {
|
1185 | exchange: toExchange(x.exchange),
|
1186 | segment: toSegment(x.segment),
|
1187 | type: x.market_type,
|
1188 | status: x.status,
|
1189 | };
|
1190 | }
|
1191 | function toMarketsStatusOverall(x) {
|
1192 | var a = {
|
1193 | count: 0,
|
1194 | openCount: 0,
|
1195 | closedCount: 0,
|
1196 | };
|
1197 | for (var s of x) {
|
1198 | a.count++;
|
1199 | if (s.status === "OPEN")
|
1200 | a.openCount++;
|
1201 | else
|
1202 | a.closedCount++;
|
1203 | }
|
1204 | return a;
|
1205 | }
|
1206 | function toMarketsStatus(x) {
|
1207 | return {
|
1208 | details: x.marketStatus.map(toMarketStatus),
|
1209 | overall: toMarketsStatusOverall(x.marketStatus),
|
1210 | };
|
1211 | }
|
1212 | const CANDLE_RESOLUTIONS = [1, 2, 3, 5, 10, 15, 20, 30, 60, 120, 240, 1440];
|
1213 | function fromCandleResolution(x) {
|
1214 | var R = 1, D = Infinity;
|
1215 | for (var r of CANDLE_RESOLUTIONS) {
|
1216 | var d = Math.abs(x - r);
|
1217 | if (d < D) {
|
1218 | R = r;
|
1219 | D = d;
|
1220 | }
|
1221 | }
|
1222 | return R === 1440 ? "D" : R.toString();
|
1223 | }
|
1224 | function fromGetMarketHistory(x) {
|
1225 | return {
|
1226 | symbol: x.symbol,
|
1227 | resolution: fromCandleResolution(x.resolution),
|
1228 | date_format: 0,
|
1229 | range_from: x.fromDate.toString(),
|
1230 | range_to: x.toDate.toString(),
|
1231 | cont_flag: x.continuous ? "1" : "0",
|
1232 | };
|
1233 | }
|
1234 | function toCandleShort(x) {
|
1235 | return {
|
1236 | date: x[0 ],
|
1237 | openPrice: x[1 ],
|
1238 | highPrice: x[2 ],
|
1239 | lowPrice: x[3 ],
|
1240 | closePrice: x[4 ],
|
1241 | volume: x[5 ],
|
1242 | };
|
1243 | }
|
1244 | function toCandle(x) {
|
1245 | return {
|
1246 | date: x.t,
|
1247 | openPrice: x.o,
|
1248 | highPrice: x.h,
|
1249 | lowPrice: x.l,
|
1250 | closePrice: x.c,
|
1251 | volume: x.v,
|
1252 | };
|
1253 | }
|
1254 | function toMarketHistoryOverall(x) {
|
1255 | var a = {
|
1256 | fromDate: 0,
|
1257 | toDate: 0,
|
1258 | openPrice: 0,
|
1259 | highPrice: 0,
|
1260 | lowPrice: 0,
|
1261 | closePrice: 0,
|
1262 | volume: 0,
|
1263 | };
|
1264 | if (x.length === 0)
|
1265 | return a;
|
1266 | var l = x.length - 1;
|
1267 | a.fromDate = x[0][0 ];
|
1268 | a.toDate = x[l][0 ];
|
1269 | a.openPrice = x[0][1 ];
|
1270 | a.highPrice = x[0][2 ];
|
1271 | a.lowPrice = x[0][3 ];
|
1272 | a.closePrice = x[l][4 ];
|
1273 | for (var c of x) {
|
1274 | a.highPrice = Math.max(a.highPrice, c[2 ]);
|
1275 | a.lowPrice = Math.min(a.lowPrice, c[3 ]);
|
1276 | a.volume += c[5 ];
|
1277 | }
|
1278 | return a;
|
1279 | }
|
1280 | function toMarketHistory(x) {
|
1281 | return {
|
1282 | details: x.candles.map(toCandleShort),
|
1283 | overall: toMarketHistoryOverall(x.candles),
|
1284 | };
|
1285 | }
|
1286 | function toMarketQuote(x) {
|
1287 | var v = x.v;
|
1288 | return {
|
1289 | symbol: x.n,
|
1290 | token: v.fyToken,
|
1291 | name: v.short_name,
|
1292 | exchange: v.exchange,
|
1293 | description: v.description,
|
1294 | priceChange: v.ch,
|
1295 | priceChangePercent: v.chp,
|
1296 | currentPrice: v.lp,
|
1297 | priceSpread: v.spread,
|
1298 | sellPrice: v.ask,
|
1299 | buyPrice: v.bid,
|
1300 | openPrice: v.open_price,
|
1301 | highPrice: v.high_price,
|
1302 | lowPrice: v.low_price,
|
1303 | closePrice: v.prev_close_price,
|
1304 | volume: v.volume,
|
1305 | date: v.tt,
|
1306 | candle: v.cmd ? toCandle(v.cmd) : null,
|
1307 | };
|
1308 | }
|
1309 | function toMarketOffer(x) {
|
1310 | return {
|
1311 | price: x.price,
|
1312 | volume: x.volume,
|
1313 | orders: x.ord,
|
1314 | };
|
1315 | }
|
1316 | function toMarketOfferL2(x, p) {
|
1317 | return {
|
1318 | price: x.price / p,
|
1319 | volume: x.volume,
|
1320 | orders: x.ord,
|
1321 | };
|
1322 | }
|
1323 | function toMarketDepth(x) {
|
1324 | var ks = Object.keys(x.d);
|
1325 | if (ks.length === 0)
|
1326 | return null;
|
1327 | var s = ks[0];
|
1328 | var v = x.d[s];
|
1329 | return {
|
1330 | symbol: s,
|
1331 | token: null,
|
1332 | name: symbolName(s),
|
1333 | exchange: symbolExchange(s),
|
1334 | expiryDate: v.expiry,
|
1335 | currentPrice: v.ltq,
|
1336 | lowerCircuitPrice: v.lower_ckt,
|
1337 | upperCircuitPrice: v.upper_ckt,
|
1338 | openPrice: v.o,
|
1339 | highPrice: v.h,
|
1340 | lowPrice: v.l,
|
1341 | closePrice: v.c,
|
1342 | volume: v.v,
|
1343 | priceChange: v.ch,
|
1344 | priceChangePercent: v.chp,
|
1345 | openInterest: v.oi,
|
1346 | previousOpenInterest: v.pdoi,
|
1347 | openInterestChangePercent: v.oipercent,
|
1348 | tradedQuantity: v.ltq,
|
1349 | tradedDate: v.ltt,
|
1350 | netPrice: v.atp,
|
1351 | buyQuantity: v.totalbuyqty,
|
1352 | sellQuantity: v.totalsellqty,
|
1353 | buyOffers: v.bids.map(toMarketOffer),
|
1354 | sellOffers: v.ask.map(toMarketOffer),
|
1355 | };
|
1356 | }
|
1357 | function toEdisTransaction(x) {
|
1358 | return {
|
1359 | id: x.transactionId,
|
1360 | isin: x.isin,
|
1361 | quantity: x.qty,
|
1362 | remainingQuantity: x.qty - x.qtyUtlize,
|
1363 | entryDate: x.entryDate,
|
1364 | startDate: x.startDate,
|
1365 | endDate: x.endDate,
|
1366 | source: x.source,
|
1367 | status: x.status,
|
1368 | clientId: x.clientId,
|
1369 | errorCode: x.errCode,
|
1370 | errorCount: x.errorCount,
|
1371 | reason: x.reason,
|
1372 | };
|
1373 | }
|
1374 | function toEdisTransactionsOverall(x) {
|
1375 | var a = {
|
1376 | count: 0,
|
1377 | quantity: 0,
|
1378 | remainingQuantity: 0,
|
1379 | };
|
1380 | for (var t of x) {
|
1381 | a.count++;
|
1382 | a.quantity += t.qty;
|
1383 | a.remainingQuantity += t.qty - t.qtyUtlize;
|
1384 | }
|
1385 | return a;
|
1386 | }
|
1387 | function toEdisTransactions(x) {
|
1388 | var ts = x.data.length === 0 ? [] : x.data;
|
1389 | return {
|
1390 | details: ts.map(toEdisTransaction),
|
1391 | overall: toEdisTransactionsOverall(ts),
|
1392 | };
|
1393 | }
|
1394 | function fromEdisHolding(x) {
|
1395 | return {
|
1396 | isin_code: x.isin,
|
1397 | qty: x.quantity,
|
1398 | };
|
1399 | }
|
1400 | function toOrderUpdateNotification(x) {
|
1401 | var d = x.d;
|
1402 | return {
|
1403 | id: d.id,
|
1404 | symbol: d.symbol,
|
1405 | token: d.fyToken,
|
1406 | type: toOrderType(d.type),
|
1407 | side: toOrderSide(d.side),
|
1408 | productType: toProductType(d.productType),
|
1409 | status: toOrderStatus(d.status),
|
1410 | validity: toOrderValidity(d.orderValidity),
|
1411 | offline: d.offlineOrder,
|
1412 | quantity: d.qty,
|
1413 | remainingQuantity: d.remainingQuantity,
|
1414 | filledQuantity: d.filledQty,
|
1415 | disclosedQuantity: d.discloseQty,
|
1416 | remainingDisclosedQuantity: d.dqQtyRem,
|
1417 | limitPrice: d.limitPrice,
|
1418 | stopPrice: d.stopPrice,
|
1419 | date: d.orderDateTime,
|
1420 | parentId: d.parentId || null,
|
1421 | tradedPrice: d.tradedPrice,
|
1422 | message: d.message,
|
1423 | };
|
1424 | }
|
1425 | function toMarketDataNotification(x, map) {
|
1426 | var d = x.d;
|
1427 | var t = d.token.toString();
|
1428 | var p = d.price_conv || 1;
|
1429 | var s = map != null ? map.get(t) || null : null;
|
1430 | var priceChange = d.ltp - d.prev_close_price;
|
1431 | var bid = d.bids == null ? d.bid : d.bids[0].price;
|
1432 | var ask = d.asks == null ? d.ask : d.asks[0].price;
|
1433 | return {
|
1434 | symbol: s,
|
1435 | token: t,
|
1436 | name: s != null ? symbolName(s) : null,
|
1437 | exchange: s != null ? symbolExchange(s) : null,
|
1438 | date: d.tt,
|
1439 | marketStatus: d.marketStat,
|
1440 | currentPrice: d.ltp / p,
|
1441 | openPrice: d.open_price / p,
|
1442 | highPrice: d.high_price / p,
|
1443 | lowPrice: d.low_price / p,
|
1444 | closePrice: d.prev_close_price / p,
|
1445 | priceChange: priceChange / p,
|
1446 | priceChangePercent: priceChange / d.prev_close_price,
|
1447 | candle: {
|
1448 | date: d.tt,
|
1449 | openPrice: d.o / p,
|
1450 | highPrice: d.h / p,
|
1451 | lowPrice: d.l / p,
|
1452 | closePrice: d.c / p,
|
1453 | volume: Number(d.v),
|
1454 | },
|
1455 | openInterest: Number(d.oi),
|
1456 | previousOpenInterest: Number(d.pdoi),
|
1457 | tradedQuantity: d.LTQ,
|
1458 | tradedDate: d.L2_LTT,
|
1459 | tradedPrice: d.ATP / p,
|
1460 | volume: d.volume,
|
1461 | buyQuantity: Number(d.tot_buy),
|
1462 | sellQuantity: Number(d.tot_sell),
|
1463 | buyPrice: bid / p,
|
1464 | sellPrice: ask / p,
|
1465 | priceSpread: (ask - bid) / p,
|
1466 | buyOffers: d.bids == null ? null : d.bids.map(x => toMarketOfferL2(x, p)),
|
1467 | sellOffers: d.asks == null ? null : d.asks.map(x => toMarketOfferL2(x, p)),
|
1468 | };
|
1469 | }
|
1470 | function charge(x, p) {
|
1471 | return 0.01 * Math.round(x * p);
|
1472 | }
|
1473 | function equityDeliveryBuyCharges(x) {
|
1474 | var sttctt = charge(x, 0.10);
|
1475 | var gst = charge(sttctt, 18.0);
|
1476 | var exch = charge(x, 0.00325);
|
1477 | var stamp = charge(x, 0.015);
|
1478 | var sebi = charge(x, 0.0001);
|
1479 | return sttctt + gst + exch + stamp + sebi;
|
1480 | }
|
1481 | function equityDeliverySellCharges(x) {
|
1482 | var debit = 7.00 + 5.50;
|
1483 | return debit + equityDeliveryBuyCharges(x);
|
1484 | }
|
1485 | function equityDeliveryCharges(side, value) {
|
1486 | if (side === "BUY")
|
1487 | return equityDeliveryBuyCharges(value);
|
1488 | return equityDeliverySellCharges(value);
|
1489 | }
|
1490 | function equityIntradayBuyCharges(x) {
|
1491 | var broker = Math.min(20.00, charge(x, 0.03));
|
1492 | var gst = charge(broker, 18.0);
|
1493 | var exch = charge(x, 0.00325);
|
1494 | var stamp = charge(x, 0.003);
|
1495 | var sebi = charge(x, 0.0001);
|
1496 | return broker + gst + exch + stamp + sebi;
|
1497 | }
|
1498 | function equityIntradaySellCharges(x) {
|
1499 | var broker = Math.min(20.00, charge(x, 0.03));
|
1500 | var sttctt = charge(x, 0.025);
|
1501 | var gst = charge(broker + sttctt, 18.0);
|
1502 | var exch = charge(x, 0.00325);
|
1503 | var stamp = charge(x, 0.003);
|
1504 | var sebi = charge(x, 0.0001);
|
1505 | return broker + sttctt + gst + exch + stamp + sebi;
|
1506 | }
|
1507 | function equityIntradayCharges(side, value) {
|
1508 | if (side === "BUY")
|
1509 | return equityIntradayBuyCharges(value);
|
1510 | return equityIntradaySellCharges(value);
|
1511 | }
|
1512 | function equityFuturesBuyCharges(x) {
|
1513 | var broker = Math.min(20.00, charge(x, 0.03));
|
1514 | var gst = charge(broker, 18.0);
|
1515 | var exch = charge(x, 0.0019);
|
1516 | var clear = charge(x, 0.0005);
|
1517 | var stamp = charge(x, 0.002);
|
1518 | var sebi = charge(x, 0.0001);
|
1519 | return broker + gst + exch + clear + stamp + sebi;
|
1520 | }
|
1521 | function equityFuturesSellCharges(x) {
|
1522 | var broker = Math.min(20.00, charge(x, 0.03));
|
1523 | var sttctt = charge(x, 0.01);
|
1524 | var gst = charge(broker + sttctt, 18.0);
|
1525 | var exch = charge(x, 0.0019);
|
1526 | var clear = charge(x, 0.0005);
|
1527 | var stamp = charge(x, 0.002);
|
1528 | var sebi = charge(x, 0.0001);
|
1529 | return broker + sttctt + gst + exch + clear + stamp + sebi;
|
1530 | }
|
1531 | function equityFuturesCharges(side, value) {
|
1532 | if (side === "BUY")
|
1533 | return equityFuturesBuyCharges(value);
|
1534 | return equityFuturesSellCharges(value);
|
1535 | }
|
1536 | function equityOptionsBuyCharges(x) {
|
1537 | var broker = 20.00;
|
1538 | var gst = charge(broker, 18.0);
|
1539 | var exch = charge(x, 0.053);
|
1540 | var clear = charge(x, 0.009);
|
1541 | var stamp = charge(x, 0.003);
|
1542 | var sebi = charge(x, 0.0001);
|
1543 | return broker + gst + exch + clear + stamp + sebi;
|
1544 | }
|
1545 | function equityOptionsSellCharges(x) {
|
1546 | var broker = 20.00;
|
1547 | var sttctt = charge(x, 0.05);
|
1548 | var gst = charge(broker + sttctt, 18.0);
|
1549 | var exch = charge(x, 0.053);
|
1550 | var clear = charge(x, 0.009);
|
1551 | var stamp = charge(x, 0.003);
|
1552 | var sebi = charge(x, 0.0001);
|
1553 | return broker + sttctt + gst + exch + clear + stamp + sebi;
|
1554 | }
|
1555 | function equityOptionsCharges(side, value) {
|
1556 | if (side === "BUY")
|
1557 | return equityOptionsBuyCharges(value);
|
1558 | return equityOptionsSellCharges(value);
|
1559 | }
|
1560 | function currencyFuturesBuySellCharges(x) {
|
1561 | var broker = Math.min(20.00, charge(x, 0.03));
|
1562 | var gst = charge(broker, 18.0);
|
1563 | var exch = charge(x, 0.00115);
|
1564 | var clear = charge(x, 0.0005);
|
1565 | var stamp = charge(x, 0.0001);
|
1566 | var sebi = charge(x, 0.0001);
|
1567 | return broker + gst + exch + clear + stamp + sebi;
|
1568 | }
|
1569 | function currencyFuturesCharges(side, value) {
|
1570 | return currencyFuturesBuySellCharges(value);
|
1571 | }
|
1572 | function currencyOptionsBuySellCharges(x) {
|
1573 | var broker = 20.00;
|
1574 | var gst = charge(broker, 18.0);
|
1575 | var exch = charge(x, 0.04);
|
1576 | var clear = charge(x, 0.009);
|
1577 | var stamp = charge(x, 0.0001);
|
1578 | var sebi = charge(x, 0.0001);
|
1579 | return broker + gst + exch + clear + stamp + sebi;
|
1580 | }
|
1581 | function currencyOptionsCharges(side, value) {
|
1582 | return currencyOptionsBuySellCharges(value);
|
1583 | }
|
1584 | function commodityFuturesBuyCharges(x) {
|
1585 | var broker = Math.min(20.00, charge(x, 0.03));
|
1586 | var gst = charge(broker, 18.0);
|
1587 | var exch = charge(x, 0.0026);
|
1588 | var clear = charge(x, 0.0018);
|
1589 | var stamp = charge(x, 0.002);
|
1590 | var sebi = charge(x, 0.0001);
|
1591 | return broker + gst + exch + clear + stamp + sebi;
|
1592 | }
|
1593 | function commodityFuturesSellCharges(x) {
|
1594 | var broker = Math.min(20.00, charge(x, 0.03));
|
1595 | var sttctt = charge(x, 0.01);
|
1596 | var gst = charge(broker + sttctt, 18.0);
|
1597 | var exch = charge(x, 0.0026);
|
1598 | var clear = charge(x, 0.0018);
|
1599 | var stamp = charge(x, 0.002);
|
1600 | var sebi = charge(x, 0.0001);
|
1601 | return broker + sttctt + gst + exch + clear + stamp + sebi;
|
1602 | }
|
1603 | function commodityFuturesCharges(side, value) {
|
1604 | if (side === "BUY")
|
1605 | return commodityFuturesBuyCharges(value);
|
1606 | return commodityFuturesSellCharges(value);
|
1607 | }
|
1608 | function commodityOptionsBuyCharges(x) {
|
1609 | var broker = 20.00;
|
1610 | var gst = charge(broker, 18.0);
|
1611 | var clear = charge(x, 0.05);
|
1612 | var stamp = charge(x, 0.0003);
|
1613 | var sebi = charge(x, 0.0001);
|
1614 | return broker + gst + clear + stamp + sebi;
|
1615 | }
|
1616 | function commodityOptionsSellCharges(x) {
|
1617 | var broker = 20.00;
|
1618 | var sttctt = charge(x, 0.05);
|
1619 | var gst = charge(broker + sttctt, 18.0);
|
1620 | var clear = charge(x, 0.05);
|
1621 | var stamp = charge(x, 0.0003);
|
1622 | var sebi = charge(x, 0.0001);
|
1623 | return broker + sttctt + gst + clear + stamp + sebi;
|
1624 | }
|
1625 | function commodityOptionsCharges(side, value) {
|
1626 | if (side === "BUY")
|
1627 | return commodityOptionsBuyCharges(value);
|
1628 | return commodityOptionsSellCharges(value);
|
1629 | }
|
1630 | class ApiError extends Error {
|
1631 | constructor(code, message) {
|
1632 | super(message);
|
1633 | this.code = code;
|
1634 | this.name = this.constructor.name;
|
1635 | this.stack = (new Error(message)).stack;
|
1636 | }
|
1637 | }
|
1638 | function loginStep1(appId, redirectUrl, state = "default") {
|
1639 | return loginStep1$1(fromLoginStep1Request({ appId, redirectUrl, state }));
|
1640 | }
|
1641 | function loginStep2(appHash, authorizationCode) {
|
1642 | return loginStep2$1(fromLoginStep2Request({ appHash, authorizationCode }));
|
1643 | }
|
1644 | function validateApiStatus(x) {
|
1645 | if (x.s !== "ok")
|
1646 | throw new ApiError(x.code, x.message);
|
1647 | }
|
1648 | function validateApiOrder(x) {
|
1649 | if (x.id === "")
|
1650 | throw new ApiError(x.code, x.message);
|
1651 | }
|
1652 | async function getProfile(auth) {
|
1653 | var a = await getProfile$1(fromAuthorization(auth));
|
1654 | validateApiStatus(a);
|
1655 | return toProfile(a);
|
1656 | }
|
1657 | async function getFunds(auth) {
|
1658 | var a = await getFunds$1(fromAuthorization(auth));
|
1659 | validateApiStatus(a);
|
1660 | return toFunds(a);
|
1661 | }
|
1662 | async function getHoldings(auth) {
|
1663 | var a = await getHoldings$1(fromAuthorization(auth));
|
1664 | validateApiStatus(a);
|
1665 | return toHoldings(a);
|
1666 | }
|
1667 | async function getOrder(auth, id) {
|
1668 | var a = await getOrder$1(fromAuthorization(auth), { id });
|
1669 | validateApiStatus(a);
|
1670 | return toOrder(a.orderBook[0]);
|
1671 | }
|
1672 | async function getOrders(auth) {
|
1673 | var a = await getOrders$1(fromAuthorization(auth));
|
1674 | validateApiStatus(a);
|
1675 | return toOrders(a);
|
1676 | }
|
1677 | async function getPositions(auth) {
|
1678 | var a = await getPositions$1(fromAuthorization(auth));
|
1679 | validateApiStatus(a);
|
1680 | return toPositions(a);
|
1681 | }
|
1682 | async function getTrades(auth) {
|
1683 | var a = await getTrades$1(fromAuthorization(auth));
|
1684 | validateApiStatus(a);
|
1685 | return toTrades(a);
|
1686 | }
|
1687 | async function placeOrder(auth, order) {
|
1688 | var a = await placeOrder$1(fromAuthorization(auth), fromPlaceOrder(order));
|
1689 | validateApiOrder(a);
|
1690 | return a.id;
|
1691 | }
|
1692 | function placeOrders(auth, orders) {
|
1693 | var p = placeOrders$1(fromAuthorization(auth), orders.map(fromPlaceOrder));
|
1694 | return orders.map((_, i) => p.then(a => {
|
1695 | validateApiStatus(a);
|
1696 | validateApiOrder(a.data[i].body);
|
1697 | return a.data[i].body.id;
|
1698 | }));
|
1699 | }
|
1700 | async function modifyOrder(auth, order) {
|
1701 | var a = await modifyOrder$1(fromAuthorization(auth), fromModifyOrder(order));
|
1702 | validateApiStatus(a);
|
1703 | return a.id;
|
1704 | }
|
1705 | function modifyOrders(auth, orders) {
|
1706 | var p = modifyOrders$1(fromAuthorization(auth), orders.map(fromModifyOrder));
|
1707 | return orders.map((_, i) => p.then(a => {
|
1708 | validateApiStatus(a);
|
1709 | validateApiOrder(a.data[i].body);
|
1710 | }));
|
1711 | }
|
1712 | async function cancelOrder(auth, id) {
|
1713 | var a = await cancelOrder$1(fromAuthorization(auth), { id });
|
1714 | validateApiStatus(a);
|
1715 | }
|
1716 | function cancelOrders(auth, ids) {
|
1717 | var p = cancelOrders$1(fromAuthorization(auth), ids.map(id => ({ id })));
|
1718 | return ids.map((_, i) => p.then(a => {
|
1719 | validateApiStatus(a);
|
1720 | validateApiOrder(a.data[i].body);
|
1721 | }));
|
1722 | }
|
1723 | async function exitPosition(auth, id) {
|
1724 | var a = await exitPosition$1(fromAuthorization(auth), { id });
|
1725 | validateApiStatus(a);
|
1726 | }
|
1727 | async function exitAllPositions(auth) {
|
1728 | var a = await exitAllPositions$1(fromAuthorization(auth));
|
1729 | validateApiStatus(a);
|
1730 | }
|
1731 | async function convertPosition(auth, conversion) {
|
1732 | var a = await convertPosition$1(fromAuthorization(auth), fromConvertPosition(conversion));
|
1733 | validateApiStatus(a);
|
1734 | }
|
1735 | async function getMarketStatus(auth) {
|
1736 | var a = await getMarketStatus$1(fromAuthorization(auth));
|
1737 | validateApiStatus(a);
|
1738 | return toMarketsStatus(a);
|
1739 | }
|
1740 | async function getMarketHistory(auth, market) {
|
1741 | var a = await getMarketHistory$1(fromAuthorization(auth), fromGetMarketHistory(market));
|
1742 | validateApiStatus(a);
|
1743 | return toMarketHistory(a);
|
1744 | }
|
1745 | async function getMarketQuotes(auth, symbols) {
|
1746 | var a = await getMarketQuotes$1(fromAuthorization(auth), { symbols: symbols.join() });
|
1747 | validateApiStatus(a);
|
1748 | return a.d.map(toMarketQuote);
|
1749 | }
|
1750 | async function getMarketDepth(auth, symbol) {
|
1751 | var a = await getMarketDepth$1(fromAuthorization(auth), { symbol, ohlcv_flag: 1 });
|
1752 | validateApiStatus(a);
|
1753 | return toMarketDepth(a);
|
1754 | }
|
1755 | function getSymbolMaster(auth, exchange, segment) {
|
1756 | return getSymbolMaster$1(null, { exchange, segment });
|
1757 | }
|
1758 | function processSymbolMaster(csv) {
|
1759 | var a = [];
|
1760 | var RLINE = /[^\n]+/g, m = null;
|
1761 | while ((m = RLINE.exec(csv)) != null)
|
1762 | a.push(toSymbolDetails(m[0]));
|
1763 | return a;
|
1764 | }
|
1765 | async function loadSymbolMaster(auth, exchange, segment) {
|
1766 | var csv = await getSymbolMaster(null, exchange, segment);
|
1767 | return processSymbolMaster(csv);
|
1768 | }
|
1769 | async function generateEdisTpin(auth) {
|
1770 | var a = await generateEdisTpin$1(fromAuthorization(auth));
|
1771 | validateApiStatus(a);
|
1772 | }
|
1773 | async function getEdisTransactions(auth) {
|
1774 | var a = await getEdisTransactions$1(fromAuthorization(auth));
|
1775 | validateApiStatus(a);
|
1776 | return toEdisTransactions(a);
|
1777 | }
|
1778 | function submitEdisHoldingsStep(auth, holdings) {
|
1779 | return submitEdisHoldingsStep$1(fromAuthorization(auth), { recordLst: holdings.map(fromEdisHolding) });
|
1780 | }
|
1781 | async function inquireEdisTransaction(auth, id) {
|
1782 | var a = await inquireEdisTransaction$1(fromAuthorization(auth), { transactionId: id });
|
1783 | validateApiStatus(a);
|
1784 | return a.data.FAILED_CNT > 0 ? -a.data.FAILED_CNT : a.data.SUCEESS_CNT;
|
1785 | }
|
1786 | function connectOrderUpdate(auth, fn) {
|
1787 | return connectOrderUpdate$1(fromAuthorization(auth), x => {
|
1788 | if (x.d)
|
1789 | fn(toOrderUpdateNotification(x));
|
1790 | });
|
1791 | }
|
1792 | async function subscribeOrderUpdate(conn) {
|
1793 | var a = await subscribeOrderUpdate$1(conn);
|
1794 | if (a.code < 0)
|
1795 | throw new ApiError(a.code, a.message);
|
1796 | }
|
1797 | async function unsubscribeOrderUpdate(conn) {
|
1798 | var a = await unsubscribeOrderUpdate$1(conn);
|
1799 | if (a.code < 0)
|
1800 | throw new ApiError(a.code, a.message);
|
1801 | }
|
1802 | function connectMarketData(auth, fn, map = null) {
|
1803 | return connectMarketData$1(fromAuthorization(auth), x => {
|
1804 | if (x.d)
|
1805 | fn(toMarketDataNotification(x, map));
|
1806 | });
|
1807 | }
|
1808 | async function subscribeMarketQuote(conn, symbols) {
|
1809 | var a = await subscribeMarketQuote$1(conn, symbols);
|
1810 | if (a.code < 0)
|
1811 | throw new ApiError(a.code, a.message);
|
1812 | }
|
1813 | async function subscribeMarketDepth(conn, symbols) {
|
1814 | var a = await subscribeMarketDepth$1(conn, symbols);
|
1815 | if (a.code < 0)
|
1816 | throw new ApiError(a.code, a.message);
|
1817 | }
|
1818 | async function unsubscribeMarketQuote(conn, symbols) {
|
1819 | var a = await unsubscribeMarketQuote$1(conn, symbols);
|
1820 | if (a.code < 0)
|
1821 | throw new ApiError(a.code, a.message);
|
1822 | }
|
1823 | async function unsubscribeMarketDepth(conn, symbols) {
|
1824 | var a = await unsubscribeMarketDepth$1(conn, symbols);
|
1825 | if (a.code < 0)
|
1826 | throw new ApiError(a.code, a.message);
|
1827 | }
|
1828 | class Api {
|
1829 | constructor(appId, accessToken) {
|
1830 | this.appId = appId;
|
1831 | this.accessToken = accessToken;
|
1832 | this.symbolDetails = new Map();
|
1833 | this.tokenSymbol = new Map();
|
1834 | this.orderUpdateConnection = null;
|
1835 | this.marketDataConnection = null;
|
1836 | }
|
1837 | static loginStep1(appId, redirectUrl, state = "default") {
|
1838 | return loginStep1(appId, redirectUrl, state);
|
1839 | }
|
1840 | static loginStep2(appHash, authorizationCode) {
|
1841 | return loginStep2(appHash, authorizationCode);
|
1842 | }
|
1843 | static getSymbolMaster(exchange, segment) { return getSymbolMaster(null, exchange, segment); }
|
1844 | getProfile() { return getProfile(this); }
|
1845 | getFunds() { return getFunds(this); }
|
1846 | getHoldings() { return getHoldings(this); }
|
1847 | getOrder(id) { return getOrder(this, id); }
|
1848 | getOrders() { return getOrders(this); }
|
1849 | getPositions() { return getPositions(this); }
|
1850 | getTrades() { return getTrades(this); }
|
1851 | placeOrder(order) { return placeOrder(this, order); }
|
1852 | placeOrders(orders) { return placeOrders(this, orders); }
|
1853 | modifyOrder(order) { return modifyOrder(this, order); }
|
1854 | modifyOrders(orders) { return modifyOrders(this, orders); }
|
1855 | cancelOrder(id) { return cancelOrder(this, id); }
|
1856 | cancelOrders(ids) { return cancelOrders(this, ids); }
|
1857 | exitPosition(id) { return exitPosition(this, id); }
|
1858 | exitAllPositions() { return exitAllPositions(this); }
|
1859 | convertPosition(conversion) { return convertPosition(this, conversion); }
|
1860 | getMarketStatus() { return getMarketStatus(this); }
|
1861 | getMarketHistory(market) { return getMarketHistory(this, market); }
|
1862 | getMarketQuotes(symbols) { return getMarketQuotes(this, symbols); }
|
1863 | getMarketDepth(symbol) { return getMarketDepth(this, symbol); }
|
1864 | processSymbolMaster(csv) {
|
1865 | var rs = processSymbolMaster(csv);
|
1866 | for (var r of rs) {
|
1867 | this.symbolDetails.set(r.symbol, r);
|
1868 | this.tokenSymbol.set(r.token, r.symbol);
|
1869 | }
|
1870 | return rs;
|
1871 | }
|
1872 | async loadSymbolMaster(exchange, segment) {
|
1873 | var rs = await loadSymbolMaster(null, exchange, segment);
|
1874 | for (var r of rs) {
|
1875 | this.symbolDetails.set(r.symbol, r);
|
1876 | this.tokenSymbol.set(r.token, r.symbol);
|
1877 | }
|
1878 | return rs;
|
1879 | }
|
1880 | generateEdisTpin() { return generateEdisTpin(this); }
|
1881 | getEdisTransactions() { return getEdisTransactions(this); }
|
1882 | submitEdisHoldingsStep(holdings) { return submitEdisHoldingsStep(this, holdings); }
|
1883 | inquireEdisTransaction(id) { return inquireEdisTransaction(this, id); }
|
1884 | connectOrderUpdate(fn) {
|
1885 | if (this.orderUpdateConnection != null)
|
1886 | this.orderUpdateConnection.then(c => c.close());
|
1887 | return this.orderUpdateConnection = connectOrderUpdate(this, fn);
|
1888 | }
|
1889 | async subscribeOrderUpdate() {
|
1890 | return subscribeOrderUpdate(await this.orderUpdateConnection);
|
1891 | }
|
1892 | async unsubscribeOrderUpdate() {
|
1893 | return unsubscribeOrderUpdate(await this.orderUpdateConnection);
|
1894 | }
|
1895 | async connectMarketData(fn) {
|
1896 | if (this.marketDataConnection != null)
|
1897 | this.marketDataConnection.then(c => c.close());
|
1898 | return this.marketDataConnection = connectMarketData(this, fn, this.tokenSymbol);
|
1899 | }
|
1900 | async subscribeMarketQuote(symbols) {
|
1901 | return subscribeMarketQuote(await this.marketDataConnection, symbols);
|
1902 | }
|
1903 | async subscribeMarketDepth(symbols) {
|
1904 | return subscribeMarketDepth(await this.marketDataConnection, symbols);
|
1905 | }
|
1906 | async unsubscribeMarketQuote(symbols) {
|
1907 | return unsubscribeMarketQuote(await this.marketDataConnection, symbols);
|
1908 | }
|
1909 | async unsubscribeMarketDepth(symbols) {
|
1910 | return unsubscribeMarketDepth(await this.marketDataConnection, symbols);
|
1911 | }
|
1912 | }
|
1913 |
|
1914 | exports.Api = Api;
|
1915 | exports.cancelOrder = cancelOrder;
|
1916 | exports.cancelOrders = cancelOrders;
|
1917 | exports.commodityFuturesCharges = commodityFuturesCharges;
|
1918 | exports.commodityOptionsCharges = commodityOptionsCharges;
|
1919 | exports.connectMarketData = connectMarketData;
|
1920 | exports.connectOrderUpdate = connectOrderUpdate;
|
1921 | exports.convertPosition = convertPosition;
|
1922 | exports.currencyFuturesCharges = currencyFuturesCharges;
|
1923 | exports.currencyOptionsCharges = currencyOptionsCharges;
|
1924 | exports.derivativeType = derivativeType;
|
1925 | exports.derivativeTypeDescription = derivativeTypeDescription;
|
1926 | exports.equityDeliveryCharges = equityDeliveryCharges;
|
1927 | exports.equityFuturesCharges = equityFuturesCharges;
|
1928 | exports.equityIntradayCharges = equityIntradayCharges;
|
1929 | exports.equityOptionsCharges = equityOptionsCharges;
|
1930 | exports.exchange = exchange;
|
1931 | exports.exchangeDescription = exchangeDescription;
|
1932 | exports.exitAllPositions = exitAllPositions;
|
1933 | exports.exitPosition = exitPosition;
|
1934 | exports.generateEdisTpin = generateEdisTpin;
|
1935 | exports.getEdisTransactions = getEdisTransactions;
|
1936 | exports.getFunds = getFunds;
|
1937 | exports.getHoldings = getHoldings;
|
1938 | exports.getMarketDepth = getMarketDepth;
|
1939 | exports.getMarketHistory = getMarketHistory;
|
1940 | exports.getMarketQuotes = getMarketQuotes;
|
1941 | exports.getMarketStatus = getMarketStatus;
|
1942 | exports.getOrder = getOrder;
|
1943 | exports.getOrders = getOrders;
|
1944 | exports.getPositions = getPositions;
|
1945 | exports.getProfile = getProfile;
|
1946 | exports.getSymbolMaster = getSymbolMaster;
|
1947 | exports.getTrades = getTrades;
|
1948 | exports.holdingType = holdingType;
|
1949 | exports.holdingTypeDescription = holdingTypeDescription;
|
1950 | exports.http = http;
|
1951 | exports.inquireEdisTransaction = inquireEdisTransaction;
|
1952 | exports.instrumentType = instrumentType;
|
1953 | exports.instrumentTypeDescription = instrumentTypeDescription;
|
1954 | exports.loadSymbolMaster = loadSymbolMaster;
|
1955 | exports.loginStep1 = loginStep1;
|
1956 | exports.loginStep2 = loginStep2;
|
1957 | exports.modifyOrder = modifyOrder;
|
1958 | exports.modifyOrders = modifyOrders;
|
1959 | exports.optionType = optionType;
|
1960 | exports.optionTypeDescription = optionTypeDescription;
|
1961 | exports.orderSide = orderSide;
|
1962 | exports.orderSideDescription = orderSideDescription;
|
1963 | exports.orderSource = orderSource;
|
1964 | exports.orderSourceDescription = orderSourceDescription;
|
1965 | exports.orderStatus = orderStatus;
|
1966 | exports.orderStatusDescription = orderStatusDescription;
|
1967 | exports.orderType = orderType;
|
1968 | exports.orderTypeDescription = orderTypeDescription;
|
1969 | exports.orderValidity = orderValidity;
|
1970 | exports.orderValidityDescription = orderValidityDescription;
|
1971 | exports.placeOrder = placeOrder;
|
1972 | exports.placeOrders = placeOrders;
|
1973 | exports.positionSide = positionSide;
|
1974 | exports.positionSideDescription = positionSideDescription;
|
1975 | exports.processSymbolMaster = processSymbolMaster;
|
1976 | exports.productType = productType;
|
1977 | exports.productTypeDescription = productTypeDescription;
|
1978 | exports.segment = segment;
|
1979 | exports.segmentDescription = segmentDescription;
|
1980 | exports.submitEdisHoldingsStep = submitEdisHoldingsStep;
|
1981 | exports.subscribeMarketDepth = subscribeMarketDepth;
|
1982 | exports.subscribeMarketQuote = subscribeMarketQuote;
|
1983 | exports.subscribeOrderUpdate = subscribeOrderUpdate;
|
1984 | exports.symbolDerivativeType = symbolDerivativeType;
|
1985 | exports.symbolDescription = symbolDescription;
|
1986 | exports.symbolExchange = symbolExchange;
|
1987 | exports.symbolIsin = symbolIsin;
|
1988 | exports.symbolLotSize = symbolLotSize;
|
1989 | exports.symbolName = symbolName;
|
1990 | exports.symbolOptionType = symbolOptionType;
|
1991 | exports.symbolSeries = symbolSeries;
|
1992 | exports.symbolStrikePrice = symbolStrikePrice;
|
1993 | exports.symbolToken = symbolToken;
|
1994 | exports.unsubscribeMarketDepth = unsubscribeMarketDepth;
|
1995 | exports.unsubscribeMarketQuote = unsubscribeMarketQuote;
|
1996 | exports.unsubscribeOrderUpdate = unsubscribeOrderUpdate;
|
1997 | exports.websocket = websocket;
|