@davoodmehraban89 / VELYQOR / commits / 94557d6
Fork 0

Intelligence, Advanced Charting & Trading Platform

Phase 0: implement portable PostgreSQL market core

* feat(db): add canonical PostgreSQL market core schema * feat(db): add portable workspace persistence schema * test(db): add market schema invariant checks * chore: document portable database environment contract * docs: lock PostgreSQL provider portability decision * docs: advance state to PostgreSQL core implementation

davoodmehraban89 committed Oct 5, 2026 at 10:20 UTC 94557d6e8c7c000c964f854606ffe39d0a5cadf3
6 files changed +238 -33
.env.example new
+8
@@ -0,0 +1,8 @@
1 +# Canonical PostgreSQL connection. Provider-agnostic by design.
2 +DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/DATABASE?sslmode=require
3 +
4 +# Application defaults
5 +APP_TIMEZONE=Asia/Tehran
6 +MARKET_DATA_DEFAULT_QUALITY_THRESHOLD=70
7 +
8 +# Never commit real credentials. Production secrets belong in the runtime secret store.
PROJECT_STATE.md
+28 -33
@@ -3,7 +3,7 @@
3 Last updated: 2026-10-05
4
5 ## Current phase
6 -Phase 0 — Foundation & Governance
6 +Phase 0 — Foundation & Governance; PostgreSQL core implementation in progress.
7
8 ## Product scope locked for MVP
9 - Iran free-market USD/IRT
@@ -15,45 +15,40 @@ Phase 0 — Foundation & Governance
15
16 ## Architecture baseline
17 - Modular monolith for the MVP.
18 -- TypeScript/React/Next.js web application; exact package versions are pinned when implementation begins.
19 -- PostgreSQL as canonical datastore; Supabase is the preferred MVP PostgreSQL/Auth/Realtime platform, pending project connection.
20 -- Cloudflare as edge/runtime/cache/protection layer, not the primary database.
18 +- TypeScript/React/Next.js web application.
19 +- PostgreSQL is the canonical datastore; hosting is provider-portable through `DATABASE_URL`.
20 +- Neon is the preferred initial managed PostgreSQL provider, but is not a domain dependency.
21 +- Cloudflare is edge/runtime/cache/protection; Hyperdrive may front PostgreSQL after credentials exist.
22 - Provider adapters feed immutable raw observations, normalization, quality gates, candle construction, and derived-series calculation.
23 - UTC canonical storage; Asia/Tehran presentation.
24
24 -## Connection priority
25 -P0: GitHub, Context7, PostgreSQL/Supabase, Cloudflare.
26 -P1: Figma, Notion.
27 -P2: TradingCursor (benchmark/research only), Gmail, Railway/Render if a demonstrated need appears.
28 -
25 ## Completed
30 -- Independent private GitHub repository created: `davoodmehraban89/VELYQOR`.
31 -- Initial `main` branch established by owner.
32 -- Foundation branch created: `foundation/phase-0`.
33 -- Product README normalized.
34 -- Engineering/agent operating rules added.
35 -- Next.js current documentation checked through Context7; current v16 documentation requires Node.js >=20.9 and supports TypeScript/App Router defaults.
26 +- Independent private GitHub repository established.
27 +- Phase 0 foundation PR passed CI and was merged to `main`.
28 +- Engineering rules, Definition of Done, architecture baseline and canonical market contracts established.
29 +- PostgreSQL portability decision recorded in ADR-0002.
30 +- Initial PostgreSQL migrations created for instruments, providers, raw observations, normalized ticks, candles, derived values, data-quality events, users, workspaces and drawings.
31 +- Six canonical MVP instruments are seeded.
32 +- Database invariant test added for canonical instruments and invalid OHLC rejection.
33 +- Cloudflare account connection verified; Hyperdrive API is available and currently has no configurations.
34 +- Neon plugin is installed in the ChatGPT environment, but its operational actions are not exposed in this conversation yet.
35
36 ## In progress
38 -- Architecture Decision Records.
39 -- Canonical instrument/unit/time contracts.
40 -- Repository skeleton and CI baseline.
41 -- Supabase/PostgreSQL connection.
42 -- Cloudflare environment connection.
43 -- Phase 1 provider research and data proof.
44 -
45 -## Blockers / external actions
46 -- Supabase project for VELYQOR is not yet identified/connected.
47 -- Cloudflare application/environment for VELYQOR is not yet identified/connected.
48 -- Figma and Notion project spaces are not required to start data proof, but are pending for P1.
37 +- Provisioning a managed PostgreSQL database for VELYQOR.
38 +- Applying and executing database migrations/invariant tests against a real PostgreSQL instance.
39 +- Cloudflare Hyperdrive configuration after PostgreSQL credentials exist.
40 +- Phase 1 provider research/data proof.
41 +
42 +## External blocker
43 +A live PostgreSQL instance has not yet been provisioned/connected in this conversation. Until a database connection is available, migrations cannot truthfully be reported as executed. Neon is the selected initial provider; the schema itself remains portable PostgreSQL.
44
45 ## Risks
51 -- Iranian market-data providers may have licensing, timestamp-quality, anti-bot, history, or reliability limitations.
52 -- UI timeframe availability must be constrained by actual observation frequency; synthetic precision is prohibited.
53 -- XAU/USD and USD/IRT source timestamps require explicit alignment and staleness thresholds for theoretical gold.
46 +- Iranian market-data provider licensing, timestamp quality, anti-bot restrictions, history and reliability.
47 +- UI timeframes must reflect actual observation frequency; synthetic precision is prohibited.
48 +- XAU/USD and USD/IRT source timestamps require explicit alignment/staleness thresholds.
49
50 ## Next checkpoint
56 -1. Commit initial ADRs and data contracts.
57 -2. Establish minimal TypeScript/Next.js repository skeleton and CI.
58 -3. Connect/create PostgreSQL/Supabase resources.
59 -4. Begin provider research and implement the first raw-ingestion proof only after provider/legal/technical suitability is documented.
51 +1. Provision/connect VELYQOR PostgreSQL.
52 +2. Execute migrations and invariant tests.
53 +3. Create Cloudflare Hyperdrive against the database.
54 +4. Start Phase 1 provider adapters and data-quality proof.
db/migrations/0001_market_core.sql new
+124
@@ -0,0 +1,124 @@
1 +BEGIN;
2 +
3 +CREATE TYPE asset_class AS ENUM ('FX','COMMODITY','DERIVED','CRYPTO','EQUITY','OTHER');
4 +CREATE TYPE quality_state AS ENUM ('GOOD','DEGRADED','STALE','INVALID');
5 +
6 +CREATE TABLE instruments (
7 + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
8 + symbol TEXT NOT NULL UNIQUE,
9 + display_name TEXT NOT NULL,
10 + asset_class asset_class NOT NULL,
11 + base_asset TEXT NOT NULL,
12 + quote_asset TEXT NOT NULL,
13 + unit TEXT NOT NULL,
14 + market TEXT NOT NULL,
15 + timezone TEXT NOT NULL DEFAULT 'UTC',
16 + price_precision SMALLINT NOT NULL CHECK (price_precision BETWEEN 0 AND 18),
17 + active BOOLEAN NOT NULL DEFAULT TRUE,
18 + created_at TIMESTAMPTZ NOT NULL DEFAULT now()
19 +);
20 +
21 +CREATE TABLE providers (
22 + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
23 + code TEXT NOT NULL UNIQUE,
24 + name TEXT NOT NULL,
25 + provider_type TEXT NOT NULL,
26 + priority SMALLINT NOT NULL DEFAULT 100,
27 + active BOOLEAN NOT NULL DEFAULT TRUE,
28 + created_at TIMESTAMPTZ NOT NULL DEFAULT now()
29 +);
30 +
31 +CREATE TABLE provider_instruments (
32 + provider_id BIGINT NOT NULL REFERENCES providers(id),
33 + instrument_id BIGINT NOT NULL REFERENCES instruments(id),
34 + external_symbol TEXT NOT NULL,
35 + metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
36 + active BOOLEAN NOT NULL DEFAULT TRUE,
37 + PRIMARY KEY (provider_id, instrument_id),
38 + UNIQUE (provider_id, external_symbol)
39 +);
40 +
41 +CREATE TABLE raw_market_observations (
42 + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
43 + provider_id BIGINT NOT NULL REFERENCES providers(id),
44 + instrument_id BIGINT NOT NULL REFERENCES instruments(id),
45 + provider_timestamp TIMESTAMPTZ,
46 + received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
47 + raw_price TEXT NOT NULL,
48 + raw_payload JSONB,
49 + raw_payload_hash TEXT,
50 + status TEXT NOT NULL DEFAULT 'RECEIVED',
51 + CHECK (length(raw_price) > 0)
52 +);
53 +CREATE INDEX raw_observations_lookup_idx ON raw_market_observations (instrument_id, provider_timestamp DESC);
54 +CREATE INDEX raw_observations_received_idx ON raw_market_observations (received_at DESC);
55 +
56 +CREATE TABLE market_ticks (
57 + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
58 + instrument_id BIGINT NOT NULL REFERENCES instruments(id),
59 + provider_id BIGINT NOT NULL REFERENCES providers(id),
60 + ts TIMESTAMPTZ NOT NULL,
61 + price NUMERIC(30,10) NOT NULL CHECK (price > 0),
62 + quality quality_state NOT NULL,
63 + quality_score NUMERIC(5,2) NOT NULL CHECK (quality_score BETWEEN 0 AND 100),
64 + flags JSONB NOT NULL DEFAULT '[]'::jsonb,
65 + raw_observation_id BIGINT REFERENCES raw_market_observations(id),
66 + created_at TIMESTAMPTZ NOT NULL DEFAULT now()
67 +);
68 +CREATE INDEX market_ticks_lookup_idx ON market_ticks (instrument_id, ts DESC);
69 +
70 +CREATE TABLE candles (
71 + instrument_id BIGINT NOT NULL REFERENCES instruments(id),
72 + timeframe TEXT NOT NULL,
73 + open_time TIMESTAMPTZ NOT NULL,
74 + close_time TIMESTAMPTZ NOT NULL,
75 + open NUMERIC(30,10) NOT NULL CHECK (open > 0),
76 + high NUMERIC(30,10) NOT NULL CHECK (high > 0),
77 + low NUMERIC(30,10) NOT NULL CHECK (low > 0),
78 + close NUMERIC(30,10) NOT NULL CHECK (close > 0),
79 + volume NUMERIC(30,10),
80 + observation_count INTEGER NOT NULL CHECK (observation_count > 0),
81 + quality quality_state NOT NULL,
82 + quality_score NUMERIC(5,2) NOT NULL CHECK (quality_score BETWEEN 0 AND 100),
83 + PRIMARY KEY (instrument_id, timeframe, open_time),
84 + CHECK (open_time < close_time),
85 + CHECK (low <= open AND open <= high),
86 + CHECK (low <= close AND close <= high),
87 + CHECK (low <= high)
88 +);
89 +
90 +CREATE TABLE derived_market_values (
91 + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
92 + instrument_id BIGINT NOT NULL REFERENCES instruments(id),
93 + ts TIMESTAMPTZ NOT NULL,
94 + value NUMERIC(30,10) NOT NULL,
95 + calculation_version TEXT NOT NULL,
96 + source_snapshot JSONB NOT NULL,
97 + quality quality_state NOT NULL,
98 + quality_score NUMERIC(5,2) NOT NULL CHECK (quality_score BETWEEN 0 AND 100),
99 + flags JSONB NOT NULL DEFAULT '[]'::jsonb,
100 + UNIQUE (instrument_id, ts, calculation_version)
101 +);
102 +CREATE INDEX derived_values_lookup_idx ON derived_market_values (instrument_id, ts DESC);
103 +
104 +CREATE TABLE data_quality_events (
105 + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
106 + instrument_id BIGINT REFERENCES instruments(id),
107 + provider_id BIGINT REFERENCES providers(id),
108 + event_type TEXT NOT NULL,
109 + severity TEXT NOT NULL CHECK (severity IN ('INFO','WARNING','ERROR','CRITICAL')),
110 + started_at TIMESTAMPTZ NOT NULL,
111 + resolved_at TIMESTAMPTZ,
112 + details JSONB NOT NULL DEFAULT '{}'::jsonb,
113 + CHECK (resolved_at IS NULL OR resolved_at >= started_at)
114 +);
115 +
116 +INSERT INTO instruments(symbol, display_name, asset_class, base_asset, quote_asset, unit, market, timezone, price_precision) VALUES
117 +('USD_IRT_FREE','US Dollar / Iranian Toman — Free Market','FX','USD','IRT','IRT_PER_USD','IRAN_FREE','Asia/Tehran',0),
118 +('GOLD18_IRT','18K Gold / Iranian Toman','COMMODITY','GOLD18_GRAM','IRT','IRT_PER_GRAM','IRAN','Asia/Tehran',0),
119 +('XAU_USD','Gold Spot / US Dollar','COMMODITY','XAU','USD','USD_PER_TROY_OUNCE','GLOBAL','UTC',4),
120 +('GOLD18_THEORETICAL_IRT','Theoretical 18K Gold / Iranian Toman','DERIVED','GOLD18_GRAM','IRT','IRT_PER_GRAM','VELYQOR','Asia/Tehran',0),
121 +('GOLD18_PREMIUM_IRT','18K Gold Premium / Iranian Toman','DERIVED','GOLD18_PREMIUM','IRT','IRT_PER_GRAM','VELYQOR','Asia/Tehran',0),
122 +('GOLD18_PREMIUM_PCT','18K Gold Premium Percent','DERIVED','GOLD18_PREMIUM','PCT','PERCENT','VELYQOR','Asia/Tehran',4);
123 +
124 +COMMIT;
db/migrations/0002_workspaces.sql new
+31
@@ -0,0 +1,31 @@
1 +BEGIN;
2 +
3 +CREATE TABLE app_users (
4 + id UUID PRIMARY KEY,
5 + created_at TIMESTAMPTZ NOT NULL DEFAULT now()
6 +);
7 +
8 +CREATE TABLE workspaces (
9 + id UUID PRIMARY KEY,
10 + user_id UUID NOT NULL REFERENCES app_users(id) ON DELETE CASCADE,
11 + name TEXT NOT NULL,
12 + active_symbol TEXT NOT NULL REFERENCES instruments(symbol),
13 + timeframe TEXT NOT NULL,
14 + layout JSONB NOT NULL DEFAULT '{}'::jsonb,
15 + created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
16 + updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
17 +);
18 +CREATE INDEX workspaces_user_idx ON workspaces (user_id, updated_at DESC);
19 +
20 +CREATE TABLE drawings (
21 + id UUID PRIMARY KEY,
22 + workspace_id UUID NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
23 + instrument_id BIGINT NOT NULL REFERENCES instruments(id),
24 + drawing_type TEXT NOT NULL,
25 + payload JSONB NOT NULL,
26 + created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
27 + updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
28 +);
29 +CREATE INDEX drawings_workspace_idx ON drawings (workspace_id, instrument_id);
30 +
31 +COMMIT;
db/tests/market_core_invariants.sql new
+27
@@ -0,0 +1,27 @@
1 +BEGIN;
2 +
3 +DO $$
4 +DECLARE instrument_count INTEGER;
5 +BEGIN
6 + SELECT count(*) INTO instrument_count FROM instruments
7 + WHERE symbol IN ('USD_IRT_FREE','GOLD18_IRT','XAU_USD','GOLD18_THEORETICAL_IRT','GOLD18_PREMIUM_IRT','GOLD18_PREMIUM_PCT');
8 + IF instrument_count <> 6 THEN
9 + RAISE EXCEPTION 'Expected 6 canonical MVP instruments, got %', instrument_count;
10 + END IF;
11 +END $$;
12 +
13 +-- Invalid candles must be rejected by constraints.
14 +DO $$
15 +DECLARE usd_id BIGINT;
16 +BEGIN
17 + SELECT id INTO usd_id FROM instruments WHERE symbol='USD_IRT_FREE';
18 + BEGIN
19 + INSERT INTO candles(instrument_id,timeframe,open_time,close_time,open,high,low,close,observation_count,quality,quality_score)
20 + VALUES(usd_id,'1m','2026-01-01T00:00:00Z','2026-01-01T00:01:00Z',100,90,80,85,2,'GOOD',100);
21 + RAISE EXCEPTION 'Invalid candle unexpectedly accepted';
22 + EXCEPTION WHEN check_violation THEN
23 + NULL;
24 + END;
25 +END $$;
26 +
27 +ROLLBACK;
docs/architecture/ADR-0002-postgresql-provider-portability.md new
+20
@@ -0,0 +1,20 @@
1 +# ADR-0002: PostgreSQL Provider Portability
2 +
3 +Status: Accepted
4 +Date: 2026-10-05
5 +
6 +## Decision
7 +VELYQOR's canonical database technology is PostgreSQL. Hosting provider identity is infrastructure configuration, not a domain dependency.
8 +
9 +The application consumes a standard `DATABASE_URL`. Schema migrations must use portable PostgreSQL features unless an extension is separately approved by ADR. Provider SDKs must not leak into market-domain modules.
10 +
11 +The initial managed provider may be Neon. Supabase, self-hosted PostgreSQL, or another compatible managed service can replace it without redesigning the market domain.
12 +
13 +Cloudflare Hyperdrive may pool/accelerate PostgreSQL connections after a database exists; Hyperdrive is not the datastore itself.
14 +
15 +## Consequences
16 +- No Supabase-specific schema requirement.
17 +- Auth is decoupled from core market data.
18 +- Database migrations live in `db/migrations`.
19 +- Secrets are supplied by runtime configuration and never committed.
20 +- Provider migration remains operational rather than architectural work.