Repository navigation
Expand file tree
/
Copy pathvwap.ts
More file actions
600 lines (563 loc) · 22.1 KB
/
Copy pathvwap.ts
File metadata and controls
600 lines (563 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
import { pgPool } from '../db'
import { config, type NetworkName } from '../config'
import type { DecimalFormat } from '../utils/decimals'
import { getOnChainSources } from '../ingest/venues'
import { getFailedSources } from '../ingest/sourceFailures'
export const STALENESS_THRESHOLD_SECONDS = 300
export const HIGH_CONFIDENCE_MAX_AGE_SECONDS = 30
export const MEDIUM_CONFIDENCE_MAX_AGE_SECONDS = 300
export interface VwapDetailedResult {
num: number
raw: string
stale?: boolean
status?: 'ok' | 'stale' | 'unknown'
}
/**
* Every query in this module filters on `network`.
*
* `price_points` and `pool_snapshots` both carry a `network` column and index
* it as the leading column of `(network, pair_key, timestamp)`, and the same
* pair key exists on both chains. An unfiltered read therefore does not return
* "the" price for a pair — it returns a volume-weighted blend of two separate
* markets, which is a number no one traded at on either chain.
*
* That is why `network` is a required argument rather than an optional
* refinement: there is no default that is correct by accident, and a caller
* that doesn't know which chain it is quoting should refuse rather than guess.
*
* Sources filtering and health semantics (#652):
* - VWAP strictly reads on-chain execution venues via `getOnChainSources()`.
* Centralized exchange (CEX) rows are excluded and cannot move on-chain price.
* - Venues currently recorded as failed for this (network, pairKey) via
* `getFailedSources()` are excluded from the volume-weighted aggregate.
* - When every on-chain venue has failed or is excluded, the price does not
* silently fall to zero: it returns the last known good on-chain price marked
* stale (`stale: true, status: 'stale'`). If no price point exists, returns 0
* with `status: 'unknown'`.
*/
export async function calculateVWAPDetailed(
pairKey: string,
windowMinutes: number,
network: NetworkName,
source?: 'SDEX' | 'AMM' | string
): Promise<VwapDetailedResult> {
const onChainSources = getOnChainSources()
const failedSources = getFailedSources(network, pairKey)
const failedSet = new Set(failedSources)
let allowedSources: string[]
let sourceClause: string
const params: (string | number | string[])[] = [pairKey, network, windowMinutes]
if (source) {
if (!onChainSources.includes(source) || failedSet.has(source)) {
allowedSources = []
} else {
allowedSources = [source]
sourceClause = 'AND source = $4'
params.push(source)
}
} else {
allowedSources = onChainSources.filter(s => !failedSet.has(s))
sourceClause = 'AND source = ANY($4)'
params.push(allowedSources)
}
// When every on-chain venue has failed, do not silently become zero (#652).
// Return the last good value marked stale within bounded window, or unknown if no recent history exists.
if (allowedSources.length === 0) {
const candidateSources = source && onChainSources.includes(source) ? [source] : onChainSources
const fallbackWindowMinutes = Math.max(windowMinutes, 1440)
const lastResult = await pgPool.query(
`SELECT price::numeric AS last_price
FROM price_points
WHERE pair_key = $1
AND network = $2
AND source = ANY($3)
AND COALESCE(observed_at, timestamp) > NOW() - ($4 || ' minutes')::interval
ORDER BY COALESCE(observed_at, timestamp) DESC
LIMIT 1`,
[pairKey, network, candidateSources, fallbackWindowMinutes]
)
if (lastResult.rows.length > 0 && lastResult.rows[0]?.last_price != null) {
const raw = String(lastResult.rows[0].last_price)
return {
num: parseFloat(raw),
raw,
stale: true,
status: 'stale',
}
}
return {
num: 0,
raw: '0',
stale: true,
status: 'unknown',
}
}
const result = await pgPool.query(
`SELECT
COALESCE(
SUM(price::numeric * base_volume::numeric) / NULLIF(SUM(base_volume::numeric), 0),
0
) AS vwap
FROM price_points
WHERE pair_key = $1
AND network = $2
AND COALESCE(observed_at, timestamp) > NOW() - ($3 || ' minutes')::interval
${sourceClause!}`,
params
)
const raw = String(result.rows[0]?.vwap ?? '0')
const num = parseFloat(raw)
return {
num,
raw,
stale: false,
status: num > 0 ? 'ok' : 'unknown',
}
}
export async function calculateVWAP(
pairKey: string,
windowMinutes: number,
network: NetworkName,
source?: 'SDEX' | 'AMM' | string
): Promise<number> {
const detailed = await calculateVWAPDetailed(pairKey, windowMinutes, network, source)
if (detailed.stale) return 0
return detailed.num
}
export async function calculateOHLCV(
pairKey: string,
windowMinutes: number,
network: NetworkName
): Promise<{
open: number; high: number; low: number; close: number
volume: number; tradeCount: number
}> {
const onChainSources = getOnChainSources()
const failedSources = new Set(getFailedSources(network, pairKey))
const allowedSources = onChainSources.filter(s => !failedSources.has(s))
if (allowedSources.length === 0) {
return {
open: 0,
high: 0,
low: 0,
close: 0,
volume: 0,
tradeCount: 0,
}
}
const result = await pgPool.query(
`SELECT
(SELECT price::numeric FROM price_points
WHERE pair_key = $1 AND network = $2
AND COALESCE(observed_at, timestamp) > NOW() - ($3 || ' minutes')::interval
AND source = ANY($4)
ORDER BY COALESCE(observed_at, timestamp) ASC LIMIT 1) AS open,
MAX(price::numeric) AS high,
MIN(price::numeric) AS low,
(SELECT price::numeric FROM price_points
WHERE pair_key = $1 AND network = $2
AND COALESCE(observed_at, timestamp) > NOW() - ($3 || ' minutes')::interval
AND source = ANY($4)
ORDER BY COALESCE(observed_at, timestamp) DESC LIMIT 1) AS close,
SUM(base_volume::numeric) AS volume,
COUNT(*) AS trade_count
FROM price_points
WHERE pair_key = $1
AND network = $2
AND COALESCE(observed_at, timestamp) > NOW() - ($3 || ' minutes')::interval
AND source = ANY($4)`,
[pairKey, network, windowMinutes, allowedSources]
)
const row = result.rows[0]
return {
open: parseFloat(row?.open ?? '0'),
high: parseFloat(row?.high ?? '0'),
low: parseFloat(row?.low ?? '0'),
close: parseFloat(row?.close ?? '0'),
volume: parseFloat(row?.volume ?? '0'),
tradeCount: parseInt(row?.trade_count ?? '0', 10),
}
}
/**
* Sum two decimal strings preserving exact precision without IEEE-754 loss.
*/
export function addDecimalStrings(a: string, b: string): string {
const cleanA = (a ?? '').trim() || '0'
const cleanB = (b ?? '').trim() || '0'
const [aInt = '0', aFrac = ''] = cleanA.split('.')
const [bInt = '0', bFrac = ''] = cleanB.split('.')
const maxFracLen = Math.max(aFrac.length, bFrac.length)
const aPadded = aFrac.padEnd(maxFracLen, '0')
const bPadded = bFrac.padEnd(maxFracLen, '0')
const aBig = BigInt((aInt.startsWith('-') ? '-' : '') + aInt.replace('-', '') + aPadded)
const bBig = BigInt((bInt.startsWith('-') ? '-' : '') + bInt.replace('-', '') + bPadded)
const sum = aBig + bBig
const isNeg = sum < 0n
const sumAbs = isNeg ? -sum : sum
const sumStr = sumAbs.toString().padStart(maxFracLen + 1, '0')
const intPart = sumStr.slice(0, sumStr.length - maxFracLen) || '0'
const fracPart = sumStr.slice(sumStr.length - maxFracLen).replace(/0+$/, '')
const result = (isNeg ? '-' : '') + (fracPart ? `${intPart}.${fracPart}` : intPart)
return result === '' || result === '-0' ? '0' : result
}
export const PRICE_CHANGE_24H_WINDOW_HOURS = 24
/**
* How far before `now - 24h` the reference price may be: the reference is the
* newest price observed in [now - 24h - this, now - 24h), so it is between 24
* and 26 hours old. With no price in that range the change is null, never a
* comparison with an older price.
*/
export const PRICE_CHANGE_REFERENCE_LOOKBACK_HOURS = 2
/** Short endpoint averaging window (minutes) around each end to damp thin-venue price noise. */
export const PRICE_CHANGE_ENDPOINT_VWAP_MINUTES = 5
/**
* Computes exact percentage change between two decimal strings: ((now - ago) / ago) * 100.
* Returns `{ num: null, raw: null }` when no usable reference price (`agoRaw` or `nowRaw`) exists.
*/
export function computePriceChange(
nowRaw: string | undefined | null,
agoRaw: string | undefined | null,
computedRaw?: string | null
): { num: number | null; raw: string | null } {
const agoStr = agoRaw != null ? String(agoRaw).trim() : ''
const nowStr = nowRaw != null ? String(nowRaw).trim() : ''
const agoNum = parseFloat(agoStr)
const nowNum = parseFloat(nowStr)
if (!agoStr || !nowStr || !Number.isFinite(agoNum) || agoNum === 0 || !Number.isFinite(nowNum)) {
return { num: null, raw: null }
}
if (computedRaw != null) {
const raw = String(computedRaw)
const parsed = parseFloat(raw)
return { num: Number.isFinite(parsed) ? parsed : null, raw }
}
try {
const [aInt = '0', aFrac = ''] = agoStr.split('.')
const [nInt = '0', nFrac = ''] = nowStr.split('.')
const scale = Math.max(aFrac.length, nFrac.length)
const aBig = BigInt((aInt.startsWith('-') ? '-' : '') + aInt.replace('-', '') + aFrac.padEnd(scale, '0'))
const nBig = BigInt((nInt.startsWith('-') ? '-' : '') + nInt.replace('-', '') + nFrac.padEnd(scale, '0'))
if (aBig === 0n) return { num: null, raw: null }
const diff = nBig - aBig
const PRECISION = 18n
const mult = 10n ** PRECISION
const scaledQuotient = (diff * 100n * mult) / aBig
const isNeg = scaledQuotient < 0n
const absQ = isNeg ? -scaledQuotient : scaledQuotient
const qStr = absQ.toString().padStart(Number(PRECISION) + 1, '0')
const intPart = qStr.slice(0, qStr.length - Number(PRECISION)) || '0'
const fracPart = qStr.slice(qStr.length - Number(PRECISION)).replace(/0+$/, '')
const raw = (isNeg ? '-' : '') + (fracPart ? `${intPart}.${fracPart}` : intPart)
return { num: parseFloat(raw) || 0, raw: raw === '' || raw === '-0' ? '0' : raw }
} catch {
const num = ((nowNum - agoNum) / agoNum) * 100
return { num, raw: String(num) }
}
}
export async function getPriceChange24hDetailed(
pairKey: string,
network: NetworkName
): Promise<{ num: number | null; raw: string | null }> {
// Uses half-open bounds (#236): current window [now - 24h, now), reference lookback
// [now - 24h - lookback, now - 24h). Endpoint prices use a short VWAP around each anchor
// (falling back to mean price when volume is 0) to damp cross-venue spread noise.
const result = await pgPool.query(
`WITH bounds AS (
SELECT NOW() - INTERVAL '24 hours' AS window_start,
NOW() AS window_end
),
ref_anchor AS (
SELECT COALESCE(observed_at, timestamp) AS ts
FROM price_points, bounds b
WHERE pair_key = $1
AND network = $2
AND COALESCE(observed_at, timestamp) >= b.window_start - ($3 || ' hours')::interval
AND COALESCE(observed_at, timestamp) < b.window_start
ORDER BY COALESCE(observed_at, timestamp) DESC
LIMIT 1
),
now_anchor AS (
SELECT COALESCE(observed_at, timestamp) AS ts
FROM price_points, bounds b
WHERE pair_key = $1
AND network = $2
AND COALESCE(observed_at, timestamp) >= b.window_start
AND COALESCE(observed_at, timestamp) < b.window_end
ORDER BY COALESCE(observed_at, timestamp) DESC
LIMIT 1
),
ref_agg AS (
SELECT
CASE
WHEN COALESCE(SUM(CASE WHEN p.base_volume::numeric > 0 THEN p.base_volume::numeric ELSE 0 END), 0) > 0
THEN SUM(p.price::numeric * p.base_volume::numeric) / SUM(p.base_volume::numeric)
ELSE AVG(p.price::numeric)
END AS price_24h_ago
FROM price_points p, bounds b, ref_anchor a
WHERE p.pair_key = $1
AND p.network = $2
AND COALESCE(p.observed_at, p.timestamp) >= GREATEST(b.window_start - ($3 || ' hours')::interval, a.ts - ($4 || ' minutes')::interval)
AND COALESCE(p.observed_at, p.timestamp) <= a.ts
AND COALESCE(p.observed_at, p.timestamp) < b.window_start
),
now_agg AS (
SELECT
CASE
WHEN COALESCE(SUM(CASE WHEN p.base_volume::numeric > 0 THEN p.base_volume::numeric ELSE 0 END), 0) > 0
THEN SUM(p.price::numeric * p.base_volume::numeric) / SUM(p.base_volume::numeric)
ELSE AVG(p.price::numeric)
END AS price_now
FROM price_points p, bounds b, now_anchor a
WHERE p.pair_key = $1
AND p.network = $2
AND COALESCE(p.observed_at, p.timestamp) >= GREATEST(b.window_start, a.ts - ($4 || ' minutes')::interval)
AND COALESCE(p.observed_at, p.timestamp) <= a.ts
AND COALESCE(p.observed_at, p.timestamp) < b.window_end
)
SELECT
ref_agg.price_24h_ago,
now_agg.price_now,
CASE
WHEN ref_agg.price_24h_ago IS NULL OR ref_agg.price_24h_ago = 0 OR now_agg.price_now IS NULL THEN NULL
ELSE ((now_agg.price_now - ref_agg.price_24h_ago) / ref_agg.price_24h_ago * 100)
END AS price_change_24h
FROM ref_agg, now_agg`,
[pairKey, network, PRICE_CHANGE_REFERENCE_LOOKBACK_HOURS, PRICE_CHANGE_ENDPOINT_VWAP_MINUTES]
)
const row = result.rows[0]
return computePriceChange(row?.price_now, row?.price_24h_ago, row?.price_change_24h)
}
export async function getPriceChange24h(pairKey: string, network: NetworkName): Promise<number | null> {
const detailed = await getPriceChange24hDetailed(pairKey, network)
return detailed.num
}
export interface AggregatedPriceNumeric {
price: number
sdexPrice: number
ammPrice: number
volume24h: number
sdexVolume24h: number
ammVolume24h: number
vwap1m: number
vwap5m: number
vwap1h: number
vwap24h: number
priceChange24h: number | null
sources: number
confidence: 'high' | 'medium' | 'low' | 'unknown'
lastTradeAgeSeconds: number | null
newestInputObservedAt: string | null
inputCount: number
stalenessThresholdSeconds: number
stale: boolean
}
export interface AggregatedPriceString {
price: string
sdexPrice: string
ammPrice: string
volume24h: string
sdexVolume24h: string
ammVolume24h: string
vwap1m: string
vwap5m: string
vwap1h: string
vwap24h: string
priceChange24h: string | null
sources: number
confidence: 'high' | 'medium' | 'low' | 'unknown'
lastTradeAgeSeconds: number | null
newestInputObservedAt: string | null
inputCount: number
stalenessThresholdSeconds: number
stale: boolean
}
export async function getAggregatedPrice(
pairKey: string,
network: NetworkName,
options: { decimalFormat: 'string'; staleThresholdSeconds?: number }
): Promise<AggregatedPriceString>
export async function getAggregatedPrice(
pairKey: string,
network: NetworkName,
options?: { decimalFormat?: 'number'; staleThresholdSeconds?: number }
): Promise<AggregatedPriceNumeric>
export async function getAggregatedPrice(
pairKey: string,
network: NetworkName,
options?: { decimalFormat?: DecimalFormat; staleThresholdSeconds?: number }
): Promise<AggregatedPriceNumeric | AggregatedPriceString>
export async function getAggregatedPrice(
pairKey: string,
network: NetworkName,
options?: { decimalFormat?: DecimalFormat; staleThresholdSeconds?: number }
): Promise<AggregatedPriceNumeric | AggregatedPriceString> {
const onChainSources = getOnChainSources()
const failedSources = getFailedSources(network, pairKey)
const failedSet = new Set(failedSources)
const healthyOnChainSources = onChainSources.filter(s => !failedSet.has(s))
const [vwap1m, vwap5m, vwap1h, vwap24h, sdexVwap24h, priceChange24h, ammSpotResult, lastTradeResult] = await Promise.all([
calculateVWAPDetailed(pairKey, 1, network),
calculateVWAPDetailed(pairKey, 5, network),
calculateVWAPDetailed(pairKey, 60, network),
calculateVWAPDetailed(pairKey, 1440, network),
calculateVWAPDetailed(pairKey, 1440, network, 'SDEX'),
getPriceChange24hDetailed(pairKey, network),
// AMM price: latest spot_price averaged across pools for this pair, on this
// network only. Both halves of the lookup are network-filtered: the outer
// scan of pool_snapshots, and the price_points subquery that decides which
// pool ids count as this pair. Filtering only the outer scan would still let
// a same-named pool on the other chain contribute its price.
failedSet.has('AMM')
? Promise.resolve({ rows: [] })
: pgPool.query(
`SELECT AVG(spot_price::numeric) AS amm_price
FROM (
SELECT DISTINCT ON (ps.pool_id) ps.spot_price
FROM pool_snapshots ps
WHERE ps.network = $2
AND ps.pool_id IN (
SELECT DISTINCT pool_id FROM price_points
WHERE pair_key = $1 AND network = $2 AND source = 'AMM' AND pool_id IS NOT NULL
)
ORDER BY ps.pool_id, ps.timestamp DESC
) latest`,
[pairKey, network]
),
// Last trade timestamp and input count from healthy on-chain execution venues
healthyOnChainSources.length === 0
? Promise.resolve({ rows: [{ last_trade: null, input_count: '0' }] })
: pgPool.query(
`SELECT MAX(timestamp) as last_trade, COUNT(*) as input_count FROM price_points
WHERE pair_key = $1 AND network = $2 AND source = ANY($3)`,
[pairKey, network, healthyOnChainSources]
),
])
const volResult = healthyOnChainSources.length === 0
? { rows: [] }
: await pgPool.query(
`WITH per_source AS (
SELECT
source,
SUM(base_volume::numeric) AS vol
FROM price_points
WHERE pair_key = $1
AND network = $2
AND source = ANY($3)
AND COALESCE(observed_at, timestamp) > NOW() - INTERVAL '24 hours'
GROUP BY source
)
SELECT source, vol FROM per_source
UNION ALL
SELECT 'TOTAL' AS source, COALESCE(SUM(vol)::numeric, 0) AS vol FROM per_source`,
[pairKey, network, healthyOnChainSources]
)
let sdexVolume24hRaw = '0'
let ammVolume24hRaw = '0'
let totalVolume24hRaw: string | null = null
let sdexVolume24h = 0
let ammVolume24h = 0
for (const row of volResult.rows) {
if (row.source === 'SDEX') {
sdexVolume24hRaw = String(row.vol ?? '0')
sdexVolume24h = parseFloat(sdexVolume24hRaw)
} else if (row.source === 'AMM') {
ammVolume24hRaw = String(row.vol ?? '0')
ammVolume24h = parseFloat(ammVolume24hRaw)
} else if (row.source === 'TOTAL' || row.source === null) {
totalVolume24hRaw = String(row.vol ?? '0')
}
}
if (totalVolume24hRaw === null) {
totalVolume24hRaw = addDecimalStrings(sdexVolume24hRaw, ammVolume24hRaw)
}
const volume24h = parseFloat(totalVolume24hRaw)
const sourcesResult = healthyOnChainSources.length === 0
? { rows: [{ sources: '0' }] }
: await pgPool.query(
`SELECT COUNT(DISTINCT COALESCE(pool_id, 'sdex')) AS sources
FROM price_points
WHERE pair_key = $1
AND network = $2
AND source = ANY($3)
AND COALESCE(observed_at, timestamp) > NOW() - INTERVAL '1 hour'`,
[pairKey, network, healthyOnChainSources]
)
const ammPriceRaw = String(ammSpotResult.rows[0]?.amm_price ?? '0')
const ammPrice = parseFloat(ammPriceRaw)
const lastTrade = lastTradeResult.rows[0]?.last_trade
const lastTradeAgeSeconds = lastTrade ? Math.floor((Date.now() - new Date(lastTrade).getTime()) / 1000) : null
const sources = parseInt(sourcesResult.rows[0]?.sources ?? '0', 10)
const rawInputCount = lastTradeResult.rows[0]?.input_count
const inputCount = rawInputCount !== undefined
? parseInt(rawInputCount, 10)
: (lastTrade ? Math.max(1, sources) : 0)
const newestInputObservedAt = lastTrade ? new Date(lastTrade).toISOString() : null
const staleThreshold = options?.staleThresholdSeconds
?? (config as any).pricing?.staleThresholdSeconds
?? parseInt(process.env.PRICE_STALE_THRESHOLD_SECONDS ?? process.env.STALENESS_BOUND_SECONDS ?? '300', 10)
const isString = options?.decimalFormat === 'string'
const guardStr = (r: VwapDetailedResult) => (r.num > 0 && !r.stale ? r.raw : '0')
const guardNum = (r: VwapDetailedResult) => (r.num > 0 && !r.stale ? r.num : 0)
const stringPrice = (vwap1h.num > 0 && !vwap1h.stale ? vwap1h.raw : null)
?? (vwap24h.num > 0 && !vwap24h.stale ? vwap24h.raw : null)
?? (ammPrice > 0 ? ammPriceRaw : null)
?? '0'
const numericPrice = (vwap1h.num > 0 && !vwap1h.stale ? vwap1h.num : 0)
|| (vwap24h.num > 0 && !vwap24h.stale ? vwap24h.num : 0)
|| ammPrice
|| 0
let confidence: 'high' | 'medium' | 'low' | 'unknown' = 'unknown'
if (lastTradeAgeSeconds === null) {
confidence = 'unknown'
} else if (lastTradeAgeSeconds < HIGH_CONFIDENCE_MAX_AGE_SECONDS && sources > 1 && volume24h > 0) {
confidence = 'high'
} else if (lastTradeAgeSeconds < MEDIUM_CONFIDENCE_MAX_AGE_SECONDS) {
confidence = 'medium'
} else {
confidence = 'low'
}
const isStaleByTime = lastTradeAgeSeconds !== null && lastTradeAgeSeconds >= staleThreshold
const stale = isStaleByTime || vwap1h.stale === true
if (isString) {
return {
price: stringPrice,
sdexPrice: guardStr(sdexVwap24h),
ammPrice: ammPriceRaw,
volume24h: totalVolume24hRaw,
sdexVolume24h: sdexVolume24hRaw,
ammVolume24h: ammVolume24hRaw,
vwap1m: guardStr(vwap1m),
vwap5m: guardStr(vwap5m),
vwap1h: guardStr(vwap1h),
vwap24h: guardStr(vwap24h),
priceChange24h: priceChange24h.raw,
sources,
confidence,
lastTradeAgeSeconds,
newestInputObservedAt,
inputCount,
stalenessThresholdSeconds: staleThreshold,
stale,
}
}
return {
price: numericPrice,
sdexPrice: guardNum(sdexVwap24h),
ammPrice,
volume24h,
sdexVolume24h,
ammVolume24h,
vwap1m: guardNum(vwap1m),
vwap5m: guardNum(vwap5m),
vwap1h: guardNum(vwap1h),
vwap24h: guardNum(vwap24h),
priceChange24h: priceChange24h.num,
sources,
confidence,
lastTradeAgeSeconds,
newestInputObservedAt,
inputCount,
stalenessThresholdSeconds: staleThreshold,
stale,
}
}