Share backtest request contracts and isolate stored result mapping
This commit is contained in:
parent
007e35c747
commit
420c47704e
21 changed files with 777 additions and 244 deletions
13
README.md
13
README.md
|
|
@ -457,6 +457,14 @@ backend, normalizes the result, and commits the result and terminal status in on
|
||||||
Completion events are published only after that commit. Progress cannot revive a terminal
|
Completion events are published only after that commit. Progress cannot revive a terminal
|
||||||
run, duplicate claims are rejected, and unsupported controls do not change persisted state.
|
run, duplicate claims are rejected, and unsupported controls do not change persisted state.
|
||||||
|
|
||||||
|
`@stock-bot/stock-config/backtest` owns the pure execution request schema, parsing and
|
||||||
|
defaults used by API definition snapshots, the runner and both backends. The subpath
|
||||||
|
loads no configuration manager or infrastructure. API date labels are translated to UTC
|
||||||
|
before execution; direct execution requests keep their existing full-ISO timestamp shape.
|
||||||
|
Strategy-specific parameter validation remains with each execution backend. Invalid
|
||||||
|
execution settings now fail before a definition/run write rather than being queued for
|
||||||
|
later rejection. Existing schema imports from the orchestrator remain compatibility exports.
|
||||||
|
|
||||||
`@stock-bot/types` exports the shared `BacktestRunResult` used by the runner, API, and UI.
|
`@stock-bot/types` exports the shared `BacktestRunResult` used by the runner, API, and UI.
|
||||||
Return, win-rate, drawdown, and chart-analytics percentages use fractions (`0.10` means 10%).
|
Return, win-rate, drawdown, and chart-analytics percentages use fractions (`0.10` means 10%).
|
||||||
Trade records identify their granularity with `kind: 'fill' | 'closed'`; `totalTrades` counts
|
Trade records identify their granularity with `kind: 'fill' | 'closed'`; `totalTrades` counts
|
||||||
|
|
@ -478,6 +486,11 @@ be reconciled before applying that index. Historical rows without snapshots rema
|
||||||
and are explicitly marked `legacy`; their configuration is reconstructed from the definition.
|
and are explicitly marked `legacy`; their configuration is reconstructed from the definition.
|
||||||
New executions require PostgreSQL; there is no implicit in-memory production repository.
|
New executions require PostgreSQL; there is no implicit in-memory production repository.
|
||||||
|
|
||||||
|
Stored-result compatibility conversion lives in the web API's pure `backtest-result.ts`
|
||||||
|
mapper, separate from SQL and run control. Current snapshots are returned without unit
|
||||||
|
conversion; pre-contract native/TypeScript rows retain their existing legacy unit rules.
|
||||||
|
Reading a result never rewrites the stored history or recalculates its metrics.
|
||||||
|
|
||||||
Native execution uses a disposable **worker process**, not the HTTP thread. A small
|
Native execution uses a disposable **worker process**, not the HTTP thread. A small
|
||||||
`BacktestExecutionEngine` port separates the runner from both implementations. The parent
|
`BacktestExecutionEngine` port separates the runner from both implementations. The parent
|
||||||
owns storage reads and persistence; only serializable configuration, bars, progress, and
|
owns storage reads and persistence; only serializable configuration, bars, progress, and
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,16 @@
|
||||||
"description": "Stock trading bot configuration",
|
"description": "Stock trading bot configuration",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"types": "dist/index.d.ts",
|
"types": "dist/index.d.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"default": "./dist/index.js"
|
||||||
|
},
|
||||||
|
"./backtest": {
|
||||||
|
"types": "./dist/contracts/backtest.d.ts",
|
||||||
|
"default": "./dist/contracts/backtest.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"clean": "rm -rf dist",
|
"clean": "rm -rf dist",
|
||||||
|
|
@ -12,6 +22,7 @@
|
||||||
"lint": "eslint src --ext .ts"
|
"lint": "eslint src --ext .ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@stock-bot/types": "workspace:*",
|
||||||
"@stock-bot/config": "*",
|
"@stock-bot/config": "*",
|
||||||
"@stock-bot/logger": "*",
|
"@stock-bot/logger": "*",
|
||||||
"zod": "^3.22.4"
|
"zod": "^3.22.4"
|
||||||
|
|
|
||||||
149
apps/stock/config/src/contracts/backtest.ts
Normal file
149
apps/stock/config/src/contracts/backtest.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
import {
|
||||||
|
HistoricalDataRequestError,
|
||||||
|
parseInstrumentId,
|
||||||
|
validateHistoricalDataRequest,
|
||||||
|
} from '@stock-bot/types';
|
||||||
|
|
||||||
|
/** Pure execution configuration; importing this subpath starts no configuration services. */
|
||||||
|
export const BACKTEST_DEFAULTS = Object.freeze({
|
||||||
|
commission: 0.001,
|
||||||
|
slippage: 0.0001,
|
||||||
|
dataFrequency: '1d' as const,
|
||||||
|
});
|
||||||
|
export const instrumentIdSchema = z.string().refine(id => {
|
||||||
|
try {
|
||||||
|
parseInstrumentId(id);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, 'Use an exchange-qualified instrument ID, for example AAPL.US');
|
||||||
|
export const historicalDataPolicySchema = z
|
||||||
|
.object({
|
||||||
|
adjustment: z.enum(['raw', 'provider-adjusted']),
|
||||||
|
timestamp: z.enum(['utc-session-date', 'utc-instant']),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
||||||
|
export const RiskLimitsSchema = z.object({
|
||||||
|
maxPositionSize: z.number().finite().positive(),
|
||||||
|
maxOrderSize: z.number().finite().positive(),
|
||||||
|
maxDailyLoss: z.number().finite().positive(),
|
||||||
|
maxGrossExposure: z.number().finite().positive(),
|
||||||
|
maxSymbolExposure: z.number().finite().positive(),
|
||||||
|
});
|
||||||
|
export const BacktestConfigSchema = z.object({
|
||||||
|
mode: z.literal('backtest'),
|
||||||
|
name: z.string().optional(),
|
||||||
|
runId: z.string().uuid().optional(),
|
||||||
|
backtestId: z.string().uuid().optional(),
|
||||||
|
config: z.record(z.unknown()).optional(),
|
||||||
|
startDate: z.string().datetime(),
|
||||||
|
endDate: z.string().datetime(),
|
||||||
|
symbols: z
|
||||||
|
.array(instrumentIdSchema)
|
||||||
|
.min(1)
|
||||||
|
.refine(ids => new Set(ids).size === ids.length, 'Duplicate instruments'),
|
||||||
|
dataPolicy: historicalDataPolicySchema.optional(),
|
||||||
|
datasetHash: datasetHashSchema.optional(),
|
||||||
|
initialCapital: z.number().finite().positive(),
|
||||||
|
dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||||
|
strategy: z.string().min(1),
|
||||||
|
strategies: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
name: z.string(),
|
||||||
|
enabled: z.boolean().default(true),
|
||||||
|
config: z.record(z.unknown()).optional(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
commission: z.number().finite().min(0).max(0.1).optional(),
|
||||||
|
slippage: z.number().finite().min(0).max(0.1).optional(),
|
||||||
|
fillModel: z
|
||||||
|
.object({
|
||||||
|
slippage: z.enum(['zero', 'conservative', 'realistic', 'aggressive']),
|
||||||
|
marketImpact: z.boolean(),
|
||||||
|
partialFills: z.boolean(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
speed: z.enum(['max', 'realtime', '2x', '5x', '10x']).default('max'),
|
||||||
|
riskLimits: RiskLimitsSchema.optional(),
|
||||||
|
});
|
||||||
|
export type BacktestConfig = z.infer<typeof BacktestConfigSchema>;
|
||||||
|
|
||||||
|
/** One acceptance/defaulting rule for API snapshots, direct execution and queued replay. */
|
||||||
|
export function parseBacktestRequest(input: unknown): BacktestConfig {
|
||||||
|
const config = BacktestConfigSchema.parse(input);
|
||||||
|
validateHistoricalDataRequest(config);
|
||||||
|
config.commission ??= BACKTEST_DEFAULTS.commission;
|
||||||
|
config.slippage ??= BACKTEST_DEFAULTS.slippage;
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isBacktestRequestError(error: unknown): error is Error {
|
||||||
|
return error instanceof z.ZodError || error instanceof HistoricalDataRequestError;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BacktestDefinitionInput {
|
||||||
|
name: string;
|
||||||
|
strategy: string;
|
||||||
|
symbols: string[];
|
||||||
|
startDate: string | Date;
|
||||||
|
endDate: string | Date;
|
||||||
|
initialCapital: number;
|
||||||
|
config?: Record<string, unknown> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Translate the existing API definition shape without changing its stored parameter bag. */
|
||||||
|
export function backtestRequestFromDefinition(
|
||||||
|
definition: BacktestDefinitionInput,
|
||||||
|
identity: { runId?: string; backtestId?: string; speedMultiplier?: number | null } = {}
|
||||||
|
): BacktestConfig {
|
||||||
|
const parameters = definition.config ?? {};
|
||||||
|
const historical = {
|
||||||
|
symbols: definition.symbols,
|
||||||
|
startDate:
|
||||||
|
definition.startDate instanceof Date
|
||||||
|
? definition.startDate.toISOString()
|
||||||
|
: definition.startDate,
|
||||||
|
endDate:
|
||||||
|
definition.endDate instanceof Date ? definition.endDate.toISOString() : definition.endDate,
|
||||||
|
dataFrequency: parameters.dataFrequency ?? BACKTEST_DEFAULTS.dataFrequency,
|
||||||
|
dataPolicy: parameters.dataPolicy,
|
||||||
|
datasetHash: parameters.datasetHash,
|
||||||
|
};
|
||||||
|
// Validate timezone/session intent before canonicalizing date strings to UTC.
|
||||||
|
validateHistoricalDataRequest(historical);
|
||||||
|
const multiplier = identity.speedMultiplier ?? null;
|
||||||
|
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||||
|
throw new HistoricalDataRequestError('Speed multiplier must be positive or null');
|
||||||
|
}
|
||||||
|
return parseBacktestRequest({
|
||||||
|
...historical,
|
||||||
|
runId: identity.runId,
|
||||||
|
backtestId: identity.backtestId,
|
||||||
|
name: definition.name,
|
||||||
|
mode: 'backtest',
|
||||||
|
strategy: definition.strategy,
|
||||||
|
startDate: new Date(historical.startDate).toISOString(),
|
||||||
|
endDate: new Date(historical.endDate).toISOString(),
|
||||||
|
initialCapital: definition.initialCapital,
|
||||||
|
config: parameters,
|
||||||
|
riskLimits: parameters.riskLimits,
|
||||||
|
// Definition APIs historically treat null fees as unset; the parser owns defaults.
|
||||||
|
commission: parameters.commission ?? undefined,
|
||||||
|
slippage: parameters.slippage ?? undefined,
|
||||||
|
speed:
|
||||||
|
multiplier === null
|
||||||
|
? 'max'
|
||||||
|
: multiplier >= 10
|
||||||
|
? '10x'
|
||||||
|
: multiplier >= 5
|
||||||
|
? '5x'
|
||||||
|
: multiplier >= 2
|
||||||
|
? '2x'
|
||||||
|
: 'realtime',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -9,5 +9,5 @@
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"],
|
"include": ["src/**/*"],
|
||||||
"exclude": ["node_modules", "dist", "**/*.test.ts"],
|
"exclude": ["node_modules", "dist", "**/*.test.ts"],
|
||||||
"references": [{ "path": "../../../libs/core/config" }]
|
"references": [{ "path": "../../../libs/core/config" }, { "path": "../../../libs/core/types" }]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,13 @@
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { defined } from '@stock-bot/invariants';
|
import { defined } from '@stock-bot/invariants';
|
||||||
|
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||||
import { DataManager } from '../data/DataManager';
|
import { DataManager } from '../data/DataManager';
|
||||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||||
import { amount, decimal } from '../execution/model';
|
import { amount, decimal } from '../execution/model';
|
||||||
import type { StorageService } from '../services/StorageService';
|
import type { StorageService } from '../services/StorageService';
|
||||||
import type { StrategyManager } from '../strategies/StrategyManager';
|
import type { StrategyManager } from '../strategies/StrategyManager';
|
||||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
import type { BacktestConfig, OrchestratorServices } from '../types';
|
||||||
import { BacktestMarket } from './BacktestMarket';
|
import { BacktestMarket } from './BacktestMarket';
|
||||||
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
|
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
|
||||||
import { BacktestReport } from './BacktestReport';
|
import { BacktestReport } from './BacktestReport';
|
||||||
|
|
@ -39,7 +40,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
||||||
this.closing ? 'Backtest engine is shutting down' : 'Backtest already running'
|
this.closing ? 'Backtest engine is shutting down' : 'Backtest already running'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const config = BacktestConfigSchema.parse(input);
|
const config = parseBacktestRequest(input);
|
||||||
const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]);
|
const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]);
|
||||||
this.playback = playback;
|
this.playback = playback;
|
||||||
this.completedReport = undefined;
|
this.completedReport = undefined;
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { z } from 'zod';
|
|
||||||
import type { Logger } from '@stock-bot/services';
|
import type { Logger } from '@stock-bot/services';
|
||||||
|
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||||
import { validateHistoricalDataRequest } from '@stock-bot/types';
|
import { prepareDataset } from '../data/historical-dataset';
|
||||||
import { dataPolicy, prepareDataset } from '../data/historical-dataset';
|
import type { BacktestConfig } from '../types';
|
||||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
|
||||||
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
||||||
import { normalizeBacktestResult } from './result';
|
import { normalizeBacktestResult } from './result';
|
||||||
import {
|
import {
|
||||||
|
|
@ -14,17 +13,7 @@ import {
|
||||||
type RunClaim,
|
type RunClaim,
|
||||||
} from './run-repository';
|
} from './run-repository';
|
||||||
|
|
||||||
export function parseBacktestRequest(input: unknown): BacktestConfig {
|
export { parseBacktestRequest };
|
||||||
const config = BacktestConfigSchema.parse(input);
|
|
||||||
validateHistoricalDataRequest(config);
|
|
||||||
dataPolicy(config);
|
|
||||||
if (new Date(config.endDate) <= new Date(config.startDate)) {
|
|
||||||
throw new z.ZodError([
|
|
||||||
{ code: 'custom', path: ['endDate'], message: 'Backtest endDate must be after startDate' },
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
return config;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One application workflow for HTTP, jobs, and both execution backends. */
|
/** One application workflow for HTTP, jobs, and both execution backends. */
|
||||||
export class BacktestRunner extends EventEmitter {
|
export class BacktestRunner extends EventEmitter {
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,10 @@ import { randomUUID } from 'node:crypto';
|
||||||
import type { PoolClient } from 'pg';
|
import type { PoolClient } from 'pg';
|
||||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||||
import type { PostgresClient } from '@stock-bot/services';
|
import type { PostgresClient } from '@stock-bot/services';
|
||||||
|
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||||
import { prepareDataset } from '../data/historical-dataset';
|
import { prepareDataset } from '../data/historical-dataset';
|
||||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
import type { BacktestConfig } from '../types';
|
||||||
import { BacktestCancelledError } from './execution-engine';
|
import { BacktestCancelledError } from './execution-engine';
|
||||||
import {
|
import {
|
||||||
BacktestConflictError,
|
BacktestConflictError,
|
||||||
|
|
@ -54,7 +55,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||||
if (!run) {
|
if (!run) {
|
||||||
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
|
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
|
||||||
}
|
}
|
||||||
const snapshot = BacktestConfigSchema.parse(run.request_snapshot);
|
const snapshot = parseBacktestRequest(run.request_snapshot);
|
||||||
return {
|
return {
|
||||||
runId: String(run.id),
|
runId: String(run.id),
|
||||||
backtestId: String(run.backtest_id),
|
backtestId: String(run.backtest_id),
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||||
import { StorageService } from '../services/StorageService';
|
import { StorageService } from '../services/StorageService';
|
||||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
import type { BacktestConfig, OrchestratorServices } from '../types';
|
||||||
import {
|
import {
|
||||||
BacktestCancelledError,
|
BacktestCancelledError,
|
||||||
BacktestTimeoutError,
|
BacktestTimeoutError,
|
||||||
|
|
@ -58,7 +59,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
||||||
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
|
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const config = BacktestConfigSchema.parse(input);
|
const config = parseBacktestRequest(input);
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
let finished!: () => void;
|
let finished!: () => void;
|
||||||
this.active = {
|
this.active = {
|
||||||
|
|
|
||||||
|
|
@ -1,21 +1,11 @@
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { parseInstrumentId } from '@stock-bot/types';
|
import {
|
||||||
|
datasetHashSchema,
|
||||||
|
historicalDataPolicySchema,
|
||||||
|
instrumentIdSchema,
|
||||||
|
} from '@stock-bot/stock-config/backtest';
|
||||||
|
|
||||||
export const instrumentIdSchema = z.string().refine(id => {
|
export { datasetHashSchema, historicalDataPolicySchema, instrumentIdSchema };
|
||||||
try {
|
|
||||||
parseInstrumentId(id);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}, 'Use an exchange-qualified instrument ID, for example AAPL.US');
|
|
||||||
export const historicalDataPolicySchema = z
|
|
||||||
.object({
|
|
||||||
adjustment: z.enum(['raw', 'provider-adjusted']),
|
|
||||||
timestamp: z.enum(['utc-session-date', 'utc-instant']),
|
|
||||||
})
|
|
||||||
.strict();
|
|
||||||
export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
|
||||||
const positive = z.number().finite().positive();
|
const positive = z.number().finite().positive();
|
||||||
export const datasetBarSchema = z
|
export const datasetBarSchema = z
|
||||||
.object({
|
.object({
|
||||||
|
|
|
||||||
|
|
@ -1,61 +1,14 @@
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import {
|
import { BacktestConfigSchema, RiskLimitsSchema } from '@stock-bot/stock-config/backtest';
|
||||||
datasetHashSchema,
|
|
||||||
historicalDataPolicySchema,
|
export { BacktestConfigSchema, RiskLimitsSchema };
|
||||||
instrumentIdSchema,
|
export type { BacktestConfig } from '@stock-bot/stock-config/backtest';
|
||||||
} from './contracts/historical';
|
|
||||||
|
|
||||||
// Trading modes
|
// Trading modes
|
||||||
export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']);
|
export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']);
|
||||||
export type TradingMode = z.infer<typeof TradingModeSchema>;
|
export type TradingMode = z.infer<typeof TradingModeSchema>;
|
||||||
export const RiskLimitsSchema = z.object({
|
|
||||||
maxPositionSize: z.number().finite().positive(),
|
|
||||||
maxOrderSize: z.number().finite().positive(),
|
|
||||||
maxDailyLoss: z.number().finite().positive(),
|
|
||||||
maxGrossExposure: z.number().finite().positive(),
|
|
||||||
maxSymbolExposure: z.number().finite().positive(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mode configurations
|
// Mode configurations
|
||||||
export const BacktestConfigSchema = z.object({
|
|
||||||
mode: z.literal('backtest'),
|
|
||||||
name: z.string().optional(),
|
|
||||||
runId: z.string().uuid().optional(),
|
|
||||||
backtestId: z.string().uuid().optional(),
|
|
||||||
config: z.record(z.unknown()).optional(),
|
|
||||||
startDate: z.string().datetime(),
|
|
||||||
endDate: z.string().datetime(),
|
|
||||||
symbols: z
|
|
||||||
.array(instrumentIdSchema)
|
|
||||||
.min(1)
|
|
||||||
.refine(ids => new Set(ids).size === ids.length, 'Duplicate instruments'),
|
|
||||||
dataPolicy: historicalDataPolicySchema.optional(),
|
|
||||||
datasetHash: datasetHashSchema.optional(),
|
|
||||||
initialCapital: z.number().positive(),
|
|
||||||
dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
|
||||||
strategy: z.string(),
|
|
||||||
strategies: z
|
|
||||||
.array(
|
|
||||||
z.object({
|
|
||||||
name: z.string(),
|
|
||||||
enabled: z.boolean().default(true),
|
|
||||||
config: z.record(z.unknown()).optional(),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.optional(),
|
|
||||||
commission: z.number().finite().min(0).max(0.1).optional(),
|
|
||||||
slippage: z.number().finite().min(0).max(0.1).optional(),
|
|
||||||
fillModel: z
|
|
||||||
.object({
|
|
||||||
slippage: z.enum(['zero', 'conservative', 'realistic', 'aggressive']),
|
|
||||||
marketImpact: z.boolean(),
|
|
||||||
partialFills: z.boolean(),
|
|
||||||
})
|
|
||||||
.optional(),
|
|
||||||
speed: z.enum(['max', 'realtime', '2x', '5x', '10x']).default('max'),
|
|
||||||
riskLimits: RiskLimitsSchema.optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const PaperConfigSchema = z.object({
|
export const PaperConfigSchema = z.object({
|
||||||
mode: z.literal('paper'),
|
mode: z.literal('paper'),
|
||||||
startingCapital: z.number().positive(),
|
startingCapital: z.number().positive(),
|
||||||
|
|
@ -92,8 +45,6 @@ export const ModeConfigSchema = z.discriminatedUnion('mode', [
|
||||||
LiveConfigSchema,
|
LiveConfigSchema,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export type BacktestConfig = z.infer<typeof BacktestConfigSchema>;
|
|
||||||
|
|
||||||
export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & {
|
export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & {
|
||||||
custom?: Partial<{
|
custom?: Partial<{
|
||||||
BacktestRunner: import('./backtest/BacktestRunner').BacktestRunner;
|
BacktestRunner: import('./backtest/BacktestRunner').BacktestRunner;
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
import { isBacktestRequestError } from '@stock-bot/stock-config/backtest';
|
||||||
import { BacktestService } from '../services/backtest.service';
|
import { BacktestService } from '../services/backtest.service';
|
||||||
|
|
||||||
const logger = getLogger('backtest-routes');
|
const logger = getLogger('backtest-routes');
|
||||||
|
|
@ -33,7 +33,7 @@ export function createBacktestRoutes(container: IServiceContainer) {
|
||||||
return c.json(backtest, 201);
|
return c.json(backtest, 201);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to create backtest', { error });
|
logger.error('Failed to create backtest', { error });
|
||||||
if (error instanceof HistoricalDataRequestError) {
|
if (isBacktestRequestError(error)) {
|
||||||
return c.json({ error: error.message }, 400);
|
return c.json({ error: error.message }, 400);
|
||||||
}
|
}
|
||||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
import { isBacktestRequestError } from '@stock-bot/stock-config/backtest';
|
||||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||||
|
|
||||||
const logger = getLogger('backtests-v2-routes');
|
const logger = getLogger('backtests-v2-routes');
|
||||||
|
|
@ -44,7 +44,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
||||||
return c.json(backtest, 201);
|
return c.json(backtest, 201);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to create backtest', error);
|
logger.error('Failed to create backtest', error);
|
||||||
if (error instanceof HistoricalDataRequestError) {
|
if (isBacktestRequestError(error)) {
|
||||||
return c.json({ error: error.message }, 400);
|
return c.json({ error: error.message }, 400);
|
||||||
}
|
}
|
||||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||||
|
|
@ -61,7 +61,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
||||||
return c.json(backtest);
|
return c.json(backtest);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to update backtest', error);
|
logger.error('Failed to update backtest', error);
|
||||||
if (error instanceof HistoricalDataRequestError) {
|
if (isBacktestRequestError(error)) {
|
||||||
return c.json({ error: error.message }, 400);
|
return c.json({ error: error.message }, 400);
|
||||||
}
|
}
|
||||||
return c.json({ error: 'Failed to update backtest' }, 500);
|
return c.json({ error: 'Failed to update backtest' }, 500);
|
||||||
|
|
@ -100,7 +100,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
||||||
return c.json(run, 202);
|
return c.json(run, 202);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to create run', error);
|
logger.error('Failed to create run', error);
|
||||||
if (error instanceof HistoricalDataRequestError) {
|
if (isBacktestRequestError(error)) {
|
||||||
return c.json({ error: error.message }, 400);
|
return c.json({ error: error.message }, 400);
|
||||||
}
|
}
|
||||||
return c.json({ error: 'Failed to create run' }, 500);
|
return c.json({ error: 'Failed to create run' }, 500);
|
||||||
|
|
|
||||||
108
apps/stock/web-api/src/services/backtest-result.ts
Normal file
108
apps/stock/web-api/src/services/backtest-result.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
import { BACKTEST_DEFAULTS } from '@stock-bot/stock-config/backtest';
|
||||||
|
import type { BacktestRunResult, BacktestRunTrade } from '@stock-bot/types';
|
||||||
|
|
||||||
|
type StoredTrade = Omit<BacktestRunTrade, 'kind' | 'timestamp' | 'price'> &
|
||||||
|
Partial<Pick<BacktestRunTrade, 'kind' | 'timestamp' | 'price'>>;
|
||||||
|
|
||||||
|
/** Projection returned by the saved-result query, including pre-contract history. */
|
||||||
|
export interface StoredBacktestResult {
|
||||||
|
run_id: string;
|
||||||
|
backtest_id: string;
|
||||||
|
run_status?: BacktestRunResult['status'];
|
||||||
|
completed_at: Date;
|
||||||
|
engine?: BacktestRunResult['engine'] | null;
|
||||||
|
configuration?: BacktestRunResult['config'] | null;
|
||||||
|
metrics: BacktestRunResult['metrics'];
|
||||||
|
analytics?: Partial<BacktestRunResult['analytics']> | null;
|
||||||
|
trades: StoredTrade[];
|
||||||
|
equity_curve: BacktestRunResult['equity'];
|
||||||
|
ohlc_data: BacktestRunResult['ohlcData'];
|
||||||
|
positions: BacktestRunResult['positions'];
|
||||||
|
execution_time: number;
|
||||||
|
strategy: string;
|
||||||
|
symbols: string[];
|
||||||
|
start_date: Date;
|
||||||
|
end_date: Date;
|
||||||
|
initial_capital: string | number;
|
||||||
|
backtest_config?: Record<string, unknown> & {
|
||||||
|
name?: string;
|
||||||
|
commission?: number;
|
||||||
|
slippage?: number;
|
||||||
|
dataFrequency?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read-only compatibility conversion. Stored rows and metric units are never rewritten. */
|
||||||
|
export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunResult {
|
||||||
|
const legacy = !row.configuration;
|
||||||
|
const metrics = { ...row.metrics };
|
||||||
|
const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? 0 };
|
||||||
|
const trades = row.trades.map(trade => {
|
||||||
|
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||||
|
const price = trade.price ?? trade.entryPrice;
|
||||||
|
if (!timestamp || price === undefined) {
|
||||||
|
throw new Error('Malformed stored backtest trade');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...trade,
|
||||||
|
kind: trade.kind ?? (trade.entryDate ? 'closed' : 'fill'),
|
||||||
|
timestamp,
|
||||||
|
price,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
if (legacy) {
|
||||||
|
// Pre-contract backends reported return/win rate in percentage points.
|
||||||
|
metrics.totalReturn /= 100;
|
||||||
|
metrics.winRate /= 100;
|
||||||
|
for (const key of ['annualReturn', 'annualizedReturn']) {
|
||||||
|
if (typeof metrics[key] === 'number') {
|
||||||
|
metrics[key] /= 100;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (trades.some(trade => trade.kind === 'closed')) {
|
||||||
|
metrics.totalTrades = trades.length;
|
||||||
|
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||||
|
}
|
||||||
|
analytics.exposureTime /= 100;
|
||||||
|
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||||
|
...point,
|
||||||
|
value: point.value / 100,
|
||||||
|
}));
|
||||||
|
// Legacy native finalValue marks daily returns already expressed as fractions.
|
||||||
|
if (typeof row.metrics.finalValue !== 'number') {
|
||||||
|
analytics.dailyReturns = analytics.dailyReturns?.map(value => value / 100);
|
||||||
|
}
|
||||||
|
if (analytics.monthlyReturns) {
|
||||||
|
analytics.monthlyReturns = Object.fromEntries(
|
||||||
|
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
runId: row.run_id,
|
||||||
|
backtestId: row.backtest_id,
|
||||||
|
status: row.run_status ?? 'completed',
|
||||||
|
completedAt: row.completed_at.toISOString(),
|
||||||
|
engine: row.engine ?? 'legacy',
|
||||||
|
...(legacy ? { legacy: true } : {}),
|
||||||
|
config: row.configuration ?? {
|
||||||
|
parameters: row.backtest_config ?? {},
|
||||||
|
name: row.backtest_config?.name || 'Backtest',
|
||||||
|
strategy: row.strategy,
|
||||||
|
symbols: row.symbols,
|
||||||
|
startDate: row.start_date.toISOString(),
|
||||||
|
endDate: row.end_date.toISOString(),
|
||||||
|
initialCapital: parseFloat(String(row.initial_capital)),
|
||||||
|
commission: row.backtest_config?.commission ?? BACKTEST_DEFAULTS.commission,
|
||||||
|
slippage: row.backtest_config?.slippage ?? BACKTEST_DEFAULTS.slippage,
|
||||||
|
dataFrequency: row.backtest_config?.dataFrequency || BACKTEST_DEFAULTS.dataFrequency,
|
||||||
|
},
|
||||||
|
metrics,
|
||||||
|
equity: row.equity_curve,
|
||||||
|
ohlcData: row.ohlc_data,
|
||||||
|
trades,
|
||||||
|
positions: row.positions,
|
||||||
|
analytics,
|
||||||
|
executionTime: row.execution_time,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -4,9 +4,11 @@ import { authenticatedServiceFetch } from '@stock-bot/di';
|
||||||
import { at } from '@stock-bot/invariants';
|
import { at } from '@stock-bot/invariants';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||||
import { validateHistoricalDataRequest, type BacktestRunResult } from '@stock-bot/types';
|
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||||
|
import type { BacktestRunResult } from '@stock-bot/types';
|
||||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||||
|
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||||
|
|
||||||
const logger = getLogger('backtest-v2-service');
|
const logger = getLogger('backtest-v2-service');
|
||||||
|
|
||||||
|
|
@ -78,12 +80,7 @@ export class BacktestServiceV2 {
|
||||||
request: BacktestRequest,
|
request: BacktestRequest,
|
||||||
options: { autoStart?: boolean } = {}
|
options: { autoStart?: boolean } = {}
|
||||||
): Promise<Backtest> {
|
): Promise<Backtest> {
|
||||||
validateHistoricalDataRequest({
|
backtestRequestFromDefinition(request);
|
||||||
...request,
|
|
||||||
dataFrequency: request.config?.dataFrequency,
|
|
||||||
dataPolicy: request.config?.dataPolicy,
|
|
||||||
datasetHash: request.config?.datasetHash,
|
|
||||||
});
|
|
||||||
const backtestId = uuidv4();
|
const backtestId = uuidv4();
|
||||||
|
|
||||||
const result = await this.container.postgres.query(
|
const result = await this.container.postgres.query(
|
||||||
|
|
@ -141,14 +138,7 @@ export class BacktestServiceV2 {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const next = { ...existing, ...request };
|
const next = { ...existing, ...request };
|
||||||
validateHistoricalDataRequest({
|
backtestRequestFromDefinition(next);
|
||||||
symbols: next.symbols,
|
|
||||||
startDate: new Date(next.startDate).toISOString(),
|
|
||||||
endDate: new Date(next.endDate).toISOString(),
|
|
||||||
dataFrequency: next.config?.dataFrequency,
|
|
||||||
dataPolicy: next.config?.dataPolicy,
|
|
||||||
datasetHash: next.config?.datasetHash,
|
|
||||||
});
|
|
||||||
const updates: string[] = [];
|
const updates: string[] = [];
|
||||||
const values: unknown[] = [];
|
const values: unknown[] = [];
|
||||||
let paramCount = 1;
|
let paramCount = 1;
|
||||||
|
|
@ -228,62 +218,12 @@ export class BacktestServiceV2 {
|
||||||
throw new Error('Backtest not found');
|
throw new Error('Backtest not found');
|
||||||
}
|
}
|
||||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||||
validateHistoricalDataRequest({
|
|
||||||
symbols: definition.symbols,
|
|
||||||
startDate: definition.startDate.toISOString(),
|
|
||||||
endDate: definition.endDate.toISOString(),
|
|
||||||
dataFrequency: definition.config.dataFrequency,
|
|
||||||
dataPolicy: definition.config.dataPolicy,
|
|
||||||
datasetHash: definition.config.datasetHash,
|
|
||||||
});
|
|
||||||
const multiplier = request.speedMultiplier ?? null;
|
const multiplier = request.speedMultiplier ?? null;
|
||||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
const snapshot = backtestRequestFromDefinition(definition, {
|
||||||
throw new Error('Speed multiplier must be positive or null');
|
|
||||||
}
|
|
||||||
const snapshot = {
|
|
||||||
runId,
|
runId,
|
||||||
backtestId: definition.id,
|
backtestId: definition.id,
|
||||||
name: definition.name,
|
speedMultiplier: multiplier,
|
||||||
mode: 'backtest',
|
});
|
||||||
strategy: definition.strategy,
|
|
||||||
symbols: definition.symbols,
|
|
||||||
startDate: definition.startDate.toISOString(),
|
|
||||||
endDate: definition.endDate.toISOString(),
|
|
||||||
initialCapital: definition.initialCapital,
|
|
||||||
config: definition.config,
|
|
||||||
riskLimits: definition.config.riskLimits,
|
|
||||||
dataPolicy: definition.config.dataPolicy,
|
|
||||||
datasetHash: definition.config.datasetHash,
|
|
||||||
dataFrequency: definition.config.dataFrequency ?? '1d',
|
|
||||||
commission: definition.config.commission ?? 0.001,
|
|
||||||
slippage: definition.config.slippage ?? 0.0001,
|
|
||||||
speed:
|
|
||||||
multiplier === null
|
|
||||||
? 'max'
|
|
||||||
: multiplier >= 10
|
|
||||||
? '10x'
|
|
||||||
: multiplier >= 5
|
|
||||||
? '5x'
|
|
||||||
: multiplier >= 2
|
|
||||||
? '2x'
|
|
||||||
: 'realtime',
|
|
||||||
};
|
|
||||||
if (
|
|
||||||
!snapshot.strategy ||
|
|
||||||
!Array.isArray(snapshot.symbols) ||
|
|
||||||
!snapshot.symbols.length ||
|
|
||||||
snapshot.symbols.some(symbol => typeof symbol !== 'string' || !symbol.length) ||
|
|
||||||
!Number.isFinite(snapshot.initialCapital) ||
|
|
||||||
snapshot.initialCapital <= 0 ||
|
|
||||||
Date.parse(snapshot.endDate) <= Date.parse(snapshot.startDate) ||
|
|
||||||
!['1m', '5m', '15m', '1h', '1d'].includes(String(snapshot.dataFrequency)) ||
|
|
||||||
typeof snapshot.commission !== 'number' ||
|
|
||||||
!Number.isFinite(snapshot.commission) ||
|
|
||||||
typeof snapshot.slippage !== 'number' ||
|
|
||||||
!Number.isFinite(snapshot.slippage)
|
|
||||||
) {
|
|
||||||
throw new Error('Invalid backtest execution configuration');
|
|
||||||
}
|
|
||||||
const result = await client.query(
|
const result = await client.query(
|
||||||
`INSERT INTO runs
|
`INSERT INTO runs
|
||||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
||||||
|
|
@ -381,7 +321,7 @@ export class BacktestServiceV2 {
|
||||||
|
|
||||||
// Get run results
|
// Get run results
|
||||||
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
|
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
|
||||||
const result = await this.container.postgres.query(
|
const result = await this.container.postgres.query<StoredBacktestResult>(
|
||||||
`SELECT
|
`SELECT
|
||||||
br.*,
|
br.*,
|
||||||
r.backtest_id,
|
r.backtest_id,
|
||||||
|
|
@ -403,83 +343,7 @@ export class BacktestServiceV2 {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const row = at(result.rows, 0);
|
return mapStoredBacktestResult(at(result.rows, 0));
|
||||||
const legacy = !row.configuration;
|
|
||||||
const metrics: BacktestRunResult['metrics'] = { ...row.metrics };
|
|
||||||
const analytics: BacktestRunResult['analytics'] = {
|
|
||||||
...row.analytics,
|
|
||||||
exposureTime: row.analytics?.exposureTime ?? 0,
|
|
||||||
};
|
|
||||||
const storedTrades: BacktestRunResult['trades'] = row.trades;
|
|
||||||
const trades = storedTrades.map(trade => {
|
|
||||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
|
||||||
const price = trade.price ?? trade.entryPrice;
|
|
||||||
if (!timestamp || price === undefined) {
|
|
||||||
throw new Error('Malformed stored backtest trade');
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...trade,
|
|
||||||
kind: trade.kind ?? (trade.entryDate ? 'closed' : 'fill'),
|
|
||||||
timestamp,
|
|
||||||
price,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
if (legacy) {
|
|
||||||
// Pre-contract backends both reported return/win rate in percentage points.
|
|
||||||
metrics.totalReturn /= 100;
|
|
||||||
metrics.winRate /= 100;
|
|
||||||
for (const key of ['annualReturn', 'annualizedReturn']) {
|
|
||||||
if (typeof metrics[key] === 'number') {
|
|
||||||
metrics[key] /= 100;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (trades.some(trade => trade.kind === 'closed')) {
|
|
||||||
metrics.totalTrades = trades.length;
|
|
||||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
|
||||||
}
|
|
||||||
analytics.exposureTime /= 100;
|
|
||||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
|
||||||
...point,
|
|
||||||
value: point.value / 100,
|
|
||||||
}));
|
|
||||||
// Older native results identify themselves by finalValue and already use daily fractions.
|
|
||||||
if (typeof row.metrics.finalValue !== 'number') {
|
|
||||||
analytics.dailyReturns = analytics.dailyReturns?.map(value => value / 100);
|
|
||||||
}
|
|
||||||
if (analytics.monthlyReturns) {
|
|
||||||
analytics.monthlyReturns = Object.fromEntries(
|
|
||||||
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
runId: row.run_id,
|
|
||||||
backtestId: row.backtest_id,
|
|
||||||
status: row.run_status ?? 'completed',
|
|
||||||
completedAt: row.completed_at.toISOString(),
|
|
||||||
engine: row.engine ?? 'legacy',
|
|
||||||
...(legacy ? { legacy: true } : {}),
|
|
||||||
config: row.configuration ?? {
|
|
||||||
parameters: row.backtest_config ?? {},
|
|
||||||
name: row.backtest_config?.name || 'Backtest',
|
|
||||||
strategy: row.strategy,
|
|
||||||
symbols: row.symbols,
|
|
||||||
startDate: row.start_date.toISOString(),
|
|
||||||
endDate: row.end_date.toISOString(),
|
|
||||||
initialCapital: parseFloat(row.initial_capital),
|
|
||||||
commission: row.backtest_config?.commission ?? 0.001,
|
|
||||||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
|
||||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
|
||||||
},
|
|
||||||
metrics,
|
|
||||||
equity: row.equity_curve,
|
|
||||||
ohlcData: row.ohlc_data,
|
|
||||||
trades,
|
|
||||||
positions: row.positions,
|
|
||||||
analytics,
|
|
||||||
executionTime: row.execution_time,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Private methods
|
// Private methods
|
||||||
|
|
|
||||||
1
bun.lock
1
bun.lock
|
|
@ -54,6 +54,7 @@
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@stock-bot/config": "*",
|
"@stock-bot/config": "*",
|
||||||
"@stock-bot/logger": "*",
|
"@stock-bot/logger": "*",
|
||||||
|
"@stock-bot/types": "workspace:*",
|
||||||
"zod": "^3.22.4",
|
"zod": "^3.22.4",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
|
||||||
|
|
@ -65,7 +65,7 @@ describe('orchestrator architecture boundaries', () => {
|
||||||
path === 'backtest/native-worker-protocol.ts'
|
path === 'backtest/native-worker-protocol.ts'
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
for (const specifier of imports.get(file) ?? []) {
|
for (const specifier of imports.get(file) ?? []) {
|
||||||
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types'].includes(specifier)).toBe(
|
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types', '@stock-bot/stock-config/backtest'].includes(specifier)).toBe(
|
||||||
true
|
true
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -73,6 +73,18 @@ describe('orchestrator architecture boundaries', () => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('the shared backtest contract loads no configuration manager, services or application runtime', async () => {
|
||||||
|
const entry = resolve(root, '../../config/src/contracts/backtest.ts');
|
||||||
|
expect(runtimeImports(entry).sort()).toEqual(['@stock-bot/types', 'zod']);
|
||||||
|
const bundle = await Bun.build({ entrypoints: [entry], target: 'browser', write: false });
|
||||||
|
expect(bundle.success).toBe(true);
|
||||||
|
const code = await bundle.outputs[0]?.text();
|
||||||
|
expect(code).toBeDefined();
|
||||||
|
expect(code).not.toContain('config-instance');
|
||||||
|
expect(code).not.toContain('PostgresClient');
|
||||||
|
expect(code).not.toContain('engine.node');
|
||||||
|
});
|
||||||
|
|
||||||
it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => {
|
it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => {
|
||||||
for (const entry of [
|
for (const entry of [
|
||||||
'execution/SimulationExecution.ts',
|
'execution/SimulationExecution.ts',
|
||||||
|
|
|
||||||
194
test/integration/backtest-request-contract.test.ts
Normal file
194
test/integration/backtest-request-contract.test.ts
Normal file
|
|
@ -0,0 +1,194 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import {
|
||||||
|
BACKTEST_DEFAULTS,
|
||||||
|
BacktestConfigSchema,
|
||||||
|
backtestRequestFromDefinition,
|
||||||
|
isBacktestRequestError,
|
||||||
|
parseBacktestRequest,
|
||||||
|
} from '@stock-bot/stock-config/backtest';
|
||||||
|
import { parseBacktestRequest as runnerParser } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||||
|
import { BacktestConfigSchema as orchestratorSchema } from '../../apps/stock/orchestrator/src/types';
|
||||||
|
|
||||||
|
const request = {
|
||||||
|
mode: 'backtest',
|
||||||
|
name: 'Contract fixture',
|
||||||
|
strategy: 'sma-crossover',
|
||||||
|
symbols: ['A.US'],
|
||||||
|
startDate: '2024-01-01T00:00:00.000Z',
|
||||||
|
endDate: '2024-03-01T00:00:00.000Z',
|
||||||
|
initialCapital: 10000,
|
||||||
|
dataFrequency: '1d',
|
||||||
|
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||||
|
};
|
||||||
|
const definition = {
|
||||||
|
name: request.name,
|
||||||
|
strategy: request.strategy,
|
||||||
|
symbols: request.symbols,
|
||||||
|
startDate: request.startDate,
|
||||||
|
endDate: request.endDate,
|
||||||
|
initialCapital: request.initialCapital,
|
||||||
|
config: request.config,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('shared backtest request contract', () => {
|
||||||
|
test('runner and legacy schema exports delegate to the same pure contract', () => {
|
||||||
|
expect(orchestratorSchema).toBe(BacktestConfigSchema);
|
||||||
|
expect(runnerParser).toBe(parseBacktestRequest);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('definition snapshots and direct requests share defaults without mutating their inputs', () => {
|
||||||
|
const input = structuredClone(request);
|
||||||
|
const parsed = parseBacktestRequest(input);
|
||||||
|
expect(JSON.parse(JSON.stringify(backtestRequestFromDefinition(definition)))).toEqual(parsed);
|
||||||
|
expect(parsed).toMatchObject({
|
||||||
|
commission: BACKTEST_DEFAULTS.commission,
|
||||||
|
slippage: BACKTEST_DEFAULTS.slippage,
|
||||||
|
dataFrequency: BACKTEST_DEFAULTS.dataFrequency,
|
||||||
|
speed: 'max',
|
||||||
|
});
|
||||||
|
expect(input).toEqual(request);
|
||||||
|
expect(parsed).not.toBe(input);
|
||||||
|
expect(definition.config).toEqual({ fastPeriod: 3, slowPeriod: 7 });
|
||||||
|
expect(
|
||||||
|
backtestRequestFromDefinition({ ...definition, config: { commission: null, slippage: null } })
|
||||||
|
).toMatchObject({
|
||||||
|
commission: BACKTEST_DEFAULTS.commission,
|
||||||
|
slippage: BACKTEST_DEFAULTS.slippage,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('zero costs, explicit policies, replay identity and risk settings survive normalization', () => {
|
||||||
|
const riskLimits = {
|
||||||
|
maxPositionSize: 100,
|
||||||
|
maxOrderSize: 100,
|
||||||
|
maxDailyLoss: 100,
|
||||||
|
maxGrossExposure: 1000,
|
||||||
|
maxSymbolExposure: 500,
|
||||||
|
};
|
||||||
|
const policy = { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' };
|
||||||
|
const runId = '00000000-0000-4000-8000-000000000001';
|
||||||
|
const backtestId = '00000000-0000-4000-8000-000000000002';
|
||||||
|
const config = {
|
||||||
|
...definition.config,
|
||||||
|
commission: 0,
|
||||||
|
slippage: 0,
|
||||||
|
dataFrequency: '1d',
|
||||||
|
dataPolicy: policy,
|
||||||
|
datasetHash: 'f'.repeat(64),
|
||||||
|
riskLimits,
|
||||||
|
};
|
||||||
|
const snapshot = backtestRequestFromDefinition(
|
||||||
|
{ ...definition, config },
|
||||||
|
{ runId, backtestId }
|
||||||
|
);
|
||||||
|
expect(snapshot).toMatchObject({
|
||||||
|
runId,
|
||||||
|
backtestId,
|
||||||
|
commission: 0,
|
||||||
|
slippage: 0,
|
||||||
|
dataPolicy: policy,
|
||||||
|
datasetHash: config.datasetHash,
|
||||||
|
riskLimits,
|
||||||
|
config,
|
||||||
|
});
|
||||||
|
expect(parseBacktestRequest(JSON.parse(JSON.stringify(snapshot)))).toEqual(snapshot);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('API date labels and UTC-offset ranges canonicalize without guessing timezone or sessions', () => {
|
||||||
|
expect(
|
||||||
|
backtestRequestFromDefinition({
|
||||||
|
...definition,
|
||||||
|
startDate: '2024-01-01',
|
||||||
|
endDate: '2024-03-01',
|
||||||
|
}).startDate
|
||||||
|
).toBe(request.startDate);
|
||||||
|
expect(
|
||||||
|
backtestRequestFromDefinition({
|
||||||
|
...definition,
|
||||||
|
startDate: new Date(request.startDate),
|
||||||
|
endDate: new Date(request.endDate),
|
||||||
|
}).startDate
|
||||||
|
).toBe(request.startDate);
|
||||||
|
const intraday = backtestRequestFromDefinition({
|
||||||
|
...definition,
|
||||||
|
startDate: '2024-01-01T09:00:00-05:00',
|
||||||
|
endDate: '2024-01-01T10:00:00-05:00',
|
||||||
|
config: { dataFrequency: '1m' },
|
||||||
|
});
|
||||||
|
expect(intraday.startDate).toBe('2024-01-01T14:00:00.000Z');
|
||||||
|
expect(() =>
|
||||||
|
backtestRequestFromDefinition({ ...definition, startDate: '2024-01-01T00:00:00' })
|
||||||
|
).toThrow('UTC offset');
|
||||||
|
expect(() =>
|
||||||
|
backtestRequestFromDefinition({ ...definition, startDate: '2024-01-01T01:00:00Z' })
|
||||||
|
).toThrow('UTC midnight');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('API speed multipliers preserve existing buckets and reject invalid values', () => {
|
||||||
|
for (const [speedMultiplier, speed] of [
|
||||||
|
[null, 'max'],
|
||||||
|
[0.5, 'realtime'],
|
||||||
|
[1, 'realtime'],
|
||||||
|
[2, '2x'],
|
||||||
|
[4, '2x'],
|
||||||
|
[5, '5x'],
|
||||||
|
[9, '5x'],
|
||||||
|
[10, '10x'],
|
||||||
|
[100, '10x'],
|
||||||
|
] as const) {
|
||||||
|
expect(backtestRequestFromDefinition(definition, { speedMultiplier }).speed).toBe(speed);
|
||||||
|
}
|
||||||
|
for (const speedMultiplier of [0, -1, NaN, Infinity]) {
|
||||||
|
expect(() => backtestRequestFromDefinition(definition, { speedMultiplier })).toThrow(
|
||||||
|
'Speed multiplier'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('direct and definition paths reject the same invalid execution settings', () => {
|
||||||
|
for (const config of [
|
||||||
|
{ commission: -0.1 },
|
||||||
|
{ slippage: 0.11 },
|
||||||
|
{ commission: '0.01' },
|
||||||
|
{ slippage: Infinity },
|
||||||
|
{ riskLimits: { maxDailyLoss: -1 } },
|
||||||
|
{ datasetHash: 'invalid' },
|
||||||
|
{ dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } },
|
||||||
|
{ dataFrequency: '2h' },
|
||||||
|
]) {
|
||||||
|
expect(() => backtestRequestFromDefinition({ ...definition, config })).toThrow();
|
||||||
|
expect(() => parseBacktestRequest({ ...request, ...config })).toThrow();
|
||||||
|
}
|
||||||
|
for (const fields of [
|
||||||
|
{ symbols: ['A'] },
|
||||||
|
{ symbols: ['A.US', 'A.US'] },
|
||||||
|
{ initialCapital: Infinity },
|
||||||
|
{ initialCapital: 0 },
|
||||||
|
{ strategy: '' },
|
||||||
|
{ endDate: request.startDate },
|
||||||
|
]) {
|
||||||
|
expect(() => backtestRequestFromDefinition({ ...definition, ...fields })).toThrow();
|
||||||
|
expect(() => parseBacktestRequest({ ...request, ...fields })).toThrow();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('strategy extension fields and direct multi-strategy requests remain intact', () => {
|
||||||
|
const strategies = [{ name: 'custom', config: { feature: 'extension' } }];
|
||||||
|
expect(parseBacktestRequest({ ...request, strategies }).strategies).toEqual([
|
||||||
|
{ name: 'custom', enabled: true, config: { feature: 'extension' } },
|
||||||
|
]);
|
||||||
|
const config = { featureWindow: 27, customFeature: { version: 2 }, commission: 0 };
|
||||||
|
expect(
|
||||||
|
backtestRequestFromDefinition({ ...definition, strategy: 'custom', config }).config
|
||||||
|
).toEqual(config);
|
||||||
|
expect(isBacktestRequestError(new Error('database failure'))).toBe(false);
|
||||||
|
for (const input of [{}, { ...request, symbols: ['A'] }]) {
|
||||||
|
try {
|
||||||
|
parseBacktestRequest(input);
|
||||||
|
throw new Error('unexpected acceptance');
|
||||||
|
} catch (error) {
|
||||||
|
expect(isBacktestRequestError(error)).toBe(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
193
test/integration/backtest-result-mapping.test.ts
Normal file
193
test/integration/backtest-result-mapping.test.ts
Normal file
|
|
@ -0,0 +1,193 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import {
|
||||||
|
mapStoredBacktestResult,
|
||||||
|
type StoredBacktestResult,
|
||||||
|
} from '../../apps/stock/web-api/src/services/backtest-result';
|
||||||
|
|
||||||
|
function fixture(): StoredBacktestResult {
|
||||||
|
return {
|
||||||
|
run_id: 'run',
|
||||||
|
backtest_id: 'definition',
|
||||||
|
completed_at: new Date('2024-03-01T00:00:00Z'),
|
||||||
|
strategy: 'sma-crossover',
|
||||||
|
symbols: ['A.US'],
|
||||||
|
start_date: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
end_date: new Date('2024-03-01T00:00:00Z'),
|
||||||
|
initial_capital: '10000',
|
||||||
|
metrics: {
|
||||||
|
totalReturn: 25,
|
||||||
|
winRate: 50,
|
||||||
|
maxDrawdown: 0.1,
|
||||||
|
sharpeRatio: null,
|
||||||
|
profitFactor: null,
|
||||||
|
totalTrades: 99,
|
||||||
|
avgWin: 10,
|
||||||
|
avgLoss: -5,
|
||||||
|
annualReturn: 30,
|
||||||
|
annualizedReturn: 30,
|
||||||
|
cagr: 30,
|
||||||
|
},
|
||||||
|
analytics: {
|
||||||
|
exposureTime: 25,
|
||||||
|
dailyReturns: [1, -2],
|
||||||
|
monthlyReturns: { '2024-01': 5 },
|
||||||
|
drawdownSeries: [{ timestamp: 1, value: -10 }],
|
||||||
|
riskMetrics: { var95: 0.02 },
|
||||||
|
},
|
||||||
|
trades: [
|
||||||
|
{
|
||||||
|
id: 'trade',
|
||||||
|
symbol: 'A.US',
|
||||||
|
side: 'buy',
|
||||||
|
entryDate: '2024-01-01T00:00:00Z',
|
||||||
|
entryPrice: 100,
|
||||||
|
exitDate: null,
|
||||||
|
quantity: 1,
|
||||||
|
commission: 0,
|
||||||
|
pnl: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
equity_curve: [{ date: '2024-01-01', value: 10000 }],
|
||||||
|
ohlc_data: {},
|
||||||
|
positions: [],
|
||||||
|
execution_time: 20,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('pure stored backtest result conversion', () => {
|
||||||
|
test('legacy TypeScript percentage units and closed trade identities retain existing normalization', () => {
|
||||||
|
const row = fixture();
|
||||||
|
const before = structuredClone(row);
|
||||||
|
const result = mapStoredBacktestResult(row);
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
engine: 'legacy',
|
||||||
|
legacy: true,
|
||||||
|
status: 'completed',
|
||||||
|
completedAt: '2024-03-01T00:00:00.000Z',
|
||||||
|
config: {
|
||||||
|
parameters: {},
|
||||||
|
initialCapital: 10000,
|
||||||
|
commission: 0.001,
|
||||||
|
slippage: 0.0001,
|
||||||
|
dataFrequency: '1d',
|
||||||
|
name: 'Backtest',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(result.metrics).toMatchObject({
|
||||||
|
totalReturn: 0.25,
|
||||||
|
winRate: 0.5,
|
||||||
|
maxDrawdown: 0.1,
|
||||||
|
annualReturn: 0.3,
|
||||||
|
annualizedReturn: 0.3,
|
||||||
|
cagr: 30,
|
||||||
|
totalTrades: 1,
|
||||||
|
profitableTrades: 1,
|
||||||
|
profitFactor: null,
|
||||||
|
sharpeRatio: null,
|
||||||
|
});
|
||||||
|
expect(result.analytics).toMatchObject({
|
||||||
|
exposureTime: 0.25,
|
||||||
|
dailyReturns: [0.01, -0.02],
|
||||||
|
monthlyReturns: { '2024-01': 0.05 },
|
||||||
|
drawdownSeries: [{ timestamp: 1, value: -0.1 }],
|
||||||
|
riskMetrics: { var95: 0.02 },
|
||||||
|
});
|
||||||
|
expect(result.trades[0]).toMatchObject({
|
||||||
|
kind: 'closed',
|
||||||
|
timestamp: row.trades[0]!.entryDate,
|
||||||
|
price: 100,
|
||||||
|
exitDate: null,
|
||||||
|
});
|
||||||
|
expect(row).toEqual(before);
|
||||||
|
expect(mapStoredBacktestResult(row)).toEqual(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legacy native daily fractions and fill counts are not scaled or recounted', () => {
|
||||||
|
const row = fixture();
|
||||||
|
row.metrics.finalValue = 12500;
|
||||||
|
row.analytics!.dailyReturns = [0.01, -0.02];
|
||||||
|
row.trades = [
|
||||||
|
{
|
||||||
|
id: 'fill',
|
||||||
|
symbol: 'A.US',
|
||||||
|
timestamp: '2024-01-01T00:00:00Z',
|
||||||
|
price: 100,
|
||||||
|
side: 'buy',
|
||||||
|
quantity: 1,
|
||||||
|
commission: 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const result = mapStoredBacktestResult(row);
|
||||||
|
expect(result.analytics.dailyReturns).toEqual([0.01, -0.02]);
|
||||||
|
expect(result.metrics.totalTrades).toBe(99);
|
||||||
|
expect(result.trades[0]?.kind).toBe('fill');
|
||||||
|
expect(result.metrics.profitableTrades).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('current snapshots preserve null ratios, configuration provenance and units exactly', () => {
|
||||||
|
const row = fixture();
|
||||||
|
const config = {
|
||||||
|
name: 'Frozen',
|
||||||
|
strategy: 'custom',
|
||||||
|
symbols: ['B.US'],
|
||||||
|
startDate: '2023-01-01T00:00:00Z',
|
||||||
|
endDate: '2023-03-01T00:00:00Z',
|
||||||
|
initialCapital: 100,
|
||||||
|
commission: 0,
|
||||||
|
slippage: 0,
|
||||||
|
dataFrequency: '1m',
|
||||||
|
parameters: { featureWindow: 3 },
|
||||||
|
};
|
||||||
|
row.configuration = config;
|
||||||
|
row.engine = 'typescript';
|
||||||
|
row.run_status = 'cancelled';
|
||||||
|
row.metrics.totalReturn = -0.2;
|
||||||
|
row.metrics.winRate = 0;
|
||||||
|
const before = structuredClone(row);
|
||||||
|
const result = mapStoredBacktestResult(row);
|
||||||
|
expect(result.config).toEqual(config);
|
||||||
|
expect(result.metrics).toEqual(before.metrics);
|
||||||
|
expect(result.analytics).toEqual({
|
||||||
|
...before.analytics,
|
||||||
|
exposureTime: before.analytics?.exposureTime ?? 0,
|
||||||
|
});
|
||||||
|
expect(result.engine).toBe('typescript');
|
||||||
|
expect(result.status).toBe('cancelled');
|
||||||
|
expect(result).not.toHaveProperty('legacy');
|
||||||
|
expect(row).toEqual(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legacy explicit zero fees and absent optional analytics keep their existing defaults', () => {
|
||||||
|
const row = fixture();
|
||||||
|
row.backtest_config = {
|
||||||
|
name: 'Legacy',
|
||||||
|
commission: 0,
|
||||||
|
slippage: 0,
|
||||||
|
dataFrequency: '1h',
|
||||||
|
feature: 9,
|
||||||
|
};
|
||||||
|
row.analytics = null;
|
||||||
|
row.trades = [];
|
||||||
|
expect(mapStoredBacktestResult(row)).toMatchObject({
|
||||||
|
config: {
|
||||||
|
name: 'Legacy',
|
||||||
|
commission: 0,
|
||||||
|
slippage: 0,
|
||||||
|
dataFrequency: '1h',
|
||||||
|
parameters: row.backtest_config,
|
||||||
|
},
|
||||||
|
analytics: { exposureTime: 0 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('malformed trade identities fail instead of fabricating an execution time or price', () => {
|
||||||
|
const row = fixture();
|
||||||
|
delete row.trades[0]!.entryDate;
|
||||||
|
expect(() => mapStoredBacktestResult(row)).toThrow('Malformed stored backtest trade');
|
||||||
|
row.trades[0]!.timestamp = '2024-01-01T00:00:00Z';
|
||||||
|
delete row.trades[0]!.entryPrice;
|
||||||
|
expect(() => mapStoredBacktestResult(row)).toThrow('Malformed stored backtest trade');
|
||||||
|
row.trades[0]!.price = 0;
|
||||||
|
expect(mapStoredBacktestResult(row).trades[0]?.price).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -26,6 +26,7 @@ import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/back
|
||||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||||
|
import { createBacktestRoutes as createV1Routes } from '../../apps/stock/web-api/src/routes/backtest.routes';
|
||||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||||
|
|
@ -176,6 +177,11 @@ describe('one backtest execution workflow', () => {
|
||||||
{ ...config, symbols: ['FIXTURE'] },
|
{ ...config, symbols: ['FIXTURE'] },
|
||||||
{ ...config, config: { dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } } },
|
{ ...config, config: { dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } } },
|
||||||
{ ...config, config: { datasetHash: 'invalid' } },
|
{ ...config, config: { datasetHash: 'invalid' } },
|
||||||
|
{ ...config, config: { commission: -0.01 } },
|
||||||
|
{ ...config, config: { slippage: 0.11 } },
|
||||||
|
{ ...config, config: { commission: '0.001' } },
|
||||||
|
{ ...config, initialCapital: 0 },
|
||||||
|
{ ...config, strategy: '' },
|
||||||
]) {
|
]) {
|
||||||
const response = await api.request('/api/v2/backtests', {
|
const response = await api.request('/api/v2/backtests', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|
@ -212,6 +218,18 @@ describe('one backtest execution workflow', () => {
|
||||||
'not found'
|
'not found'
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('V1 reports shared request-validation failures as bad input without creating definitions or runs', async () => {
|
||||||
|
const f = await fixture();
|
||||||
|
const response = await createV1Routes(f.services).request('/api/backtests', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ ...config, config: { commission: -0.01 } }),
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(400);
|
||||||
|
expect((await f.postgres.query('SELECT * FROM backtests')).rows).toHaveLength(0);
|
||||||
|
expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||||
|
});
|
||||||
test('REST and decorated jobs execute real data and commit the same canonical result', async () => {
|
test('REST and decorated jobs execute real data and commit the same canonical result', async () => {
|
||||||
const f = await fixture();
|
const f = await fixture();
|
||||||
const response = await f.routes.request('/api/backtest/run', {
|
const response = await f.routes.request('/api/backtest/run', {
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,10 @@ import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||||
import { Queue } from '@stock-bot/queue';
|
import { Queue } from '@stock-bot/queue';
|
||||||
|
import {
|
||||||
|
backtestRequestFromDefinition,
|
||||||
|
parseBacktestRequest,
|
||||||
|
} from '@stock-bot/stock-config/backtest';
|
||||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||||
|
|
@ -360,6 +364,38 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
||||||
})
|
})
|
||||||
).rejects.toThrow('does not match');
|
).rejects.toThrow('does not match');
|
||||||
});
|
});
|
||||||
|
test('API acceptance uses the runner contract before writing a run or dispatch intent', async () => {
|
||||||
|
const f = await fixture();
|
||||||
|
await expect(
|
||||||
|
f.api.updateBacktest(f.definition.id, { config: { commission: -1 } })
|
||||||
|
).rejects.toThrow('commission');
|
||||||
|
expect((await f.api.getBacktest(f.definition.id))?.config).toEqual(f.definition.config);
|
||||||
|
// Model malformed historical configuration that bypassed today's API validator.
|
||||||
|
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
|
||||||
|
f.definition.id,
|
||||||
|
JSON.stringify({ ...f.definition.config, slippage: 0.2 }),
|
||||||
|
]);
|
||||||
|
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow('slippage');
|
||||||
|
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||||
|
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
|
||||||
|
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
|
||||||
|
f.definition.id,
|
||||||
|
JSON.stringify(f.definition.config),
|
||||||
|
]);
|
||||||
|
const run = await f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 });
|
||||||
|
const snapshot = (
|
||||||
|
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||||
|
).rows[0].request_snapshot;
|
||||||
|
const expected = backtestRequestFromDefinition(f.definition, {
|
||||||
|
runId: run.id,
|
||||||
|
backtestId: f.definition.id,
|
||||||
|
speedMultiplier: 7,
|
||||||
|
});
|
||||||
|
expect(parseBacktestRequest(snapshot)).toEqual(expected);
|
||||||
|
expect(snapshot.speed).toBe('5x');
|
||||||
|
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
|
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
|
||||||
const f = await fixture();
|
const f = await fixture();
|
||||||
await f.pool
|
await f.pool
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["apps/stock/web-app/src/*"],
|
"@/*": ["apps/stock/web-app/src/*"],
|
||||||
"@stock-bot/stock-config": ["apps/stock/config/src/index.ts"],
|
"@stock-bot/stock-config": ["apps/stock/config/src/index.ts"],
|
||||||
|
"@stock-bot/stock-config/backtest": ["apps/stock/config/src/contracts/backtest.ts"],
|
||||||
"@stock-bot/engine": ["apps/stock/engine/index.d.ts"],
|
"@stock-bot/engine": ["apps/stock/engine/index.d.ts"],
|
||||||
"@stock-bot/*": [
|
"@stock-bot/*": [
|
||||||
"libs/core/*/src/index.ts",
|
"libs/core/*/src/index.ts",
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue