firstock 1.0.8 → 1.0.9

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.
@@ -229,5 +229,35 @@ declare abstract class AFirstock {
229
229
  abstract getExpiry(params: GetExpiryParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
230
230
  abstract brokerageCalculator(params: BrokerageCalculatorParams, callBack: (error: Error | string | null, result: Response | null) => void): void;
231
231
  abstract getHoldingsDetails(params: GetHoldingsParams, callBack: (error: Error | null, result: Response | null) => void): void;
232
+ abstract initializeWebsockets(userId: string, model: any, config?: any): Promise<[any | null, {
233
+ error: {
234
+ message: string;
235
+ };
236
+ } | null]>;
237
+ abstract closeWebsocket(ws: any | null): Promise<{
238
+ error: {
239
+ message: string;
240
+ };
241
+ } | null>;
242
+ abstract subscribe(ws: any | null, tokens: string[]): Promise<{
243
+ error: {
244
+ message: string;
245
+ };
246
+ } | null>;
247
+ abstract unsubscribe(ws: any | null, tokens: string[]): Promise<{
248
+ error: {
249
+ message: string;
250
+ };
251
+ } | null>;
252
+ abstract subscribeOptionGreeks(ws: any | null, tokens: string[]): Promise<{
253
+ error: {
254
+ message: string;
255
+ };
256
+ } | null>;
257
+ abstract unsubscribeOptionGreeks(ws: any | null, tokens: string[]): Promise<{
258
+ error: {
259
+ message: string;
260
+ };
261
+ } | null>;
232
262
  }
233
263
  export default AFirstock;
@@ -1,4 +1,7 @@
1
+ import WebSocket from "ws";
1
2
  import AFirstock from "./AFirstock";
3
+ import { FirstockWebSocket } from "../websockets/websockets";
4
+ import { Config } from "../websockets/websocket_functions";
2
5
  interface Response {
3
6
  data: {
4
7
  [key: string]: any;
@@ -932,5 +935,84 @@ export declare class Firstock extends AFirstock {
932
935
  * - `result`: Parsed response containing holdings information if successful.
933
936
  */
934
937
  getHoldingsDetails({ userId }: GetHoldingsParams, callBack: (error: Error | null, result: Response | null) => void): void;
938
+ /**
939
+ * Initializes a WebSocket connection to Firstock for real-time market data streaming.
940
+ *
941
+ * @param {string} userId - The user ID for authentication.
942
+ * @param {FirstockWebSocket} model - WebSocket model containing tokens and subscriptions.
943
+ * @param {Config} [config] - Optional configuration for WebSocket connection.
944
+ * @returns {Promise<[WebSocket | null, { error: { message: string } } | null]>}
945
+ * A promise that resolves to a tuple containing the WebSocket instance (or null on error)
946
+ * and an error object (or null on success).
947
+ */
948
+ initializeWebsockets(userId: string, model: FirstockWebSocket, config?: Config): Promise<[WebSocket | null, {
949
+ error: {
950
+ message: string;
951
+ };
952
+ } | null]>;
953
+ /**
954
+ * Closes an active WebSocket connection.
955
+ *
956
+ * @param {WebSocket | null} ws - The WebSocket instance to close.
957
+ * @returns {Promise<{ error: { message: string } } | null>}
958
+ * A promise that resolves to an error object if closure fails, or null on success.
959
+ */
960
+ closeWebsocket(ws: WebSocket | null): Promise<{
961
+ error: {
962
+ message: string;
963
+ };
964
+ } | null>;
965
+ /**
966
+ * Subscribes to market data for specified tokens.
967
+ *
968
+ * @param {WebSocket | null} ws - The WebSocket instance.
969
+ * @param {string[]} tokens - Array of token strings to subscribe to.
970
+ * @returns {Promise<{ error: { message: string } } | null>}
971
+ * A promise that resolves to an error object on failure, or null on success.
972
+ */
973
+ subscribe(ws: WebSocket | null, tokens: string[]): Promise<{
974
+ error: {
975
+ message: string;
976
+ };
977
+ } | null>;
978
+ /**
979
+ * Unsubscribes from market data for specified tokens.
980
+ *
981
+ * @param {WebSocket | null} ws - The WebSocket instance.
982
+ * @param {string[]} tokens - Array of token strings to unsubscribe from.
983
+ * @returns {Promise<{ error: { message: string } } | null>}
984
+ * A promise that resolves to an error object on failure, or null on success.
985
+ */
986
+ unsubscribe(ws: WebSocket | null, tokens: string[]): Promise<{
987
+ error: {
988
+ message: string;
989
+ };
990
+ } | null>;
991
+ /**
992
+ * Subscribes to option Greeks data for specified tokens.
993
+ *
994
+ * @param {WebSocket | null} ws - The WebSocket instance.
995
+ * @param {string[]} tokens - Array of option token strings to subscribe to.
996
+ * @returns {Promise<{ error: { message: string } } | null>}
997
+ * A promise that resolves to an error object on failure, or null on success.
998
+ */
999
+ subscribeOptionGreeks(ws: WebSocket | null, tokens: string[]): Promise<{
1000
+ error: {
1001
+ message: string;
1002
+ };
1003
+ } | null>;
1004
+ /**
1005
+ * Unsubscribes from option Greeks data for specified tokens.
1006
+ *
1007
+ * @param {WebSocket | null} ws - The WebSocket instance.
1008
+ * @param {string[]} tokens - Array of option token strings to unsubscribe from.
1009
+ * @returns {Promise<{ error: { message: string } } | null>}
1010
+ * A promise that resolves to an error object on failure, or null on success.
1011
+ */
1012
+ unsubscribeOptionGreeks(ws: WebSocket | null, tokens: string[]): Promise<{
1013
+ error: {
1014
+ message: string;
1015
+ };
1016
+ } | null>;
935
1017
  }
936
1018
  export {};
@@ -32,6 +32,15 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
35
44
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
45
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
46
  };
@@ -39,9 +48,23 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
48
  exports.Firstock = void 0;
40
49
  const axios_1 = __importDefault(require("axios"));
41
50
  const sha256 = __importStar(require("sha256"));
51
+ const ws_1 = __importDefault(require("ws"));
42
52
  const AFirstock_1 = __importDefault(require("./AFirstock"));
43
53
  const commonFunction_1 = require("../shared/commonFunction");
44
54
  const constant_1 = require("../shared/constant");
55
+ const websocket_functions_1 = require("../websockets/websocket_functions");
56
+ // interface Config {
57
+ // scheme?: string;
58
+ // host?: string;
59
+ // path?: string;
60
+ // source?: string;
61
+ // accept_encoding?: string;
62
+ // accept_language?: string;
63
+ // origin?: string;
64
+ // max_websocket_connection_retries?: number;
65
+ // time_interval?: number;
66
+ // [key: string]: any;
67
+ // }
45
68
  const axiosInterceptor = axios_1.default.create({
46
69
  baseURL: constant_1.API_LINK,
47
70
  });
@@ -1821,5 +1844,209 @@ class Firstock extends AFirstock_1.default {
1821
1844
  }
1822
1845
  });
1823
1846
  }
1847
+ // WebSocket methods
1848
+ /**
1849
+ * Initializes a WebSocket connection to Firstock for real-time market data streaming.
1850
+ *
1851
+ * @param {string} userId - The user ID for authentication.
1852
+ * @param {FirstockWebSocket} model - WebSocket model containing tokens and subscriptions.
1853
+ * @param {Config} [config] - Optional configuration for WebSocket connection.
1854
+ * @returns {Promise<[WebSocket | null, { error: { message: string } } | null]>}
1855
+ * A promise that resolves to a tuple containing the WebSocket instance (or null on error)
1856
+ * and an error object (or null on success).
1857
+ */
1858
+ initializeWebsockets(userId, model, config) {
1859
+ return __awaiter(this, void 0, void 0, function* () {
1860
+ const finalConfig = Object.assign({ scheme: 'wss', host: 'socket.firstock.in', path: '/ws', source: 'developer-api', accept_encoding: 'gzip, deflate, br', accept_language: 'en-US,en;q=0.9', origin: 'https://firstock.in', max_websocket_connection_retries: 3, time_interval: 5 }, config);
1861
+ const [baseUrl, headers, err] = (0, websocket_functions_1.getUrlAndHeaderData)(userId, finalConfig);
1862
+ if (err) {
1863
+ return [null, { error: { message: err.message } }];
1864
+ }
1865
+ try {
1866
+ const ws = new ws_1.default(baseUrl, { headers });
1867
+ yield new Promise((resolve, reject) => {
1868
+ const timeout = setTimeout(() => {
1869
+ reject(new Error('Connection timeout'));
1870
+ }, 10000);
1871
+ ws.once('open', () => {
1872
+ clearTimeout(timeout);
1873
+ resolve();
1874
+ });
1875
+ ws.once('error', (error) => {
1876
+ clearTimeout(timeout);
1877
+ reject(error);
1878
+ });
1879
+ });
1880
+ yield websocket_functions_1.connections.addConnection(ws);
1881
+ const msg = yield new Promise((resolve, reject) => {
1882
+ const timeout = setTimeout(() => {
1883
+ reject(new Error('Authentication timeout'));
1884
+ }, 5000);
1885
+ ws.once('message', (data) => {
1886
+ clearTimeout(timeout);
1887
+ resolve(data.toString());
1888
+ });
1889
+ ws.once('error', (error) => {
1890
+ clearTimeout(timeout);
1891
+ reject(error);
1892
+ });
1893
+ });
1894
+ if (msg.includes("Authentication successful")) {
1895
+ yield new Promise(resolve => setTimeout(resolve, 500));
1896
+ const modelDict = model.toDict();
1897
+ (0, websocket_functions_1.readMessage)(userId, ws, modelDict, finalConfig);
1898
+ yield new Promise(resolve => setTimeout(resolve, 500));
1899
+ if (model.tokens && model.tokens.length > 0) {
1900
+ const subscribeErr = yield (0, websocket_functions_1.subscribe)(ws, model.tokens);
1901
+ if (subscribeErr) {
1902
+ }
1903
+ }
1904
+ if (model.option_greeks_tokens && model.option_greeks_tokens.length > 0) {
1905
+ const subscribeErr = yield (0, websocket_functions_1.subscribeOptionGreeks)(ws, model.option_greeks_tokens);
1906
+ if (subscribeErr) {
1907
+ }
1908
+ }
1909
+ return [ws, null];
1910
+ }
1911
+ else if (msg.includes("Maximum sessions limit")) {
1912
+ yield websocket_functions_1.connections.deleteConnection(ws);
1913
+ return [null, { error: { message: msg } }];
1914
+ }
1915
+ else {
1916
+ yield websocket_functions_1.connections.deleteConnection(ws);
1917
+ return [null, { error: { message: `Unexpected authentication response: ${msg}` } }];
1918
+ }
1919
+ }
1920
+ catch (e) {
1921
+ return [null, { error: { message: e.message } }];
1922
+ }
1923
+ });
1924
+ }
1925
+ /**
1926
+ * Closes an active WebSocket connection.
1927
+ *
1928
+ * @param {WebSocket | null} ws - The WebSocket instance to close.
1929
+ * @returns {Promise<{ error: { message: string } } | null>}
1930
+ * A promise that resolves to an error object if closure fails, or null on success.
1931
+ */
1932
+ closeWebsocket(ws) {
1933
+ return __awaiter(this, void 0, void 0, function* () {
1934
+ if (ws === null) {
1935
+ return {
1936
+ error: {
1937
+ message: "Connection does not exist"
1938
+ }
1939
+ };
1940
+ }
1941
+ if (yield websocket_functions_1.connections.checkIfConnectionExists(ws)) {
1942
+ try {
1943
+ ws.close();
1944
+ yield websocket_functions_1.connections.deleteConnection(ws);
1945
+ return null;
1946
+ }
1947
+ catch (e) {
1948
+ const errorMsg = e.message.toLowerCase();
1949
+ if (!errorMsg.includes("closed")) {
1950
+ return {
1951
+ error: {
1952
+ message: e.message
1953
+ }
1954
+ };
1955
+ }
1956
+ else {
1957
+ yield websocket_functions_1.connections.deleteConnection(ws);
1958
+ return null;
1959
+ }
1960
+ }
1961
+ }
1962
+ else {
1963
+ return {
1964
+ error: {
1965
+ message: "Connection does not exist"
1966
+ }
1967
+ };
1968
+ }
1969
+ });
1970
+ }
1971
+ /**
1972
+ * Subscribes to market data for specified tokens.
1973
+ *
1974
+ * @param {WebSocket | null} ws - The WebSocket instance.
1975
+ * @param {string[]} tokens - Array of token strings to subscribe to.
1976
+ * @returns {Promise<{ error: { message: string } } | null>}
1977
+ * A promise that resolves to an error object on failure, or null on success.
1978
+ */
1979
+ subscribe(ws, tokens) {
1980
+ return __awaiter(this, void 0, void 0, function* () {
1981
+ if (ws === null) {
1982
+ return {
1983
+ error: {
1984
+ message: "Connection does not exist"
1985
+ }
1986
+ };
1987
+ }
1988
+ return (0, websocket_functions_1.subscribe)(ws, tokens);
1989
+ });
1990
+ }
1991
+ /**
1992
+ * Unsubscribes from market data for specified tokens.
1993
+ *
1994
+ * @param {WebSocket | null} ws - The WebSocket instance.
1995
+ * @param {string[]} tokens - Array of token strings to unsubscribe from.
1996
+ * @returns {Promise<{ error: { message: string } } | null>}
1997
+ * A promise that resolves to an error object on failure, or null on success.
1998
+ */
1999
+ unsubscribe(ws, tokens) {
2000
+ return __awaiter(this, void 0, void 0, function* () {
2001
+ if (ws === null) {
2002
+ return {
2003
+ error: {
2004
+ message: "Connection does not exist"
2005
+ }
2006
+ };
2007
+ }
2008
+ return (0, websocket_functions_1.unsubscribe)(ws, tokens);
2009
+ });
2010
+ }
2011
+ /**
2012
+ * Subscribes to option Greeks data for specified tokens.
2013
+ *
2014
+ * @param {WebSocket | null} ws - The WebSocket instance.
2015
+ * @param {string[]} tokens - Array of option token strings to subscribe to.
2016
+ * @returns {Promise<{ error: { message: string } } | null>}
2017
+ * A promise that resolves to an error object on failure, or null on success.
2018
+ */
2019
+ subscribeOptionGreeks(ws, tokens) {
2020
+ return __awaiter(this, void 0, void 0, function* () {
2021
+ if (ws === null) {
2022
+ return {
2023
+ error: {
2024
+ message: "Connection does not exist"
2025
+ }
2026
+ };
2027
+ }
2028
+ return (0, websocket_functions_1.subscribeOptionGreeks)(ws, tokens);
2029
+ });
2030
+ }
2031
+ /**
2032
+ * Unsubscribes from option Greeks data for specified tokens.
2033
+ *
2034
+ * @param {WebSocket | null} ws - The WebSocket instance.
2035
+ * @param {string[]} tokens - Array of option token strings to unsubscribe from.
2036
+ * @returns {Promise<{ error: { message: string } } | null>}
2037
+ * A promise that resolves to an error object on failure, or null on success.
2038
+ */
2039
+ unsubscribeOptionGreeks(ws, tokens) {
2040
+ return __awaiter(this, void 0, void 0, function* () {
2041
+ if (ws === null) {
2042
+ return {
2043
+ error: {
2044
+ message: "Connection does not exist"
2045
+ }
2046
+ };
2047
+ }
2048
+ return (0, websocket_functions_1.unsubscribeOptionGreeks)(ws, tokens);
2049
+ });
2050
+ }
1824
2051
  }
1825
2052
  exports.Firstock = Firstock;
package/dist/test.js CHANGED
@@ -7,11 +7,11 @@ const index_1 = __importDefault(require("./index"));
7
7
  const firstock = new index_1.default();
8
8
  let orderNumber = "";
9
9
  const userDetails = {
10
- userId: "NP2997",
11
- password: "Skanda@2025",
12
- TOTP: "1997",
13
- vendorCode: "NP2997_API",
14
- apiKey: "e55eb28e18ee1337fc0b2705f9b82465",
10
+ userId: "CM2096",
11
+ password: "Leaveme@L0ne",
12
+ TOTP: "1996",
13
+ vendorCode: "FIRSTOCK_MST_KEY",
14
+ apiKey: "Nco@MS7K8t",
15
15
  };
16
16
  // const userDetails = {
17
17
  // userId: "",
@@ -1,5 +1,5 @@
1
1
  import WebSocket from 'ws';
2
- import { Config, WebSocketModel } from './websocket_functions';
2
+ import { WebSocketModel } from './websocket_functions';
3
3
  export declare class FirstockWebSocket {
4
4
  tokens?: string[];
5
5
  option_greeks_tokens?: string[];
@@ -19,35 +19,3 @@ export declare class FirstockWebSocket {
19
19
  });
20
20
  toDict(): WebSocketModel;
21
21
  }
22
- export declare class Firstock {
23
- static initializeWebsockets(userId: string, model: FirstockWebSocket, config?: Config): Promise<[WebSocket | null, {
24
- error: {
25
- message: string;
26
- };
27
- } | null]>;
28
- static closeWebsocket(ws: WebSocket | null): Promise<{
29
- error: {
30
- message: string;
31
- };
32
- } | null>;
33
- static subscribe(ws: WebSocket | null, tokens: string[]): Promise<{
34
- error: {
35
- message: string;
36
- };
37
- } | null>;
38
- static unsubscribe(ws: WebSocket | null, tokens: string[]): Promise<{
39
- error: {
40
- message: string;
41
- };
42
- } | null>;
43
- static subscribeOptionGreeks(ws: WebSocket | null, tokens: string[]): Promise<{
44
- error: {
45
- message: string;
46
- };
47
- } | null>;
48
- static unsubscribeOptionGreeks(ws: WebSocket | null, tokens: string[]): Promise<{
49
- error: {
50
- message: string;
51
- };
52
- } | null>;
53
- }
@@ -1,20 +1,6 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.Firstock = exports.FirstockWebSocket = void 0;
16
- const ws_1 = __importDefault(require("ws"));
17
- const websocket_functions_1 = require("./websocket_functions");
3
+ exports.FirstockWebSocket = void 0;
18
4
  const logger = {
19
5
  info: (msg) => console.info(`[INFO] ${new Date().toISOString()} - ${msg}`),
20
6
  error: (msg, err) => {
@@ -46,168 +32,176 @@ class FirstockWebSocket {
46
32
  }
47
33
  }
48
34
  exports.FirstockWebSocket = FirstockWebSocket;
49
- class Firstock {
50
- static initializeWebsockets(userId, model, config) {
51
- return __awaiter(this, void 0, void 0, function* () {
52
- const finalConfig = Object.assign({ scheme: 'wss', host: 'socket.firstock.in', path: '/ws', source: 'developer-api', accept_encoding: 'gzip, deflate, br', accept_language: 'en-US,en;q=0.9', origin: 'https://firstock.in', max_websocket_connection_retries: 3, time_interval: 5 }, config);
53
- const [baseUrl, headers, err] = (0, websocket_functions_1.getUrlAndHeaderData)(userId, finalConfig);
54
- if (err) {
55
- return [null, { error: { message: err.message } }];
56
- }
57
- try {
58
- const ws = new ws_1.default(baseUrl, { headers });
59
- yield new Promise((resolve, reject) => {
60
- const timeout = setTimeout(() => {
61
- reject(new Error('Connection timeout'));
62
- }, 10000);
63
- ws.once('open', () => {
64
- clearTimeout(timeout);
65
- resolve();
66
- });
67
- ws.once('error', (error) => {
68
- clearTimeout(timeout);
69
- reject(error);
70
- });
71
- });
72
- logger.info("WebSocket connection created");
73
- yield websocket_functions_1.connections.addConnection(ws);
74
- const msg = yield new Promise((resolve, reject) => {
75
- const timeout = setTimeout(() => {
76
- reject(new Error('Authentication timeout'));
77
- }, 5000);
78
- ws.once('message', (data) => {
79
- clearTimeout(timeout);
80
- resolve(data.toString());
81
- });
82
- ws.once('error', (error) => {
83
- clearTimeout(timeout);
84
- reject(error);
85
- });
86
- });
87
- logger.info(`Initial message received: ${msg}`);
88
- if (msg.includes("Authentication successful")) {
89
- logger.info("Authentication successful, starting message reader");
90
- yield new Promise(resolve => setTimeout(resolve, 500));
91
- const modelDict = model.toDict();
92
- (0, websocket_functions_1.readMessage)(userId, ws, modelDict, finalConfig);
93
- yield new Promise(resolve => setTimeout(resolve, 500));
94
- if (model.tokens && model.tokens.length > 0) {
95
- logger.info(`Subscribing to initial tokens: ${model.tokens.join(', ')}`);
96
- const subscribeErr = yield (0, websocket_functions_1.subscribe)(ws, model.tokens);
97
- if (subscribeErr) {
98
- logger.error(`Initial subscription error: ${JSON.stringify(subscribeErr)}`);
99
- }
100
- }
101
- if (model.option_greeks_tokens && model.option_greeks_tokens.length > 0) {
102
- logger.info(`Subscribing to option Greeks tokens: ${model.option_greeks_tokens.join(', ')}`);
103
- const subscribeErr = yield (0, websocket_functions_1.subscribeOptionGreeks)(ws, model.option_greeks_tokens);
104
- if (subscribeErr) {
105
- logger.error(`Initial option Greeks subscription error: ${JSON.stringify(subscribeErr)}`);
106
- }
107
- }
108
- return [ws, null];
109
- }
110
- else if (msg.includes("Maximum sessions limit")) {
111
- yield websocket_functions_1.connections.deleteConnection(ws);
112
- return [null, { error: { message: msg } }];
113
- }
114
- else {
115
- yield websocket_functions_1.connections.deleteConnection(ws);
116
- return [null, { error: { message: `Unexpected authentication response: ${msg}` } }];
117
- }
118
- }
119
- catch (e) {
120
- logger.error(`WebSocket initialization error: ${e.message}`, e);
121
- return [null, { error: { message: e.message } }];
122
- }
123
- });
124
- }
125
- static closeWebsocket(ws) {
126
- return __awaiter(this, void 0, void 0, function* () {
127
- if (ws === null) {
128
- return {
129
- error: {
130
- message: "Connection does not exist"
131
- }
132
- };
133
- }
134
- if (yield websocket_functions_1.connections.checkIfConnectionExists(ws)) {
135
- try {
136
- ws.close();
137
- yield websocket_functions_1.connections.deleteConnection(ws);
138
- return null;
139
- }
140
- catch (e) {
141
- const errorMsg = e.message.toLowerCase();
142
- if (!errorMsg.includes("closed")) {
143
- return {
144
- error: {
145
- message: e.message
146
- }
147
- };
148
- }
149
- else {
150
- yield websocket_functions_1.connections.deleteConnection(ws);
151
- return null;
152
- }
153
- }
154
- }
155
- else {
156
- return {
157
- error: {
158
- message: "Connection does not exist"
159
- }
160
- };
161
- }
162
- });
163
- }
164
- static subscribe(ws, tokens) {
165
- return __awaiter(this, void 0, void 0, function* () {
166
- if (ws === null) {
167
- return {
168
- error: {
169
- message: "Connection does not exist"
170
- }
171
- };
172
- }
173
- return (0, websocket_functions_1.subscribe)(ws, tokens);
174
- });
175
- }
176
- static unsubscribe(ws, tokens) {
177
- return __awaiter(this, void 0, void 0, function* () {
178
- if (ws === null) {
179
- return {
180
- error: {
181
- message: "Connection does not exist"
182
- }
183
- };
184
- }
185
- return (0, websocket_functions_1.unsubscribe)(ws, tokens);
186
- });
187
- }
188
- static subscribeOptionGreeks(ws, tokens) {
189
- return __awaiter(this, void 0, void 0, function* () {
190
- if (ws === null) {
191
- return {
192
- error: {
193
- message: "Connection does not exist"
194
- }
195
- };
196
- }
197
- return (0, websocket_functions_1.subscribeOptionGreeks)(ws, tokens);
198
- });
199
- }
200
- static unsubscribeOptionGreeks(ws, tokens) {
201
- return __awaiter(this, void 0, void 0, function* () {
202
- if (ws === null) {
203
- return {
204
- error: {
205
- message: "Connection does not exist"
206
- }
207
- };
208
- }
209
- return (0, websocket_functions_1.unsubscribeOptionGreeks)(ws, tokens);
210
- });
211
- }
212
- }
213
- exports.Firstock = Firstock;
35
+ // export class Firstock {
36
+ // static async initializeWebsockets(
37
+ // userId: string,
38
+ // model: FirstockWebSocket,
39
+ // config?: Config
40
+ // ): Promise<[WebSocket | null, { error: { message: string } } | null]> {
41
+ // const finalConfig: Config = {
42
+ // scheme: 'wss',
43
+ // host: 'socket.firstock.in',
44
+ // path: '/ws',
45
+ // source: 'developer-api',
46
+ // accept_encoding: 'gzip, deflate, br',
47
+ // accept_language: 'en-US,en;q=0.9',
48
+ // origin: 'https://firstock.in',
49
+ // max_websocket_connection_retries: 3,
50
+ // time_interval: 5,
51
+ // ...config
52
+ // };
53
+ // const [baseUrl, headers, err] = getUrlAndHeaderData(userId, finalConfig);
54
+ // if (err) {
55
+ // return [null, { error: { message: err.message } }];
56
+ // }
57
+ // try {
58
+ // const ws = new WebSocket(baseUrl, { headers });
59
+ // await new Promise<void>((resolve, reject) => {
60
+ // const timeout = setTimeout(() => {
61
+ // reject(new Error('Connection timeout'));
62
+ // }, 10000);
63
+ // ws.once('open', () => {
64
+ // clearTimeout(timeout);
65
+ // resolve();
66
+ // });
67
+ // ws.once('error', (error) => {
68
+ // clearTimeout(timeout);
69
+ // reject(error);
70
+ // });
71
+ // });
72
+ // logger.info("WebSocket connection created");
73
+ // await connections.addConnection(ws);
74
+ // const msg = await new Promise<string>((resolve, reject) => {
75
+ // const timeout = setTimeout(() => {
76
+ // reject(new Error('Authentication timeout'));
77
+ // }, 5000);
78
+ // ws.once('message', (data) => {
79
+ // clearTimeout(timeout);
80
+ // resolve(data.toString());
81
+ // });
82
+ // ws.once('error', (error) => {
83
+ // clearTimeout(timeout);
84
+ // reject(error);
85
+ // });
86
+ // });
87
+ // logger.info(`Initial message received: ${msg}`);
88
+ // if (msg.includes("Authentication successful")) {
89
+ // logger.info("Authentication successful, starting message reader");
90
+ // await new Promise(resolve => setTimeout(resolve, 500));
91
+ // const modelDict = model.toDict();
92
+ // readMessage(userId, ws, modelDict, finalConfig);
93
+ // await new Promise(resolve => setTimeout(resolve, 500));
94
+ // if (model.tokens && model.tokens.length > 0) {
95
+ // logger.info(`Subscribing to initial tokens: ${model.tokens.join(', ')}`);
96
+ // const subscribeErr = await subscribeHelper(ws, model.tokens);
97
+ // if (subscribeErr) {
98
+ // logger.error(`Initial subscription error: ${JSON.stringify(subscribeErr)}`);
99
+ // }
100
+ // }
101
+ // if (model.option_greeks_tokens && model.option_greeks_tokens.length > 0) {
102
+ // logger.info(`Subscribing to option Greeks tokens: ${model.option_greeks_tokens.join(', ')}`);
103
+ // const subscribeErr = await subscribeOptionGreeksHelper(ws, model.option_greeks_tokens);
104
+ // if (subscribeErr) {
105
+ // logger.error(`Initial option Greeks subscription error: ${JSON.stringify(subscribeErr)}`);
106
+ // }
107
+ // }
108
+ // return [ws, null];
109
+ // } else if (msg.includes("Maximum sessions limit")) {
110
+ // await connections.deleteConnection(ws);
111
+ // return [null, { error: { message: msg } }];
112
+ // } else {
113
+ // await connections.deleteConnection(ws);
114
+ // return [null, { error: { message: `Unexpected authentication response: ${msg}` } }];
115
+ // }
116
+ // } catch (e) {
117
+ // logger.error(`WebSocket initialization error: ${(e as Error).message}`, e as Error);
118
+ // return [null, { error: { message: (e as Error).message } }];
119
+ // }
120
+ // }
121
+ // static async closeWebsocket(ws: WebSocket | null): Promise<{ error: { message: string } } | null> {
122
+ // if (ws === null) {
123
+ // return {
124
+ // error: {
125
+ // message: "Connection does not exist"
126
+ // }
127
+ // };
128
+ // }
129
+ // if (await connections.checkIfConnectionExists(ws)) {
130
+ // try {
131
+ // ws.close();
132
+ // await connections.deleteConnection(ws);
133
+ // return null;
134
+ // } catch (e) {
135
+ // const errorMsg = (e as Error).message.toLowerCase();
136
+ // if (!errorMsg.includes("closed")) {
137
+ // return {
138
+ // error: {
139
+ // message: (e as Error).message
140
+ // }
141
+ // };
142
+ // } else {
143
+ // await connections.deleteConnection(ws);
144
+ // return null;
145
+ // }
146
+ // }
147
+ // } else {
148
+ // return {
149
+ // error: {
150
+ // message: "Connection does not exist"
151
+ // }
152
+ // };
153
+ // }
154
+ // }
155
+ // static async subscribe(
156
+ // ws: WebSocket | null,
157
+ // tokens: string[]
158
+ // ): Promise<{ error: { message: string } } | null> {
159
+ // if (ws === null) {
160
+ // return {
161
+ // error: {
162
+ // message: "Connection does not exist"
163
+ // }
164
+ // };
165
+ // }
166
+ // return subscribeHelper(ws, tokens);
167
+ // }
168
+ // static async unsubscribe(
169
+ // ws: WebSocket | null,
170
+ // tokens: string[]
171
+ // ): Promise<{ error: { message: string } } | null> {
172
+ // if (ws === null) {
173
+ // return {
174
+ // error: {
175
+ // message: "Connection does not exist"
176
+ // }
177
+ // };
178
+ // }
179
+ // return unsubscribeHelper(ws, tokens);
180
+ // }
181
+ // static async subscribeOptionGreeks(
182
+ // ws: WebSocket | null,
183
+ // tokens: string[]
184
+ // ): Promise<{ error: { message: string } } | null> {
185
+ // if (ws === null) {
186
+ // return {
187
+ // error: {
188
+ // message: "Connection does not exist"
189
+ // }
190
+ // };
191
+ // }
192
+ // return subscribeOptionGreeksHelper(ws, tokens);
193
+ // }
194
+ // static async unsubscribeOptionGreeks(
195
+ // ws: WebSocket | null,
196
+ // tokens: string[]
197
+ // ): Promise<{ error: { message: string } } | null> {
198
+ // if (ws === null) {
199
+ // return {
200
+ // error: {
201
+ // message: "Connection does not exist"
202
+ // }
203
+ // };
204
+ // }
205
+ // return unsubscribeOptionGreeksHelper(ws, tokens);
206
+ // }
207
+ // }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "firstock",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "Node js package for using firstock developer apis",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -11,6 +11,7 @@
11
11
  "LICENSE"
12
12
  ],
13
13
  "scripts": {
14
+ "test:ws": "ts-node test_websockets.js",
14
15
  "build": "tsc",
15
16
  "prepublishOnly": "npm run build",
16
17
  "test": "echo \"Error: no test specified\" && exit 1"