Intelligence, Advanced Charting & Trading Platform

1 function finiteNonNegative(value, name) {
2 if (!Number.isFinite(value) || value < 0) {
3 throw new RangeError(`${name} must be non-negative and finite`);
4 }
5 }
6
7 export function evaluateObservationQuality({
8 price,
9 ageMs,
10 maxAgeMs,
11 referencePrice = null,
12 maxDivergencePct = null,
13 previousPrice = null,
14 maxMovePct = null,
15 }) {
16 finiteNonNegative(ageMs, 'ageMs');
17 finiteNonNegative(maxAgeMs, 'maxAgeMs');
18
19 const flags = [];
20
21 if (!Number.isFinite(price) || price <= 0) {
22 return { state: 'INVALID', flags: ['NON_POSITIVE_PRICE'], divergencePct: null, movePct: null };
23 }
24
25 if (ageMs > maxAgeMs) {
26 flags.push('STALE_SOURCE');
27 }
28
29 let divergencePct = null;
30 if (referencePrice !== null) {
31 if (!Number.isFinite(referencePrice) || referencePrice <= 0) {
32 throw new RangeError('referencePrice must be positive and finite when provided');
33 }
34 finiteNonNegative(maxDivergencePct, 'maxDivergencePct');
35 divergencePct = Math.abs(price / referencePrice - 1) * 100;
36 if (divergencePct > maxDivergencePct) flags.push('PROVIDER_DIVERGENCE');
37 }
38
39 let movePct = null;
40 if (previousPrice !== null) {
41 if (!Number.isFinite(previousPrice) || previousPrice <= 0) {
42 throw new RangeError('previousPrice must be positive and finite when provided');
43 }
44 finiteNonNegative(maxMovePct, 'maxMovePct');
45 movePct = Math.abs(price / previousPrice - 1) * 100;
46 const epsilon = Math.max(1e-12, Math.abs(maxMovePct) * Number.EPSILON * 8);
47 if (movePct - maxMovePct > epsilon) flags.push('PRICE_SPIKE');
48 }
49
50 if (flags.includes('STALE_SOURCE')) return { state: 'STALE', flags, divergencePct, movePct };
51 if (flags.length > 0) return { state: 'DEGRADED', flags, divergencePct, movePct };
52 return { state: 'GOOD', flags, divergencePct, movePct };
53 }