fyers-api-v3 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ module.exports.Config = {
2
+ "API":"https://api.fyers.in/api/v2",
3
+ "SYNC_API":"https://api-t1.fyers.in/api/v3",
4
+ "data_Api": "https://api.fyers.in/data-rest/v2",
5
+ "data_Api1": "https://api-t1.fyers.in/data",
6
+ "HSM_SOCKET": "wss://socket.fyers.in/hsm/v1-5/prod",
7
+ "Order_SOCKET": "wss://socket.fyers.in/trade/v3",
8
+ "get_profile" : "/profile",
9
+ "tradebook" : "/tradebook",
10
+ "positions" : "/positions",
11
+ "holdings" : "/holdings",
12
+ "convertPosition" : "/positions",
13
+ "funds" : "/funds",
14
+ "gtt":"/gtt",
15
+ "orders" : "/orders",
16
+ "orders_sync" : "/orders/sync",
17
+ "orderStatus" : "/order-status",
18
+ "marketStatus" : "/marketStatus",
19
+ "auth" : "/generate-authcode",
20
+ "generateAccessToken" : "/validate-authcode",
21
+ "exitPositions" : "/positions",
22
+ "multi_orders" : "/multi-order/sync",
23
+ "history" : "/history",
24
+ "quotes" : "/quotes",
25
+ "market_depth" : "/depth"
26
+ }
@@ -0,0 +1,37 @@
1
+ class ErrorHandler {
2
+ #genricErrorStructure = {s: 'error', code: 500, message: 'Genric Error'}
3
+
4
+
5
+ constructor(errorObject) {
6
+ this.errorObject = errorObject
7
+ }
8
+
9
+ getError() {
10
+ if (this.errorObject && this.errorObject.response && this.errorObject.response.data) {
11
+ return this.errorObject.response.data;
12
+ } else if (this.errorObject && (this.errorObject.code === 'ENOTFOUND')) {
13
+ return this.setError(this.errorObject.errno, this.errorObject.code)
14
+ }else if(this.errorObject.code){
15
+ return this.setError(null, this.errorObject.code)
16
+ } else if(this.errorObject){
17
+ return this.setError(null, this.errorObject)
18
+ } {
19
+ return this.#genricErrorStructure
20
+ }
21
+ }
22
+
23
+
24
+ setError(code, message) {
25
+ if(code){
26
+ this.#genricErrorStructure.code = code
27
+ }
28
+ if(message){
29
+ this.#genricErrorStructure.message = message
30
+ }
31
+
32
+ return this.#genricErrorStructure
33
+ }
34
+
35
+ }
36
+
37
+ module.exports = ErrorHandler;
package/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+
3
+ var fyersModel =require("./apiService/apiService.js");
4
+ var fyersDataSocket =require("./HSM/datasocket.min.js");
5
+ var fyersOrderSocket =require("./ordersocket/fyersSocket.js");
6
+
7
+ module.exports.fyersModel = fyersModel;
8
+ module.exports.fyersDataSocket = fyersDataSocket;
9
+ module.exports.fyersOrderSocket = fyersOrderSocket;
package/logger/log.js ADDED
@@ -0,0 +1,58 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ class Logger {
5
+ constructor(logDirectory = process.cwd()) {
6
+ const currentDate = new Date().toISOString().slice(0, 10);
7
+ this.logFileName = `${currentDate}.log`;
8
+ this.logFilePath = path.join(logDirectory, this.logFileName);
9
+ }
10
+
11
+ log(level, message, data, functionName) {
12
+ const logEntry = {
13
+ level,
14
+ datetime: new Date().toISOString(),
15
+ message,
16
+ data,
17
+ functionName,
18
+ };
19
+
20
+ const logString = JSON.stringify(logEntry) + '\n';
21
+
22
+ fs.appendFile(this.logFilePath, logString, (err) => {
23
+ if (err) {
24
+ console.error('Failed to write to log file:', err);
25
+ }
26
+ });
27
+ }
28
+
29
+ debug(message, data, functionName) {
30
+ this.log('debug', message, data, functionName);
31
+ }
32
+
33
+ info(message, data, functionName) {
34
+ this.log('info', message, data, functionName);
35
+ }
36
+
37
+ warn(message, data, functionName) {
38
+ this.log('warn', message, data, functionName);
39
+ }
40
+
41
+ error(message, data, functionName) {
42
+ this.log('error', message, data, functionName);
43
+ }
44
+ }
45
+
46
+ // Usage example
47
+ // const logger = new Logger(undefined); // Log file will be created in the current working directory with the name "YYYY-MM-DD.log"
48
+ // logger.debug('Debug message', { example: 'data' }, 'myFunction');
49
+ // logger.info('Info message', null, 'myFunction');
50
+ // logger.warn('Warning message', { example: 'data' }, 'myFunction');
51
+ // logger.error('Error message', { example: 'data' }, 'myFunction');
52
+
53
+ // const customLogDirectory = '/home/nihar/fyers_project/node SDK/logger';
54
+ // const customLogger = new Logger(customLogDirectory);
55
+ // customLogger.debug('Custom debug message', null, 'myFunction');
56
+ // customLogger.info('Custom info message', { example: 'data' }, 'myFunction');
57
+
58
+ module.exports = Logger
@@ -0,0 +1,302 @@
1
+ const WebSocket = require('ws');
2
+ let Logger = require("../logger/log.js")
3
+ let { Config } = require("../config/config");
4
+ let mapper =require("./mapper.js")
5
+ var reconnectiontries = 0
6
+ const maxreconnectiontries = 5
7
+ const ordstatobj={11: 4, 12: 4, 20: 4, 21: 4, 22: 6, 23: 6, 24: 6, 25: 6, 26: 6, 90: 2,
8
+ 91: 1, 92: 5, 93: 5, 94: 5, 51: 6, 52: 6, 53: 6, 54: 6, 55: 6, 61: 6, 62: 6, 63: 6,
9
+ 64: 6, 71: 6, 72: 6, 73: 1}
10
+ function datamapper(a,b){
11
+ const result = {};
12
+
13
+ for (const key of Object.keys(b)) {
14
+ if (a.hasOwnProperty(key)) {
15
+ result[b[key]] = a[key];
16
+ }
17
+ }
18
+
19
+ return result;
20
+ }
21
+ /**
22
+ * Class to access order update websocket.
23
+ * @class
24
+ */
25
+ class FyersOrderSocket {
26
+ constructor(authorizationKey, logpath = undefined) {
27
+ this.url = Config.Order_SOCKET;
28
+ this.authorizationKey = authorizationKey;
29
+ this.ws = null;
30
+ this.onErrorCallback = null;
31
+ this.onCloseCallback = null;
32
+ this.onMessageCallback = null;
33
+ this.onOpenCallback = null;
34
+ this.orderscallback = null;
35
+ this.LogPath = logpath;
36
+ this.Logger = new Logger(this.LogPath);
37
+ this.positionscallback = null;
38
+ this.tradescallback = null;
39
+ this.isPingEnabled = true;
40
+ this.pingInterval = null;
41
+ this.autoreconnectinterval = null;
42
+ this.orderUpdates = "orders"
43
+ this.tradeUpdates = "trades"
44
+ this.positionUpdates = "positions"
45
+ this.edis="edis"
46
+ this.pricealerts="pricealerts"
47
+ }
48
+
49
+ /**
50
+ * called to connect to the order socket
51
+ */
52
+ connect() {
53
+ const funcname = "connect"
54
+ const logger = this.Logger
55
+ try {
56
+ logger.debug("initalizing connection to socket", { "accesstoken": this.authorizationKey }, funcname)
57
+ this.ws = new WebSocket(this.url, {
58
+ headers: {
59
+ Authorization: this.authorizationKey,
60
+ },
61
+ });
62
+ this.ws.binaryType = 'arraybuffer';
63
+ this.ws.on('error', (error) => {
64
+ if (this.onErrorCallback) {
65
+ this.onErrorCallback(error);
66
+ }
67
+ else {
68
+ console.log("error occoured", error)
69
+ }
70
+ });
71
+
72
+ this.ws.on('close', (event) => {
73
+ this.stopPing()
74
+ if (this.onCloseCallback) {
75
+ this.onCloseCallback(event);
76
+ }
77
+ else {
78
+ console.log("ws closed", event)
79
+ }
80
+ });
81
+
82
+ this.ws.on('message', (message) => {
83
+ const data = message.toString();
84
+ if (data === 'pong') {
85
+ return
86
+ }
87
+ else {
88
+ var parseddata = JSON.parse(data)
89
+ if (parseddata.hasOwnProperty("orders")) {
90
+ var orderdata=datamapper(parseddata["orders"],mapper.orders)
91
+ orderdata.status=ordstatobj[orderdata.status]
92
+ orderdata['orderNumStatus']=orderdata.id+':'+orderdata.status
93
+ if (this.orderscallback) {
94
+ this.orderscallback({"s":"ok","orders":orderdata})
95
+ }
96
+ else {
97
+ console.log("Orders_internal", {"s":"ok","orders":orderdata})
98
+ }
99
+ }
100
+ else if (parseddata.hasOwnProperty("positions")) {
101
+ var positiondata=datamapper(parseddata["positions"],mapper.position)
102
+ if (this.positionscallback) {
103
+ this.positionscallback({"s":"ok","positions":positiondata})
104
+ }
105
+ else {
106
+ console.log("positions_internal", {"s":"ok","positions":positiondata})
107
+ }
108
+ }
109
+ else if (parseddata.hasOwnProperty("trades")) {
110
+ var tradebookdata=datamapper(parseddata["trades"],mapper.tradebook)
111
+ if (this.tradescallback) {
112
+ this.tradescallback({"s":"ok","trades":tradebookdata})
113
+ }
114
+ else {
115
+ console.log("trades_internal", {"s":"ok","trades":tradebookdata})
116
+ }
117
+ }
118
+ else {
119
+ if (this.onMessageCallback) {
120
+ this.onMessageCallback(parseddata);
121
+ }
122
+ else {
123
+ console.log("message_internal", parseddata)
124
+ }
125
+ }
126
+
127
+ }
128
+ });
129
+
130
+ this.ws.on('open', () => {
131
+ reconnectiontries = 0
132
+ if (this.onOpenCallback) {
133
+ this.onOpenCallback();
134
+ }
135
+ else {
136
+ console.log("connected")
137
+ }
138
+
139
+ if (this.isPingEnabled) {
140
+ this.startPing();
141
+ }
142
+ });
143
+ }
144
+ catch (error) {
145
+ console.log(`Error occured ${funcname}: ${error}`)
146
+ logger.error("unexpected error on connect function", error, funcname)
147
+ }
148
+ }
149
+
150
+ /**
151
+ * used to define onmessage,onerror,onopen,onclose for websocket.
152
+ * @param {string} onwhat - defines for what the callback function is.
153
+ * @param {Function} callback - the callback function.
154
+ * @throws error message if onwhat is not valid.
155
+ */
156
+ on(onwhat, callback) {
157
+ const funcname = "on"
158
+ const logger = this.Logger
159
+ try {
160
+ if (onwhat === 'error') {
161
+ this.onErrorCallback = callback;
162
+ }
163
+ else if (onwhat === 'general') {
164
+ this.onMessageCallback = callback;
165
+ }
166
+ else if (onwhat === 'connect') {
167
+ this.onOpenCallback = callback;
168
+ }
169
+ else if (onwhat === 'close') {
170
+ this.onCloseCallback = callback;
171
+ }
172
+ else if (onwhat === 'orders') {
173
+ this.orderscallback = callback;
174
+ }
175
+ else if (onwhat === 'trades') {
176
+ this.tradescallback = callback;
177
+ }
178
+ else if (onwhat === 'positions') {
179
+ this.positionscallback = callback;
180
+ }
181
+ else {
182
+ console.log("incorrect value passed", onwhat)
183
+ logger.error("wrong onwhat passed", { "onwhat": onwhat }, funcname)
184
+ }
185
+ }
186
+ catch (error) {
187
+ logger.error("unexpected error on 'on' function", error, funcname)
188
+ }
189
+ }
190
+
191
+ /**
192
+ * call to check if datasocket is connected
193
+ */
194
+ isConnected() {
195
+ return this.ws && this.ws.readyState === WebSocket.OPEN;
196
+ }
197
+
198
+ /**
199
+ * starts ping messages to ws
200
+ */
201
+ startPing() {
202
+ this.pingInterval = setInterval(() => {
203
+ if (this.isConnected()) {
204
+ this.ws.send("ping");
205
+ }
206
+ }, 1000);
207
+ }
208
+
209
+ /**
210
+ * stops pinging mechanism
211
+ */
212
+ stopPing() {
213
+ clearInterval(this.pingInterval);
214
+ }
215
+
216
+ /**
217
+ * Subscribe to socket.
218
+ * @param {Array|string} towhat - array or string of what you want to subscribe to.
219
+ */
220
+ subscribe(towhat) {
221
+ const funcname = "subscribe"
222
+ const logger = this.Logger
223
+ try {
224
+ if (this.isConnected()) {
225
+ logger.debug("trying to subscribe to", { "towhat": towhat }, funcname)
226
+ if (towhat.constructor === Array) {
227
+ this.ws.send(JSON.stringify({ "T": "SUB_ORD", "SLIST": towhat, "SUB_T": 1 }));
228
+ }
229
+ else {
230
+ this.ws.send(JSON.stringify({ "T": "SUB_ORD", "SLIST": [towhat], "SUB_T": 1 }));
231
+ }
232
+ }
233
+ else {
234
+ logger.error("websocket is not connected", { "towhat": towhat }, funcname)
235
+ console.log('Cannot send message. WebSocket is not connected.');
236
+ }
237
+ }
238
+ catch (error) {
239
+
240
+ logger.error("unexpected error on subscribe function", error, funcname)
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Unsubscribe to socket.
246
+ * @param {Array|string} towhat - array or string of what you want to unsubscribe to.
247
+ */
248
+ unsubscribe(towhat) {
249
+ const funcname = "unsubscribe"
250
+ const logger = this.Logger
251
+ try {
252
+ if (this.isConnected()) {
253
+ if (towhat.constructor === Array) {
254
+ logger.debug("trying to unsubscribe to", { "towhat": towhat }, funcname)
255
+ this.ws.send(JSON.stringify({ "T": "SUB_ORD", "SLIST": towhat, "SUB_T": -1 }));
256
+ }
257
+ else {
258
+ this.ws.send(JSON.stringify({ "T": "SUB_ORD", "SLIST": [towhat], "SUB_T": -1 }));
259
+ }
260
+ }
261
+ else {
262
+ logger.error("websocket is not connected", { "towhat": towhat }, funcname)
263
+ console.log('Cannot send message. WebSocket is not connected.');
264
+ }
265
+ }
266
+ catch (error) {
267
+ logger.error("unexpected error on unsubscribe function", error, funcname)
268
+ }
269
+ }
270
+
271
+ /**
272
+ * call to close the datasocket.
273
+ */
274
+ close() {
275
+ if (this.ws && this.isConnected) {
276
+ clearInterval(this.autoreconnectinterval)
277
+ this.stopPing()
278
+ this.ws.close();
279
+ }
280
+ }
281
+
282
+ /**
283
+ * call to enable autoreconnect functionality of websocket.
284
+ */
285
+ autoreconnect() {
286
+ this.autoreconnectinterval = setInterval(() => {
287
+ if ((!this.isConnected()) && (reconnectiontries < maxreconnectiontries)) {
288
+ console.log("trying to reconnect ", reconnectiontries + 1)
289
+ reconnectiontries++
290
+ this.connect()
291
+ } else if (reconnectiontries >= maxreconnectiontries) {
292
+ console.log("max autoconnect tries exceeded")
293
+ clearInterval(this.autoreconnectinterval)
294
+ this.stopPing()
295
+ reconnectiontries = 0
296
+ }
297
+ }, 5000);
298
+
299
+ }
300
+ }
301
+
302
+ module.exports = FyersOrderSocket
@@ -0,0 +1,77 @@
1
+ const ordersMapper = {
2
+ 'client_id': 'clientId',
3
+ 'id': 'id',
4
+ 'id_parent': 'parentId',
5
+ 'id_exchange': 'exchOrdId',
6
+ 'qty': 'qty',
7
+ 'qty_remaining': 'remainingQuantity',
8
+ 'qty_filled': 'filledQty',
9
+ 'price_limit': 'limitPrice',
10
+ 'price_stop': 'stopPrice',
11
+ 'tradedPrice': 'price_traded',
12
+ 'ord_type': 'type',
13
+ 'fy_token': 'fyToken',
14
+ 'exchange': 'exchange',
15
+ 'segment': 'segment',
16
+ 'symbol': 'symbol',
17
+ 'instrument': 'instrument',
18
+ 'oms_msg': 'message',
19
+ 'offline_flag': 'offlineOrder',
20
+ 'time_oms': 'orderDateTime',
21
+ 'validity': 'orderValidity',
22
+ 'product_type': 'productType',
23
+ 'tran_side': 'side',
24
+ 'ord_status': 'status',
25
+ 'ord_source': 'source',
26
+ 'symbol_exch': 'ex_sym',
27
+ 'symbol_desc': 'description'
28
+ }
29
+
30
+ const positionbookMapper = {
31
+ 'symbol': 'symbol',
32
+ 'id': 'id',
33
+ 'buy_avg': 'buyAvg',
34
+ 'buy_qty': 'buyQty',
35
+ 'buy_val': 'buyVal',
36
+ 'sell_avg': 'sellAvg',
37
+ 'sell_qty': 'sellQty',
38
+ 'sell_val': 'sellVal',
39
+ 'net_avg': 'netAvg',
40
+ 'net_qty': 'netQty',
41
+ 'tran_side': 'side',
42
+ 'qty': 'qty',
43
+ 'product_type': 'productType',
44
+ 'pl_realized': 'realized_profit',
45
+ 'rbirefrate': 'rbiRefRate',
46
+ 'fy_token': 'fyToken',
47
+ 'exchange': 'exchange',
48
+ 'segment': 'segment',
49
+ 'day_buy_qty': 'dayBuyQty',
50
+ 'day_sell_qty': 'daySellQty',
51
+ 'cf_buy_qty': 'cfBuyQty',
52
+ 'cf_sell_qty': 'cfSellQty',
53
+ 'qty_multiplier': 'qtyMulti_com',
54
+ 'pl_total': 'pl',
55
+ 'cross_curr_flag': 'crossCurrency',
56
+ 'pl_unrealized': 'unrealized_profit',
57
+ }
58
+
59
+ const tradebookMapper = {
60
+ 'id_fill': 'tradeNumber',
61
+ 'id': 'orderNumber',
62
+ 'qty_traded': 'tradedQty',
63
+ 'price_traded': 'tradePrice',
64
+ 'traded_val': 'tradeValue',
65
+ 'product_type': 'productType',
66
+ 'client_id': 'clientId',
67
+ 'id_exchange': 'exchangeOrderNo',
68
+ 'ord_type': 'orderType',
69
+ 'tran_side': 'side',
70
+ 'symbol': 'symbol',
71
+ 'fill_time': 'orderDateTime',
72
+ 'fy_token': 'fyToken',
73
+ 'exchange': 'exchange',
74
+ 'segment': 'segment',
75
+ }
76
+
77
+ module.exports = { "orders": ordersMapper, "position": positionbookMapper, "tradebook": tradebookMapper }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "fyers-api-v3",
3
+ "version": "1.0.0",
4
+ "description": "connect to fyers API",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "",
10
+ "license": "ISC",
11
+ "dependencies": {
12
+ "axios": "^1.3.5",
13
+ "jsonwebtoken": "^9.0.1",
14
+ "ws": "^8.13.0"
15
+ },
16
+ "devDependencies": {
17
+ "javascript-obfuscator": "^4.0.2"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/FyersDev/fyers-api-js.git"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/FyersDev/fyers-api-js/issues"
25
+ },
26
+ "homepage": "https://github.com/FyersDev/fyers-api-js#readme"
27
+ }
package/sample/api.js ADDED
@@ -0,0 +1,46 @@
1
+ var fyersModel= require("../index.js").fyersModel
2
+
3
+ var fyers= new fyersModel()
4
+
5
+ fyers.setAppId("QCxxxx25-1xx")
6
+
7
+ fyers.setRedirectUrl("https://xxx.xxxxxxx.xxxx")
8
+ // generate authcode
9
+ ////////////////////////////
10
+
11
+ // var URL=fyers.generateAuthCode()
12
+
13
+ // console.log(URL)
14
+
15
+ // after getting authcode
16
+
17
+ ////////////////////////////
18
+
19
+ // generate accesstoken
20
+ ////////////////////////////
21
+ // var authcode=""
22
+
23
+ // fyers.generate_access_token({"client_id":fyers.AppID,"secret_key":"4362L6SS2C","auth_code":authcode}).then((response)=>{
24
+ // console.log(response)
25
+ // })
26
+ ////////////////////////////
27
+
28
+ fyers.setAccessToken("")
29
+
30
+ fyers.get_profile().then((response)=>{
31
+ console.log(response)
32
+ }).catch((err)=>{
33
+ console.log(err)
34
+ })
35
+
36
+ fyers.getQuotes(["NSE:SBIN-EQ","NSE:TCS-EQ"]).then((response)=>{
37
+ console.log(response)
38
+ }).catch((err)=>{
39
+ console.log(err)
40
+ })
41
+
42
+ fyers.getMarketDepth({"symbol":["NSE:SBIN-EQ","NSE:TCS-EQ"],"ohlcv_flag":1}).then((response)=>{
43
+ console.log(response)
44
+ }).catch((err)=>{
45
+ console.log(err)
46
+ })
@@ -0,0 +1,25 @@
1
+ let DataSocket = require("../index.js").fyersDataSocket;
2
+
3
+ var skt= DataSocket.getInstance("")
4
+
5
+ skt.on("connect",function(){skt.subscribe(['NSE:IDEA-EQ',"NSE:SBIN-EQ"],false,1)
6
+ skt.mode(skt.FullMode,1)
7
+ console.log(skt.isConnected())
8
+ // skt.mode(skt.LiteMode,[11,12,13])
9
+ // skt.channelresume(2)
10
+ // skt.unsubscribe(['NSE:IDEA-EQ'],false,1)
11
+ })
12
+
13
+ skt.on("message",function(message){
14
+ console.log({"TEST":message})
15
+ })
16
+
17
+ skt.on("error",function(message){
18
+ console.log("erroris",message)
19
+ })
20
+
21
+ skt.on("close",function(){
22
+ console.log("socket closed")
23
+ })
24
+ skt.connect()
25
+ skt.autoreconnect()
@@ -0,0 +1,29 @@
1
+ var fyersOrderSocket= require("../index.js").fyersOrderSocket
2
+
3
+ var skt=new fyersOrderSocket("")
4
+
5
+ skt.on("error",function (errmsg) {
6
+ console.log(errmsg)
7
+ })
8
+ skt.on('general',function (msg) {
9
+ console.log(msg)
10
+ })
11
+ skt.on('connect',function () {
12
+ skt.subscribe([skt.orderUpdates,skt.tradeUpdates,skt.positionUpdates,skt.edis,skt.pricealerts])
13
+ console.log(skt.isConnected())
14
+ })
15
+ skt.on('close',function () {
16
+ console.log('closed')
17
+ })
18
+ skt.on('orders',function (msg) {
19
+ console.log("orders",msg)
20
+ })
21
+ skt.on('trades',function (msg) {
22
+ console.log('trades',msg)
23
+ })
24
+ skt.on('positions',function (msg) {
25
+ console.log('positions',msg)
26
+ })
27
+ skt.autoreconnect()
28
+ skt.connect()
29
+