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
|
|
@ -4,6 +4,16 @@
|
|||
"description": "Stock trading bot configuration",
|
||||
"main": "dist/index.js",
|
||||
"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": {
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf dist",
|
||||
|
|
@ -12,6 +22,7 @@
|
|||
"lint": "eslint src --ext .ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@stock-bot/config": "*",
|
||||
"@stock-bot/logger": "*",
|
||||
"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/**/*"],
|
||||
"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 { EventEmitter } from 'node:events';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import { DataManager } from '../data/DataManager';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { amount, decimal } from '../execution/model';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
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 { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
|
||||
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'
|
||||
);
|
||||
}
|
||||
const config = BacktestConfigSchema.parse(input);
|
||||
const config = parseBacktestRequest(input);
|
||||
const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]);
|
||||
this.playback = playback;
|
||||
this.completedReport = undefined;
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { z } from 'zod';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { validateHistoricalDataRequest } from '@stock-bot/types';
|
||||
import { dataPolicy, prepareDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { prepareDataset } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
||||
import { normalizeBacktestResult } from './result';
|
||||
import {
|
||||
|
|
@ -14,17 +13,7 @@ import {
|
|||
type RunClaim,
|
||||
} from './run-repository';
|
||||
|
||||
export function parseBacktestRequest(input: unknown): BacktestConfig {
|
||||
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;
|
||||
}
|
||||
export { parseBacktestRequest };
|
||||
|
||||
/** One application workflow for HTTP, jobs, and both execution backends. */
|
||||
export class BacktestRunner extends EventEmitter {
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ import { randomUUID } from 'node:crypto';
|
|||
import type { PoolClient } from 'pg';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import { prepareDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError } from './execution-engine';
|
||||
import {
|
||||
BacktestConflictError,
|
||||
|
|
@ -54,7 +55,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
if (!run) {
|
||||
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
|
||||
}
|
||||
const snapshot = BacktestConfigSchema.parse(run.request_snapshot);
|
||||
const snapshot = parseBacktestRequest(run.request_snapshot);
|
||||
return {
|
||||
runId: String(run.id),
|
||||
backtestId: String(run.backtest_id),
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
||||
import type { BacktestConfig, OrchestratorServices } from '../types';
|
||||
import {
|
||||
BacktestCancelledError,
|
||||
BacktestTimeoutError,
|
||||
|
|
@ -58,7 +59,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
|
||||
);
|
||||
}
|
||||
const config = BacktestConfigSchema.parse(input);
|
||||
const config = parseBacktestRequest(input);
|
||||
const controller = new AbortController();
|
||||
let finished!: () => void;
|
||||
this.active = {
|
||||
|
|
|
|||
|
|
@ -1,21 +1,11 @@
|
|||
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 => {
|
||||
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 { datasetHashSchema, historicalDataPolicySchema, instrumentIdSchema };
|
||||
const positive = z.number().finite().positive();
|
||||
export const datasetBarSchema = z
|
||||
.object({
|
||||
|
|
|
|||
|
|
@ -1,61 +1,14 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
datasetHashSchema,
|
||||
historicalDataPolicySchema,
|
||||
instrumentIdSchema,
|
||||
} from './contracts/historical';
|
||||
import { BacktestConfigSchema, RiskLimitsSchema } from '@stock-bot/stock-config/backtest';
|
||||
|
||||
export { BacktestConfigSchema, RiskLimitsSchema };
|
||||
export type { BacktestConfig } from '@stock-bot/stock-config/backtest';
|
||||
|
||||
// Trading modes
|
||||
export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']);
|
||||
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
|
||||
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({
|
||||
mode: z.literal('paper'),
|
||||
startingCapital: z.number().positive(),
|
||||
|
|
@ -92,8 +45,6 @@ export const ModeConfigSchema = z.discriminatedUnion('mode', [
|
|||
LiveConfigSchema,
|
||||
]);
|
||||
|
||||
export type BacktestConfig = z.infer<typeof BacktestConfigSchema>;
|
||||
|
||||
export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & {
|
||||
custom?: Partial<{
|
||||
BacktestRunner: import('./backtest/BacktestRunner').BacktestRunner;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
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';
|
||||
|
||||
const logger = getLogger('backtest-routes');
|
||||
|
|
@ -33,7 +33,7 @@ export function createBacktestRoutes(container: IServiceContainer) {
|
|||
return c.json(backtest, 201);
|
||||
} catch (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: 'Failed to create backtest' }, 500);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
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';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
|
@ -44,7 +44,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest, 201);
|
||||
} catch (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: 'Failed to create backtest' }, 500);
|
||||
|
|
@ -61,7 +61,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest);
|
||||
} catch (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: 'Failed to update backtest' }, 500);
|
||||
|
|
@ -100,7 +100,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(run, 202);
|
||||
} catch (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: '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 { getLogger } from '@stock-bot/logger';
|
||||
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 type { WebSocketHandler } from '../websocket/run-updates';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
||||
|
|
@ -78,12 +80,7 @@ export class BacktestServiceV2 {
|
|||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
validateHistoricalDataRequest({
|
||||
...request,
|
||||
dataFrequency: request.config?.dataFrequency,
|
||||
dataPolicy: request.config?.dataPolicy,
|
||||
datasetHash: request.config?.datasetHash,
|
||||
});
|
||||
backtestRequestFromDefinition(request);
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
|
|
@ -141,14 +138,7 @@ export class BacktestServiceV2 {
|
|||
return null;
|
||||
}
|
||||
const next = { ...existing, ...request };
|
||||
validateHistoricalDataRequest({
|
||||
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,
|
||||
});
|
||||
backtestRequestFromDefinition(next);
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
|
|
@ -228,62 +218,12 @@ export class BacktestServiceV2 {
|
|||
throw new Error('Backtest not found');
|
||||
}
|
||||
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;
|
||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new Error('Speed multiplier must be positive or null');
|
||||
}
|
||||
const snapshot = {
|
||||
const snapshot = backtestRequestFromDefinition(definition, {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
name: definition.name,
|
||||
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');
|
||||
}
|
||||
speedMultiplier: multiplier,
|
||||
});
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
||||
|
|
@ -381,7 +321,7 @@ export class BacktestServiceV2 {
|
|||
|
||||
// Get run results
|
||||
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
|
||||
const result = await this.container.postgres.query(
|
||||
const result = await this.container.postgres.query<StoredBacktestResult>(
|
||||
`SELECT
|
||||
br.*,
|
||||
r.backtest_id,
|
||||
|
|
@ -403,83 +343,7 @@ export class BacktestServiceV2 {
|
|||
return null;
|
||||
}
|
||||
|
||||
const row = 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,
|
||||
};
|
||||
return mapStoredBacktestResult(at(result.rows, 0));
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue