continuation
This commit is contained in:
parent
32e43c9243
commit
879e9b4228
42 changed files with 2607 additions and 1306 deletions
|
|
@ -0,0 +1,170 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import {
|
||||
BacktestConflictError,
|
||||
type BacktestRunRepository,
|
||||
type RunIdentity,
|
||||
} from './run-repository';
|
||||
|
||||
/** Uses the existing backtests/runs schema; never commits completion without the result. */
|
||||
export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||
constructor(private readonly postgres: Pick<PostgresClient, 'transaction'>) {}
|
||||
|
||||
async start(config: BacktestConfig): Promise<RunIdentity> {
|
||||
return this.postgres.transaction(async client => {
|
||||
if (config.runId) {
|
||||
const claimed = await client.query<{ id: string; backtest_id: string }>(
|
||||
`UPDATE runs SET status = 'running', progress = 0, error = NULL,
|
||||
started_at = NOW(), completed_at = NULL, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('pending', 'failed')
|
||||
AND ($2::uuid IS NULL OR backtest_id = $2::uuid)
|
||||
RETURNING id, backtest_id`,
|
||||
[config.runId, config.backtestId ?? null]
|
||||
);
|
||||
const run = claimed.rows[0];
|
||||
if (!run) {
|
||||
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
|
||||
}
|
||||
return { runId: run.id, backtestId: run.backtest_id };
|
||||
}
|
||||
|
||||
const backtestId = config.backtestId ?? randomUUID();
|
||||
if (!config.backtestId) {
|
||||
await client.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
[
|
||||
backtestId,
|
||||
config.name ?? 'Backtest',
|
||||
config.strategy,
|
||||
JSON.stringify(config.symbols),
|
||||
config.startDate,
|
||||
config.endDate,
|
||||
config.initialCapital,
|
||||
JSON.stringify({
|
||||
...config.config,
|
||||
dataFrequency: config.dataFrequency,
|
||||
commission: config.commission,
|
||||
slippage: config.slippage,
|
||||
}),
|
||||
]
|
||||
);
|
||||
}
|
||||
// Serialize run numbering on the parent rather than racing MAX(run_number).
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest definition not found');
|
||||
}
|
||||
const runId = randomUUID();
|
||||
await client.query(
|
||||
`INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3
|
||||
FROM runs WHERE backtest_id = $2`,
|
||||
[
|
||||
runId,
|
||||
backtestId,
|
||||
config.speed === 'max'
|
||||
? null
|
||||
: config.speed === 'realtime'
|
||||
? 1
|
||||
: Number.parseFloat(config.speed),
|
||||
]
|
||||
);
|
||||
return { runId, backtestId };
|
||||
});
|
||||
}
|
||||
|
||||
async complete(result: BacktestRunResult): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
const updated = await client.query(
|
||||
`UPDATE runs SET status = $2, progress = CASE WHEN $2 = 'completed' THEN 100 ELSE progress END,
|
||||
completed_at = $3, updated_at = NOW(), error = NULL
|
||||
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused') RETURNING id`,
|
||||
[result.runId, result.status, result.completedAt, result.backtestId]
|
||||
);
|
||||
if (!updated.rows.length) {
|
||||
throw new BacktestConflictError('Run no longer belongs to this execution');
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO backtest_results
|
||||
(run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
|
||||
[
|
||||
result.runId,
|
||||
result.completedAt,
|
||||
JSON.stringify(result.metrics),
|
||||
JSON.stringify(result.equity),
|
||||
JSON.stringify(result.ohlcData),
|
||||
JSON.stringify(result.trades),
|
||||
JSON.stringify(result.positions),
|
||||
JSON.stringify(result.analytics),
|
||||
result.executionTime,
|
||||
JSON.stringify(result.config),
|
||||
result.engine,
|
||||
]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async updateProgress(runId: string, progress: number, currentDate?: string): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`UPDATE runs SET progress = GREATEST(progress, $2),
|
||||
current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused')`,
|
||||
[runId, progress, currentDate ?? null]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async updateControl(
|
||||
runId: string,
|
||||
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }
|
||||
): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
const result = await client.query(
|
||||
`UPDATE runs SET status = COALESCE($2::run_status, status),
|
||||
paused_at = CASE WHEN $2 = 'paused' THEN NOW() ELSE paused_at END,
|
||||
speed_multiplier = CASE WHEN $3 THEN $4 ELSE speed_multiplier END, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
|
||||
[
|
||||
runId,
|
||||
update.status ?? null,
|
||||
update.speedMultiplier !== undefined,
|
||||
update.speedMultiplier ?? null,
|
||||
]
|
||||
);
|
||||
if (!result.rows.length) {
|
||||
throw new BacktestConflictError('No matching active run');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fail(runId: string, error: string): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2, completed_at = NOW(), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused')`,
|
||||
[runId, error]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async cancel(runId: string): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
const result = await client.query(
|
||||
`UPDATE runs SET status = 'cancelled', error = NULL, completed_at = NOW(), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
|
||||
[runId]
|
||||
);
|
||||
if (!result.rows.length) {
|
||||
throw new BacktestConflictError('No matching active run to cancel');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue