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
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue