market-data-tradingview-ws 0.1.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +928 -206
- package/lib/proxy.js +114 -0
- package/lib/tradingView.js +111 -147
- package/lib/utils.js +48 -33
- package/package.json +6 -1
package/lib/proxy.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { fetch, Socks5ProxyAgent } = require('undici');
|
|
4
|
+
const { SocksProxyAgent } = require('socks-proxy-agent');
|
|
5
|
+
|
|
6
|
+
const HTTP_TIMEOUT = 12_000;
|
|
7
|
+
|
|
8
|
+
let cachedProxyUrl = null;
|
|
9
|
+
let cachedDispatcher = null;
|
|
10
|
+
let cachedWebSocketAgent = null;
|
|
11
|
+
|
|
12
|
+
function resetWebSocketAgent() {
|
|
13
|
+
const agent = cachedWebSocketAgent;
|
|
14
|
+
cachedWebSocketAgent = null;
|
|
15
|
+
if (agent) agent.destroy();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function closeProxyAgents() {
|
|
19
|
+
resetWebSocketAgent();
|
|
20
|
+
await resetProxyDispatcher();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function resolveProxy(proxy, type) {
|
|
24
|
+
if (!proxy || typeof proxy !== 'object') return null;
|
|
25
|
+
if (proxy.url || proxy.host || proxy.port) return type === 'ws' ? null : proxy;
|
|
26
|
+
let value = proxy[type];
|
|
27
|
+
|
|
28
|
+
if (value === undefined && ['authentication', 'token', 'logout'].includes(type)) value = proxy.http;
|
|
29
|
+
if (!value || value === false || value.enabled === false) return null;
|
|
30
|
+
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function buildProxyUrl(proxy) {
|
|
35
|
+
if (!proxy || typeof proxy !== 'object') return null;
|
|
36
|
+
const { url, protocol, host, port, username, password } = proxy;
|
|
37
|
+
|
|
38
|
+
if (url && url.trim()) return url.trim();
|
|
39
|
+
if (!host && !port) return null;
|
|
40
|
+
if (!host || !port) throw new Error('Marketdata TV proxy host or port is not configured');
|
|
41
|
+
|
|
42
|
+
const auth = username || password ? `${encodeURIComponent(username || '')}:${encodeURIComponent(password || '')}@` : '';
|
|
43
|
+
return `${protocol || 'socks5'}://${auth}${host}:${port}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function getProxyDispatcher(proxy = {}) {
|
|
47
|
+
const proxyUrl = buildProxyUrl(proxy);
|
|
48
|
+
if (!proxyUrl) return null;
|
|
49
|
+
if (cachedDispatcher && cachedProxyUrl === proxyUrl) return cachedDispatcher;
|
|
50
|
+
|
|
51
|
+
if (cachedDispatcher) {
|
|
52
|
+
cachedDispatcher.destroy().catch(() => {});
|
|
53
|
+
cachedDispatcher = null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
cachedProxyUrl = proxyUrl;
|
|
57
|
+
cachedDispatcher = new Socks5ProxyAgent(proxyUrl);
|
|
58
|
+
return cachedDispatcher;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function resetProxyDispatcher(error) {
|
|
62
|
+
const dispatcher = cachedDispatcher;
|
|
63
|
+
|
|
64
|
+
cachedProxyUrl = null;
|
|
65
|
+
cachedDispatcher = null;
|
|
66
|
+
|
|
67
|
+
if (!dispatcher) return;
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
await dispatcher.destroy(error);
|
|
71
|
+
} catch {}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function getWebSocketAgent(proxy = null) {
|
|
75
|
+
const proxyUrl = buildProxyUrl(proxy);
|
|
76
|
+
|
|
77
|
+
if (!proxyUrl) {
|
|
78
|
+
resetWebSocketAgent();
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
cachedWebSocketAgent?.destroy();
|
|
83
|
+
cachedWebSocketAgent = new SocksProxyAgent(proxyUrl, { timeout: 20_000 });
|
|
84
|
+
|
|
85
|
+
return cachedWebSocketAgent;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function fetchWithProxy(url, options = {}, proxy = null) {
|
|
89
|
+
const dispatcher = getProxyDispatcher(proxy);
|
|
90
|
+
const timeoutSignal = AbortSignal.timeout(HTTP_TIMEOUT);
|
|
91
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
|
|
92
|
+
console.debug('TV HTTP request:', { proxy: Boolean(dispatcher), timeout: HTTP_TIMEOUT });
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
const requestOptions = { ...options, signal };
|
|
96
|
+
if (!dispatcher) return await fetch(url, requestOptions);
|
|
97
|
+
|
|
98
|
+
return await fetch(url, { ...requestOptions, dispatcher });
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (dispatcher) await resetProxyDispatcher(error);
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
module.exports = {
|
|
106
|
+
fetch,
|
|
107
|
+
fetchWithProxy,
|
|
108
|
+
resolveProxy,
|
|
109
|
+
buildProxyUrl,
|
|
110
|
+
getProxyDispatcher,
|
|
111
|
+
resetProxyDispatcher,
|
|
112
|
+
getWebSocketAgent,
|
|
113
|
+
closeProxyAgents,
|
|
114
|
+
};
|
package/lib/tradingView.js
CHANGED
|
@@ -1,130 +1,122 @@
|
|
|
1
|
+
/* eslint-disable prefer-const */
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
|
-
const
|
|
4
|
-
const cleanerRgx = /~h~/g;
|
|
5
|
-
const splitterRgx = /~m~[0-9]{1,}~m~/g;
|
|
6
|
-
const urlSymbolSearch = 'https://symbol-search.tradingview.com/symbol_search';
|
|
7
|
-
const urlwwwTV = 'https://www.tradingview.com';
|
|
4
|
+
const utils = require('./utils.js');
|
|
8
5
|
const urlRuTV = 'https://ru.tradingview.com';
|
|
6
|
+
const urlWwwTV = 'https://www.tradingview.com';
|
|
7
|
+
const { fetchWithProxy, resolveProxy } = require('./proxy');
|
|
9
8
|
|
|
10
9
|
class TradingView {
|
|
11
|
-
async authentication({ login,
|
|
12
|
-
const url =
|
|
13
|
-
const headers = {
|
|
14
|
-
Referer: urlwwwTV,
|
|
15
|
-
};
|
|
16
|
-
|
|
10
|
+
async authentication({ login, password, proxy }) {
|
|
11
|
+
const url = urlWwwTV + '/accounts/signin/';
|
|
17
12
|
const form = new FormData();
|
|
18
13
|
form.append('username', login);
|
|
19
|
-
form.append('password',
|
|
14
|
+
form.append('password', password || '');
|
|
20
15
|
form.append('remember', 'on');
|
|
16
|
+
|
|
17
|
+
const res = await fetchWithProxy(url, {
|
|
18
|
+
method: 'POST',
|
|
19
|
+
headers: { Referer: urlWwwTV },
|
|
20
|
+
body: form,
|
|
21
|
+
}, resolveProxy(proxy, 'authentication'));
|
|
22
|
+
if (!res.ok) throw new Error('Failed to authenticate, status: ' + res.status);
|
|
23
|
+
|
|
24
|
+
let cookies = [];
|
|
25
|
+
if (typeof res.headers.getSetCookie === 'function') cookies = res.headers.getSetCookie();
|
|
26
|
+
else if (typeof res.headers.raw === 'function') cookies = res.headers.raw()['set-cookie'] || [];
|
|
27
|
+
else {
|
|
28
|
+
const one = res.headers.get('set-cookie');
|
|
29
|
+
if (one) cookies = [one];
|
|
30
|
+
}
|
|
21
31
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
if (!res.ok) throw new Error('Failed to get auth_token, status: ' + res.status);
|
|
30
|
-
|
|
31
|
-
const rawSetCookie = response.headers.raw()['set-cookie'];
|
|
32
|
-
console.log('Raw Set-Cookie headers:', rawSetCookie);
|
|
33
|
-
let sessionid, sessionid_sign;
|
|
34
|
-
for (const cookie of rawSetCookie) {
|
|
35
|
-
if (cookie.startsWith('sessionid=')) sessionid = cookie.split(';')[0].split('=')[1];
|
|
36
|
-
if (cookie.startsWith('sessionid_sign=')) sessionid_sign = cookie.split(';')[0].split('=')[1];
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const data = await res.json();
|
|
40
|
-
if (!data?.user?.auth_token) throw new Error('Error get auth_token, no auth_token in response');
|
|
41
|
-
return { sessionid, sessionid_sign, token: data.user.auth_token };
|
|
42
|
-
} catch (error) {
|
|
43
|
-
throw new Error('Authentication failed: ' + error.message);
|
|
32
|
+
let sessionId = '';
|
|
33
|
+
let sessionIdSign = '';
|
|
34
|
+
for (const cookie of cookies) {
|
|
35
|
+
if (cookie.startsWith('sessionid=')) sessionId = cookie.split(';')[0].split('=')[1] || '';
|
|
36
|
+
if (cookie.startsWith('sessionid_sign=')) sessionIdSign = cookie.split(';')[0].split('=')[1] || '';
|
|
44
37
|
}
|
|
45
|
-
}
|
|
46
38
|
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
39
|
+
const data = await res.json();
|
|
40
|
+
const token = data?.user?.auth_token;
|
|
41
|
+
if (!token) throw new Error('Error get auth_token, no auth_token in response');
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
sessionId,
|
|
45
|
+
sessionIdSign,
|
|
46
|
+
token,
|
|
47
|
+
// backward compatibility
|
|
48
|
+
sessionid: sessionId,
|
|
49
|
+
sessionidsign: sessionIdSign,
|
|
53
50
|
};
|
|
51
|
+
}
|
|
54
52
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
53
|
+
async getToken({ sessionId, sessionIdSign, tvEcuid, imageUrl, sessionid, sessionidsign, tvecuid, imageurl, proxy, signal }) {
|
|
54
|
+
const sid = sessionId || sessionid;
|
|
55
|
+
const sign = sessionIdSign || sessionidsign;
|
|
56
|
+
const ecuid = tvEcuid || tvecuid;
|
|
57
|
+
const chartId = imageUrl || imageurl;
|
|
58
|
+
const url = urlRuTV + '/chart/' + chartId;
|
|
59
|
+
const cookie = 'tv_ecuid=' + ecuid + '; sessionid=' + sid + '; sessionid_sign=' + sign;
|
|
60
|
+
const headers = { accept: 'text/html', cookie };
|
|
61
|
+
const requestProxy = resolveProxy(proxy, 'token');
|
|
62
|
+
|
|
63
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
64
|
+
const startedAt = Date.now();
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
const res = await fetchWithProxy(url, { method: 'GET', headers, signal }, requestProxy);
|
|
68
|
+
|
|
69
|
+
console.warn('Response status:', res.status);
|
|
70
|
+
const html = await res.text();
|
|
71
|
+
|
|
72
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
73
|
+
|
|
74
|
+
const match = html.match(/"auth_token"\s*:\s*"([^"]+)"/);
|
|
75
|
+
const token = match ? match[1] : null;
|
|
76
|
+
if (!token) throw new Error('Auth token not found in HTML');
|
|
77
|
+
|
|
78
|
+
console.warn('✅ Auth token found');
|
|
79
|
+
return token;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
const aborted = signal?.aborted === true || error?.name === 'AbortError';
|
|
82
|
+
console.warn('❌ TV getToken failed:', { attempt, ms: Date.now() - startedAt, name: error?.name, code: error?.cause?.code || error?.code, message: error?.message || String(error), aborted });
|
|
83
|
+
if (aborted) {
|
|
84
|
+
const cancelled = new Error('Connection cancelled');
|
|
85
|
+
cancelled.code = 'CONNECT_CANCELLED';
|
|
86
|
+
throw cancelled;
|
|
87
|
+
}
|
|
88
|
+
if (attempt === 2) throw error;
|
|
89
|
+
|
|
90
|
+
await utils.pause(500)
|
|
65
91
|
}
|
|
66
|
-
return token;
|
|
67
|
-
} catch (err) {
|
|
68
|
-
console.error('❌ Error fetching token:', err.message);
|
|
69
|
-
return null;
|
|
70
92
|
}
|
|
71
93
|
}
|
|
72
94
|
|
|
73
|
-
async disconnect({ sessionid, sessionidsign }) {
|
|
74
|
-
const
|
|
95
|
+
async disconnect({ sessionId, sessionIdSign, sessionid, sessionidsign, proxy }) {
|
|
96
|
+
const sid = sessionId || sessionid;
|
|
97
|
+
const sign = sessionIdSign || sessionidsign;
|
|
98
|
+
if (!sid || !sign) return true;
|
|
99
|
+
const cookie = 'sessionid=' + sid + '; sessionid_sign=' + sign;
|
|
75
100
|
const headers = {
|
|
76
101
|
Origin: urlRuTV,
|
|
77
102
|
Referer: urlRuTV + '/u/PartnerFinance/',
|
|
103
|
+
cookie,
|
|
78
104
|
};
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
// headers,
|
|
84
|
-
// });
|
|
85
|
-
|
|
86
|
-
// if (!res.ok) throw new Error('Failed to disconnect, status: ' + res.status);
|
|
87
|
-
return true;
|
|
88
|
-
} catch (error) {
|
|
89
|
-
throw new Error('Disconnection failed: ' + error.message);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async getSymbol({ symbol, type }) {
|
|
94
|
-
// type = 'stock' | 'futures' | 'forex' | 'cfd' | 'crypto' | 'index' | 'economic'
|
|
95
|
-
// query = what you want to search!
|
|
96
|
-
// it returns first matching item
|
|
97
|
-
try {
|
|
98
|
-
const res = await fetch(urlSymbolSearch + '?text=' + symbol + '&type=' + type);
|
|
99
|
-
if (res.status === 200) {
|
|
100
|
-
const data = await res.json();
|
|
101
|
-
// console.log(data);
|
|
102
|
-
return data[0];
|
|
103
|
-
}
|
|
104
|
-
throw new Error('Failed to fetch symbol data');
|
|
105
|
-
} catch (error) {
|
|
106
|
-
console.error('Error in getSymbol:', error.message);
|
|
107
|
-
return 'Network Error!';
|
|
108
|
-
}
|
|
105
|
+
|
|
106
|
+
const res = await fetchWithProxy(urlRuTV + '/accounts/logout/', { method: 'POST', headers }, resolveProxy(proxy, 'logout'));
|
|
107
|
+
if (!res.ok) throw new Error('Failed to disconnect, status: ' + res.status);
|
|
108
|
+
return true;
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
-
// getSymbolId({ data }) {
|
|
112
|
-
// const name = data.type === 'futures' ? data.contracts[0].symbol : data.symbol;
|
|
113
|
-
// return data.exchange.toUpperCase() + ':' + name.toUpperCase();
|
|
114
|
-
// }
|
|
115
|
-
|
|
116
111
|
createSession({ startsWith }) {
|
|
117
112
|
if (typeof startsWith !== 'string' || startsWith.length === 0) {
|
|
118
113
|
throw new Error('Invalid startsWith parameter');
|
|
119
114
|
}
|
|
120
|
-
|
|
121
|
-
while (session.length < 12) session += letters[Math.floor(Math.random() * letters.length)];
|
|
122
|
-
return session;
|
|
115
|
+
return utils.createSession(startsWith, 12);
|
|
123
116
|
}
|
|
124
117
|
|
|
125
118
|
formatWSPacket({ packet }) {
|
|
126
|
-
|
|
127
|
-
return '~m~' + msg.length + '~m~' + msg;
|
|
119
|
+
return utils.formatWSPacket(packet);
|
|
128
120
|
}
|
|
129
121
|
|
|
130
122
|
parsePacket({ str }) {
|
|
@@ -136,50 +128,35 @@ class TradingView {
|
|
|
136
128
|
}
|
|
137
129
|
|
|
138
130
|
parseWSPacket({ str }) {
|
|
139
|
-
return str
|
|
140
|
-
.toString()
|
|
141
|
-
.replace(cleanerRgx, '')
|
|
142
|
-
.split(splitterRgx)
|
|
143
|
-
.map((p) => {
|
|
144
|
-
if (!p) return false;
|
|
145
|
-
try {
|
|
146
|
-
return JSON.parse(p);
|
|
147
|
-
} catch (error) {
|
|
148
|
-
console.error('Cant parse', p);
|
|
149
|
-
return false;
|
|
150
|
-
}
|
|
151
|
-
})
|
|
152
|
-
.filter((p) => p);
|
|
131
|
+
return utils.parseWSPacket(str);
|
|
153
132
|
}
|
|
154
133
|
|
|
155
134
|
eachPacket(packet) {
|
|
156
135
|
if (typeof packet === 'number') {
|
|
157
136
|
return { type: 'ping', data: packet }; // Ping
|
|
137
|
+
} else if (packet.session_id) {
|
|
138
|
+
return { type: 'session', data: packet };
|
|
158
139
|
} else if (packet.m && packet.p) {
|
|
159
|
-
|
|
160
|
-
// if (packet.m.startsWith('du')) return { type: packet.m, data: packet.p };
|
|
161
|
-
if (packet.m.startsWith('timescale') || packet.m.startsWith('qsd') || packet.m.startsWith('du'))
|
|
140
|
+
if (packet.m.startsWith('timescale') || packet.m.startsWith('qsd') || packet.m.startsWith('du')) {
|
|
162
141
|
return { type: packet.m, data: packet.p };
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
// ['data', packet.p],
|
|
166
|
-
// ]);
|
|
142
|
+
}
|
|
143
|
+
|
|
167
144
|
if (packet.m.startsWith('series') || packet.m.startsWith('symbol') || packet.m.startsWith('quote')) {
|
|
168
145
|
const type = packet.m.split('_');
|
|
169
|
-
return {
|
|
170
|
-
|
|
171
|
-
|
|
146
|
+
return {
|
|
147
|
+
type: type[0],
|
|
148
|
+
data: { sub: type[1], detail: packet.p, time: packet.t_ms || Date.now() },
|
|
149
|
+
};
|
|
172
150
|
}
|
|
173
|
-
// const session = packet.p[0];
|
|
174
151
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
152
|
+
return {
|
|
153
|
+
type: 'msg',
|
|
154
|
+
data: {
|
|
155
|
+
sub: packet.m,
|
|
156
|
+
detail: packet.p,
|
|
157
|
+
time: packet.t_ms || Date.now(),
|
|
158
|
+
},
|
|
159
|
+
};
|
|
183
160
|
} else {
|
|
184
161
|
return { type: 'msgError', data: packet }; // Error
|
|
185
162
|
}
|
|
@@ -197,10 +174,6 @@ class TradingView {
|
|
|
197
174
|
return this.formatWSPacket({ packet: { m: 'set_locale', p: ['ru', 'RU'] } });
|
|
198
175
|
}
|
|
199
176
|
|
|
200
|
-
// setFieldsQuote({ session }) {
|
|
201
|
-
// return this.formatWSPacket({ packet: { m: 'quote_set_fields', p: [session, 'lp'] } });
|
|
202
|
-
// }
|
|
203
|
-
|
|
204
177
|
// При установлении уменьшает набор полей до выбранных, без этого свойства дает наиболее полный набор
|
|
205
178
|
setFieldsSmall({ session }) {
|
|
206
179
|
return this.formatWSPacket({
|
|
@@ -293,14 +266,6 @@ class TradingView {
|
|
|
293
266
|
});
|
|
294
267
|
}
|
|
295
268
|
|
|
296
|
-
// ничего не пришло, требует изучения
|
|
297
|
-
quoteFastSymbol({ session, symbol }) {
|
|
298
|
-
// console.log('quoteFastSymbol', session, symbol);
|
|
299
|
-
return this.formatWSPacket({
|
|
300
|
-
packet: { m: 'quote_fast_symbols', p: [session, '={"adjustment":"splits","currency-id":"USD","symbol":"' + symbol + '"}'] },
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
|
|
304
269
|
quoteRemoveSymbols({ session, symbol }) {
|
|
305
270
|
return this.formatWSPacket({ packet: { m: 'quote_remove_symbols', p: [session, symbol] } });
|
|
306
271
|
}
|
|
@@ -333,6 +298,10 @@ class TradingView {
|
|
|
333
298
|
});
|
|
334
299
|
}
|
|
335
300
|
|
|
301
|
+
removeSeries({ chartSession, frame }) {
|
|
302
|
+
return this.formatWSPacket({ packet: { m: 'remove_series', p: [ chartSession, frame ] }});
|
|
303
|
+
}
|
|
304
|
+
|
|
336
305
|
// study = {id: st1 (st2, st3, st4 ...), name: 'Volume@tv-basicstudies-221', details: { length: 20, col_prev_close: false}
|
|
337
306
|
createStudy({ chartSession, study, series = 'st1', frame = 'sds_1' }) {
|
|
338
307
|
return this.formatWSPacket({
|
|
@@ -355,11 +324,6 @@ class TradingView {
|
|
|
355
324
|
return this.formatWSPacket({ packet: { m: 'request_more_data', p: [chartSession, frame, add] } });
|
|
356
325
|
}
|
|
357
326
|
|
|
358
|
-
moreTickmark({ chartSession, frame, add }) {
|
|
359
|
-
// "m":"request_more_tickmarks","p":["cs_lslcBHYaqGTT","sds_1",10]
|
|
360
|
-
return this.formatWSPacket({ packet: { m: 'request_more_tickmarks', p: [chartSession, frame, add] } });
|
|
361
|
-
}
|
|
362
|
-
|
|
363
327
|
createPong({ value }) {
|
|
364
328
|
return this.formatWSPacket({ packet: '~h~' + value });
|
|
365
329
|
}
|
package/lib/utils.js
CHANGED
|
@@ -1,40 +1,55 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
// import https from 'https';
|
|
3
2
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
setTimeout(resolve, time);
|
|
8
|
-
});
|
|
9
|
-
}
|
|
3
|
+
const letters = 'abcdefghijklmnopqrstuvwxyz';
|
|
4
|
+
const cleanerRgx = /~h~/g;
|
|
5
|
+
const splitterRgx = /~m~[0-9]{1,}~m~/g;
|
|
10
6
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
// res.on('data', (c) => {
|
|
16
|
-
// data += c;
|
|
17
|
-
// });
|
|
18
|
-
// res.on('end', () => {
|
|
19
|
-
// if (raw) {
|
|
20
|
-
// cb({ data, cookies: res.headers['set-cookie'] });
|
|
21
|
-
// return;
|
|
22
|
-
// }
|
|
7
|
+
module.exports = {
|
|
8
|
+
pause(time = 0) {
|
|
9
|
+
return new Promise((resolve) => setTimeout(resolve, Math.abs(time)));
|
|
10
|
+
},
|
|
23
11
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
12
|
+
extractJSON(text = '') {
|
|
13
|
+
if (typeof text !== 'string') return null;
|
|
14
|
+
const match = text.match(/\{.*?\}/s);
|
|
15
|
+
if (!match) return null;
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(match[0]);
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
},
|
|
31
22
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
23
|
+
positive(value, fallback) {
|
|
24
|
+
const number = Number(value);
|
|
25
|
+
return number > 0 ? number : fallback;
|
|
26
|
+
},
|
|
35
27
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
28
|
+
createSession(startsWith = '', size = 12) {
|
|
29
|
+
let session = String(startsWith || '');
|
|
30
|
+
while (session.length < size) session += letters[Math.floor(Math.random() * letters.length)];
|
|
31
|
+
return session;
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
formatWSPacket(packet) {
|
|
35
|
+
const msg = typeof packet === 'object' ? JSON.stringify(packet) : packet;
|
|
36
|
+
return '~m~' + msg.length + '~m~' + msg;
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
parseWSPacket(str) {
|
|
40
|
+
return str
|
|
41
|
+
.toString()
|
|
42
|
+
.replace(cleanerRgx, '')
|
|
43
|
+
.split(splitterRgx)
|
|
44
|
+
.map((part) => {
|
|
45
|
+
if (!part) return false;
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(part);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
console.error('Cant parse', part);
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
.filter((part) => part);
|
|
54
|
+
},
|
|
40
55
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "market-data-tradingview-ws",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "marketData from Tradingview ws",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -8,7 +8,12 @@
|
|
|
8
8
|
},
|
|
9
9
|
"author": "sulimenkoas@gmail.com",
|
|
10
10
|
"license": "MIT",
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=24"
|
|
13
|
+
},
|
|
11
14
|
"dependencies": {
|
|
15
|
+
"socks-proxy-agent": "^10.1.0",
|
|
16
|
+
"undici": "^8.7.0",
|
|
12
17
|
"ws": "^8.13.0"
|
|
13
18
|
}
|
|
14
19
|
}
|