zerodha / kiteconnectjs Goto Github PK
View Code? Open in Web Editor NEWThe official typescript client library for the Kite Connect trading APIs
License: MIT License
The official typescript client library for the Kite Connect trading APIs
License: MIT License
Access to XMLHttpRequest at 'https://api.kite.trade/session/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am getting this cors issue while trying to retrieve access token from the api '/session/token',
hi,
I am trying to implement the ticker (websocket client) but I am getting no response from the ticker.
(this might be due to the fact that I am trying this on a weekend :))
My code snippet:
function startWebSocket (api_key, user_id, public_token){
console.log("-----inside function startWebSocket------");
check(api_key,String);
check(user_id, String);
check(public_token, String);
let KiteTicker = require("kiteconnect").KiteTicker;
let ticker = new KiteTicker(api_key, user_id, public_token);
console.log("-----Getting ticker started ------");
console.log(ticker);
console.log("-----starting the Ticker ------");
ticker.connect();
console.log("Ticker connected: "+ticker.connected());
ticker.on("tick", logTick);
ticker.on("connect", onTickerSubscribe);
ticker.on("unsubscribe", onTickerUnSubscribe);
ticker.on("disconnect", onTickerDisconnet);
function logTick(ticks) {
console.log("-----recieved quote ------");
console.log("Ticks", ticks);
}
function onTickerSubscribe() {
console.log("Ticker connected: "+ticker.connected());
console.log("-----Subscribing to WS ------");
let items = [738561,11654402,884737];
ticker.subscribe(items);
ticker.setMode(ticker.modeLTP, items);
}
function onTickerUnSubscribe(){
console.log("-----Ticker Unsubscribed ------");
console.log("Ticker connected: "+ticker.connected());
}
function onTickerDisconnet () {
console.log("-----Ticker Disconnected ------");
console.log("Ticker connected: "+ticker.connected());
}
}
The logs from the server:
I20170218-07:42:01.999(5.5)? ------REcieved the response from Zerodha server--------
I20170218-07:42:02.005(5.5)? -----inside function startWebSocket------
I20170218-07:42:02.007(5.5)? -----Getting ticker started ------
I20170218-07:42:02.019(5.5)? { modeFull: 'full',
I20170218-07:42:02.019(5.5)? modeQuote: 'quote',
I20170218-07:42:02.020(5.5)? modeLTP: 'ltp',
I20170218-07:42:02.021(5.5)? autoReconnect: [Function],
I20170218-07:42:02.021(5.5)? connect: [Function],
I20170218-07:42:02.022(5.5)? disconnect: [Function],
I20170218-07:42:02.022(5.5)? connected: [Function],
I20170218-07:42:02.022(5.5)? on: [Function],
I20170218-07:42:02.023(5.5)? subscribe: [Function],
I20170218-07:42:02.024(5.5)? unsubscribe: [Function],
I20170218-07:42:02.025(5.5)? setMode: [Function] }
I20170218-07:42:02.027(5.5)? -----starting the Ticker ------
I20170218-07:42:02.028(5.5)? Ticker connected: false
I20170218-07:42:03.174(5.5)? Ticker connected: true
I20170218-07:42:03.175(5.5)? -----Subscribing to WS ------
I20170218-07:42:33.173(5.5)? -----Ticker Disconnected ------
I20170218-07:42:33.174(5.5)? Ticker connected: false
I20170218-07:42:38.199(5.5)? -----Ticker Disconnected ------
I20170218-07:42:38.200(5.5)? Ticker connected: false
Will appreciate any help.
REgards
ARsh
Compiled with problems:X
ERROR in ./node_modules/kiteconnect/lib/connect.js 9:18-40
Module not found: Error: Can't resolve 'querystring' in 'D:\Project\node_modules\kiteconnect\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "querystring": require.resolve("querystring-es3") }'
- install 'querystring-es3'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "querystring": false }
I see 'querystring' is used in kiteconnect but is not included in dependency in the project
Can we please have support for quote/ohcl
and quote/ltp
calls for bulk quotes? I am ready to help here.
While debugging an issue with orderCancel API, i noticed that the "variety" parameter is having different check implemented in orderCancel API compared orderPlace/orderModify. Is this intentional ?
Here are the steps to reproduce the issue.
This always throws the error:
{ status: 'error',
message: 'Invalid session credentials',
error_type: 'TokenException' }
I am not sure, if I am getting the request_token incorrectly? or if there is something wrong with the response?
In the above line, if variety === null, then it would assign variety = null, which will cause issues further down the line of your code.
Hopefully no one has done that as of yet :)
Let me know, if you need a pull-request for the same from my end.
In python client on_message function is exposed with binary data. Can you add similar on_message trigger that triggers callback method with binary data.
I can create PR if you would like.
there are no response error when web-socket ticker run
At the exit of my program, as a good practise, I want to disconnect and release the websocket connection established by the KiteTicker. But there is no API exposed to do that!
getHistoricalData() returns incorrect candle data. Problem is in parseHistorical() function on line number 1032.
function parseHistorical(jsonData, headers) {
// Return if its an error
if (jsonData.error_type) return jsonData;
var results = [];
for(var i=0; i<jsonData.data.candles.length - 1; i++) { //should not be length-1
// for(var i=0; i<jsonData.data.candles.length ; i++) { Correct one
var d = jsonData.data.candles[i];
results.push({
"date": new Date(d[0]),
"open": d[1],
"high": d[2],
"low": d[3],
"close": d[4],
"volume": d[5]
});
}
return { "data": results };
}
Hi
I hit the following error when kite.orders() statement is executed.
<--- Last few GCs --->
31665 ms: Mark-sweep 1386.9 (1442.5) -> 1386.9 (1442.5) MB, 904.2 / 0.0 ms [allocation failure] [GC in old space requested].
32591 ms: Mark-sweep 1386.9 (1442.5) -> 1386.9 (1421.5) MB, 926.6 / 0.0 ms [last resort gc].
33492 ms: Mark-sweep 1386.9 (1421.5) -> 1386.9 (1421.5) MB, 900.4 / 0.0 ms [last resort gc].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0000023D67BCFB61
2: encode(aka encode) [D:\Balaji\stock\node_modules\request\node_modules\qs\lib\utils.js:~118] [pc=0000003A658E9E00] (this=0000023D67B04381 ,str=0000022E800A7901 <Very long string[7279]>)
3: arguments adaptor frame: 2->1
4: stringify(aka stringify) [D:\Balaji\stock\node_modules\request\node_modules\qs\lib\stringify.js:~32] [pc=0000003A658EB680] (this=0000023D67B04381 <u...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
I use nodeJS version v6.9.5 on Windows 10. Is there any specific version of nodeJS that you want me to use?
I have successful authentication to zerodha platform, have valid api_key, api_secret, access_token.
This is almost a showstopper to me.
Could you please help me identifying the problem?
Thanks
Balaji
parseHistorical starts parsing assuming the response is always valid. If the HTTP response is an error code it gets lost
why it was closed without any comment?
Originally posted by @Aravin in #23 (comment)
Readme says use requestAccessToken to generate access token but this method is not at all found in connect.js file. How do I generate access token ?
getLTP function is returning undefined in v3.2.0
const ltpResponse = await kiteConnect.getLTP([
'NSE:NIFTY BANK',
'BSE:SENSEX',
]);
Above snippet returning proper data in v3.1.0 whereas same returning undefined
in v3.2.0.
After setting debug true in both versions i can see there is difference between request query string.
v3.1.0 => /quote/ltp?i=NSE%3ANIFTY%20BANK&i=BSE%3ASENSEX
v3.2.0 => /quote/ltp?i[]=NSE:NIFTY+BANK&i[]=BSE:SENSEX
Node: v14.4.0
z
Getting following warning on calling generateSession function with invalid code.
(node:5690) UnhandledPromiseRejectionWarning: #<Object>
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5690) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:5690) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here is runkit link to reproduce this issue.
While using the below code in Angular 9
var jsonDataToken = jsonData.filter(item => item.accessToken !== '')[0];
var KiteConnect = require("kiteconnectts").KiteConnect;
var kc = new KiteConnect({api_key: jsonDataToken.apiKey});
kc.generateSession(jsonDataToken.accessToken, jsonDataToken.secretKey)
.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.
});
}
Hi,
I am looking for admin API i.e I can manage multiple accounts from single class Instance. Is that possible ?
is this sdk support react native?
I'm getting the unhandled rejection fatal error every time even applying catch to the method call:
My code:
Connect
.generateSession(
this.req.body.request_token,
process.env.ZERODHA_API_SECRET,
)
.catch((err) => {
throw err;
});
Error:
unhandledRejection {
status: 'error',
message: 'Token is invalid or has expired.',
data: null,
error_type: 'TokenException'
}
Looking at README, I instantly noticed that the doc is using var
keyword for variables.
Example:
var KiteTicker = require("kiteconnect").KiteTicker;
var ticker = new KiteTicker({
api_key: "api_key",
access_token: "access_token"
});
According to conformance with ECMAScript standard, it would be better if we were to use let
not var
keyword.
Was it not enforced due to breaking changes?
If not, I can raise a PR to update the documentation. ๐
historical promise returning unstructured data like
[ '2017-06-06T09:15:00+0530', 965.7, 973, 964.65, 973, 112886 ]
instead of
[ { date: '2015-02-10T00:00:00+0530', open: 277.5, high: 290.8, low: 275.7, close: 287.3, volume: 22589681 } ]
After looking into source code i noticed that this condition should be response.statusCode
.
Per https://kite.trade/docs/connect/v3/websocket/ , postbacks for trade events should be available, but I see no documentation in the Node client for this
Also, the postback documentation does not contain the order tag. Will this be supplied as well?
Hi, there is any plan to add the typescript types. If not I may consider doing it sometime if its alright.
Please do list out some additional critereon for listing it as @types/kiteconnect
I was wondering if there were any plans for types or typescript support?
Hi,
Do you plan to provide type definitions anytime soon?
Also there is a unofficial library written in TypeScript - https://github.com/anurag2pirad/kiteconnect-ts
Would you validate it for use by us?
Thanks
Hey, this repo has types merged 3 weeks ago. when the new release will get published on npm?
Cancelling regular order fails with 404 exception
{"status":"fail","reason":"404 - "{\"status\": \"error\", \"message\": \"Route not found\", \"error_type\": \"GeneralException\"}""}
When I run the sample code on my pc i get this error:
{
status: 'error',
message: 'Invalid session credentials',
error_type: 'TokenException'
}
ReferenceError: packet is not defined
Instrument token ids returned by your instrument api and token ids inside ticks are different.
I don't know whether it's a bug with the js libarary or on your server side.
For example:
TCS:NSE EQ token id is 2953217 according to instrument API call.
But the token id inside tick data is 11536
TCS:
[ { tradable: true,
mode: 'quote',
instrument_token: 11536,
last_price: 3102,
last_quantity: 10,
average_price: 3112.02,
volume: 1619805,
buy_quantity: 4858,
sell_quantity: 0,
ohlc: { open: 3114.95, high: 3142.35, low: 3090.05, close: 3116.4 },
change: -0.4620716211012736 } ]
how to over come cors issue in kite ticker implemetation. i am using vue js on front end
Hi,
I am trying to connect via nodejs application to kiteconnect.
In the Kite Connect API documentation, the request parameters are as follows:
Parameter | |
---|---|
api_key | The public API key |
request_token | The one-time token obtained after the login flow |
checksum | SHA-256 hash of (api_key + request_token + api_secret) |
Where as in the nodejs version:
kc.requestAccessToken("request_token", "api_secret")
.then(function(response) {
init();
})
.catch(function(err) {
console.log(err.response);
})
The function requestAccessToken does not have the third parameter.
Could you please check if this is by design or a bug?
If it is by design, please do show a working example on how to connect via nodejs(server side).
REgards
Arshdeep
I am using kiteconnectjs version 3.0.0-beta.3 and I am using subscribe() function to fetch the data through websocket.
I found that the last_trade_time and timestamp has delay of about 5:30 Hrs seems its using GST time for calculation.
Below is the data that was received @10:06:20AM
{"tradable":true,"mode":"full","instrument_token":738561,"last_price":1083.3,"last_quantity":33,"average_price":1087.65,"volume":2796789,"buy_quantity":447077,"sell_quantity":420705,"ohlc":{"open":1099.8,"high":1108.9,"low":1073.05,"close":1099.8},"change":-1.5002727768685216,"last_trade_time":"2018-07-16T04:36:19.000Z","timestamp":"2018-07-16T04:36:20.000Z","oi":0,"oi_day_high":0,"oi_day_low":0,"depth":{"buy":[{"quantity":67,"price":1083.4,"orders":1},{"quantity":379,"price":1083.15,"orders":5},{"quantity":5,"price":1083,"orders":1},{"quantity":12,"price":1082.9,"orders":1},{"quantity":118,"price":1082.85,"orders":2}],"sell":[{"quantity":527,"price":1083.5,"orders":5},{"quantity":100,"price":1083.55,"orders":2},{"quantity":350,"price":1083.6,"orders":1},{"quantity":2,"price":1083.75,"orders":1},{"quantity":25,"price":1083.8,"orders":1}]}}
Do I need to manually convert respective fields to IST time or the API will take care of the same.
Thanks
axios <=0.21.0
Severity: high
Server-Side Request Forgery - https://npmjs.com/advisories/1594
Denial of Service - https://npmjs.com/advisories/880
papaparse <5.2.0
Severity: high
Regular Expression Denial of Service - https://npmjs.com/advisories/1515
can be fixed by npm audit fix
Context:
The ticker.ts
lib has a rather elaborate and tedious way of handling the connection which may not suite for all use cases. For starters, you cannot set/change the access_token once a connection has been estabished since the package blocks the main thread. Therefore, although it might be useful for some cases, for any serious solution we should be able to handle the connection in a more customizable fashion.
Question
Most of the library is straight forward and we've used all the necessary variables that we require from the class but apart from the parseBinary
method that follows a elaborate packet convention. It would immesenly help us out if we you can expose to this function as a static method.
Happy to make a PR, once you approve @vividvilla
Thanks!
Sai
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.