diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json
index e28b9ff4..e17a21a3 100644
--- a/apps/stock/config/package.json
+++ b/apps/stock/config/package.json
@@ -64,6 +64,10 @@
"./paper-deployments": {
"types": "./dist/contracts/paper-deployments.d.ts",
"import": "./dist/contracts/paper-deployments.js"
+ },
+ "./stored-source": {
+ "types": "./dist/contracts/stored-source.d.ts",
+ "default": "./dist/contracts/stored-source.js"
}
},
"scripts": {
diff --git a/apps/stock/config/src/contracts/stored-source.ts b/apps/stock/config/src/contracts/stored-source.ts
new file mode 100644
index 00000000..74f52987
--- /dev/null
+++ b/apps/stock/config/src/contracts/stored-source.ts
@@ -0,0 +1,89 @@
+/** Read-only source diagnostics. These do not certify a dataset or retain source evidence. */
+import { z } from 'zod';
+import { parseInstrumentId } from '@stock-bot/types';
+
+const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
+export const storedSourceIntervalSchema = z.enum(['1m', '5m', '1h']);
+const instrument = z.string().refine(value => {
+ try {
+ return parseInstrumentId(value).id === value;
+ } catch {
+ return false;
+ }
+}, 'Expected a provider instrument identity, for example AAPL.US');
+export const storedSourceSelectionSchema = z
+ .object({ instrumentId: instrument, interval: storedSourceIntervalSchema })
+ .strict();
+export type StoredSourceSelection = z.infer;
+export const storedSourceQuerySchema = storedSourceSelectionSchema
+ .extend({
+ start: instant,
+ end: instant,
+ })
+ .strict()
+ .refine(value => value.start < value.end, 'End must be after start');
+export type StoredSourceQuery = z.infer;
+export const storedSourceCoverageSchema = z
+ .object({
+ version: z.literal('stored-eod-coverage/v1'),
+ observedAt: instant,
+ query: storedSourceSelectionSchema,
+ series: z
+ .array(
+ z
+ .object({
+ instrumentId: instrument,
+ interval: storedSourceIntervalSchema,
+ rowCount: count,
+ firstTimestamp: instant.nullable(),
+ lastTimestamp: instant.nullable(),
+ invalidTimestampRows: count,
+ })
+ .strict()
+ )
+ .max(1),
+ })
+ .strict();
+export type StoredSourceCoverage = z.infer;
+export const storedSourceIssueSchema = z.enum([
+ 'identity-mismatch',
+ 'invalid-timestamp',
+ 'outside-range',
+ 'invalid-prices',
+ 'null-volume',
+ 'invalid-volume',
+ 'duplicate-timestamp',
+]);
+export const storedSourceInspectionSchema = z
+ .object({
+ version: z.literal('stored-eod-inspection/v1'),
+ observedAt: instant,
+ query: storedSourceQuerySchema,
+ rowCount: count,
+ invalidRows: count,
+ nullVolumeRows: count,
+ duplicateRows: count,
+ firstTimestamp: instant.nullable(),
+ lastTimestamp: instant.nullable(),
+ days: z.array(
+ z
+ .object({
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
+ rowCount: count,
+ invalidRows: count,
+ })
+ .strict()
+ ),
+ issues: z.array(
+ z
+ .object({
+ code: storedSourceIssueSchema,
+ rowCount: count,
+ timestamps: z.array(instant.nullable()),
+ })
+ .strict()
+ ),
+ })
+ .strict();
+export type StoredSourceInspection = z.infer;
diff --git a/apps/stock/web-api/src/routes/datasets.routes.ts b/apps/stock/web-api/src/routes/datasets.routes.ts
index ac8329a0..6397fcf6 100644
--- a/apps/stock/web-api/src/routes/datasets.routes.ts
+++ b/apps/stock/web-api/src/routes/datasets.routes.ts
@@ -14,6 +14,11 @@ import {
prepareStoredDataset,
StoredDatasetPreparationError,
} from '../services/stored-dataset-preparation';
+import {
+ inspectStoredSource,
+ storedSourceCoverage,
+ StoredSourceInspectionError,
+} from '../services/stored-source-inspection';
const logger = getLogger('dataset-catalog-routes');
@@ -28,6 +33,47 @@ export function createDatasetRoutes(container: IServiceContainer) {
throw new DatasetPreparationError(400, 'Invalid JSON request');
}
};
+ app.get('/api/v2/datasets/stored-eod/coverage', async c => {
+ c.header('Cache-Control', 'no-store');
+ try {
+ return c.json(await storedSourceCoverage(container.mongodb, c.req.query(), c.req.raw.signal));
+ } catch (error) {
+ if (c.req.raw.signal.aborted) {
+ return Response.json(
+ { error: 'Stored source inspection cancelled' },
+ { status: 499, headers: { 'Cache-Control': 'no-store' } }
+ );
+ }
+ if (error instanceof StoredSourceInspectionError) {
+ return c.json({ error: error.message }, error.status);
+ }
+ logger.error('Failed to inspect stored source coverage', error);
+ return c.json({ error: 'Stored source coverage unavailable' }, 500);
+ }
+ });
+ app.post('/api/v2/datasets/stored-eod/inspect', async c => {
+ c.header('Cache-Control', 'no-store');
+ try {
+ return c.json(
+ await inspectStoredSource(container.mongodb, await readBody(c.req.raw), c.req.raw.signal)
+ );
+ } catch (error) {
+ if (c.req.raw.signal.aborted) {
+ return Response.json(
+ { error: 'Stored source inspection cancelled' },
+ { status: 499, headers: { 'Cache-Control': 'no-store' } }
+ );
+ }
+ if (
+ error instanceof StoredSourceInspectionError ||
+ error instanceof DatasetPreparationError
+ ) {
+ return c.json({ error: error.message }, error.status);
+ }
+ logger.error('Failed to inspect stored source quality', error);
+ return c.json({ error: 'Stored source inspection unavailable' }, 500);
+ }
+ });
app.post('/api/v2/datasets/canonical/stored-source', async c => {
c.header('Cache-Control', 'no-store');
try {
diff --git a/apps/stock/web-api/src/services/stored-source-inspection.ts b/apps/stock/web-api/src/services/stored-source-inspection.ts
new file mode 100644
index 00000000..d506bc7d
--- /dev/null
+++ b/apps/stock/web-api/src/services/stored-source-inspection.ts
@@ -0,0 +1,269 @@
+import type { MongoDBClient } from '@stock-bot/services';
+import {
+ storedSourceCoverageSchema,
+ storedSourceInspectionSchema,
+ storedSourceQuerySchema,
+ storedSourceSelectionSchema,
+ type StoredSourceCoverage,
+ type StoredSourceInspection,
+} from '@stock-bot/stock-config/stored-source';
+import { parseInstrumentId } from '@stock-bot/types';
+import {
+ PREPARATION_BATCH_SIZE,
+ preparationCheckpoint,
+} from '../../../orchestrator/src/data/preparation';
+
+const collections = {
+ '1m': 'eodIntraday1M',
+ '5m': 'eodIntraday5M',
+ '1h': 'eodIntraday1H',
+} as const;
+type Store = Pick;
+type Row = Record;
+type Code = StoredSourceInspection['issues'][number]['code'];
+export class StoredSourceInspectionError extends Error {
+ constructor(
+ readonly status: 400 | 503,
+ message: string
+ ) {
+ super(message);
+ }
+}
+function required(store: Store | null | undefined): Store {
+ if (!store) {
+ throw new StoredSourceInspectionError(503, 'Stored EOD data is unavailable');
+ }
+ return store;
+}
+function timestamp(value: unknown): number | null {
+ return typeof value === 'number' &&
+ Number.isSafeInteger(value) &&
+ value >= 0 &&
+ Number.isSafeInteger(value * 1000) &&
+ Number.isFinite(new Date(value * 1000).getTime())
+ ? value * 1000
+ : null;
+}
+
+/** Inspect one indexed source series; first/last rows do not establish complete sessions. */
+export async function storedSourceCoverage(
+ store: Store | null | undefined,
+ input: unknown,
+ signal: AbortSignal
+): Promise {
+ signal.throwIfAborted();
+ const parsed = storedSourceSelectionSchema.safeParse(input);
+ if (!parsed.success) {
+ throw new StoredSourceInspectionError(
+ 400,
+ 'Select one qualified instrument and supported timeframe'
+ );
+ }
+ const query = parsed.data;
+ const groups = await required(store).aggregate(collections[query.interval], [
+ { $match: { eodSearchCode: query.instrumentId } },
+ {
+ $project: {
+ _id: 0,
+ validTimestamp: {
+ $cond: [
+ // Decimal128 remains an object in the JS reader. Only these BSON types
+ // can become its finite integer Unix-seconds number.
+ { $in: [{ $type: '$timestamp' }, ['double', 'int', 'long']] },
+ {
+ $cond: [
+ {
+ $and: [
+ { $gte: ['$timestamp', 0] },
+ { $lte: ['$timestamp', 8_640_000_000_000] },
+ { $eq: ['$timestamp', { $trunc: '$timestamp' }] },
+ ],
+ },
+ '$timestamp',
+ null,
+ ],
+ },
+ null,
+ ],
+ },
+ },
+ },
+ {
+ $group: {
+ _id: null,
+ rowCount: { $sum: 1 },
+ firstTimestamp: { $min: '$validTimestamp' },
+ lastTimestamp: { $max: '$validTimestamp' },
+ invalidTimestampRows: { $sum: { $cond: [{ $eq: ['$validTimestamp', null] }, 1, 0] } },
+ },
+ },
+ ]);
+ signal.throwIfAborted();
+ const series = groups.map(group => {
+ if (
+ !Number.isSafeInteger(group.rowCount) ||
+ Number(group.rowCount) < 0 ||
+ !Number.isSafeInteger(group.invalidTimestampRows) ||
+ Number(group.invalidTimestampRows) < 0 ||
+ Number(group.invalidTimestampRows) > Number(group.rowCount)
+ ) {
+ throw new Error('Invalid stored source coverage');
+ }
+ return {
+ ...query,
+ rowCount: Number(group.rowCount),
+ firstTimestamp: timestamp(group.firstTimestamp),
+ lastTimestamp: timestamp(group.lastTimestamp),
+ invalidTimestampRows: Number(group.invalidTimestampRows),
+ };
+ });
+ return storedSourceCoverageSchema.parse({
+ version: 'stored-eod-coverage/v1',
+ observedAt: Date.now(),
+ query,
+ series,
+ });
+}
+
+/** Explain raw field problems without changing rows or making financial eligibility decisions. */
+export async function inspectStoredSource(
+ store: Store | null | undefined,
+ input: unknown,
+ signal: AbortSignal
+): Promise {
+ signal.throwIfAborted();
+ const parsed = storedSourceQuerySchema.safeParse(input);
+ if (!parsed.success) {
+ throw new StoredSourceInspectionError(
+ 400,
+ 'Select an instrument, supported timeframe and valid UTC start/end range'
+ );
+ }
+ const query = parsed.data;
+ const identity = parseInstrumentId(query.instrumentId);
+ const rows = await required(store).find(
+ collections[query.interval],
+ {
+ eodSearchCode: identity.id,
+ timestamp: { $gte: query.start / 1000, $lt: query.end / 1000 },
+ },
+ {
+ sort: { timestamp: 1 },
+ projection: {
+ _id: 0,
+ eodSearchCode: 1,
+ symbol: 1,
+ exchange: 1,
+ timestamp: 1,
+ open: 1,
+ high: 1,
+ low: 1,
+ close: 1,
+ volume: 1,
+ },
+ }
+ );
+ signal.throwIfAborted();
+ const bad = new Set();
+ const issues = new Map }>();
+ const byTimestamp = new Map();
+ const instants: Array = [];
+ const issue = (code: Code, index: number, at: number | null) => {
+ bad.add(index);
+ const existing = issues.get(code) ?? { rowCount: 0, timestamps: [] };
+ existing.rowCount++;
+ existing.timestamps.push(at);
+ issues.set(code, existing);
+ };
+ const numeric = (value: unknown) =>
+ typeof value === 'number'
+ ? value
+ : typeof value === 'string' && value.trim()
+ ? Number(value)
+ : NaN;
+ let nullVolumeRows = 0;
+ for (const [index, row] of rows.entries()) {
+ const at = timestamp(row.timestamp);
+ instants.push(at);
+ if (
+ row.eodSearchCode !== identity.id ||
+ row.symbol !== identity.symbol ||
+ row.exchange !== identity.exchange
+ ) {
+ issue('identity-mismatch', index, at);
+ }
+ if (at === null) {
+ issue('invalid-timestamp', index, at);
+ } else {
+ if (at < query.start || at >= query.end) {
+ issue('outside-range', index, at);
+ }
+ const same = byTimestamp.get(at) ?? [];
+ same.push(index);
+ byTimestamp.set(at, same);
+ }
+ const open = numeric(row.open);
+ const high = numeric(row.high);
+ const low = numeric(row.low);
+ const close = numeric(row.close);
+ if (
+ ![open, high, low, close].every(
+ value => typeof value === 'number' && Number.isFinite(value) && value > 0
+ ) ||
+ high < Math.max(open, close) ||
+ low > Math.min(open, close)
+ ) {
+ issue('invalid-prices', index, at);
+ }
+ if (row.volume === null || row.volume === undefined) {
+ nullVolumeRows++;
+ issue('null-volume', index, at);
+ } else if (!Number.isFinite(numeric(row.volume)) || numeric(row.volume) < 0) {
+ issue('invalid-volume', index, at);
+ }
+ if ((index + 1) % PREPARATION_BATCH_SIZE === 0) {
+ await preparationCheckpoint(signal);
+ }
+ }
+ let duplicateRows = 0;
+ for (const [at, indices] of byTimestamp) {
+ if (indices.length > 1) {
+ duplicateRows += indices.length - 1;
+ for (const index of indices) {
+ issue('duplicate-timestamp', index, at);
+ }
+ }
+ }
+ const days = new Map();
+ let firstTimestamp: number | null = null,
+ lastTimestamp: number | null = null;
+ for (let index = 0; index < instants.length; index++) {
+ const at = instants[index];
+ if (at === null || at === undefined) {
+ continue;
+ }
+ firstTimestamp = firstTimestamp === null ? at : Math.min(firstTimestamp, at);
+ lastTimestamp = lastTimestamp === null ? at : Math.max(lastTimestamp, at);
+ const date = new Date(at).toISOString().slice(0, 10);
+ const day = days.get(date) ?? { date, rowCount: 0, invalidRows: 0 };
+ day.rowCount++;
+ if (bad.has(index)) {
+ day.invalidRows++;
+ }
+ days.set(date, day);
+ }
+ signal.throwIfAborted();
+ return storedSourceInspectionSchema.parse({
+ version: 'stored-eod-inspection/v1',
+ observedAt: Date.now(),
+ query,
+ rowCount: rows.length,
+ invalidRows: bad.size,
+ nullVolumeRows,
+ duplicateRows,
+ firstTimestamp,
+ lastTimestamp,
+ days: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)),
+ issues: [...issues].map(([code, detail]) => ({ code, ...detail })),
+ });
+}
diff --git a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx
index 7a776167..2c0d23aa 100644
--- a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx
+++ b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx
@@ -3,6 +3,7 @@ import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canoni
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
import { backtestApiV2, DatasetPreparationRequestError } from '../services/backtestApiV2';
+import { StoredSourceInspector } from './StoredSourceInspector';
export interface DatasetPreparationState {
busy: boolean;
@@ -268,6 +269,9 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
uses that captured snapshot without querying storage again.
)}
+ {mode === 'stored-eod' && (
+
+ )}