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 CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  const WebSocket = require('ws');
6
6
  const tv = require('./tradingView.js');
7
+ const utils = require('./utils.js');
8
+ const { resolveProxy, getWebSocketAgent, closeProxyAgents } = require('./proxy.js');
7
9
 
8
10
  const periods = {
9
11
  60: '1',
@@ -17,49 +19,68 @@ const periods = {
17
19
  2592000: '1M',
18
20
  };
19
21
 
20
- const extractJSON = (str) => {
21
- const match = str.match(/\{.*?\}/s);
22
- return match ? JSON.parse(match[0]) : null;
23
- }
24
22
 
25
- let ws = null;
26
23
 
27
24
  module.exports = class Client {
28
25
  #charts = {
29
26
  values: {},
30
27
  set({ key, data }) {
31
- if (data) {
32
- this.values[key] = {
33
- id: data.id,
34
- symbol: data.symbol,
35
- period: parseInt(data.period),
36
- symbolKey: data.symbolKey,
37
- frame: data.frame,
38
- i: data.i,
39
- deleted: data.deleted || false,
40
- limit: data.limit || 1500,
41
- };
42
- }
28
+ if (!data) return;
29
+
30
+ this.values[key] = {
31
+ id: data.id,
32
+ symbol: data.symbol,
33
+ period: parseInt(data.period),
34
+ symbolKey: data.symbolKey,
35
+ frame: data.frame,
36
+ i: data.i,
37
+ deleted: data.deleted === true,
38
+ limit: Number(data.limit || 1500),
39
+ requestedLimit: Number(data.requestedLimit || data.limit || 1500),
40
+ historyPending: data.historyPending === true,
41
+ historyBars: data.historyBars && typeof data.historyBars === 'object' ? data.historyBars : {},
42
+ seriesGeneration: Number(data.seriesGeneration || 0),
43
+ historyCompletionsPending: Number(data.historyCompletionsPending || 0),
44
+ seriesCreated: data.seriesCreated === true,
45
+ end: data.end ?? null,
46
+ };
43
47
  },
44
48
  delete({ key }) {
45
- this.values[key].deleted = true;
49
+ const data = this.values[key];
50
+ if (!data) return null;
51
+ data.deleted = true;
52
+ data.historyPending = false;
53
+ data.historyCompletionsPending = 0;
54
+ data.historyBars = {};
55
+ data.seriesCreated = false;
56
+ data.end = null;
57
+ return data;
46
58
  },
47
59
  get({ key }) {
48
60
  return this.values[key];
49
61
  },
50
62
  getDeleted() {
51
- for (let key of Object.keys(this.values)) {
52
- if (this.values[key].deleted) {
53
- this.values[key].deleted = false;
54
- return this.get({ key });
63
+ for (const key of Object.keys(this.values)) {
64
+ const item = this.values[key];
65
+
66
+ if (item?.deleted) {
67
+ return { key, data: item };
55
68
  }
56
69
  }
70
+
57
71
  return null;
58
72
  },
73
+ claimDeleted({ key }) {
74
+ if (!this.values[key]) return null;
75
+ this.values[key].deleted = false;
76
+ return this.values[key];
77
+ },
59
78
  getBySymbolPeriod({ symbol, period }) {
60
79
  for (let key of Object.keys(this.values)) {
61
80
  // console.warn(symbol, period, key, this.values[key], this.values[key].symbol === symbol, this.values[key].period === period);
62
- if (this.values[key].symbol === symbol && parseInt(this.values[key].period) === parseInt(period) && !this.values[key].deleted) return key;
81
+ if (this.values[key].symbol === symbol && parseInt(this.values[key].period) === parseInt(period) && !this.values[key].deleted) {
82
+ return key;
83
+ }
63
84
  }
64
85
  return null;
65
86
  },
@@ -93,62 +114,426 @@ module.exports = class Client {
93
114
  if (index !== -1) arr.splice(index, 1);
94
115
  },
95
116
  };
96
- #symbols = {
97
- values: {},
98
- max: 1,
99
- getSymbol({ key, symbol }) {
100
- // let data = this.values[symbol];
101
- // if (data === undefined) data = this.set({ key, symbol });
102
- // return data;
103
- const symbolKey = 'sds_sym_' + this.max++;
104
- ws.send(tv.resolveSymbol({ chartSession: key, symbolKey, symbol }));
105
- this.values[symbol] = { key: symbolKey };
106
- return this.values[symbol];
107
- },
108
- };
117
+ #symbols = { values: {}, max: 1 };
118
+
119
+ #watchdogIntervalMs = 10_000;
120
+ #watchdogTimeoutMs = 60_000;
109
121
 
122
+ #ws = null;
123
+ #proxy = null;
124
+ #result = null;
125
+
126
+ #connectPromise = null;
127
+ #connectTimeoutMs = 20_000;
128
+
129
+ #stopWatchdog() {
130
+ if (!this.#watchdogTimer) return;
131
+ clearInterval(this.#watchdogTimer);
132
+ this.#watchdogTimer = null;
133
+ }
134
+
135
+ #startWatchdog() {
136
+ this.#stopWatchdog();
137
+ this.#lastMessageAt = Date.now();
138
+ this.#watchdogTimer = setInterval(() => {
139
+ const socket = this.#ws;
140
+ if (!socket ||socket.readyState !== WebSocket.OPEN) return;
141
+ const silenceMs = Date.now() - this.#lastMessageAt;
142
+ if (silenceMs <= this.#watchdogTimeoutMs) return;
143
+ this.#emit('error', { type: 'ws_stalled', silenceMs });
144
+ socket.terminate();
145
+ }, this.#watchdogIntervalMs);
146
+
147
+ this.#watchdogTimer.unref?.();
148
+ }
149
+
110
150
  #token = null;
111
151
  #sessionid = null;
112
152
  #sessionidsign = null;
153
+ #connectGeneration = 0;
154
+ #connectAbortController = null;
155
+
156
+ #chartFrameMax = 0;
157
+ #chartQueue = [];
158
+ #queuedChartKeys = new Set();
159
+ #queueTimer = null;
160
+ #queueProcessing = false;
161
+ #queueBlockedUntil = 0;
162
+ #configuredMaxChartSessions = 180;
163
+ #maxChartSessions = 180;
164
+ #chartCreateIntervalMs = 60;
165
+ #queueRetryMs = 500;
166
+ #chartQueueTtlMs = 30_000;
167
+ #maxQueuedCharts = 200;
168
+ #maxBufferedAmount = 4 * 1024 * 1024;
169
+ #closeTimeoutMs = 5_000;
170
+ #intentionalClose = false;
171
+ #watchdogTimer = null;
172
+ #lastMessageAt = 0;
113
173
 
114
- constructor() {
115
- // this.#resolved = new Map();
174
+ constructor(config = {}) {
175
+ const cfg = config && typeof config === 'object' ? config : {};
176
+ this.#configuredMaxChartSessions = utils.positive(cfg.max, this.#configuredMaxChartSessions);
177
+ this.#maxChartSessions = this.#configuredMaxChartSessions;
178
+ this.#chartCreateIntervalMs = utils.positive(cfg.interval, this.#chartCreateIntervalMs);
179
+ this.#queueRetryMs = utils.positive(cfg.retry, this.#queueRetryMs);
180
+ this.#maxQueuedCharts = utils.positive(cfg.queued, this.#maxQueuedCharts);
181
+ this.#chartQueueTtlMs = Math.max(utils.positive(cfg.ttl, this.#chartQueueTtlMs),this.#maxQueuedCharts * this.#chartCreateIntervalMs * 2);
116
182
  }
117
183
 
118
- async close() {
119
- // token delete !!!
120
- ws.close();
184
+ #emit(name, payload) {
185
+ if (typeof this.#result !== 'function') return;
186
+ try {
187
+ this.#result(name, payload);
188
+ } catch (error) {
189
+ console.error('Marketdata result callback failed:', { event: name, message: error?.message || String(error) } );
190
+ }
191
+ }
192
+
193
+ #resolveSymbol({ chartSession, symbol }) {
194
+ const symbolKey = 'sds_sym_' + this.#symbols.max++;
195
+ if (!this.#send(tv.resolveSymbol({ chartSession, symbolKey, symbol }))) return null;
196
+ this.#symbols.values[symbol] = { key: symbolKey };
197
+ return this.#symbols.values[symbol];
198
+ }
199
+
200
+ #resetRemoteState() {
201
+ this.#charts.values = {};
202
+ this.#quotes.values = {};
203
+ this.#symbols.values = {};
204
+ this.#symbols.max = 1;
205
+ this.#maxChartSessions = this.#configuredMaxChartSessions;
206
+ this.#chartFrameMax = 0;
207
+ this.#chartQueue = [];
208
+ this.#queuedChartKeys.clear();
209
+ this.#queueBlockedUntil = 0;
210
+ this.#stopQueueTimer();
211
+ this.#queueProcessing = false;
212
+ }
213
+
214
+ #resetState() {
215
+ this.#resetRemoteState();
216
+ }
217
+
218
+ #chartQueueKey({ symbol, period }) {
219
+ return symbol + '|' + String(period);
220
+ }
221
+
222
+ #nextChartFrame() {
223
+ this.#chartFrameMax++;
224
+ return ('sds_' + String(this.#chartFrameMax));
225
+ }
226
+
227
+ #validateChartIdentity({ symbol, period }) {
228
+ const normalizedSymbol = typeof symbol === 'string' ? symbol.trim() : '';
229
+ if (!normalizedSymbol || !normalizedSymbol.includes(':') || normalizedSymbol.length > 100 ) return { ok: false, reason: 'invalid_symbol' };
230
+ const normalizedPeriod = Number(period);
231
+ if (!Number.isInteger(normalizedPeriod) || !Object.prototype.hasOwnProperty.call(periods, normalizedPeriod)) return { ok: false, reason: 'invalid_period' };
232
+ return { ok: true, symbol: normalizedSymbol, period: normalizedPeriod };
233
+ }
234
+
235
+ #validateChartRequest({ symbol, period, limit }) {
236
+ const identity = this.#validateChartIdentity({ symbol, period });
237
+ if (!identity.ok) return identity;
238
+
239
+ const normalizedLimit = Number(limit);
240
+ if (!Number.isInteger(normalizedLimit) || normalizedLimit <= 0 || normalizedLimit > 1500) return { ok: false, reason: 'invalid_limit' };
241
+
242
+ return { ...identity, limit: normalizedLimit };
243
+ }
244
+
245
+ #assertConnectGeneration(generation) {
246
+ if (generation === this.#connectGeneration) return;
247
+ const error = new Error('Connection cancelled');
248
+ error.code = 'CONNECT_CANCELLED';
249
+ throw error;
250
+ }
251
+
252
+ #countActiveCharts() {
253
+ return Object.values(this.#charts.values).filter((item) => item && !item.deleted && item.symbol && item.period).length;
254
+ }
255
+
256
+ #parseChartBars({ frame }) {
257
+ const series = frame?.s;
258
+ if (!Array.isArray(series)) return [];
259
+
260
+ const chart = [];
261
+ for (const each of series) {
262
+ const values = each?.v;
263
+ if (!Array.isArray(values) || values.length < 6) continue;
264
+
265
+ const timestamp = Number(values[0]) * 1000;
266
+ if (!Number.isFinite(timestamp)) continue;
267
+
268
+ chart.push({
269
+ open: values[1],
270
+ high: values[2],
271
+ low: values[3],
272
+ close: values[4],
273
+ timestamp,
274
+ volume: values[5],
275
+ });
276
+ }
277
+
278
+ return chart;
279
+ }
280
+
281
+ #mergeChartBars({ session, chart }) {
282
+ if (!session.historyBars || typeof session.historyBars !== 'object') {
283
+ session.historyBars = {};
284
+ }
285
+
286
+ for (const bar of chart) {
287
+ session.historyBars[String(bar.timestamp)] = bar;
288
+ }
289
+ }
290
+
291
+ #getChartHistory({ session }) {
292
+ const requestedLimit = Math.max(1, Number(session.requestedLimit || session.limit || 1500));
293
+ return Object.values(session.historyBars || {}).sort((left, right) => left.timestamp - right.timestamp).slice(-requestedLimit);
294
+ }
295
+
296
+ #scheduleQueue(delay = 0) {
297
+ if (!this.#isOpen() || this.#queueTimer) return;
298
+ this.#queueTimer = setTimeout(() => {
299
+ this.#queueTimer = null;
300
+ void this.#processChartQueue();
301
+ }, Math.max(0, delay));
302
+
303
+ this.#queueTimer.unref?.();
304
+ }
305
+
306
+ #stopQueueTimer() {
307
+ if (!this.#queueTimer) return;
308
+ clearTimeout(this.#queueTimer);
309
+ this.#queueTimer = null;
310
+ }
311
+
312
+ #isOpen() {
313
+ return this.#ws?.readyState === WebSocket.OPEN;
314
+ }
315
+
316
+ #send(data) {
317
+ const socket = this.#ws;
318
+
319
+ if (!socket || socket.readyState !== WebSocket.OPEN) return false;
320
+
321
+ if (socket.bufferedAmount > this.#maxBufferedAmount) {
322
+ this.#emit('error', {
323
+ type: 'ws_backpressure',
324
+ bufferedAmount: socket.bufferedAmount,
325
+ });
326
+ return false;
327
+ }
328
+
329
+ socket.send(data, (error) => {
330
+ if (!error) return;
331
+ this.#emit('error', {
332
+ type: 'ws_send_error',
333
+ message: error.message,
334
+ });
335
+ });
336
+
337
+ return true;
338
+ }
339
+
340
+ #logQueueState(context = '', extra = {}) {
341
+ console.debug('chartQueueState', {
342
+ context,
343
+ active: this.#countActiveCharts(),
344
+ max: this.#maxChartSessions,
345
+ queued: this.#chartQueue.length,
346
+ queuedKeys: this.#queuedChartKeys.size,
347
+ blockedMs: Math.max(0, this.#queueBlockedUntil - Date.now()),
348
+ createIntervalMs: this.#chartCreateIntervalMs,
349
+ retryMs: this.#queueRetryMs,
350
+ ...extra,
351
+ });
352
+ }
353
+
354
+ #enqueueChart({ symbol, period, limit }) {
355
+ const queueKey = this.#chartQueueKey({ symbol, period });
356
+ const existing = this.#chartQueue.find((item) => item.queueKey === queueKey);
357
+
358
+ if (existing) {
359
+ existing.limit = Math.max(Number(existing.limit || 0), Number(limit || 0));
360
+ existing.expiresAt = Date.now() + this.#chartQueueTtlMs;
361
+ return 'queued';
362
+ }
363
+
364
+ if (this.#chartQueue.length >= this.#maxQueuedCharts) {
365
+ this.#logQueueState('enqueue_drop_overflow', { symbol, period, limit, maxQueued: this.#maxQueuedCharts });
366
+ this.#emit('error', { type: 'chart_queue_overflow', symbol, period, limit, maxQueued: this.#maxQueuedCharts, retryable: true });
367
+ return 'dropped';
368
+ }
369
+
370
+ this.#queuedChartKeys.add(queueKey);
371
+ this.#chartQueue.push({ symbol, period, limit, queueKey, expiresAt: Date.now() + this.#chartQueueTtlMs });
372
+ this.#scheduleQueue();
373
+
374
+ return 'queued';
121
375
  }
122
376
 
123
- getAll() {
124
- return { quotes: this.#quotes.values, charts: this.#charts.values };
377
+ #dropQueuedSymbolPeriod({ symbol, period }) {
378
+ const queueKey = this.#chartQueueKey({ symbol, period });
379
+ if (!this.#queuedChartKeys.has(queueKey)) return false;
380
+ this.#chartQueue = this.#chartQueue.filter((item) => item.queueKey !== queueKey);
381
+ this.#queuedChartKeys.delete(queueKey);
382
+ return true;
125
383
  }
126
384
 
127
- getQuotes() {
128
- return { quotes: this.#quotes.values, symbols: Object.values(this.#quotes.values).map(each => each.symbols) };
385
+ #onCapacitySignal(reason = '') {
386
+ const text = String(reason || '');
387
+ if (text.includes('max charts per connection reached')) {
388
+ const active = this.#countActiveCharts();
389
+ if (active > 0 && active < this.#maxChartSessions) this.#maxChartSessions = active;
390
+ this.#queueBlockedUntil = Date.now() + 10_000;
391
+ this.#logQueueState('capacity_max_charts', { reason: text.slice(0, 220) });
392
+ this.#scheduleQueue(this.#queueRetryMs);
393
+ return 'capacity_max_charts';
394
+ }
395
+ if (text.includes('max sessions rate reached')) {
396
+ this.#queueBlockedUntil = Date.now() + 5_000;
397
+ this.#logQueueState('capacity_rate_limit', { reason: text.slice(0, 220) });
398
+ this.#scheduleQueue(this.#queueRetryMs);
399
+ return 'capacity_rate_limit';
400
+ }
401
+ return null;
402
+ }
403
+
404
+ async #processChartQueue() {
405
+ if (this.#queueProcessing || !this.#isOpen()) return;
406
+ const generation = this.#connectGeneration;
407
+ this.#queueProcessing = true;
408
+ try {
409
+ const wait = this.#queueBlockedUntil - Date.now();
410
+ if (wait > 0) {
411
+ this.#scheduleQueue(wait);
412
+ return;
413
+ }
414
+
415
+ while (this.#chartQueue.length > 0) {
416
+ if (generation !== this.#connectGeneration || !this.#isOpen()) return;
417
+ const active = this.#countActiveCharts();
418
+ if (active >= this.#maxChartSessions) {
419
+ this.#logQueueState('queue_paused_capacity');
420
+ this.#scheduleQueue(this.#queueRetryMs);
421
+ return;
422
+ }
423
+
424
+ const next = this.#chartQueue.shift();
425
+ if (!next) break;
426
+ this.#queuedChartKeys.delete(next.queueKey);
427
+ if (next.expiresAt && next.expiresAt < Date.now()) {
428
+ this.#logQueueState('queue_drop_expired', { symbol: next.symbol, period: next.period });
429
+ this.#emit('error', { type: 'chart_queue_expired', symbol: next.symbol, period: next.period, limit: next.limit, retryable: true });
430
+ continue;
431
+ }
432
+
433
+ const existKey = this.#charts.getBySymbolPeriod({ symbol: next.symbol, period: next.period });
434
+ if (existKey) continue;
435
+
436
+ const status = this.#addChartSymbolNow({ symbol: next.symbol, period: next.period, limit: next.limit });
437
+ if (status === 'not_connected') {
438
+ this.#emit('error', { type: 'chart_send_failed', symbol: next.symbol, period: next.period, limit: next.limit, retryable: true });
439
+ return;
440
+ }
441
+ await utils.pause(this.#chartCreateIntervalMs);
442
+ }
443
+ } finally {
444
+ if (generation === this.#connectGeneration) {
445
+ this.#queueProcessing = false;
446
+ if (this.#chartQueue.length > 0 && this.#isOpen()) this.#scheduleQueue(this.#queueRetryMs);
447
+ }
448
+ }
129
449
  }
130
450
 
131
- getCharts() {
132
- return { charts: this.#charts.values };
451
+ async close() {
452
+ this.#intentionalClose = true;
453
+ this.#connectGeneration++;
454
+
455
+ this.#connectAbortController?.abort();
456
+ this.#connectAbortController = null;
457
+
458
+ this.#stopWatchdog();
459
+ this.#stopQueueTimer();
460
+
461
+ const socket = this.#ws;
462
+
463
+ if (socket) {
464
+ await new Promise((resolve) => {
465
+ let settled = false;
466
+ const finish = () => {
467
+ if (settled) return;
468
+ settled = true;
469
+ clearTimeout(forceTimer);
470
+ resolve();
471
+ };
472
+
473
+ const forceTimer = setTimeout(() => {
474
+ if (socket.readyState !== WebSocket.CLOSED) socket.terminate();
475
+ finish();
476
+ }, this.#closeTimeoutMs);
477
+
478
+ forceTimer.unref?.();
479
+ socket.once('close', finish);
480
+
481
+ if (socket.readyState === WebSocket.CONNECTING) {
482
+ socket.terminate();
483
+ } else if (socket.readyState === WebSocket.OPEN) {
484
+ socket.close(1000, 'Client shutdown');
485
+ } else if (socket.readyState === WebSocket.CLOSED) {
486
+ finish();
487
+ }
488
+ });
489
+
490
+ socket.removeAllListeners();
491
+
492
+ if (this.#ws === socket) this.#ws = null;
493
+ }
494
+
495
+ await closeProxyAgents();
496
+
497
+ this.#resetRemoteState();
498
+
499
+ this.#token = null;
500
+ this.#sessionid = null;
501
+ this.#sessionidsign = null;
502
+ this.#proxy = null;
503
+ this.#result = null;
504
+
505
+ this.#intentionalClose = false;
506
+
507
+ return 'close';
133
508
  }
134
509
 
135
510
  // Возвращает debug state с информацией
136
511
  getDebugState() {
512
+ const charts = Object.values(this.#charts.values);
137
513
  return {
138
- wsReadyState: ws?.readyState,
139
- wsUrl: ws?.url,
514
+ wsReadyState: this.#ws?.readyState ?? null,
515
+ wsUrl: this.#ws?.url ?? null,
516
+ wsBufferedAmount: this.#ws ?.bufferedAmount ?? 0,
517
+ lastMessageAgeMs: this.#lastMessageAt ? Date.now() - this.#lastMessageAt : null,
518
+ connectGeneration: this.#connectGeneration,
519
+ connecting: Boolean(this.#connectPromise),
140
520
  tokenLen: this.#token ? this.#token.length : 0,
141
- sessionid: this.#sessionid,
142
- sessionidsign: this.#sessionidsign,
143
- chartsCount: Object.keys(this.#charts.values).length,
521
+ sessionid: Boolean(this.#sessionid),
522
+ sessionidsign: Boolean(this.#sessionidsign),
523
+ chartsCount: charts.length,
524
+ activeChartSessions: charts.filter((chart) => chart && chart.deleted !== true).length,
525
+ deletedChartSessions: charts.filter((chart) => chart?.deleted === true).length,
144
526
  quotesCount: Object.keys(this.#quotes.values).length,
145
- chartsKeys: Object.keys(this.#charts.values),
146
- quotesKeys: Object.keys(this.#quotes.values),
527
+ chartQueueLength: this.#chartQueue.length,
528
+ chartQueuedKeys: this.#queuedChartKeys.size,
529
+ configuredMaxChartSessions: this.#configuredMaxChartSessions,
530
+ maxChartSessions: this.#maxChartSessions,
531
+ queueBlockedMs: Math.max(0, this.#queueBlockedUntil - Date.now()),
147
532
  };
148
533
  }
149
534
 
150
- async getToken({ sessionid, sessionidsign, tvecuid, imageurl }) {
151
- return tv.getToken({ sessionid, sessionidsign, tvecuid, imageurl });
535
+ async getToken({ sessionId, sessionIdSign, tvEcuid, imageUrl, proxy, signal }) {
536
+ return tv.getToken({ sessionId, sessionIdSign, tvEcuid, imageUrl, proxy, signal });
152
537
  }
153
538
 
154
539
  auth(token = 'unauthorized_user_token') {
@@ -160,62 +545,157 @@ module.exports = class Client {
160
545
  });
161
546
  }
162
547
 
163
- async connect({ url, options, result, sessionid, sessionidsign, tvecuid, imageurl }) {
548
+ async connect({ url, options = {}, result, sessionid, sessionidsign, tvecuid, imageurl, proxy }) {
549
+ if (this.#isOpen()) return 'open';
550
+ if (this.#connectPromise) return this.#connectPromise;
551
+ if (typeof result !== 'function') throw new TypeError('result callback must be a function');
552
+
553
+ const generation = ++this.#connectGeneration;
554
+ this.#connectAbortController?.abort();
555
+ const controller = new AbortController();
556
+ this.#connectAbortController = controller;
557
+
558
+ this.#connectPromise = this.#connectInternal({ url, options, result, sessionid, sessionidsign, tvecuid, imageurl, proxy, generation, signal: controller.signal });
559
+
164
560
  try {
165
- this.#token = await this.getToken({ sessionid, sessionidsign, tvecuid, imageurl });
166
- // console.info('Token:', this.#token);
167
- this.#sessionid = sessionid;
168
- this.#sessionidsign = sessionidsign;
169
-
170
- if (this.#token.length > 10) {
171
- return new Promise((resolv, reject) => {
172
- try {
173
- url += '?from=chart%2F' + imageurl + '%2F';
174
- const date = new Date();
175
- url += '&date=' + date.getFullYear() + '_' + String(date.getMonth() + 1).padStart(2, '0') + '_' + String(date.getDate()).padStart(2, '0') + '-11_25';
176
- url += '&type=chart';
177
- ws = new WebSocket(url, options);
178
-
179
- const originalSend = ws.send;
180
- ws.send = function(data) {
181
- // console.log('Message sent:', data);
182
- originalSend.apply(ws, arguments);
183
- };
184
-
185
- ws.onclose = () => console.log('disconnected');
186
-
187
- ws.onerror = (error) => reject(console.error('error: ', error));
188
- ws.onopen = () => {
189
- ws.send(this.auth(this.#token));
190
- ws.send(tv.setLocaleRu());
191
-
192
- const quoteKey = this.createQuoteSmallSession();
193
-
194
- this.messageListner({ result });
195
- resolv('open');
196
- };
197
- } catch (error) {
198
- reject(error);
199
- }
200
- });
201
- }
202
- return null;
203
- } catch (error) {
204
- console.error('Error in connect:', error.message);
205
- throw error;
561
+ return await this.#connectPromise;
562
+ } finally {
563
+ if (this.#connectAbortController === controller) this.#connectAbortController = null;
564
+ this.#connectPromise = null;
206
565
  }
207
566
  }
208
567
 
568
+ async #connectInternal({ url, options, result, sessionid, sessionidsign, tvecuid, imageurl, proxy, generation, signal }) {
569
+ this.#result = result;
570
+ this.#proxy = proxy || null;
571
+
572
+ this.#token = await this.getToken({ sessionId: sessionid, sessionIdSign: sessionidsign, tvEcuid: tvecuid, imageUrl: imageurl, proxy, signal });
573
+
574
+ this.#assertConnectGeneration(generation);
575
+
576
+ this.#sessionid = sessionid;
577
+ this.#sessionidsign = sessionidsign;
578
+
579
+ if (!this.#token || this.#token.length <= 10) throw new Error('Invalid TradingView auth token');
580
+
581
+ this.#resetRemoteState();
582
+
583
+ const date = new Date();
584
+ const year = date.getFullYear();
585
+ const month = String(date.getMonth() + 1).padStart(2, '0');
586
+ const day = String(date.getDate()).padStart(2, '0');
587
+
588
+ const wsUrl = `${url}?from=chart%2F` + `${imageurl}%2F&date=` + `${year}_${month}_${day}` + `-11_25&type=chart`;
589
+ const wsProxy = resolveProxy(proxy, 'ws');
590
+ const agent = getWebSocketAgent(wsProxy);
591
+ const wsOptions = { ...options, handshakeTimeout: options.handshakeTimeout ?? this.#connectTimeoutMs };
592
+
593
+ if (agent) wsOptions.agent = agent;
594
+ else delete wsOptions.agent;
595
+
596
+ this.#assertConnectGeneration(generation);
597
+
598
+ const socket = new WebSocket(wsUrl, wsOptions);
599
+
600
+ this.#ws = socket;
601
+ this.messageListner({ socket });
602
+
603
+ return new Promise((resolve, reject) => {
604
+ let opened = false;
605
+ let settled = false;
606
+
607
+ const finishResolve = (value) => {
608
+ if (settled) return;
609
+ settled = true;
610
+ clearTimeout(connectTimer);
611
+ resolve(value);
612
+ };
613
+
614
+ const finishReject = (error) => {
615
+ if (settled) return;
616
+ settled = true;
617
+ clearTimeout(connectTimer);
618
+ reject(error instanceof Error ? error : new Error(String(error)));
619
+ };
620
+
621
+ const connectTimer = setTimeout(() => {
622
+ finishReject(new Error(`WebSocket connect timeout after ${this.#connectTimeoutMs} ms`));
623
+ socket.terminate();
624
+ }, this.#connectTimeoutMs);
625
+
626
+ connectTimer.unref?.();
627
+
628
+ socket.once('open', () => {
629
+ if (this.#ws !== socket || generation !== this.#connectGeneration) {
630
+ socket.terminate();
631
+ finishReject(new Error('Stale WebSocket connection'));
632
+ return;
633
+ }
634
+
635
+ opened = true;
636
+
637
+ this.#lastMessageAt = Date.now();
638
+ this.#send(this.auth(this.#token));
639
+ this.#send(tv.setLocaleRu());
640
+ this.#startWatchdog();
641
+ finishResolve('open');
642
+ });
643
+
644
+ socket.on('error', (error) => {
645
+ if (!opened) {
646
+ finishReject(error);
647
+ if (socket.readyState !== WebSocket.CLOSED) socket.terminate();
648
+ return;
649
+ }
650
+ this.#emit('error', { type: 'ws_error', message: error.message });
651
+ });
652
+
653
+ socket.once('unexpected-response', (request, response) => {
654
+ finishReject(new Error(`Unexpected WebSocket response: ${response.statusCode}`));
655
+ socket.terminate();
656
+ },
657
+ );
658
+
659
+ socket.once('close', (code, reasonBuffer) => {
660
+ const reason = reasonBuffer ?.toString() || '';
661
+ const isCurrentSocket = this.#ws === socket;
662
+ if (isCurrentSocket) {
663
+ this.#ws = null;
664
+ this.#stopWatchdog();
665
+ this.#stopQueueTimer();
666
+ this.#resetRemoteState();
667
+ }
668
+
669
+ if (!opened) {
670
+ finishReject(new Error(`WebSocket closed before open: ${code} ${reason}`));
671
+ return;
672
+ }
673
+
674
+ if (isCurrentSocket) {
675
+ this.#emit('disconnect', { code, reason, intentional: this.#intentionalClose });
676
+ }
677
+ });
678
+ });
679
+ }
680
+
209
681
  async disconnect() {
210
- tv.disconnect({ sessionid: this.#sessionid, sessionidsign: this.#sessionidsign });
211
- return 'close';
682
+ try {
683
+ if (this.#sessionid && this.#sessionidsign) {
684
+ await tv.disconnect({ sessionId: this.#sessionid, sessionIdSign: this.#sessionidsign, proxy: this.#proxy, });
685
+ }
686
+ } catch (error) {
687
+ console.warn('disconnect failed:', error?.message || error);
688
+ } finally {
689
+ await this.close();
690
+ }
691
+ return 'disconnect';
212
692
  }
213
693
 
214
694
  createQuoteSmallSession() {
215
695
  const key = tv.createSession({ startsWith: 'qs_' });
216
696
  this.#quotes.set({ key, data: { id: key, type: 'small', symbols: [] } });
217
- ws.send(tv.quoteCreateSession({ session: key }));
218
- ws.send(tv.setFieldsSmall({ session: key }));
697
+ this.#send(tv.quoteCreateSession({ session: key }));
698
+ this.#send(tv.setFieldsSmall({ session: key }));
219
699
  // ws.send(tv.setFields({ session: key }));
220
700
  return key;
221
701
  }
@@ -223,184 +703,426 @@ module.exports = class Client {
223
703
  createQuoteFullSession() {
224
704
  const key = tv.createSession({ startsWith: 'qs_' });
225
705
  this.#quotes.set({ key, data: { id: key, type: 'full', symbols: [] } });
226
- ws.send(tv.quoteCreateSession({ session: key }));
706
+ this.#send(tv.quoteCreateSession({ session: key }));
227
707
  return key;
228
708
  }
229
709
 
230
710
  createChartSession() {
231
711
  const key = tv.createSession({ startsWith: 'cs_' });
232
712
  this.#charts.set({ key, data: { id: key, symbol: '', period: 0, symbolKey: '', frame: '', i: '', deleted: false } });
233
- ws.send(tv.chartCreateSession({ chartSession: key }));
234
- ws.send(tv.switchTimezone({ chartSession: key, tz: 'Etc/UTC' }));
713
+ const created = this.#send(tv.chartCreateSession({ chartSession: key }));
714
+ const timezone = created && this.#send(tv.switchTimezone({ chartSession: key, tz: 'Etc/UTC' }));
715
+ if (!created || !timezone) {
716
+ delete this.#charts.values[key];
717
+ return null;
718
+ }
235
719
  return key;
236
720
  }
237
721
 
238
722
  addQuoteSymbols({ symbols }) {
239
- const result = { add: [], exist: [] };
240
- // if (Object.keys(this.#quotes.values).length === 0) this.createQuoteSet1Session();
241
- symbols.forEach((symbol) => {
723
+ const result = { add: [], exist: [], rejected: [] };
724
+ if (!Array.isArray(symbols) || symbols.length === 0) return result;
725
+
726
+ const valid = symbols.filter((symbol) => typeof symbol === 'string').map((symbol) => symbol.trim()).filter(Boolean);
727
+ if (valid.length === 0) return result;
728
+
729
+ if (!this.#isOpen()) {
730
+ result.rejected = valid;
731
+ return { ...result, status: 'not_connected' };
732
+ }
733
+
734
+ if (Object.keys(this.#quotes.values).length === 0) this.createQuoteSmallSession();
735
+
736
+ for (const symbol of valid) {
242
737
  let key = this.#quotes.getBySymbol({ symbol });
243
738
  if (key) {
244
739
  result.exist.push(symbol);
245
- } else {
246
- key = this.#quotes.add({ symbol });
247
- ws.send(tv.quoteAddSymbol({ session: key, symbol }));
248
- // ws.send(tv.quoteFastSymbol({ session: key, symbol }));
249
- result.add.push(symbol);
740
+ continue;
250
741
  }
251
- });
252
- return result;
742
+
743
+ key = this.#quotes.add({ symbol });
744
+ if (!key) {
745
+ result.rejected.push(symbol);
746
+ continue;
747
+ }
748
+
749
+ const sent = this.#send(tv.quoteAddSymbol({ session: key, symbol }));
750
+ if (!sent) {
751
+ this.#quotes.delete({ key, symbol });
752
+ result.rejected.push(symbol);
753
+ continue;
754
+ }
755
+
756
+ result.add.push(symbol);
757
+ }
758
+
759
+ return { ...result, status: result.rejected.length === 0 ? 'ok' : 'partial' };
253
760
  }
254
761
 
255
762
  deleteQuoteSymbol({ symbol }) {
256
- const key = this.#quotes.getBySymbol({ symbol });
763
+ if (typeof symbol !== 'string' || !symbol.trim()) return 'invalid';
764
+ const normalized = symbol.trim();
765
+ const key = this.#quotes.getBySymbol({ symbol: normalized });
257
766
  if (!key) return 'unlisted';
258
- this.#quotes.delete({ key, symbol });
259
- ws.send(tv.quoteRemoveSymbols({ session: key, symbol }));
260
- return 'delete';
767
+ this.#quotes.delete({ key, symbol: normalized });
768
+ const sent = this.#send(tv.quoteRemoveSymbols({ session: key, symbol: normalized }));
769
+ return sent ? 'delete' : 'not_connected';
261
770
  }
262
771
 
263
- addChartSymbol({ symbol, period, limit = 1500 }) {
772
+ #reuseDeletedChartSession({ key, symbol, period, limit }) {
773
+ const data = this.#charts.get({ key });
774
+ if (!data) return 'unlisted';
775
+ const resolved = this.#resolveSymbol({ chartSession: key, symbol });
776
+ if (!resolved) return 'not_connected';
777
+ data.deleted = false;
778
+ data.symbolKey = resolved.key;
779
+ data.symbol = symbol;
780
+ data.period = period;
781
+ data.frame = this.#nextChartFrame();
782
+ data.i = 's1';
783
+ data.historyPending = true;
784
+ data.requestedLimit = Number(limit);
785
+ data.limit = Number(limit);
786
+ data.historyBars = {};
787
+ data.historyCompletionsPending = 1;
788
+ data.seriesGeneration = Number(data.seriesGeneration || 0) + 1;
789
+ data.seriesCreated = true;
790
+ data.end = null;
791
+
792
+ const sent = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[period], limit}));
793
+ if (!sent) {
794
+ this.#charts.delete({ key });
795
+ return 'not_connected';
796
+ }
797
+
798
+ this.#charts.set({ key, data });
799
+ console.debug('tv chart session reused:', { symbol, period, session: key, frame: data.frame, limit, generation: data.seriesGeneration });
800
+ return 'add';
801
+ }
802
+
803
+ #addChartSymbolNow({ symbol, period, limit = 1500 }) {
264
804
  if (!symbol || typeof symbol !== 'string') console.debug('Invalid symbol parameter', symbol); // throw new Error('Invalid symbol parameter', symbol);
265
805
  if (!period || typeof period !== 'number') console.debug('Invalid period parameter', period); // throw new Error('Invalid period parameter', period);
266
806
  if (!limit || typeof limit !== 'number') console.debug('Invalid limit parameter', limit); // throw new Error('Invalid limit parameter', limit);
267
807
 
268
808
  let key = this.#charts.getBySymbolPeriod({ symbol, period });
269
809
  if (key) {
270
- console.warn('addChartSymbol exist:', key, symbol, period);
810
+ const data = this.#charts.get({ key });
811
+ if (data && Number(limit) > Number(data.limit || 0)) {
812
+ const add = Number(limit) - Number(data.limit || 0);
813
+ const sent = this.#send(tv.moreData({ chartSession: key, frame: data.frame, add }));
814
+ if (!sent) return 'not_connected';
815
+ data.historyPending = true;
816
+ data.requestedLimit = Number(limit);
817
+ data.limit = Number(limit);
818
+ this.#charts.set({ key, data });
819
+ console.debug('addChartSymbol extend:', key, symbol, period, { add, limit });
820
+ return 'extend';
821
+ }
822
+ console.debug('addChartSymbol exist:', key, symbol, period);
271
823
  return 'exist';
272
824
  }
273
- // console.warn('modules addChartSymbol1', symbol, period, limit, key);
274
825
  const deleted = this.#charts.getDeleted();
275
- if (deleted !== null && deleted.limit === limit) return this.updateChartSymbol({ symbol, period, limit, last: { symbol: deleted.symbol, period: parseInt(deleted.period) }});
826
+ if (deleted !== null) return this.#reuseDeletedChartSession({ key: deleted.key, symbol, period, limit });
276
827
 
277
828
  key = this.createChartSession();
829
+ if (!key) return 'not_connected';
278
830
  const data = this.#charts.get({ key });
279
831
 
280
- data.symbolKey = this.#symbols.getSymbol({ key, symbol }).key;
832
+ const resolved = this.#resolveSymbol({ chartSession: key, symbol });
833
+ if (!resolved) {
834
+ this.#charts.delete({ key });
835
+ return 'not_connected';
836
+ }
837
+ data.symbolKey = resolved.key;
838
+
281
839
  data.symbol = symbol;
282
840
  data.period = period;
283
- data.frame = 'sds_' + Object.keys(this.#charts.values).length;
284
- data.i = 's' + 1;
285
- data.limit = limit;
841
+ data.frame = this.#nextChartFrame();
842
+ data.i = 's1';
843
+ data.historyPending = true;
844
+ data.requestedLimit = Number(limit);
845
+ data.limit = Number(limit);
846
+ data.historyBars = {};
847
+ data.historyCompletionsPending = 1;
848
+ data.seriesGeneration = Number(data.seriesGeneration || 0) + 1;
849
+ data.seriesCreated = true;
850
+ data.end = null;
851
+
852
+ const sent = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[period], limit}));
853
+ if (!sent) {
854
+ this.#charts.delete({ key });
855
+ return 'not_connected';
856
+ }
286
857
 
287
- ws.send(
288
- tv.createSeries({
289
- chartSession: key,
290
- frame: data.frame,
291
- increment: data.i,
292
- symbolKey: data.symbolKey,
293
- period: periods[period],
294
- limit,
295
- }),
296
- );
297
- // console.warn('addChartSymbol4', periods[period], data);
298
858
  this.#charts.set({ key, data });
859
+ console.debug('tv chart sent:', { symbol, period, session: key, frame: data.frame, limit });
299
860
  return 'add';
300
861
  }
301
862
 
302
- updateChartSymbol({ symbol, period, limit, last }) {
303
- const key = this.#charts.getBySymbolPeriod({ symbol: last.symbol, period: last.period });
863
+ addChartSymbol({ symbol, period, limit = 1500 }) {
864
+ const validation = this.#validateChartRequest({ symbol, period, limit });
865
+ if (!validation.ok) return { status: 'invalid', reason: validation.reason };
866
+ if (!this.#isOpen()) return { status: 'not_connected', symbol: validation.symbol, period: validation.period };
867
+
868
+ const key = this.#charts.getBySymbolPeriod({ symbol: validation.symbol, period: validation.period });
869
+ if (key) {
870
+ const data = this.#charts.get({ key });
871
+ if (data && validation.limit > Number(data.limit || 0)) {
872
+ const add = validation.limit - Number(data.limit || 0);
873
+ const sent = this.#send(tv.moreData({ chartSession: key, frame: data.frame, add }));
874
+ if (!sent) return { status: 'not_connected' };
875
+ data.historyPending = true;
876
+ data.historyCompletionsPending = Number(data.historyCompletionsPending || 0) + 1;
877
+ data.requestedLimit = validation.limit;
878
+ data.limit = validation.limit;
879
+ this.#charts.set({ key, data });
880
+ return { status: 'extend', symbol: validation.symbol, period: validation.period, limit: validation.limit };
881
+ }
882
+ return { status: 'exist', symbol: validation.symbol, period: validation.period, limit: Number(data?.limit || 0) };
883
+ }
884
+ const status = this.#enqueueChart({ symbol: validation.symbol, period: validation.period, limit: validation.limit });
885
+ return { status, symbol: validation.symbol, period: validation.period, limit: validation.limit };
886
+ }
887
+
888
+ updateChartSymbol({ symbol, period, limit, last, key: providedKey }) {
889
+ const validation = this.#validateChartRequest({ symbol, period, limit });
890
+ if (!validation.ok) return { status: 'invalid', reason: validation.reason};
891
+ if (!this.#isOpen()) return { status: 'not_connected' };
892
+ const key = providedKey || (last ? this.#charts.getBySymbolPeriod({ symbol: last.symbol, period: last.period }) : null);
893
+ if (!key) return { status: 'unlisted' };
894
+
304
895
  const data = this.#charts.get({ key });
305
-
306
- data.symbolKey = this.#symbols.getSymbol({ key, symbol }).key;
307
- data.symbol = symbol;
308
- data.period = period;
309
- data.i = 's' + (parseInt(data.i.replace(/[^0-9]/g, '')) + 1);
310
-
311
- ws.send(
312
- tv.modifySeries({
313
- chartSession: key,
314
- frame: data.frame,
315
- increment: data.i,
316
- symbolKey: data.symbolKey,
317
- period: periods[period],
318
- }),
319
- );
320
- this.#charts.set({ key, data });
321
- if (data.limit < limit) {
322
- ws.send(tv.moreData({ chartSession: key, frame: data.frame, add: limit - data.limit }));
323
- data.limit = limit;
896
+ if (!data) return { status: 'unlisted' };
897
+
898
+ if (data.seriesCreated === true && data.frame) {
899
+ const removed = this.#send(tv.removeSeries({ chartSession: key, frame: data.frame }));
900
+ if (!removed) {
901
+ return { status: 'retry', reason: 'remove_series_not_sent' };
902
+ }
903
+ }
904
+
905
+ const resolved = this.#resolveSymbol({ chartSession: key, symbol: validation.symbol });
906
+ if (!resolved) {
907
+ this.#charts.delete({ key });
908
+ this.#stopQueueTimer();
909
+ this.#scheduleQueue(0);
910
+ return { status: 'not_connected' };
911
+ }
912
+ data.symbolKey = resolved.key;
913
+ data.symbol = validation.symbol;
914
+ data.period = validation.period;
915
+ data.frame = this.#nextChartFrame();
916
+ data.i = 's1';
917
+ data.limit = validation.limit;
918
+ data.requestedLimit = validation.limit;
919
+ data.historyBars = {};
920
+ data.historyPending = true;
921
+ data.historyCompletionsPending = 1;
922
+ data.seriesGeneration = Number(data.seriesGeneration || 0) + 1;
923
+ data.seriesCreated = true;
924
+ data.deleted = false;
925
+ data.end = null;
926
+
927
+ const created = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[validation.period], limit: validation.limit }));
928
+ if (!created) {
929
+ data.deleted = true;
930
+ data.seriesCreated = false;
931
+ data.historyPending = false;
932
+ data.historyCompletionsPending = 0;
933
+ data.historyBars = {};
934
+ this.#charts.set({ key, data });
935
+ this.#stopQueueTimer();
936
+ this.#scheduleQueue(0);
937
+ return { status: 'not_connected' };
324
938
  }
325
- return 'update';
939
+
940
+ this.#charts.set({
941
+ key,
942
+ data,
943
+ });
944
+
945
+ return { status: 'update', symbol: validation.symbol, period: validation.period, limit: validation.limit };
326
946
  }
327
947
 
328
948
  deleteChartSymbol({ symbol, period }) {
329
- let key = this.#charts.getBySymbolPeriod({ symbol, period });
330
- if (!key) return void console.warn('deleteChartSymbol empty key');
949
+ const validation = this.#validateChartIdentity({ symbol, period });
950
+ if (!validation.ok) return { status: 'invalid', reason: validation.reason };
951
+ const droppedFromQueue = this.#dropQueuedSymbolPeriod({ symbol: validation.symbol, period: validation.period });
952
+ const key = this.#charts.getBySymbolPeriod({ symbol: validation.symbol, period: validation.period });
953
+ if (!key) return { status: droppedFromQueue ? 'dequeued' : 'unlisted' };
954
+
955
+ const data = this.#charts.get({ key });
956
+ let remoteRemoved = false;
957
+
958
+ if (data?.seriesCreated === true && this.#isOpen()) {
959
+ remoteRemoved = this.#send(tv.removeSeries({ chartSession: key, frame: data.frame }));
960
+ if (!remoteRemoved) return { status: 'retry', reason: 'remove_series_not_sent' };
961
+ }
962
+
331
963
  this.#charts.delete({ key });
332
- return void console.log('deleteChartSymbol: ', key);
333
- }
964
+ this.#stopQueueTimer();
965
+ this.#scheduleQueue(0);
334
966
 
335
- messageListner({ result }) {
336
- ws.on('message', (raw) => {
337
- if (ws.readyState !== ws.OPEN) return;
967
+ return { status: droppedFromQueue ? 'delete+dequeued' : 'delete', remoteRemoved };
968
+ }
338
969
 
339
- // console.log('raw: ', JSON.stringify(raw.toString()));
340
- let session = '';
341
- tv.parsePacket({ str: raw }).forEach((packet) => {
342
- this.handlePacket({ packet, result, raw });
343
- });
970
+ messageListner({ socket }) {
971
+ socket.on('message', (raw) => {
972
+ if (this.#ws !== socket || socket.readyState !== WebSocket.OPEN) return;
973
+ this.#lastMessageAt = Date.now();
974
+ try {
975
+ tv.parsePacket({str: raw,}).forEach((packet) => this.handlePacket({ packet, raw }));
976
+ } catch (error) {
977
+ this.#emit('error', { type: 'message_handler_error', message: error?.message || String(error) });
978
+ }
344
979
  });
345
980
  }
346
981
 
347
- handlePacket({ packet, result, raw }) {
982
+ handlePacket({ packet, raw }) {
348
983
  if (!packet) {
349
- console.warn('Undefined packet:', raw.toString());
984
+ console.warn('Undefined packet:', raw?.toString?.() || '');
350
985
  return;
351
986
  }
352
987
 
353
988
  switch (packet.type) {
354
989
  case 'ping':
355
- ws.send(tv.createPong({ value: packet.data }));
990
+ this.#send(tv.createPong({ value: packet.data }));
356
991
  break;
357
992
  case 'qsd':
358
- this.handleQsdPacket({ packet, result });
993
+ this.handleQsdPacket({ packet });
359
994
  break;
360
995
  case 'du':
361
996
  case 'timescale_update':
362
- this.handleChartPacket({ packet, result });
997
+ this.handleChartPacket({ packet });
363
998
  break;
364
999
  case 'session':
365
1000
  console.info(packet);
366
1001
  break;
367
- case 'symbol':
1002
+
368
1003
  case 'series':
1004
+ if (packet?.data?.sub === 'completed') this.handleSeriesPacket({ packet });
1005
+ else if (packet?.data?.sub === 'error') this.handleSeriesError({ packet });
1006
+ break;
1007
+
1008
+ case 'symbol':
369
1009
  case 'quote':
370
1010
  break;
1011
+
1012
+ case 'msg': {
1013
+ const sub = packet?.data?.sub || 'unknown';
1014
+ const detail = packet?.data?.detail || null;
1015
+
1016
+ console.error('Unhandled packet type:', packet.type, sub);
1017
+ console.debug('packet error state:', this.getDebugState());
1018
+
1019
+ const capacityType = this.#onCapacitySignal(JSON.stringify(detail || []));
1020
+ if (capacityType) {
1021
+ this.#emit('error', { type: capacityType, sub, detail, retryable: true });
1022
+ break;
1023
+ }
1024
+ this.#emit('error', { type: packet.type, sub, detail });
1025
+ break;
1026
+ }
1027
+
1028
+ case 'msgError':
1029
+ console.error('Unhandled packet type:', packet.type);
1030
+ console.debug('packet error state:', this.getDebugState());
1031
+
1032
+ const detail = packet?.data || null;
1033
+ const capacityType = this.#onCapacitySignal(JSON.stringify(detail || {}));
1034
+ if (capacityType) {
1035
+ this.#emit('error', { type: capacityType, detail, retryable: true });
1036
+ break;
1037
+ }
1038
+ this.#emit('error', { type: packet.type, detail });
1039
+ break;
1040
+
371
1041
  default:
372
1042
  console.error('Unhandled packet type:', packet.type);
373
- result('error', raw.toString());
1043
+ console.debug('packet error state:', this.getDebugState());
1044
+ this.#emit('error', { type: packet.type || 'unknown', raw: raw?.toString?.() || null});
374
1045
  }
375
1046
  }
376
1047
 
377
- handleQsdPacket({ packet, result }) {
378
- const send = packet.data[1].v;
379
- const name = send.bid === undefined && send.ask === undefined ? 'data' : 'levelI';
380
- send.symbol = (extractJSON(packet.data[1].n) || { symbol: packet.data[1].n }).symbol;
381
- result(name, send);
382
- }
383
-
384
- handleChartPacket({ packet, result }) {
385
- const session = this.#charts.get({ key: packet.data[0] });
386
- if (packet.data[1][session.frame].s.length > 0) {
387
- const send = {
388
- symbol: session.symbol,
389
- period: parseInt(session.period),
390
- chart: [],
391
- end: packet.data[1][session.frame].lbs.bar_close_time,
392
- };
393
- packet.data[1][session.frame].s.forEach((each) => {
394
- send.chart.push({
395
- open: each.v[1],
396
- high: each.v[2],
397
- low: each.v[3],
398
- close: each.v[4],
399
- timestamp: each.v[0] * 1000,
400
- volume: each.v[5],
401
- });
402
- });
403
- result(packet.type === 'du' ? 'chart_update' : 'chart_history', send);
1048
+ handleQsdPacket({ packet }) {
1049
+ const source = packet?.data?.[1];
1050
+ const value = source?.v;
1051
+
1052
+ if (!source || !value || typeof value !== 'object') {
1053
+ this.#emit('error', { type: 'invalid_qsd_packet' });
1054
+ return;
404
1055
  }
1056
+
1057
+ const parsed = utils.extractJSON(source.n);
1058
+ const send = { ...value, symbol: parsed?.symbol || source.n || null };
1059
+ const name = send.bid === undefined && send.ask === undefined ? 'data' : 'levelI';
1060
+
1061
+ this.#emit(name, send);
1062
+ }
1063
+
1064
+ handleSeriesError({ packet }) {
1065
+ const detail = packet?.data?.detail;
1066
+ if (!Array.isArray(detail)) return;
1067
+
1068
+ const chartSessionKey = detail[0];
1069
+ const errorFrame = detail[1];
1070
+ const session = chartSessionKey ? this.#charts.get({ key: chartSessionKey }) : null;
1071
+ if (!session || session.deleted) return;
1072
+ if (errorFrame && errorFrame !== session.frame) return;
1073
+
1074
+ const symbol = session.symbol;
1075
+ const period = parseInt(session.period);
1076
+ const message = detail.slice(2).map((value) => typeof value === 'string' ? value : JSON.stringify(value)).join(' ') || 'TradingView series error';
1077
+
1078
+ this.#charts.delete({ key: chartSessionKey });
1079
+ this.#stopQueueTimer();
1080
+ this.#scheduleQueue(0);
1081
+ this.#emit('error', { type: 'chart_error', code: 'series_error', symbol, period, message, detail, retryable: false });
1082
+ }
1083
+
1084
+ handleSeriesPacket({ packet }) {
1085
+ const detail = packet?.data?.detail;
1086
+ if (!Array.isArray(detail)) return;
1087
+
1088
+ const chartSessionKey = detail[0];
1089
+ const completedFrame = detail[1];
1090
+ const session = chartSessionKey ? this.#charts.get({ key: chartSessionKey }) : null;
1091
+
1092
+ if (!session || session.deleted || session.historyPending !== true) return;
1093
+ if (completedFrame && completedFrame !== session.frame) return;
1094
+
1095
+ session.historyCompletionsPending = Math.max(0, Number(session.historyCompletionsPending || 1) - 1);
1096
+ if (session.historyCompletionsPending > 0) return;
1097
+
1098
+ const chart = this.#getChartHistory({ session });
1099
+ session.historyPending = false;
1100
+ session.historyBars = Object.fromEntries(chart.map((bar) => [String(bar.timestamp), bar]));
1101
+ console.debug('tv chart history completed:', { symbol: session.symbol, period: session.period, count: chart.length, session: chartSessionKey, frame: session.frame, generation: session.seriesGeneration });
1102
+ this.#emit('chart_history', { symbol: session.symbol, period: parseInt(session.period), chart, end: session.end ?? null });
1103
+ }
1104
+
1105
+ handleChartPacket({ packet }) {
1106
+ const chartSessionKey = packet?.data?.[0];
1107
+ const session = chartSessionKey ? this.#charts.get({ key: chartSessionKey }) : null;
1108
+ if (!session || session.deleted) return;
1109
+
1110
+ const frame = packet?.data?.[1]?.[session.frame];
1111
+ if (!frame) return;
1112
+
1113
+ const chart = this.#parseChartBars({ frame });
1114
+ if (chart.length === 0) return;
1115
+
1116
+ session.end = frame?.lbs?.bar_close_time ?? session.end ?? null;
1117
+
1118
+ this.#mergeChartBars({ session, chart });
1119
+
1120
+ console.debug('tv chart received:', { symbol: session.symbol, period: session.period, count: chart.length, historyPending: session.historyPending });
1121
+
1122
+ if (session.historyPending === true) return;
1123
+
1124
+ const stored = this.#getChartHistory({ session });
1125
+ session.historyBars = Object.fromEntries(stored.map((bar) => [String(bar.timestamp), bar]));
1126
+ this.#emit('chart_update', { symbol: session.symbol, period: parseInt(session.period), chart, end: session.end });
405
1127
  }
406
1128
  };