market-data-tradingview-ws 2.1.4 → 2.1.5

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.
Files changed (2) hide show
  1. package/lib/client.js +202 -61
  2. package/package.json +1 -1
package/lib/client.js CHANGED
@@ -38,10 +38,15 @@ module.exports = class Client {
38
38
  broken: data.broken === true,
39
39
  limit: Number(data.limit || 1500),
40
40
  requestedLimit: Number(data.requestedLimit || data.limit || 1500),
41
+ initialLimit: data.initialLimit,
42
+ batchSize: data.batchSize,
43
+ onHistoryProgress: data.onHistoryProgress,
44
+ historySignal: data.historySignal,
41
45
  historyPending: data.historyPending === true,
42
46
  historyBars: data.historyBars && typeof data.historyBars === 'object' ? data.historyBars : {},
47
+ historyBatch: data.historyBatch ?? null,
48
+ latestTimestamp: data.latestTimestamp ?? null,
43
49
  seriesGeneration: Number(data.seriesGeneration || 0),
44
- historyCompletionsPending: Number(data.historyCompletionsPending || 0),
45
50
  seriesCreated: data.seriesCreated === true,
46
51
  end: data.end ?? null,
47
52
  };
@@ -51,7 +56,9 @@ module.exports = class Client {
51
56
  if (!data) return null;
52
57
  data.deleted = true;
53
58
  data.historyPending = false;
54
- data.historyCompletionsPending = 0;
59
+ data.onHistoryProgress = null;
60
+ data.historySignal = null;
61
+ data.historyBatch = null;
55
62
  data.historyBars = {};
56
63
  data.seriesCreated = false;
57
64
  data.end = null;
@@ -64,7 +71,9 @@ module.exports = class Client {
64
71
  data.deleted = true;
65
72
  data.broken = true;
66
73
  data.historyPending = false;
67
- data.historyCompletionsPending = 0;
74
+ data.onHistoryProgress = null;
75
+ data.historySignal = null;
76
+ data.historyBatch = null;
68
77
  data.historyBars = {};
69
78
  data.seriesCreated = false;
70
79
  data.end = null;
@@ -220,6 +229,7 @@ module.exports = class Client {
220
229
  }
221
230
 
222
231
  #resetRemoteState() {
232
+ for (const session of Object.values(this.#charts.values)) this.#closeHistoryBatch(session, 'upstream_error');
223
233
  this.#charts.values = {};
224
234
  this.#quotes.values = {};
225
235
  this.#symbols.values = {};
@@ -256,13 +266,13 @@ module.exports = class Client {
256
266
  return { ok: true, symbol: normalizedSymbol, period: normalizedPeriod };
257
267
  }
258
268
 
259
- #validateChartRequest({ symbol, period, limit }) {
269
+ #validateChartRequest({ symbol, period, limit, maxLimit = this.#chartInitialLimitMax }) {
260
270
  const identity = this.#validateChartIdentity({ symbol, period });
261
271
  if (!identity.ok) return identity;
262
272
 
263
273
  if (typeof limit !== 'number' && typeof limit !== 'string') return { ok: false, reason: 'invalid_limit' };
264
274
  const normalizedLimit = Number(limit);
265
- if (!Number.isSafeInteger(normalizedLimit) || normalizedLimit <= 0 || normalizedLimit > this.#chartInitialLimitMax) return { ok: false, reason: 'invalid_limit' };
275
+ if (!Number.isSafeInteger(normalizedLimit) || normalizedLimit <= 0 || normalizedLimit > maxLimit) return { ok: false, reason: 'invalid_limit' };
266
276
 
267
277
  return { ...identity, limit: normalizedLimit };
268
278
  }
@@ -308,7 +318,13 @@ module.exports = class Client {
308
318
  session.historyBars = {};
309
319
  }
310
320
 
321
+ const batch = session.historyPending ? session.historyBatch : null;
322
+ if (batch) batch.received += chart.length;
311
323
  for (const bar of chart) {
324
+ if (batch && !Object.hasOwn(session.historyBars, bar.timestamp)) {
325
+ batch.newUnique++;
326
+ if (batch.before !== null && bar.timestamp < batch.before) batch.earlier = true;
327
+ }
312
328
  session.historyBars[String(bar.timestamp)] = bar;
313
329
  }
314
330
  }
@@ -318,6 +334,75 @@ module.exports = class Client {
318
334
  return Object.values(session.historyBars || {}).sort((left, right) => left.timestamp - right.timestamp).slice(-requestedLimit);
319
335
  }
320
336
 
337
+ #beginHistoryBatch(session, requested, before = null) {
338
+ const batch = { requested, before, startedAt: Date.now(), received: 0, newUnique: 0, earlier: false };
339
+ session.historyBatch = batch;
340
+ session.historyPending = true;
341
+ return batch;
342
+ }
343
+
344
+ #logHistoryBatch(session, batch, chart, stopReason) {
345
+ console.debug('tv chart history batch:', {
346
+ symbol: session.symbol,
347
+ period: session.period,
348
+ requested: batch.requested,
349
+ received: batch.received,
350
+ newUnique: batch.newUnique,
351
+ accumulated: chart.length,
352
+ earliestTimestamp: chart[0]?.timestamp ?? null,
353
+ durationMs: Date.now() - batch.startedAt,
354
+ stopReason,
355
+ });
356
+ }
357
+
358
+ #closeHistoryBatch(session, reason) {
359
+ const batch = session.historyBatch;
360
+ if (!batch) return;
361
+ session.historyBatch = null;
362
+ batch.cleanup?.();
363
+ if (session.historyPending) {
364
+ this.#logHistoryBatch(session, batch, this.#getChartHistory({ session }), session.historySignal?.aborted ? session.historySignal.reason : reason);
365
+ }
366
+ }
367
+
368
+ #failHistorySend(session, chart) {
369
+ session.historyPending = false;
370
+ const progress = session.onHistoryProgress;
371
+ session.onHistoryProgress = null;
372
+ session.historySignal = null;
373
+ session.requestedLimit = session.limit = chart.length;
374
+ progress?.(chart, 'send_failed');
375
+ }
376
+
377
+ #requestMoreHistory({ session, chart, limit, batchSize }) {
378
+ const add = Math.min(limit - chart.length, batchSize);
379
+ const batch = this.#beginHistoryBatch(session, add, chart[0]?.timestamp ?? Infinity);
380
+ const signal = session.historySignal;
381
+ const abort = () => {
382
+ this.#logHistoryBatch(session, batch, this.#getChartHistory({ session }), signal.reason);
383
+ // Keep the wire request until series_completed, even after its waiter has left.
384
+ session.historyPending = false;
385
+ session.requestedLimit = session.limit = chart.length;
386
+ session.onHistoryProgress = null;
387
+ session.historySignal = null;
388
+ };
389
+ signal?.addEventListener('abort', abort, { once: true });
390
+ batch.cleanup = () => signal?.removeEventListener('abort', abort);
391
+ const sent = this.#send(tv.moreData({ chartSession: session.id, frame: session.frame, add }), () => {
392
+ if (session.historyBatch !== batch || this.#charts.get({ key: session.id }) !== session) return;
393
+ this.#closeHistoryBatch(session, 'send_failed');
394
+ if (session.historyPending || session.onHistoryProgress) this.#failHistorySend(session, chart);
395
+ });
396
+ if (!sent) {
397
+ if (session.historyBatch === batch) {
398
+ this.#closeHistoryBatch(session, 'send_failed');
399
+ session.historyPending = false;
400
+ }
401
+ return false;
402
+ }
403
+ return true;
404
+ }
405
+
321
406
  #scheduleQueue(delay = 0) {
322
407
  if (this.#chartQueuePaused || !this.#isOpen() || this.#queueTimer) return;
323
408
  this.#queueTimer = setTimeout(() => {
@@ -337,7 +422,7 @@ module.exports = class Client {
337
422
  return this.#ws?.readyState === WebSocket.OPEN;
338
423
  }
339
424
 
340
- #send(data) {
425
+ #send(data, onError) {
341
426
  const socket = this.#ws;
342
427
 
343
428
  if (!socket || socket.readyState !== WebSocket.OPEN) return false;
@@ -349,6 +434,7 @@ module.exports = class Client {
349
434
 
350
435
  socket.send(data, (error) => {
351
436
  if (!error) return;
437
+ onError?.();
352
438
  this.#emit('error', { type: 'ws_send_error', message: error.message });
353
439
  });
354
440
 
@@ -369,12 +455,17 @@ module.exports = class Client {
369
455
  });
370
456
  }
371
457
 
372
- #enqueueChart({ symbol, period, limit }) {
458
+ #enqueueChart({ symbol, period, limit, batchSize, onHistoryProgress, historySignal }) {
373
459
  const queueKey = this.#chartQueueKey({ symbol, period });
374
460
  const existing = this.#chartQueue.find((item) => item.queueKey === queueKey);
375
461
 
376
462
  if (existing) {
377
- existing.limit = Math.max(Number(existing.limit || 0), Number(limit || 0));
463
+ if (limit >= existing.limit) {
464
+ existing.limit = limit;
465
+ existing.batchSize = batchSize;
466
+ existing.onHistoryProgress = onHistoryProgress;
467
+ existing.historySignal = historySignal;
468
+ }
378
469
  existing.expiresAt = Date.now() + this.#chartQueueTtlMs;
379
470
  return 'queued';
380
471
  }
@@ -386,7 +477,7 @@ module.exports = class Client {
386
477
  }
387
478
 
388
479
  this.#queuedChartKeys.add(queueKey);
389
- this.#chartQueue.push({ symbol, period, limit, queueKey, expiresAt: Date.now() + this.#chartQueueTtlMs });
480
+ this.#chartQueue.push({ symbol, period, limit, batchSize, onHistoryProgress, historySignal, queueKey, expiresAt: Date.now() + this.#chartQueueTtlMs });
390
481
  this.#scheduleQueue();
391
482
 
392
483
  return 'queued';
@@ -451,7 +542,7 @@ module.exports = class Client {
451
542
  const existKey = this.#charts.getBySymbolPeriod({ symbol: next.symbol, period: next.period });
452
543
  if (existKey) continue;
453
544
 
454
- const status = this.#addChartSymbolNow({ symbol: next.symbol, period: next.period, limit: next.limit });
545
+ const status = this.#addChartSymbolNow(next);
455
546
  if (status === 'not_connected') {
456
547
  this.#emit('error', { type: 'chart_send_failed', symbol: next.symbol, period: next.period, limit: next.limit, retryable: true });
457
548
  return;
@@ -820,7 +911,7 @@ module.exports = class Client {
820
911
  return 'delete';
821
912
  }
822
913
 
823
- #reuseDeletedChartSession({ key, symbol, period, limit }) {
914
+ #reuseDeletedChartSession({ key, symbol, period, limit, batchSize, onHistoryProgress, historySignal }) {
824
915
  const data = this.#charts.get({ key });
825
916
  if (!data) return 'unlisted';
826
917
  const resolved = this.#resolveSymbol({ chartSession: key, symbol });
@@ -831,17 +922,22 @@ module.exports = class Client {
831
922
  data.period = period;
832
923
  data.frame = this.#nextChartFrame();
833
924
  data.i = 's1';
834
- data.historyPending = true;
835
925
  data.requestedLimit = Number(limit);
836
926
  data.limit = Number(limit);
927
+ data.initialLimit = Math.min(limit, this.#chartInitialLimitMax);
928
+ data.batchSize = batchSize;
929
+ data.onHistoryProgress = onHistoryProgress;
930
+ data.historySignal = historySignal;
837
931
  data.historyBars = {};
838
- data.historyCompletionsPending = 1;
932
+ data.latestTimestamp = null;
839
933
  data.seriesGeneration = Number(data.seriesGeneration || 0) + 1;
840
934
  data.seriesCreated = true;
841
935
  data.end = null;
936
+ this.#beginHistoryBatch(data, data.initialLimit);
842
937
 
843
- const sent = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[period], limit}));
938
+ const sent = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[period], limit: data.initialLimit }));
844
939
  if (!sent) {
940
+ this.#closeHistoryBatch(data, 'send_failed');
845
941
  this.#charts.delete({ key });
846
942
  return 'not_connected';
847
943
  }
@@ -851,32 +947,15 @@ module.exports = class Client {
851
947
  return 'add';
852
948
  }
853
949
 
854
- #addChartSymbolNow({ symbol, period, limit = 1500 }) {
950
+ #addChartSymbolNow({ symbol, period, limit, batchSize, onHistoryProgress, historySignal }) {
855
951
  if (!symbol || typeof symbol !== 'string') console.debug('Invalid symbol parameter', symbol); // throw new Error('Invalid symbol parameter', symbol);
856
952
  if (!period || typeof period !== 'number') console.debug('Invalid period parameter', period); // throw new Error('Invalid period parameter', period);
857
953
  if (!limit || typeof limit !== 'number') console.debug('Invalid limit parameter', limit); // throw new Error('Invalid limit parameter', limit);
858
954
 
859
- let key = this.#charts.getBySymbolPeriod({ symbol, period });
860
- if (key) {
861
- const data = this.#charts.get({ key });
862
- if (data && Number(limit) > Number(data.limit || 0)) {
863
- const add = Number(limit) - Number(data.limit || 0);
864
- const sent = this.#send(tv.moreData({ chartSession: key, frame: data.frame, add }));
865
- if (!sent) return 'not_connected';
866
- data.historyPending = true;
867
- data.requestedLimit = Number(limit);
868
- data.limit = Number(limit);
869
- this.#charts.set({ key, data });
870
- console.debug('addChartSymbol extend:', key, symbol, period, { add, limit });
871
- return 'extend';
872
- }
873
- console.debug('addChartSymbol exist:', key, symbol, period);
874
- return 'exist';
875
- }
876
955
  const deleted = this.#charts.getDeleted();
877
- if (deleted !== null) return this.#reuseDeletedChartSession({ key: deleted.key, symbol, period, limit });
956
+ if (deleted !== null) return this.#reuseDeletedChartSession({ key: deleted.key, symbol, period, limit, batchSize, onHistoryProgress, historySignal });
878
957
 
879
- key = this.createChartSession();
958
+ const key = this.createChartSession();
880
959
  if (!key) return 'not_connected';
881
960
  const data = this.#charts.get({ key });
882
961
 
@@ -891,17 +970,21 @@ module.exports = class Client {
891
970
  data.period = period;
892
971
  data.frame = this.#nextChartFrame();
893
972
  data.i = 's1';
894
- data.historyPending = true;
895
973
  data.requestedLimit = Number(limit);
896
974
  data.limit = Number(limit);
975
+ data.initialLimit = Math.min(limit, this.#chartInitialLimitMax);
976
+ data.batchSize = batchSize;
977
+ data.onHistoryProgress = onHistoryProgress;
978
+ data.historySignal = historySignal;
897
979
  data.historyBars = {};
898
- data.historyCompletionsPending = 1;
899
980
  data.seriesGeneration = Number(data.seriesGeneration || 0) + 1;
900
981
  data.seriesCreated = true;
901
982
  data.end = null;
983
+ this.#beginHistoryBatch(data, data.initialLimit);
902
984
 
903
- const sent = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[period], limit}));
985
+ const sent = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[period], limit: data.initialLimit }));
904
986
  if (!sent) {
987
+ this.#closeHistoryBatch(data, 'send_failed');
905
988
  this.#charts.delete({ key });
906
989
  return 'not_connected';
907
990
  }
@@ -911,28 +994,31 @@ module.exports = class Client {
911
994
  return 'add';
912
995
  }
913
996
 
914
- addChartSymbol({ symbol, period, limit = 1500 }) {
915
- const validation = this.#validateChartRequest({ symbol, period, limit });
997
+ addChartSymbol({ symbol, period, limit = 1500, batchSize = 1500, onHistoryProgress, historySignal }) {
998
+ const validation = this.#validateChartRequest({ symbol, period, limit, maxLimit: Number.MAX_SAFE_INTEGER });
916
999
  if (!validation.ok) return { status: 'invalid', reason: validation.reason };
1000
+ if (!Number.isSafeInteger(batchSize) || batchSize <= 0 || batchSize > 40000) return { status: 'invalid', reason: 'invalid_batch_size' };
917
1001
  if (!this.#isOpen()) return { status: 'not_connected', symbol: validation.symbol, period: validation.period };
918
1002
 
919
1003
  const key = this.#charts.getBySymbolPeriod({ symbol: validation.symbol, period: validation.period });
920
1004
  if (key) {
921
1005
  const data = this.#charts.get({ key });
922
- if (data && validation.limit > Number(data.limit || 0)) {
923
- const add = validation.limit - Number(data.limit || 0);
924
- const sent = this.#send(tv.moreData({ chartSession: key, frame: data.frame, add }));
925
- if (!sent) return { status: 'not_connected' };
926
- data.historyPending = true;
927
- data.historyCompletionsPending = Number(data.historyCompletionsPending || 0) + 1;
1006
+ if (data && (validation.limit > data.limit || (data.historySignal?.aborted && data.historyBatch))) {
1007
+ const chart = this.#getChartHistory({ session: data });
1008
+ data.historySignal = historySignal;
1009
+ if (!data.historyBatch && !this.#requestMoreHistory({ session: data, chart, limit: validation.limit, batchSize })) {
1010
+ data.historySignal = null;
1011
+ return { status: 'not_connected', reason: 'history_send_failed' };
1012
+ }
928
1013
  data.requestedLimit = validation.limit;
929
1014
  data.limit = validation.limit;
930
- this.#charts.set({ key, data });
1015
+ data.batchSize = batchSize;
1016
+ data.onHistoryProgress = onHistoryProgress;
931
1017
  return { status: 'extend', symbol: validation.symbol, period: validation.period, limit: validation.limit };
932
1018
  }
933
1019
  return { status: 'exist', symbol: validation.symbol, period: validation.period, limit: Number(data?.limit || 0) };
934
1020
  }
935
- const status = this.#enqueueChart({ symbol: validation.symbol, period: validation.period, limit: validation.limit });
1021
+ const status = this.#enqueueChart({ symbol: validation.symbol, period: validation.period, limit: validation.limit, batchSize, onHistoryProgress, historySignal });
936
1022
  return { status, symbol: validation.symbol, period: validation.period, limit: validation.limit };
937
1023
  }
938
1024
 
@@ -952,6 +1038,7 @@ module.exports = class Client {
952
1038
  return { status: 'retry', reason: 'remove_series_not_sent' };
953
1039
  }
954
1040
  }
1041
+ this.#closeHistoryBatch(data, 'cancellation');
955
1042
 
956
1043
  const resolved = this.#resolveSymbol({ chartSession: key, symbol: validation.symbol });
957
1044
  if (!resolved) {
@@ -967,20 +1054,24 @@ module.exports = class Client {
967
1054
  data.i = 's1';
968
1055
  data.limit = validation.limit;
969
1056
  data.requestedLimit = validation.limit;
1057
+ data.initialLimit = validation.limit;
1058
+ data.batchSize = null;
1059
+ data.onHistoryProgress = null;
1060
+ data.historySignal = null;
970
1061
  data.historyBars = {};
971
- data.historyPending = true;
972
- data.historyCompletionsPending = 1;
1062
+ data.latestTimestamp = null;
973
1063
  data.seriesGeneration = Number(data.seriesGeneration || 0) + 1;
974
1064
  data.seriesCreated = true;
975
1065
  data.deleted = false;
976
1066
  data.end = null;
1067
+ this.#beginHistoryBatch(data, data.initialLimit);
977
1068
 
978
1069
  const created = this.#send(tv.createSeries({ chartSession: key, frame: data.frame, increment: data.i, symbolKey: data.symbolKey, period: periods[validation.period], limit: validation.limit }));
979
1070
  if (!created) {
1071
+ this.#closeHistoryBatch(data, 'send_failed');
980
1072
  data.deleted = true;
981
1073
  data.seriesCreated = false;
982
1074
  data.historyPending = false;
983
- data.historyCompletionsPending = 0;
984
1075
  data.historyBars = {};
985
1076
  this.#charts.set({ key, data });
986
1077
  this.#stopQueueTimer();
@@ -1007,6 +1098,7 @@ module.exports = class Client {
1007
1098
  if (!remoteRemoved) return { status: 'retry', reason: 'remove_series_not_sent' };
1008
1099
  }
1009
1100
 
1101
+ this.#closeHistoryBatch(data, 'cancellation');
1010
1102
  this.#charts.delete({ key });
1011
1103
  this.#stopQueueTimer();
1012
1104
  this.#scheduleQueue(0);
@@ -1122,6 +1214,7 @@ module.exports = class Client {
1122
1214
  const period = parseInt(session.period);
1123
1215
  const message = detail.slice(2).map((value) => typeof value === 'string' ? value : JSON.stringify(value)).join(' ') || 'TradingView series error';
1124
1216
 
1217
+ this.#closeHistoryBatch(session, 'upstream_error');
1125
1218
  this.#charts.break({ key: chartSessionKey });
1126
1219
  this.#logQueueState('series_error_session_quarantined', { session: chartSessionKey, frame: errorFrame, symbol, period });
1127
1220
  this.#stopQueueTimer();
@@ -1137,14 +1230,49 @@ module.exports = class Client {
1137
1230
  const completedFrame = detail[1];
1138
1231
  const session = chartSessionKey ? this.#charts.get({ key: chartSessionKey }) : null;
1139
1232
 
1140
- if (!session || session.deleted || session.historyPending !== true) return;
1233
+ const batch = session?.historyBatch;
1234
+ if (!batch || session.deleted) return;
1141
1235
  if (completedFrame && completedFrame !== session.frame) return;
1142
1236
 
1143
- session.historyCompletionsPending = Math.max(0, Number(session.historyCompletionsPending || 1) - 1);
1144
- if (session.historyCompletionsPending > 0) return;
1145
-
1237
+ const frame = session.frame;
1146
1238
  const chart = this.#getChartHistory({ session });
1239
+ const abandoned = !session.historyPending;
1240
+ session.historyBatch = null;
1241
+ batch.cleanup?.();
1242
+ if (abandoned && (!session.onHistoryProgress || session.historySignal?.aborted)) {
1243
+ session.onHistoryProgress = null;
1244
+ session.historySignal = null;
1245
+ session.requestedLimit = session.limit = chart.length;
1246
+ return;
1247
+ }
1248
+
1249
+ // Only an earlier unique bar proves that a backfill moved further back.
1250
+ const progressed = chart.length > 0 && ((batch.before === null && session.batchSize !== null) || batch.earlier || abandoned);
1251
+ let limit = session.limit;
1252
+ if (progressed && chart.length < limit && typeof session.onHistoryProgress === 'function') {
1253
+ limit = Math.min(limit, session.onHistoryProgress(chart));
1254
+ }
1255
+ if (session.deleted || this.#charts.get({ key: chartSessionKey }) !== session || session.frame !== frame) {
1256
+ if (!abandoned) this.#logHistoryBatch(session, batch, chart, 'cancellation');
1257
+ return;
1258
+ }
1259
+ const aborted = session.historySignal?.aborted;
1260
+ const stopReason = aborted ? session.historySignal.reason
1261
+ : chart.length >= limit ? 'target_reached' : progressed ? null : 'no_progress';
1262
+ if (!abandoned) this.#logHistoryBatch(session, batch, chart, stopReason);
1263
+ if (limit < session.limit) session.requestedLimit = session.limit = Math.max(chart.length, limit);
1264
+ if (!stopReason) {
1265
+ if (this.#requestMoreHistory({ session, chart, limit, batchSize: session.batchSize })) return;
1266
+ if (!session.deleted && this.#charts.get({ key: chartSessionKey }) === session && session.frame === frame) this.#failHistorySend(session, chart);
1267
+ return;
1268
+ }
1269
+
1147
1270
  session.historyPending = false;
1271
+ session.onHistoryProgress = null;
1272
+ session.historySignal = null;
1273
+ if (aborted) {
1274
+ session.requestedLimit = session.limit = chart.length;
1275
+ }
1148
1276
  session.historyBars = Object.fromEntries(chart.map((bar) => [String(bar.timestamp), bar]));
1149
1277
  console.debug('tv chart history completed:', { symbol: session.symbol, period: session.period, count: chart.length, session: chartSessionKey, frame: session.frame, generation: session.seriesGeneration });
1150
1278
  this.#emit('chart_history', { symbol: session.symbol, period: parseInt(session.period), chart, end: session.end ?? null });
@@ -1161,16 +1289,29 @@ module.exports = class Client {
1161
1289
  const chart = this.#parseChartBars({ frame });
1162
1290
  if (chart.length === 0) return;
1163
1291
 
1164
- session.end = frame?.lbs?.bar_close_time ?? session.end ?? null;
1165
-
1166
- this.#mergeChartBars({ session, chart });
1167
-
1168
- console.debug('tv chart received:', { symbol: session.symbol, period: session.period, count: chart.length, historyPending: session.historyPending });
1169
-
1170
- if (session.historyPending === true) return;
1292
+ const newest = chart.reduce((latest, bar) => (bar.timestamp >= latest.timestamp ? bar : latest));
1293
+ const live = session.latestTimestamp !== null && newest.timestamp >= session.latestTimestamp;
1294
+ session.latestTimestamp = Math.max(newest.timestamp, session.latestTimestamp ?? -Infinity);
1295
+ const batch = session.historyBatch;
1296
+ const abandoned = batch && !session.historyPending;
1297
+ if (!batch || batch.before === null || live) session.end = frame?.lbs?.bar_close_time ?? session.end ?? null;
1298
+ if (!abandoned) this.#mergeChartBars({ session, chart });
1299
+
1300
+ if (batch) {
1301
+ if (batch.before !== null && packet.type === 'du' && live) {
1302
+ if (abandoned) {
1303
+ this.#mergeChartBars({ session, chart: [newest] });
1304
+ const stored = this.#getChartHistory({ session });
1305
+ session.historyBars = Object.fromEntries(stored.map((bar) => [String(bar.timestamp), bar]));
1306
+ }
1307
+ this.#emit('chart_update', { symbol: session.symbol, period: parseInt(session.period), chart: [newest], end: session.end });
1308
+ }
1309
+ return;
1310
+ }
1171
1311
 
1172
1312
  const stored = this.#getChartHistory({ session });
1173
1313
  session.historyBars = Object.fromEntries(stored.map((bar) => [String(bar.timestamp), bar]));
1314
+ if (chart[0] !== newest) chart.sort((left, right) => right.timestamp - left.timestamp);
1174
1315
  this.#emit('chart_update', { symbol: session.symbol, period: parseInt(session.period), chart, end: session.end });
1175
1316
  }
1176
1317
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "market-data-tradingview-ws",
3
- "version": "2.1.4",
3
+ "version": "2.1.5",
4
4
  "description": "marketData from Tradingview ws",
5
5
  "main": "index.js",
6
6
  "scripts": {