Intelligence, Advanced Charting & Trading Platform
Phase 1: candle builder and quality scoring
* test: define candle builder acceptance behavior * feat: implement deterministic candle builder * test: define deterministic quality scoring * feat: implement deterministic quality scoring * docs: refresh Phase 1 execution ledger
davoodmehraban89 committed
Oct 5, 2026 at 16:39 UTC
c4e9e84ccf540f71731d08dc6ba45f59d5796be2
5 files changed
+173
-33
PROJECT_STATE.md
+34
-33
@@ -3,7 +3,7 @@
3
Last updated: 2026-10-05
4
5
## Current phase
6
-Phase 1 — Market Domain & Data Proof started. Phase 0 PostgreSQL foundation is merged.
6
+Phase 1 — Market Data Integrity & Data Proof.
7
8
## Product scope locked for MVP
9
- Iran free-market USD/IRT
@@ -16,49 +16,50 @@ Phase 1 — Market Domain & Data Proof started. Phase 0 PostgreSQL foundation is
16
## Architecture baseline
17
- Modular monolith for MVP, with independently schedulable ingestion workers.
18
- TypeScript/React/Next.js web application.
19
-- PostgreSQL is the only canonical database contract. Hosting provider is replaceable through `DATABASE_URL`.
20
-- Initial hosting target is Aiven Free PostgreSQL if it can be provisioned without payment credentials; Aiven is infrastructure only, never a domain dependency.
21
-- Supabase, Neon, Render and Railway are not architectural dependencies. They remain replaceable hosting alternatives.
22
-- Cloudflare is edge/runtime/cache/protection. Hyperdrive can front any compatible reachable PostgreSQL once credentials exist.
19
+- PostgreSQL is the canonical database contract; hosting is replaceable through `DATABASE_URL`.
20
+- Cloudflare is edge/runtime/cache/protection. Hyperdrive is configured only after a reachable PostgreSQL endpoint exists.
21
- Provider adapters feed immutable raw observations, normalization, quality gates, candle construction, and derived-series calculation.
22
- UTC canonical storage; Asia/Tehran presentation.
25
-- No UI timeframe may imply precision not supported by source data.
23
+- No UI timeframe may imply precision not supported by observed source cadence.
24
25
## Completed
28
-- Independent private GitHub repository established.
29
-- Phase 0 foundation merged to `main` with green CI.
30
-- Provider-neutral PostgreSQL market core merged to `main` with green CI.
31
-- Engineering rules, Definition of Done, architecture baseline and canonical market contracts established.
32
-- PostgreSQL migrations exist for instruments, providers, raw observations, normalized ticks, candles, derived values, data-quality events, users, workspaces and drawings.
33
-- Six canonical MVP instruments are seeded.
34
-- Database invariant test exists for canonical instruments and invalid OHLC rejection.
35
-- Cloudflare account connection verified.
36
-- Render Free PostgreSQL was tested and rejected for the current zero-cost constraint because provisioning required payment credentials.
26
+- Phase 0 foundation and provider-neutral PostgreSQL schema merged.
27
+- Canonical instruments, raw observations, ticks, candles, derived values, quality events, workspaces and drawings schema defined.
28
- Deterministic theoretical 18K gold and premium calculations implemented.
38
-- Source timestamp alignment and staleness semantics implemented.
39
-- Provider normalization contract implemented, including IRR-to-IRT conversion and refusal to guess unsupported units.
40
-- Provider health contract implemented.
41
-- Deterministic market-data quality classification implemented for GOOD / DEGRADED / STALE / INVALID.
42
-- CI floating-point assertion defect was identified from workflow logs and corrected with tolerance-based numeric assertions.
29
+- Timestamp alignment, staleness, provider normalization and provider health implemented.
30
+- GOOD / DEGRADED / STALE / INVALID quality classification implemented.
31
+- Provider-neutral ingestion and derived-gold pipeline implemented.
32
+- Navasan adapters implemented for USD_IRT_FREE and GOLD18_IRT, including IRR→IRT normalization and historical daily OHLC parsing.
33
+- Alpha Vantage XAU/USD spot adapter implemented.
34
+- Data Proof metrics implemented for cadence, gaps, duplicates and out-of-order observations.
35
+- Provider source matrix documented.
36
+- Render Free PostgreSQL was tested and rejected because provisioning required payment credentials.
37
38
## In progress
45
-- Phase 1 provider research/data proof for USD/IRT, GOLD18/IRT and XAU/USD.
39
+- Deterministic multi-timeframe candle builder with no synthetic gap filling.
40
+- Numeric quality scoring and propagation into candles/derived data.
41
+- Live Data Proof for USD_IRT_FREE, GOLD18_IRT and XAU_USD.
42
- Managed PostgreSQL provisioning on a no-card free provider.
47
-- Provider-specific adapters only after legal/technical source suitability is documented.
48
-- Integration of quality state with ingestion/candle pipeline.
43
+- Secondary legally usable Iranian source research for cross-check/failover.
44
50
-## External blocker
51
-A live VELYQOR PostgreSQL endpoint is not yet connected. This blocks executing migrations against production-like infrastructure, but it does not block domain implementation, deterministic tests, provider research, or application scaffolding.
45
+## External blockers
46
+1. No live VELYQOR PostgreSQL endpoint is connected, so production-like migration/invariant execution and Hyperdrive binding cannot yet be completed.
47
+2. Live provider credentials are not connected to the runtime, so real cadence/quota/freshness measurements cannot yet be completed.
48
+
49
+## Phase 1 exit gates
50
+1. PostgreSQL migrations and invariants execute successfully against a live reachable PostgreSQL instance.
51
+2. USD_IRT_FREE, GOLD18_IRT and XAU_USD each have a live tested ingestion path.
52
+3. Observed cadence, latency, gaps, duplicates, out-of-order behavior and failure/recovery are recorded for each source.
53
+4. Candle construction is deterministic and never invents missing observations.
54
+5. Quality state/score propagates into candles and derived values.
55
+6. At least one secondary legally usable reference is identified for Iranian market cross-check, or the lack of one is explicitly accepted as a launch risk.
56
+7. Secrets are runtime-only and absent from the repository.
57
+8. CI is green for all Phase 1 domain behavior.
58
59
## Risks
54
-- Iranian market-data provider licensing, timestamp quality, anti-bot restrictions, history and reliability.
55
-- UI timeframes must reflect actual observation frequency; synthetic precision is prohibited.
56
-- XAU/USD and USD/IRT source timestamps require explicit alignment/staleness thresholds.
60
+- Iranian market-data licensing, timestamp quality, anti-bot restrictions, history and reliability.
61
+- Free source cadence may be insufficient for intraday timeframes; unsupported timeframes must stay disabled.
62
- Free database hosting is temporary infrastructure and must not become a product dependency.
63
64
## Next checkpoint
60
-1. Get Phase 1 domain/provider contract CI green and merge.
61
-2. Complete provider source matrix and select primary/secondary candidates for each canonical symbol.
62
-3. Connect Aiven or another no-card PostgreSQL endpoint and execute migrations/invariants.
63
-4. Configure Cloudflare Hyperdrive only after a real PostgreSQL endpoint exists.
64
-5. Start chart application shell after Data Proof gates are satisfied.
65
+Finish all non-external Phase 1 gates, then execute live PostgreSQL and provider Data Proof immediately when runtime credentials/endpoints are available.
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));
packages/market-domain/src/quality-score.mjs
new
+17
@@ -0,0 +1,17 @@
1
+const BASE = Object.freeze({ GOOD: 100, DEGRADED: 80, STALE: 30, INVALID: 0 });
2
+
3
+export function qualityScore({ state, flags = [], ageRatio = 0 }) {
4
+ if (!(state in BASE)) throw new RangeError(`unsupported quality state: ${state}`);
5
+ if (!Array.isArray(flags)) throw new TypeError('flags must be an array');
6
+ if (!Number.isFinite(ageRatio) || ageRatio < 0) throw new RangeError('ageRatio must be non-negative and finite');
7
+ if (state === 'INVALID') return 0;
8
+
9
+ let score = BASE[state];
10
+ if (flags.includes('PROVIDER_DIVERGENCE')) score -= 15;
11
+ if (flags.includes('STALE_SOURCE')) score -= 10;
12
+ if (ageRatio >= 0.75 && ageRatio <= 1) score -= 10;
13
+ if (ageRatio > 1) score -= Math.min(20, Math.floor(ageRatio - 1) * 5);
14
+
15
+ if (state === 'STALE') score = Math.min(score, 30);
16
+ return Math.max(0, Math.min(100, score));
17
+}
packages/market-domain/test/candle-builder.test.mjs
new
+40
@@ -0,0 +1,40 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { buildCandles } from '../src/candle-builder.mjs';
4
+
5
+const ticks = [
6
+ { timestamp: '2026-10-05T12:00:10Z', price: 100, quality: 'GOOD' },
7
+ { timestamp: '2026-10-05T12:00:40Z', price: 105, quality: 'GOOD' },
8
+ { timestamp: '2026-10-05T12:01:10Z', price: 103, quality: 'DEGRADED' },
9
+ { timestamp: '2026-10-05T12:01:50Z', price: 101, quality: 'GOOD' },
10
+];
11
+
12
+test('builds deterministic 1m OHLC candles', () => {
13
+ const candles = buildCandles({ ticks, timeframe: '1m' });
14
+ assert.equal(candles.length, 2);
15
+ assert.deepEqual(candles[0], {
16
+ openTime: '2026-10-05T12:00:00.000Z', closeTime: '2026-10-05T12:01:00.000Z',
17
+ open: 100, high: 105, low: 100, close: 105, observationCount: 2, quality: 'GOOD',
18
+ });
19
+ assert.equal(candles[1].open, 103);
20
+ assert.equal(candles[1].close, 101);
21
+ assert.equal(candles[1].quality, 'DEGRADED');
22
+});
23
+
24
+test('sorts out-of-order ticks and collapses exact duplicate timestamp/price pairs', () => {
25
+ const candles = buildCandles({ ticks: [ticks[1], ticks[0], ticks[0]], timeframe: '1m' });
26
+ assert.equal(candles[0].open, 100);
27
+ assert.equal(candles[0].close, 105);
28
+ assert.equal(candles[0].observationCount, 2);
29
+});
30
+
31
+test('does not synthesize empty candles across gaps', () => {
32
+ const candles = buildCandles({ ticks: [ticks[0], { timestamp: '2026-10-05T12:05:10Z', price: 110, quality: 'GOOD' }], timeframe: '1m' });
33
+ assert.equal(candles.length, 2);
34
+ assert.equal(candles[1].openTime, '2026-10-05T12:05:00.000Z');
35
+});
36
+
37
+test('rejects unsupported timeframes and invalid prices', () => {
38
+ assert.throws(() => buildCandles({ ticks, timeframe: '2m' }), /unsupported timeframe/i);
39
+ assert.throws(() => buildCandles({ ticks: [{ timestamp: ticks[0].timestamp, price: 0, quality: 'GOOD' }], timeframe: '1m' }), /price/i);
40
+});
packages/market-domain/test/quality-score.test.mjs
new
+20
@@ -0,0 +1,20 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { qualityScore } from '../src/quality-score.mjs';
4
+
5
+test('scores healthy fresh observations at 100', () => {
6
+ assert.equal(qualityScore({ state: 'GOOD', flags: [], ageRatio: 0.1 }), 100);
7
+});
8
+
9
+test('penalizes divergence and approaching staleness deterministically', () => {
10
+ const score = qualityScore({ state: 'DEGRADED', flags: ['PROVIDER_DIVERGENCE'], ageRatio: 0.8 });
11
+ assert.equal(score, 55);
12
+});
13
+
14
+test('caps stale observations below healthy presentation threshold', () => {
15
+ assert.ok(qualityScore({ state: 'STALE', flags: ['STALE_SOURCE'], ageRatio: 2 }) <= 30);
16
+});
17
+
18
+test('invalid observations always score zero', () => {
19
+ assert.equal(qualityScore({ state: 'INVALID', flags: ['NON_POSITIVE_PRICE'], ageRatio: 0 }), 0);
20
+});