forked from dsuraj72/smartapi-javascript
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathsmartapi-connect.js
More file actions
519 lines (466 loc) · 11.7 KB
/
smartapi-connect.js
File metadata and controls
519 lines (466 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
'use strict';
let axios = require('axios');
let querystring = require('querystring');
let address = require('address');
let publicIp = require('public-ip');
let { API } = require('../config/api');
/**
* @constructor
* @name SmartApi
* @param {Object} params
* @param {string} api_key
* @param {string} root
* @param {string} timeout
* @param {string} debug
* @param {string} access_token
* @param {string} refresh_token
* @param {string} default_login_uri
* @param {string} session_expiry_hook
*/
var SmartApi = function (params) {
var self = this;
self.totp = params.totp;
self.api_key = params.api_key;
self.client_code = params.client_code || null;
self.root = params.root || API.root;
self.timeout = params.timeout || API.timeout;
self.debug = params.debug || API.debug;
self.access_token = params.access_token || null;
self.refresh_token = params.refresh_token || null;
self.default_login_uri = API.login;
self.session_expiry_hook = null;
self.local_ip = null;
self.mac_addr = null;
self.public_ip = null;
address(function (err, addrs) {
self.local_ip = addrs !== undefined ? addrs.ip : '192.168.168.168';
self.mac_addr =
addrs !== undefined ? addrs.mac : 'fe80::216e:6507:4b90:3719';
});
(async () => {
self.public_ip = await publicIp.v4();
})();
var requestInstance = axios.create({
baseURL: self.root,
timeout: self.timeout,
headers: {
'X-ClientLocalIP': self.local_ip, //'192.168.168.168',
'X-ClientPublicIP': self.public_ip, //'106.193.147.98',
'X-MACAddress': self.mac_addr, //'fe80::216e:6507:4b90:3719',
},
paramsSerializer: function (params) {
return querystring.stringify(params);
},
});
// Set content type as form encoded for PUT and POST
requestInstance.defaults.headers.post['Content-Type'] = 'application/json';
requestInstance.defaults.headers.put['Content-Type'] = 'application/json';
// 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(
(response) => {
try {
if (self.debug) console.log(response);
// console.log('response::', response);
if (response?.status === 200) {
if (response?.data?.success || response?.data?.status) {
return response.data;
} else {
// USER INPUT OR TOKEN RELATED ERROR TO BE HANDLED HERE
if (
response?.data?.errorCode === 'AG8001' &&
self.session_expiry_hook !== null
) {
self.session_expiry_hook();
}
// REFRESH TOKEN ISSUES
// else if (response.data.errorCode === "AB8050") {
// // CUSTOM
// }
return response?.data;
}
} else {
return response?.data;
}
} catch (error) {
return [];
}
},
(error) => {
try {
// console.log(error);
let errorObj = {};
if (error?.response?.status) {
errorObj.status = error?.response?.status;
errorObj.message = error?.response?.statusText;
} else {
errorObj.status = 500;
errorObj.message = 'Error';
}
return errorObj;
// return Promise.reject(errorObj);
} catch (error) {
return [];
}
}
);
/**
* Used to set access_token
* @method setAccessToken
* @param {string} access_token
*/
self.setAccessToken = function (access_token) {
self.access_token = access_token;
};
/**
* Description
* @method setPublicToken
* @param {string} refresh_token
*/
self.setPublicToken = function (refresh_token) {
self.refresh_token = refresh_token;
};
self.setClientCode = function (client_code) {
self.client_code = client_code;
};
/**
* Description
* @method setSessionExpiryHook
* @param {function} cb Callback
*/
self.setSessionExpiryHook = function (cb) {
self.session_expiry_hook = cb;
};
/**
* Description
* @method generateSession
* @param {string} clientcode
* @param {string} password
* @param {string} totp
*/
self.generateSession = function (client_code, password, totp) {
let params = {
clientcode: client_code,
password: password,
totp: totp,
};
let token_data = post_request('user_login', params);
token_data
.then((response) => {
if (response.status) {
// console.log(response.data.jwtToken)
self.setClientCode(client_code);
self.setAccessToken(response.data.jwtToken);
self.setPublicToken(response.data.refreshToken);
}
})
.catch(function (err) {
throw err;
});
return token_data;
};
/**
* Description
* @method getLoginURL
*/
self.getLoginURL = function () {
return self.default_login_uri + '?api_key=' + self.api_key;
};
/**
* Description
* @method generateToken
* @param {string} refresh_token
*/
self.generateToken = function (refresh_token) {
let token_data = post_request('generate_token', {
refreshToken: refresh_token,
});
token_data.then((response) => {
if (response.status) {
self.setAccessToken(response.data.jwtToken);
self.setPublicToken(token_data.data.refreshToken);
}
});
return token_data;
};
/**
* Description
* @method logout
*/
self.logout = function (client_code) {
if (client_code != null)
return post_request('logout', { clientcode: client_code });
else
return {
status: 500,
message: 'Client Code is required.',
};
};
/**
* Description
* @method getProfile
*/
self.getProfile = function () {
return get_request('get_profile');
};
/**
* Description
* @method placeOrder
* @param {object} params
* @param {string} variety (NORMAL or STOPLOSS)
* @param {string} tradingsymbol (RELIANCE-EQ, INFY-EQ, SBIN-EQ)
* @param {string} exchange (NSE or BSE)
* @param {string} transactiontype (BUY or SELL)
* @param {string} ordertype (MARKET, LIMIT, STOPLOSS_MARKET, STOPLOSS_LIMIT)
* @param {string} producttype (DELIVERY, MARGIN, INTRADAY, AMO_DELIVERY, AMO_INTRADAY)
* @param {number} price
* @param {number} quantity
* @param {number} disclosedquantity
* @param {string} duration (DAY or IOC)
*/
self.placeOrder = function (params) {
return post_request('order_place', params);
};
/**
* Description
* @method modifyOrder
* @param {object} params
* @param {string} orderid
* @param {string} variety (NORMAL or STOPLOSS)
* @param {string} tradingsymbol (RELIANCE-EQ, INFY-EQ, SBIN-EQ)
* @param {string} exchange (NSE or BSE)
* @param {string} transactiontype (BUY or SELL)
* @param {string} ordertype (MARKET, LIMIT, STOPLOSS_MARKET, STOPLOSS_LIMIT)
* @param {string} producttype (DELIVERY, MARGIN, INTRADAY, AMO_DELIVERY, AMO_INTRADAY)
* @param {number} price
* @param {number} quantity
* @param {number} disclosedquantity
* @param {string} duration (DAY or IOC)
*/
self.modifyOrder = function (params) {
return post_request('order_modify', params);
};
/**
* Description
* @method cancelOrder
* @param {string} order_id
*/
self.cancelOrder = function (params) {
return post_request('order_cancel', params);
};
/**
* Description
* @method getOrderBook
*/
self.getOrderBook = function () {
return get_request('order_get_book');
};
/**
* Description
* @method getTradeBook
*/
self.getTradeBook = function () {
return get_request('get_tradebook');
};
/**
* Description
* @method getRMS
*/
self.getRMS = function () {
return get_request('get_rms');
};
/**
* Description
* @method getHolding
*/
self.getHolding = function () {
return get_request('get_holding');
};
/**
* Description
* @method getPosition
*/
self.getPosition = function () {
return get_request('get_position');
};
/**
* Description
* @method convertPosition
* @param {object} params
* @param {string} exchange
* @param {string} symboltoken
* @param {string} producttype
* @param {string} newproducttype
* @param {string} tradingsymbol
* @param {string} symbolname
* @param {string} instrumenttype
* @param {string} priceden
* @param {string} pricenum
* @param {string} genden
* @param {string} gennum
* @param {string} precision
* @param {string} multiplier
* @param {string} boardlotsize
* @param {string} buyqty
* @param {string} sellqty
* @param {string} buyamount
* @param {string} sellamount
* @param {string} transactiontype
* @param {string} quantity
* @param {string} type
*/
self.convertPosition = function (params) {
return post_request('convert_position', params);
};
/**
* Description
* @method createRule
* @param {object} params
* @param {string} tradingsymbol
* @param {string} symboltoken
* @param {string} exchange
* @param {string} producttype
* @param {string} side
* @param {string} price
* @param {string} qty
* @param {string} disclosedqty
* @param {string} triggerprice
* @param {string} timeperiod
*/
self.createRule = function (params) {
return post_request('create_rule', params);
};
/**
* Description
* @method modifyRule
* @param {object} params
* @param {string} id
* @param {string} symboltoken
* @param {string} exchange
* @param {string} qty
*/
self.modifyRule = function (params) {
return post_request('modify_rule', params);
};
/**
* Description
* @method cancelRule
* @param {object} params
* @param {string} id
* @param {string} symboltoken
* @param {string} exchange
*/
self.cancelRule = function (params) {
return post_request('cancel_rule', params);
};
/**
* Description
* @method ruleDetails
* @param {object} params
* @param {string} id
*/
self.ruleDetails = function (params) {
return post_request('rule_details', params);
};
/**
* Description
* @method ruleList
* @param {object} params
* @param {Array} status
* @param {string} page
* @param {string} count
*/
self.ruleList = function (params) {
// Array length check
if (Array.isArray(params.status)) return post_request('rule_list', params);
else
return {
status: 500,
message:
'Invalid status. Please refer Smart API documentation for more details.',
};
};
/**
* Description
* @method marketData
* @param {object} params
* @param {string} mode
* @param {string} exchangeTokens
*/
self.marketData = function (params){
return post_request('market_data',params);
};
/**
* Description
* @method ruleList
* @param {object} params
* @param {string} exchange
* @param {string} symboltoken
* @param {string} interval
* @param {string} fromdate
* @param {string} todate
*/
self.getCandleData = function (params) {
return post_request('candle_data', params);
};
function get_request(route, params, responseType, responseTransformer) {
return request_util(
route,
'GET',
params || {},
responseType,
responseTransformer
);
}
function post_request(route, params, responseType, responseTransformer) {
return request_util(
route,
'POST',
params || {},
responseType,
responseTransformer
);
}
function request_util(
route,
method,
params,
responseType,
responseTransformer
) {
let url = API[route],
payload = null;
if (method !== 'GET' || method !== 'DELETE') {
payload = params;
}
let options = {
method: method,
url: url,
// params: queryParams,
data: JSON.stringify(payload),
// Set auth header
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'X-UserType': 'USER',
'X-SourceID': 'WEB',
'X-PrivateKey': self.api_key, // ? self.api_key : 'smartapi_key'
},
};
// console.log('options', options);
if (self.access_token) {
options['headers']['Authorization'] = 'Bearer ' + self.access_token;
}
// Set response transformer
if (responseTransformer) {
options.transformResponse =
axios.defaults.transformResponse.concat(responseTransformer);
}
return requestInstance.request(options);
}
};
module.exports = SmartApi;