62 lines
2.3 KiB
TypeScript
62 lines
2.3 KiB
TypeScript
import { createHash, randomUUID } from 'node:crypto';
|
|
import type { Pool } from 'pg';
|
|
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
|
import type {
|
|
BacktestServiceV2,
|
|
RunSubmission,
|
|
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
|
|
|
/** Insert an already accepted pre-cutover row for read/custody compatibility tests.
|
|
* This is not an admission API or executable simulator, and cannot seed catalog requests.
|
|
*/
|
|
export async function seedHistoricalRun(
|
|
pool: Pool,
|
|
api: BacktestServiceV2,
|
|
input: { backtestId: string },
|
|
receipt?: RunSubmission
|
|
) {
|
|
const definition = await api.getBacktest(input.backtestId);
|
|
if (!definition || definition.strategyVersionId !== null || definition.strategy === 'catalog') {
|
|
throw new Error('Historical fixture requires a legacy template');
|
|
}
|
|
const runId = randomUUID();
|
|
const snapshot = backtestRequestFromDefinition(
|
|
{
|
|
name: definition.name,
|
|
strategy: definition.strategy,
|
|
symbols: definition.symbols,
|
|
startDate: definition.startDate.toISOString(),
|
|
endDate: definition.endDate.toISOString(),
|
|
initialCapital: definition.initialCapital,
|
|
config: definition.config,
|
|
},
|
|
{ runId, backtestId: definition.id, speedMultiplier: null }
|
|
);
|
|
const hash = receipt
|
|
? createHash('sha256')
|
|
.update(JSON.stringify({ version: 1, backtestId: definition.id, speedMultiplier: null }))
|
|
.digest('hex')
|
|
: null;
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query('BEGIN');
|
|
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [definition.id]);
|
|
await client.query(
|
|
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot,submission_principal,submission_key,submission_hash)
|
|
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3,$4,$5,$6 FROM runs WHERE backtest_id=$2`,
|
|
[runId, definition.id, snapshot, receipt?.principal ?? null, receipt?.key ?? null, hash]
|
|
);
|
|
await client.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
|
await client.query('COMMIT');
|
|
} catch (error) {
|
|
await client.query('ROLLBACK');
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
const saved = await api.getRun(runId);
|
|
if (!saved) {
|
|
throw new Error('Historical fixture row missing');
|
|
}
|
|
return saved;
|
|
}
|