@davoodmehraban89 / VELYQOR / commits / f63e631
Fork 0

Intelligence, Advanced Charting & Trading Platform

feat: implement deterministic candle builder

davoodmehraban89 committed Oct 5, 2026 at 16:37 UTC f63e6317a2451c6025a372292ab6db0908e431ab
1 file changed +62
packages/market-domain/src/candle-builder.mjs new
+62
@@ -0,0 +1,62 @@
1 +const TIMEFRAMES_MS = Object.freeze({
2 + '1m': 60_000,
3 + '5m': 300_000,
4 + '15m': 900_000,
5 + '30m': 1_800_000,
6 + '1h': 3_600_000,
7 + '4h': 14_400_000,
8 + '1d': 86_400_000,
9 +});
10 +
11 +const QUALITY_RANK = Object.freeze({ GOOD: 0, DEGRADED: 1, STALE: 2, INVALID: 3 });
12 +
13 +function parseTick(tick, index) {
14 + if (!tick || typeof tick !== 'object' || Array.isArray(tick)) throw new TypeError(`tick[${index}] must be an object`);
15 + const timestampMs = new Date(tick.timestamp).valueOf();
16 + if (!Number.isFinite(timestampMs)) throw new TypeError(`tick[${index}].timestamp must be valid`);
17 + if (!Number.isFinite(tick.price) || tick.price <= 0) throw new RangeError(`tick[${index}].price must be positive and finite`);
18 + if (!(tick.quality in QUALITY_RANK)) throw new RangeError(`tick[${index}].quality is unsupported`);
19 + return { timestampMs, price: tick.price, quality: tick.quality };
20 +}
21 +
22 +function worstQuality(items) {
23 + return items.reduce((worst, item) => QUALITY_RANK[item.quality] > QUALITY_RANK[worst] ? item.quality : worst, 'GOOD');
24 +}
25 +
26 +export function buildCandles({ ticks, timeframe }) {
27 + if (!Array.isArray(ticks)) throw new TypeError('ticks must be an array');
28 + const intervalMs = TIMEFRAMES_MS[timeframe];
29 + if (!intervalMs) throw new RangeError(`unsupported timeframe: ${timeframe}`);
30 +
31 + const seen = new Set();
32 + const parsed = ticks.map(parseTick).filter((tick) => {
33 + const key = `${tick.timestampMs}:${tick.price}`;
34 + if (seen.has(key)) return false;
35 + seen.add(key);
36 + return true;
37 + }).sort((a, b) => a.timestampMs - b.timestampMs);
38 +
39 + const buckets = new Map();
40 + for (const tick of parsed) {
41 + const openMs = Math.floor(tick.timestampMs / intervalMs) * intervalMs;
42 + const bucket = buckets.get(openMs) ?? [];
43 + bucket.push(tick);
44 + buckets.set(openMs, bucket);
45 + }
46 +
47 + return [...buckets.entries()].sort(([a], [b]) => a - b).map(([openMs, items]) => {
48 + const prices = items.map((item) => item.price);
49 + return {
50 + openTime: new Date(openMs).toISOString(),
51 + closeTime: new Date(openMs + intervalMs).toISOString(),
52 + open: items[0].price,
53 + high: Math.max(...prices),
54 + low: Math.min(...prices),
55 + close: items.at(-1).price,
56 + observationCount: items.length,
57 + quality: worstQuality(items),
58 + };
59 + });
60 +}
61 +
62 +export const SUPPORTED_TIMEFRAMES = Object.freeze(Object.keys(TIMEFRAMES_MS));