more stuff
This commit is contained in:
parent
c3cb36c8d6
commit
7dec0be3b4
26 changed files with 1394 additions and 275 deletions
|
|
@ -49,6 +49,8 @@ export interface Run {
|
|||
completedAt?: Date;
|
||||
pausedAt?: Date;
|
||||
progress: number;
|
||||
cancelRequested: boolean;
|
||||
attemptNumber: number;
|
||||
currentDate?: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
|
|
@ -200,29 +202,69 @@ export class BacktestServiceV2 {
|
|||
async createRun(request: RunRequest): Promise<Run> {
|
||||
const runId = uuidv4();
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
request.backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
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 = {
|
||||
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,
|
||||
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(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb
|
||||
FROM runs WHERE backtest_id = $2 RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
request.backtestId,
|
||||
request.speedMultiplier === undefined ? null : request.speedMultiplier,
|
||||
]
|
||||
[runId, request.backtestId, multiplier, JSON.stringify(snapshot)]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return at(result.rows, 0);
|
||||
});
|
||||
const run = this.mapRun(row);
|
||||
// startRun handles dispatch failures; the runner owns execution and terminal persistence.
|
||||
void this.startRun(run);
|
||||
return run;
|
||||
return this.mapRun(row);
|
||||
}
|
||||
|
||||
async getRun(id: string): Promise<Run | null> {
|
||||
|
|
@ -248,14 +290,17 @@ export class BacktestServiceV2 {
|
|||
|
||||
async updateRunProgress(
|
||||
id: string,
|
||||
updates: { progress?: number; currentDate?: Date }
|
||||
updates: { progress?: number; currentDate?: Date; attemptId: string }
|
||||
): Promise<void> {
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs
|
||||
SET progress = COALESCE($2, progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null]
|
||||
);
|
||||
const result = await this.container.postgres.transaction(async client => {
|
||||
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]);
|
||||
return client.query(
|
||||
`UPDATE runs
|
||||
SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId]
|
||||
);
|
||||
});
|
||||
const row = result.rows[0];
|
||||
if (row) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
|
|
@ -273,7 +318,21 @@ export class BacktestServiceV2 {
|
|||
await this.sendControl(id, 'resume');
|
||||
}
|
||||
async cancelRun(id: string): Promise<void> {
|
||||
await this.sendControl(id, 'stop');
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs SET cancel_requested = TRUE,
|
||||
status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END,
|
||||
completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`,
|
||||
[id]
|
||||
);
|
||||
const row = result.rows[0];
|
||||
if (!row) {
|
||||
throw new Error('No cancellable run found');
|
||||
}
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
type: 'run_update',
|
||||
data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
await this.sendControl(id, 'speed', { speed: speedMultiplier });
|
||||
|
|
@ -394,94 +453,6 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
// Private methods
|
||||
private async startRun(run: Run): Promise<void> {
|
||||
try {
|
||||
const backtest = await this.getBacktest(run.backtestId);
|
||||
if (!backtest) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
|
||||
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
runId: run.id,
|
||||
backtestId: backtest.id,
|
||||
name: backtest.name,
|
||||
mode: 'backtest',
|
||||
startDate: backtest.startDate.toISOString(),
|
||||
endDate: backtest.endDate.toISOString(),
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
initialCapital: backtest.initialCapital,
|
||||
config: backtest.config,
|
||||
dataFrequency: backtest.config.dataFrequency ?? '1d',
|
||||
commission: backtest.config.commission ?? 0.001,
|
||||
slippage: backtest.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
run.speedMultiplier === null
|
||||
? 'max'
|
||||
: run.speedMultiplier >= 10
|
||||
? '10x'
|
||||
: run.speedMultiplier >= 5
|
||||
? '5x'
|
||||
: run.speedMultiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
if (response.status === 409) {
|
||||
const outcome: unknown = await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null);
|
||||
if (
|
||||
outcome &&
|
||||
typeof outcome === 'object' &&
|
||||
'status' in outcome &&
|
||||
outcome.status === 'cancelled' &&
|
||||
(await this.getRun(run.id))?.status === 'cancelled'
|
||||
) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(run.id, {
|
||||
type: 'run_update',
|
||||
data: { status: 'cancelled', timestamp: new Date().toISOString() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error(`Orchestrator returned ${response.status}: ${await response.text()}`);
|
||||
}
|
||||
const result: BacktestRunResult = await response.json();
|
||||
if (
|
||||
result.runId !== run.id ||
|
||||
result.backtestId !== backtest.id ||
|
||||
!['completed', 'cancelled'].includes(result.status)
|
||||
) {
|
||||
throw new Error('Invalid orchestrator run response');
|
||||
}
|
||||
// Results and terminal state are already committed by the orchestrator.
|
||||
this.getWebSocketHandler()?.sendCompletion(run.id, result);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error('Backtest dispatch failed', { runId: run.id, error });
|
||||
// A broken HTTP connection must not overwrite a claimed or completed execution.
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2,
|
||||
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
||||
[run.id, message]
|
||||
);
|
||||
} catch (persistenceError) {
|
||||
logger.error('Could not record backtest dispatch failure', {
|
||||
runId: run.id,
|
||||
persistenceError,
|
||||
});
|
||||
}
|
||||
this.getWebSocketHandler()?.sendError(run.id, message);
|
||||
}
|
||||
}
|
||||
|
||||
private mapBacktest(row: QueryResultRow): Backtest {
|
||||
return {
|
||||
id: row.id,
|
||||
|
|
@ -515,6 +486,8 @@ export class BacktestServiceV2 {
|
|||
completedAt: row.completed_at,
|
||||
pausedAt: row.paused_at,
|
||||
progress: parseFloat(row.progress),
|
||||
cancelRequested: row.cancel_requested === true,
|
||||
attemptNumber: Number(row.attempt_number ?? 0),
|
||||
currentDate: row.current_simulation_date,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue