-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathconnect.ts
1246 lines (1127 loc) · 41.5 KB
/
connect.ts
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
import axios, { AxiosInstance, AxiosRequestConfig, AxiosTransformer, Method } from 'axios';
import csvParse from 'papaparse';
import sha256 from 'crypto-js/sha256';
import qs from 'qs';
import utils from './utils';
import { KiteConnectParams, Varieties, GTTStatusTypes, AnyObject, Order, MarginOrder, VirtualContractParam, TransactionTypes, KiteConnectInterface, CancelOrderParams, ExitOrderParams, ModifyGTTParams, ModifyOrderParams, PlaceGTTParams, PlaceMFOrderParams, PlaceOrderParams, ConvertPositionParams, Exchanges } from '../interfaces';
import { DEFAULTS, ROUTES } from '../constants';
/**
* @classdesc API client class. In production, you may initialise a single instance of this class per `api_key`.
* This module provides an easy to use abstraction over the HTTP APIs.
* The HTTP calls have been converted to methods and their JSON responses.
* See the **[Kite Connect API documentation](https://kite.trade/docs/connect/v3/)**
* for the complete list of APIs, supported parameters and values, and response formats.
*
* Getting started with API
* ------------------------
* ~~~~
*
* import { KiteConnect } from 'kiteconnect';
*
* const apiKey = 'your_api_key'
* const apiSecret = 'your_api_secret'
* const requestToken = 'your_request_token'
*
* const kc = new KiteConnect({ api_key: apiKey })
*
* async function init() {
* try {
* await generateSession()
* await getProfile()
* } catch (err) {
* console.error(err)
* }
* }
*
* 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)
* }
* }
*
* 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 return a promise which you can `await` to handle asynchronously.
*
* ~~~~
* try {
* const result = await kiteConnectApiCall;
* // On success
* } catch (error) {
* // On rejection
* }
* ~~~~
*
* @constructor
* @name KiteConnect
*
* @param {Object} params Init params.
* @param {string} params.api_key API key issued to you.
* @param {string} [params.access_token=null] 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.
* @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 {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 <caption>Initialize KiteConnect object</caption>
* const kc = new KiteConnect({ api_key: apiKey })
*/
export class KiteConnect implements KiteConnectInterface {
/**
* @type {string}
*/
api_key: string;
/**
* @type {?(string | null)}
*/
access_token?: string | null;
/**
* @type {?string}
*/
root?: string;
/**
* @type {?string}
*/
login_uri?: string;
/**
* @type {?boolean}
*/
debug?: boolean;
/**
* @type {?number}
*/
timeout?: number;
/**
* @type {?(function | null)}
*/
session_expiry_hook?: (() => void) | null;
/**
* @type {?string}
*/
default_login_uri?: string;
/**
* @private
* @type {AxiosInstance}
*/
private requestInstance: AxiosInstance;
// Constants
readonly PRODUCT_MIS: string = 'MIS';
readonly PRODUCT_CNC: string = 'CNC';
readonly PRODUCT_NRML: string = 'NRML';
// Order types
readonly ORDER_TYPE_MARKET: string = 'MARKET';
readonly ORDER_TYPE_LIMIT: string = 'LIMIT';
readonly ORDER_TYPE_SLM: string = 'SL-M';
readonly ORDER_TYPE_SL: string ='SL';
// Varieties
readonly VARIETY_REGULAR: string = 'regular';
readonly VARIETY_CO: string = 'co';
readonly VARIETY_AMO: string = 'amo';
readonly VARIETY_ICEBERG: string = 'iceberg';
readonly VARIETY_AUCTION: string = 'auction';
// Transaction types
readonly TRANSACTION_TYPE_BUY: string = 'BUY';
readonly TRANSACTION_TYPE_SELL: string = 'SELL';
// Validities
readonly VALIDITY_DAY: string = 'DAY';
readonly VALIDITY_IOC: string = 'IOC';
readonly VALIDITY_TTL: string = 'TTL';
// Exchanges
readonly EXCHANGE_NSE: string = 'NSE';
readonly EXCHANGE_BSE: string = 'BSE';
readonly EXCHANGE_NFO: string = 'NFO';
readonly EXCHANGE_CDS: string = 'CDS';
readonly EXCHANGE_BCD: string = 'BCD';
readonly EXCHANGE_BFO: string = 'BFO';
readonly EXCHANGE_MCX: string = 'MCX';
// Margins segments
readonly MARGIN_EQUITY: string = 'equity';
readonly MARGIN_COMMODITY: string = 'commodity';
// Statuses
readonly STATUS_CANCELLED: string = 'CANCELLED';
readonly STATUS_REJECTED: string = 'REJECTED';
readonly STATUS_COMPLETE: string = 'COMPLETE';
// GTT types
readonly GTT_TYPE_OCO: string = 'two-leg';
readonly GTT_TYPE_SINGLE: string = 'single';
// GTT statuses
readonly GTT_STATUS_ACTIVE: string = 'active';
readonly GTT_STATUS_TRIGGERED: string = 'triggered';
readonly GTT_STATUS_DISABLED: string = 'disabled';
readonly GTT_STATUS_EXPIRED: string = 'expired';
readonly GTT_STATUS_CANCELLED: string = 'cancelled';
readonly GTT_STATUS_REJECTED: string = 'rejected';
readonly GTT_STATUS_DELETED: string = 'deleted';
// Position types
readonly POSITION_TYPE_DAY: string = 'day';
readonly POSITION_TYPE_OVERNIGHT: string = 'overnight';
/**
* Creates an instance of KiteConnect.
*
* @constructor
* @param {KiteConnectParams} params - The configuration parameters for initializing the instance.
*/
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_login_uri = DEFAULTS.login;
this.session_expiry_hook = null;
this.requestInstance = this.createAxiosInstance();
}
/**
* Creates a custom Axios instance with the provided configuration.
*
* @private
* @returns {AxiosInstance} Custom Axios instance
*/
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) {
const searchParams = new URLSearchParams();
for (const key in params) {
if (params.hasOwnProperty(key)) {
const value = params[key];
if (Array.isArray(value)) {
value.forEach(val => searchParams.append(key, val));
} else {
searchParams.append(key, value);
}
}
}
return searchParams.toString();
}
});
// Add a request interceptor
requestInstance.interceptors.request.use((request) => {
if (this.debug) console.log(request);
return request;
});
// Add a response interceptor
requestInstance.interceptors.response.use((response) => {
if (this.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 + ')'
};
}
}, (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' && 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
}
return Promise.reject(resp);
});
return requestInstance;
}
/**
* Sets the access token for the API client.
*
* @param accessToken The access token to set.
* @returns {void}
*/
setAccessToken(accessToken: string): void {
this.access_token = accessToken;
}
/**
* Sets a callback function to be invoked when the session expires.
*
* @param cb - The callback function to set as the session expiry hook.
* @returns void
*/
setSessionExpiryHook = function (cb: Function) {
this.session_expiry_hook = cb;
};
/**
* Returns the login URL with the embedded API key.
*
* @remarks
* This method constructs and returns the login URL with the embedded API key.
*
* @returns The login URL with the embedded API key.
*/
getLoginURL() {
return `${this.default_login_uri}?api_key=${this.api_key}&v=3`;
};
/**
* Generates a session using the provided request token and API secret.
*
* @remarks
* This method generates a session by sending a request to the API with the provided request token and API secret.
* Upon successful completion, the method resolves with the session details, including the access token. If an error occurs,
* the method rejects with an error.
*
* @param {string} request_token - The request token obtained during the login flow.
* @param {string} api_secret - The API secret associated with the user's account.
* @returns {Promise<any>} A promise that resolves when the session generation is successful and rejects if an error occurs.
*/
generateSession(request_token: string, api_secret: string): Promise<any> {
return new Promise((resolve, reject) => {
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((resp: any) => {
// Set access token.
if (resp && resp.access_token) {
this.setAccessToken(resp.access_token);
}
return resolve(resp);
}).catch(function (err: Error) {
return reject(err);
});
});
};
/**
* Invalidates the access token.
*
* @remarks
* This method sends a DELETE request to invalidate the specified access token.
* If no access token is provided, the method uses the default access token associated with the instance.
*
* @param {string} [access_token] - The access token to invalidate. If not provided, the default access token is used.
* @returns {Promise<boolean>} A promise that resolves when the DELETE request is complete.
*/
invalidateAccessToken(access_token?: string): Promise<any> {
return this._delete('api.token.invalidate', {
api_key: this.api_key,
access_token: access_token || this.access_token,
});
};
/**
* Renews the access token using the provided refresh token and API secret.
*
* @remarks
* This method sends a request to renew the access token using the given refresh token
* and API secret. If the renewal is successful, the promise resolves to the renewed
* access token. If the renewal fails, the promise is rejected with an error message.
*
* @param {string} refresh_token - The refresh token used for renewing the access token.
* @param {string} api_secret - The API secret required for the renewal process.
* @returns {Promise<any>} A promise that resolves to the renewed access token if successful.
* If the renewal fails, the promise is rejected with an error message.
*/
renewAccessToken(refresh_token: string, api_secret: string): Promise<any> {
return new Promise((resolve, reject) => {
const checksum = sha256(this.api_key + refresh_token + api_secret).toString();
const p = this._post('api.token.renew', {
api_key: this.api_key,
refresh_token: refresh_token,
checksum: checksum
});
p.then((resp: any) => {
if (resp && resp.access_token) {
this.setAccessToken(resp.access_token);
}
return resolve(resp);
}).catch(function (err: Error) {
return reject(err);
});
});
};
/**
* Invalidates the specified refresh token.
*
* @param {string} refresh_token - The refresh token to invalidate.
* @returns A promise that resolves when the DELETE request is complete.
*/
invalidateRefreshToken = function (refresh_token: string): Promise<void> {
return this._delete('api.token.invalidate', {
api_key: this.api_key,
refresh_token: refresh_token
});
};
/**
* Retrieves the user's profile.
*
* @returns {Promise<any>} A promise that resolves with the user's profile data.
*/
getProfile(): Promise<any> {
return this._get('user.profile');
};
/**
* Retrieves margin details for the specified segment or all segments.
*
* @remarks
* If a segment is specified, margin details for that segment are retrieved. Otherwise, margin details for all segments are retrieved.
*
* @param {?string} segment - Optional. The segment for which to retrieve margin details.
* @returns {Promise<any>} A promise that resolves with the margin details.
* If a segment is specified, the promise resolves with margin details for that segment.
* If no segment is specified, the promise resolves with margin details for all segments.
*/
getMargins(segment?: string): Promise<any> {
if (segment) {
return this._get('user.margins.segment', { 'segment': segment });
} else {
return this._get('user.margins');
}
};
/**
* Places an order with the specified variety and parameters.
*
* @param {Varieties} variety - The variety of the order.
* @param {PlaceOrderParams} params - The parameters for the order.
* @returns {Promise<any>} A promise that resolves with the result of the order placement.
*/
placeOrder(variety: Varieties, params: PlaceOrderParams): Promise<any> {
params.variety = variety;
return this._post('order.place', params);
};
/**
* @param {Varieties} variety - The variety of the order.
* @param {(string | number)} order_id - The ID of the order to modify.
* @param {ModifyOrderParams} params - The parameters for modifying the order.
* @returns {Promise<any>} A Promise that resolves with the modified order details.
*/
modifyOrder(variety: Varieties, order_id: string | number, params: ModifyOrderParams): Promise<any> {
params.variety = variety;
params.order_id = order_id;
return this._put('order.modify', params);
};
/**
* @param {Varieties} variety - The variety of the order.
* @param {(string | number)} order_id - The ID of the order to modify.
* @param {?CancelOrderParams} [params] - The parameters for cancelling the order.
* @returns {Promise<any>}
*/
cancelOrder(variety: Varieties, order_id: string | number, params?: CancelOrderParams): Promise<any> {
params = params || {};
params.variety = variety;
params.order_id = order_id;
return this._delete('order.cancel', params);
};
/**
* @param {Varieties} variety - The variety of the order.
* @param {string} order_id - The ID of the order to modify.
* @param {ExitOrderParams} params - The parameters required for exiting the order.
* @returns {Promise<any>}
*/
exitOrder(variety: Varieties, order_id: string, params: ExitOrderParams): Promise<any> {
return this.cancelOrder(variety, order_id, params);
};
/**
* Retrieves orders.
*
* @returns {Promise<any>} A Promise that resolves to the retrieved orders.
*/
getOrders(): Promise<any> {
return this._get('orders', null, null, this.formatResponse);
};
/**
* Retrieves the order history for a given order ID.
*
* @param {(string | number)} order_id - The ID of the order to retrieve history for.
* @returns {Promise<any>} - A Promise that resolves to the order history information.
* The resolved value can be of any type.
*/
getOrderHistory(order_id: string | number): Promise<any> {
return this._get('order.info', { 'order_id': order_id }, null, this.formatResponse);
};
/**
* Retrieves trades data.
*
* @remarks
* This method retrieves trades data from the server.
*
* @returns {Promise<any>} A Promise that resolves with the trades data.
*/
getTrades(): Promise<any> {
return this._get('trades', null, null, this.formatResponse);
};
/**
* Retrieves the trades associated with a specific order.
*
* @param {string | number} order_id - The ID of the order.
* @returns {Promise<any>} A Promise resolving to the trades associated with the order.
*/
getOrderTrades(order_id: string | number): Promise<any> {
return this._get('order.trades', { 'order_id': order_id }, null, this.formatResponse);
};
/**
* Calculates margins for the specified orders.
*
* @param {MarginOrder[]} orders - The array of orders for which margins are to be calculated.
* @param {string} [mode='compact'] - The mode for margin calculation (optional).
* @returns {Promise<any>} - A Promise that resolves with the calculated margins.
*/
orderMargins(orders: MarginOrder[], mode: string = 'compact'): Promise<any> {
return this._post('order.margins', orders, null, undefined, true,
{ 'mode': mode });
};
/**
* Retrieves the virtual contract note for the specified orders.
*
* @param {VirtualContractParam[]} orders - The array of orders for which to retrieve the virtual contract note.
* @returns {Promise<any>} A Promise that resolves with the virtual contract note.
*/
getvirtualContractNote(orders: VirtualContractParam[]): Promise<any> {
return this._post('order.contract_note', orders, null, undefined, true, null);
};
/**
* Retrieves margin information for a basket of orders.
*
* @param {Order[]} orders - The array of orders for which to retrieve margin information.
* @param {boolean} [consider_positions=true] - Flag indicating whether to consider existing positions.
* @param {*} [mode='compact'] - The mode of operation. Default is compact.
* @returns {Promise<any>} - A Promise that resolves to margin information for the basket of orders.
*/
orderBasketMargins(orders: Order[], consider_positions: boolean = true, mode: string = 'compact'): Promise<any> {
return this._post('order.margins.basket', orders, null, undefined, true,
{ 'consider_positions': consider_positions, 'mode': mode });
};
/**
* Retrieves the holdings from the portfolio.
*
* @returns {Promise<any>} A Promise that resolves with the holdings data.
*/
getHoldings(): Promise<any> {
return this._get('portfolio.holdings');
};
/**
* Retrieves auction instruments.
*
* @remarks
* This method retrieves auction instruments from the portfolio holdings.
*
* @returns {Promise<any>} A Promise that resolves with the auction instruments.
*/
getAuctionInstruments(): Promise<any> {
return this._get('portfolio.holdings.auction');
};
/**
* Retrieves positions from the portfolio.
*
* @returns {Promise<any>} A promise that resolves with the positions data.
*/
getPositions(): Promise<any> {
return this._get('portfolio.positions');
};
/**
* Converts a position based on the provided parameters.
*
* @param {ConvertPositionParams} params - The parameters for converting the position.
* @returns {Promise<any>} A Promise that resolves with the result of the conversion.
*
*/
convertPosition(params: ConvertPositionParams): Promise<any> {
return this._put('portfolio.positions.convert', params);
};
/**
* Retrieves instruments based on the provided exchange.
*
* @param {Exchanges} exchange - Exchange name
* @returns {Promise<any>} - A Promise resolving to the fetched instruments.
*/
getInstruments(exchange: Exchanges): Promise<any> {
if (exchange) {
return this._get('market.instruments', {
'exchange': exchange
}, null, this.transformInstrumentsResponse);
} else {
return this._get('market.instruments.all', null, null, this.transformInstrumentsResponse);
}
};
/**
* Retrieves Quote data for the specified instruments.
*
* @param {(string | string[])} instruments - An array of exchange:tradingsymbol
* @returns {Promise<any>} A promise that resolves with the quote data for the specified instruments.
*/
getQuote(instruments: string | string[]): Promise<any> {
return this._get('market.quote', {"i": instruments}, null, formatQuoteResponse);
};
/**
* Retrieves OHLC (Open, High, Low, Close) data for the specified instruments.
*
* @param {(string | string[])} instruments - An array of exchange:tradingsymbol.
* @returns {Promise<any>} A promise that resolves with the OHLC data for the specified instruments.
*/
getOHLC(instruments: string | string[]): Promise<any> {
return this._get('market.quote.ohlc', {"i": instruments});
};
/**
* Retrieves the last traded price (LTP) of the specified instruments.
*
* @remarks
* This method fetches the last traded price (LTP) for the provided instruments.
*
* @param {(string | string[])} instruments - An array of exchange:tradingsymbol
* @returns {Promise<any>} The last traded price (LTP) of the specified instruments as a Promise<any>.
*/
getLTP(instruments: string | string[]): Promise<any>{
return this._get('market.quote.ltp', {"i": instruments});
};
/**
* Retrieve historical data (candles) for an instrument.
* For example:
* ~~~~
* [{
* date: '2015-02-10T00:00:00+0530',
* open: 277.5,
* high: 290.8,
* low: 275.7,
* close: 287.3,
* volume: 22589681
* }, ....]
* ~~~~
* @param {(number | string)} 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 {Promise<any>}
*/
getHistoricalData(instrument_token: number | string, 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 this._get('market.historical', {
instrument_token: instrument_token,
interval: interval,
from: from_date,
to: to_date,
continuous: continuous,
oi: oi
}, null, this.parseHistorical);
};
/**
* @param {?(string | number)} [order_id]
* @returns {*}
*/
getMFOrders(order_id?: string | number) {
if (order_id) {
return this._get('mf.order.info', { 'order_id': order_id }, null, this.formatResponse);
} else {
return this._get('mf.orders', null, null, this.formatResponse);
}
};
/**
*
*
* @param {PlaceMFOrderParams} params
* @returns {*}
*/
placeMFOrder(params: PlaceMFOrderParams) {
return this._post('mf.order.place', params);
}
/**
*
*
* @param {(string | number)} order_id
* @returns {*}
*/
cancelMFOrder(order_id: string | number) {
return this._delete('mf.order.cancel', { 'order_id': order_id })
}
/**
*
*
* @param {?(string | number)} [sip_id]
* @returns {*}
*/
getMFSIPS(sip_id?: string | number) {
if (sip_id) {
return this._get('mf.sip.info', { 'sip_id': sip_id }, null, this.formatResponse);
} else {
return this._get('mf.sips', null, null, this.formatResponse);
}
}
/**
*
*
* @param {Order} params
* @returns {*}
*/
placeMFSIP(params: Order) {
return this._post('mf.sip.place', params);
}
/**
*
*
* @param {(string | number)} sip_id
* @param {Order} params
* @returns {*}
*/
modifyMFSIP(sip_id: string | number, params: Order) {
params.sip_id = sip_id;
return this._put('mf.sip.modify', params);
}
/**
*
*
* @param {(string | number)} sip_id
* @returns {*}
*/
cancelMFSIP(sip_id: string | number) {
return this._delete('mf.sip.cancel', { 'sip_id': sip_id });
}
/**
*
*
* @returns {*}
*/
getMFHoldings() {
return this._get('mf.holdings');
}
/**
*
*
* @returns {*}
*/
getMFInstruments() {
return this._get('mf.instruments', null, null, transformMFInstrumentsResponse);
}
/**
* Get GTTs list
*
* @returns {Promise<any>}
*/
getGTTs() {
return this._get('gtt.triggers', null, null, this.formatResponse);
}
/**
* Get specific GTT history
*
* @param {(string | number)} trigger_id
* @returns {Promise<any>}
*/
getGTT(trigger_id: string | number) {
return this._get('gtt.trigger_info', { 'trigger_id': trigger_id }, null, this.formatResponse);
};
/**
* Get API params from user defined GTT params
*
* @param {PlaceGTTParams} params
* @returns {{ condition: { exchange: Exchanges; tradingsymbol: string; trigger_values: {}; last_price: any; }; orders: {}; }}
*/
private _getGTTPayload(params: PlaceGTTParams) {
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 === GTTStatusTypes.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_SINGLE && params.trigger_values?.length !== 1) {
throw new Error('Invalid `trigger_values` for `single` order type')
}
const condition = {
exchange: params.exchange,
tradingsymbol: params.tradingsymbol,
trigger_values: params.trigger_values,
last_price: params.last_price
}
let orders = [] as any[];
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 as string),
price: parseFloat(o.price as string),
exchange: params.exchange,
tradingsymbol: params.tradingsymbol
})
}
return { condition, orders };
};
/**
* Place GTT.
* @param {PlaceGTTParams} params
* @returns {Promise<any>}
*/
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
});
};
/**
* Modify GTT Order
*
* @param {(string | number)} trigger_id
* @param {PlaceGTTParams} params
* @returns {Promise<any>}
*/
modifyGTT(trigger_id: string | number, params: PlaceGTTParams) {
const payload = this._getGTTPayload(params);
return this._put('gtt.modify', {
trigger_id: trigger_id,
type: params.trigger_type,
condition: JSON.stringify(payload.condition),
orders: JSON.stringify(payload.orders)
});
};
/**
* Delete specific GTT order
*
* @param {(string | number)} trigger_id
* @returns {Promise<any>}
*/
deleteGTT(trigger_id: string | number) {
return this._delete('gtt.delete', { 'trigger_id': trigger_id }, null, undefined);
};
/**
* Validate postback data checksum
*
* @param {AnyObject} postback_data
* @param {string} api_secret
* @returns {boolean}
*/
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');
}
const inputString = postback_data.order_id + postback_data.order_timestamp + api_secret;
let checksum;
try {
checksum = sha256(inputString).toString();
} catch (e) {
throw (e)
}
return postback_data.checksum === checksum;
}
/**
*
* @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);
}
/**
*
*
* @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);
}
/**
*
*
* @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);
}
/**
*
*
* @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);
}
/**
*
*
* @private
* @param {string} route
* @param {Method} method
* @param {AnyObject} params