Intelligence, Advanced Charting & Trading Platform

1 function parseObservation(observation, index) {
2 if (!observation || typeof observation !== 'object' || Array.isArray(observation)) {
3 throw new TypeError(`observation[${index}] must be an object`);
4 }
5
6 const timestampMs = new Date(observation.timestamp).valueOf();
7 if (!Number.isFinite(timestampMs)) {
8 throw new TypeError(`observation[${index}].timestamp must be valid`);
9 }
10
11 if (!Number.isFinite(observation.price) || observation.price <= 0) {
12 throw new RangeError(`observation[${index}].price must be positive and finite`);
13 }
14
15 return { timestampMs, price: observation.price };
16 }
17
18 function median(values) {
19 if (values.length === 0) return null;
20 const sorted = [...values].sort((a, b) => a - b);
21 const middle = Math.floor(sorted.length / 2);
22 if (sorted.length % 2 === 1) return sorted[middle];
23 return (sorted[middle - 1] + sorted[middle]) / 2;
24 }
25
26 export function analyzeObservationSeries(observations) {
27 if (!Array.isArray(observations)) throw new TypeError('observations must be an array');
28
29 const parsed = observations.map(parseObservation);
30 let outOfOrderCount = 0;
31 for (let i = 1; i < parsed.length; i += 1) {
32 if (parsed[i].timestampMs < parsed[i - 1].timestampMs) outOfOrderCount += 1;
33 }
34
35 const timestampCounts = new Map();
36 for (const item of parsed) {
37 timestampCounts.set(item.timestampMs, (timestampCounts.get(item.timestampMs) ?? 0) + 1);
38 }
39
40 const uniqueTimestamps = [...timestampCounts.keys()].sort((a, b) => a - b);
41 const gaps = [];
42 for (let i = 1; i < uniqueTimestamps.length; i += 1) {
43 gaps.push(uniqueTimestamps[i] - uniqueTimestamps[i - 1]);
44 }
45
46 const duplicateTimestampCount = [...timestampCounts.values()]
47 .reduce((total, count) => total + Math.max(0, count - 1), 0);
48
49 return {
50 count: parsed.length,
51 uniqueTimestampCount: uniqueTimestamps.length,
52 duplicateTimestampCount,
53 outOfOrderCount,
54 maxGapMs: gaps.length ? Math.max(...gaps) : null,
55 medianCadenceMs: median(gaps),
56 firstTimestamp: uniqueTimestamps.length ? new Date(uniqueTimestamps[0]).toISOString() : null,
57 lastTimestamp: uniqueTimestamps.length ? new Date(uniqueTimestamps.at(-1)).toISOString() : null,
58 };
59 }