diff --git a/.eslintrc.js b/.eslintrc.js index 8b44217..1a01058 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,14 +1,15 @@ module.exports = { - "env": { - "browser": true, - "es2021": true + env: { + browser: true, + es2021: true }, - "overrides": [ + overrides: [ ], - "parserOptions": { - "ecmaVersion": "latest", - "sourceType": "module" + parserOptions: { + ecmaVersion: "latest", + sourceType: "module" }, - "rules": { + rules: { + 'quote-props': ['error', 'as-needed'], } } diff --git a/.gitignore b/.gitignore index 9b4cf26..b7be06a 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,9 @@ logs *.log npm-debug.log* dist +docs + +**/*.js # Runtime data pids diff --git a/constants/index.ts b/constants/index.ts new file mode 100644 index 0000000..45b609a --- /dev/null +++ b/constants/index.ts @@ -0,0 +1,61 @@ +import { AnyObject } from '../interfaces/any-object'; + +export const ROUTES: { [key: string]: string } = { + 'api.token': '/session/token', + 'api.token.invalidate': '/session/token', + 'api.token.renew': '/session/refresh_token', + 'user.profile': '/user/profile', + 'user.margins': '/user/margins', + 'user.margins.segment': '/user/margins/{segment}', + + 'orders': '/orders', + 'trades': '/trades', + 'order.info': '/orders/{order_id}', + 'order.place': '/orders/{variety}', + 'order.modify': '/orders/{variety}/{order_id}', + 'order.cancel': '/orders/{variety}/{order_id}', + 'order.trades': '/orders/{order_id}/trades', + 'order.margins': '/margins/orders', + 'order.margins.basket': '/margins/basket', + + 'portfolio.positions': '/portfolio/positions', + 'portfolio.holdings': '/portfolio/holdings', + 'portfolio.holdings.auction': '/portfolio/holdings/auctions', + 'portfolio.positions.convert': '/portfolio/positions', + + 'mf.orders': '/mf/orders', + 'mf.order.info': '/mf/orders/{order_id}', + 'mf.order.place': '/mf/orders', + 'mf.order.cancel': '/mf/orders/{order_id}', + + 'mf.sips': '/mf/sips', + 'mf.sip.info': '/mf/sips/{sip_id}', + 'mf.sip.place': '/mf/sips', + 'mf.sip.modify': '/mf/sips/{sip_id}', + 'mf.sip.cancel': '/mf/sips/{sip_id}', + + 'mf.holdings': '/mf/holdings', + 'mf.instruments': '/mf/instruments', + + 'market.instruments.all': '/instruments', + 'market.instruments': '/instruments/{exchange}', + 'market.historical': '/instruments/historical/{instrument_token}/{interval}', + 'market.trigger_range': '/instruments/trigger_range/{transaction_type}', + + 'market.quote': '/quote', + 'market.quote.ohlc': '/quote/ohlc', + 'market.quote.ltp': '/quote/ltp', + + 'gtt.triggers': '/gtt/triggers', + 'gtt.trigger_info': '/gtt/triggers/{trigger_id}', + 'gtt.place': '/gtt/triggers', + 'gtt.modify': '/gtt/triggers/{trigger_id}', + 'gtt.delete': '/gtt/triggers/{trigger_id}' +}; + +export const DEFAULTS: AnyObject = { + 'root': 'https://api.kite.trade', + 'login': 'https://kite.zerodha.com/connect/login', + 'debug': false, + 'timeout': 7000 +}; \ No newline at end of file diff --git a/examples/connect.js b/examples/connect.js deleted file mode 100644 index 6550606..0000000 --- a/examples/connect.js +++ /dev/null @@ -1,497 +0,0 @@ -var KiteConnect = require("kiteconnect").KiteConnect; - -var api_key = "api_key", - secret = "api_secret", - request_token = "request_token", - access_token = ""; - -var options = { - "api_key": api_key, - "debug": false -}; - -let kc = new KiteConnect(options); -kc.setSessionExpiryHook(sessionHook); - -if(!access_token) { - kc.generateSession(request_token, secret) - .then(function(response) { - console.log("Response", response); - init(); - }) - .catch(function(err) { - console.log(err); - }) -} else { - kc.setAccessToken(access_token); - init(); -} - -function init() { - console.log(kc.getLoginURL()) - - getProfile(); - getMargins(); - getMargins("equity"); - getPositions(); - convertPosition(); - getHoldings(); - getOrders(); - getOrderHistory(); - getTrades(); - getOrderTrades(); - getInstruments(); - getInstruments("NFO"); - getQuote(["NSE:RELIANCE"]); - getOHLC(["NSE:RELIANCE"]); - getLTP(["NSE:RELIANCE"]); - getHistoricalData(779521, "day", new Date("2018-01-01 18:05:00"), new Date("2018-01-10 18:05:37")); - getHistoricalData(779521, "day", "2018-01-01 18:05:00", "2018-01-10 18:05:37"); - getMFInstruments(); - getMFOrders(); - getMFSIPS(); - - regularOrderPlace("regular"); - icebergTTLOrderPlace("iceberg"); - modifyOrder("regular"); - cancelOrder("regular"); - - getGTT(); - getGTT("some_trigger_id"); - placeGTT(); - modifyGTT(); - deleteGTT("some_trigger_id"); - - orderMargins(); - basketMargins(); - - invalidateAccessToken() -} - -function sessionHook() { - console.log("User loggedout"); -} - -function getProfile() { - kc.getProfile() - .then(function(response) { - console.log(response) - }).catch(function(err) { - console.log(err); - }); -} - -function getMargins(segment) { - kc.getMargins(segment) - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function getPositions() { - kc.getPositions() - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function getHoldings() { - kc.getHoldings() - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err.response); - }); -} - -function getOrders() { - kc.getOrders() - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function getOrderHistory() { - kc.getOrders() - .then(function(response) { - if (response.length === 0) { - console.log("No orders.") - return - } - - kc.getOrderHistory(response[0].order_id) - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); - }).catch(function(err) { - console.log(err); - }); -} - -function getTrades() { - kc.getTrades() - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function getOrderTrades() { - kc.getOrders() - .then(function(response) { - var completedOrdersID; - for (var order of response) { - if (order.status === kc.STATUS_COMPLETE) { - completedOrdersID = order.order_id; - break; - } - } - - if (!completedOrdersID) { - console.log("No completed orders.") - return - } - - kc.getOrderTrades(completedOrdersID) - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); - }).catch(function(err) { - console.log(err); - }); -} - -function getInstruments(exchange) { - kc.getInstruments(exchange).then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }) -} - -function getQuote(instruments) { - kc.getQuote(instruments).then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }) -} - -function getOHLC(instruments) { - kc.getOHLC(instruments).then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }) -} - -function getLTP(instruments) { - kc.getLTP(instruments).then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }) -} - -function getHistoricalData(instrument_token, interval, from_date, to_date, continuous) { - kc.getHistoricalData(instrument_token, interval, from_date, to_date, continuous) - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function getMFInstruments() { - kc.getMFInstruments() - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function getMFOrders() { - kc.getMFOrders() - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function getMFSIPS() { - kc.getMFSIPS() - .then(function(response) { - console.log(response); - }).catch(function(err) { - console.log(err); - }); -} - -function invalidateAccessToken(access_token) { - kc.invalidateAccessToken(access_token) - .then(function(response) { - console.log(response); - testOrders(); - }).catch(function(err) { - console.log(err.response); - }); -} - -function regularOrderPlace(variety) { - kc.placeOrder(variety, { - "exchange": "NSE", - "tradingsymbol": "RELIANCE", - "transaction_type": "BUY", - "quantity": 1, - "product": "MIS", - "order_type": "MARKET" - }).then(function(resp) { - console.log(resp); - }).catch(function(err) { - console.log(err); - }); -} - -function icebergTTLOrderPlace(variety) { - kc.placeOrder(variety, { - "exchange": "NSE", - "tradingsymbol": "SBIN", - "transaction_type": "BUY", - "quantity": 1000, - "product": "CNC", - "order_type": "LIMIT", - "validity":"TTL", - "price":432, - "validity_ttl":10, - "iceberg_legs":5, - "iceberg_quantity":200 - }).then(function(resp) { - console.log(resp); - }).catch(function(err) { - console.log(err); - }); -} - -function modifyOrder(variety) { - var tradingsymbol = "RELIANCE"; - var exchange = "NSE"; - var instrument = exchange + ":" + tradingsymbol; - - function modify(variety, order_id) { - kc.modifyOrder(variety, order_id, { - quantity: 2 - }).then(function(resp) { - console.log(resp); - }).catch(function(err) { - console.log(err); - }); - } - - kc.getLTP([instrument]) - .then(function(resp) { - kc.placeOrder(variety, { - "exchange": exchange, - "tradingsymbol": tradingsymbol, - "transaction_type": "BUY", - "quantity": 1, - "product": "MIS", - "order_type": "LIMIT", - "price": resp[instrument].last_price - 5 - }).then(function(resp) { - modify(variety, resp.order_id); - }).catch(function(err) { - console.log("Order place error", err); - }); - }).catch(function(err) { - console.log(err); - }); -} - -function cancelOrder(variety) { - var tradingsymbol = "RELIANCE"; - var exchange = "NSE"; - var instrument = exchange + ":" + tradingsymbol; - - function cancel(variety, order_id) { - kc.cancelOrder(variety, order_id) - .then(function(resp) { - console.log(resp); - }).catch(function(err) { - console.log(err); - }); - } - - kc.getLTP([instrument]) - .then(function(resp) { - kc.placeOrder(variety, { - "exchange": exchange, - "tradingsymbol": tradingsymbol, - "transaction_type": "BUY", - "quantity": 1, - "product": "MIS", - "order_type": "LIMIT", - "price": resp[instrument].last_price - 5 - }).then(function(resp) { - cancel(variety, resp.order_id); - }).catch(function(err) { - console.log("Order place error", err); - }); - }).catch(function(err) { - console.log(err); - }); -} - -function getGTT(trigger_id) { - if (trigger_id) { - kc.getGTTs().then(function (resp) { - console.log(resp) - }).catch(function (error) { - console.log(error) - }) - } else { - kc.getGTT(trigger_id).then(function (resp) { - console.log(resp) - }).catch(function (error) { - console.log(error) - }) - } -} - -function placeGTT() { - kc.placeGTT({ - trigger_type: kc.GTT_TYPE_OCO, - tradingsymbol: "SBIN", - exchange: "NSE", - trigger_values: [300, 400], - last_price: 318, - orders: [{ - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 300 - }, { - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 400 - }] - }).then(function (resp) { - console.log(resp) - }).catch(function (error) { - console.log(error) - }) -} - -function modifyGTT(trigger_id) { - kc.modifyGTT(trigger_id, { - trigger_type: kc.GTT_TYPE_OCO, - tradingsymbol: "SBIN", - exchange: "NSE", - trigger_values: [301, 401], - last_price: 318, - orders: [{ - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 300 - }, { - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 400 - }] - }).then(function (resp) { - console.log(resp) - }).catch(function (error) { - console.log(error) - }) -} - -function deleteGTT(trigger_id) { - kc.deleteGTT(trigger_id).then(function (resp) { - console.log(resp) - }).catch(function (error) { - console.log(error) - }) -} - -function convertPosition() { - kc.convertPosition({ - exchange:"MCX", - tradingsymbol:"GOLDPETAL21JUNFUT", - transaction_type:"BUY", - position_type:"day", - quantity:4, - old_product:"MIS", - new_product:"NRML" - }).then(function (resp) { - console.log(resp) - }).catch(function (error) { - console.log(error) - }) -} - -function orderMargins() { - kc.orderMargins([{ - "exchange": "NFO", - "tradingsymbol": "NIFTY21JUN15400PE", - "transaction_type": "BUY", - "variety": "regular", - "product": "MIS", - "order_type": "MARKET", - "quantity": 75 - }, - { - "exchange": "NFO", - "tradingsymbol": "NIFTY21JUN14450PE", - "transaction_type": "SELL", - "variety": "regular", - "product": "MIS", - "order_type": "MARKET", - "quantity": 150 - }], "compact").then(function(resp) { - console.log(resp); - }).catch(function(err) { - console.log(err); }); -} - -function basketMargins() { - kc.orderBasketMargins([{ - "exchange": "NFO", - "tradingsymbol": "NIFTY21JUN15400PE", - "transaction_type": "BUY", - "variety": "regular", - "product": "MIS", - "order_type": "MARKET", - "quantity": 75 - }, - { - "exchange": "NFO", - "tradingsymbol": "NIFTY21JUN14450PE", - "transaction_type": "SELL", - "variety": "regular", - "product": "MIS", - "order_type": "MARKET", - "quantity": 150 - }], true, "compact").then(function (resp) { - console.log(resp); - }).catch(function(err) { - console.log(err); }); -} \ No newline at end of file diff --git a/examples/websocket.js b/examples/websocket.js deleted file mode 100644 index 469e530..0000000 --- a/examples/websocket.js +++ /dev/null @@ -1,40 +0,0 @@ -var KiteTicker = require("kiteconnect").KiteTicker; -var ticker = new KiteTicker({ - api_key: "api_key", - access_token: "access_token" -}); - - -ticker.connect(); -ticker.on('ticks', onTicks); -ticker.on('connect', subscribe); -ticker.on('disconnect', onDisconnect); -ticker.on('error', onError); -ticker.on('close', onClose); -ticker.on('order_update', onTrade); - -function onTicks(ticks) { - console.log("Ticks", ticks); -} - -function subscribe() { - var items = [738561]; - ticker.subscribe(items); - ticker.setMode(ticker.modeFull, items); -} - -function onDisconnect(error) { - console.log("Closed connection on disconnect", error); -} - -function onError(error) { - console.log("Closed connection on error", error); -} - -function onClose(reason) { - console.log("Closed connection on close", reason); -} - -function onTrade(order) { - console.log("Order update", order); -} diff --git a/interfaces/any-object.ts b/interfaces/any-object.ts new file mode 100644 index 0000000..44b61c5 --- /dev/null +++ b/interfaces/any-object.ts @@ -0,0 +1,15 @@ +/** + * + * @date 07/06/2023 - 21:38:08 + * + * @export + * @interface AnyObject + * @typedef {AnyObject} + */ +export interface AnyObject { + /** + * + * @date 07/06/2023 - 21:38:08 + */ + [key: string]: any; +} \ No newline at end of file diff --git a/interfaces/connect.ts b/interfaces/connect.ts new file mode 100644 index 0000000..5b110e1 --- /dev/null +++ b/interfaces/connect.ts @@ -0,0 +1,1178 @@ + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum ProductTypes { + PRODUCT_MIS = 'MIS', + PRODUCT_CNC = 'CNC', + PRODUCT_CO = 'CO', + PRODUCT_NRML = 'NRML', + PRODUCT_BO = 'BO', +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum Varieties { + VARIETY_AMO = 'amo', + VARIETY_AUCTION = 'auction', + VARIETY_BO = 'bo', + VARIETY_ICEBERG = 'ice', + VARIETY_REGULAR = 'regular', + VARIETY_CO = 'co', + TEST = 'test' +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum ValidityTypes { + VALIDITY_DAY = 'DAY', + VALIDITY_IOC = 'IOC', + VALIDITY_TTL = 'TTL', +} + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum MarginTypes { + MARGIN_EQUITY = 'equity', + MARGIN_COMMODITY = 'commodity', +} + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum StatusTypes { + STATUS_CANCELLED = 'CANCELLED', + STATUS_REJECTED = 'REJECTED', + STATUS_COMPLETE = 'COMPLETE', +} + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum GTTStatusTypes { + GTT_TYPE_OCO = 'two-leg', + GTT_TYPE_SINGLE = 'single', + GTT_STATUS_ACTIVE = 'active', + GTT_STATUS_TRIGGERED = 'triggered', + GTT_STATUS_DISABLED = 'disabled', + GTT_STATUS_EXPIRED = 'expired', + GTT_STATUS_CANCELLED = 'cancelled', + GTT_STATUS_REJECTED = 'rejected', + GTT_STATUS_DELETED = 'deleted', +} + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum PositionTypes { + POSITION_TYPE_DAY = 'day', + POSITION_TYPE_OVERNIGHT = 'overnight', +} + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @interface KiteConnectParams + * @typedef {KiteConnectParams} + */ +export interface KiteConnectParams { + /** + * API key issued to you. + */ + api_key: string; + /** + * Token obtained after the login flow in exchange for the `request_token`. + * Pre-login, this will default to null, but once you have obtained it, you + * should persist it in a database or session to pass to the Kite Connect + * class initialisation for subsequent requests. + * + * Defaults to `null` + */ + access_token?: string | null; + /** + * API end point root. Unless you explicitly want to send API requests to a + * non-default endpoint, this can be ignored. + * + * Defaults to 'https?://api.kite.trade' + */ + root?: string; + /** + * Kite connect login url + * + * Defaults to 'https?://kite.trade/connect/login' + */ + login_uri?: string; + /** + * If set to true, will console log requests and responses. + * + * Defaults to `false` + */ + debug?: boolean; + /** + * Time (milliseconds) for which the API client will wait for a request to complete before it fails. + * + * Defaults to `7000` + */ + timeout?: number; + /* + * Default url for which user will be redirected to login page + * defa + */ + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?string} + */ + default_login_uri?: string; +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @interface KiteConectInterface + * @typedef {KiteConectInterface} + * @extends {KiteConnectParams} + */ +export interface KiteConectInterface extends KiteConnectParams { + +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum ExchangeTypes { + NSE = 'NSE', + BSE = 'BPSE', + NFO = 'NFO', + BFO = 'BFO', + CDS = 'CDS', + MCX = 'MCX' +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum TransactionTypes { + BUY = 'BUY', + SELL = 'SELL' +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum Products { + NRML = 'NRML', + MIS = 'MIS', + CNC = 'CNC' +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum OrderTypes { + LIMIT = 'LIMIT', + SL = 'SL', + SLM = 'SL-M', + MARKET = 'MARKET' +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @enum {number} + */ +export enum Validities { + DAY = 'DAY', + IOC = 'IOC', +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @interface OrderParams + * @typedef {OrderParams} + */ +export interface OrderParams { + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?string} + */ + exchange?: string; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?string} + */ + tradingsymbol?: string; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?TransactionTypes} + */ + transaction_type?: TransactionTypes; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + quantity?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?Products} + */ + product?: Products; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {OrderTypes} + */ + order_type: OrderTypes; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?Validities} + */ + validity?: Validities; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + price?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + disclosed_quantity?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + trigger_price?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + squareoff?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + stoploss?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + traling_stoploss?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + validity_ttl?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + iceberg_legs?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + iceberg_quantity?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?number} + */ + auction_number?: number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?string} + */ + tag?: string; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?string} + */ + variety?: string; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?(string | number)} + */ + order_id?: string | number; +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @interface CancelOrderParams + * @typedef {CancelOrderParams} + */ +export interface CancelOrderParams { + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?(string | number)} + */ + parent_order_id?: string | number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?string} + */ + variety?: string; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?(string | number)} + */ + order_id?: string | number; +}; + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @interface ExitOrderParams + * @typedef {ExitOrderParams} + */ +export interface ExitOrderParams { + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?(string | number)} + */ + parent_order_id?: string | number; +} + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @interface ConvertPositionParams + * @typedef {ConvertPositionParams} + */ +export interface ConvertPositionParams { + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {string} + */ + exchange: string; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {string} + */ + tradingsymbol: string; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {TransactionTypes} + */ + transaction_type: TransactionTypes; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {PositionTypes} + */ + position_type: PositionTypes; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {(string | number)} + */ + quantity: string | number; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {Products} + */ + old_product: Products; + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {Products} + */ + new_product: Products; +} + +/** + * + * @date 07/06/2023 - 21:38:13 + * + * @export + * @interface Order + * @typedef {Order} + */ +export interface Order { + /** + * + * @date 07/06/2023 - 21:38:13 + * + * @type {?TransactionTypes} + */ + transaction_type?: TransactionTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + quantity?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Products} + */ + product?: Products; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?OrderTypes} + */ + order_type?: OrderTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?ExchangeTypes} + */ + exchange?: ExchangeTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + tradingsymbol?: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Varieties} + */ + variety?: Varieties; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(number | string)} + */ + price?: number | string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?number} + */ + trigger_price?: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?PositionTypes} + */ + position_type?: PositionTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Products} + */ + old_product?: Products; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Products} + */ + new_product?: Products; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + amount?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + tag?: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + instalments?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + frequency?: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + initial_amount?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + instalment_day?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + status?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + sip_id?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(GTTStatusTypes.GTT_TYPE_OCO | GTTStatusTypes.GTT_TYPE_SINGLE)} + */ + trigger_type?: GTTStatusTypes.GTT_TYPE_OCO | GTTStatusTypes.GTT_TYPE_SINGLE; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?any[]} + */ + trigger_values?: any[]; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + last_price?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Order[]} + */ + orders?: Order[]; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + order_id?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + parent_order_id?: string | number; +} + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface getHistoricalDataParms + * @typedef {getHistoricalDataParms} + */ +export interface getHistoricalDataParms { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + instrument_token: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + interval: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {(string | Date)} + */ + from_date: string | Date; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {(string | Date)} + */ + to_date: string | Date; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?boolean} + */ + continuous?: boolean; +}; + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface ModifyGTTParams + * @typedef {ModifyGTTParams} + */ +export interface ModifyGTTParams { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {(GTTStatusTypes.GTT_TYPE_SINGLE | GTTStatusTypes.GTT_TYPE_OCO)} + */ + trigger_type: GTTStatusTypes.GTT_TYPE_SINGLE | GTTStatusTypes.GTT_TYPE_OCO; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + tradingsymbol: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {ExchangeTypes} + */ + exchange: ExchangeTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {Array} + */ + trigger_values: Array; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {number} + */ + last_price: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {{ + transaction_type: string + quantity: number; + product: Products; + order_type: OrderTypes; + price: number; + }[]} + */ + orders: { + transaction_type: string + quantity: number; + product: Products; + order_type: OrderTypes; + price: number; + }[]; +}; + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface ModifyMFSIPParams + * @typedef {ModifyMFSIPParams} + */ +export interface ModifyMFSIPParams { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + instalments?: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + frequency?: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + instalment_day?: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + status?: string; +} + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface ModifyOrderParams + * @typedef {ModifyOrderParams} + */ +export interface ModifyOrderParams { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?number} + */ + quantity?: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?number} + */ + price?: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?OrderTypes} + */ + order_type?: OrderTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Validities} + */ + validity?: Validities; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?number} + */ + disclosed_quantity?: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?number} + */ + trigger_price?: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + parent_order_id?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + variety?: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + order_id?: string | number; +}; + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface OrderMarginOrder + * @typedef {OrderMarginOrder} + */ +export interface OrderMarginOrder { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + exchange: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + tradingsymbol: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {TransactionTypes} + */ + transaction_type: TransactionTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {Varieties} + */ + variety: Varieties; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {ProductTypes} + */ + product: ProductTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {OrderTypes} + */ + order_type: OrderTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {number} + */ + quantity: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {number} + */ + price: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {number} + */ + trigger_price: number; +}; + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface PlaceMFOrderParams + * @typedef {PlaceMFOrderParams} + */ +export interface PlaceMFOrderParams { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + tradingsymbol: string + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {TransactionTypes} + */ + transaction_type: TransactionTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + quantity?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + amount?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + tag?: string; +} + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface PlaceGTTParams + * @typedef {PlaceGTTParams} + */ +export interface PlaceGTTParams { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {(GTTStatusTypes.GTT_TYPE_OCO | GTTStatusTypes.GTT_TYPE_SINGLE)} + */ + trigger_type: GTTStatusTypes.GTT_TYPE_OCO | GTTStatusTypes.GTT_TYPE_SINGLE; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + tradingsymbol: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {ExchangeTypes} + */ + exchange: ExchangeTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {Array} + */ + trigger_values: Array; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {number} + */ + last_price: number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {{ + transaction_type: TransactionTypes; + quantity: number; + product: Products; + order_type: OrderTypes; + price: number + }[]} + */ + orders: { + transaction_type: TransactionTypes; + quantity: number; + product: Products; + order_type: OrderTypes; + price: number + }[]; +}; + +/** + * + * @date 07/06/2023 - 21:38:12 + * + * @export + * @interface PlaceOrderParams + * @typedef {PlaceOrderParams} + */ +export interface PlaceOrderParams { + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {string} + */ + tradingsymbol: string; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Varieties} + */ + variety?: Varieties; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?ExchangeTypes} + */ + exchange?: ExchangeTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {TransactionTypes} + */ + transaction_type: TransactionTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?OrderTypes} + */ + order_type?: OrderTypes; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?Products} + */ + product?: Products; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + quantity?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?(string | number)} + */ + amount?: string | number; + /** + * + * @date 07/06/2023 - 21:38:12 + * + * @type {?string} + */ + tag?: string; +}; \ No newline at end of file diff --git a/interfaces/index.ts b/interfaces/index.ts new file mode 100644 index 0000000..7d86bcf --- /dev/null +++ b/interfaces/index.ts @@ -0,0 +1,3 @@ +export * from './connect'; +export * from './any-object'; +export * from './ticker'; \ No newline at end of file diff --git a/interfaces/ticker.ts b/interfaces/ticker.ts new file mode 100644 index 0000000..e3f2a73 --- /dev/null +++ b/interfaces/ticker.ts @@ -0,0 +1,65 @@ +/** + * + * @date 07/06/2023 - 21:38:22 + * + * @export + * @interface KiteTickerParams + * @typedef {KiteTickerParams} + */ +export interface KiteTickerParams { + /** + * + * @date 07/06/2023 - 21:38:22 + * + * @type {?string} + */ + api_key?: string; + /** + * + * @date 07/06/2023 - 21:38:22 + * + * @type {?string} + */ + access_token?: string; + /** + * + * @date 07/06/2023 - 21:38:22 + * + * @type {?boolean} + */ + reconnect?: boolean; + /** + * + * @date 07/06/2023 - 21:38:22 + * + * @type {?number} + */ + max_retry?: number; + /** + * + * @date 07/06/2023 - 21:38:22 + * + * @type {?number} + */ + max_delay?: number; + /** + * + * @date 07/06/2023 - 21:38:22 + * + * @type {string} + */ + root: string; +} + +/** + * + * @date 07/06/2023 - 21:38:22 + * + * @export + * @interface KiteTickerInterface + * @typedef {KiteTickerInterface} + * @extends {KiteTickerParams} + */ +export interface KiteTickerInterface extends KiteTickerParams { + +} \ No newline at end of file diff --git a/lib/connect.ts b/lib/connect.ts index 7ea6ea5..0edb1a2 100644 --- a/lib/connect.ts +++ b/lib/connect.ts @@ -1,10 +1,13 @@ -"use strict"; +'use strict'; + +import axios, { AxiosInstance, AxiosRequestConfig, AxiosTransformer, Method } from 'axios'; +import csvParse from 'papaparse'; +import sha256 from 'crypto-js/sha256'; +import querystring from 'querystring'; +import utils from './utils'; +import { KiteConnectParams, Varieties, GTTStatusTypes, AnyObject, Order, TransactionTypes, KiteConectInterface, CancelOrderParams, ExitOrderParams, ModifyGTTParams, ModifyOrderParams, PlaceGTTParams, PlaceMFOrderParams, PlaceOrderParams } from '../interfaces'; +import { DEFAULTS, ROUTES } from '../constants'; -import axios from "axios"; -import csvParse from "papaparse"; -import sha256 from "crypto-js/sha256"; -import querystring from "querystring"; -import utils from "./utils"; /** * @classdesc API client class. In production, you may initialise a single instance of this class per `api_key`. @@ -17,11 +20,11 @@ import utils from "./utils"; * ------------------------ * ~~~~ * - * const KiteConnect = require("kiteconnect").KiteConnect; + * const KiteConnect = require('kiteconnect').KiteConnect; * - * const kc = new KiteConnect({api_key: "your_api_key"}); + * const kc = new KiteConnect({api_key: 'your_api_key'}); * - * kc.generateSession("request_token", "api_secret") + * kc.generateSession('request_token', 'api_secret') * .then(function(response) { * init(); * }) @@ -65,1134 +68,920 @@ import utils from "./utils"; * exchange for the `request_token`. Pre-login, this will default to null, * but once you have obtained it, you should persist it in a database or session to pass * to the Kite Connect class initialisation for subsequent requests. - * @param {string} [params.root="https://api.kite.trade"] API end point root. Unless you explicitly + * @param {string} [params.root='https://api.kite.trade'] API end point root. Unless you explicitly * want to send API requests to a non-default endpoint, this can be ignored. - * @param {string} [params.login_uri="https://kite.zerodha.com/connect/login"] Kite connect login url + * @param {string} [params.login_uri='https://kite.zerodha.com/connect/login'] Kite connect login url * @param {bool} [params.debug=false] If set to true, will console log requests and responses. * @param {number} [params.timeout=7000] Time (milliseconds) for which the API client will wait * for a request to complete before it fails. * * @example Initialize KiteConnect object - * const kc = KiteConnect("my_api_key", {timeout: 10, debug: false}) + * const kc = KiteConnect('my_api_key', {timeout: 10, debug: false}) */ -const KiteConnect = function(params) { - const self = this; - const defaults = { - "root": "https://api.kite.trade", - "login": "https://kite.zerodha.com/connect/login", - "debug": false, - "timeout": 7000 - }; - self.api_key = params.api_key; - self.root = params.root || defaults.root; - self.timeout = params.timeout || defaults.timeout; - self.debug = params.debug || defaults.debug; - self.access_token = params.access_token || null; - self.default_login_uri = defaults.login; - self.session_expiry_hook = null; - - const kiteVersion = 3; // Kite version to send in header - const userAgent = utils.getUserAgent(); // User agent to be sent with every request - - const routes = { - "api.token": "/session/token", - "api.token.invalidate": "/session/token", - "api.token.renew": "/session/refresh_token", - "user.profile": "/user/profile", - "user.margins": "/user/margins", - "user.margins.segment": "/user/margins/{segment}", - - "orders": "/orders", - "trades": "/trades", - "order.info": "/orders/{order_id}", - "order.place": "/orders/{variety}", - "order.modify": "/orders/{variety}/{order_id}", - "order.cancel": "/orders/{variety}/{order_id}", - "order.trades": "/orders/{order_id}/trades", - "order.margins": "/margins/orders", - "order.margins.basket": "/margins/basket", - - "portfolio.positions": "/portfolio/positions", - "portfolio.holdings": "/portfolio/holdings", - "portfolio.holdings.auction": "/portfolio/holdings/auctions", - "portfolio.positions.convert": "/portfolio/positions", - - "mf.orders": "/mf/orders", - "mf.order.info": "/mf/orders/{order_id}", - "mf.order.place": "/mf/orders", - "mf.order.cancel": "/mf/orders/{order_id}", - - "mf.sips": "/mf/sips", - "mf.sip.info": "/mf/sips/{sip_id}", - "mf.sip.place": "/mf/sips", - "mf.sip.modify": "/mf/sips/{sip_id}", - "mf.sip.cancel": "/mf/sips/{sip_id}", - - "mf.holdings": "/mf/holdings", - "mf.instruments": "/mf/instruments", - - "market.instruments.all": "/instruments", - "market.instruments": "/instruments/{exchange}", - "market.historical": "/instruments/historical/{instrument_token}/{interval}", - "market.trigger_range": "/instruments/trigger_range/{transaction_type}", - - "market.quote": "/quote", - "market.quote.ohlc": "/quote/ohlc", - "market.quote.ltp": "/quote/ltp", - - "gtt.triggers": "/gtt/triggers", - "gtt.trigger_info": "/gtt/triggers/{trigger_id}", - "gtt.place": "/gtt/triggers", - "gtt.modify": "/gtt/triggers/{trigger_id}", - "gtt.delete": "/gtt/triggers/{trigger_id}" - }; - const requestInstance = axios.create({ - baseURL: self.root, - timeout: self.timeout, - headers: { - "X-Kite-Version": kiteVersion, - "User-Agent": userAgent - }, - paramsSerializer: function(params) { - return querystring.stringify(params); - } - }); - - // Add a request interceptor - requestInstance.interceptors.request.use(function(request) { - if (self.debug) console.log(request); - return request; - }); - - // Add a response interceptor - requestInstance.interceptors.response.use(function(response) { - if (self.debug) console.log(response); - - const contentType = response.headers["content-type"]; - if (contentType === "application/json" && typeof response.data === "object") { - // Throw incase of error - if (response.data.error_type) throw response.data; - - // Return success data - return response.data.data; - } else if (contentType === "text/csv") { - // Return the response directly - return response.data - } else { - return { - "error_type": "DataException", - "message": "Unknown content type (" + contentType + ") with response: (" + response.data + ")" - }; - } - }, function (error) { - let resp = { - "message": "Unknown error", - "error_type": "GeneralException", - "data": null - }; - if (error.response) { - // The request was made and the server responded with a status code - // that falls out of the range of 2xx - if (error.response.data && error.response.data.error_type) { - if (error.response.data.error_type === "TokenException" && self.session_expiry_hook) { - self.session_expiry_hook() - } - resp = error.response.data; - } else { - resp.error_type = "NetworkException"; - resp.message = error.response.statusText; - } - } else if (error.request) { - // The request was made but no response was received - // `error.request` is an instance of XMLHttpRequest in the browser and an instance of - // http.ClientRequest in node.js - resp.error_type = "NetworkException"; - resp.message = "No response from server with error code: " + error.code; - } else if (error.message) { - resp = error - } - return Promise.reject(resp); - }); - - // Constants - // Products - /** - * @memberOf KiteConnect - */ - self.PRODUCT_MIS = "MIS"; - /** - * @memberOf KiteConnect - */ - self.PRODUCT_CNC = "CNC"; +class KiteConnect implements KiteConectInterface { /** - * @memberOf KiteConnect - */ - self.PRODUCT_NRML = "NRML"; - /** - * @memberOf KiteConnect - */ - self.PRODUCT_CO = "CO"; - /** - * @memberOf KiteConnect - */ - self.PRODUCT_BO = "BO"; - - // Order types + * + * @date 07/06/2023 - 21:37:49 + * + * @type {string} + */ + api_key: string; /** - * @memberOf KiteConnect - */ - self.ORDER_TYPE_MARKET = "MARKET"; + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?(string | null)} + */ + access_token?: string | null; /** - * @memberOf KiteConnect - */ - self.ORDER_TYPE_LIMIT = "LIMIT"; + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?string} + */ + root?: string; /** - * @memberOf KiteConnect - */ - self.ORDER_TYPE_SLM = "SL-M"; + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?string} + */ + login_uri?: string; /** - * @memberOf KiteConnect - */ - self.ORDER_TYPE_SL = "SL"; - - // varities + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?boolean} + */ + debug?: boolean; /** - * @memberOf KiteConnect - */ - self.VARIETY_REGULAR = "regular"; + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?number} + */ + timeout?: number; /** - * @memberOf KiteConnect - */ - self.VARIETY_BO = "bo"; + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?string} + */ + default_connect_uri?: string; /** - * @memberOf KiteConnect - */ - self.VARIETY_CO = "co"; + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?(string | null)} + */ + session_expiry_hook?: string | null; /** - * @memberOf KiteConnect - */ - self.VARIETY_AMO = "amo"; + * + * @date 07/06/2023 - 21:37:49 + * + * @type {?string} + */ + default_login_uri?: string; /** - * @memberOf KiteConnect - */ - self.VARIETY_ICEBERG = "iceberg"; + * + * @date 07/06/2023 - 21:37:49 + * + * @private + * @type {AxiosInstance} + */ + private requestInstance: AxiosInstance; /** - * @memberOf KiteConnect - */ - self.VARIETY_AUCTION = "auction"; + * Creates an instance of KiteConnect. + * @date 07/06/2023 - 21:37:49 + * + * @constructor + * @param {KiteConnectParams} params + */ + constructor(params: KiteConnectParams) { + this.api_key = params.api_key; + this.root = params.root || DEFAULTS.root; + this.timeout = params.timeout || DEFAULTS.timeout; + this.debug = params.debug || DEFAULTS.debug; + this.access_token = params.access_token || null; + this.default_connect_uri = DEFAULTS.login; + this.session_expiry_hook = null; + this.requestInstance = this.createAxiosInstance(); + } - // Transaction type - /** - * @memberOf KiteConnect - */ - self.TRANSACTION_TYPE_BUY = "BUY"; /** - * @memberOf KiteConnect - */ - self.TRANSACTION_TYPE_SELL = "SELL"; + * + * @date 07/06/2023 - 21:37:49 + * + * @private + * @returns {*} + */ + private createAxiosInstance() { + const kiteVersion = 3; // Kite version to send in header + const userAgent = utils.getUserAgent(); // User agent to be sent with every request + const requestInstance = axios.create({ + baseURL: this.root as string, + timeout: this.timeout, + headers: { + 'X-Kite-Version': kiteVersion, + 'User-Agent': userAgent + }, + paramsSerializer(params) { + return querystring.stringify(params); + } + }); - // Validity - /** - * @memberOf KiteConnect - */ - self.VALIDITY_DAY = "DAY"; - /** - * @memberOf KiteConnect - */ - self.VALIDITY_IOC = "IOC"; - /** - * @memberOf KiteConnect - */ - self.VALIDITY_TTL = "TTL"; + // Add a request interceptor + requestInstance.interceptors.request.use((request) => { + if (this.debug) console.log(request); + return request; + }); - // Exchanges - /** - * @memberOf KiteConnect - */ - self.EXCHANGE_NSE = "NSE"; - /** - * @memberOf KiteConnect - */ - self.EXCHANGE_BSE = "BSE"; - /** - * @memberOf KiteConnect - */ - self.EXCHANGE_NFO = "NFO"; - /** - * @memberOf KiteConnect - */ - self.EXCHANGE_CDS = "CDS"; - /** - * @memberof KiteConnect - */ - self.EXCHANGE_BCD = "BCD"; - /** - * @memberof KiteConnect - */ - self.EXCHANGE_BFO = "BFO"; - /** - * @memberOf KiteConnect - */ - self.EXCHANGE_MCX = "MCX"; + // Add a response interceptor + requestInstance.interceptors.response.use((response) => { + if (this.debug) console.log(response); - // Margins segments - /** - * @memberOf KiteConnect - */ - self.MARGIN_EQUITY = "equity"; - /** - * @memberOf KiteConnect - */ - self.MARGIN_COMMODITY = "commodity"; + const contentType = response.headers['content-type']; + if (contentType === 'application/json' && typeof response.data === 'object') { + // Throw incase of error + if (response.data.error_type) throw response.data; - /** - * @memberOf KiteConnect - */ - self.STATUS_CANCELLED = "CANCELLED"; - /** - * @memberOf KiteConnect - */ - self.STATUS_REJECTED = "REJECTED"; - /** - * @memberOf KiteConnect - */ - self.STATUS_COMPLETE = "COMPLETE"; - /** - * @memberOf KiteConnect - */ - self.GTT_TYPE_OCO = "two-leg"; - /** - * @memberOf KiteConnect - */ - self.GTT_TYPE_SINGLE = "single"; - /** - * @memberOf KiteConnect - */ - self.GTT_STATUS_ACTIVE = "active"; - /** - * @memberOf KiteConnect - */ - self.GTT_STATUS_TRIGGERED = "triggered"; - /** - * @memberOf KiteConnect - */ - self.GTT_STATUS_DISABLED = "disabled"; - /** - * @memberOf KiteConnect - */ - self.GTT_STATUS_EXPIRED = "expired"; - /** - * @memberOf KiteConnect - */ - self.GTT_STATUS_CANCELLED = "cancelled"; - /** - * @memberOf KiteConnect - */ - self.GTT_STATUS_REJECTED = "rejected"; - /** - * @memberOf KiteConnect - */ - self.GTT_STATUS_DELETED = "deleted"; + // Return success data + return response.data.data; + } else if (contentType === 'text/csv') { + // Return the response directly + return response.data + } else { + return { + 'error_type': 'DataException', + 'message': 'Unknown content type (' + contentType + ') with response: (' + response.data + ')' + }; + } + }, function (error) { + let resp = { + 'message': 'Unknown error', + 'error_type': 'GeneralException', + 'data': null + }; - /** - * @memberOf KiteConnect - */ - self.POSITION_TYPE_DAY = "day"; + if (error.response) { + // The request was made and the server responded with a status code + // that falls out of the range of 2xx + if (error.response.data && error.response.data.error_type) { + if (error.response.data.error_type === 'TokenException' && this.session_expiry_hook) { + this.session_expiry_hook() + } + + resp = error.response.data; + } else { + resp.error_type = 'NetworkException'; + resp.message = error.response.statusText; + } + } else if (error.request) { + // The request was made but no response was received + // `error.request` is an instance of XMLHttpRequest in the browser and an instance of + // http.ClientRequest in node.js + resp.error_type = 'NetworkException'; + resp.message = 'No response from server with error code: ' + error.code; + } else if (error.message) { + resp = error + } - /** - * @memberOf KiteConnect - */ - self.POSITION_TYPE_OVERNIGHT = "overnight"; + return Promise.reject(resp); + }); + return requestInstance; + } /** - * Set `access_token` received after a successful authentication. - * @method setAccessToken - * @memberOf KiteConnect - * @instance - * @param {string} access_token Token obtained in exchange for `request_token`. - * Once you have obtained `access_token`, you should persist it in a database or session to pass - * to the Kite Connect class initialisation for subsequent requests. - */ - self.setAccessToken = function(access_token) { - self.access_token = access_token; - }; + * + * @date 07/06/2023 - 21:37:49 + * + * @param {string} accessToken + */ + setAccessToken(accessToken: string) { + this.access_token = accessToken; + } /** - * Set a callback hook for session (`TokenException` -- timeout, expiry etc.) errors. - * `access_token` (login session) can become invalid for a number of - * reasons, but it doesn't make sense for the client to try and catch it during every API call. + * + * @date 07/06/2023 - 21:37:49 * - * A callback method that handles session errors can be set here and when the client encounters - * a token error at any point, it'll be called. - * - * This callback, for instance, can log the user out of the UI, - * clear session cookies, or initiate a fresh login. - * @method setSessionExpiryHook - * @memberOf KiteConnect - * @instance - * @param {function} cb Callback + * @param {Function} cb */ - self.setSessionExpiryHook = function(cb) { - self.session_expiry_hook = cb; + setSessionExpiryHook = function (cb: Function) { + this.session_expiry_hook = cb; }; /** - * Get the remote login url to which a user should be redirected to initiate the login flow. - * @method getLoginURL - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:49 + * + * @returns {string} */ - self.getLoginURL = function() { - return self.default_login_uri + "?api_key=" + self.api_key + "&v=" + kiteVersion; - }; + getLoginURL() { + return `${this.default_login_uri}?api_key=${this.api_key}&v=3`; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Do the token exchange with the `request_token` obtained after the login flow, - * and retrieve the `access_token` required for all subsequent requests. The - * response contains not just the `access_token`, but metadata for - * the user who has authenticated. - * @method generateSession - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 * - * @param {string} request_token Token obtained from the GET parameters after a successful login redirect. - * @param {string} api_secret API secret issued with the API key. + * @param {string} request_token + * @param {string} api_secret + * @returns {*} */ - self.generateSession = function(request_token, api_secret) { + generateSession(request_token: string, api_secret: string) { return new Promise(function (resolve, reject) { - const checksum = sha256(self.api_key + request_token + api_secret).toString(); - const p = _post("api.token", { - api_key: self.api_key, - request_token: request_token, - checksum: checksum - }, null, formatGenerateSession); - - p.then(function(resp: any) { + const checksum = sha256(this.api_key + request_token + api_secret).toString(); + const p = this._post('api.token', { + api_key: this.api_key, + request_token: request_token, + checksum: checksum + }, null, formatGenerateSession); + + p.then(function (resp: any) { // Set access token. if (resp && resp.access_token) { - self.setAccessToken(resp.access_token); + this.setAccessToken(resp.access_token); } return resolve(resp); - }).catch(function(err) { + }).catch(function (err: Error) { return reject(err); }); }); - }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Kill the session by invalidating the access token. - * If access_token is passed then it will be set as current access token and get in validated. - * @method invalidateAccessToken - * @memberOf KiteConnect - * @instance - * @param {string} [access_token] Token to invalidate. Default is the active `access_token`. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {?string} [access_token] + * @returns {*} */ - self.invalidateAccessToken = function(access_token) { - access_token = access_token || this.access_token; - - return _delete("api.token.invalidate", { - api_key: self.api_key, - access_token: access_token + invalidateAccessToken(access_token?: string) { + return this._delete('api.token.invalidate', { + api_key: this.api_key, + access_token: access_token || this.access_token, }); - }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Renew access token by active refresh token. - * Renewed access token is implicitly set. - * @method renewAccessToken - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 * - * @param {string} refresh_token Token obtained from previous successful login. - * @param {string} api_secret API secret issued with the API key. + * @param {string} refresh_token + * @param {string} api_secret + * @returns {*} */ - self.renewAccessToken = function(refresh_token, api_secret) { - return new Promise(function (resolve, reject) { - const checksum = sha256(self.api_key + refresh_token + api_secret).toString(); + renewAccessToken(refresh_token: string, api_secret: string) { + return new Promise((resolve, reject) => { + const checksum = sha256(this.api_key + refresh_token + api_secret).toString(); - const p = _post("api.token.renew", { - api_key: self.api_key, + const p = this._post('api.token.renew', { + api_key: this.api_key, refresh_token: refresh_token, checksum: checksum }); - p.then(function(resp: any) { + p.then(function (resp: any) { if (resp && resp.access_token) { - self.setAccessToken(resp.access_token); + this.setAccessToken(resp.access_token); } return resolve(resp); - }).catch(function(err) { + }).catch(function (err: Error) { return reject(err); }); }); - }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Invalidate the refresh token. - * @method invalidateRefreshToken - * @memberOf KiteConnect - * @instance - * @param {string} refresh_token Token to invalidate. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {string} refresh_token + * @returns {*} */ - self.invalidateRefreshToken = function(refresh_token) { - return _delete("api.token.invalidate", { + invalidateRefreshToken = function (refresh_token: string) { + return this._delete('api.token.invalidate', { api_key: this.api_key, refresh_token: refresh_token }); }; /** - * Get user profile details. - * @method getProfile - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getProfile = function() { - return _get("user.profile"); - } + getProfile() { + return this._get('user.profile'); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Get account balance and cash margin details for a particular segment. - * @method getMargins - * @memberOf KiteConnect - * @instance - * @param {string} [segment] trading segment (eg: equity or commodity). + * + * @date 07/06/2023 - 21:37:48 + * + * @param {?string} [segment] + * @returns {*} */ - self.getMargins = function(segment) { + getMargins(segment?: string) { if (segment) { - return _get("user.margins.segment", {"segment": segment}); + return this._get('user.margins.segment', { 'segment': segment }); } else { - return _get("user.margins"); + return this._get('user.margins'); } - }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Place an order. - * @method placeOrder - * @memberOf KiteConnect - * @instance - * @param {string} variety Order variety (ex. bo, co, amo, regular). - * @param {string} params Order params. - * @param {string} params.exchange Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). - * @param {string} params.tradingsymbol Tradingsymbol of the instrument (ex. RELIANCE, INFY). - * @param {string} params.transaction_type Transaction type (BUY or SELL). - * @param {number} params.quantity Order quantity - * @param {string} params.product Product code (NRML, MIS, CNC). - * @param {string} params.order_type Order type (LIMIT, SL, SL-M, MARKET). - * @param {string} [params.validity] Order validity (DAY, IOC). - * @param {number} [params.price] Order Price - * @param {number} [params.disclosed_quantity] Disclosed quantity - * @param {number} [params.trigger_price] Trigger price - * @param {number} [params.squareoff] Square off value (only for bracket orders) - * @param {number} [params.stoploss] Stoploss value (only for bracket orders) - * @param {number} [params.trailing_stoploss] Trailing stoploss value (only for bracket orders) - * @param {number} [params.validity_ttl] Order validity in minutes for TTL validity orders - * @param {number} [params.iceberg_legs] Total number of legs for iceberg order variety - * @param {number} [params.iceberg_quantity] Split quantity for each iceberg leg order - * @param {number} [params.auction_number] A unique identifier for a particular auction - * @param {string} [params.tag] An optional tag to apply to an order to identify it (alphanumeric, max 20 chars) - */ - self.placeOrder = function (variety, params) { + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Varieties} variety + * @param {PlaceOrderParams} params + * @returns {*} + */ + placeOrder(variety: Varieties, params: PlaceOrderParams) { params.variety = variety; - return _post("order.place", params); - }; + return this._post('order.place', params); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Modify an order - * @method modifyOrder - * @memberOf KiteConnect - * @instance - * @param {string} variety Order variety (ex. bo, co, amo, regular). - * @param {string} order_id ID of the order. - * @param {Object} params Order modify params. - * @param {number} [params.quantity] Order quantity - * @param {number} [params.price] Order Price - * @param {string} [params.order_type] Order type (NRML, SL, SL-M, MARKET). - * @param {string} [params.validity] Order validity (DAY, IOC). - * @param {number} [params.disclosed_quantity] Disclosed quantity - * @param {number} [params.trigger_price] Trigger price - * @param {string} [params.parent_order_id] Parent order id incase of multilegged orders. - */ - self.modifyOrder = function(variety, order_id, params) { + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Varieties} variety + * @param {(string | number)} order_id + * @param {ModifyOrderParams} params + * @returns {*} + */ + modifyOrder(variety: Varieties, order_id: string | number, params: ModifyOrderParams) { params.variety = variety; params.order_id = order_id; - return _put("order.modify", params); - }; + return this._put('order.modify', params); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Cancel an order - * @method cancelOrder - * @memberOf KiteConnect - * @instance - * @param {string} variety Order variety (ex. bo, co, amo) - * @param {string} order_id ID of the order. - * @param {Object} [params] Order params. -regular). - * @param {string} [params.parent_order_id] Parent order id incase of multilegged orders. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Varieties} variety + * @param {(string | number)} order_id + * @param {?CancelOrderParams} [params] + * @returns {*} */ - self.cancelOrder = function (variety, order_id, params) { + cancelOrder(variety: Varieties, order_id: string | number, params?: CancelOrderParams) { params = params || {}; params.variety = variety; params.order_id = order_id; - return _delete("order.cancel", params); - }; + return this._delete('order.cancel', params); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Exit an order - * @method exitOrder - * @memberOf KiteConnect - * @instance - * @param {string} variety Order variety (ex. bo, co, amo) - * @param {string} order_id ID of the order. - * @param {Object} [params] Order params. - * @param {string} [params.parent_order_id] Parent order id incase of multilegged orders. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Varieties} variety + * @param {string} order_id + * @param {ExitOrderParams} params + * @returns {*} */ - self.exitOrder = function (variety, order_id, params) { - return self.cancelOrder(variety, order_id, params); - }; + exitOrder(variety: Varieties, order_id: string, params: ExitOrderParams) { + return this.cancelOrder(variety, order_id, params); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Get list of orders. - * @method getOrders - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getOrders = function() { - return _get("orders", null, null, formatResponse); - }; + getOrders() { + return this._get('orders', null, null, this.formatResponse); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Get list of order history. - * @method getOrderHistory - * @memberOf KiteConnect - * @instance - * @param {string} order_id ID of the order whose order details to be retrieved. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} order_id + * @returns {*} */ - self.getOrderHistory = function(order_id) { - return _get("order.info", {"order_id": order_id}, null, formatResponse); - }; + getOrderHistory(order_id: string | number) { + return this._get('order.info', { 'order_id': order_id }, null, this.formatResponse); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve the list of trades executed. - * @method getTrades - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getTrades = function() { - return _get("trades", null, null, formatResponse); - }; + getTrades() { + return this._get('trades', null, null, this.formatResponse); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve the list of trades a particular order). - * An order can be executed in tranches based on market conditions. - * These trades are individually recorded under an order. - * @method getOrderTrades - * @memberOf KiteConnect - * @instance - * @param {string} order_id ID of the order whose trades are to be retrieved. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} order_id + * @returns {*} */ - self.getOrderTrades = function(order_id) { - return _get("order.trades", {"order_id": order_id}, null, formatResponse); - }; + getOrderTrades(order_id: string | number) { + return this._get('order.trades', { 'order_id': order_id }, null, this.formatResponse); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Fetch required margin for order/list of orders - * @method orderMargins - * @memberOf KiteConnect - * @instance - * @param {Object[]} orders Margin fetch orders. - * @param {string} orders[].exchange Name of the exchange(eg. NSE, BSE, NFO, CDS, MCX) - * @param {string} orders[].tradingsymbol Trading symbol of the instrument - * @param {string} orders[].transaction_type eg. BUY, SELL - * @param {string} orders[].variety Order variety (regular, amo, bo, co etc.) - * @param {string} orders[].product Margin product to use for the order - * @param {string} orders[].order_type Order type (MARKET, LIMIT etc.) - * @param {number} orders[].quantity Quantity of the order - * @param {number} orders[].price Price at which the order is going to be placed (LIMIT orders) - * @param {number} orders[].trigger_price Trigger price (for SL, SL-M, CO orders) - * @param {string} mode (optional) Compact mode will only give the total margins - */ - self.orderMargins = function(orders, mode=null) { - return _post("order.margins", orders, null, null, true, - {"mode":mode}); + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Order[]} orders + * @param {*} [mode=null] + * @returns {*} + */ + orderMargins(orders: Order[], mode = null) { + return this._post('order.margins', orders, null, undefined, true, + { 'mode': mode }); } /** - * Fetch basket margin for list of orders - * @method orderBasketMargins - * @memberOf KiteConnect - * @instance - * @param {Object[]} orders Margin fetch orders. - * @param {string} orders[].exchange Name of the exchange(eg. NSE, BSE, NFO, CDS, MCX) - * @param {string} orders[].tradingsymbol Trading symbol of the instrument - * @param {string} orders[].transaction_type eg. BUY, SELL - * @param {string} orders[].variety Order variety (regular, amo, bo, co etc.) - * @param {string} orders[].product Margin product to use for the order - * @param {string} orders[].order_type Order type (MARKET, LIMIT etc.) - * @param {number} orders[].quantity Quantity of the order - * @param {number} orders[].price Price at which the order is going to be placed (LIMIT orders) - * @param {number} orders[].trigger_price Trigger price (for SL, SL-M, CO orders) - * @param {string} consider_positions Boolean to consider users positions while calculating margins - * @param {string} mode (optional) Compact mode will only give the total margins - */ - self.orderBasketMargins = function(orders, consider_positions=true, mode=null) { - return _post("order.margins.basket", orders, null, null, true, - {"consider_positions":consider_positions, "mode":mode}); + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Order[]} orders + * @param {boolean} [consider_positions=true] + * @param {*} [mode=null] + * @returns {*} + */ + orderBasketMargins(orders: Order[], consider_positions = true, mode = null) { + return this._post('order.margins.basket', orders, null, undefined, true, + { 'consider_positions': consider_positions, 'mode': mode }); } /** - * Retrieve the list of equity holdings. - * @method getHoldings - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getHoldings = function() { - return _get("portfolio.holdings"); - }; + getHoldings() { + return this._get('portfolio.holdings'); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieves list of available instruments for a auction session. - * @method getAuctionInstruments - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getAuctionInstruments = function() { - return _get("portfolio.holdings.auction"); - } + getAuctionInstruments() { + return this._get('portfolio.holdings.auction'); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve positions. - * @method getPositions - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getPositions = function() { - return _get("portfolio.positions"); - }; + getPositions() { + return this._get('portfolio.positions'); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Modify an open position's product type. - * @method convertPosition - * @memberOf KiteConnect - * @instance - * @param {Object} params params. - * @param {string} params.exchange Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). - * @param {string} params.tradingsymbol Tradingsymbol of the instrument (ex. RELIANCE, INFY). - * @param {string} params.transaction_type Transaction type (BUY or SELL). - * @param {string} params.position_type Position type (overnight, day). - * @param {string} params.quantity Position quantity - * @param {string} params.old_product Current product code (NRML, MIS, CNC). - * @param {string} params.new_product New Product code (NRML, MIS, CNC). - */ - self.convertPosition = function(params) { - return _put("portfolio.positions.convert", params); - }; + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Order} params + * @returns {*} + */ + convertPosition(params: Order) { + return this._put('portfolio.positions.convert', params); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve the list of market instruments available to trade. - * Note that the results could be large, several hundred KBs in size, - * with tens of thousands of entries in the list. - * Response is array for objects. For example - * ~~~~ - * { - * instrument_token: '131098372', - * exchange_token: '512103', - * tradingsymbol: 'NIDHGRN', - * name: 'NIDHI GRANITES', - * last_price: '0.0', - * expiry: '', - * strike: '0.0', - * tick_size: '0.05', - * lot_size: '1', - * instrument_type: 'EQ', - * segment: 'BSE', - * exchange: 'BSE' }, ...] - * ~~~~ - * - * @method getInstruments - * @memberOf KiteConnect - * @instance - * @param {Array} [segment] Filter instruments based on exchange (NSE, BSE, NFO, BFO, CDS, MCX). - * If no `segment` is specified, all instruments are returned. - */ - self.getInstruments = function(exchange) { - if(exchange) { - return _get("market.instruments", { - "exchange": exchange - }, null, transformInstrumentsResponse); + * + * @date 07/06/2023 - 21:37:48 + * + * @param {boolean} exchange + * @returns {*} + */ + getInstruments(exchange: boolean) { + if (exchange) { + return this._get('market.instruments', { + 'exchange': exchange + }, null, this.transformInstrumentsResponse); } else { - return _get("market.instruments.all", null, null, transformInstrumentsResponse); + return this._get('market.instruments.all', null, null, this.transformInstrumentsResponse); } - }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve quote and market depth for list of instruments. - * @method getQuote - * @memberOf KiteConnect - * @instance - * @param {Array} instruments is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. - * For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..] + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string[] | string)} instruments + * @returns {*} */ - self.getQuote = function(instruments) { - return _get("market.quote", {"i": instruments}, null, formatQuoteResponse); - }; + getQuote(instruments: string[] | string) { + return this._get('market.quote', { 'i': instruments }, null, formatQuoteResponse); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve OHLC for list of instruments. - * @method getOHLC - * @memberOf KiteConnect - * @instance - * @param {Array} instruments is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. - * For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..] + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string[] | string)} instruments + * @returns {*} */ - self.getOHLC = function(instruments) { - return _get("market.quote.ohlc", {"i": instruments}); - }; + getOHLC(instruments: string[] | string) { + return this._get('market.quote.ohlc', { 'i': instruments }); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve LTP for list of instruments. - * @method getLTP - * @memberOf KiteConnect - * @instance - * @param {Array} instruments is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. - * For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..] + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string[] | string)} instruments + * @returns {*} */ - self.getLTP = function(instruments) { - return _get("market.quote.ltp", {"i": instruments}); - }; - + getLTP(instruments: string[] | string) { + return this._get('market.quote.ltp', { 'i': instruments }); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Retrieve historical data (candles) for an instrument. - * Although the actual response JSON from the API does not have field - * names such has 'open', 'high' etc., this functin call structures - * the data into an array of objects with field names. For example: - * - * ~~~~ - * [{ - * date: '2015-02-10T00:00:00+0530', - * open: 277.5, - * high: 290.8, - * low: 275.7, - * close: 287.3, - * volume: 22589681 - * }, ....] - * ~~~~ - * - * @method getHistoricalData - * @memberOf KiteConnect - * @instance - * @param {string} instrument_token Instrument identifier (retrieved from the instruments()) call. - * @param {string} interval candle interval (minute, day, 5 minute etc.) - * @param {string|Date} from_date From date (String in format of 'yyyy-mm-dd HH:MM:SS' or Date object). - * @param {string|Date} to_date To date (String in format of 'yyyy-mm-dd HH:MM:SS' or Date object). - * @param {bool} [continuous=false] is a bool flag to get continuous data for futures and options instruments. Defaults to false. - * @param {bool} [oi=false] is a bool flag to include OI data for futures and options instruments. Defaults to false. - */ - self.getHistoricalData = function(instrument_token, interval, from_date, to_date, continuous, oi) { + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} instrument_token + * @param {string} interval + * @param {(string | Date)} from_date + * @param {(string | Date)} to_date + * @param {(number | boolean)} [continuous=false] + * @param {(number | boolean)} [oi=false] + * @returns {*} + */ + getHistoricalData(instrument_token: string | number, interval: string, from_date: string | Date, to_date: string | Date, continuous: number | boolean = false, oi: number | boolean = false) { continuous = continuous ? 1 : 0; oi = oi ? 1 : 0; - if (typeof to_date === "object") to_date = _getDateTimeString(to_date) - if (typeof from_date === "object") from_date = _getDateTimeString(from_date) - - return _get("market.historical", { - instrument_token: instrument_token, - interval: interval, - from: from_date, - to: to_date, - continuous: continuous, - oi: oi - }, null, parseHistorical); - }; - - // Convert Date object to string of format yyyy-mm-dd HH:MM:SS - function _getDateTimeString(date) { - const isoString = date.toISOString(); - return isoString.replace("T", " ").split(".")[0]; - } - - /** - * Retrieve the buy/sell trigger range for Cover Orders. - * @method getTriggerRange - * @memberOf KiteConnect - * @instance - * @param {string} exchange Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). - * @param {string} tradingsymbol Tranding symbol of the instrument (ex. RELIANCE, INFY). - * @param {string} transaction_type Transaction type (BUY or SELL). + if (typeof to_date === 'object') to_date = _getDateTimeString(to_date) + if (typeof from_date === 'object') from_date = _getDateTimeString(from_date) + + return this._get('market.historical', { + instrument_token: instrument_token, + interval: interval, + from: from_date, + to: to_date, + continuous: continuous, + oi: oi + }, null, this.parseHistorical); + }/** + * + * @date 07/06/2023 - 21:37:48 */ - self.getTriggerRange = function(transaction_type, instruments) { - return _get("market.trigger_range", - { - "i": instruments, - "transaction_type": transaction_type.toLowerCase() - } - ); - }; + ; /** - * Get list of mutual fund orders. - * @method getMFOrders - * @memberOf KiteConnect - * @instance - * @param {string} [order_id] ID of the order (optional) whose order details are to be retrieved. - * If no `order_id` is specified, all orders for the day are returned. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {?(string | number)} [order_id] + * @returns {*} */ - self.getMFOrders = function (order_id) { + getMFOrders(order_id?: string | number) { if (order_id) { - return _get("mf.order.info", { "order_id": order_id }, null, formatResponse); + return this._get('mf.order.info', { 'order_id': order_id }, null, this.formatResponse); } else { - return _get("mf.orders", null, null, formatResponse); + return this._get('mf.orders', null, null, this.formatResponse); } - }; - + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Place a mutual fund order. - * @method placeMFOrder - * @memberOf KiteConnect - * @instance - * @param {string} params Order params. - * @param {string} params.tradingsymbol Tradingsymbol (ISIN) of the fund. - * @param {string} params.transaction_type Transaction type (BUY or SELL). - * @param {string} [params.quantity] Quantity to SELL. Not applicable on BUYs. - * @param {string} [params.amount] Amount worth of units to purchase. Not applicable on SELLs - * @param {string} [params.tag] An optional tag to apply to an order to identify it (alphanumeric, max 20 chars) + * + * @date 07/06/2023 - 21:37:48 + * + * @param {PlaceMFOrderParams} params + * @returns {*} */ - self.placeMFOrder = function (params) { - return _post("mf.order.place", params); + placeMFOrder(params: PlaceMFOrderParams) { + return this._post('mf.order.place', params); } /** - * Cancel a mutual fund order. - * @method cancelMFOrder - * @memberOf KiteConnect - * @instance - * @param {string} order_id ID of the order. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} order_id + * @returns {*} */ - self.cancelMFOrder = function (order_id) { - return _delete("mf.order.cancel", { "order_id": order_id }) + cancelMFOrder(order_id: string | number) { + return this._delete('mf.order.cancel', { 'order_id': order_id }) } /** - * Get list of mutual fund SIPS. - * @method getMFSIPS - * @memberOf KiteConnect - * @instance - * @param {string} sip_id ID of the SIP. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {?(string | number)} [sip_id] + * @returns {*} */ - self.getMFSIPS = function (sip_id) { + getMFSIPS(sip_id?: string | number) { if (sip_id) { - return _get("mf.sip.info", {"sip_id": sip_id}, null, formatResponse); + return this._get('mf.sip.info', { 'sip_id': sip_id }, null, this.formatResponse); } else { - return _get("mf.sips", null, null, formatResponse); + return this._get('mf.sips', null, null, this.formatResponse); } } /** - * Place a mutual fund SIP. - * @method placeMFSIP - * @memberOf KiteConnect - * @instance - * @param {string} params Order params. - * @param {string} params.tradingsymbol Tradingsymbol (ISIN) of the fund. - * @param {string} params.amount Amount worth of units to purchase. - * @param {string} params.instalments Number of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled - * @param {string} params.frequency Order frequency. weekly, monthly, or quarterly. - * @param {string} [params.initial_amount] Amount worth of units to purchase before the SIP starts. - * @param {string} [params.instalment_day] If frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on. - * @param {string} [params.tag] An optional tag to apply to an order to identify it (alphanumeric, max 20 chars) - */ - self.placeMFSIP = function (params) { - return _post("mf.sip.place", params); + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Order} params + * @returns {*} + */ + placeMFSIP(params: Order) { + return this._post('mf.sip.place', params); } /** - * Modify a mutual fund SIP. - * @method modifyMFSIP - * @memberOf KiteConnect - * @instance - * @param {string} sip_id ID of the SIP. - * @param {string} params Order params. - * @param {string} [params.instalments] Number of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled - * @param {string} [params.frequency] Order frequency. weekly, monthly, or quarterly. - * @param {string} [params.instalment_day] If frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on. - * @param {string} [params.status] Pause or unpause an SIP (active or paused). + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} sip_id + * @param {Order} params + * @returns {*} */ - self.modifyMFSIP = function (sip_id, params) { + modifyMFSIP(sip_id: string | number, params: Order) { params.sip_id = sip_id; - return _put("mf.sip.modify", params); + return this._put('mf.sip.modify', params); } /** - * Cancel a mutual fund SIP. - * @method cancelMFSIP - * @memberOf KiteConnect - * @instance - * @param {string} sip_id ID of the SIP. + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} sip_id + * @returns {*} */ - self.cancelMFSIP = function (sip_id) { - return _delete("mf.sip.cancel", {"sip_id": sip_id}); + cancelMFSIP(sip_id: string | number) { + return this._delete('mf.sip.cancel', { 'sip_id': sip_id }); } /** - * Get list of mutual fund holdings. - * @method getMFHoldings - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getMFHoldings = function () { - return _get("mf.holdings"); + getMFHoldings() { + return this._get('mf.holdings'); } /** - * Get list of mutual fund instruments. - * @method getMFInstruments - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getMFInstruments = function () { - return _get("mf.instruments", null, null, transformMFInstrumentsResponse); + getMFInstruments() { + return this._get('mf.instruments', null, null, transformMFInstrumentsResponse); } /** - * Get GTTs list - * @method getGTTs - * @memberOf KiteConnect - * @instance + * + * @date 07/06/2023 - 21:37:48 + * + * @returns {*} */ - self.getGTTs = function () { - return _get("gtt.triggers", null, null, formatResponse); + getGTTs() { + return this._get('gtt.triggers', null, null, this.formatResponse); } /** - * Get list of order history. - * @method getGTT - * @memberOf KiteConnect - * @instance - * @param {string} trigger_id GTT trigger ID + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} trigger_id + * @returns {*} */ - self.getGTT = function (trigger_id) { - return _get("gtt.trigger_info", { "trigger_id": trigger_id }, null, formatResponse); - }; + getGTT(trigger_id: string | number) { + return this._get('gtt.trigger_info', { 'trigger_id': trigger_id }, null, this.formatResponse); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; - // Get API params from user defined GTT params. - self._getGTTPayload = function (params) { - if (params.trigger_type !== self.GTT_TYPE_OCO && params.trigger_type !== self.GTT_TYPE_SINGLE) { - throw new Error("Invalid `params.trigger_type`") + /** + * + * @date 07/06/2023 - 21:37:48 + * + * @param {Order} params + * @returns {{ condition: { exchange: ExchangeTypes; tradingsymbol: string; trigger_values: {}; last_price: any; }; orders: {}; }} + */ + _getGTTPayload(params: Order) { + if (params.trigger_type !== GTTStatusTypes.GTT_TYPE_OCO && params.trigger_type !== GTTStatusTypes.GTT_TYPE_SINGLE) { + throw new Error('Invalid `params.trigger_type`') } - if (params.trigger_type === self.GTT_TYPE_OCO && params.trigger_values.length !== 2) { - throw new Error("Invalid `trigger_values` for `OCO` order type") + if (params.trigger_type === GTTStatusTypes.GTT_TYPE_OCO && params.trigger_values?.length !== 2) { + throw new Error('Invalid `trigger_values` for `OCO` order type') } - if (params.trigger_type === self.GTT_TYPE_SINGLE && params.trigger_values.length !== 1) { - throw new Error("Invalid `trigger_values` for `single` order type") + if (params.trigger_type === GTTStatusTypes.GTT_TYPE_SINGLE && params.trigger_values?.length !== 1) { + throw new Error('Invalid `trigger_values` for `single` order type') } - let condition = { + const condition = { exchange: params.exchange, tradingsymbol: params.tradingsymbol, trigger_values: params.trigger_values, - last_price: parseFloat(params.last_price) + last_price: parseFloat(params.last_price as string) } let orders = [] as any[]; - for (let o of params.orders) { + for (let o of params.orders as Order[]) { orders.push({ transaction_type: o.transaction_type, order_type: o.order_type, product: o.product, - quantity: parseInt(o.quantity), - price: parseFloat(o.price), + quantity: parseInt(o.quantity as string), + price: parseFloat(o.price as string), exchange: params.exchange, tradingsymbol: params.tradingsymbol }) } - return { condition, orders } - }; + return { condition, orders }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Place GTT. - * @method placeGTT - * @memberOf KiteConnect - * @instance - * @param {string} params.trigger_type GTT type, its either `self.GTT_TYPE_OCO` or `self.GTT_TYPE_SINGLE`. - * @param {string} params.tradingsymbol Tradingsymbol of the instrument (ex. RELIANCE, INFY). - * @param {string} params.exchange Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). - * @param {number[]} params.trigger_values List of trigger values, number of items depends on trigger type. - * @param {number} params.last_price Price at which trigger is created. This is usually the last price of the instrument. - * @param {Object[]} params.orders List of orders. - * @param {string} params.orders.transaction_type Transaction type (BUY or SELL). - * @param {number} params.orders.quantity Order quantity - * @param {string} params.orders.product Product code (NRML, MIS, CNC). - * @param {string} params.orders.order_type Order type (NRML, SL, SL-M, MARKET). - * @param {number} params.orders.price Order price. - */ - self.placeGTT = function (params) { - let payload = self._getGTTPayload(params) - return _post("gtt.place", { + * + * @date 07/06/2023 - 21:37:48 + * + * @param {PlaceGTTParams} params + * @returns {*} + */ + placeGTT(params: PlaceGTTParams) { + const payload = this._getGTTPayload(params); + return this._post('gtt.place', { condition: JSON.stringify(payload.condition), orders: JSON.stringify(payload.orders), type: params.trigger_type }); - }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Place GTT. - * @method modifyGTT - * @memberOf KiteConnect - * @instance - * @param {string} trigger_id GTT trigger ID. - * @param {Object} params Modify params - * @param {string} params.trigger_type GTT type, its either `self.GTT_TYPE_OCO` or `self.GTT_TYPE_SINGLE`. - * @param {string} params.tradingsymbol Tradingsymbol of the instrument (ex. RELIANCE, INFY). - * @param {string} params.exchange Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX). - * @param {number[]} params.trigger_values List of trigger values, number of items depends on trigger type. - * @param {number} params.last_price Price at which trigger is created. This is usually the last price of the instrument. - * @param {Object[]} params.orders List of orders. - * @param {string} params.orders.transaction_type Transaction type (BUY or SELL). - * @param {number} params.orders.quantity Order quantity - * @param {string} params.orders.product Product code (NRML, MIS, CNC). - * @param {string} params.orders.order_type Order type (NRML, SL, SL-M, MARKET). - * @param {number} params.orders.price Order price. - */ - self.modifyGTT = function (trigger_id, params) { - let payload = self._getGTTPayload(params) - return _put("gtt.modify", { + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} trigger_id + * @param {ModifyGTTParams} params + * @returns {*} + */ + modifyGTT(trigger_id: string | number, params: ModifyGTTParams) { + const payload = this._getGTTPayload(params as Order); + return this._put('gtt.modify', { trigger_id: trigger_id, type: params.trigger_type, condition: JSON.stringify(payload.condition), orders: JSON.stringify(payload.orders) }); - }; + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Get list of order history. - * @method deleteGTT - * @memberOf KiteConnect - * @instance - * @param {string} trigger_id GTT ID + * + * @date 07/06/2023 - 21:37:48 + * + * @param {(string | number)} trigger_id + * @returns {*} */ - self.deleteGTT = function (trigger_id) { - return _delete("gtt.delete", { "trigger_id": trigger_id }, null, null); - }; + deleteGTT(trigger_id: string | number) { + return this._delete('gtt.delete', { 'trigger_id': trigger_id }, null, undefined); + }/** + * + * @date 07/06/2023 - 21:37:48 + */ + ; /** - * Validate postback data checksum - * @method validatePostback - * @memberOf KiteConnect - * @instance - * @param {object} postback_data Postback data received. Must be an json object with required keys order_id, checksum and order_timestamp - * @param {string} api_secret Api secret of the app - * @returns {bool} Return true if checksum matches else false - * @throws Throws an error if the @postback_data or @api_secret is invalid + * + * @date 07/06/2023 - 21:37:48 + * + * @param {AnyObject} postback_data + * @param {string} api_secret + * @returns {boolean} */ - self.validatePostback = function(postback_data, api_secret) { + validatePostback(postback_data: AnyObject, api_secret: string) { if (!postback_data || !postback_data.checksum || !postback_data.order_id || !postback_data.order_timestamp || !api_secret) { - throw new Error("Invalid postback data or api_secret"); + throw new Error('Invalid postback data or api_secret'); } const inputString = postback_data.order_id + postback_data.order_timestamp + api_secret; @@ -1200,219 +989,342 @@ regular). try { checksum = sha256(inputString).toString(); } catch (e) { - throw(e) + throw (e) } - if (postback_data.checksum === checksum) { - return true; - } else { - return false; - } + return postback_data.checksum === checksum; } - // Format generate session response - function formatGenerateSession(data) { - if (!data.data || typeof data.data !== "object") return data; + /** + * + * @date 07/06/2023 - 21:37:48 + * + * @private + * @param {string} route + * @param {?(AnyObject | null)} [params] + * @param {?(string | null)} [responseType] + * @param {?AxiosTransformer} [responseTransformer] + * @param {boolean} [isJSON=false] + * @returns {*} + */ + private _get(route: string, params?: AnyObject | null, responseType?: string | null, responseTransformer?: AxiosTransformer, isJSON = false) { + return this.request(route, 'GET', params || {}, responseType, responseTransformer, isJSON); + } - if (data.data.login_time) { - data.data.login_time = new Date(data.data.login_time); - } + /** + * + * @date 07/06/2023 - 21:37:48 + * + * @private + * @param {string} route + * @param {(AnyObject | null)} params + * @param {?(string | null)} [responseType] + * @param {?AxiosTransformer} [responseTransformer] + * @param {boolean} [isJSON=false] + * @param {(AnyObject | null)} [queryParams=null] + * @returns {*} + */ + private _post(route: string, params: AnyObject | null, responseType?: string | null, responseTransformer?: AxiosTransformer, isJSON = false, queryParams: AnyObject | null = null) { + return this.request(route, 'POST', params || {}, responseType, responseTransformer, isJSON, queryParams); + } - return data; + /** + * + * @date 07/06/2023 - 21:37:48 + * + * @private + * @param {string} route + * @param {(AnyObject | null)} params + * @param {?(string | null)} [responseType] + * @param {?AxiosTransformer} [responseTransformer] + * @param {boolean} [isJSON=false] + * @param {*} [queryParams=null] + * @returns {*} + */ + private _put(route: string, params: AnyObject | null, responseType?: string | null, responseTransformer?: AxiosTransformer, isJSON = false, queryParams = null) { + return this.request(route, 'PUT', params || {}, responseType, responseTransformer, isJSON, queryParams); } - function formatQuoteResponse(data) { - if (!data.data || typeof data.data !== "object") return data; + /** + * + * @date 07/06/2023 - 21:37:48 + * + * @private + * @param {string} route + * @param {(AnyObject | null)} params + * @param {?(string | null)} [responseType] + * @param {?AxiosTransformer} [responseTransformer] + * @param {boolean} [isJSON=false] + * @returns {*} + */ + private _delete(route: string, params: AnyObject | null, responseType?: string | null, responseTransformer?: AxiosTransformer, isJSON = false) { + return this.request(route, 'DELETE', params || {}, responseType, responseTransformer, isJSON); + } - for (const k in data.data) { - const item = data.data[k]; - for (const field of ["timestamp", "last_trade_time"]) { - if (item[field] && item[field].length === 19) { - item[field] = new Date(item[field]); + /** + * + * @date 07/06/2023 - 21:37:48 + * + * @private + * @param {string} route + * @param {Method} method + * @param {AnyObject} params + * @param {?(string | null)} [responseType] + * @param {?AxiosTransformer} [responseTransformer] + * @param {?boolean} [isJSON] + * @param {?(Record | null)} [queryParams] + * @returns {*} + */ + private request(route: string, method: Method, params: AnyObject, responseType?: string | null, responseTransformer?: AxiosTransformer, isJSON?: boolean, queryParams?: Record | null) { + // Check access token + if (!responseType) responseType = 'json'; + let uri = ROUTES[route]; + + // Replace variables in 'RESTful' URLs with corresponding params + if (uri.indexOf('{') !== -1) { + let k; + for (k in params) { + if (params.hasOwnProperty(k)) { + uri = uri.replace('{' + k + '}', params[k]); } } } - return data; - } - - // Format response ex. datetime string to date - function formatResponse(data) { - if (!data.data || typeof data.data !== "object") return data; - let list: any = []; - if (data.data instanceof Array) { - list = data.data; + let payload: null | string = null; + if (method === 'GET' || method === 'DELETE') { + queryParams = params; } else { - list = [data.data] + if (isJSON) { + // post JSON payload + payload = JSON.stringify(params); + } else { + // post url encoded payload + payload = querystring.stringify(params); + } } - const results: any[] = []; - const fields = ["order_timestamp", "exchange_timestamp", "created", "last_instalment", "fill_timestamp"]; - - for (const item of list) { - for (const field of fields) { - if (item[field] && item[field].length === 19) { - item[field] = new Date(item[field]); - } - } + const options: AxiosRequestConfig = { + method, + url: uri, + params: queryParams, + data: payload, + // Set auth header + headers: {} + }; - results.push(item); + // Send auth token + if (this.access_token) { + const authHeader = `${this.api_key}:${this.access_token}`; + options['headers']['Authorization'] = `token ${authHeader}`; } - if (data.data instanceof Array) { - data.data = results; + // Set request header content type + if (isJSON) { + options['headers']['Content-Type'] = 'application/json'; } else { - data.data = results[0]; + options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + // Set response transformer + if (responseTransformer) { + options.transformResponse = (axios.defaults.transformResponse as any).concat(responseTransformer); } - return data; + return this.requestInstance.request(options); } - function parseHistorical(jsonData) { + + /** + * + * @date 07/06/2023 - 21:37:48 + * + * @private + * @param {AnyObject} jsonData + * @returns {AnyObject} + */ + private parseHistorical(jsonData: AnyObject): AnyObject { // Return if its an error if (jsonData.error_type) return jsonData; - + const results = [] as any[]; - for(let i=0; i= maximumReconnectMaxRetries ? maximumReconnectMaxRetries : max_retry; + reconnect_max_delay = max_delay <= minimumReconnectMaxDelay ? minimumReconnectMaxDelay : max_delay; + }/** + * + * @date 07/06/2023 - 21:38:00 */ - this.autoReconnect = function (t, max_retry, max_delay) { - autoReconnect(t, max_retry, max_delay) - }; + ; /** - * Initiate a websocket connection - * @memberOf KiteTicker - * @method connect - * @instance + * + * @date 07/06/2023 - 21:38:00 */ - this.connect = function () { + connect() { // Skip if its already connected if (!ws) return; if (ws.readyState == ws.CONNECTING || ws.readyState == ws.OPEN) return; - const url = root + "?api_key=" + params.api_key + - "&access_token=" + params.access_token + "&uid=" + (new Date().getTime().toString()); + const url = this.root + '?api_key=' + this.api_key + + '&access_token=' + this.access_token + '&uid=' + (new Date().getTime().toString()); ws = new WebSocket(url, { headers: { - "X-Kite-Version": "3", - "User-Agent": utils.getUserAgent() + 'X-Kite-Version': '3', + 'User-Agent': utils.getUserAgent() } }); - ws.binaryType = "arraybuffer"; + ws.binaryType = 'arraybuffer'; ws.onopen = function () { // Reset last reconnect interval @@ -278,14 +376,14 @@ const KiteTicker = function (params) { // Reset current_reconnection_count attempt current_reconnection_count = 0 // Store current open connection url to check for auto re-connection. - if (!current_ws_url) current_ws_url = this.url + if (!current_ws_url) current_ws_url = this.url; // Trigger on connect event - trigger("connect"); + trigger('connect'); // If there isn't an incoming message in n seconds, assume disconnection. clearInterval(read_timer); last_read = new Date(); - read_timer = setInterval(function () { + read_timer = setInterval(() => { // @ts-ignore if ((new Date() - last_read) / 1000 >= read_timeout) { // reset current_ws_url incase current connection times out @@ -294,7 +392,7 @@ const KiteTicker = function (params) { current_ws_url = null; if (ws) ws.close(); clearInterval(read_timer); - triggerDisconnect(); + this.triggerDisconnect(); } }, read_timeout * 1000); }; @@ -303,10 +401,10 @@ const KiteTicker = function (params) { // Binary tick data. if (e.data instanceof ArrayBuffer) { // Trigger on message event when binary message is received - trigger("message", [e.data]); + trigger('message', [e.data]); if (e.data.byteLength > 2) { const d = parseBinary(e.data); - if (d) trigger("ticks", [d]); + if (d) trigger('ticks', [d]); } } else { parseTextMessage(e.data) @@ -317,382 +415,399 @@ const KiteTicker = function (params) { }; ws.onerror = function (e) { - trigger("error", [e]); + trigger('error', [e]); // Force close to avoid ghost connections if (this && this.readyState == this.OPEN) this.close(); }; ws.onclose = function (e) { - trigger("close", [e]); + trigger('close', [e]); // the ws id doesn't match the current global id, // meaning it's a ghost close event. just ignore. if (current_ws_url && (this.url != current_ws_url)) return; - triggerDisconnect(e); + this.triggerDisconnect(e); }; - }; + }/** + * + * @date 07/06/2023 - 21:38:00 + */ + ; /** - * @memberOf KiteTicker - * @method disconnect - * @instance + * + * @date 07/06/2023 - 21:38:00 */ - this.disconnect = function () { - if (ws && ws.readyState != ws.CLOSING && ws.readyState != ws.CLOSED) { - ws.close(); + attemptReconnection() { + // Try reconnecting only so many times. + if (current_reconnection_count > reconnect_max_tries) { + trigger('noreconnect'); + process.exit(1); } + + if (current_reconnection_count > 0) { + last_reconnect_interval = Math.pow(2, current_reconnection_count); + } else if (!last_reconnect_interval) { + last_reconnect_interval = 1; + } + + if (last_reconnect_interval > reconnect_max_delay) { + last_reconnect_interval = reconnect_max_delay; + } + + current_reconnection_count++; + + trigger('reconnect', [current_reconnection_count, last_reconnect_interval]); + + setTimeout(() => { + this.connect(); + }, last_reconnect_interval * 1000); } /** - * Check if the ticker is connected - * @memberOf KiteTicker - * @method connected - * @instance - * @returns {bool} + * + * @date 07/06/2023 - 21:38:00 + * + * @param {?WebSocket.CloseEvent} [e] */ - this.connected = function () { - if (ws && ws.readyState == ws.OPEN) { - return true; - } else { - return false; - } - }; + triggerDisconnect(e?: WebSocket.CloseEvent) { + ws = null; + trigger('disconnect', [e]); + if (auto_reconnect) this.attemptReconnection(); + } /** - * Register websocket event callbacks - * Available events - * ~~~~ - * connect - when connection is successfully established. - * ticks - when ticks are available (Arrays of `ticks` object as the first argument). - * disconnect - when socket connection is disconnected. Error is received as a first param. - * error - when socket connection is closed with error. Error is received as a first param. - * close - when socket connection is closed cleanly. - * reconnect - When reconnecting (current re-connection count and reconnect interval as arguments respectively). - * noreconnect - When re-connection fails after n number times. - * order_update - When order update (postback) is received for the connected user (Data object is received as first argument). - * message - when binary message is received from the server. - * ~~~~ + * + * @date 07/06/2023 - 21:37:59 * - * @memberOf KiteTicker - * @method on - * @instance + * @returns {boolean} + */ + connected() { + return (ws && ws.readyState == ws.OPEN); + } + + /** + * + * @date 07/06/2023 - 21:37:59 * - * @example - * ticker.on("ticks", callback); - * ticker.on("connect", callback); - * ticker.on("disconnect", callback); + * @param {string} e + * @param {Function} callback */ - this.on = function (e, callback) { + on(e: string, callback: Function) { if (triggers.hasOwnProperty(e)) { - triggers[e].push(callback); + (triggers as AnyObject)[e].push(callback); } - }; + }/** + * + * @date 07/06/2023 - 21:37:59 + */ + ; /** - * Subscribe to array of tokens - * @memberOf KiteTicker - * @method subscribe - * @instance - * @param {array} tokens Array of tokens to be subscribed + * + * @date 07/06/2023 - 21:37:59 * - * @example - * ticker.subscribe([738561]); + * @param {(string[] | number[])} tokens + * @returns {{}} */ - this.subscribe = function (tokens) { + subscribe(tokens: string[] | number[]) { if (tokens.length > 0) { - send({ "a": mSubscribe, "v": tokens }); + send({ 'a': mSubscribe, 'v': tokens }); } return tokens; - }; + }/** + * + * @date 07/06/2023 - 21:37:59 + */ + ; /** - * Unsubscribe to array of tokens - * @memberOf KiteTicker - * @method unsubscribe - * @instance - * @param {array} tokens Array of tokens to be subscribed + * + * @date 07/06/2023 - 21:37:59 * - * @example - * ticker.unsubscribe([738561]); + * @param {(string[] | number[])} tokens + * @returns {{}} */ - this.unsubscribe = function (tokens) { + unsubscribe(tokens: string[] | number[]) { if (tokens.length > 0) { - send({ "a": mUnSubscribe, "v": tokens }); + send({ 'a': mUnSubscribe, 'v': tokens }); } return tokens; - }; + }/** + * + * @date 07/06/2023 - 21:37:59 + */ + ; /** - * Set modes to array of tokens - * @memberOf KiteTicker - * @method setMode - * @instance - * @param {string} mode - mode to set - * @param {array} tokens Array of tokens to be subscribed + * + * @date 07/06/2023 - 21:37:59 * - * @example - * ticker.setMode(ticker.modeFull, [738561]); + * @param {string} mode + * @param {(string[] | number[])} tokens + * @returns {{}} */ - this.setMode = function (mode, tokens) { + setMode(mode: string, tokens: string[] | number[]) { if (tokens.length > 0) { - send({ "a": mSetMode, "v": [mode, tokens] }); + send({ 'a': mSetMode, 'v': [mode, tokens] }); } return tokens; - }; + }/** + * + * @date 07/06/2023 - 21:37:59 + */ + ; /** - * Parse received binary message - * @memberOf KiteTicker - * @method parseBinary - * @instance - * @param {ArrayBufferTypes} binpacks - tick buffer packets + * + * @date 07/06/2023 - 21:37:59 + * + * @param {ArrayBuffer} binpacks + * @returns {{}} */ - - this.parseBinary = function (binpacks) { + parseBinary(binpacks: ArrayBuffer) { return parseBinary(binpacks); } - function autoReconnect(t, max_retry, max_delay) { - auto_reconnect = (t == true); - // Set default values - max_retry = max_retry || defaultReconnectMaxRetries; - max_delay = max_delay || defaultReconnectMaxDelay; +} - // Set reconnect constraints - reconnect_max_tries = max_retry >= maximumReconnectMaxRetries ? maximumReconnectMaxRetries : max_retry; - reconnect_max_delay = max_delay <= minimumReconnectMaxDelay ? minimumReconnectMaxDelay : max_delay; - } - function triggerDisconnect(e?) { - ws = null; - trigger("disconnect", [e]); - if (auto_reconnect) attemptReconnection(); - } +// send a message via the socket +// automatically encodes json if possible +/** + * + * @date 07/06/2023 - 21:37:59 + * + * @param {(AnyObject | string)} message + */ +function send(message: AnyObject | string) { + if (!ws || ws.readyState != ws.OPEN) return; - // send a message via the socket - // automatically encodes json if possible - function send(message) { - if (!ws || ws.readyState != ws.OPEN) return; + try { + if (typeof (message) == 'object') { + message = JSON.stringify(message); + } + ws.send(message); + } catch (e) { ws.close(); }; +} - try { - if (typeof (message) == "object") { - message = JSON.stringify(message); - } - ws.send(message); - } catch (e) { ws.close(); }; +// trigger event callbacks +/** + * + * @date 07/06/2023 - 21:37:59 + * + * @param {string} e + * @param {?any[]} [args] + */ +function trigger(e: string, args?: any[]) { + if (!triggers[e]) return + for (let n = 0; n < triggers[e].length; n++) { + triggers[e][n].apply(triggers[e][n], args ? args : []); } +} - // trigger event callbacks - function trigger(e, args?) { - if (!triggers[e]) return - for (let n = 0; n < triggers[e].length; n++) { - triggers[e][n].apply(triggers[e][n], args ? args : []); - } +/** + * + * @date 07/06/2023 - 21:37:59 + * + * @param {(string | AnyObject)} data + */ +function parseTextMessage(data: string | AnyObject) { + try { + data = JSON.parse(data as string) + } catch (e) { + return } - function parseTextMessage(data) { - try { - data = JSON.parse(data) - } catch (e) { - return - } - - if (data.type === "order") { - trigger("order_update", [data.data]); - } + if ((data as AnyObject).type === 'order') { + trigger('order_update', [(data as AnyObject).data]); } +} - // parse received binary message. each message is a combination of multiple tick packets - // [2-bytes num packets][size1][tick1][size2][tick2] ... - function parseBinary(binpacks) { - const packets = splitPackets(binpacks), - ticks: any[] = []; +// parse received binary message. each message is a combination of multiple tick packets +// [2-bytes num packets][size1][tick1][size2][tick2] ... +/** + * + * @date 07/06/2023 - 21:37:59 + * + * @param {ArrayBuffer} binpacks + * @returns {{}} + */ +function parseBinary(binpacks: ArrayBuffer) { + const packets = splitPackets(binpacks), + ticks: any[] = []; + + for (let n = 0; n < packets.length; n++) { + const bin: any = packets[n], + instrument_token = buf2long(bin.slice(0, 4)), + segment = instrument_token & 0xff; - for (let n = 0; n < packets.length; n++) { - const bin: any = packets[n], - instrument_token = buf2long(bin.slice(0, 4)), - segment = instrument_token & 0xff; + let tradable = true; + if (segment === Indices) tradable = false; - let tradable = true; - if (segment === Indices) tradable = false; + // Add price divisor based on segment + let divisor = 100.0; + if (segment === NseCD) { + divisor = 10000000.0; - // Add price divisor based on segment - let divisor = 100.0; - if (segment === NseCD) { - divisor = 10000000.0; + } else if (segment == BseCD) { + divisor = 10000.0; + } - } else if (segment == BseCD) { - divisor = 10000.0; + // Parse LTP + if (bin.byteLength === 8) { + ticks.push({ + tradable: tradable, + mode: modeLTP, + instrument_token, + last_price: buf2long(bin.slice(4, 8)) / divisor + }); + // Parse indices quote and full mode + } else if (bin.byteLength === 28 || bin.byteLength === 32) { + let mode = modeQuote; + if (bin.byteLength === 32) mode = modeFull; + + const tick: AnyObject = { + tradable, + mode, + instrument_token, + last_price: buf2long(bin.slice(4, 8)) / divisor, + ohlc: { + high: buf2long(bin.slice(8, 12)) / divisor, + low: buf2long(bin.slice(12, 16)) / divisor, + open: buf2long(bin.slice(16, 20)) / divisor, + close: buf2long(bin.slice(20, 24)) / divisor + }, + change: buf2long(bin.slice(24, 28)) + }; + + // Compute the change price using close price and last price + if (tick.ohlc.close != 0) { + tick.change = (tick.last_price - tick.ohlc.close) * 100 / tick.ohlc.close; } - // Parse LTP - if (bin.byteLength === 8) { - ticks.push({ - tradable: tradable, - mode: modeLTP, - instrument_token: instrument_token, - last_price: buf2long(bin.slice(4, 8)) / divisor - }); - // Parse indices quote and full mode - } else if (bin.byteLength === 28 || bin.byteLength === 32) { - let mode = modeQuote; - if (bin.byteLength === 32) mode = modeFull; - - const tick: any = { - tradable: tradable, - mode: mode, - instrument_token: instrument_token, - last_price: buf2long(bin.slice(4, 8)) / divisor, - ohlc: { - high: buf2long(bin.slice(8, 12)) / divisor, - low: buf2long(bin.slice(12, 16)) / divisor, - open: buf2long(bin.slice(16, 20)) / divisor, - close: buf2long(bin.slice(20, 24)) / divisor - }, - change: buf2long(bin.slice(24, 28)) - }; + // Full mode with timestamp in seconds + if (bin.byteLength === 32) { + tick.exchange_timestamp = null; + const timestamp = buf2long(bin.slice(28, 32)); + if (timestamp) tick.exchange_timestamp = new Date(timestamp * 1000); + } - // Compute the change price using close price and last price - if (tick.ohlc.close != 0) { - tick.change = (tick.last_price - tick.ohlc.close) * 100 / tick.ohlc.close; + ticks.push(tick); + } else if (bin.byteLength === 44 || bin.byteLength === 184) { + let mode = modeQuote; + if (bin.byteLength === 184) mode = modeFull; + + const tick = { + tradable, + mode, + instrument_token, + last_price: buf2long(bin.slice(4, 8)) / divisor, + last_traded_quantity: buf2long(bin.slice(8, 12)), + average_traded_price: buf2long(bin.slice(12, 16)) / divisor, + volume_traded: buf2long(bin.slice(16, 20)), + total_buy_quantity: buf2long(bin.slice(20, 24)), + total_sell_quantity: buf2long(bin.slice(24, 28)), + ohlc: { + open: buf2long(bin.slice(28, 32)) / divisor, + high: buf2long(bin.slice(32, 36)) / divisor, + low: buf2long(bin.slice(36, 40)) / divisor, + close: buf2long(bin.slice(40, 44)) / divisor } + } as AnyObject; - // Full mode with timestamp in seconds - if (bin.byteLength === 32) { - tick.exchange_timestamp = null; - const timestamp = buf2long(bin.slice(28, 32)); - if (timestamp) tick.exchange_timestamp = new Date(timestamp * 1000); - } + // Compute the change price using close price and last price + if (tick.ohlc.close != 0) { + tick.change = (tick.last_price - tick.ohlc.close) * 100 / tick.ohlc.close; + } - ticks.push(tick); - } else if (bin.byteLength === 44 || bin.byteLength === 184) { - let mode = modeQuote; - if (bin.byteLength === 184) mode = modeFull; - - const tick = { - tradable: tradable, - mode: mode, - instrument_token: instrument_token, - last_price: buf2long(bin.slice(4, 8)) / divisor, - last_traded_quantity: buf2long(bin.slice(8, 12)), - average_traded_price: buf2long(bin.slice(12, 16)) / divisor, - volume_traded: buf2long(bin.slice(16, 20)), - total_buy_quantity: buf2long(bin.slice(20, 24)), - total_sell_quantity: buf2long(bin.slice(24, 28)), - ohlc: { - open: buf2long(bin.slice(28, 32)) / divisor, - high: buf2long(bin.slice(32, 36)) / divisor, - low: buf2long(bin.slice(36, 40)) / divisor, - close: buf2long(bin.slice(40, 44)) / divisor - } - } as any; - - // Compute the change price using close price and last price - if (tick.ohlc.close != 0) { - tick.change = (tick.last_price - tick.ohlc.close) * 100 / tick.ohlc.close; - } + // Parse full mode + if (bin.byteLength === 184) { + // Parse last trade time + tick.last_trade_time = null; + const last_trade_time = buf2long(bin.slice(44, 48)); + if (last_trade_time) tick.last_trade_time = new Date(last_trade_time * 1000); + + // Parse timestamp + tick.exchange_timestamp = null; + const timestamp = buf2long(bin.slice(60, 64)); + if (timestamp) tick.exchange_timestamp = new Date(timestamp * 1000); + + // Parse OI + tick.oi = buf2long(bin.slice(48, 52)); + tick.oi_day_high = buf2long(bin.slice(52, 56)); + tick.oi_day_low = buf2long(bin.slice(56, 60)); + tick.depth = { + buy: [], + sell: [] + }; - // Parse full mode - if (bin.byteLength === 184) { - // Parse last trade time - tick.last_trade_time = null; - const last_trade_time = buf2long(bin.slice(44, 48)); - if (last_trade_time) tick.last_trade_time = new Date(last_trade_time * 1000); - - // Parse timestamp - tick.exchange_timestamp = null; - const timestamp = buf2long(bin.slice(60, 64)); - if (timestamp) tick.exchange_timestamp = new Date(timestamp * 1000); - - // Parse OI - tick.oi = buf2long(bin.slice(48, 52)); - tick.oi_day_high = buf2long(bin.slice(52, 56)); - tick.oi_day_low = buf2long(bin.slice(56, 60)); - tick.depth = { - buy: [], - sell: [] - }; - - let s = 0, depth = bin.slice(64, 184); - for (let i = 0; i < 10; i++) { - s = i * 12; - tick.depth[i < 5 ? "buy" : "sell"].push({ - quantity: buf2long(depth.slice(s, s + 4)), - price: buf2long(depth.slice(s + 4, s + 8)) / divisor, - orders: buf2long(depth.slice(s + 8, s + 10)) - }); - } + let s = 0, depth = bin.slice(64, 184); + for (let i = 0; i < 10; i++) { + s = i * 12; + tick.depth[i < 5 ? 'buy' : 'sell'].push({ + quantity: buf2long(depth.slice(s, s + 4)), + price: buf2long(depth.slice(s + 4, s + 8)) / divisor, + orders: buf2long(depth.slice(s + 8, s + 10)) + }); } - - ticks.push(tick); } - } - return ticks; - } - - // split one long binary message into individual tick packets - function splitPackets(bin) { - // number of packets - let num = buf2long(bin.slice(0, 2)), - j = 2, - packets: any[] = []; - - for (let i = 0; i < num; i++) { - // first two bytes is the packet length - const size = buf2long(bin.slice(j, j + 2)), - packet = bin.slice(j + 2, j + 2 + size); - - packets.push(packet); - - j += 2 + size; + ticks.push(tick); } - - return packets; } - function attemptReconnection() { - // Try reconnecting only so many times. - if (current_reconnection_count > reconnect_max_tries) { - trigger("noreconnect"); - process.exit(1); - } - - if (current_reconnection_count > 0) { - last_reconnect_interval = Math.pow(2, current_reconnection_count); - } else if (!last_reconnect_interval) { - last_reconnect_interval = 1; - } + return ticks; +} - if (last_reconnect_interval > reconnect_max_delay) { - last_reconnect_interval = reconnect_max_delay; - } +// split one long binary message into individual tick packets +/** + * + * @date 07/06/2023 - 21:37:59 + * + * @param {ArrayBuffer} bin + * @returns {{}} + */ +function splitPackets(bin: ArrayBuffer) { + // number of packets + let num = buf2long(bin.slice(0, 2)), + j = 2, + packets: any[] = []; - current_reconnection_count++; + for (let i = 0; i < num; i++) { + // first two bytes is the packet length + const size = buf2long(bin.slice(j, j + 2)), + packet = bin.slice(j + 2, j + 2 + size); - trigger("reconnect", [current_reconnection_count, last_reconnect_interval]); + packets.push(packet); - setTimeout(function () { - self.connect(); - }, last_reconnect_interval * 1000); + j += 2 + size; } - // Big endian byte array to long. - function buf2long(buf) { - let b = new Uint8Array(buf), - val = 0, - len = b.length; + return packets; +} - for (let i = 0, j = len - 1; i < len; i++, j--) { - val += b[j] << (i * 8); - } +// Big endian byte array to long. +/** + * + * @date 07/06/2023 - 21:37:59 + * + * @param {ArrayBuffer} buf + * @returns {number} + */ +function buf2long(buf: ArrayBuffer) { + let b = new Uint8Array(buf), + val = 0, + len = b.length; - return val; + for (let i = 0, j = len - 1; i < len; i++, j--) { + val += b[j] << (i * 8); } - const self = this; -}; + + return val; +} export default KiteTicker; diff --git a/lib/utils.ts b/lib/utils.ts index 572ca17..66616d5 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -1,11 +1,23 @@ import packageInfo from '../package.json'; +/** + * + * @date 07/06/2023 - 21:38:03 + * + * @returns {*} + */ function getPackageInfo() { return packageInfo; } +/** + * + * @date 07/06/2023 - 21:38:03 + * + * @returns {string} + */ function getUserAgent() { - return "kiteconnectjs/" + packageInfo.version; + return 'kiteconnectjs/' + packageInfo.version; } export default { diff --git a/package-lock.json b/package-lock.json index 7406c0e..03d5407 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,14 +15,21 @@ "mocha": "^10.0.0", "nock": "^13.2.4", "papaparse": "^5.3.1", + "querystring": "^0.2.1", + "rimraf": "^3.0.2", + "taffydb": "^2.7.3", + "typedoc": "^0.24.8", "ws": "^6.2.2" }, "devDependencies": { + "@types/chai": "^4.3.4", "@types/crypto-js": "^4.1.1", + "@types/mocha": "^10.0.1", "@types/node": "^18.11.18", "@types/papaparse": "^5.3.5", + "@types/ws": "^8.5.4", "eslint": "^8.30.0", - "jsdoc": "^3.4.0", + "jsdoc": "^4.0.2", "minami": "^1.1.1", "typescript": "^4.9.4" }, @@ -31,9 +38,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.12.16", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.12.16.tgz", - "integrity": "sha512-c/+u9cqV6F0+4Hpq01jnJO+GLp2DdT63ppz9Xa+6cHaajM9VFzK/iDXiKK65YtpeVwu+ctfS6iqlMqRgQRzeCw==", + "version": "7.21.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.21.4.tgz", + "integrity": "sha512-alVJj7k7zIxqBZ7BTRhz0IqJFxW1VJbm6N8JbcYhQ186df9ZBPbZBmWSqAMXwHGsCJdYks7z/voa3ibiS5bCIw==", "dev": true, "bin": { "parser": "bin/babel-parser.js" @@ -142,6 +149,18 @@ "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", "dev": true }, + "node_modules/@jsdoc/salty": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/@jsdoc/salty/-/salty-0.2.5.tgz", + "integrity": "sha512-TfRP53RqunNe2HBobVBJ0VLhK1HbfvBYeTC1ahnN64PWvyYyGebmMiPkuwvD9fpw2ZbkoPb8Q7mwy0aR8Z9rvw==", + "dev": true, + "dependencies": { + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v12.0.0" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -177,12 +196,46 @@ "node": ">= 8" } }, + "node_modules/@types/chai": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.4.tgz", + "integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==", + "dev": true + }, "node_modules/@types/crypto-js": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.1.1.tgz", "integrity": "sha512-BG7fQKZ689HIoc5h+6D2Dgq1fABRa0RbBWKBd9SP/MVRVXROflpm5fhwyATX5duFmbStzyzyycPB8qUYKDH3NA==", "dev": true }, + "node_modules/@types/linkify-it": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-3.0.2.tgz", + "integrity": "sha512-HZQYqbiFVWufzCwexrvh694SOim8z2d+xJl5UNamcvQFejLY/2YUtzXHYi3cHdI7PMlS8ejH2slRAOJQ32aNbA==", + "dev": true + }, + "node_modules/@types/markdown-it": { + "version": "12.2.3", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-12.2.3.tgz", + "integrity": "sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ==", + "dev": true, + "dependencies": { + "@types/linkify-it": "*", + "@types/mdurl": "*" + } + }, + "node_modules/@types/mdurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-1.0.2.tgz", + "integrity": "sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA==", + "dev": true + }, + "node_modules/@types/mocha": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.1.tgz", + "integrity": "sha512-/fvYntiO1GeICvqbQ3doGDIP97vWmvFt83GKguJ6prmQM2iXZfFcq6YE8KteFyRtX2/h5Hf91BYvPodJKFYv5Q==", + "dev": true + }, "node_modules/@types/node": { "version": "18.11.18", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", @@ -198,6 +251,15 @@ "@types/node": "*" } }, + "node_modules/@types/ws": { + "version": "8.5.4", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", + "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@ungap/promise-all-settled": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz", @@ -256,6 +318,11 @@ "node": ">=8" } }, + "node_modules/ansi-sequence-parser": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/ansi-sequence-parser/-/ansi-sequence-parser-1.1.0.tgz", + "integrity": "sha512-lEm8mt52to2fT8GhciPCGeCXACSz2UwIN4X2e2LJSnZ5uAbn2/dsYdOmUXq0AtWS5cpAupysIneExOgH0Vd2TQ==" + }, "node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -283,13 +350,9 @@ } }, "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "dependencies": { - "sprintf-js": "~1.0.2" - } + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" }, "node_modules/assertion-error": { "version": "1.1.0", @@ -376,15 +439,15 @@ } }, "node_modules/catharsis": { - "version": "0.8.11", - "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.11.tgz", - "integrity": "sha512-a+xUyMV7hD1BrDQA/3iPV7oc+6W26BgVJO05PGEoatMyIuPScQKsde6i3YorWX1qs+AZjnJ18NqdKoCtKiNh1g==", + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.9.0.tgz", + "integrity": "sha512-prMTQVpcns/tzFgFVkVp6ak6RykZyWb3gu8ckUpd6YkTlacOd3DXGJjIpD4Q6zJirizvaiAjSSHlOsA+6sNh2A==", "dev": true, "dependencies": { - "lodash": "^4.17.14" + "lodash": "^4.17.15" }, "engines": { - "node": ">= 8" + "node": ">= 10" } }, "node_modules/chai": { @@ -589,10 +652,13 @@ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "node_modules/entities": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz", - "integrity": "sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ==", - "dev": true + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz", + "integrity": "sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==", + "dev": true, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } }, "node_modules/escalade": { "version": "3.1.1", @@ -1032,9 +1098,9 @@ } }, "node_modules/graceful-fs": { - "version": "4.2.6", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", - "integrity": "sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ==", + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", "dev": true }, "node_modules/grapheme-splitter": { @@ -1208,46 +1274,42 @@ "js-yaml": "bin/js-yaml.js" } }, - "node_modules/js-yaml/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" - }, "node_modules/js2xmlparser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.1.tgz", - "integrity": "sha512-KrPTolcw6RocpYjdC7pL7v62e55q7qOMHvLX1UCLc5AAS8qeJ6nukarEJAF2KL2PZxlbGueEbINqZR2bDe/gUw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.2.tgz", + "integrity": "sha512-6n4D8gLlLf1n5mNLQPRfViYzu9RATblzPEtm1SthMX1Pjao0r9YI9nw7ZIfRxQMERS87mcswrg+r/OYrPRX6jA==", "dev": true, "dependencies": { - "xmlcreate": "^2.0.3" + "xmlcreate": "^2.0.4" } }, "node_modules/jsdoc": { - "version": "3.6.6", - "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.6.tgz", - "integrity": "sha512-znR99e1BHeyEkSvgDDpX0sTiTu+8aQyDl9DawrkOGZTTW8hv0deIFXx87114zJ7gRaDZKVQD/4tr1ifmJp9xhQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-4.0.2.tgz", + "integrity": "sha512-e8cIg2z62InH7azBBi3EsSEqrKx+nUtAS5bBcYTSpZFA+vhNPyhv8PTFZ0WsjOPDj04/dOLlm08EDcQJDqaGQg==", "dev": true, "dependencies": { - "@babel/parser": "^7.9.4", + "@babel/parser": "^7.20.15", + "@jsdoc/salty": "^0.2.1", + "@types/markdown-it": "^12.2.3", "bluebird": "^3.7.2", - "catharsis": "^0.8.11", + "catharsis": "^0.9.0", "escape-string-regexp": "^2.0.0", - "js2xmlparser": "^4.0.1", + "js2xmlparser": "^4.0.2", "klaw": "^3.0.0", - "markdown-it": "^10.0.0", - "markdown-it-anchor": "^5.2.7", - "marked": "^0.8.2", + "markdown-it": "^12.3.2", + "markdown-it-anchor": "^8.4.1", + "marked": "^4.0.10", "mkdirp": "^1.0.4", "requizzle": "^0.2.3", "strip-json-comments": "^3.1.0", - "taffydb": "2.6.2", - "underscore": "~1.10.2" + "underscore": "~1.13.2" }, "bin": { "jsdoc": "jsdoc.js" }, "engines": { - "node": ">=8.15.0" + "node": ">=12.0.0" } }, "node_modules/json-schema-traverse": { @@ -1267,6 +1329,11 @@ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" }, + "node_modules/jsonc-parser": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", + "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==" + }, "node_modules/klaw": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", @@ -1290,9 +1357,9 @@ } }, "node_modules/linkify-it": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-2.2.0.tgz", - "integrity": "sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", + "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", "dev": true, "dependencies": { "uc.micro": "^1.0.1" @@ -1313,9 +1380,9 @@ } }, "node_modules/lodash": { - "version": "4.17.20", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", - "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==", + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, "node_modules/lodash.merge": { @@ -1352,15 +1419,20 @@ "get-func-name": "^2.0.0" } }, + "node_modules/lunr": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", + "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==" + }, "node_modules/markdown-it": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-10.0.0.tgz", - "integrity": "sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg==", + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", + "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", "dev": true, "dependencies": { - "argparse": "^1.0.7", - "entities": "~2.0.0", - "linkify-it": "^2.0.0", + "argparse": "^2.0.1", + "entities": "~2.1.0", + "linkify-it": "^3.0.1", "mdurl": "^1.0.1", "uc.micro": "^1.0.5" }, @@ -1369,30 +1441,30 @@ } }, "node_modules/markdown-it-anchor": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-5.3.0.tgz", - "integrity": "sha512-/V1MnLL/rgJ3jkMWo84UR+K+jF1cxNG1a+KwqeXqTIJ+jtA8aWSHuigx8lTzauiIjBDbwF3NcWQMotd0Dm39jA==", + "version": "8.6.7", + "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-8.6.7.tgz", + "integrity": "sha512-FlCHFwNnutLgVTflOYHPW2pPcl2AACqVzExlkGQNsi4CJgqOHN7YTgDd4LuhgN1BFO3TS0vLAruV1Td6dwWPJA==", "dev": true, "peerDependencies": { + "@types/markdown-it": "*", "markdown-it": "*" } }, "node_modules/marked": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/marked/-/marked-0.8.2.tgz", - "integrity": "sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw==", - "dev": true, + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz", + "integrity": "sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==", "bin": { - "marked": "bin/marked" + "marked": "bin/marked.js" }, "engines": { - "node": ">= 8.16.2" + "node": ">= 12" } }, "node_modules/mdurl": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", - "integrity": "sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==", + "integrity": "sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==", "dev": true }, "node_modules/minami": { @@ -1659,6 +1731,15 @@ "node": ">=6" } }, + "node_modules/querystring": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.1.tgz", + "integrity": "sha512-wkvS7mL/JMugcup3/rMitHmd9ecIGd2lhFhK9N3UUQ450h66d1r3Y9nvXzQAW1Lq+wyx61k/1pfKS5KuKiyEbg==", + "deprecated": "The querystring API is considered Legacy. new code should use the URLSearchParams API instead.", + "engines": { + "node": ">=0.4.x" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -1750,7 +1831,6 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "dev": true, "dependencies": { "glob": "^7.1.3" }, @@ -1832,11 +1912,16 @@ "node": ">=8" } }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true + "node_modules/shiki": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-0.14.2.tgz", + "integrity": "sha512-ltSZlSLOuSY0M0Y75KA+ieRaZ0Trf5Wl3gutE7jzLuIcWxLp5i/uEnLoQWNvgKXQ5OMpGkJnVMRLAuzjc0LJ2A==", + "dependencies": { + "ansi-sequence-parser": "^1.1.0", + "jsonc-parser": "^3.2.0", + "vscode-oniguruma": "^1.7.0", + "vscode-textmate": "^8.0.0" + } }, "node_modules/string-width": { "version": "4.2.3", @@ -1888,10 +1973,9 @@ } }, "node_modules/taffydb": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz", - "integrity": "sha1-fLy2S1oUG2ou/CxdLGe04VCyomg= sha512-y3JaeRSplks6NYQuCOj3ZFMO3j60rTwbuKCvZxsAraGYH2epusatvZ0baZYA01WsGqJBq/Dl6vOrMUJqyMj8kA==", - "dev": true + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.7.3.tgz", + "integrity": "sha512-GQ3gtYFSOAxSMN/apGtDKKkbJf+8izz5YfbGqIsUc7AMiQOapARZ76dhilRY2h39cynYxBFdafQo5HUL5vgkrg==" }, "node_modules/text-table": { "version": "0.2.0", @@ -1942,11 +2026,44 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/typedoc": { + "version": "0.24.8", + "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.24.8.tgz", + "integrity": "sha512-ahJ6Cpcvxwaxfu4KtjA8qZNqS43wYt6JL27wYiIgl1vd38WW/KWX11YuAeZhuz9v+ttrutSsgK+XO1CjL1kA3w==", + "dependencies": { + "lunr": "^2.3.9", + "marked": "^4.3.0", + "minimatch": "^9.0.0", + "shiki": "^0.14.1" + }, + "bin": { + "typedoc": "bin/typedoc" + }, + "engines": { + "node": ">= 14.14" + }, + "peerDependencies": { + "typescript": "4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x" + } + }, + "node_modules/typedoc/node_modules/minimatch": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.1.tgz", + "integrity": "sha512-0jWhJpD/MdhPXwPuiRkCbfYfSKp2qnn2eOc279qI7f+osl/l+prKSrvhg157zSYvx/1nmgn2NqdT6k2Z7zSH9w==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/typescript": { "version": "4.9.4", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz", "integrity": "sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==", - "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -1962,9 +2079,9 @@ "dev": true }, "node_modules/underscore": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.10.2.tgz", - "integrity": "sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg==", + "version": "1.13.6", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.6.tgz", + "integrity": "sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A==", "dev": true }, "node_modules/uri-js": { @@ -1976,6 +2093,16 @@ "punycode": "^2.1.0" } }, + "node_modules/vscode-oniguruma": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-1.7.0.tgz", + "integrity": "sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA==" + }, + "node_modules/vscode-textmate": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-8.0.0.tgz", + "integrity": "sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg==" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -2035,9 +2162,9 @@ } }, "node_modules/xmlcreate": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.3.tgz", - "integrity": "sha512-HgS+X6zAztGa9zIK3Y3LXuJes33Lz9x+YyTxgrkIdabu2vqcGOWwdfCpf1hWLRrd553wd4QCDf6BBO6FfdsRiQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.4.tgz", + "integrity": "sha512-nquOebG4sngPmGPICTS5EnxqhKbCmz5Ox5hsszI2T6U5qdrJizBc+0ilYSEjTSzU0yZcmvppztXe/5Al5fUwdg==", "dev": true }, "node_modules/y18n": { diff --git a/package.json b/package.json index 3c67180..e06a9fe 100644 --- a/package.json +++ b/package.json @@ -2,12 +2,14 @@ "name": "kiteconnect", "version": "4.1.0", "description": "The official JS client library for the Kite Connect trading APIs", - "main": "./dist/", + "main": "./dist", "types": "./types/index.d.ts", "scripts": { - "generate-docs": "node_modules/.bin/jsdoc --configure .jsdoc.json --verbose", - "build": "tsc", - "test": "tsc && mocha" + "generate-docs": "typedoc --entryPoints \"lib/**/*.ts\" \"interfaces/**/*.ts\" --out ./docs", + "build": "tsc --project tsconfig.json", + "build-test": "tsc --project test/tsconfig.json", + "eslint:fix": "eslint", + "test": "npm run build && npm run build-test && mocha --allowJs test/**/*.js && rimraf **/*.js" }, "repository": { "type": "git", @@ -36,14 +38,21 @@ "mocha": "^10.0.0", "nock": "^13.2.4", "papaparse": "^5.3.1", + "querystring": "^0.2.1", + "rimraf": "^3.0.2", + "taffydb": "^2.7.3", + "typedoc": "^0.24.8", "ws": "^6.2.2" }, "devDependencies": { + "@types/chai": "^4.3.4", "@types/crypto-js": "^4.1.1", + "@types/mocha": "^10.0.1", "@types/node": "^18.11.18", "@types/papaparse": "^5.3.5", + "@types/ws": "^8.5.4", "eslint": "^8.30.0", - "jsdoc": "^3.4.0", + "jsdoc": "^4.0.2", "minami": "^1.1.1", "typescript": "^4.9.4" }, diff --git a/test/test.js b/test/test.js deleted file mode 100644 index dd958b1..0000000 --- a/test/test.js +++ /dev/null @@ -1,675 +0,0 @@ -"use strict"; - -const nock = require("nock"); -const expect = require("chai").expect; -const path = require("path"); -const fs = require("fs"); -const KiteConnect = require("../dist/connect.js").default; - -const mockDir = "./kiteconnect-mocks"; - -// run testsuite -testSuite(); - -function parseJson(fileName){ - // read and parse mock json file - var rawdata = fs.readFileSync(path.join(__dirname, mockDir, fileName)); - var mockData= JSON.parse(rawdata); - return mockData; -} - -function testSuite(){ - - var kc = new KiteConnect({"api_key":"your api_key"}); - - // Chaining the mock requests - nock(kc.root) - // getProfile - .get("/user/profile") - .reply(200, parseJson("profile.json")) - - // getMargins - .get("/user/margins") - .reply(200, parseJson("margins.json")) - - // getMargins(segment) - .get("/user/margins/test") - .query({ segment: "test" }) - .reply(200, parseJson("margins_equity.json")) - - // placeOrder - .post("/orders/test") - .reply(200, parseJson("order_response.json")) - - // modifyOrder - .put("/orders/test/100") - .reply(200, parseJson("order_modify.json")) - - // cancelOrder - .delete("/orders/test/100") - .query({ variety: "test", order_id: 100 }) - .reply(200, parseJson("order_cancel.json")) - - // getOrders - .get("/orders") - .reply(200, parseJson("orders.json")) - - // getOrderHistory - .get("/orders/100") - .query({ order_id: "100" }) - .reply(200, parseJson("order_info.json")) - - // getTrades - .get("/trades") - .reply(200, parseJson("trades.json")) - - // getOrderTrades - .get("/orders/100/trades") - .query({ order_id: 100 }) - .reply(200, parseJson("order_trades.json")) - - // getHoldings - .get("/portfolio/holdings") - .reply(200, parseJson("holdings.json")) - - // getHoldings - .get("/portfolio/holdings/auctions") - .reply(200, parseJson("auctions_list.json")) - - // getPositions - .get("/portfolio/positions") - .reply(200, parseJson("positions.json")) - - // convertPosition - .put("/portfolio/positions") - .reply(200, parseJson("convert_position.json")) - - // placeMFOrder - .post("/mf/orders") - .reply(200, parseJson("mf_order_response.json")) - - // cancelMFOrder - .delete("/mf/orders/100") - .query({ order_id: 100 }) - .reply(200, parseJson("mf_order_cancel.json")) - - // getMFOrders - .get("/mf/orders") - .reply(200, parseJson("mf_orders.json")) - - // getMFOrders(order_id) - .get("/mf/orders/100") - .query({ order_id: 100 }) - .reply(200, parseJson("mf_orders_info.json")) - - // placeMFSIP - .post("/mf/sips") - .reply(200, parseJson("mf_sip_place.json")) - - // modifyMFSIP - .put("/mf/sips/100") - .reply(200, parseJson("mf_sip_modify.json")) - - // cancelMFSIP - .delete("/mf/sips/100") - .query({ sip_id: 100 }) - .reply(200, parseJson("mf_sip_cancel.json")) - - // getMFSIPS - .get("/mf/sips") - .reply(200, parseJson("mf_sips.json")) - - // getMFSIPS(sip_id) - .get("/mf/sips/100") - .query({ sip_id: 100 }) - .reply(200, parseJson("mf_sip_info.json")) - - // getMFHoldings - .get("/mf/holdings") - .reply(200, parseJson("mf_holdings.json")) - - // getHistoricalData - .get("/instruments/historical/100/minute") - .query({ instrument_token: "100" , interval: "minute", - from: "2022-06-01 09:15:00", to: "2022-06-01 15:30:00", - continuous: 0, oi:0}) - .reply(200, parseJson("historical_minute.json")) - - // getQuote - .get("/quote") - .query({ i:"NSE:INFY"}) - .reply(200, parseJson("quote.json")) - - // getLTP - .get("/quote/ltp") - .query({ i: "NSE:INFY" }) - .reply(200, parseJson("ltp.json")) - - // getOHLC - .get("/quote/ohlc") - .query({ i:"NSE:INFY"}) - .reply(200, parseJson("quote.json")) - - // placeGTT - .post("/gtt/triggers") - .reply(200, parseJson("gtt_place_order.json")) - - // modifyGTT - .put("/gtt/triggers/100") - .reply(200, parseJson("gtt_modify_order.json")) - - // deleteGTT - .delete("/gtt/triggers/100") - .query({ trigger_id: 100 }) - .reply(200, parseJson("gtt_delete_order.json")) - - // getGTTs - .get("/gtt/triggers") - .reply(200, parseJson("gtt_get_orders.json")) - - // getGTT(trigger_id) - .get("/gtt/triggers/100") - .query({ trigger_id:100}) - .reply(200, parseJson("gtt_get_order.json")) - - // orderMargins - .post("/margins/orders") - .query({ mode: null }) - .reply(200, parseJson("order_margins.json")) - - - // fetch user profile detail - describe("getProfile", function() { - it("fetch user profile detail", (done) => { - kc.getProfile() - .then(function(response) { - expect(response).to.have.property("user_id"); - expect(response).to.have.property("user_name"); - return done(); - }).catch(done); - }) - }); - - // fetch user fund detail - describe("getMargins", function() { - it("fetch equity and commodity segment funds", (done) => { - kc.getMargins() - .then(function(response) { - expect(response).to.have.property("equity"); - expect(response).to.have.property("commodity"); - return done(); - }).catch(done); - }) - it("fetch equity specific segment funds", (done) => { - kc.getMargins("test") - .then(function(response) { - expect(response).to.have.property("enabled"); - return done(); - }).catch(done); - }) - }); - - // Order APIs - // Place market and limit order - describe("placeOrder", function() { - it("Place market order", (done) => { - kc.placeOrder("test", { - "exchange": "NSE", - "tradingsymbol": "SBIN", - "transaction_type": "BUY", - "quantity": 1, - "product": "MIS", - "order_type": "MARKET"}) - .then(function(response) { - expect(response).to.have.property("order_id"); - return done(); - }).catch(done); - }) - }); - - // modify open pending order - describe("modifyOrder", function() { - it("Modify an open order", (done) => { - kc.modifyOrder("test", 100,{ - "price":10}) - .then(function(response) { - expect(response).to.have.property("order_id"); - return done(); - }).catch(done); - }) - }); - - // cancel an open pending order - describe("cancelOrder", function() { - it("cancel an open pending order", (done) => { - kc.cancelOrder("test", 100) - .then(function(response) { - expect(response).to.have.property("order_id"); - return done(); - }).catch(done); - }) - }); - - // Retrieve complete orderbook - describe("getOrders", function() { - it("Retrieve the list of all orders under orderbook", (done) => { - kc.getOrders() - .then(function(response) { - expect(response).to.be.an("array"); - expect(response).to.have.nested.property("[0].order_id"); - expect(response).to.have.nested.property("[0].status"); - expect(response).to.have.nested.property("[0].tradingsymbol"); - return done(); - }).catch(done); - }) - }); - - // Retrieve the history of a given order - describe("getOrderHistory", function() { - it("Retrieve the history of a given order", (done) => { - kc.getOrderHistory(100) - .then(function(response) { - expect(response).to.have.nested.property("[0].order_id"); - expect(response).to.have.nested.property("[0].status"); - return done(); - }).catch(done); - }) - }); - - // Retrieve the list of all executed trades - describe("getTrades", function() { - it("Retrieve the list of all executed trades for the day", (done) => { - kc.getTrades() - .then(function(response) { - expect(response).to.be.an("array"); - expect(response).to.have.nested.property("[0].order_id"); - expect(response).to.have.nested.property("[0].exchange_timestamp"); - return done(); - }).catch(done); - }) - }); - - // Retrieve all the trades generated by an order - describe("getOrderTrades", function() { - it("Retrieve all the trades generated by an order", (done) => { - kc.getOrderTrades(100) - .then(function(response) { - expect(response).to.be.an("array"); - return done(); - }).catch(done); - }) - }); - - // Portfolio APIs - // Retrieve the list of equity holdings - describe("getHoldings", function() { - it("Retrieve the list of equity holdings", (done) => { - kc.getHoldings() - .then(function(response) { - expect(response).to.be.an("array"); - expect(response).to.have.nested.property("[0].tradingsymbol"); - expect(response).to.have.nested.property("[0].average_price"); - return done(); - }).catch(done); - }) - }); - - // Retrieves list of available instruments for a auction session - describe("getAuctionInstruments", function() { - it("Retrieves list of available instruments for a auction session", (done) => { - kc.getAuctionInstruments() - .then(function(response) { - expect(response).to.be.an("array"); - expect(response).to.have.nested.property("[0].auction_number"); - expect(response).to.have.nested.property("[0].instrument_token"); - expect(response).to.have.nested.property("[0].tradingsymbol"); - return done(); - }).catch(done); - }) - }); - - // Retrieve the list of positions - describe("getPositions", function() { - it("Retrieve the list of positions", (done) => { - kc.getPositions() - .then(function(response) { - expect(response).to.have.property("net"); - expect(response).to.have.property("day"); - return done(); - }).catch(done); - }) - }); - - // convert existing position - describe("convertPosition", function() { - it("convert existing position", (done) => { - kc.convertPosition ({ - "tradingsymbol": "SBIN", - "exchange":"NSE", - "transaction_type":"BUY", - "position_type":"day", - "quantity":1, - "old_product":"CNC", - "new_product":"MIS" - }) - .then(function(response) { - expect(response).to.equal(true); - return done(); - }).catch(done); - }) - }); - - // MF APIs - // Place MF Order - describe("placeMFOrder", function() { - it("Place MF order", (done) => { - kc.placeMFOrder({ - "tradingsymbol": "INF174K01LS2", - "transaction_type": "BUY", - "amount" : 1000}) - .then(function(response) { - expect(response).to.have.property("order_id"); - return done(); - }).catch(done); - }) - }); - - // cancel an open pending MF order - describe("cancelMFOrder", function() { - it("cancel an open pending MF order", (done) => { - kc.cancelMFOrder(100) - .then(function(response) { - expect(response).to.have.property("order_id"); - return done(); - }).catch(done); - }) - }); - - // Retrieve the list of all MF orders (open and executed) over the last 7 days - describe("getMFOrders", function() { - it("Retrieve the list of all MF orders from orderbook", (done) => { - kc.getMFOrders() - .then(function(response) { - expect(response).to.be.an("array") - return done(); - }).catch(done); - }) - }); - - // Retrieve the detail of a given MF order - describe("getMFOrders", function() { - it("Retrieve the detail of a given MF order", (done) => { - kc.getMFOrders(100) - .then(function(response) { - expect(response).to.have.property("order_timestamp"); - expect(response).to.have.property("status"); - return done(); - }).catch(done); - }) - }); - - // Place MF SIP Order - describe("placeMFSIP", function() { - it("Place MF SIP Order", (done) => { - kc.placeMFSIP({ - "tradingsymbol": "INF174K01LS2", - "frequency" : "monthly", - "instalment_day": 1, - "instalments" : -1, - "initial_amount" : 5000, - "amount" : 1000 - }) - .then(function(response) { - expect(response).to.have.property("sip_id"); - return done(); - }).catch(done); - }) - }); - - // modify open pending MF SIP order - describe("modifyMFSIP", function() { - it("modify open pending NF SIP order", (done) => { - kc.modifyMFSIP(100,{ - "instalments":12}) - .then(function(response) { - expect(response).to.have.property("sip_id"); - return done(); - }).catch(done); - }) - }); - - // cancel an open pending MF SIP order - describe("cancelMFSIP", function() { - it("cancel an open pending MF SIP order", (done) => { - kc.cancelMFSIP(100) - .then(function(response) { - expect(response).to.have.property("sip_id"); - return done(); - }).catch(done); - }) - }); - - // Retrieve complete SIP orderbook - describe("getMFSIPS", function() { - it("Retrieve complete SIP orderbook", (done) => { - kc.getMFSIPS() - .then(function(response) { - expect(response).to.be.an("array"); - expect(response).to.have.nested.property("[0].status"); - expect(response).to.have.nested.property("[0].created"); - return done(); - }).catch(done); - }) - }); - - // Retrieve the detail of a given SIP order - describe("getMFSIPS", function() { - it("Retrieve the detail of a given SIP order", (done) => { - kc.getMFSIPS(100) - .then(function(response) { - expect(response).to.have.property("status"); - expect(response).to.have.property("created"); - return done(); - }).catch(done); - }) - }); - - // Retrieve complete MF holdings - describe("getMFHoldings", function() { - it("Retrieve complete MF holdings", (done) => { - kc.getMFHoldings() - .then(function(response) { - expect(response).to.be.an("array"); - expect(response).to.have.nested.property("[0].folio"); - expect(response).to.have.nested.property("[0].fund"); - return done(); - }).catch(done); - }) - }); - - // Historical candle APIs - describe("getHistoricalData", function() { - // for intraday candle - it("Fetch historical data for minute(intraday) candle", (done) => { - kc.getHistoricalData(100, "minute", - "2022-06-01 09:15:00", "2022-06-01 15:30:00") - .then(function(response) { - expect(response).to.have.nested.property("[0].date"); - expect(response).to.have.nested.property("[0].open"); - expect(response).to.have.nested.property("[0].close"); - expect(response).to.have.nested.property("[0].volume"); - return done(); - }).catch(done); - }) - }); - - // Market quotes and instruments - // Retrieve full market quotes for instruments - describe("getQuote", function() { - it("Retrieve full market quotes for instruments", (done) => { - kc.getQuote("NSE:INFY") - .then(function(response) { - expect(response).to.have.property("NSE:INFY"); - expect(response).to.have.nested.property("NSE:INFY.last_price"); - expect(response).to.have.nested.property("NSE:INFY.depth"); - expect(response).to.have.nested.property("NSE:INFY.ohlc"); - return done(); - }).catch(done); - }) - }); - - // Retrieve LTP quotes for instruments - describe("getLTP", function() { - it("Retrieve LTP quotes for instruments", (done) => { - kc.getLTP("NSE:INFY") - .then(function(response) { - expect(response).to.have.property("NSE:INFY"); - expect(response).to.have.nested.property("NSE:INFY.instrument_token"); - expect(response).to.have.nested.property("NSE:INFY.last_price"); - return done(); - }).catch(done); - }) - }); - - // Retrieve OHLC quotes for instruments - describe("getOHLC", function() { - it("Retrieve OHLC quotes for instruments", (done) => { - kc.getOHLC("NSE:INFY") - .then(function(response) { - expect(response).to.have.property("NSE:INFY"); - expect(response).to.have.nested.property("NSE:INFY.last_price"); - expect(response).to.have.nested.property("NSE:INFY.ohlc"); - return done(); - }).catch(done); - }) - }); - - // GTT APIs - // Place a GTT - describe("placeGTT", function() { - it("Place an GTT OCO order", (done) => { - kc.placeGTT({ - trigger_type: kc.GTT_TYPE_OCO, - tradingsymbol: "SBIN", - exchange: "NSE", - trigger_values: [350, 450], - last_price: 400, - orders: [{ - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 350 - }, { - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 450 - }] - } - ) - .then(function(response) { - expect(response).to.have.property("trigger_id"); - return done(); - }).catch(done); - }) - }); - - //Retrieve a list of all GTTs visible in GTT order book - describe("getGTTs", function() { - it("Fetch list of all GTTs visible in GTT order book", (done) => { - kc.getGTTs() - .then(function(response) { - expect(response).to.have.nested.property("[0].id"); - expect(response).to.have.nested.property("[0].created_at"); - expect(response).to.have.nested.property("[0].user_id"); - expect(response).to.have.nested.property("[0].status"); - return done(); - }).catch(done); - }) - }); - - // Retrieve an individual trigger - describe("getGTT", function() { - it("Fetch specific gtt order detail using trigger_id", (done) => { - kc.getGTT(100) - .then(function(response) { - expect(response).to.have.property("id"); - expect(response).to.have.property("type"); - expect(response).to.have.property("status"); - expect(response).to.have.property("condition"); - return done(); - }).catch(done); - }) - }); - - // Modify an active GTT - describe("modifyGTT", function() { - it("Modify an open GTT order using trigger_id", (done) => { - kc.modifyGTT(100, { - trigger_type: kc.GTT_TYPE_OCO, - tradingsymbol: "SBIN", - exchange: "NSE", - trigger_values: [358, 458], - last_price: 400, - orders: [{ - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 358 - }, { - transaction_type: kc.TRANSACTION_TYPE_SELL, - quantity: 1, - product: kc.PRODUCT_CNC, - order_type: kc.ORDER_TYPE_LIMIT, - price: 458 - }]}) - .then(function(response) { - expect(response).to.have.property("trigger_id"); - return done(); - }).catch(done); - }) - }); - - // Delete an active GTT - describe("deleteGTT", function() { - it("Delete a GTT using trigger_id", (done) => { - kc.deleteGTT(100) - .then(function(response) { - expect(response).to.have.property("trigger_id"); - return done(); - }).catch(done); - }) - }); - - // Margin APIs - // fetch order Margin detail - describe("orderMargins", function() { - it("Fetch order margin detail", (done) => { - kc.orderMargins([ - { - "exchange": "NSE", - "tradingsymbol": "SBIN", - "transaction_type": "BUY", - "variety": "regular", - "product": "MIS", - "order_type": "MARKET", - "quantity": 1 - } - ]) - .then(function(response) { - expect(response).to.have.nested.property("[0].type"); - expect(response).to.have.nested.property("[0].var"); - expect(response).to.have.nested.property("[0].span"); - expect(response).to.have.nested.property("[0].exposure"); - // Order charges - expect(response).to.have.nested.property("[0].charges.total"); - expect(response).to.have.nested.property("[0].charges.transaction_tax"); - expect(response).to.have.nested.property("[0].charges.gst.total"); - return done(); - }).catch(done); - }) - }); -} diff --git a/test/test.ts b/test/test.ts new file mode 100644 index 0000000..5a2ec12 --- /dev/null +++ b/test/test.ts @@ -0,0 +1,678 @@ +'use strict'; + +import nock from 'nock'; +import { expect } from 'chai'; +import * as path from 'path'; +import * as fs from 'fs'; +//@ts-ignore +import { default as KiteConnect } from '../lib/connect'; +import { AnyObject } from '../interfaces/any-object.js'; +import { ExchangeTypes, GTTStatusTypes, OrderTypes, PositionTypes, Products, TransactionTypes, Varieties } from '../interfaces'; + +const mockDir = './kiteconnect-mocks'; + +// run testsuite +testSuite(); + +function parseJson(fileName: string){ + // read and parse mock json file + const rawdata = fs.readFileSync(path.join(__dirname, mockDir, fileName)); + const mockData= JSON.parse(rawdata as unknown as string); + return mockData; +} + +function testSuite(){ + //@ts-ignore + const kc = new KiteConnect({'api_key':'your api_key'}); + + // Chaining the mock requests + nock(kc.root as string) + // getProfile + .get('/user/profile') + .reply(200, parseJson('profile.json')) + + // getMargins + .get('/user/margins') + .reply(200, parseJson('margins.json')) + + // getMargins(segment) + .get('/user/margins/test') + .query({ segment: 'test' }) + .reply(200, parseJson('margins_equity.json')) + + // placeOrder + .post('/orders/test') + .reply(200, parseJson('order_response.json')) + + // modifyOrder + .put('/orders/test/100') + .reply(200, parseJson('order_modify.json')) + + // cancelOrder + .delete('/orders/test/100') + .query({ variety: 'test', order_id: 100 }) + .reply(200, parseJson('order_cancel.json')) + + // getOrders + .get('/orders') + .reply(200, parseJson('orders.json')) + + // getOrderHistory + .get('/orders/100') + .query({ order_id: '100' }) + .reply(200, parseJson('order_info.json')) + + // getTrades + .get('/trades') + .reply(200, parseJson('trades.json')) + + // getOrderTrades + .get('/orders/100/trades') + .query({ order_id: 100 }) + .reply(200, parseJson('order_trades.json')) + + // getHoldings + .get('/portfolio/holdings') + .reply(200, parseJson('holdings.json')) + + // getHoldings + .get('/portfolio/holdings/auctions') + .reply(200, parseJson('auctions_list.json')) + + // getPositions + .get('/portfolio/positions') + .reply(200, parseJson('positions.json')) + + // convertPosition + .put('/portfolio/positions') + .reply(200, parseJson('convert_position.json')) + + // placeMFOrder + .post('/mf/orders') + .reply(200, parseJson('mf_order_response.json')) + + // cancelMFOrder + .delete('/mf/orders/100') + .query({ order_id: 100 }) + .reply(200, parseJson('mf_order_cancel.json')) + + // getMFOrders + .get('/mf/orders') + .reply(200, parseJson('mf_orders.json')) + + // getMFOrders(order_id) + .get('/mf/orders/100') + .query({ order_id: 100 }) + .reply(200, parseJson('mf_orders_info.json')) + + // placeMFSIP + .post('/mf/sips') + .reply(200, parseJson('mf_sip_place.json')) + + // modifyMFSIP + .put('/mf/sips/100') + .reply(200, parseJson('mf_sip_modify.json')) + + // cancelMFSIP + .delete('/mf/sips/100') + .query({ sip_id: 100 }) + .reply(200, parseJson('mf_sip_cancel.json')) + + // getMFSIPS + .get('/mf/sips') + .reply(200, parseJson('mf_sips.json')) + + // getMFSIPS(sip_id) + .get('/mf/sips/100') + .query({ sip_id: 100 }) + .reply(200, parseJson('mf_sip_info.json')) + + // getMFHoldings + .get('/mf/holdings') + .reply(200, parseJson('mf_holdings.json')) + + // getHistoricalData + .get('/instruments/historical/100/minute') + .query({ instrument_token: '100' , interval: 'minute', + from: '2022-06-01 09:15:00', to: '2022-06-01 15:30:00', + continuous: 0, oi:0}) + .reply(200, parseJson('historical_minute.json')) + + // getQuote + .get('/quote') + .query({ i:'NSE:INFY'}) + .reply(200, parseJson('quote.json')) + + // getLTP + .get('/quote/ltp') + .query({ i: 'NSE:INFY' }) + .reply(200, parseJson('ltp.json')) + + // getOHLC + .get('/quote/ohlc') + .query({ i:'NSE:INFY'}) + .reply(200, parseJson('quote.json')) + + // placeGTT + .post('/gtt/triggers') + .reply(200, parseJson('gtt_place_order.json')) + + // modifyGTT + .put('/gtt/triggers/100') + .reply(200, parseJson('gtt_modify_order.json')) + + // deleteGTT + .delete('/gtt/triggers/100') + .query({ trigger_id: 100 }) + .reply(200, parseJson('gtt_delete_order.json')) + + // getGTTs + .get('/gtt/triggers') + .reply(200, parseJson('gtt_get_orders.json')) + + // getGTT(trigger_id) + .get('/gtt/triggers/100') + .query({ trigger_id:100}) + .reply(200, parseJson('gtt_get_order.json')) + + // orderMargins + .post('/margins/orders') + .query({ mode: null }) + .reply(200, parseJson('order_margins.json')) + + + // fetch user profile detail + describe('getProfile', function() { + it('fetch user profile detail', (done) => { + kc.getProfile() + .then(function(response: AnyObject) { + expect(response).to.have.property('user_id'); + expect(response).to.have.property('user_name'); + return done(); + }).catch(done); + }) + }); + + // fetch user fund detail + describe('getMargins', function() { + it('fetch equity and commodity segment funds', (done) => { + kc.getMargins() + .then(function(response: AnyObject) { + expect(response).to.have.property('equity'); + expect(response).to.have.property('commodity'); + return done(); + }).catch(done); + }) + it('fetch equity specific segment funds', (done) => { + kc.getMargins('test') + .then(function(response: AnyObject) { + expect(response).to.have.property('enabled'); + return done(); + }).catch(done); + }) + }); + + // Order APIs + // Place market and limit order + describe('placeOrder', function() { + it('Place market order', (done) => { + kc.placeOrder(Varieties.TEST, { + 'exchange': ExchangeTypes.NSE, + 'tradingsymbol': 'SBIN', + 'transaction_type': TransactionTypes.BUY, + 'quantity': 1, + 'product': Products.MIS, + 'order_type': OrderTypes.MARKET}) + .then(function(response: AnyObject) { + expect(response).to.have.property('order_id'); + return done(); + }).catch(done); + }) + }); + + // modify open pending order + describe('modifyOrder', function() { + it('Modify an open order', (done) => { + kc.modifyOrder(Varieties.TEST, 100,{ + 'price':10}) + .then(function(response: AnyObject) { + expect(response).to.have.property('order_id'); + return done(); + }).catch(done); + }) + }); + + // cancel an open pending order + describe('cancelOrder', function() { + it('cancel an open pending order', (done) => { + kc.cancelOrder(Varieties.TEST, 100) + .then(function(response: AnyObject) { + expect(response).to.have.property('order_id'); + return done(); + }).catch(done); + }) + }); + + // Retrieve complete orderbook + describe('getOrders', function() { + it('Retrieve the list of all orders under orderbook', (done) => { + kc.getOrders() + .then(function(response: AnyObject) { + expect(response).to.be.an('array'); + expect(response).to.have.nested.property('[0].order_id'); + expect(response).to.have.nested.property('[0].status'); + expect(response).to.have.nested.property('[0].tradingsymbol'); + return done(); + }).catch(done); + }) + }); + + // Retrieve the history of a given order + describe('getOrderHistory', function() { + it('Retrieve the history of a given order', (done) => { + kc.getOrderHistory(100) + .then(function(response: AnyObject) { + expect(response).to.have.nested.property('[0].order_id'); + expect(response).to.have.nested.property('[0].status'); + return done(); + }).catch(done); + }) + }); + + // Retrieve the list of all executed trades + describe('getTrades', function() { + it('Retrieve the list of all executed trades for the day', (done) => { + kc.getTrades() + .then(function(response: AnyObject) { + expect(response).to.be.an('array'); + expect(response).to.have.nested.property('[0].order_id'); + expect(response).to.have.nested.property('[0].exchange_timestamp'); + return done(); + }).catch(done); + }) + }); + + // Retrieve all the trades generated by an order + describe('getOrderTrades', function() { + it('Retrieve all the trades generated by an order', (done) => { + kc.getOrderTrades(100) + .then(function(response: AnyObject) { + expect(response).to.be.an('array'); + return done(); + }).catch(done); + }) + }); + + // Portfolio APIs + // Retrieve the list of equity holdings + describe('getHoldings', function() { + it('Retrieve the list of equity holdings', (done) => { + kc.getHoldings() + .then(function(response: AnyObject) { + expect(response).to.be.an('array'); + expect(response).to.have.nested.property('[0].tradingsymbol'); + expect(response).to.have.nested.property('[0].average_price'); + return done(); + }).catch(done); + }) + }); + + // Retrieves list of available instruments for a auction session + describe('getAuctionInstruments', function() { + it('Retrieves list of available instruments for a auction session', (done) => { + kc.getAuctionInstruments() + .then(function(response: AnyObject) { + expect(response).to.be.an('array'); + expect(response).to.have.nested.property('[0].auction_number'); + expect(response).to.have.nested.property('[0].instrument_token'); + expect(response).to.have.nested.property('[0].tradingsymbol'); + return done(); + }).catch(done); + }) + }); + + // Retrieve the list of positions + describe('getPositions', function() { + it('Retrieve the list of positions', (done) => { + kc.getPositions() + .then(function(response: AnyObject) { + expect(response).to.have.property('net'); + expect(response).to.have.property('day'); + return done(); + }).catch(done); + }) + }); + + // convert existing position + describe('convertPosition', function() { + it('convert existing position', (done) => { + kc.convertPosition ({ + 'tradingsymbol': 'SBIN', + 'exchange': ExchangeTypes.NSE, + 'transaction_type': TransactionTypes.BUY, + 'position_type': PositionTypes.POSITION_TYPE_DAY, + 'quantity':1, + 'old_product': Products.CNC, + 'new_product': Products.MIS, + }) + .then(function(response: AnyObject) { + expect(response).to.equal(true); + return done(); + }).catch(done); + }) + }); + + // MF APIs + // Place MF Order + describe('placeMFOrder', function() { + it('Place MF order', (done) => { + kc.placeMFOrder({ + 'tradingsymbol': 'INF174K01LS2', + 'transaction_type': TransactionTypes.BUY, + 'amount' : 1000}) + .then(function(response: AnyObject) { + expect(response).to.have.property('order_id'); + return done(); + }).catch(done); + }) + }); + + // cancel an open pending MF order + describe('cancelMFOrder', function() { + it('cancel an open pending MF order', (done) => { + kc.cancelMFOrder(100) + .then(function(response: AnyObject) { + expect(response).to.have.property('order_id'); + return done(); + }).catch(done); + }) + }); + + // Retrieve the list of all MF orders (open and executed) over the last 7 days + describe('getMFOrders', function() { + it('Retrieve the list of all MF orders from orderbook', (done) => { + kc.getMFOrders() + .then(function(response: AnyObject) { + expect(response).to.be.an('array') + return done(); + }).catch(done); + }) + }); + + // Retrieve the detail of a given MF order + describe('getMFOrders', function() { + it('Retrieve the detail of a given MF order', (done) => { + kc.getMFOrders(100) + .then(function(response: AnyObject) { + expect(response).to.have.property('order_timestamp'); + expect(response).to.have.property('status'); + return done(); + }).catch(done); + }) + }); + + // Place MF SIP Order + describe('placeMFSIP', function() { + it('Place MF SIP Order', (done) => { + kc.placeMFSIP({ + 'tradingsymbol': 'INF174K01LS2', + 'frequency' : 'monthly', + 'instalment_day': 1, + 'instalments' : -1, + 'initial_amount' : 5000, + 'amount' : 1000 + }) + .then(function(response: AnyObject) { + expect(response).to.have.property('sip_id'); + return done(); + }).catch(done); + }) + }); + + // modify open pending MF SIP order + describe('modifyMFSIP', function() { + it('modify open pending NF SIP order', (done) => { + kc.modifyMFSIP(100,{ + 'instalments':12}) + .then(function(response: AnyObject) { + expect(response).to.have.property('sip_id'); + return done(); + }).catch(done); + }) + }); + + // cancel an open pending MF SIP order + describe('cancelMFSIP', function() { + it('cancel an open pending MF SIP order', (done) => { + kc.cancelMFSIP(100) + .then(function(response: AnyObject) { + expect(response).to.have.property('sip_id'); + return done(); + }).catch(done); + }) + }); + + // Retrieve complete SIP orderbook + describe('getMFSIPS', function() { + it('Retrieve complete SIP orderbook', (done) => { + kc.getMFSIPS() + .then(function(response: AnyObject) { + expect(response).to.be.an('array'); + expect(response).to.have.nested.property('[0].status'); + expect(response).to.have.nested.property('[0].created'); + return done(); + }).catch(done); + }) + }); + + // Retrieve the detail of a given SIP order + describe('getMFSIPS', function() { + it('Retrieve the detail of a given SIP order', (done) => { + kc.getMFSIPS(100) + .then(function(response: AnyObject) { + expect(response).to.have.property('status'); + expect(response).to.have.property('created'); + return done(); + }).catch(done); + }) + }); + + // Retrieve complete MF holdings + describe('getMFHoldings', function() { + it('Retrieve complete MF holdings', (done) => { + kc.getMFHoldings() + .then(function(response: AnyObject) { + expect(response).to.be.an('array'); + expect(response).to.have.nested.property('[0].folio'); + expect(response).to.have.nested.property('[0].fund'); + return done(); + }).catch(done); + }) + }); + + // Historical candle APIs + describe('getHistoricalData', function() { + // for intraday candle + it('Fetch historical data for minute(intraday) candle', (done) => { + kc.getHistoricalData(100, 'minute', + '2022-06-01 09:15:00', '2022-06-01 15:30:00') + .then(function(response: AnyObject) { + expect(response).to.have.nested.property('[0].date'); + expect(response).to.have.nested.property('[0].open'); + expect(response).to.have.nested.property('[0].close'); + expect(response).to.have.nested.property('[0].volume'); + return done(); + }).catch(done); + }) + }); + + // Market quotes and instruments + // Retrieve full market quotes for instruments + describe('getQuote', function() { + it('Retrieve full market quotes for instruments', (done) => { + kc.getQuote('NSE:INFY') + .then(function(response: AnyObject) { + expect(response).to.have.property('NSE:INFY'); + expect(response).to.have.nested.property('NSE:INFY.last_price'); + expect(response).to.have.nested.property('NSE:INFY.depth'); + expect(response).to.have.nested.property('NSE:INFY.ohlc'); + return done(); + }).catch(done); + }) + }); + + // Retrieve LTP quotes for instruments + describe('getLTP', function() { + it('Retrieve LTP quotes for instruments', (done) => { + kc.getLTP('NSE:INFY') + .then(function(response: AnyObject) { + expect(response).to.have.property('NSE:INFY'); + expect(response).to.have.nested.property('NSE:INFY.instrument_token'); + expect(response).to.have.nested.property('NSE:INFY.last_price'); + return done(); + }).catch(done); + }) + }); + + // Retrieve OHLC quotes for instruments + describe('getOHLC', function() { + it('Retrieve OHLC quotes for instruments', (done) => { + kc.getOHLC('NSE:INFY') + .then(function(response: AnyObject) { + expect(response).to.have.property('NSE:INFY'); + expect(response).to.have.nested.property('NSE:INFY.last_price'); + expect(response).to.have.nested.property('NSE:INFY.ohlc'); + return done(); + }).catch(done); + }) + }); + + // GTT APIs + // Place a GTT + describe('placeGTT', function() { + it('Place an GTT OCO order', (done) => { + kc.placeGTT({ + trigger_type: GTTStatusTypes.GTT_TYPE_OCO, + tradingsymbol: 'SBIN', + exchange: ExchangeTypes.NSE, + trigger_values: [350, 450], + last_price: 400, + orders: [{ + transaction_type: TransactionTypes.SELL, + quantity: 1, + product: Products.CNC, + order_type: OrderTypes.LIMIT, + price: 350 + }, { + transaction_type: TransactionTypes.SELL, + quantity: 1, + product: Products.CNC, + order_type: OrderTypes.LIMIT, + price: 450 + }] + } + ) + .then(function(response: AnyObject) { + expect(response).to.have.property('trigger_id'); + return done(); + }).catch(done); + }) + }); + + //Retrieve a list of all GTTs visible in GTT order book + describe('getGTTs', function() { + it('Fetch list of all GTTs visible in GTT order book', (done) => { + kc.getGTTs() + .then(function(response: AnyObject) { + expect(response).to.have.nested.property('[0].id'); + expect(response).to.have.nested.property('[0].created_at'); + expect(response).to.have.nested.property('[0].user_id'); + expect(response).to.have.nested.property('[0].status'); + return done(); + }).catch(done); + }) + }); + + // Retrieve an individual trigger + describe('getGTT', function() { + it('Fetch specific gtt order detail using trigger_id', (done) => { + kc.getGTT(100) + .then(function(response: AnyObject) { + expect(response).to.have.property('id'); + expect(response).to.have.property('type'); + expect(response).to.have.property('status'); + expect(response).to.have.property('condition'); + return done(); + }).catch(done); + }) + }); + + // Modify an active GTT + describe('modifyGTT', function() { + it('Modify an open GTT order using trigger_id', (done) => { + kc.modifyGTT(100, { + trigger_type: GTTStatusTypes.GTT_TYPE_OCO, + tradingsymbol: 'SBIN', + exchange: ExchangeTypes.NSE, + trigger_values: [358, 458], + last_price: 400, + orders: [{ + transaction_type: TransactionTypes.SELL, + quantity: 1, + product: Products.CNC, + order_type: OrderTypes.LIMIT, + price: 358 + }, { + transaction_type: TransactionTypes.SELL, + quantity: 1, + product: Products.CNC, + order_type: OrderTypes.LIMIT, + price: 458 + }]}) + .then(function(response: AnyObject) { + expect(response).to.have.property('trigger_id'); + return done(); + }).catch(done); + }) + }); + + // Delete an active GTT + describe('deleteGTT', function() { + it('Delete a GTT using trigger_id', (done) => { + kc.deleteGTT(100) + .then(function(response: AnyObject) { + expect(response).to.have.property('trigger_id'); + return done(); + }).catch(done); + }) + }); + + // Margin APIs + // fetch order Margin detail + describe('orderMargins', function() { + it('Fetch order margin detail', (done) => { + kc.orderMargins([ + { + 'exchange': ExchangeTypes.NSE, + 'tradingsymbol': 'SBIN', + 'transaction_type': TransactionTypes.BUY, + 'variety': Varieties.VARIETY_REGULAR, + 'product': Products.MIS, + 'order_type': OrderTypes.MARKET, + 'quantity': 1 + } + ]) + .then(function(response: AnyObject) { + expect(response).to.have.nested.property('[0].type'); + expect(response).to.have.nested.property('[0].var'); + expect(response).to.have.nested.property('[0].span'); + expect(response).to.have.nested.property('[0].exposure'); + // Order charges + expect(response).to.have.nested.property('[0].charges.total'); + expect(response).to.have.nested.property('[0].charges.transaction_tax'); + expect(response).to.have.nested.property('[0].charges.gst.total'); + return done(); + }).catch(done); + }) + }); +} diff --git a/test/test_ticker.js b/test/test_ticker.js deleted file mode 100644 index cab0820..0000000 --- a/test/test_ticker.js +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; - -const path = require("path"); -const fs = require("fs"); -const expect = require("chai").expect; -var KiteTicker = require("../dist/ticker.js").default; - - -// Ticker binary packets -var ltpPacket = "ltpMode_binary.packet"; -var quotePacket = "quoteMode_binary.packet"; -var fullPacket = "fullMode_binary.packet"; - -function testTicker() { - var ticker = new KiteTicker({ - api_key: "api_key", - access_token: "access_token", - }); - - // Fetch ltp mode tick data - describe("ltpModeTick", function() { - it("Fetch ltp mode tick data", () => { - var tickData = ticker.parseBinary(toArrayBuffer(ltpPacket)); - expect(tickData).to.be.an("array"); - expect(tickData[0].mode).to.equal("ltp"); - expect(tickData).to.have.nested.property("[0].instrument_token"); - expect(tickData).to.have.nested.property("[0].last_price"); - }) - }); - - // Fetch quote mode tick data - describe("quoteModeTick", function() { - it("Fetch quote mode tick data", () => { - var tickData = ticker.parseBinary(toArrayBuffer(quotePacket)); - expect(tickData).to.be.an("array"); - expect(tickData[0].mode).to.equal("quote"); - expect(tickData).to.have.nested.property("[0].instrument_token"); - expect(tickData).to.have.nested.property("[0].ohlc"); - expect(tickData).to.have.nested.property("[0].volume_traded"); - - }) - }); - - // Fetch Full mode tick data - describe("fullModeTick", function() { - it("Fetch full mode tick data", () => { - var tickData = ticker.parseBinary(toArrayBuffer(fullPacket)); - expect(tickData).to.be.an("array"); - expect(tickData[0].mode).to.equal("full"); - expect(tickData).to.have.nested.property("[0].exchange_timestamp"); - expect(tickData).to.have.nested.property("[0].last_trade_time"); - expect(tickData).to.have.nested.property("[0].depth"); - - }) - }); -} - -// Read binary packets -function readBufferPacket(fileName) { - var rawData = fs.readFileSync(path.join(__dirname, "./", fileName)); - return rawData; -} - -// Convert buffer to binary buffer array -function toArrayBuffer(tickerMode) { - var buf = readBufferPacket(tickerMode); - var ab = new ArrayBuffer(buf.length); - var view = new Uint8Array(ab); - for (let i = 0; i < buf.length; ++i) { - view[i] = buf[i]; - } - return ab; -} - -// Run ticker tests -testTicker() \ No newline at end of file diff --git a/test/test_ticker.ts b/test/test_ticker.ts new file mode 100644 index 0000000..72941dc --- /dev/null +++ b/test/test_ticker.ts @@ -0,0 +1,78 @@ +'use strict'; + +import * as path from 'path'; +import * as fs from 'fs'; +import { expect } from 'chai'; +//@ts-ignore +import { default as KiteTicker } from '../lib/ticker'; + + +// Ticker binary packets +const ltpPacket = 'ltpMode_binary.packet'; +const quotePacket = 'quoteMode_binary.packet'; +const fullPacket = 'fullMode_binary.packet'; + +function testTicker() { + //@ts-ignore + const ticker = new KiteTicker({ + api_key: 'api_key', + access_token: 'access_token', + }); + + // Fetch ltp mode tick data + describe('ltpModeTick', function() { + it('Fetch ltp mode tick data', () => { + const tickData = ticker.parseBinary(toArrayBuffer(ltpPacket)); + expect(tickData).to.be.an('array'); + expect(tickData[0].mode).to.equal('ltp'); + expect(tickData).to.have.nested.property('[0].instrument_token'); + expect(tickData).to.have.nested.property('[0].last_price'); + }) + }); + + // Fetch quote mode tick data + describe('quoteModeTick', function() { + it('Fetch quote mode tick data', () => { + const tickData = ticker.parseBinary(toArrayBuffer(quotePacket)); + expect(tickData).to.be.an('array'); + expect(tickData[0].mode).to.equal('quote'); + expect(tickData).to.have.nested.property('[0].instrument_token'); + expect(tickData).to.have.nested.property('[0].ohlc'); + expect(tickData).to.have.nested.property('[0].volume_traded'); + + }) + }); + + // Fetch Full mode tick data + describe('fullModeTick', function() { + it('Fetch full mode tick data', () => { + const tickData = ticker.parseBinary(toArrayBuffer(fullPacket)); + expect(tickData).to.be.an('array'); + expect(tickData[0].mode).to.equal('full'); + expect(tickData).to.have.nested.property('[0].exchange_timestamp'); + expect(tickData).to.have.nested.property('[0].last_trade_time'); + expect(tickData).to.have.nested.property('[0].depth'); + + }) + }); +} + +// Read binary packets +function readBufferPacket(fileName: string) { + const rawData = fs.readFileSync(path.join(__dirname, './', fileName)); + return rawData; +} + +// Convert buffer to binary buffer array +function toArrayBuffer(tickerMode: string) { + const buf = readBufferPacket(tickerMode); + const ab = new ArrayBuffer(buf.length); + const view = new Uint8Array(ab); + for (let i = 0; i < buf.length; ++i) { + view[i] = buf[i]; + } + return ab; +} + +// Run ticker tests +testTicker() \ No newline at end of file diff --git a/test/tsconfig.json b/test/tsconfig.json new file mode 100644 index 0000000..bf5c64e --- /dev/null +++ b/test/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "resolveJsonModule": true, + "noImplicitThis": false, + "target": "es2015", + "module": "commonjs", + "esModuleInterop": true, + "strict": true + }, + "files": ["test.ts", "test_ticker.ts"], + "exclude": ["../constants/**/*.ts", "../interfaces/**/*.ts", "../lib/**/*.ts"] +} + \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 74e9c03..4b6b254 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,9 +12,8 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "outDir": "dist", + "outDir": "./dist", "noImplicitThis": false, - "noImplicitAny": false, "target": "es2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "jsx": "preserve", /* Specify what JSX code is generated. */ @@ -48,7 +47,7 @@ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declaration": false, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ // "declarationMap": true, /* Create sourcemaps for d.ts files. */ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ diff --git a/types/connect.d.ts b/types/connect.d.ts index 09a59ac..fea3be4 100644 --- a/types/connect.d.ts +++ b/types/connect.d.ts @@ -1165,13 +1165,13 @@ type KiteConnectParams = { * API end point root. Unless you explicitly want to send API requests to a * non-default endpoint, this can be ignored. * - * Defaults to "https://api.kite.trade" + * Defaults to 'https://api.kite.trade' */ root?: string; /** * Kite connect login url * - * Defaults to "https://kite.trade/connect/login" + * Defaults to 'https://kite.trade/connect/login' */ login_uri?: string; /** @@ -1455,7 +1455,7 @@ type Connect = { /** * Retrieve LTP for list of instruments. * @param instruments is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. - * For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..] + * For example NSE:INFY and for list of instruments ['NSE:RELIANCE', 'NSE:SBIN', ..] */ getLTP: (instruments: string[]) => Promise< Record< @@ -1509,7 +1509,7 @@ type Connect = { /** * Retrieve OHLC for list of instruments. * @param instruments is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. - * For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..] + * For example NSE:INFY and for list of instruments ['NSE:RELIANCE', 'NSE:SBIN', ..] */ getOHLC: (instruments: string[]) => Promise< Record< @@ -1627,7 +1627,7 @@ type Connect = { /** * Retrieve quote and market depth for list of instruments. * @param instruments is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. - * For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..] + * For example NSE:INFY and for list of instruments ['NSE:RELIANCE', 'NSE:SBIN', ..] */ getQuote: (instruments: string[]) => Promise< Record< @@ -2093,11 +2093,11 @@ type KiteConnect = { * ------------------------ * ~~~~ * - * var KiteConnect = require("kiteconnect").KiteConnect; + * var KiteConnect = require('kiteconnect').KiteConnect; * - * var kc = new KiteConnect({api_key: "your_api_key"}); + * var kc = new KiteConnect({api_key: 'your_api_key'}); * - * kc.generateSession("request_token", "api_secret") + * kc.generateSession('request_token', 'api_secret') * .then(function(response) { * init(); * }) @@ -2133,7 +2133,7 @@ type KiteConnect = { * ~~~~ * * @example Initialize KiteConnect object - * var kc = KiteConnect("my_api_key", {timeout: 10, debug: false}) + * var kc = KiteConnect('my_api_key', {timeout: 10, debug: false}) */ new (params: KiteConnectParams): Connect; }; diff --git a/types/ticker.d.ts b/types/ticker.d.ts index f4724d3..293e1f9 100644 --- a/types/ticker.d.ts +++ b/types/ticker.d.ts @@ -75,9 +75,9 @@ type KiteTickerParams = { * ~~~~ * * @example - * ticker.on("ticks", callback); - * ticker.on("connect", callback); - * ticker.on("disconnect", callback); + * ticker.on('ticks', callback); + * ticker.on('connect', callback); + * ticker.on('disconnect', callback); */ on: ( event: @@ -125,18 +125,18 @@ type KiteTickerParams = { * Getting started: * --------------- * - * import { KiteTicker } from "kiteconnect"; + * import { KiteTicker } from 'kiteconnect'; * const ticker = new KiteTicker({ - * api_key: "api_key", - * access_token: "access_token" + * api_key: 'api_key', + * access_token: 'access_token' * }); * * ticker.connect(); - * ticker.on("ticks", onTicks); - * ticker.on("connect", subscribe); + * ticker.on('ticks', onTicks); + * ticker.on('connect', subscribe); * * function onTicks(ticks) { - * console.log("Ticks", ticks); + * console.log('Ticks', ticks); * } * * function subscribe() { @@ -233,32 +233,32 @@ type KiteTickerParams = { * * Here is an example demonstrating auto reconnection. * - * import { KiteTicker } from "kiteconnect"; + * import { KiteTicker } from 'kiteconnect'; * const ticker = new KiteTicker({ - * api_key: "api_key", - * access_token: "access_token" + * api_key: 'api_key', + * access_token: 'access_token' * }); * * // set autoreconnect with 10 maximum reconnections and 5 second interval * ticker.autoReconnect(true, 10, 5) * ticker.connect(); - * ticker.on("ticks", onTicks); - * ticker.on("connect", subscribe); + * ticker.on('ticks', onTicks); + * ticker.on('connect', subscribe); * - * ticker.on("noreconnect", function() { - * console.log("noreconnect"); + * ticker.on('noreconnect', function() { + * console.log('noreconnect'); * }); * - * ticker.on("reconnect", function(reconnect_count, reconnect_interval) { - * console.log("Reconnecting: attempt - ", reconnect_count, " interval - ", reconnect_interval); + * ticker.on('reconnect', function(reconnect_count, reconnect_interval) { + * console.log('Reconnecting: attempt - ', reconnect_count, ' interval - ', reconnect_interval); * }); * - * ticker.on("message", function(binary_msg){ - * console.log("Binary message", binary_msg); + * ticker.on('message', function(binary_msg){ + * console.log('Binary message', binary_msg); * }); * * function onTicks(ticks) { - * console.log("Ticks", ticks); + * console.log('Ticks', ticks); * } * * function subscribe() { diff --git a/yarn.lock b/yarn.lock index 2713798..379d62e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,10 +2,10 @@ # yarn lockfile v1 -"@babel/parser@^7.9.4": - version "7.12.16" - resolved "https://registry.npmjs.org/@babel/parser/-/parser-7.12.16.tgz" - integrity sha512-c/+u9cqV6F0+4Hpq01jnJO+GLp2DdT63ppz9Xa+6cHaajM9VFzK/iDXiKK65YtpeVwu+ctfS6iqlMqRgQRzeCw== +"@babel/parser@^7.20.15": + version "7.21.4" + resolved "https://registry.npmjs.org/@babel/parser/-/parser-7.21.4.tgz" + integrity sha512-alVJj7k7zIxqBZ7BTRhz0IqJFxW1VJbm6N8JbcYhQ186df9ZBPbZBmWSqAMXwHGsCJdYks7z/voa3ibiS5bCIw== "@eslint/eslintrc@^1.4.0": version "1.4.0" @@ -41,6 +41,13 @@ resolved "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz" integrity sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA== +"@jsdoc/salty@^0.2.1": + version "0.2.5" + resolved "https://registry.npmjs.org/@jsdoc/salty/-/salty-0.2.5.tgz" + integrity sha512-TfRP53RqunNe2HBobVBJ0VLhK1HbfvBYeTC1ahnN64PWvyYyGebmMiPkuwvD9fpw2ZbkoPb8Q7mwy0aR8Z9rvw== + dependencies: + lodash "^4.17.21" + "@nodelib/fs.scandir@2.1.5": version "2.1.5" resolved "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz" @@ -62,11 +69,39 @@ "@nodelib/fs.scandir" "2.1.5" fastq "^1.6.0" +"@types/chai@^4.3.4": + version "4.3.4" + resolved "https://registry.npmjs.org/@types/chai/-/chai-4.3.4.tgz" + integrity sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw== + "@types/crypto-js@^4.1.1": version "4.1.1" resolved "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.1.1.tgz" integrity sha512-BG7fQKZ689HIoc5h+6D2Dgq1fABRa0RbBWKBd9SP/MVRVXROflpm5fhwyATX5duFmbStzyzyycPB8qUYKDH3NA== +"@types/linkify-it@*": + version "3.0.2" + resolved "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-3.0.2.tgz" + integrity sha512-HZQYqbiFVWufzCwexrvh694SOim8z2d+xJl5UNamcvQFejLY/2YUtzXHYi3cHdI7PMlS8ejH2slRAOJQ32aNbA== + +"@types/markdown-it@*", "@types/markdown-it@^12.2.3": + version "12.2.3" + resolved "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-12.2.3.tgz" + integrity sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ== + dependencies: + "@types/linkify-it" "*" + "@types/mdurl" "*" + +"@types/mdurl@*": + version "1.0.2" + resolved "https://registry.npmjs.org/@types/mdurl/-/mdurl-1.0.2.tgz" + integrity sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA== + +"@types/mocha@^10.0.1": + version "10.0.1" + resolved "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.1.tgz" + integrity sha512-/fvYntiO1GeICvqbQ3doGDIP97vWmvFt83GKguJ6prmQM2iXZfFcq6YE8KteFyRtX2/h5Hf91BYvPodJKFYv5Q== + "@types/node@*", "@types/node@^18.11.18": version "18.11.18" resolved "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz" @@ -79,6 +114,13 @@ dependencies: "@types/node" "*" +"@types/ws@^8.5.4": + version "8.5.4" + resolved "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz" + integrity sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg== + dependencies: + "@types/node" "*" + "@ungap/promise-all-settled@1.1.2": version "1.1.2" resolved "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz" @@ -114,6 +156,11 @@ ansi-regex@^5.0.1: resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== +ansi-sequence-parser@^1.1.0: + version "1.1.0" + resolved "https://registry.npmjs.org/ansi-sequence-parser/-/ansi-sequence-parser-1.1.0.tgz" + integrity sha512-lEm8mt52to2fT8GhciPCGeCXACSz2UwIN4X2e2LJSnZ5uAbn2/dsYdOmUXq0AtWS5cpAupysIneExOgH0Vd2TQ== + ansi-styles@^4.0.0, ansi-styles@^4.1.0: version "4.3.0" resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz" @@ -129,13 +176,6 @@ anymatch@~3.1.2: normalize-path "^3.0.0" picomatch "^2.0.4" -argparse@^1.0.7: - version "1.0.10" - resolved "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz" - integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== - dependencies: - sprintf-js "~1.0.2" - argparse@^2.0.1: version "2.0.1" resolved "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz" @@ -210,12 +250,12 @@ camelcase@^6.0.0: resolved "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz" integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA== -catharsis@^0.8.11: - version "0.8.11" - resolved "https://registry.npmjs.org/catharsis/-/catharsis-0.8.11.tgz" - integrity sha512-a+xUyMV7hD1BrDQA/3iPV7oc+6W26BgVJO05PGEoatMyIuPScQKsde6i3YorWX1qs+AZjnJ18NqdKoCtKiNh1g== +catharsis@^0.9.0: + version "0.9.0" + resolved "https://registry.npmjs.org/catharsis/-/catharsis-0.9.0.tgz" + integrity sha512-prMTQVpcns/tzFgFVkVp6ak6RykZyWb3gu8ckUpd6YkTlacOd3DXGJjIpD4Q6zJirizvaiAjSSHlOsA+6sNh2A== dependencies: - lodash "^4.17.14" + lodash "^4.17.15" chai@^4.3.6: version "4.3.6" @@ -339,10 +379,10 @@ emoji-regex@^8.0.0: resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== -entities@~2.0.0: - version "2.0.3" - resolved "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz" - integrity sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ== +entities@~2.1.0: + version "2.1.0" + resolved "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz" + integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w== escalade@^3.1.1: version "3.1.1" @@ -583,9 +623,9 @@ globals@^13.19.0: type-fest "^0.20.2" graceful-fs@^4.1.9: - version "4.2.6" - resolved "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz" - integrity sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ== + version "4.2.11" + resolved "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz" + integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== grapheme-splitter@^1.0.4: version "1.0.4" @@ -694,32 +734,33 @@ js-yaml@^4.1.0, js-yaml@4.1.0: dependencies: argparse "^2.0.1" -js2xmlparser@^4.0.1: - version "4.0.1" - resolved "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.1.tgz" - integrity sha512-KrPTolcw6RocpYjdC7pL7v62e55q7qOMHvLX1UCLc5AAS8qeJ6nukarEJAF2KL2PZxlbGueEbINqZR2bDe/gUw== +js2xmlparser@^4.0.2: + version "4.0.2" + resolved "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.2.tgz" + integrity sha512-6n4D8gLlLf1n5mNLQPRfViYzu9RATblzPEtm1SthMX1Pjao0r9YI9nw7ZIfRxQMERS87mcswrg+r/OYrPRX6jA== dependencies: - xmlcreate "^2.0.3" + xmlcreate "^2.0.4" -jsdoc@^3.4.0: - version "3.6.6" - resolved "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.6.tgz" - integrity sha512-znR99e1BHeyEkSvgDDpX0sTiTu+8aQyDl9DawrkOGZTTW8hv0deIFXx87114zJ7gRaDZKVQD/4tr1ifmJp9xhQ== +jsdoc@^4.0.2: + version "4.0.2" + resolved "https://registry.npmjs.org/jsdoc/-/jsdoc-4.0.2.tgz" + integrity sha512-e8cIg2z62InH7azBBi3EsSEqrKx+nUtAS5bBcYTSpZFA+vhNPyhv8PTFZ0WsjOPDj04/dOLlm08EDcQJDqaGQg== dependencies: - "@babel/parser" "^7.9.4" + "@babel/parser" "^7.20.15" + "@jsdoc/salty" "^0.2.1" + "@types/markdown-it" "^12.2.3" bluebird "^3.7.2" - catharsis "^0.8.11" + catharsis "^0.9.0" escape-string-regexp "^2.0.0" - js2xmlparser "^4.0.1" + js2xmlparser "^4.0.2" klaw "^3.0.0" - markdown-it "^10.0.0" - markdown-it-anchor "^5.2.7" - marked "^0.8.2" + markdown-it "^12.3.2" + markdown-it-anchor "^8.4.1" + marked "^4.0.10" mkdirp "^1.0.4" requizzle "^0.2.3" strip-json-comments "^3.1.0" - taffydb "2.6.2" - underscore "~1.10.2" + underscore "~1.13.2" json-schema-traverse@^0.4.1: version "0.4.1" @@ -736,6 +777,11 @@ json-stringify-safe@^5.0.1: resolved "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz" integrity sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA== +jsonc-parser@^3.2.0: + version "3.2.0" + resolved "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz" + integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== + klaw@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz" @@ -751,10 +797,10 @@ levn@^0.4.1: prelude-ls "^1.2.1" type-check "~0.4.0" -linkify-it@^2.0.0: - version "2.2.0" - resolved "https://registry.npmjs.org/linkify-it/-/linkify-it-2.2.0.tgz" - integrity sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw== +linkify-it@^3.0.1: + version "3.0.3" + resolved "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz" + integrity sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ== dependencies: uc.micro "^1.0.1" @@ -775,10 +821,10 @@ lodash.set@^4.3.2: resolved "https://registry.npmjs.org/lodash.set/-/lodash.set-4.3.2.tgz" integrity sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg== -lodash@^4.17.14: - version "4.17.20" - resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz" - integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== +lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21: + version "4.17.21" + resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" + integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== log-symbols@4.1.0: version "4.1.0" @@ -795,31 +841,36 @@ loupe@^2.3.1: dependencies: get-func-name "^2.0.0" -markdown-it-anchor@^5.2.7: - version "5.3.0" - resolved "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-5.3.0.tgz" - integrity sha512-/V1MnLL/rgJ3jkMWo84UR+K+jF1cxNG1a+KwqeXqTIJ+jtA8aWSHuigx8lTzauiIjBDbwF3NcWQMotd0Dm39jA== +lunr@^2.3.9: + version "2.3.9" + resolved "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz" + integrity sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow== -markdown-it@*, markdown-it@^10.0.0: - version "10.0.0" - resolved "https://registry.npmjs.org/markdown-it/-/markdown-it-10.0.0.tgz" - integrity sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg== +markdown-it-anchor@^8.4.1: + version "8.6.7" + resolved "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-8.6.7.tgz" + integrity sha512-FlCHFwNnutLgVTflOYHPW2pPcl2AACqVzExlkGQNsi4CJgqOHN7YTgDd4LuhgN1BFO3TS0vLAruV1Td6dwWPJA== + +markdown-it@*, markdown-it@^12.3.2: + version "12.3.2" + resolved "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz" + integrity sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg== dependencies: - argparse "^1.0.7" - entities "~2.0.0" - linkify-it "^2.0.0" + argparse "^2.0.1" + entities "~2.1.0" + linkify-it "^3.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" -marked@^0.8.2: - version "0.8.2" - resolved "https://registry.npmjs.org/marked/-/marked-0.8.2.tgz" - integrity sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw== +marked@^4.0.10, marked@^4.3.0: + version "4.3.0" + resolved "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz" + integrity sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A== mdurl@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz" - integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g== + integrity sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g== minami@^1.1.1: version "1.2.3" @@ -847,6 +898,13 @@ minimatch@^3.1.2: dependencies: brace-expansion "^1.1.7" +minimatch@^9.0.0: + version "9.0.1" + resolved "https://registry.npmjs.org/minimatch/-/minimatch-9.0.1.tgz" + integrity sha512-0jWhJpD/MdhPXwPuiRkCbfYfSKp2qnn2eOc279qI7f+osl/l+prKSrvhg157zSYvx/1nmgn2NqdT6k2Z7zSH9w== + dependencies: + brace-expansion "^2.0.1" + minimatch@5.0.1: version "5.0.1" resolved "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz" @@ -1007,6 +1065,11 @@ punycode@^2.1.0: resolved "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz" integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== +querystring@^0.2.1: + version "0.2.1" + resolved "https://registry.npmjs.org/querystring/-/querystring-0.2.1.tgz" + integrity sha512-wkvS7mL/JMugcup3/rMitHmd9ecIGd2lhFhK9N3UUQ450h66d1r3Y9nvXzQAW1Lq+wyx61k/1pfKS5KuKiyEbg== + queue-microtask@^1.2.2: version "1.2.3" resolved "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz" @@ -1091,10 +1154,15 @@ shebang-regex@^3.0.0: resolved "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz" - integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g== +shiki@^0.14.1: + version "0.14.2" + resolved "https://registry.npmjs.org/shiki/-/shiki-0.14.2.tgz" + integrity sha512-ltSZlSLOuSY0M0Y75KA+ieRaZ0Trf5Wl3gutE7jzLuIcWxLp5i/uEnLoQWNvgKXQ5OMpGkJnVMRLAuzjc0LJ2A== + dependencies: + ansi-sequence-parser "^1.1.0" + jsonc-parser "^3.2.0" + vscode-oniguruma "^1.7.0" + vscode-textmate "^8.0.0" string-width@^4.1.0, string-width@^4.2.0: version "4.2.3" @@ -1131,10 +1199,10 @@ supports-color@8.1.1: dependencies: has-flag "^4.0.0" -taffydb@2.6.2: - version "2.6.2" - resolved "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz" - integrity sha1-fLy2S1oUG2ou/CxdLGe04VCyomg= sha512-y3JaeRSplks6NYQuCOj3ZFMO3j60rTwbuKCvZxsAraGYH2epusatvZ0baZYA01WsGqJBq/Dl6vOrMUJqyMj8kA== +taffydb@^2.7.3: + version "2.7.3" + resolved "https://registry.npmjs.org/taffydb/-/taffydb-2.7.3.tgz" + integrity sha512-GQ3gtYFSOAxSMN/apGtDKKkbJf+8izz5YfbGqIsUc7AMiQOapARZ76dhilRY2h39cynYxBFdafQo5HUL5vgkrg== text-table@^0.2.0: version "0.2.0" @@ -1165,7 +1233,17 @@ type-fest@^0.20.2: resolved "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz" integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ== -typescript@^4.9.4: +typedoc@^0.24.8: + version "0.24.8" + resolved "https://registry.npmjs.org/typedoc/-/typedoc-0.24.8.tgz" + integrity sha512-ahJ6Cpcvxwaxfu4KtjA8qZNqS43wYt6JL27wYiIgl1vd38WW/KWX11YuAeZhuz9v+ttrutSsgK+XO1CjL1kA3w== + dependencies: + lunr "^2.3.9" + marked "^4.3.0" + minimatch "^9.0.0" + shiki "^0.14.1" + +typescript@^4.9.4, "typescript@4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x": version "4.9.4" resolved "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz" integrity sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg== @@ -1175,10 +1253,10 @@ uc.micro@^1.0.1, uc.micro@^1.0.5: resolved "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== -underscore@~1.10.2: - version "1.10.2" - resolved "https://registry.npmjs.org/underscore/-/underscore-1.10.2.tgz" - integrity sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg== +underscore@~1.13.2: + version "1.13.6" + resolved "https://registry.npmjs.org/underscore/-/underscore-1.13.6.tgz" + integrity sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A== uri-js@^4.2.2: version "4.4.1" @@ -1187,6 +1265,16 @@ uri-js@^4.2.2: dependencies: punycode "^2.1.0" +vscode-oniguruma@^1.7.0: + version "1.7.0" + resolved "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-1.7.0.tgz" + integrity sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA== + +vscode-textmate@^8.0.0: + version "8.0.0" + resolved "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-8.0.0.tgz" + integrity sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg== + which@^2.0.1: version "2.0.2" resolved "https://registry.npmjs.org/which/-/which-2.0.2.tgz" @@ -1225,10 +1313,10 @@ ws@^6.2.2: dependencies: async-limiter "~1.0.0" -xmlcreate@^2.0.3: - version "2.0.3" - resolved "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.3.tgz" - integrity sha512-HgS+X6zAztGa9zIK3Y3LXuJes33Lz9x+YyTxgrkIdabu2vqcGOWwdfCpf1hWLRrd553wd4QCDf6BBO6FfdsRiQ== +xmlcreate@^2.0.4: + version "2.0.4" + resolved "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.4.tgz" + integrity sha512-nquOebG4sngPmGPICTS5EnxqhKbCmz5Ox5hsszI2T6U5qdrJizBc+0ilYSEjTSzU0yZcmvppztXe/5Al5fUwdg== y18n@^5.0.5: version "5.0.8"