market-data-tradingview-ws 1.0.0 → 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
@@ -5,6 +5,7 @@
5
5
  const WebSocket = require('ws');
6
6
  const tv = require('./tradingView.js');
7
7
  const utils = require('./utils.js');
8
+ const { resolveProxy, getWebSocketAgent, closeProxyAgents } = require('./proxy.js');
8
9
 
9
10
  const periods = {
10
11
  60: '1',
@@ -18,38 +19,55 @@ const periods = {
18
19
  2592000: '1M',
19
20
  };
20
21
 
21
- let ws = null;
22
+
22
23
 
23
24
  module.exports = class Client {
24
25
  #charts = {
25
26
  values: {},
26
27
  set({ key, data }) {
27
- if (data) {
28
- this.values[key] = {
29
- id: data.id,
30
- symbol: data.symbol,
31
- period: parseInt(data.period),
32
- symbolKey: data.symbolKey,
33
- frame: data.frame,
34
- i: data.i,
35
- deleted: data.deleted || false,
36
- limit: data.limit || 1500,
37
- };
38
- }
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
+ };
39
47
  },
40
48
  delete({ key }) {
41
- 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;
42
58
  },
43
59
  get({ key }) {
44
60
  return this.values[key];
45
61
  },
46
- getDeleted({ min = 0 } = {}) {
47
- for (let key of Object.keys(this.values)) {
62
+ getDeleted() {
63
+ for (const key of Object.keys(this.values)) {
48
64
  const item = this.values[key];
49
- if (item.deleted && Number(item.limit || 0) >= Number(min || 0)) {
65
+
66
+ if (item?.deleted) {
50
67
  return { key, data: item };
51
68
  }
52
69
  }
70
+
53
71
  return null;
54
72
  },
55
73
  claimDeleted({ key }) {
@@ -96,91 +114,227 @@ module.exports = class Client {
96
114
  if (index !== -1) arr.splice(index, 1);
97
115
  },
98
116
  };
99
- #symbols = {
100
- values: {},
101
- max: 1,
102
- getSymbol({ key, symbol }) {
103
- // let data = this.values[symbol];
104
- // if (data === undefined) data = this.set({ key, symbol });
105
- // return data;
106
- const symbolKey = 'sds_sym_' + this.max++;
107
- if (ws && ws.readyState === ws.OPEN) ws.send(tv.resolveSymbol({ chartSession: key, symbolKey, symbol }));
108
- this.values[symbol] = { key: symbolKey };
109
- return this.values[symbol];
110
- },
111
- };
117
+ #symbols = { values: {}, max: 1 };
118
+
119
+ #watchdogIntervalMs = 10_000;
120
+ #watchdogTimeoutMs = 60_000;
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
+ }
112
149
 
113
150
  #token = null;
114
151
  #sessionid = null;
115
152
  #sessionidsign = null;
153
+ #connectGeneration = 0;
154
+ #connectAbortController = null;
155
+
156
+ #chartFrameMax = 0;
116
157
  #chartQueue = [];
117
158
  #queuedChartKeys = new Set();
118
159
  #queueTimer = null;
119
160
  #queueProcessing = false;
120
161
  #queueBlockedUntil = 0;
162
+ #configuredMaxChartSessions = 180;
121
163
  #maxChartSessions = 180;
122
164
  #chartCreateIntervalMs = 60;
123
165
  #queueRetryMs = 500;
124
- #chartQueueTtlMs = 8000;
166
+ #chartQueueTtlMs = 30_000;
125
167
  #maxQueuedCharts = 200;
126
- #pending = new Set();
168
+ #maxBufferedAmount = 4 * 1024 * 1024;
169
+ #closeTimeoutMs = 5_000;
170
+ #intentionalClose = false;
171
+ #watchdogTimer = null;
172
+ #lastMessageAt = 0;
127
173
 
128
174
  constructor(config = {}) {
129
175
  const cfg = config && typeof config === 'object' ? config : {};
130
- this.#maxChartSessions = utils.positive(cfg.max, this.#maxChartSessions);
176
+ this.#configuredMaxChartSessions = utils.positive(cfg.max, this.#configuredMaxChartSessions);
177
+ this.#maxChartSessions = this.#configuredMaxChartSessions;
131
178
  this.#chartCreateIntervalMs = utils.positive(cfg.interval, this.#chartCreateIntervalMs);
132
179
  this.#queueRetryMs = utils.positive(cfg.retry, this.#queueRetryMs);
133
- this.#chartQueueTtlMs = utils.positive(cfg.ttl, this.#chartQueueTtlMs);
134
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);
135
182
  }
136
183
 
137
- #resetState() {
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() {
138
201
  this.#charts.values = {};
139
202
  this.#quotes.values = {};
140
203
  this.#symbols.values = {};
141
204
  this.#symbols.max = 1;
205
+ this.#maxChartSessions = this.#configuredMaxChartSessions;
206
+ this.#chartFrameMax = 0;
142
207
  this.#chartQueue = [];
143
208
  this.#queuedChartKeys.clear();
144
209
  this.#queueBlockedUntil = 0;
145
- this.#pending.clear();
146
- if (this.#queueTimer) {
147
- clearTimeout(this.#queueTimer);
148
- this.#queueTimer = null;
149
- }
210
+ this.#stopQueueTimer();
211
+ this.#queueProcessing = false;
212
+ }
213
+
214
+ #resetState() {
215
+ this.#resetRemoteState();
150
216
  }
151
217
 
152
218
  #chartQueueKey({ symbol, period }) {
153
219
  return symbol + '|' + String(period);
154
220
  }
155
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
+
156
252
  #countActiveCharts() {
157
253
  return Object.values(this.#charts.values).filter((item) => item && !item.deleted && item.symbol && item.period).length;
158
254
  }
159
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
+
160
296
  #scheduleQueue(delay = 0) {
161
- if (this.#queueTimer) return;
297
+ if (!this.#isOpen() || this.#queueTimer) return;
162
298
  this.#queueTimer = setTimeout(() => {
163
299
  this.#queueTimer = null;
164
300
  void this.#processChartQueue();
165
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;
166
310
  }
167
311
 
168
312
  #isOpen() {
169
- return !!ws && ws.readyState === ws.OPEN;
313
+ return this.#ws?.readyState === WebSocket.OPEN;
170
314
  }
171
315
 
172
316
  #send(data) {
173
- if (!this.#isOpen()) return false;
174
- ws.send(data);
175
- return true;
176
- }
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
+ });
177
336
 
178
- #flush() {
179
- if (!this.#isOpen()) return;
180
- if (this.#pending.size === 0) return;
181
- const symbols = Array.from(this.#pending);
182
- this.#pending.clear();
183
- this.addQuoteSymbols({ symbols });
337
+ return true;
184
338
  }
185
339
 
186
340
  #logQueueState(context = '', extra = {}) {
@@ -198,19 +352,25 @@ module.exports = class Client {
198
352
  }
199
353
 
200
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
+
201
364
  if (this.#chartQueue.length >= this.#maxQueuedCharts) {
202
- this.#logQueueState('enqueue_drop_overflow', { force: true, symbol, period, limit, maxQueued: 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 });
203
367
  return 'dropped';
204
368
  }
205
369
 
206
- const queueKey = this.#chartQueueKey({ symbol, period });
207
- if (this.#queuedChartKeys.has(queueKey)) return 'queued';
208
370
  this.#queuedChartKeys.add(queueKey);
209
371
  this.#chartQueue.push({ symbol, period, limit, queueKey, expiresAt: Date.now() + this.#chartQueueTtlMs });
210
- if (this.#chartQueue.length > 25) {
211
- this.#logQueueState('enqueue_backpressure', { symbol, period, limit });
212
- }
213
372
  this.#scheduleQueue();
373
+
214
374
  return 'queued';
215
375
  }
216
376
 
@@ -227,27 +387,25 @@ module.exports = class Client {
227
387
  if (text.includes('max charts per connection reached')) {
228
388
  const active = this.#countActiveCharts();
229
389
  if (active > 0 && active < this.#maxChartSessions) this.#maxChartSessions = active;
230
- this.#queueBlockedUntil = Date.now() + 10 * 1000;
231
- this.#logQueueState('capacity_max_charts', { force: true, reason: text.slice(0, 220) });
390
+ this.#queueBlockedUntil = Date.now() + 10_000;
391
+ this.#logQueueState('capacity_max_charts', { reason: text.slice(0, 220) });
232
392
  this.#scheduleQueue(this.#queueRetryMs);
233
- return;
393
+ return 'capacity_max_charts';
234
394
  }
235
395
  if (text.includes('max sessions rate reached')) {
236
- this.#queueBlockedUntil = Date.now() + 5 * 1000;
237
- this.#logQueueState('capacity_rate_limit', { force: true, reason: text.slice(0, 220) });
396
+ this.#queueBlockedUntil = Date.now() + 5_000;
397
+ this.#logQueueState('capacity_rate_limit', { reason: text.slice(0, 220) });
238
398
  this.#scheduleQueue(this.#queueRetryMs);
399
+ return 'capacity_rate_limit';
239
400
  }
401
+ return null;
240
402
  }
241
403
 
242
404
  async #processChartQueue() {
243
- if (this.#queueProcessing) return;
405
+ if (this.#queueProcessing || !this.#isOpen()) return;
406
+ const generation = this.#connectGeneration;
244
407
  this.#queueProcessing = true;
245
408
  try {
246
- if (!ws || ws.readyState !== ws.OPEN) {
247
- this.#scheduleQueue(this.#queueRetryMs);
248
- return;
249
- }
250
-
251
409
  const wait = this.#queueBlockedUntil - Date.now();
252
410
  if (wait > 0) {
253
411
  this.#scheduleQueue(wait);
@@ -255,6 +413,7 @@ module.exports = class Client {
255
413
  }
256
414
 
257
415
  while (this.#chartQueue.length > 0) {
416
+ if (generation !== this.#connectGeneration || !this.#isOpen()) return;
258
417
  const active = this.#countActiveCharts();
259
418
  if (active >= this.#maxChartSessions) {
260
419
  this.#logQueueState('queue_paused_capacity');
@@ -267,56 +426,114 @@ module.exports = class Client {
267
426
  this.#queuedChartKeys.delete(next.queueKey);
268
427
  if (next.expiresAt && next.expiresAt < Date.now()) {
269
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 });
270
430
  continue;
271
431
  }
272
432
 
273
433
  const existKey = this.#charts.getBySymbolPeriod({ symbol: next.symbol, period: next.period });
274
434
  if (existKey) continue;
275
435
 
276
- this.#addChartSymbolNow({ symbol: next.symbol, period: next.period, limit: next.limit });
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
+ }
277
441
  await utils.pause(this.#chartCreateIntervalMs);
278
442
  }
279
443
  } finally {
280
- this.#queueProcessing = false;
281
- if (this.#chartQueue.length > 0 && !this.#queueTimer) this.#scheduleQueue(this.#queueRetryMs);
444
+ if (generation === this.#connectGeneration) {
445
+ this.#queueProcessing = false;
446
+ if (this.#chartQueue.length > 0 && this.#isOpen()) this.#scheduleQueue(this.#queueRetryMs);
447
+ }
282
448
  }
283
449
  }
284
450
 
285
451
  async close() {
286
- this.#resetState();
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
+
287
499
  this.#token = null;
288
500
  this.#sessionid = null;
289
501
  this.#sessionidsign = null;
290
- if (ws && (ws.readyState === ws.OPEN || ws.readyState === ws.CONNECTING)) ws.close();
291
- ws = null;
502
+ this.#proxy = null;
503
+ this.#result = null;
504
+
505
+ this.#intentionalClose = false;
506
+
292
507
  return 'close';
293
508
  }
294
509
 
295
510
  // Возвращает debug state с информацией
296
511
  getDebugState() {
512
+ const charts = Object.values(this.#charts.values);
297
513
  return {
298
- wsReadyState: ws?.readyState,
299
- 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),
300
520
  tokenLen: this.#token ? this.#token.length : 0,
301
- sessionid: this.#sessionid,
302
- sessionidsign: this.#sessionidsign,
303
- 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,
304
526
  quotesCount: Object.keys(this.#quotes.values).length,
305
- chartsKeys: Object.keys(this.#charts.values),
306
- quotesKeys: Object.keys(this.#quotes.values),
307
527
  chartQueueLength: this.#chartQueue.length,
308
528
  chartQueuedKeys: this.#queuedChartKeys.size,
529
+ configuredMaxChartSessions: this.#configuredMaxChartSessions,
309
530
  maxChartSessions: this.#maxChartSessions,
310
- activeChartSessions: this.#countActiveCharts(),
311
531
  queueBlockedMs: Math.max(0, this.#queueBlockedUntil - Date.now()),
312
- quotes: this.#quotes.values,
313
- quoteSymbols: Object.values(this.#quotes.values).map((item) => item.symbols),
314
- charts: this.#charts.values,
315
532
  };
316
533
  }
317
534
 
318
- async getToken({ sessionId, sessionIdSign, tvEcuid, imageUrl }) {
319
- 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 });
320
537
  }
321
538
 
322
539
  auth(token = 'unauthorized_user_token') {
@@ -328,64 +545,143 @@ module.exports = class Client {
328
545
  });
329
546
  }
330
547
 
331
- 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
+
332
560
  try {
333
- this.#token = await this.getToken({
334
- sessionId: sessionid,
335
- sessionIdSign: sessionidsign,
336
- tvEcuid: tvecuid,
337
- imageUrl: imageurl,
338
- });
339
- // console.info('Token:', this.#token);
340
- this.#sessionid = sessionid;
341
- this.#sessionidsign = sessionidsign;
342
-
343
- if (this.#token.length > 10) {
344
- return new Promise((resolv, reject) => {
345
- try {
346
- const date = new Date();
347
- const year = date.getFullYear();
348
- const month = String(date.getMonth() + 1).padStart(2, '0');
349
- const day = String(date.getDate()).padStart(2, '0');
350
- url += `?from=chart%2F${imageurl}%2F&date=${year}_${month}_${day}-11_25&type=chart`;
351
- ws = new WebSocket(url, options);
352
-
353
- const originalSend = ws.send;
354
- ws.send = function (...args) {
355
- // console.log('Message sent:', args[0]);
356
- originalSend.apply(ws, args);
357
- };
358
-
359
- ws.onclose = () => console.log('disconnected');
360
-
361
- ws.onerror = (error) => reject(console.error('error: ', error));
362
- ws.onopen = () => {
363
- this.#send(this.auth(this.#token));
364
- this.#send(tv.setLocaleRu());
365
-
366
- const quoteKey = this.createQuoteSmallSession();
367
- this.#flush();
368
-
369
- this.messageListner({ result });
370
- this.#scheduleQueue();
371
- resolv('open');
372
- };
373
- } catch (error) {
374
- reject(error);
375
- }
376
- });
377
- }
378
- return null;
379
- } catch (error) {
380
- console.error('Error in connect:', error.message);
381
- throw error;
561
+ return await this.#connectPromise;
562
+ } finally {
563
+ if (this.#connectAbortController === controller) this.#connectAbortController = null;
564
+ this.#connectPromise = null;
382
565
  }
383
566
  }
384
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
+
385
681
  async disconnect() {
386
682
  try {
387
683
  if (this.#sessionid && this.#sessionidsign) {
388
- await tv.disconnect({ sessionId: this.#sessionid, sessionIdSign: this.#sessionidsign });
684
+ await tv.disconnect({ sessionId: this.#sessionid, sessionIdSign: this.#sessionidsign, proxy: this.#proxy, });
389
685
  }
390
686
  } catch (error) {
391
687
  console.warn('disconnect failed:', error?.message || error);
@@ -414,41 +710,94 @@ module.exports = class Client {
414
710
  createChartSession() {
415
711
  const key = tv.createSession({ startsWith: 'cs_' });
416
712
  this.#charts.set({ key, data: { id: key, symbol: '', period: 0, symbolKey: '', frame: '', i: '', deleted: false } });
417
- this.#send(tv.chartCreateSession({ chartSession: key }));
418
- this.#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
+ }
419
719
  return key;
420
720
  }
421
721
 
422
722
  addQuoteSymbols({ symbols }) {
423
- const result = { add: [], exist: [], queued: [] };
723
+ const result = { add: [], exist: [], rejected: [] };
424
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
+
425
729
  if (!this.#isOpen()) {
426
- symbols.forEach((symbol) => {
427
- if (typeof symbol === 'string' && symbol.length > 0) this.#pending.add(symbol);
428
- });
429
- result.queued = symbols.slice();
430
- return result;
730
+ result.rejected = valid;
731
+ return { ...result, status: 'not_connected' };
431
732
  }
432
- // if (Object.keys(this.#quotes.values).length === 0) this.createQuoteSet1Session();
433
- symbols.forEach((symbol) => {
733
+
734
+ if (Object.keys(this.#quotes.values).length === 0) this.createQuoteSmallSession();
735
+
736
+ for (const symbol of valid) {
434
737
  let key = this.#quotes.getBySymbol({ symbol });
435
738
  if (key) {
436
739
  result.exist.push(symbol);
437
- } else {
438
- key = this.#quotes.add({ symbol });
439
- this.#send(tv.quoteAddSymbol({ session: key, symbol }));
440
- result.add.push(symbol);
740
+ continue;
441
741
  }
442
- });
443
- 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' };
444
760
  }
445
761
 
446
762
  deleteQuoteSymbol({ symbol }) {
447
- 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 });
448
766
  if (!key) return 'unlisted';
449
- this.#quotes.delete({ key, symbol });
450
- this.#send(tv.quoteRemoveSymbols({ session: key, symbol }));
451
- 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';
770
+ }
771
+
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';
452
801
  }
453
802
 
454
803
  #addChartSymbolNow({ symbol, period, limit = 1500 }) {
@@ -461,7 +810,10 @@ module.exports = class Client {
461
810
  const data = this.#charts.get({ key });
462
811
  if (data && Number(limit) > Number(data.limit || 0)) {
463
812
  const add = Number(limit) - Number(data.limit || 0);
464
- this.#send(tv.moreData({ chartSession: key, frame: data.frame, add }));
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);
465
817
  data.limit = Number(limit);
466
818
  this.#charts.set({ key, data });
467
819
  console.debug('addChartSymbol extend:', key, symbol, period, { add, limit });
@@ -470,122 +822,166 @@ module.exports = class Client {
470
822
  console.debug('addChartSymbol exist:', key, symbol, period);
471
823
  return 'exist';
472
824
  }
473
- // console.warn('modules addChartSymbol1', symbol, period, limit, key);
474
- const deleted = this.#charts.getDeleted({ min: limit });
475
- if (deleted !== null) {
476
- this.#charts.claimDeleted({ key: deleted.key });
477
- return this.updateChartSymbol({
478
- symbol,
479
- period,
480
- limit,
481
- key: deleted.key,
482
- last: { symbol: deleted.data.symbol, period: parseInt(deleted.data.period) },
483
- });
484
- }
825
+ const deleted = this.#charts.getDeleted();
826
+ if (deleted !== null) return this.#reuseDeletedChartSession({ key: deleted.key, symbol, period, limit });
485
827
 
486
828
  key = this.createChartSession();
829
+ if (!key) return 'not_connected';
487
830
  const data = this.#charts.get({ key });
488
831
 
489
- 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
+
490
839
  data.symbol = symbol;
491
840
  data.period = period;
492
- data.frame = 'sds_' + Object.keys(this.#charts.values).length;
493
- data.i = 's' + 1;
494
- 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
+ }
495
857
 
496
- this.#send(
497
- tv.createSeries({
498
- chartSession: key,
499
- frame: data.frame,
500
- increment: data.i,
501
- symbolKey: data.symbolKey,
502
- period: periods[period],
503
- limit,
504
- }),
505
- );
506
- // console.warn('addChartSymbol4', periods[period], data);
507
858
  this.#charts.set({ key, data });
859
+ console.debug('tv chart sent:', { symbol, period, session: key, frame: data.frame, limit });
508
860
  return 'add';
509
861
  }
510
862
 
511
863
  addChartSymbol({ symbol, period, limit = 1500 }) {
512
- if (!symbol || typeof symbol !== 'string') return 'invalid';
513
- if (!period || typeof period !== 'number') return 'invalid';
514
- if (!limit || typeof limit !== 'number') 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 };
515
867
 
516
- const key = this.#charts.getBySymbolPeriod({ symbol, period });
868
+ const key = this.#charts.getBySymbolPeriod({ symbol: validation.symbol, period: validation.period });
517
869
  if (key) {
518
870
  const data = this.#charts.get({ key });
519
- if (data && Number(limit) > Number(data.limit || 0)) {
520
- const add = Number(limit) - Number(data.limit || 0);
521
- this.#send(tv.moreData({ chartSession: key, frame: data.frame, add }));
522
- data.limit = Number(limit);
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;
523
879
  this.#charts.set({ key, data });
524
- console.debug('addChartSymbol extend:', key, symbol, period, { add, limit });
525
- return 'extend';
880
+ return { status: 'extend', symbol: validation.symbol, period: validation.period, limit: validation.limit };
526
881
  }
527
- console.debug('addChartSymbol exist:', key, symbol, period);
528
- return 'exist';
882
+ return { status: 'exist', symbol: validation.symbol, period: validation.period, limit: Number(data?.limit || 0) };
529
883
  }
530
-
531
- return this.#enqueueChart({ symbol, period, limit });
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 };
532
886
  }
533
887
 
534
888
  updateChartSymbol({ symbol, period, limit, last, key: providedKey }) {
535
- const key = providedKey || this.#charts.getBySymbolPeriod({ symbol: last.symbol, period: last.period });
536
- if (!key) return 'unlisted';
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
+
537
895
  const data = this.#charts.get({ key });
538
- if (!data) return 'unlisted';
896
+ if (!data) return { status: 'unlisted' };
539
897
 
540
- data.symbolKey = this.#symbols.getSymbol({ key, symbol }).key;
541
- data.symbol = symbol;
542
- data.period = period;
543
- data.i = 's' + (parseInt(data.i.replace(/[^0-9]/g, '')) + 1);
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
+ }
544
904
 
545
- this.#send(
546
- tv.modifySeries({
547
- chartSession: key,
548
- frame: data.frame,
549
- increment: data.i,
550
- symbolKey: data.symbolKey,
551
- period: periods[period],
552
- }),
553
- );
554
- this.#charts.set({ key, data });
555
- if (data.limit < limit) {
556
- this.#send(tv.moreData({ chartSession: key, frame: data.frame, add: limit - data.limit }));
557
- data.limit = limit;
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' };
558
911
  }
559
- return 'update';
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' };
938
+ }
939
+
940
+ this.#charts.set({
941
+ key,
942
+ data,
943
+ });
944
+
945
+ return { status: 'update', symbol: validation.symbol, period: validation.period, limit: validation.limit };
560
946
  }
561
947
 
562
948
  deleteChartSymbol({ symbol, period }) {
563
- const droppedFromQueue = this.#dropQueuedSymbolPeriod({ symbol, period });
564
- let key = this.#charts.getBySymbolPeriod({ symbol, period });
565
- if (!key) {
566
- if (droppedFromQueue) return 'dequeued';
567
- return 'unlisted';
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' };
568
961
  }
962
+
569
963
  this.#charts.delete({ key });
570
- this.#scheduleQueue();
571
- if (droppedFromQueue) return 'delete+dequeued';
572
- return 'delete';
573
- }
964
+ this.#stopQueueTimer();
965
+ this.#scheduleQueue(0);
574
966
 
575
- messageListner({ result }) {
576
- ws.on('message', (raw) => {
577
- if (!ws || ws.readyState !== ws.OPEN) return;
967
+ return { status: droppedFromQueue ? 'delete+dequeued' : 'delete', remoteRemoved };
968
+ }
578
969
 
579
- // console.log('raw: ', JSON.stringify(raw.toString()));
580
- tv.parsePacket({ str: raw }).forEach((packet) => {
581
- this.handlePacket({ packet, result, raw });
582
- });
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
+ }
583
979
  });
584
980
  }
585
981
 
586
- handlePacket({ packet, result, raw }) {
982
+ handlePacket({ packet, raw }) {
587
983
  if (!packet) {
588
- console.warn('Undefined packet:', raw.toString());
984
+ console.warn('Undefined packet:', raw?.toString?.() || '');
589
985
  return;
590
986
  }
591
987
 
@@ -594,78 +990,139 @@ module.exports = class Client {
594
990
  this.#send(tv.createPong({ value: packet.data }));
595
991
  break;
596
992
  case 'qsd':
597
- this.handleQsdPacket({ packet, result });
993
+ this.handleQsdPacket({ packet });
598
994
  break;
599
995
  case 'du':
600
996
  case 'timescale_update':
601
- this.handleChartPacket({ packet, result });
997
+ this.handleChartPacket({ packet });
602
998
  break;
603
999
  case 'session':
604
1000
  console.info(packet);
605
1001
  break;
606
- case 'symbol':
1002
+
607
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':
608
1009
  case 'quote':
609
1010
  break;
610
- case 'msg': {
1011
+
1012
+ case 'msg': {
611
1013
  const sub = packet?.data?.sub || 'unknown';
1014
+ const detail = packet?.data?.detail || null;
1015
+
612
1016
  console.error('Unhandled packet type:', packet.type, sub);
613
1017
  console.debug('packet error state:', this.getDebugState());
614
- this.#onCapacitySignal(JSON.stringify(packet?.data?.detail || []));
615
- result('error', {
616
- type: packet.type,
617
- sub,
618
- detail: packet?.data?.detail || null,
619
- });
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 });
620
1025
  break;
621
1026
  }
1027
+
622
1028
  case 'msgError':
623
1029
  console.error('Unhandled packet type:', packet.type);
624
1030
  console.debug('packet error state:', this.getDebugState());
625
- this.#onCapacitySignal(JSON.stringify(packet?.data || {}));
626
- result('error', {
627
- type: packet.type,
628
- detail: packet?.data || null,
629
- });
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 });
630
1039
  break;
1040
+
631
1041
  default:
632
1042
  console.error('Unhandled packet type:', packet.type);
633
1043
  console.debug('packet error state:', this.getDebugState());
634
- result('error', {
635
- type: packet.type,
636
- raw: raw.toString(),
637
- });
1044
+ this.#emit('error', { type: packet.type || 'unknown', raw: raw?.toString?.() || null});
638
1045
  }
639
1046
  }
640
1047
 
641
- handleQsdPacket({ packet, result }) {
642
- const send = packet.data[1].v;
643
- const name = send.bid === undefined && send.ask === undefined ? 'data' : 'levelI';
644
- send.symbol = (utils.extractJSON(packet.data[1].n) || { symbol: packet.data[1].n }).symbol;
645
- result(name, send);
646
- }
647
-
648
- handleChartPacket({ packet, result }) {
649
- const session = this.#charts.get({ key: packet.data[0] });
650
- if (!session || !packet?.data?.[1]?.[session.frame]) return;
651
- if (packet.data[1][session.frame].s.length > 0) {
652
- const send = {
653
- symbol: session.symbol,
654
- period: parseInt(session.period),
655
- chart: [],
656
- end: packet.data[1][session.frame].lbs.bar_close_time,
657
- };
658
- packet.data[1][session.frame].s.forEach((each) => {
659
- send.chart.push({
660
- open: each.v[1],
661
- high: each.v[2],
662
- low: each.v[3],
663
- close: each.v[4],
664
- timestamp: each.v[0] * 1000,
665
- volume: each.v[5],
666
- });
667
- });
668
- 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;
669
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 });
670
1127
  }
671
1128
  };