firstock 1.0.6 → 1.0.8

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,936 @@
1
+ import AFirstock from "./AFirstock";
2
+ interface Response {
3
+ data: {
4
+ [key: string]: any;
5
+ };
6
+ }
7
+ interface LoginParams {
8
+ userId: string;
9
+ password: string;
10
+ TOTP: string;
11
+ vendorCode: string;
12
+ apiKey: string;
13
+ [key: string]: any;
14
+ }
15
+ interface PlaceOrderParams {
16
+ userId: string;
17
+ exchange: string;
18
+ tradingSymbol: string;
19
+ quantity: string | number;
20
+ price: string | number;
21
+ product: string;
22
+ transactionType: string;
23
+ priceType: string;
24
+ retention: string;
25
+ remarks: string;
26
+ triggerPrice: string;
27
+ [key: string]: any;
28
+ }
29
+ interface CancelOrderParams {
30
+ userId: string;
31
+ orderNumber: string;
32
+ [key: string]: any;
33
+ }
34
+ interface ModifyOrderParams {
35
+ userId: string;
36
+ orderNumber: string;
37
+ price: string | number;
38
+ quantity: string | number;
39
+ triggerPrice: string | number;
40
+ tradingSymbol: string;
41
+ exchange: string;
42
+ priceType: string;
43
+ product: string;
44
+ retention: string;
45
+ [key: string]: any;
46
+ }
47
+ interface SingleOrderHistoryParams {
48
+ userId: string;
49
+ orderNumber: string;
50
+ [key: string]: any;
51
+ }
52
+ interface UserDetailsParams {
53
+ userId: string;
54
+ [key: string]: any;
55
+ }
56
+ interface OrderMarginParams {
57
+ userId: string;
58
+ exchange: string;
59
+ tradingSymbol: string;
60
+ quantity: string | number;
61
+ price: string | number;
62
+ product: string;
63
+ transactionType: string;
64
+ priceType: string;
65
+ [key: string]: any;
66
+ }
67
+ interface ProductConversionParams {
68
+ userId: string;
69
+ exchange: string;
70
+ tradingSymbol: string;
71
+ quantity: string | number;
72
+ product: string;
73
+ previousProduct: string;
74
+ transactionType?: string;
75
+ positionType?: string;
76
+ msgFlag?: string;
77
+ [key: string]: any;
78
+ }
79
+ interface OrderBookParams {
80
+ userId: string;
81
+ [key: string]: any;
82
+ }
83
+ interface TradeBookParams {
84
+ userId: string;
85
+ [key: string]: any;
86
+ }
87
+ interface PositionsBookParams {
88
+ userId: string;
89
+ [key: string]: any;
90
+ }
91
+ interface MultiQuoteItem {
92
+ exchange: string;
93
+ tradingSymbol: string;
94
+ [key: string]: any;
95
+ }
96
+ interface GetMultiQuotesParams {
97
+ userId: string;
98
+ data: MultiQuoteItem[];
99
+ [key: string]: any;
100
+ }
101
+ interface OptionChainParams {
102
+ userId: string;
103
+ exchange: string;
104
+ symbol: string;
105
+ strikePrice: string | number;
106
+ count: string | number;
107
+ expiry?: string;
108
+ [key: string]: any;
109
+ }
110
+ interface GetQuoteLTPParams {
111
+ userId: string;
112
+ exchange: string;
113
+ tradingSymbol: string;
114
+ [key: string]: any;
115
+ }
116
+ interface GetMultiQuotesLTPParams {
117
+ userId: string;
118
+ data: MultiQuoteItem[];
119
+ [key: string]: any;
120
+ }
121
+ interface SearchScriptsParams {
122
+ userId: string;
123
+ stext: string;
124
+ [key: string]: any;
125
+ }
126
+ interface GetSecurityInfoParams {
127
+ userId: string;
128
+ exchange: string;
129
+ tradingSymbol: string;
130
+ [key: string]: any;
131
+ }
132
+ interface HoldingsParams {
133
+ userId: string;
134
+ product?: string;
135
+ [key: string]: any;
136
+ }
137
+ interface LimitsParams {
138
+ userId: string;
139
+ [key: string]: any;
140
+ }
141
+ interface GetQuotesParams {
142
+ userId: string;
143
+ exchange: string;
144
+ tradingSymbol: string;
145
+ [key: string]: any;
146
+ }
147
+ interface GetIndexListParams {
148
+ userId: string;
149
+ exchange: string;
150
+ [key: string]: any;
151
+ }
152
+ interface TimePriceSeriesParams {
153
+ userId: string;
154
+ exchange: string;
155
+ tradingSymbol: string;
156
+ endTime: string;
157
+ startTime: string;
158
+ interval: string | number;
159
+ [key: string]: any;
160
+ }
161
+ interface BrokerageCalculatorParams {
162
+ userId: string;
163
+ exchange: string;
164
+ tradingSymbol: string;
165
+ transactionType: string;
166
+ Product: string;
167
+ quantity: string | number;
168
+ price: string | number;
169
+ strike_price: string | number;
170
+ inst_name: string;
171
+ lot_size: string | number;
172
+ [key: string]: any;
173
+ }
174
+ interface GetExpiryParams {
175
+ userId: string;
176
+ exchange: string;
177
+ tradingSymbol: string;
178
+ [key: string]: any;
179
+ }
180
+ interface GetHoldingsParams {
181
+ userId: string;
182
+ [key: string]: any;
183
+ }
184
+ export declare class Firstock extends AFirstock {
185
+ private token;
186
+ private userId;
187
+ private jsonObj;
188
+ constructor();
189
+ /**
190
+ * Authenticates the user with Firstock using credentials and retrieves a session token (susertoken).
191
+ *
192
+ * This method sends a secure login request to the Firstock API with SHA256-hashed password and TOTP (if applicable),
193
+ * and stores the received session token locally for future authenticated requests.
194
+ *
195
+ * On success, updates the instance with `token` and `userId`, and saves the token to a configuration file.
196
+ *
197
+ * @param {Object} params - Login parameters.
198
+ * @param {string} params.userId - Firstock user ID (e.g., AB1234).
199
+ * @param {string} params.password - Plain password (will be SHA256 hashed before sending).
200
+ * @param {string} params.TOTP - Two-factor authentication code, if enabled.
201
+ * @param {string} params.vendorCode - Unique vendor code provided by Firstock.
202
+ * @param {string} params.apiKey - API key issued by Firstock.
203
+ *
204
+ * @param {function} callBack - Callback with `(error, result)`:
205
+ * - `error`: Error object if login fails.
206
+ * - `result`: Parsed response containing login information and token if successful.
207
+ */
208
+ login({ userId, password, TOTP, vendorCode, apiKey }: LoginParams, callBack: (error: Error | null, result: Response | null) => void): void;
209
+ /**
210
+ * Fetches the Option Chain data from the Firstock API.
211
+ *
212
+ * This method retrieves nearby call and put option contracts for a given symbol and strike price.
213
+ * It's useful for constructing an option chain view or for identifying options for trading.
214
+ *
215
+ * The user must be logged in before calling this method (valid `jKey` required).
216
+ *
217
+ * @param {Object} params - Parameters required to fetch the option chain.
218
+ * @param {string} params.userId - Your Firstock user ID (must be same as used during login).
219
+ * @param {string} params.exchange - Exchange name (typically `"NFO"` for NSE options).
220
+ * @param {string} params.symbol - Underlying symbol or index (e.g., `"NIFTY"`).
221
+ * @param {string|number} params.strikePrice - Central strike price to base the option chain on.
222
+ * @param {string|number} params.count - Number of strike levels above and below the central price to retrieve.
223
+ * @param {string} [params.expiry] - (Optional) Expiry date of options in `DDMONYY` format (e.g., `"17APR25"`).
224
+ *
225
+ * @param {function} callBack - A callback function receiving `(error, result)`.
226
+ * On success, `result` contains an array of option contracts:
227
+ * - `exchange`: "NFO"
228
+ * - `lotSize`: Lot size of contract
229
+ * - `optionType`: "CE" or "PE"
230
+ * - `strikePrice`: Strike price of the contract
231
+ * - `tradingSymbol`: Usable symbol to place orders
232
+ * - `lastTradedPrice`: LTP of the option
233
+ */
234
+ optionChain(params: OptionChainParams, callBack: (error: Error | string | null, result: any | null) => void): void;
235
+ /**
236
+ * Fetches intraday candlestick data for a given trading symbol and interval.
237
+ *
238
+ * This method provides time-series data (OHLCV) for short-term intervals like 1min, 2min, 5min, etc.
239
+ * It's ideal for charting, intraday analysis, and short-term strategy backtesting.
240
+ *
241
+ * ⚠️ The user must be logged in (valid jKey) before calling this method.
242
+ *
243
+ * @param {Object} params - Parameters for fetching time price series.
244
+ * @param {string} params.userId - Firstock user ID (same as used during login).
245
+ * @param {string} params.exchange - Exchange code (e.g., "NSE", "BSE", "NFO").
246
+ * @param {string} params.tradingSymbol - Symbol or instrument for intraday data (e.g., "NIFTY").
247
+ * @param {string} params.startTime - Start time in `"HH:MM:SS DD-MM-YYYY"` format (24-hour clock).
248
+ * @param {string} params.endTime - End time in `"HH:MM:SS DD-MM-YYYY"` format.
249
+ * @param {string|number} params.interval - Candle interval (e.g., `"1mi"`, `"2mi"`, `"5mi"`).
250
+ *
251
+ * @param {function} callBack - Callback function receiving `(error, result)`.
252
+ * On success, result includes an array of candlestick objects:
253
+ * - `time`: ISO timestamp
254
+ * - `epochTime`: UNIX time
255
+ * - `open`, `high`, `low`, `close`: Prices for the interval
256
+ * - `volume`: Volume during the interval
257
+ * - `oi`: Open interest (if applicable)
258
+ */
259
+ timePriceSeries(params: TimePriceSeriesParams, callBack: (error: Error | string | null, result: any | null) => void): void;
260
+ getPosts(): Promise<any>;
261
+ getUsers(): any;
262
+ getPostByUserId(): any;
263
+ /**
264
+ * Logs the user out of the Firstock platform and invalidates the session token (`jKey`).
265
+ *
266
+ * This method securely ends the authenticated session by calling the Firstock `/logout` API.
267
+ * It ensures that the session token is no longer valid, preventing unauthorized future requests.
268
+ *
269
+ * The user must be logged in before calling this method. Otherwise, it returns an error.
270
+ *
271
+ * Best Practice: Always log the user out after completing trading activity or on app exit.
272
+ *
273
+ * @param {Object} params - Parameters for logout.
274
+ * @param {string} params.userId - Firstock user ID (same as used during login).
275
+ *
276
+ * @param {function} callBack - Callback function receiving `(error, result)`:
277
+ * - `error`: Error message or `null` on success.
278
+ * - `result`: Logout response object if successful, otherwise `null`.
279
+ *
280
+ * Security:
281
+ * - After successful logout, the jKey/token becomes invalid.
282
+ * - Any further API calls with the same token will be rejected.
283
+ */
284
+ logout(params: {
285
+ userId: string;
286
+ }, callBack: (error: Error | string | null, result: Response | null) => void): void;
287
+ /**
288
+ * Fetches detailed profile and privilege information of the logged-in Firstock user.
289
+ *
290
+ * This method sends a POST request to the `/userDetails` endpoint to retrieve user-specific
291
+ * account information including email, enabled exchanges, order types, and privilege level.
292
+ * It first checks for valid login session data (jKey) before making the API call.
293
+ *
294
+ * @param {Object} params - Parameters for the request.
295
+ * @param {string} params.userId - The Firstock user ID used during login.
296
+ *
297
+ * @param {function} callBack - Callback function that returns either an error or the result.
298
+ * @param {Error|string|null} callBack.error - An error message if the request fails.
299
+ * @param {UserDetailsResponse|null} callBack.result - The user details data if successful.
300
+ *
301
+ * Response includes:
302
+ * - actid: Account ID (same as userId)
303
+ * - email: Registered email address
304
+ * - exchange: Array of enabled exchanges (e.g., NSE, BSE)
305
+ * - orarr: Allowed order types (e.g., MKT, LMT)
306
+ * - uprev: User privilege level (e.g., INVESTOR)
307
+ * - userName: Full name of the user
308
+ * - requestTime: Timestamp of the request
309
+ *
310
+ * Notes:
311
+ * - If the user is not logged in or the session token is expired, an appropriate error is returned.
312
+ * - Always ensure the session token (jKey) used is from the latest successful login.
313
+ */
314
+ userDetails(params: UserDetailsParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
315
+ /**
316
+ * Places a new trade order on the Firstock trading platform.
317
+ *
318
+ * This method sends a POST request to the `/placeOrder` endpoint using the provided parameters.
319
+ * It supports market, limit, and stop-loss order types across supported exchanges like NSE, BSE, and NFO.
320
+ *
321
+ * @param {Object} params - Required order parameters.
322
+ * @param {string} params.userId - Firstock user ID (same as used during login).
323
+ * @param {string} params.exchange - Exchange to place order on (e.g., "NSE", "BSE", "NFO").
324
+ * @param {string} params.retention - Order validity period ("DAY", "IOC").
325
+ * @param {string} params.product - Product type ("C", "I", "M").
326
+ * @param {string} params.priceType - Type of order ("MKT", "LMT", "SL-MKT", "SL-LMT").
327
+ * @param {string} params.tradingSymbol - Instrument symbol (e.g., "IDEA-EQ", "NIFTY06MAR25C22500").
328
+ * @param {string} params.transactionType - "B" (Buy) or "S" (Sell).
329
+ * @param {string} params.price - Order price (0 for market orders).
330
+ * @param {string} params.triggerPrice - Trigger price for stop-loss orders (0 for others).
331
+ * @param {string} params.quantity - Quantity of shares or lots to trade.
332
+ * @param {string} params.remarks - Optional order remark or note.
333
+ *
334
+ * @param {function} callBack - Callback function.
335
+ * @param {Error|string|null} callBack.error - Error message, if any.
336
+ * @param {OrderResponse|null} callBack.result - Response data containing the order details.
337
+ *
338
+ * Notes:
339
+ * - Requires a valid session token (jKey), obtained during login.
340
+ * - Returns `orderNumber` and `requestTime` on success.
341
+ * - Handles various error conditions such as missing fields or invalid sessions.
342
+ * - URL-encode special characters in trading symbols (e.g., use `L%26TFH-EQ` instead of `L&TFH-EQ`).
343
+ */
344
+ placeOrder(params: PlaceOrderParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
345
+ /**
346
+ * Fetches the margin requirements for a prospective order on the Firstock trading platform.
347
+ *
348
+ * This API helps preview the required margin, available margin, cash balance, and potential warnings (e.g., insufficient funds)
349
+ * before placing a live trade. It's recommended for risk checks and order feasibility validation.
350
+ *
351
+ * @param {Object} params - Required parameters for order margin calculation.
352
+ * @param {string} params.userId - Firstock user ID (same as used during login).
353
+ * @param {string} params.exchange - Exchange where the order is intended ("NSE", "BSE", "NFO", etc.).
354
+ * @param {string} params.transactionType - "B" for Buy or "S" for Sell.
355
+ * @param {string} params.product - Product type ("C", "M", "I").
356
+ * @param {string} params.tradingSymbol - Instrument symbol (e.g., "IDEA-EQ", "NIFTY06MAR25C22500").
357
+ * @param {string} params.quantity - Number of shares or lots.
358
+ * @param {string} params.priceType - Order type ("MKT", "LMT", "SL-LMT", "SL-MKT").
359
+ * @param {string} params.price - Order price (use "0" for market orders).
360
+ *
361
+ * @param {function} callBack - Callback function.
362
+ * @param {Error|string|null} callBack.error - Error object or message, if any.
363
+ * @param {OrderMarginResponse|null} callBack.result - Margin data including total cash, required margin, available margin, remarks, and timestamp.
364
+ *
365
+ * Notes:
366
+ * - Requires a valid `jKey` (session token) obtained during login.
367
+ * - The method returns key margin fields: `marginOnNewOrder`, `availableMargin`, `cash`, `remarks`, and `requestTime`.
368
+ * - Use this to verify sufficient margin before attempting to place the order.
369
+ * - `remarks` may include warnings such as "Insufficient Balance".
370
+ * - Ensure that the selected product type is supported on the specified exchange.
371
+ * - If `jKey` is missing or expired, the response will indicate session invalidation.
372
+ */
373
+ orderMargin(params: OrderMarginParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
374
+ /**
375
+ * Retrieves the list of all orders placed by the user, including open, filled, and rejected orders.
376
+ *
377
+ * This method sends a request to the Firstock Order Book API and returns a structured list of all orders
378
+ * along with their details such as exchange, transaction type, quantity, price, status, rejection reasons, etc.
379
+ *
380
+ * Useful for real-time order tracking, trade reconciliation, and identifying rejected or pending trades.
381
+ *
382
+ * @param {Object} params - Required parameters for retrieving the order book.
383
+ * @param {string} params.userId - Unique Firstock user ID (same as used during login).
384
+ *
385
+ * @param {function} callBack - Callback function.
386
+ * @param {Error|string|null} callBack.error - Error object or message, if any.
387
+ * @param {OrderBookResponse|null} callBack.result - Array of order details including order number, quantity, status, average price, and rejection reason.
388
+ *
389
+ * Notes:
390
+ * - Requires a valid `jKey` (session token) obtained at login.
391
+ * - Orders include both current and historical data such as `REJECTED`, `FILLED`, or `OPEN`.
392
+ * - Each order record contains fields like `orderNumber`, `exchange`, `transactionType`, `quantity`, `priceType`, `status`, `remarks`, and `rejectReason`.
393
+ * - Use this data for populating order history in user dashboards or triggering logic based on order state.
394
+ * - If `jKey` is invalid or expired, response will indicate session expiration.
395
+ * - Frequent polling should be rate-limited; consider WebSocket alternatives if available.
396
+ */
397
+ orderBook(params: OrderBookParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
398
+ /**
399
+ * Cancels a previously placed order that has not yet been fully executed.
400
+ *
401
+ * This method interacts with the Firstock Cancel Order API to invalidate an active order. It is useful for
402
+ * real-time risk management and preventing undesired executions when market conditions change or the user
403
+ * decides to withdraw the order.
404
+ *
405
+ * @param {Object} params - Required parameters for cancelling an order.
406
+ * @param {string} params.userId - Unique Firstock user ID (same as used during login).
407
+ * @param {string} params.orderNumber - The unique identifier of the order to be cancelled.
408
+ *
409
+ * @param {function} callBack - Callback function to handle the response.
410
+ * @param {Error|string|null} callBack.error - Error message or object, if the request fails.
411
+ * @param {OrderResponse|null} callBack.result - Response data containing order cancellation status.
412
+ *
413
+ * Notes:
414
+ * - Only orders in an “open” or “partially filled” state are eligible for cancellation.
415
+ * - The session token (`jKey`) must be valid and active; otherwise, a re-login may be required.
416
+ * - Responses include fields like `orderNumber`, `rejreason`, and `requestTime`.
417
+ * - A failed cancellation may return reasons such as "order is not open to cancel".
418
+ * - It's recommended to verify the final order status using the Order Book API after cancellation.
419
+ */
420
+ cancelOrder(params: CancelOrderParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
421
+ /**
422
+ * Modifies an existing active order with updated parameters like price, quantity, or trigger price.
423
+ *
424
+ * This method interacts with the Firstock Modify Order API to alter a live order without canceling it.
425
+ * It's useful for adapting orders in response to changing market conditions without losing order priority.
426
+ *
427
+ * @param {Object} params - Parameters required to modify an order.
428
+ * @param {string} params.userId - Firstock user ID used during login.
429
+ * @param {string} params.orderNumber - The order identifier to be modified.
430
+ * @param {string} params.priceType - Order type ("MKT", "LMT", "SL-LMT", "SL-MKT").
431
+ * @param {string} params.tradingSymbol - Trading symbol (e.g., "IDEA-EQ").
432
+ * @param {string} [params.price] - Price for limit orders. Should be "0" for market orders.
433
+ * @param {string} [params.quantity] - Number of shares/lots to modify.
434
+ * @param {string} [params.triggerPrice] - Trigger price for SL orders. Optional for other types.
435
+ * @param {string} [params.retention] - Optional order duration (e.g., "DAY", "IOC").
436
+ * @param {string} [params.product] - Product type (e.g., "C", "M", "I").
437
+ *
438
+ * @param {function} callBack - Callback to handle response or error.
439
+ * @param {Error|string|null} callBack.error - Error object or message if request fails.
440
+ * @param {OrderResponse|null} callBack.result - Response data on successful order modification.
441
+ *
442
+ * Notes:
443
+ * - Only open or partially filled orders can be modified.
444
+ * - Session token (jKey) must be valid.
445
+ * - Use consistent combinations of `priceType`, `price`, and `triggerPrice`.
446
+ * - Invalid combinations or closed orders will cause the request to fail.
447
+ * - Always verify status using the Order Book API after calling this method.
448
+ */
449
+ modifyOrder(params: ModifyOrderParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
450
+ /**
451
+ * Fetches detailed history of a specific order including each step or fill event.
452
+ *
453
+ * This method provides a breakdown of an order's lifecycle such as status changes,
454
+ * partial fills, rejection reasons, and timestamps for each transition.
455
+ *
456
+ * **Endpoint:** POST `/singleOrderHistory`
457
+ * **URL:** https://api.firstock.in/V1/singleOrderHistory
458
+ *
459
+ * @param {SingleOrderHistoryParams} params - The order details required to fetch history.
460
+ * @param {string} params.userId - Unique Firstock user ID (same as login).
461
+ * @param {string} params.orderNumber - Unique identifier for the order to retrieve.
462
+ *
463
+ * @param {(error: Error | string | null, result: OrderResponse | null) => void} callBack - Callback function with either error or response.
464
+ *
465
+ * @returns {void}
466
+ *
467
+ * @example
468
+ * firstock.singleOrderHistory(
469
+ * { userId: "AB1234", orderNumber: "24121300003425" },
470
+ * (err, result) => {
471
+ * if (err) console.error(err);
472
+ * else console.log(result);
473
+ * }
474
+ * );
475
+ */
476
+ singleOrderHistory(params: SingleOrderHistoryParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
477
+ /**
478
+ * Retrieves the trade history (executed orders) for a user account.
479
+ *
480
+ * Unlike the Order Book, which includes pending and partially filled orders, this method
481
+ * returns only completed or partially executed trades, including fill details such as
482
+ * price, quantity, and timestamps.
483
+ *
484
+ * **Endpoint:** POST `/tradeBook`
485
+ * **URL:** https://api.firstock.in/V1/tradeBook
486
+ *
487
+ * @param {TradeBookParams} params - Parameters for fetching the trade book.
488
+ * @param {string} params.userId - Unique Firstock user ID (used during login).
489
+ *
490
+ * @param {(error: Error | string | null, result: TradeBookResponse | null) => void} callBack - Callback function with error or trade data.
491
+ *
492
+ * @returns {void}
493
+ *
494
+ * @remarks
495
+ * - Ensure `jKey` is valid (session token from login). An invalid or expired session will trigger an error.
496
+ * - Useful for profit/loss calculations, compliance audits, and trade reconciliation.
497
+ * - Typical failure reasons: invalid `userId`, expired session, or no trades found.
498
+ */
499
+ tradeBook(params: TradeBookParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
500
+ /**
501
+ * Fetches the list of current open positions for the given user.
502
+ *
503
+ * This API provides detailed information about each open position such as:
504
+ * - Buy/sell quantities and average prices for the day
505
+ * - Net quantity and average price
506
+ * - Unrealized mark-to-market (MTM) and realized profit/loss
507
+ * - Exchange, product type, trading symbol, and more
508
+ *
509
+ * Common uses include:
510
+ * - Real-time profit/loss tracking
511
+ * - Position reconciliation with order/trade books
512
+ * - Margin requirement assessment based on product type
513
+ *
514
+ * @param {PositionsBookParams} params - Parameters including userId (Firstock ID)
515
+ * @param {(error: Error | string | null, result: PositionsBookResponse | null) => void} callBack - Callback to receive either error or response
516
+ *
517
+ * @returns {void}
518
+ */
519
+ positionBook(params: PositionsBookParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
520
+ /**
521
+ * Converts the product type for an existing open position.
522
+ *
523
+ * Enables traders to change a position's product type (e.g., from MIS to CNC) without closing and reopening it.
524
+ * This is useful for margin optimization or carrying over intraday positions.
525
+ *
526
+ * Benefits:
527
+ * - Adjust strategy without exiting trades
528
+ * - Free up or reallocate margin
529
+ * - Avoid unnecessary brokerage or slippage
530
+ *
531
+ * Restrictions and considerations:
532
+ * - Ensure jKey (session token) is valid
533
+ * - Conversion may not be allowed after square-off time
534
+ * - Check position size before attempting partial conversions
535
+ * - Only supported symbols and product types are eligible
536
+ *
537
+ * @param {ProductConversionParams} params - Includes userId, tradingSymbol, exchange, quantity, product, and previousProduct
538
+ * @param {(error: Error | string | null, result: ProductConversionResponse | null) => void} callBack - Callback that returns the conversion result or error
539
+ *
540
+ * @returns {void}
541
+ */
542
+ productConversion(params: ProductConversionParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
543
+ /**
544
+ * Retrieves the user's holdings (portfolio) from Firstock.
545
+ *
546
+ * This method fetches a summary of securities held in the user's Demat account or portfolio.
547
+ * Unlike the position book (which reflects intraday/open positions), holdings represent delivery-based investments.
548
+ *
549
+ * Key Features:
550
+ * - Provides long-term investment details.
551
+ * - Shows exchange and trading symbol for each holding.
552
+ * - Useful for portfolio valuation and analysis.
553
+ *
554
+ * @param {HoldingsParams} params - Required parameters to fetch holdings.
555
+ * @param {string} params.userId - Unique identifier of the user (same as login).
556
+ * @param {string} [params.product] - Optional product type (e.g., CNC, MIS).
557
+ * @param {(error: Error | string | null, result: HoldingsResponse | null) => void} callBack - Callback function with error or result.
558
+ *
559
+ * Endpoint: POST /holdings
560
+ * Headers: { "Content-Type": "application/json" }
561
+ *
562
+ * Response:
563
+ * - On success: { status: "success", message: "Fetched holdings", data: [...] }
564
+ * - On error: Error string such as "INVALID_JKEY" or "No config data found"
565
+ *
566
+ * Notes:
567
+ * - Requires a valid session (jKey). If the jKey is invalid or expired, prompt the user to log in again.
568
+ */
569
+ holdings(params: HoldingsParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
570
+ /**
571
+ * Calculates the margin required for placing a basket of orders in a single request.
572
+ *
573
+ * The Basket Margin API is used to compute the net margin impact of multiple orders, which is particularly useful
574
+ * for complex strategies like spreads, options combinations, or simultaneous stock purchases.
575
+ *
576
+ * Key Features:
577
+ * - Evaluates margin requirements for multiple trades together.
578
+ * - Helps prevent partial order failures due to insufficient margin.
579
+ * - Optimized for complex order execution.
580
+ *
581
+ * @param {Object} params - Basket margin request parameters.
582
+ * @param {string} params.userId - Firstock user ID (same as used during login).
583
+ * @param {string} params.exchange - Exchange code (e.g., "NSE", "BSE", "NFO").
584
+ * @param {string} params.transactionType - "B" (Buy) or "S" (Sell) for the first order.
585
+ * @param {string} params.product - Product type (e.g., "C", "M", "I").
586
+ * @param {string} params.tradingSymbol - Trading symbol (e.g., "RELIANCE-EQ").
587
+ * @param {string | number} params.quantity - Quantity of the first order.
588
+ * @param {string} params.priceType - Price type (e.g., "MKT", "LMT").
589
+ * @param {string | number} params.price - Price for the first order. Use "0" for market orders.
590
+ * @param {Array<Object>} params.BasketList_Params - Additional orders in the basket.
591
+ * @param {string} params.BasketList_Params[].exchange - Exchange code for each order.
592
+ * @param {string} params.BasketList_Params[].transactionType - "B" or "S" for each order.
593
+ * @param {string} params.BasketList_Params[].product - Product type for each order.
594
+ * @param {string} params.BasketList_Params[].tradingSymbol - Symbol for each order.
595
+ * @param {string | number} params.BasketList_Params[].quantity - Quantity for each order.
596
+ * @param {string} params.BasketList_Params[].priceType - Price type for each order.
597
+ * @param {string | number} params.BasketList_Params[].price - Price for each order.
598
+ *
599
+ * @param {(error: Error | string | null, result: any | null) => void} callBack - Callback with error or result.
600
+ *
601
+ * Response:
602
+ * - status: "success" or "error"
603
+ * - message: Description of result
604
+ * - data: Contains fields like `BasketMargin`, `MarginOnNewOrder`, `PreviousMargin`, `TradedMargin`, and `Remarks`.
605
+ *
606
+ * Notes:
607
+ * - Requires a valid `jKey` (session token).
608
+ * - Combine this with the RMS Limits API to check available margin.
609
+ * - Ensure all basket items are accurately populated to avoid miscalculations.
610
+ *
611
+ * Endpoint: POST /basketMargin
612
+ * Content-Type: application/json
613
+ */
614
+ basketMargin(params: {
615
+ userId: string;
616
+ exchange: string;
617
+ transactionType: string;
618
+ product: string;
619
+ tradingSymbol: string;
620
+ quantity: string | number;
621
+ priceType: string;
622
+ price: string | number;
623
+ BasketList_Params: {
624
+ exchange: string;
625
+ transactionType: string;
626
+ product: string;
627
+ tradingSymbol: string;
628
+ quantity: string | number;
629
+ priceType: string;
630
+ price: string | number;
631
+ }[];
632
+ }, callBack: (error: Error | string | null, result: any | null) => void): void;
633
+ /**
634
+ * Fetches the real-time RMS limits for a user account.
635
+ *
636
+ * This API provides detailed information about a user's trading limits and margin utilization.
637
+ * It helps in assessing available margin, broker collateral, cash balance, collateral values,
638
+ * exposure used, and other key risk metrics.
639
+ *
640
+ * Key Use Cases:
641
+ * - Check if the user has sufficient buying power before placing new trades.
642
+ * - Monitor exposure, margin used, collateral, and available limits.
643
+ * - Ensure session is valid using the jKey.
644
+ *
645
+ * @param {Object} params - The input parameters.
646
+ * @param {string} params.userId - The Firstock user ID (used during login).
647
+ *
648
+ * @param {(error: Error | string | null, result: LimitsResponse | null) => void} callBack - Callback function
649
+ * to handle the response. Returns either an error or a `LimitsResponse` object.
650
+ *
651
+ * Response Structure:
652
+ * - status: "success" or "error"
653
+ * - message: Description of the result
654
+ * - data: Object containing:
655
+ * - availableMargin: Margin available for new orders
656
+ * - brkcollamt: Broker collateral amount
657
+ * - cash: Cash balance in the account
658
+ * - collateral: Value of pledged holdings
659
+ * - expo: Exposure margin used
660
+ * - marginused: Total margin used
661
+ * - payin: Incoming funds not yet cleared
662
+ * - peak_mar: Peak margin used in the session
663
+ * - premium: Option premium paid or received
664
+ * - span: SPAN margin used (for F&O)
665
+ * - requestTime: Timestamp of data retrieval
666
+ *
667
+ * Notes:
668
+ * - Always ensure the session token (`jKey`) is valid.
669
+ * - If jKey is invalid, prompt the user to re-authenticate.
670
+ * - This API is essential for real-time risk and margin tracking.
671
+ *
672
+ * Endpoint: POST /limit
673
+ * Headers: Content-Type: application/json
674
+ */
675
+ limit(params: LimitsParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
676
+ /**
677
+ * Fetches live market quotes for a given trading symbol on a specified exchange.
678
+ *
679
+ * This method retrieves real-time pricing and order book data such as last traded price,
680
+ * day high/low, and best bid/ask levels. It is useful for market analysis and building
681
+ * live trading interfaces.
682
+ *
683
+ * @param {GetQuotesParams} params - Request parameters including userId, exchange, and tradingSymbol.
684
+ * @param {(error: Error | string | null, result: GetQuotesResponse | null) => void} callBack -
685
+ * Callback function that handles the response or error.
686
+ *
687
+ * @remarks
688
+ * - Requires the user to be logged in with a valid session key (`jKey`).
689
+ * - Calls the POST /getQuote endpoint.
690
+ * - Parses and returns the latest quote data if successful.
691
+ *
692
+ * @example
693
+ * firstock.getQuotes(
694
+ * {
695
+ * userId: 'AB1234',
696
+ * exchange: 'NSE',
697
+ * tradingSymbol: 'RELIANCE-EQ'
698
+ * },
699
+ * (error, result) => {
700
+ * if (error) {
701
+ * console.error('Quote Error:', error);
702
+ * } else {
703
+ * console.log('Quote Data:', result);
704
+ * }
705
+ * }
706
+ * );
707
+ */
708
+ getQuote(params: GetQuotesParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
709
+ /**
710
+ * Fetches the Last Traded Price (LTP) for a given trading symbol on a specified exchange.
711
+ *
712
+ * This API provides a lightweight response containing the most recent traded price,
713
+ * without full market depth. Ideal for simple UIs or price checks.
714
+ *
715
+ * @param {GetQuoteLTPParams} params - Request parameters including:
716
+ * - `userId` (string): Unique Firstock user ID.
717
+ * - `exchange` (string): Exchange name ("NSE", "BSE", "NFO", etc.).
718
+ * - `tradingSymbol` (string): Trading symbol (e.g., "RELIANCE-EQ").
719
+ *
720
+ * @param {(error: Error | string | null, result: GetQuoteLTPResponse | null) => void} callBack -
721
+ * Callback function invoked with the LTP response or error.
722
+ *
723
+ * @remarks
724
+ * - Endpoint: `POST /getQuote/ltp`
725
+ * - Requires valid session (`jKey`) from a successful login.
726
+ * - Returns fields like company name, exchange, last traded price, and token.
727
+ * - Useful for real-time updates, alerts, or minimal display dashboards.
728
+ *
729
+ * @returns {void}
730
+ *
731
+ */
732
+ getQuoteltp(params: GetQuoteLTPParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
733
+ /**
734
+ * Get Last Traded Prices (LTP) for multiple instruments.
735
+ *
736
+ * This method is used to retrieve the latest traded prices (LTP) for multiple stocks or derivatives
737
+ * from Firstock's trading API. It is efficient for watchlists or dashboards where only price is required.
738
+ *
739
+ * **Endpoint:** POST `/getMultiQuotes/ltp`
740
+ *
741
+ * **Required Fields in `params`:**
742
+ * - `userId` (string): Firstock user ID.
743
+ * - `data` (Array<{ exchange: string, tradingSymbol: string }>): List of instruments to fetch LTP for.
744
+ *
745
+ * **Usage Notes:**
746
+ * - Each item in `data` must have `exchange` (e.g., NSE, BSE) and `tradingSymbol`.
747
+ * - A valid `jKey` (from login) is auto-fetched from local config.
748
+ * - This is a lightweight alternative to the full quote API.
749
+ *
750
+ * **Example Data:**
751
+ * ```ts
752
+ * {
753
+ * userId: "AB1234",
754
+ * data: [
755
+ * { exchange: "NSE", tradingSymbol: "RELIANCE-EQ" },
756
+ * { exchange: "NFO", tradingSymbol: "NIFTY03APR25C23500" }
757
+ * ]
758
+ * }
759
+ * ```
760
+ *
761
+ * @param {GetMultiQuotesLTPParams} params - Parameters including userId and instrument list.
762
+ * @param {(error: Error | string | null, result: GetMultiQuotesLTPResponse | null) => void} callBack - Callback with either error or result.
763
+ *
764
+ * @returns {void}
765
+ */
766
+ getMultiQuotesltp(params: GetMultiQuotesLTPParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
767
+ /**
768
+ * Fetches detailed market quotes for multiple instruments (symbols) in a single API request.
769
+ * This includes last traded price, best bid/ask levels, open interest, daily high/low/open/close prices, and more.
770
+ *
771
+ * @param {GetMultiQuotesParams} params - Parameters required for the API call.
772
+ * @param {string} params.userId - Unique identifier for the Firstock user.
773
+ * @param {Array<{ exchange: string, tradingSymbol: string }>} params.data - Array of exchange-symbol pairs for which quotes are to be retrieved.
774
+ * @param {(error: Error | string | null, result: GetMultiQuotesResponse | null) => void} callBack - Callback function to handle the API response or error.
775
+ *
776
+ * @returns {void} - No return value; the result is returned via the callback.
777
+ *
778
+ * @example
779
+ * getMultiQuotes(
780
+ * {
781
+ * userId: 'AB1234',
782
+ * data: [
783
+ * { exchange: 'NSE', tradingSymbol: 'RELIANCE-EQ' },
784
+ * { exchange: 'NFO', tradingSymbol: 'NIFTY28JUN29P39000' }
785
+ * ]
786
+ * },
787
+ * (err, result) => {
788
+ * if (err) {
789
+ * console.error(err);
790
+ * } else {
791
+ * console.log(result);
792
+ * }
793
+ * }
794
+ * );
795
+ */
796
+ getMultiQuotes(params: GetMultiQuotesParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
797
+ /**
798
+ * Searches for tradable instruments (scrips) across multiple exchanges based on partial or full input text.
799
+ *
800
+ * This API is useful for autocompleting trading symbols in client applications.
801
+ *
802
+ * @param {SearchScriptsParams} params - Parameters for the search request.
803
+ * @param {string} params.userId - Unique identifier for the Firstock user (same as used during login).
804
+ * @param {string} params.stext - Partial or full text to search trading symbols (e.g., "ITC").
805
+ *
806
+ * @param {(error: Error | string | null, result: SearchScriptsResponse | null) => void} callBack -
807
+ * Callback to handle the response or error.
808
+ *
809
+ * @returns {void} - Result is returned via the callback function.
810
+ *
811
+ * @example
812
+ * searchScripts(
813
+ * {
814
+ * userId: 'AB1234',
815
+ * stext: 'ITC'
816
+ * },
817
+ * (err, result) => {
818
+ * if (err) {
819
+ * console.error('Error:', err);
820
+ * } else {
821
+ * console.log('Matched Scrips:', result?.data);
822
+ * }
823
+ * }
824
+ * );
825
+ */
826
+ searchScrips(params: SearchScriptsParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
827
+ /**
828
+ * Retrieves detailed security information about a trading symbol on a specific exchange.
829
+ *
830
+ * This API helps validate and fetch metadata like segment, instrument name, lot size, and token ID
831
+ * before placing or managing trades (especially useful in derivatives trading).
832
+ *
833
+ * @param {GetSecurityInfoParams} params - Parameters for fetching security information.
834
+ * @param {string} params.userId - Firstock user ID (used during login).
835
+ * @param {string} params.exchange - Exchange name (e.g., "NSE", "BSE", "NFO").
836
+ * @param {string} params.tradingSymbol - Symbol identifier (e.g., "IDEA-EQ", "NIFTY06MAR25C22500").
837
+ *
838
+ * @param {(error: Error | string | null, result: GetSecurityInfoResponse | null) => void} callBack -
839
+ * Callback function to handle the response or error.
840
+ *
841
+ * @returns {void} - Result is returned via the callback.
842
+ *
843
+ * @example
844
+ * getSecurityInfo(
845
+ * {
846
+ * userId: "AB1234",
847
+ * exchange: "NSE",
848
+ * tradingSymbol: "NIFTY"
849
+ * },
850
+ * (err, result) => {
851
+ * if (err) {
852
+ * console.error("Security Info Error:", err);
853
+ * } else {
854
+ * console.log("Security Info:", result?.data);
855
+ * }
856
+ * }
857
+ * );
858
+ */
859
+ securityInfo(params: GetSecurityInfoParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
860
+ /**
861
+ * Fetches the list of major stock market indices from the Firstock API.
862
+ *
863
+ * This method is useful for retrieving a consolidated list of index tokens and trading symbols
864
+ * (such as NIFTY50, BANKNIFTY, SENSEX, etc.). These identifiers can then be used for quote-related APIs.
865
+ *
866
+ * The user must be logged in before calling this method (a valid `jKey` is required).
867
+ *
868
+ * @param {Object} params - Parameters required to fetch the index list.
869
+ * @param {string} params.userId - Your Firstock user ID (must be the same as used during login).
870
+ * @param {string} params.exchange - Exchange from which to fetch index list (e.g., "NSE" or "BSE").
871
+ *
872
+ * @param {function} callBack - A callback function receiving `(error, result)`.
873
+ * On success, `result` contains an array of index objects:
874
+ * - `exchange`: The exchange code (e.g., "NSE")
875
+ * - `token`: Numeric identifier for the index
876
+ * - `tradingSymbol`: Usable symbol for quote APIs
877
+ * - `symbol`: Abbreviated symbol
878
+ * - `idxname`: Descriptive name like "NIFTY 50", "BANKNIFTY", etc.
879
+ *
880
+ * @returns {void}
881
+ */
882
+ indexList(params: GetIndexListParams, callBack: (error: Error | string | null, result: any | null) => void): void;
883
+ /**
884
+ * Fetches available expiry dates for a given trading symbol on the specified exchange.
885
+ *
886
+ * Useful for retrieving valid expiry dates for derivatives (Futures & Options) contracts.
887
+ * A valid session (jKey) is required before calling this method.
888
+ *
889
+ * @param {Object} params - Parameters for the API call.
890
+ * @param {string} params.userId - The Firstock user ID (must match the login session).
891
+ * @param {string} params.exchange - The exchange code (e.g., "NSE", "NFO").
892
+ * @param {string} params.tradingSymbol - The trading symbol (e.g., "NIFTY").
893
+ *
894
+ * @param {function} callBack - Callback function with `(error, result)` arguments.
895
+ * On success, result contains an array of expiry dates.
896
+ */
897
+ getExpiry(params: GetExpiryParams, callBack: (error: Error | string | null, result: any | null) => void): void;
898
+ /**
899
+ * Calculates total brokerage charges, taxes, and final costs for a given trade.
900
+ *
901
+ * This API helps estimate the net cost or profitability of a trade before execution.
902
+ * It supports equity and derivatives markets and provides a breakdown of all applicable charges.
903
+ *
904
+ * Requires a valid login session (jKey). Ideal for use before placing or simulating trades.
905
+ *
906
+ * @param {Object} params - Parameters required for brokerage calculation.
907
+ * @param {string} params.userId - The Firstock user ID (must match logged-in session).
908
+ * @param {string} params.exchange - The exchange where the order is placed (e.g., "NSE", "NFO").
909
+ * @param {string} params.tradingSymbol - The symbol of the instrument (e.g., "RELIANCE27FEB25F").
910
+ * @param {string} params.transactionType - The order side: "B" (Buy) or "S" (Sell).
911
+ * @param {string} params.Product - The product type: e.g., "M", "C", "I".
912
+ * @param {string|number} params.quantity - Quantity of the instrument to trade.
913
+ * @param {string|number} params.price - Price at which the order is to be placed.
914
+ * @param {string|number} params.strike_price - Applicable strike price (mandatory for F&O instruments).
915
+ * @param {string} params.inst_name - Instrument name, such as FUTSTK, OPTIDX, etc. (required for derivatives).
916
+ * @param {string|number} params.lot_size - Lot size of the instrument (required for derivatives).
917
+ *
918
+ * @param {function} callBack - Callback function with signature `(error, result)`.
919
+ * On success, result contains detailed brokerage information.
920
+ */
921
+ brokerageCalculator(params: BrokerageCalculatorParams, callBack: (error: Error | string | null, result: any | null) => void): void;
922
+ /**
923
+ * Retrieves holdings details for a user from the Firstock API.
924
+ *
925
+ * This method sends a request to the Firstock holdingsDetails endpoint using the provided
926
+ * user ID and session token (jKey) retrieved from config.json. The response contains the user's holdings information.
927
+ *
928
+ * @param {Object} params - Holdings parameters.
929
+ * @param {string} params.userId - Firstock user ID (e.g., SU2707).
930
+ * @param {function} callBack - Callback with `(error, result)`:
931
+ * - `error`: Error object if the request fails.
932
+ * - `result`: Parsed response containing holdings information if successful.
933
+ */
934
+ getHoldingsDetails({ userId }: GetHoldingsParams, callBack: (error: Error | null, result: Response | null) => void): void;
935
+ }
936
+ export {};