Intelligence, Advanced Charting & Trading Platform
feat: implement provider normalization and health contracts
davoodmehraban89 committed
Oct 5, 2026 at 16:17 UTC
a92ab2a2c413142d301fc1cc707c0ea7d61b4548
1 file changed
+77
packages/market-domain/src/provider-contract.mjs
new
+77
@@ -0,0 +1,77 @@
1
+function positiveFinite(value, name) {
2
+ if (!Number.isFinite(value) || value <= 0) {
3
+ throw new RangeError(`${name} must be positive and finite`);
4
+ }
5
+}
6
+
7
+function validDate(value, name) {
8
+ if (!(value instanceof Date) || Number.isNaN(value.valueOf())) {
9
+ throw new TypeError(`${name} must be a valid Date`);
10
+ }
11
+}
12
+
13
+export function normalizeIranianQuote({ value, unit }) {
14
+ positiveFinite(value, 'value');
15
+ if (unit === 'IRT_PER_USD' || unit === 'IRT_PER_GRAM') return value;
16
+ if (unit === 'IRR_PER_USD' || unit === 'IRR_PER_GRAM') return value / 10;
17
+ throw new RangeError(`unsupported unit: ${unit}`);
18
+}
19
+
20
+export function canonicalObservation({
21
+ providerCode,
22
+ canonicalSymbol,
23
+ providerTimestamp,
24
+ receivedAt,
25
+ price,
26
+ rawUnit,
27
+}) {
28
+ if (!providerCode || !canonicalSymbol) throw new TypeError('providerCode and canonicalSymbol are required');
29
+ validDate(providerTimestamp, 'providerTimestamp');
30
+ validDate(receivedAt, 'receivedAt');
31
+ if (receivedAt.valueOf() < providerTimestamp.valueOf()) {
32
+ throw new RangeError('receivedAt cannot be before providerTimestamp');
33
+ }
34
+
35
+ const canonicalUnits = {
36
+ USD_IRT_FREE: 'IRT_PER_USD',
37
+ GOLD18_IRT: 'IRT_PER_GRAM',
38
+ XAU_USD: 'USD_PER_TROY_OUNCE',
39
+ };
40
+ const canonicalUnit = canonicalUnits[canonicalSymbol];
41
+ if (!canonicalUnit) throw new RangeError(`unsupported canonical symbol: ${canonicalSymbol}`);
42
+
43
+ let normalizedPrice = price;
44
+ if (canonicalSymbol === 'USD_IRT_FREE' || canonicalSymbol === 'GOLD18_IRT') {
45
+ normalizedPrice = normalizeIranianQuote({ value: price, unit: rawUnit });
46
+ } else {
47
+ positiveFinite(price, 'price');
48
+ if (rawUnit !== canonicalUnit) throw new RangeError(`unsupported unit: ${rawUnit}`);
49
+ }
50
+
51
+ return {
52
+ providerCode,
53
+ canonicalSymbol,
54
+ providerTimestamp: providerTimestamp.toISOString(),
55
+ receivedAt: receivedAt.toISOString(),
56
+ price: normalizedPrice,
57
+ canonicalUnit,
58
+ rawUnit,
59
+ };
60
+}
61
+
62
+export function providerHealth({ now, lastSuccessAt, staleAfterMs }) {
63
+ validDate(now, 'now');
64
+ validDate(lastSuccessAt, 'lastSuccessAt');
65
+ if (!Number.isFinite(staleAfterMs) || staleAfterMs < 0) {
66
+ throw new RangeError('staleAfterMs must be non-negative and finite');
67
+ }
68
+ if (lastSuccessAt.valueOf() > now.valueOf()) {
69
+ throw new RangeError('lastSuccessAt cannot be in the future');
70
+ }
71
+
72
+ const ageMs = now.valueOf() - lastSuccessAt.valueOf();
73
+ return {
74
+ status: ageMs <= staleAfterMs ? 'GOOD' : 'STALE',
75
+ ageMs,
76
+ };
77
+}