Skip to content

Commit

Permalink
feat: add TypeScript interfaces, types, examples, update README, and …
Browse files Browse the repository at this point in the history
…improve documentation and unit tests
  • Loading branch information
ranjanrak committed Jun 12, 2024
1 parent 7d5ce42 commit 5134991
Show file tree
Hide file tree
Showing 15 changed files with 1,786 additions and 1,166 deletions.
99 changes: 3 additions & 96 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,99 +1,6 @@
# Kite v4
# Kite v5

### Breaking changes
- Upgrade deps and set minimum nodejs version to 8.0.0+
- Return promise instead of throwing error on generateSession and renewAccessToken
- Handle gtt payload validation and throw proper error
- Change ticker response attributes naming as per [kite connect doc](https://kite.trade/docs/connect/v3/websocket/#quote-packet-structure)

### New features
- Order margin call : [orderMargins](https://github.com/zerodha/kiteconnectjs/blob/master/lib/connect.js#L704)
- Basket order margin call : [orderBasketMargins](https://github.com/zerodha/kiteconnectjs/blob/master/lib/connect.js#L727)
- Add OI param to `getHistoricalData`
- Add global constant for postion types `POSITION_TYPE_DAY`, `POSITION_TYPE_OVERNIGHT` and `EXCHANGE_BCD`

### Fixes
- Remove `order_id` param from complete tradebook fetch `getTrades`
- Fix `cancelMF` order_id param struct
- Handle price conversion for BCD segment in ticker
- Remove un-used `headers` param for `parseHistorical`
- Update comment block for `getQuote, getOHLC, getLTP, placeOrder and placeMFOrder`


# Kite v3

### New features
- method: `getProfile`
- method: `getOHLC`
- method: `getLTP`
- method: `getInstrumentsMargins`
- Added MF API calls
- method: `getMFOrders`
- method: `getMFHoldings`
- method: `placeMFOrder`
- method: `cancelMFOrder`
- method: `getMFSIPS`
- method: `placeMFSIP`
- method: `modifyMFSIP`
- method: `cancelMFSIP`
- method: `getMFInstruments`
- method: `exitOrder`
- method: `renewAccessToken`
- method: `invalidateRefreshToken`
- constants for products, order type, transaction type, variety, validity, exchanges and margin segments

### API method name changes

| v2 | v3 |
| ------------------------- | ------------------------- |
| requestAccessToken | generateSession |
| invalidateToken | invalidateAccessToken |
| setSessionHook | setSessionExpiryHook |
| loginUrl | getLoginURL |
| margins | getMargins |
| orderPlace | placeOrder |
| orderModify | modifyOrder |
| orderCancel | cancelOrder |
| orders | getOrders |
| orders(order_id) | getOrderHistory |
| trades | getTrades |
| trades(order_id) | getOrderTrades |
| holdings | getHoldings |
| positions | getPositions |
| productModify | convertPosition |
| instruments | getInstruments |
| historical | getHistoricalData |
| triggerRange | getTriggerRange |

### Params and other changes
- `KiteConnect` takes all the params as object including `api_key`
- `convertPosition` method takes all the params as object
- All success response returns only `data` field in response instead with envelope
- All error thrown are in the format of `{"message": "Unknown error", "error_type": "GeneralException", "data": null}`
- [Changes in `generateSession` response structure](https://kite.trade/docs/connect/v3/user/#response-attributes)
- [Changes in `getPositions` response structure](https://kite.trade/docs/connect/v3/portfolio/#response-attributes_1)
- [Changes in `getQuote` response structure](https://kite.trade/docs/connect/v3/market-quotes/#retrieving-full-market-quotes)
- [Changes in `placeOrder` params](https://kite.trade/docs/connect/v3/orders/#bracket-order-bo-parameters)
- Changes in `getHistoricalData` params
- All datetime string fields has been converted to `Date` object.
- `getOrders`, `getOrderHistory`, `getTrades`, `getOrderTrades`, `getMFOrders` responses fields `order_timestamp`, `exchange_timestamp`, `fill_timestamp`
- `getMFSIPS` fields `created`, `last_instalment`
- `generateSession` field `login_time`
- `getQuote` fields `timestamp`, `last_trade_time`
- `getInstruments` field `expiry`
- `getMFInstruments` field `last_price_date`

### KiteTicker changes
- `KiteTicker` receives param `access_token` instead of `public_token`
- New params addedd to `KiteTicker` initializer
- `reconnect` - Toggle auto reconnect on/off
- `max_retry` - Max retry count for auto reconnect
- `max_delay` - Max delay between subsequent retries
- Auto reconnect is enabled by default
- Renamed callback `reconnecting` to `reconnect`
- Added new callbacks
- `error` - when socket connection is closed with error. Error is received as a first param
- `close` - when socket connection is closed cleanly
- `order_update` - When order update (postback) is received for the connected user (Data object is received as first argument)


- Upgrade deps and set minimum nodejs version to 18.0.0+
- New ts lib ## To-do: Add all changes
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 Zerodha Technology Pvt. Ltd. (India)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
164 changes: 86 additions & 78 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# The Kite Connect API Javascript client - v5
# The Kite Connect API JavaScript/TypeScript Client

The official Javascript node client for communicating with the [Kite Connect API](https://kite.trade).
The official JavaScript/TypeScript for communicating with the [Kite Connect API](https://kite.trade).

Kite Connect is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (WebSockets), and more, with the simple HTTP API collection.

[Zerodha Technology](http://zerodha.com) (c) 2018. Licensed under the MIT License.
[Zerodha Technology](http://zerodha.com) (c) 2024. Licensed under the MIT License.

## Documentation

- [Javascript client documentation](https://kite.trade/docs/kiteconnectjs/v3)
- [Typescript client documentation](https://kite.trade/docs/kiteconnectjs/v3)
- [Kite Connect HTTP API documentation](https://kite.trade/docs/connect/v3)

## Requirements
Expand All @@ -25,93 +25,103 @@ Or via [yarn](https://yarnpkg.com/package/kiteconnect)

yarn add kiteconnect

## Breaking changes - v5

`v5` is a **breaking** major release with multiple internal modification including for typescript.<br>
## Getting started with API

Below are the breaking changes:
```typescript
import { KiteConnect } from "kiteconnect";

- Upgrade deps and set minimum nodejs version to 8.0.0+
- Return promise instead of throwing error on generateSession and renewAccessToken
- Handle gtt payload validation and throw proper error
- Change ticker response attributes naming as per [kite connect doc](https://kite.trade/docs/connect/v3/websocket/#quote-packet-structure)
const apiKey = "your_api_key";
const apiSecret = "your_api_secret";
const requestToken = "your_request_token";

## Getting started with API
const kc = new KiteConnect({ api_key: apiKey });

```javascript
var KiteConnect = require("kiteconnect").KiteConnect;
async function init() {
try {
await generateSession();
await getProfile();
} catch (err) {
console.error(err);
}
}

var kc = new KiteConnect({
api_key: "your_api_key",
});
async function generateSession() {
try {
const response = await kc.generateSession(requestToken, apiSecret);
kc.setAccessToken(response.access_token);
console.log("Session generated:", response);
} catch (err) {
console.error("Error generating session:", err);
}
}

kc.generateSession("request_token", "api_secret")
.then(function (response) {
init();
})
.catch(function (err) {
console.log(err);
});

function init() {
// Fetch equity margins.
// You can have other api calls here.
kc.getMargins()
.then(function (response) {
// You got user's margin details.
})
.catch(function (err) {
// Something went wrong.
});
async function getProfile() {
try {
const profile = await kc.getProfile();
console.log("Profile:", profile);
} catch (err) {
console.error("Error getting profile:", err);
}
}
// Initialize the API calls
init();
```

## API promises

All API calls returns a promise which you can use to call methods like `.then(...)` and `.catch(...)`.
## Getting started WebSocket client

```javascript
kiteConnectApiCall
.then(function (v) {
// On success
})
.catch(function (e) {
// On rejected
});
```
```typescript
import { KiteTicker } from "kiteconnect";

## Getting started WebSocket client
const apiKey = "your_api_key";
const accessToken = "generated_access_token";

```javascript
var KiteTicker = require("kiteconnect").KiteTicker;
var ticker = new KiteTicker({
api_key: "api_key",
access_token: "access_token",
const ticker = new KiteTicker({
api_key: apiKey,
access_token: accessToken,
});

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) {
function onTicks(ticks: any[]): void {
console.log("Ticks", ticks);
}

function subscribe() {
var items = [738561];
ticker.subscribe(items);
ticker.setMode(ticker.modeFull, items);
function subscribe(): void {
const tokens = [738561, 256265];
ticker.subscribe(tokens);
ticker.setMode(ticker.modeFull, tokens);
}

function onDisconnect(error: Error): void {
console.log("Closed connection on disconnect", error);
}

function onError(error: Error): void {
console.log("Closed connection on error", error);
}

function onClose(reason: string): void {
console.log("Closed connection on close", reason);
}

function onTrade(order: any): void {
console.log("Order update", order);
}
```

## Auto re-connect WebSocket client

Optionally you can enable client side auto re-connection to automatically reconnect if the connection is dropped.
It is very useful at times when client side network is unreliable and patchy.
Optionally, you can enable client-side auto re-connection to automatically reconnect if the connection is dropped. It is very useful when the client-side network is unreliable and patchy.

All you need to do is enable auto re-connection with preferred interval and time. For example
Enable auto re-connection with a preferred interval and time. For example:

```javascript
```typescript
// Enable auto reconnect with 5 second interval and retry for maximum of 20 times.
ticker.autoReconnect(true, 20, 5);

Expand All @@ -127,38 +137,37 @@ ticker.autoReconnect(true, -1, 5);

Here is an example demonstrating auto reconnection.

```javascript
var KiteTicker = require("kiteconnect").KiteTicker;
var ticker = new KiteTicker({
```typescript
import { KiteTicker } from "kiteconnect";

const apiKey = "your_api_key";
const accessToken = "generated_access_token";
const ticker = new KiteTicker({
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("noreconnect", function () {
ticker.on("noreconnect", () => {
console.log("noreconnect");
});

ticker.on("reconnecting", function (reconnect_interval, reconnections) {
ticker.on("reconnect", (reconnect_count: any, reconnect_interval: any) => {
console.log(
"Reconnecting: attempt - ",
reconnections,
" innterval - ",
reconnect_count,
" interval - ",
reconnect_interval
);
});

function onTicks(ticks) {
function onTicks(ticks: any[]) {
console.log("Ticks", ticks);
}

function subscribe() {
var items = [738561];
const items = [738561];
ticker.subscribe(items);
ticker.setMode(ticker.modeFull, items);
}
Expand All @@ -173,8 +182,7 @@ npm run test
## Generate documentation

```
$ npm install -g jsdoc
$ jsdoc -r ./lib -d ./docs
$ npx typedoc --out ./docs
```

## Changelog
Expand Down
Loading

0 comments on commit 5134991

Please sign in to comment.