refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -1,8 +1,5 @@
|
|||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import type {
|
||||
BacktestExecutionEngine,
|
||||
LegacyBacktestExecutionEngine,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import type { BacktestExecutionEngine } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import type { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import type {
|
||||
BacktestRunRepository,
|
||||
|
|
@ -12,7 +9,7 @@ import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/
|
|||
|
||||
function canonicalDependencies(
|
||||
engine: BacktestExecutionEngine,
|
||||
legacy: LegacyBacktestExecutionEngine,
|
||||
legacy: Pick<BacktestExecutionEngine, 'on' | 'off' | 'stopBacktest' | 'getStatus' | 'shutdown'>,
|
||||
repository: BacktestRunRepository,
|
||||
withoutReplay: Omit<BacktestExecutionEngine, 'runCanonical'>,
|
||||
withoutClaim: Omit<BacktestRunRepository, 'startCanonical'>,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
import type { StrategyContext, StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import type * as AuthorAPI from '@stock-bot/research/strategy-api';
|
||||
import type { FinancialDecimal, FinancialStrategyIntent } from '@stock-bot/types';
|
||||
// Existing hosts keep the same contract while external authors use the public subpath.
|
||||
import type { StrategyProgram as LegacyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
|
||||
type State = { count: number; indicator: { values: number[] } };
|
||||
|
||||
|
|
@ -62,8 +60,7 @@ const asynchronous: StrategyProgram<State> = {
|
|||
};
|
||||
void asynchronous;
|
||||
|
||||
const legacyProgram: LegacyProgram<State> = valid;
|
||||
const publicProgram: StrategyProgram<State> = legacyProgram;
|
||||
const publicProgram: StrategyProgram<State> = valid;
|
||||
void publicProgram;
|
||||
|
||||
// @ts-expect-error The author package exposes no strategy execution controller.
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backte
|
|||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import type { StorageService } from '@stock-bot/trading-runtime/historical-storage';
|
||||
import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import {
|
||||
createRoutes,
|
||||
|
|
|
|||
4
test/fixtures/canonical-paper.ts
vendored
4
test/fixtures/canonical-paper.ts
vendored
|
|
@ -1,6 +1,6 @@
|
|||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type { CanonicalMatchingConfig } from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { CanonicalMatchingConfig } from '@stock-bot/stock-config/canonical-execution';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import type { CanonicalPaperInput } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
|
||||
export function canonicalConfig(owners = ['A']): CanonicalMatchingConfig {
|
||||
|
|
|
|||
2
test/fixtures/canonical-regime-research.ts
vendored
2
test/fixtures/canonical-regime-research.ts
vendored
|
|
@ -3,7 +3,7 @@ import {
|
|||
type BuiltinStrategySelection,
|
||||
type MeanReversionSignalParameters,
|
||||
type MeanReversionStrategySelection,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { nativeReplayFixture } from './native-replay';
|
||||
|
||||
|
|
|
|||
2
test/fixtures/canonical-result.ts
vendored
2
test/fixtures/canonical-result.ts
vendored
|
|
@ -2,7 +2,7 @@ import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
|||
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import { createSmaStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
import { canonicalRunnerFixture } from './canonical-runner';
|
||||
|
||||
|
|
|
|||
2
test/fixtures/canonical-sma.ts
vendored
2
test/fixtures/canonical-sma.ts
vendored
|
|
@ -1,4 +1,4 @@
|
|||
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { nativeReplayFixture } from './native-replay';
|
||||
|
||||
|
|
|
|||
51
test/fixtures/execution.ts
vendored
51
test/fixtures/execution.ts
vendored
|
|
@ -1,55 +1,4 @@
|
|||
import { TradingEngine } from '@stock-bot/engine';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
|
||||
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
type MarketData,
|
||||
type OrderRequest,
|
||||
} from '../../apps/stock/orchestrator/src/types';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
export const logger = getLogger('execution-test');
|
||||
export const start = Date.parse('2024-01-01T00:00:00Z');
|
||||
export const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A.US', 'B.US'],
|
||||
startDate: new Date(start).toISOString(),
|
||||
endDate: '2025-01-01T00:00:00Z',
|
||||
initialCapital: 10000,
|
||||
dataFrequency: '1d',
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
});
|
||||
export function quote(
|
||||
id: string,
|
||||
price = 100,
|
||||
size = 100,
|
||||
timestamp = start,
|
||||
symbol = 'A'
|
||||
): MarketData {
|
||||
return {
|
||||
type: 'quote',
|
||||
eventId: id,
|
||||
data: { symbol, bid: price, ask: price, bidSize: size, askSize: size, timestamp },
|
||||
};
|
||||
}
|
||||
export function order(
|
||||
clientOrderId: string,
|
||||
side: 'buy' | 'sell' = 'buy',
|
||||
quantity = 10
|
||||
): OrderRequest {
|
||||
return { symbol: 'A', side, quantity, orderType: 'market', timeInForce: 'DAY', clientOrderId };
|
||||
}
|
||||
export function makeExecution(repository?: ExecutionRepository, clock = () => start) {
|
||||
const engine = new TradingEngine('backtest', {
|
||||
startTime: start,
|
||||
endTime: Date.parse(config.endDate),
|
||||
speedMultiplier: 0,
|
||||
initialCapital: 10000,
|
||||
});
|
||||
const execution = new ExecutionService({ logger }, {} as StorageService, { repository, clock });
|
||||
return { execution, engine };
|
||||
}
|
||||
|
|
|
|||
2
test/fixtures/native-replay-worker.ts
vendored
2
test/fixtures/native-replay-worker.ts
vendored
|
|
@ -1,5 +1,5 @@
|
|||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { replayTraceSchema } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
function send(message: unknown): Promise<void> {
|
||||
return new Promise((resolve, reject) =>
|
||||
|
|
|
|||
2
test/fixtures/native-replay.ts
vendored
2
test/fixtures/native-replay.ts
vendored
|
|
@ -1,4 +1,4 @@
|
|||
import type { ReplayConfig } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import type { ReplayConfig } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
|
||||
/** Retained synthetic sessions, raw executable bars, explicit availability. */
|
||||
|
|
|
|||
2
test/fixtures/paper-feed.ts
vendored
2
test/fixtures/paper-feed.ts
vendored
|
|
@ -2,7 +2,7 @@ import { parseFinancialDecimal } from '@stock-bot/types';
|
|||
import type {
|
||||
PaperConfigurationInput,
|
||||
PaperFrameInput,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
} from '@stock-bot/stock-config/paper-runtime';
|
||||
import { canonicalConfig } from './canonical-paper';
|
||||
|
||||
export function paperFeedConfiguration(instruments = ['X']): PaperConfigurationInput {
|
||||
|
|
|
|||
4
test/fixtures/paper-runtime.ts
vendored
4
test/fixtures/paper-runtime.ts
vendored
|
|
@ -3,11 +3,11 @@ import { readFileSync } from 'node:fs';
|
|||
import { Pool } from 'pg';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import type {
|
||||
PaperConfigurationInput,
|
||||
PaperFrameInput,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
} from '@stock-bot/stock-config/paper-runtime';
|
||||
import type {
|
||||
CanonicalExecutionRepository,
|
||||
CanonicalTransaction,
|
||||
|
|
|
|||
56
test/fixtures/strategy-crash-owner.ts
vendored
56
test/fixtures/strategy-crash-owner.ts
vendored
|
|
@ -1,56 +0,0 @@
|
|||
/** Disposable process used only against an isolated stock_bot_safety schema. */
|
||||
import { Pool } from 'pg';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
|
||||
import { logger, makeExecution, start } from './execution';
|
||||
import { attachCounter, CounterStrategy, FaultRepository } from './strategy-recovery';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL,
|
||||
schema = process.env.STRATEGY_FIXTURE_SCHEMA,
|
||||
phase = process.env.STRATEGY_FIXTURE_PHASE;
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
!schema ||
|
||||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
|
||||
!['decision', 'checkpoint', 'dispatch'].includes(phase ?? '')
|
||||
) {
|
||||
throw new Error('Unsafe strategy crash fixture');
|
||||
}
|
||||
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new FaultRepository(new PostgresExecutionRepository(postgres));
|
||||
const { execution, engine } = makeExecution(repository, () => start + 100);
|
||||
await execution.initialize(
|
||||
{
|
||||
mode: 'paper',
|
||||
accountId: 'fixture',
|
||||
startingCapital: 10000,
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
maxQuoteAgeMs: 1000,
|
||||
},
|
||||
engine
|
||||
);
|
||||
const blocked = async () => {
|
||||
process.send?.({ phase });
|
||||
await new Promise<void>(() => {});
|
||||
};
|
||||
const strategy = new CounterStrategy(execution);
|
||||
if (phase === 'decision') {
|
||||
strategy.onDecision = blocked;
|
||||
} else {
|
||||
repository.fault = {
|
||||
method: 'putIntent',
|
||||
stage: 'commit',
|
||||
matches: value =>
|
||||
(value as { status: string }).status === (phase === 'checkpoint' ? 'pending' : 'dispatched'),
|
||||
hook: blocked,
|
||||
};
|
||||
}
|
||||
await attachCounter(execution, strategy);
|
||||
throw new Error('Crash fixture did not reach its requested boundary');
|
||||
158
test/fixtures/strategy-recovery.ts
vendored
158
test/fixtures/strategy-recovery.ts
vendored
|
|
@ -1,158 +0,0 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { z } from 'zod';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import type {
|
||||
ExecutionRepository,
|
||||
ExecutionTransaction,
|
||||
} from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import type {
|
||||
ExecutionService,
|
||||
StrategyFill,
|
||||
} from '../../apps/stock/orchestrator/src/services/ExecutionService';
|
||||
import {
|
||||
BaseStrategy,
|
||||
type Signal,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type {
|
||||
StrategyDependencies,
|
||||
StrategyRegistry,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
|
||||
import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from './execution';
|
||||
|
||||
export const recoveryConfig: StrategyConfig = {
|
||||
id: 'counter',
|
||||
name: 'fixture',
|
||||
symbols: ['A'],
|
||||
parameters: {},
|
||||
allocation: 1,
|
||||
enabled: true,
|
||||
};
|
||||
export function makeStrategyManager({
|
||||
execution,
|
||||
modeManager,
|
||||
registry = createBuiltinStrategyRegistry(),
|
||||
marketData = new EventEmitter(),
|
||||
}: StrategyDependencies & { registry?: StrategyRegistry; marketData?: EventEmitter }) {
|
||||
return new StrategyManager({
|
||||
logger,
|
||||
execution,
|
||||
marketData,
|
||||
createStrategy: config => registry.create(config, { execution, modeManager }),
|
||||
});
|
||||
}
|
||||
|
||||
export class CounterStrategy extends BaseStrategy {
|
||||
count = 0;
|
||||
equities: number[] = [];
|
||||
failDecision = false;
|
||||
failFill = false;
|
||||
onDecision?: () => Promise<void>;
|
||||
version = 'counter/v1';
|
||||
constructor(execution: ExecutionService, config = recoveryConfig) {
|
||||
super(config, {} as ModeManager, execution);
|
||||
}
|
||||
override getCheckpointVersion() {
|
||||
return this.version;
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return { count: this.count, equities: this.equities };
|
||||
}
|
||||
protected override restoreIndicators(input: unknown) {
|
||||
const state = z
|
||||
.object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) })
|
||||
.parse(input);
|
||||
this.count = state.count;
|
||||
this.equities = state.equities;
|
||||
}
|
||||
protected updateIndicators() {
|
||||
this.count++;
|
||||
}
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
this.equities.push((await this.executionService.getAccount()).equity);
|
||||
await this.onDecision?.();
|
||||
if (this.failDecision) {
|
||||
throw new Error('injected decision failure');
|
||||
}
|
||||
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
|
||||
}
|
||||
override async onFill(fill: StrategyFill) {
|
||||
await super.onFill(fill);
|
||||
if (this.failFill) {
|
||||
throw new Error('injected fill callback failure');
|
||||
}
|
||||
}
|
||||
}
|
||||
export async function attachCounter(
|
||||
execution: ExecutionService,
|
||||
strategy = new CounterStrategy(execution)
|
||||
) {
|
||||
const manager = new StrategyManager({
|
||||
logger,
|
||||
execution,
|
||||
marketData: new EventEmitter(),
|
||||
createStrategy: () => {
|
||||
throw new Error('Counter fixtures attach their strategies directly');
|
||||
},
|
||||
});
|
||||
try {
|
||||
await manager.attachStrategy(strategy);
|
||||
} catch (error) {
|
||||
await manager.shutdown();
|
||||
throw error;
|
||||
}
|
||||
return { manager, strategy };
|
||||
}
|
||||
|
||||
export class FaultRepository implements ExecutionRepository {
|
||||
fault?: {
|
||||
method: keyof ExecutionTransaction;
|
||||
matches: (argument: unknown) => boolean;
|
||||
stage: 'before' | 'after' | 'commit';
|
||||
hook?: () => Promise<void>;
|
||||
};
|
||||
constructor(private readonly delegate: ExecutionRepository) {}
|
||||
initialize(...args: Parameters<ExecutionRepository['initialize']>) {
|
||||
return this.delegate.initialize(...args);
|
||||
}
|
||||
async transact<T>(account: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
|
||||
let matched: typeof this.fault;
|
||||
const result = await this.delegate.transact(account, tx =>
|
||||
work(
|
||||
new Proxy(tx, {
|
||||
get: (target, key: keyof ExecutionTransaction) => {
|
||||
const value = target[key];
|
||||
if (typeof value !== 'function') {
|
||||
return value;
|
||||
}
|
||||
return async (...args: unknown[]) => {
|
||||
const fault = this.fault;
|
||||
const hit = fault && key === fault.method && fault.matches(args[0]);
|
||||
if (hit) {
|
||||
this.fault = undefined;
|
||||
matched = fault;
|
||||
}
|
||||
if (hit && fault.stage === 'before') {
|
||||
throw new Error('injected transaction failure');
|
||||
}
|
||||
const answer = await Reflect.apply(value, target, args);
|
||||
if (hit && fault.stage === 'after') {
|
||||
throw new Error('injected transaction failure');
|
||||
}
|
||||
return answer;
|
||||
};
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
if (matched?.stage === 'commit') {
|
||||
if (matched.hook) {
|
||||
await matched.hook();
|
||||
}
|
||||
throw new Error('injected lost commit acknowledgement');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,155 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
dayMs,
|
||||
equityAnalysis,
|
||||
factorStatistics,
|
||||
performanceAnalysis,
|
||||
returnStatistics,
|
||||
tradeStatistics,
|
||||
} from '@stock-bot/calculations/analytics';
|
||||
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
|
||||
import golden from '../fixtures/analytics-golden.json';
|
||||
|
||||
const start = Date.parse('2024-01-01T00:00:00Z');
|
||||
const points = (values: number[]) =>
|
||||
values.map((value, i) => ({ timestamp: start + i * dayMs, value }));
|
||||
|
||||
describe('pure, fraction-based analytics golden fixtures', () => {
|
||||
test('drawdown depths belong to each period, equal peaks recover, and ongoing periods use observed time', () => {
|
||||
const result = equityAnalysis(points(golden.drawdowns.equity), 100);
|
||||
result.periods.forEach((period, i) => {
|
||||
expect(period.depth).toBeCloseTo(golden.drawdowns.depths[i]!);
|
||||
expect(period.duration).toBe(golden.drawdowns.durations[i]!);
|
||||
});
|
||||
expect(result.maxDrawdown).toBeCloseTo(0.2);
|
||||
expect(result.currentDrawdown).toBe(0);
|
||||
const recovered = equityAnalysis(points([100, 90, 100, 80]), 100);
|
||||
expect(recovered.periods[0]?.recovery).toBe(2);
|
||||
expect(recovered.periods[1]?.recovery).toBeNull();
|
||||
expect(recovered.periods[1]?.depth).toBeCloseTo(0.2);
|
||||
expect(recovered.maxDrawdownDuration).toBe(1);
|
||||
const facade = new PerformanceAnalyzer(100);
|
||||
points(golden.drawdowns.equity).forEach(point =>
|
||||
facade.addEquityPoint(new Date(point.timestamp), point.value)
|
||||
);
|
||||
expect(facade.analyzeDrawdowns().drawdownPeriods.map(period => period.depth)).toEqual(
|
||||
result.periods.map(period => period.depth)
|
||||
);
|
||||
});
|
||||
test('CAGR requires positive capital, positive ending equity and positive elapsed time', () => {
|
||||
expect(equityAnalysis([], 100).annualizedReturn).toBeNull();
|
||||
const growth = equityAnalysis(
|
||||
[
|
||||
{ timestamp: start, value: 100 },
|
||||
{ timestamp: start + 730 * dayMs, value: 121 },
|
||||
],
|
||||
100
|
||||
);
|
||||
expect(growth.totalReturn).toBeCloseTo(0.21);
|
||||
expect(growth.annualizedReturn).toBeCloseTo(0.1);
|
||||
for (const end of [0, -10])
|
||||
expect(equityAnalysis(points([100, end]), 100).annualizedReturn).toBeNull();
|
||||
expect(() => equityAnalysis(points([100]), 0)).toThrow();
|
||||
expect(() => equityAnalysis(points([100, NaN]), 100)).toThrow('finite');
|
||||
expect(() => equityAnalysis(points([100, 110]).reverse(), 100)).toThrow('ordered');
|
||||
const sameTime = new PerformanceAnalyzer(100);
|
||||
sameTime.addEquityPoint(new Date(start), 100);
|
||||
sameTime.addEquityPoint(new Date(start), 101);
|
||||
expect(sameTime.analyze().cagr).toBeNull();
|
||||
expect(sameTime.analyze().annualizedReturn).toBeNull();
|
||||
expect(sameTime.exportReport()).toContain('CAGR: N/A');
|
||||
expect(sameTime.exportReport()).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
test('UTC grouping keeps first-period returns and never associates a skipped denominator with another month', () => {
|
||||
const result = equityAnalysis(
|
||||
[
|
||||
{ timestamp: Date.parse('2024-01-31T23:30:00Z'), value: 110 },
|
||||
{ timestamp: Date.parse('2024-02-01T00:30:00Z'), value: 0 },
|
||||
{ timestamp: Date.parse('2024-03-01T00:30:00Z'), value: 50 },
|
||||
{ timestamp: Date.parse('2024-04-01T00:30:00Z'), value: 75 },
|
||||
],
|
||||
100
|
||||
);
|
||||
expect(result.dailyReturns[0]).toBeCloseTo(0.1);
|
||||
expect(result.monthlyReturns['2024-01']).toBeCloseTo(0.1);
|
||||
expect(result.monthlyReturns['2024-02']).toBe(-1);
|
||||
expect(result.monthlyReturns['2024-03']).toBeUndefined();
|
||||
expect(result.monthlyReturns['2024-04']).toBe(0.5);
|
||||
});
|
||||
test('sample volatility and full-series downside RMS use daily fractions, not percentage points', () => {
|
||||
const result = returnStatistics(golden.daily.returns, 0);
|
||||
expect(result.volatility! ** 2).toBeCloseTo(golden.daily.annualVariance, 10);
|
||||
expect(result.downsideDeviation! ** 2).toBeCloseTo(golden.daily.annualDownsideVariance, 10);
|
||||
expect(result.sharpeRatio).toBeCloseTo(
|
||||
golden.daily.annualExcess / Math.sqrt(golden.daily.annualVariance)
|
||||
);
|
||||
expect(result.sortinoRatio).toBeCloseTo(
|
||||
golden.daily.annualExcess / Math.sqrt(golden.daily.annualDownsideVariance)
|
||||
);
|
||||
expect(returnStatistics([], 0).volatility).toBeNull();
|
||||
expect(returnStatistics([0.1], 0).sharpeRatio).toBeNull();
|
||||
expect(returnStatistics([0, 0, 0], 0).sharpeRatio).toBeNull();
|
||||
expect(returnStatistics([0, 0, 0], 0).volatility).toBe(0);
|
||||
expect(returnStatistics([0.1, 0.2], 0).sortinoRatio).toBeNull();
|
||||
expect(() => returnStatistics([Infinity])).toThrow('finite');
|
||||
expect(() => returnStatistics(Array<number>(3))).toThrow('finite');
|
||||
});
|
||||
test('historical loss tails require enough samples and have one shared positive-loss sign convention', () => {
|
||||
expect(returnStatistics(Array(19).fill(-0.01)).var95).toBeNull();
|
||||
const risk = returnStatistics(Array.from({ length: 100 }, (_, i) => i / 1000 - 0.05));
|
||||
expect(risk.var95).toBeCloseTo(0.046);
|
||||
expect(risk.cvar95).toBeCloseTo(0.048);
|
||||
expect(risk.var99).toBeCloseTo(0.05);
|
||||
expect(returnStatistics(Array(100).fill(0.01)).var95).toBe(0);
|
||||
});
|
||||
test('trade statistics count completed trades, break streaks on breakeven and preserve undefined ratios', () => {
|
||||
const result = tradeStatistics(
|
||||
golden.trades.pnl.map(pnl => ({ pnl, holdingPeriod: 60 })),
|
||||
365
|
||||
);
|
||||
const { pnl: _pnl, ...expected } = golden.trades;
|
||||
expect(result).toMatchObject(expected);
|
||||
expect(result.avgWin).toBe(15);
|
||||
expect(result.avgLoss).toBe(2.5);
|
||||
expect(result.avgHoldingPeriod).toBe(60);
|
||||
expect(result.avgTradesPerDay).toBeCloseTo(8 / 252);
|
||||
expect(tradeStatistics([], 0).profitFactor).toBeNull();
|
||||
expect(tradeStatistics([{ pnl: 10, holdingPeriod: 0 }], 1).profitFactor).toBeNull();
|
||||
expect(tradeStatistics([{ pnl: -10, holdingPeriod: 0 }], 1).profitFactor).toBe(0);
|
||||
expect(() => tradeStatistics([{ pnl: NaN, holdingPeriod: 0 }], 1)).toThrow();
|
||||
});
|
||||
test('benchmark math validates alignment and uses the same fraction-based excess-return convention', () => {
|
||||
const benchmark = [-0.01, 0.02, -0.02, 0.03];
|
||||
const result = factorStatistics(
|
||||
benchmark.map(value => 2 * value),
|
||||
benchmark,
|
||||
0
|
||||
);
|
||||
expect(result.beta).toBeCloseTo(2);
|
||||
expect(result.alpha).toBeCloseTo(0);
|
||||
expect(result.correlation).toBeCloseTo(1);
|
||||
expect(factorStatistics([0, 0], [0, 0]).beta).toBeNull();
|
||||
expect(() => factorStatistics([0], [0, 0])).toThrow('same length');
|
||||
expect(() => factorStatistics([0, NaN], [0, 0])).toThrow('finite');
|
||||
});
|
||||
test('facade input/output detachment, cache invalidation and legacy report percentages are explicit', () => {
|
||||
const analyzer = new PerformanceAnalyzer(100);
|
||||
const date = new Date(start);
|
||||
analyzer.addEquityPoint(date, 100);
|
||||
date.setUTCFullYear(2030);
|
||||
analyzer.addEquityPoint(new Date(start + 365 * dayMs), 110);
|
||||
expect(analyzer.analyze().totalReturn).toBeCloseTo(10);
|
||||
expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1);
|
||||
const view = analyzer.getAnalysis();
|
||||
view.metrics.totalReturn = 999;
|
||||
expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1);
|
||||
analyzer.addEquityPoint(new Date(start + 366 * dayMs), 120);
|
||||
expect(analyzer.analyze().totalReturn).toBeCloseTo(20);
|
||||
const bankrupt = performanceAnalysis(points([100, 0, -10]), [], 100);
|
||||
expect(bankrupt.metrics.totalReturn).toBeCloseTo(-1.1);
|
||||
expect(bankrupt.metrics.cagr).toBeNull();
|
||||
expect(
|
||||
Object.values(bankrupt.metrics).every(value => value === null || Number.isFinite(value))
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,295 +0,0 @@
|
|||
import type { AxiosRequestConfig } from 'axios';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { createAnalyticsRoutes } from '../../apps/stock/orchestrator/src/api/rest/analytics';
|
||||
import { AnalyticsServiceError } from '../../apps/stock/orchestrator/src/services/analytics-error';
|
||||
import { AnalyticsService } from '../../apps/stock/orchestrator/src/services/AnalyticsService';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
const performance = {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
totalTrades: 0,
|
||||
};
|
||||
const risk = { currentExposure: 0, dailyPnl: 0, positionCount: 0, grossExposure: 0, var95: null };
|
||||
const optimize = {
|
||||
symbols: ['A.US', 'B.US'],
|
||||
returns: [
|
||||
[0.01, -0.01],
|
||||
[-0.01, 0.02],
|
||||
],
|
||||
constraints: { minWeight: 0.1, maxWeight: 0.9 },
|
||||
};
|
||||
function fixture(initial: unknown = performance) {
|
||||
let data = initial;
|
||||
let failure = false;
|
||||
let now = 0;
|
||||
const requests: AxiosRequestConfig[] = [];
|
||||
const service = new AnalyticsService(
|
||||
{ logger },
|
||||
{
|
||||
baseUrl: 'http://analytics.fixture',
|
||||
now: () => now,
|
||||
client: {
|
||||
async request(request) {
|
||||
requests.push(structuredClone(request));
|
||||
if (failure) throw new Error('Private upstream diagnostic must never reach the client');
|
||||
return { data };
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
return {
|
||||
service,
|
||||
requests,
|
||||
routes: createAnalyticsRoutes({ logger, custom: { AnalyticsService: service } }),
|
||||
setData(value: unknown) {
|
||||
data = value;
|
||||
},
|
||||
fail(value = true) {
|
||||
failure = value;
|
||||
},
|
||||
advance(ms: number) {
|
||||
now += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
const post = (body: unknown) => ({
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const from = new Date('2024-01-01T00:00:00Z');
|
||||
const to = new Date('2024-02-01T00:00:00Z');
|
||||
|
||||
describe('analytics upstream contract and HTTP failure semantics', () => {
|
||||
test('outages never become zero metrics, equal weights, normal regimes, identity matrices or false model misses', async () => {
|
||||
const f = fixture();
|
||||
f.fail();
|
||||
for (const [path, options] of [
|
||||
[
|
||||
'/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString(),
|
||||
undefined,
|
||||
],
|
||||
['/risk/P', undefined],
|
||||
['/regime', undefined],
|
||||
['/optimize', post(optimize)],
|
||||
['/correlation', post({ symbols: ['A.US', 'B.US'] })],
|
||||
['/predict', post({ modelId: 'model', features: { x: 1 } })],
|
||||
] as const) {
|
||||
const response = await f.routes.request(path, options);
|
||||
expect(response.status).toBe(503);
|
||||
expect(await response.json()).toEqual({
|
||||
error: 'Analytics service is unavailable',
|
||||
code: 'analytics_unavailable',
|
||||
});
|
||||
}
|
||||
await expect(f.service.runBacktestAnalysis('run')).rejects.toBeInstanceOf(
|
||||
AnalyticsServiceError
|
||||
);
|
||||
expect(
|
||||
f.requests.every(request => request.timeout === 5000 && request.maxContentLength === 1048576)
|
||||
).toBe(true);
|
||||
const missing = await createAnalyticsRoutes({ logger }).request('/risk/P');
|
||||
expect(missing.status).toBe(503);
|
||||
});
|
||||
test('invalid upstream values are 502, not client 400, and never enter the success cache', async () => {
|
||||
const f = fixture({ ...performance, totalReturn: '0' });
|
||||
const path =
|
||||
'/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString();
|
||||
const response = await f.routes.request(path);
|
||||
expect(response.status).toBe(502);
|
||||
expect((await response.json()).code).toBe('analytics_invalid_response');
|
||||
f.setData(performance);
|
||||
expect(await f.service.getPerformanceMetrics('P', from, to)).toEqual(performance);
|
||||
expect(f.requests).toHaveLength(2);
|
||||
const view = await f.service.getPerformanceMetrics('P', from, to);
|
||||
view.totalReturn = 100;
|
||||
expect((await f.service.getPerformanceMetrics('P', from, to)).totalReturn).toBe(0);
|
||||
f.setData({ ...performance, totalReturn: Infinity });
|
||||
f.advance(60000);
|
||||
await expect(f.service.getPerformanceMetrics('P', from, to)).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
});
|
||||
test('cache expiration honors each entry TTL and expired failures never masquerade as fresh observations', async () => {
|
||||
const f = fixture({ regime: 'observed-bull' });
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bull');
|
||||
f.setData({ regime: 'observed-bear' });
|
||||
f.advance(60001);
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bull');
|
||||
expect(f.requests).toHaveLength(1);
|
||||
f.advance(240000);
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bear');
|
||||
f.setData(risk);
|
||||
expect(await f.service.getRiskMetrics('P')).toEqual(risk);
|
||||
f.advance(60000);
|
||||
f.fail();
|
||||
await expect(f.service.getRiskMetrics('P')).rejects.toMatchObject({ status: 503 });
|
||||
f.fail(false);
|
||||
f.setData({ ...risk, dailyPnl: -10 });
|
||||
expect((await f.service.getRiskMetrics('P')).dailyPnl).toBe(-10);
|
||||
});
|
||||
test('success cache is bounded and identifiers are encoded rather than interpreted as paths', async () => {
|
||||
const f = fixture(risk);
|
||||
for (let i = 0; i < 129; i++) await f.service.getRiskMetrics(String(i));
|
||||
await f.service.getRiskMetrics('0');
|
||||
expect(f.requests).toHaveLength(130);
|
||||
await f.service.getRiskMetrics('A/B?secret');
|
||||
expect(f.requests.at(-1)?.url).toBe('http://analytics.fixture/analytics/risk/A%2FB%3Fsecret');
|
||||
});
|
||||
test('optimization forwards real symbol identities and maps the Python wire contract without fabricating weights', async () => {
|
||||
const f = fixture({
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: null,
|
||||
});
|
||||
const result = await f.service.optimizePortfolio(optimize);
|
||||
expect(result).toEqual({
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expectedReturn: 0.1,
|
||||
expectedRisk: 0.2,
|
||||
sharpeRatio: null,
|
||||
});
|
||||
expect(f.requests[0]?.data).toMatchObject({
|
||||
symbols: optimize.symbols,
|
||||
returns: optimize.returns,
|
||||
constraints: { min_weight: 0.1, max_weight: 0.9 },
|
||||
});
|
||||
for (const data of [
|
||||
{
|
||||
symbols: ['B.US', 'A.US'],
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
{
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.4],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
{
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: NaN,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
]) {
|
||||
f.setData(data);
|
||||
await expect(f.service.optimizePortfolio(optimize)).rejects.toMatchObject({ status: 502 });
|
||||
}
|
||||
});
|
||||
test('correlations validate dimensions, ordered identities, symmetry, range and positive semidefiniteness', async () => {
|
||||
const f = fixture({
|
||||
symbols: ['A.US', 'B.US'],
|
||||
matrix: [
|
||||
[1, 0.5],
|
||||
[0.5, 1],
|
||||
],
|
||||
});
|
||||
expect(await f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).toEqual([
|
||||
[1, 0.5],
|
||||
[0.5, 1],
|
||||
]);
|
||||
expect(f.requests[0]?.data).toEqual(['A.US', 'B.US']);
|
||||
for (const matrix of [
|
||||
[[1]],
|
||||
[
|
||||
[1, 2],
|
||||
[2, 1],
|
||||
],
|
||||
[
|
||||
[1, 0.5],
|
||||
[0.2, 1],
|
||||
],
|
||||
[
|
||||
[0.9, 0],
|
||||
[0, 1],
|
||||
],
|
||||
[
|
||||
[1, NaN],
|
||||
[NaN, 1],
|
||||
],
|
||||
]) {
|
||||
f.setData({ symbols: ['A.US', 'B.US'], matrix });
|
||||
await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
}
|
||||
f.setData({
|
||||
symbols: ['A.US', 'B.US', 'C.US'],
|
||||
matrix: [
|
||||
[1, 0.9, 0.9],
|
||||
[0.9, 1, -0.9],
|
||||
[0.9, -0.9, 1],
|
||||
],
|
||||
});
|
||||
await expect(
|
||||
f.service.calculateCorrelationMatrix(['A.US', 'B.US', 'C.US'])
|
||||
).rejects.toMatchObject({ status: 502 });
|
||||
f.setData({
|
||||
symbols: ['B.US', 'A.US'],
|
||||
matrix: [
|
||||
[1, 0],
|
||||
[0, 1],
|
||||
],
|
||||
});
|
||||
await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
});
|
||||
test('model and backtest responses validate identity, finite JSON and wire field names', async () => {
|
||||
const f = fixture({
|
||||
model_id: 'model',
|
||||
prediction: 0,
|
||||
probability: null,
|
||||
metadata: { version: 'v1' },
|
||||
});
|
||||
expect((await f.service.predictWithModel('model', { x: 1 })).prediction).toBe(0);
|
||||
expect(f.requests[0]?.data).toEqual({ model_id: 'model', features: { x: 1 } });
|
||||
f.setData({ model_id: 'wrong-model', prediction: 1 });
|
||||
await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
f.setData({ model_id: 'model', prediction: 1, metadata: { nested: { value: Infinity } } });
|
||||
await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
f.setData({
|
||||
backtest_id: 'other',
|
||||
metrics: {},
|
||||
statistics: {},
|
||||
risk_analysis: {},
|
||||
trade_analysis: {},
|
||||
});
|
||||
await expect(f.service.runBacktestAnalysis('run')).rejects.toMatchObject({ status: 502 });
|
||||
});
|
||||
test('invalid client requests return 400 before upstream access', async () => {
|
||||
const f = fixture();
|
||||
for (const [path, options] of [
|
||||
[
|
||||
'/performance/P?start_date=' + to.toISOString() + '&end_date=' + from.toISOString(),
|
||||
undefined,
|
||||
],
|
||||
['/optimize', post({ ...optimize, returns: [[1], [2]] })],
|
||||
['/optimize', post({ ...optimize, constraints: { minWeight: 0.8 } })],
|
||||
['/correlation', post({ symbols: ['A.US', 'A.US'] })],
|
||||
['/predict', post({ modelId: '', features: { x: 1 } })],
|
||||
['/predict', { method: 'POST', body: '{broken' }],
|
||||
] as const)
|
||||
expect((await f.routes.request(path, options)).status).toBe(400);
|
||||
expect(f.requests).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -2,7 +2,6 @@ import { expect, test } from 'bun:test';
|
|||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { BacktestMetrics } from '../../apps/stock/web-app/src/features/backtest/components/BacktestMetrics';
|
||||
import { CompactPerformanceMetrics } from '../../apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics';
|
||||
|
||||
const metrics = {
|
||||
|
|
@ -19,40 +18,7 @@ const metrics = {
|
|||
avgLoss: 0,
|
||||
};
|
||||
const text = (html: string) => html.replace(/<[^>]*>/g, '');
|
||||
test('detailed metrics distinguish undefined ratios from legitimate zero return and exposure', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(BacktestMetrics, {
|
||||
isLoading: false,
|
||||
result: {
|
||||
id: 'fixture',
|
||||
config: {
|
||||
name: 'fixture',
|
||||
startDate: new Date('2024-01-01'),
|
||||
endDate: new Date('2024-02-01'),
|
||||
initialCapital: 1000,
|
||||
symbols: ['A.US'],
|
||||
strategy: 'sma',
|
||||
speedMultiplier: 0,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
},
|
||||
metrics,
|
||||
positions: [],
|
||||
trades: [],
|
||||
performanceData: [],
|
||||
analytics: { exposureTime: 0 },
|
||||
},
|
||||
})
|
||||
);
|
||||
const rendered = text(html);
|
||||
expect(rendered).toContain('Sharpe RatioN/A');
|
||||
expect(rendered).toContain('Profit FactorN/A');
|
||||
expect(rendered).toContain('Calmar RatioN/A');
|
||||
expect(rendered).toContain('Sortino RatioN/A');
|
||||
expect(rendered).toContain('Total Return0.00%');
|
||||
expect(rendered).toContain('Exposure Time0.0%');
|
||||
expect(rendered).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
|
||||
test('compact metrics preserve null ratios and render a genuine zero profit', () => {
|
||||
const result: BacktestRunResult = {
|
||||
runId: 'fixture',
|
||||
|
|
@ -88,34 +54,3 @@ test('compact metrics preserve null ratios and render a genuine zero profit', ()
|
|||
expect(rendered).toContain('$0.00');
|
||||
expect(rendered).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
|
||||
test('null_metrics: detailed exposure is unavailable rather than a measured zero', () => {
|
||||
const rendered = text(
|
||||
renderToStaticMarkup(
|
||||
createElement(BacktestMetrics, {
|
||||
isLoading: false,
|
||||
result: {
|
||||
id: 'fixture',
|
||||
config: {
|
||||
name: 'fixture',
|
||||
startDate: new Date('2024-01-01'),
|
||||
endDate: new Date('2024-02-01'),
|
||||
initialCapital: 1000,
|
||||
symbols: ['A.US'],
|
||||
strategy: 'sma',
|
||||
speedMultiplier: 0,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
},
|
||||
metrics,
|
||||
positions: [],
|
||||
trades: [],
|
||||
performanceData: [],
|
||||
analytics: { exposureTime: null },
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(rendered).toContain('Exposure TimeN/A');
|
||||
expect(rendered).not.toContain('Exposure Time0.0%');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import {
|
|||
runReplaySessionAsync,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { ReplayResultFormat } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import type { ReplayResultFormat } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
|
|
|
|||
|
|
@ -1,436 +0,0 @@
|
|||
import { describe, expect, spyOn, test } from 'bun:test';
|
||||
import type { HistoricalDataset } from '@stock-bot/types';
|
||||
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
|
||||
import {
|
||||
BacktestPlayback,
|
||||
type PlaybackProgress,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/BacktestPlayback';
|
||||
import { BacktestReport } from '../../apps/stock/orchestrator/src/backtest/BacktestReport';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import type { ClosedTrade } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
||||
import { formatReport } from '../../apps/stock/orchestrator/src/backtest/report-format';
|
||||
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
|
||||
const day = 86400000;
|
||||
const start = Date.parse('2024-01-01T00:00:00Z');
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A.US', 'B.US'],
|
||||
startDate: new Date(start).toISOString(),
|
||||
endDate: '2024-03-01T00:00:00Z',
|
||||
initialCapital: 1000,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
const bars = [0, 1, 2].flatMap(index =>
|
||||
config.symbols.map(symbol => ({
|
||||
symbol,
|
||||
timestamp: start + index * day,
|
||||
open: 100,
|
||||
high: 101,
|
||||
low: 99,
|
||||
close: 100,
|
||||
volume: 1000,
|
||||
vwap: 100,
|
||||
}))
|
||||
);
|
||||
const dataset: HistoricalDataset = {
|
||||
manifest: {
|
||||
version: 1,
|
||||
hash: '0'.repeat(64),
|
||||
instruments: config.symbols.map(id => ({ id, symbol: id.split('.')[0]!, exchange: 'US' })),
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
interval: '1d',
|
||||
policy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
volumePolicy: 'reported',
|
||||
qualityPolicy: 'reject-invalid-no-interpolation',
|
||||
sources: config.symbols.map(instrumentId => ({
|
||||
instrumentId,
|
||||
provider: 'synthetic',
|
||||
revision: 'fixture',
|
||||
})),
|
||||
barCount: bars.length,
|
||||
},
|
||||
bars,
|
||||
};
|
||||
const trade: ClosedTrade = {
|
||||
id: 'closed-1',
|
||||
symbol: 'A.US',
|
||||
side: 'Buy',
|
||||
quantity: 1,
|
||||
entry_price: 100,
|
||||
exit_price: 90,
|
||||
entry_time: new Date(start).toISOString(),
|
||||
exit_time: new Date(start + day).toISOString(),
|
||||
pnl: -10,
|
||||
pnl_percent: -10,
|
||||
commission: 0,
|
||||
duration_ms: day,
|
||||
};
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason: unknown) => void;
|
||||
const promise = new Promise<T>((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
async function deadline<T>(work: Promise<T>): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
work,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('Control did not settle promptly')), 500);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
const turn = () => new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
|
||||
describe('backtest playback isolation and controls', () => {
|
||||
test('a cursor consumes frozen inputs in order, preserves timestamp ties and yields to timers', async () => {
|
||||
const playback = new BacktestPlayback(start, null);
|
||||
const events = Object.freeze(
|
||||
Array.from({ length: 1001 }, (_, id) => ({ id, timestamp: start + Math.floor(id / 2) }))
|
||||
);
|
||||
const seen: number[] = [];
|
||||
const updates: PlaybackProgress[] = [];
|
||||
let timerRan = false;
|
||||
setTimeout(() => {
|
||||
timerRan = true;
|
||||
}, 0);
|
||||
await playback.process(
|
||||
events,
|
||||
event => event.timestamp,
|
||||
async event => {
|
||||
seen.push(event.id);
|
||||
},
|
||||
update => updates.push(update)
|
||||
);
|
||||
playback.finish();
|
||||
expect(seen).toEqual(events.map(event => event.id));
|
||||
expect(timerRan).toBe(true);
|
||||
expect(events).toHaveLength(1001);
|
||||
expect(updates.filter(update => update.progress === 100)).toHaveLength(1);
|
||||
expect(updates.at(-1)).toMatchObject({
|
||||
processed: 1001,
|
||||
total: 1001,
|
||||
remaining: 0,
|
||||
progress: 100,
|
||||
});
|
||||
expect(playback.getStatus()).toMatchObject({
|
||||
isRunning: false,
|
||||
isPaused: false,
|
||||
progress: 100,
|
||||
});
|
||||
});
|
||||
|
||||
test('pause blocks delivery and resume wakes it without a polling interval', async () => {
|
||||
const playback = new BacktestPlayback(start, null);
|
||||
playback.pause();
|
||||
let processed = 0;
|
||||
const work = playback.process(
|
||||
[start],
|
||||
time => time,
|
||||
async () => {
|
||||
processed++;
|
||||
},
|
||||
() => {}
|
||||
);
|
||||
await turn();
|
||||
expect(processed).toBe(0);
|
||||
playback.resume();
|
||||
await deadline(work);
|
||||
expect(processed).toBe(1);
|
||||
playback.finish();
|
||||
playback.pause();
|
||||
expect(playback.getStatus().isPaused).toBe(false);
|
||||
});
|
||||
|
||||
test('stop wakes a paused run and never emits completed progress', async () => {
|
||||
const playback = new BacktestPlayback(start, null);
|
||||
playback.pause();
|
||||
const updates: number[] = [];
|
||||
const work = playback.process(
|
||||
[start],
|
||||
time => time,
|
||||
async () => {
|
||||
throw new Error('Must not execute');
|
||||
},
|
||||
update => updates.push(update.progress)
|
||||
);
|
||||
const outcome = work.catch(error => error);
|
||||
await turn();
|
||||
playback.stop();
|
||||
expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError);
|
||||
expect(updates).toEqual([]);
|
||||
playback.finish();
|
||||
});
|
||||
|
||||
test.each(['stop', 'setSpeed'] as const)('%s interrupts a long pacing timer', async control => {
|
||||
const playback = new BacktestPlayback(start, 0.001);
|
||||
let processed = 0;
|
||||
const work = playback.process(
|
||||
[start],
|
||||
time => time,
|
||||
async () => {
|
||||
processed++;
|
||||
},
|
||||
() => {}
|
||||
);
|
||||
const outcome = work.catch(error => error);
|
||||
await turn();
|
||||
if (control === 'stop') playback.stop();
|
||||
else playback.setSpeed(null);
|
||||
const settled = await deadline(outcome);
|
||||
if (control === 'stop') expect(settled).toBeInstanceOf(BacktestCancelledError);
|
||||
expect(processed).toBe(control === 'stop' ? 0 : 1);
|
||||
playback.finish();
|
||||
});
|
||||
|
||||
test('cancellation detaches a slow read and a late rejection cannot resume execution', async () => {
|
||||
const playback = new BacktestPlayback(start, null);
|
||||
const load = deferred<number>();
|
||||
const entered = deferred<void>();
|
||||
const work = playback.read(() => {
|
||||
entered.resolve();
|
||||
return load.promise;
|
||||
});
|
||||
const outcome = work.catch(error => error);
|
||||
await entered.promise;
|
||||
playback.stop();
|
||||
expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError);
|
||||
load.reject(new Error('Late read failure'));
|
||||
await turn();
|
||||
let calls = 0;
|
||||
await expect(
|
||||
playback.read(async () => {
|
||||
calls++;
|
||||
return 1;
|
||||
})
|
||||
).rejects.toBeInstanceOf(BacktestCancelledError);
|
||||
expect(calls).toBe(0);
|
||||
playback.finish();
|
||||
});
|
||||
|
||||
test('failed delivery cannot advance its cursor or claim completion', async () => {
|
||||
const playback = new BacktestPlayback(start, null);
|
||||
const updates: number[] = [];
|
||||
await expect(
|
||||
playback.process(
|
||||
[1, 2],
|
||||
time => time,
|
||||
async time => {
|
||||
if (time === 2) throw new Error('delivery failure');
|
||||
},
|
||||
update => updates.push(update.progress)
|
||||
)
|
||||
).rejects.toThrow('delivery failure');
|
||||
expect(playback.getStatus().progress).toBe(50);
|
||||
expect(updates).not.toContain(100);
|
||||
playback.finish();
|
||||
});
|
||||
|
||||
test('speed validation rejects non-finite, zero and negative values', () => {
|
||||
for (const speed of [NaN, Infinity, 0, -1]) {
|
||||
expect(() => new BacktestPlayback(start, speed)).toThrow('positive or null');
|
||||
expect(() => new BacktestPlayback(start, null).setSpeed(speed)).toThrow('positive or null');
|
||||
}
|
||||
});
|
||||
|
||||
test('one playback cannot run two cursors or continue after finalization', async () => {
|
||||
const playback = new BacktestPlayback(start, null);
|
||||
await playback.process(
|
||||
[start],
|
||||
time => time,
|
||||
async () => {},
|
||||
() => {}
|
||||
);
|
||||
await expect(
|
||||
playback.process(
|
||||
[start],
|
||||
time => time,
|
||||
async () => {},
|
||||
() => {}
|
||||
)
|
||||
).rejects.toThrow('already started');
|
||||
playback.finish();
|
||||
await expect(playback.read(async () => 1)).rejects.toBeInstanceOf(BacktestCancelledError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('detached, repeatable backtest reporting', () => {
|
||||
test('analysis runs once per completion and formatting never re-analyzes retained inputs', () => {
|
||||
const analyze = spyOn(PerformanceAnalyzer.prototype, 'analyze');
|
||||
try {
|
||||
const report = new BacktestReport(config, 'cached');
|
||||
report.record(start + day, 990);
|
||||
report.complete(dataset, [trade], [], {});
|
||||
report.export('html');
|
||||
report.export('csv');
|
||||
report.export('json');
|
||||
expect(analyze).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
analyze.mockRestore();
|
||||
}
|
||||
});
|
||||
test('exports retain completed equity and do not append the same trades repeatedly', () => {
|
||||
const report = new BacktestReport(config, 'report');
|
||||
report.record(start, 1000);
|
||||
report.record(start + day, 990);
|
||||
const trades = structuredClone([trade]);
|
||||
const result = report.complete(dataset, trades, [], { totalIssues: 0 });
|
||||
expect(result.metrics.totalTrades).toBe(1);
|
||||
expect(result.config).toMatchObject({ commission: 0.001, slippage: 0.0001 });
|
||||
const first = report.export();
|
||||
const parsed = JSON.parse(first);
|
||||
expect(parsed.summary.totalTrades).toBe(1);
|
||||
expect(parsed.equityCurve.at(-1).value).toBe(990);
|
||||
trades[0]!.pnl = 10000;
|
||||
result.equity[0]!.value = 1;
|
||||
report.export('csv');
|
||||
report.export('html');
|
||||
expect(report.export()).toBe(first);
|
||||
expect(() => report.complete(dataset, [], [], {})).toThrow('already finalized');
|
||||
expect(() => report.record(start + day * 2, 0)).toThrow('already finalized');
|
||||
});
|
||||
|
||||
test('zero and negative equity remain losses, never a fabricated starting balance', () => {
|
||||
const report = new BacktestReport(config, 'loss');
|
||||
report.record(start + day, 0);
|
||||
report.record(start + day * 2, -100);
|
||||
const result = report.complete(dataset, [], [], {});
|
||||
expect(result.equity.map(point => point.value)).toEqual([1000, 0, -100]);
|
||||
expect(result.metrics.totalReturn).toBeCloseTo(-110);
|
||||
expect(result.metrics.maxDrawdown).toBe(1.1);
|
||||
expect(result.analytics.drawdownSeries.at(-1)?.value).toBeCloseTo(-110);
|
||||
expect(
|
||||
Object.values(result.analytics.riskMetrics).every(
|
||||
value => value === null || Number.isFinite(value)
|
||||
)
|
||||
).toBe(true);
|
||||
expect(result.analytics.dailyReturns.every(Number.isFinite)).toBe(true);
|
||||
});
|
||||
|
||||
test('a one-timestamp run has finite analytics, stable timestamp ties and grouped OHLC', () => {
|
||||
const report = new BacktestReport(config, 'single');
|
||||
report.record(start, 999);
|
||||
report.record(start, 998);
|
||||
const result = report.complete(dataset, [], [], {});
|
||||
expect(result.equity).toEqual([{ date: new Date(start).toISOString(), value: 998 }]);
|
||||
expect(result.metrics.totalReturn).toBeCloseTo(-0.2);
|
||||
expect(result.metrics.maxDrawdown).toBeCloseTo(0.002);
|
||||
expect(result.analytics.dailyReturns).toHaveLength(1);
|
||||
expect(result.analytics.dailyReturns[0]).toBeCloseTo(-0.2);
|
||||
expect(result.metrics.sharpeRatio).toBeNull();
|
||||
expect(result.metrics.annualizedReturn).toBeNull();
|
||||
expect(
|
||||
Object.values(result.analytics.riskMetrics).every(
|
||||
value => value === null || Number.isFinite(value)
|
||||
)
|
||||
).toBe(true);
|
||||
expect(Object.keys(result.ohlcData)).toEqual(config.symbols);
|
||||
expect(result.ohlcData['A.US']?.map(bar => bar.timestamp)).toEqual([
|
||||
start,
|
||||
start + day,
|
||||
start + day * 2,
|
||||
]);
|
||||
expect(result.ohlcData['B.US']).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('ongoing drawdown duration uses the simulated horizon, not the wall clock', () => {
|
||||
const report = new BacktestReport(config, 'drawdown');
|
||||
report.record(start + day, 900);
|
||||
report.record(start + day * 4, 800);
|
||||
report.complete(dataset, [], [], {});
|
||||
expect(JSON.parse(report.export()).summary.maxDrawdownDuration).toBe(3);
|
||||
expect(report.export('html')).toContain('20.00%');
|
||||
expect(JSON.parse(report.export()).performanceReport).toContain('Max Drawdown: 20.00%');
|
||||
});
|
||||
|
||||
test('monthly grouping uses UTC, and invalid or unordered observations fail explicitly', () => {
|
||||
const report = new BacktestReport(config, 'utc');
|
||||
report.record(Date.parse('2024-01-31T23:30:00Z'), 1100);
|
||||
report.record(Date.parse('2024-02-01T00:30:00Z'), 1200);
|
||||
const result = report.complete(dataset, [], [], {});
|
||||
expect(Object.keys(result.analytics.monthlyReturns)).toEqual(['2024-01', '2024-02']);
|
||||
expect(result.analytics.monthlyReturns['2024-01']).toBeCloseTo(10);
|
||||
expect(result.analytics.monthlyReturns['2024-02']).toBeCloseTo((100 / 1100) * 100);
|
||||
const invalid = new BacktestReport(config, 'invalid');
|
||||
expect(() => invalid.export()).toThrow('No completed');
|
||||
expect(() => invalid.record(start - 1, 1000)).toThrow('Out-of-order');
|
||||
expect(() => invalid.record(start, NaN)).toThrow('Invalid');
|
||||
expect(() => invalid.record(Infinity, 1000)).toThrow('Invalid');
|
||||
const insolvent = new BacktestReport(config, 'insolvent');
|
||||
insolvent.record(start + day, 0);
|
||||
insolvent.record(Date.parse('2024-02-01T00:30:00Z'), -10);
|
||||
const losses = insolvent.complete(dataset, [], [], {});
|
||||
expect(losses.analytics.monthlyReturns).toEqual({ '2024-01': -100 });
|
||||
});
|
||||
|
||||
test('risk analytics and summary share fraction-based math without 100x percentage scaling', () => {
|
||||
const report = new BacktestReport(config, 'risk');
|
||||
let value = config.initialCapital;
|
||||
for (let i = 1; i <= 30; i++) {
|
||||
value *= 1 + (i % 2 ? -0.01 : 0.02);
|
||||
report.record(start + i * day, value);
|
||||
}
|
||||
const result = report.complete(dataset, [], [], {});
|
||||
const returns = result.analytics.dailyReturns.map(value => value / 100);
|
||||
const average = returns.reduce((sum, value) => sum + value, 0) / returns.length;
|
||||
const expected =
|
||||
Math.sqrt(
|
||||
returns.reduce((sum, value) => sum + (value - average) ** 2, 0) / (returns.length - 1)
|
||||
) * Math.sqrt(252);
|
||||
expect(result.analytics.riskMetrics.volatility).toBeCloseTo(expected, 10);
|
||||
const summary = JSON.parse(report.export()).summary;
|
||||
expect(summary.volatility / 100).toBeCloseTo(expected, 10);
|
||||
expect(summary.var95 / 100).toBeCloseTo(result.analytics.riskMetrics.var95!, 10);
|
||||
expect(summary.cvar95 / 100).toBeCloseTo(result.analytics.riskMetrics.cvar95!, 10);
|
||||
});
|
||||
|
||||
test('quality inspection groups symbols once without changing frozen inputs or retaining old warnings', () => {
|
||||
const input = structuredClone(dataset);
|
||||
for (const bar of input.bars.filter(bar => bar.timestamp === start + day)) {
|
||||
bar.close = bar.symbol === 'A.US' ? 150 : 50;
|
||||
bar.open = bar.close;
|
||||
bar.high = bar.close + 1;
|
||||
bar.low = bar.close - 1;
|
||||
bar.vwap = bar.close;
|
||||
}
|
||||
const before = structuredClone(input);
|
||||
const inspector = new DataManager({
|
||||
async getHistoricalBars() {
|
||||
return [];
|
||||
},
|
||||
});
|
||||
inspector.inspectDataset(input);
|
||||
const quality = inspector.getDataQualityReport();
|
||||
expect(quality.totalIssues).toBe(4);
|
||||
expect(quality.bySymbol).toEqual({ 'A.US': 2, 'B.US': 2 });
|
||||
expect(quality.issues.map(issue => issue.symbol)).toEqual(['A.US', 'A.US', 'B.US', 'B.US']);
|
||||
expect(input).toEqual(before);
|
||||
inspector.inspectDataset(dataset);
|
||||
expect(inspector.getDataQualityReport().totalIssues).toBe(0);
|
||||
});
|
||||
|
||||
test('HTML escapes text and CSV quotes cells while preserving numeric losses', () => {
|
||||
const report = new BacktestReport(config, 'escaping');
|
||||
report.record(start + day, 990);
|
||||
report.complete(dataset, [{ ...trade, symbol: '<script>"bad",\nvalue</script>' }], [], {});
|
||||
expect(report.export('html')).not.toContain('<script>');
|
||||
expect(report.export('html')).toContain('<script>');
|
||||
expect(report.export('csv')).toContain('"<script>""bad"",\nvalue</script>"');
|
||||
expect(report.export('csv')).toContain(',-10,-10');
|
||||
const snapshot = JSON.parse(report.export());
|
||||
snapshot.trades[0].symbol = '=HYPERLINK("hostile")';
|
||||
expect(formatReport(snapshot, 'csv')).toContain('"\'=HYPERLINK(""hostile"")"');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,334 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
|
||||
import {
|
||||
defaultRiskLimits,
|
||||
type Account,
|
||||
type StoredOrder,
|
||||
} from '../../apps/stock/orchestrator/src/execution/model';
|
||||
import type { ExecutionTransaction } from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import type {
|
||||
MarketInput,
|
||||
StrategyCheckpoint,
|
||||
StrategyOrderIntent,
|
||||
} from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
|
||||
|
||||
const initial: Account = {
|
||||
initialCapital: 10000,
|
||||
cash: 10000,
|
||||
realizedPnl: 0,
|
||||
dailyPnl: 0,
|
||||
day: '2024-01-01',
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
limits: { ...defaultRiskLimits },
|
||||
maxQuoteAgeMs: 60000,
|
||||
positions: {},
|
||||
quotes: {},
|
||||
strategyPositions: {},
|
||||
};
|
||||
const input: MarketInput = {
|
||||
id: '10',
|
||||
sequence: 1,
|
||||
status: 'pending',
|
||||
market: {
|
||||
type: 'trade',
|
||||
data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: 1 },
|
||||
},
|
||||
};
|
||||
const request = {
|
||||
symbol: 'A.US',
|
||||
side: 'buy',
|
||||
quantity: 1,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY',
|
||||
clientOrderId: '__proto__',
|
||||
} as const;
|
||||
const order: StoredOrder = {
|
||||
request,
|
||||
fingerprint: 'fingerprint',
|
||||
policy: { commission: 0.001, slippage: 0 },
|
||||
report: {
|
||||
orderId: 'order',
|
||||
clientOrderId: request.clientOrderId,
|
||||
symbol: request.symbol,
|
||||
side: request.side,
|
||||
quantity: 1,
|
||||
status: 'accepted',
|
||||
fills: [],
|
||||
timestamp: 1,
|
||||
},
|
||||
};
|
||||
const checkpoint: StrategyCheckpoint = {
|
||||
strategyId: 'strategy',
|
||||
config: {
|
||||
id: 'strategy',
|
||||
name: 'test',
|
||||
enabled: true,
|
||||
symbols: ['A.US'],
|
||||
parameters: {},
|
||||
allocation: 1,
|
||||
},
|
||||
configHash: 'hash',
|
||||
version: 'v1',
|
||||
enabled: true,
|
||||
cursor: 0,
|
||||
state: { count: 0 },
|
||||
};
|
||||
const intent: StrategyOrderIntent = {
|
||||
clientOrderId: request.clientOrderId,
|
||||
strategyId: checkpoint.strategyId,
|
||||
sequence: 1,
|
||||
request,
|
||||
status: 'pending',
|
||||
};
|
||||
const fill = { id: '__proto__', price: 100, quantity: 1, commission: 0.1, timestamp: 1, pnl: 0 };
|
||||
const journal = {
|
||||
kind: 'market' as const,
|
||||
market: input.market,
|
||||
recipients: ['strategy'],
|
||||
account: initial,
|
||||
};
|
||||
|
||||
async function fixture(account = initial) {
|
||||
const repository = new BacktestExecutionRepository();
|
||||
await repository.initialize('run', account);
|
||||
return {
|
||||
repository,
|
||||
transact: <T>(work: (tx: ExecutionTransaction) => Promise<T>) =>
|
||||
repository.transact('run', work),
|
||||
};
|
||||
}
|
||||
|
||||
describe('run-local execution transaction isolation', () => {
|
||||
test('uninitialized stores fail explicitly', async () => {
|
||||
await expect(new BacktestExecutionRepository().transact('run', async () => 1)).rejects.toThrow(
|
||||
'not initialized'
|
||||
);
|
||||
});
|
||||
|
||||
test('a failed transaction rolls back every table, index, sequence and account mutation', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
f.transact(async tx => {
|
||||
tx.account.cash = 1;
|
||||
await tx.putOrder(order);
|
||||
await tx.insertFill(order.report.orderId, fill);
|
||||
await tx.recordEvent('__proto__', 'hash');
|
||||
await tx.putStrategy(checkpoint);
|
||||
await tx.putIntent(intent);
|
||||
await tx.putInput(input);
|
||||
await tx.appendJournal(journal);
|
||||
expect(await tx.findOrder('__proto__')).toEqual(order);
|
||||
expect(await tx.nextJournal(0)).toMatchObject({ sequence: 1 });
|
||||
throw new Error('rollback');
|
||||
})
|
||||
).rejects.toThrow('rollback');
|
||||
await f.transact(async tx => {
|
||||
expect(tx.account.cash).toBe(10000);
|
||||
expect(tx.account.strategySequence).toBeUndefined();
|
||||
expect(await tx.findOrder('__proto__')).toBeUndefined();
|
||||
expect(await tx.getOrder('order')).toBeUndefined();
|
||||
expect(await tx.openOrders()).toEqual([]);
|
||||
expect(await tx.strategies()).toEqual([]);
|
||||
expect(await tx.nextIntent()).toBeUndefined();
|
||||
expect(await tx.nextInput()).toBeUndefined();
|
||||
expect(await tx.nextJournal(0)).toBeUndefined();
|
||||
expect(await tx.recordEvent('__proto__', 'hash')).toBe(true);
|
||||
expect(await tx.insertFill('order', fill)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test('caller-owned objects, returned reads and retained transaction references cannot mutate commits', async () => {
|
||||
const seed = structuredClone(initial);
|
||||
const f = await fixture(seed);
|
||||
seed.cash = 0;
|
||||
const writes = structuredClone({ order, checkpoint, intent, input, journal });
|
||||
let escaped!: ExecutionTransaction;
|
||||
const result = await f.transact(async tx => {
|
||||
escaped = tx;
|
||||
await tx.putOrder(writes.order);
|
||||
await tx.putStrategy(writes.checkpoint);
|
||||
await tx.putIntent(writes.intent);
|
||||
await tx.putInput(writes.input);
|
||||
await tx.appendJournal(writes.journal);
|
||||
return tx.account;
|
||||
});
|
||||
result.cash = 2;
|
||||
escaped.account.cash = 3;
|
||||
writes.order.report.status = 'rejected';
|
||||
writes.checkpoint.enabled = false;
|
||||
writes.intent.status = 'dispatched';
|
||||
writes.input.status = 'applied';
|
||||
writes.journal.account.cash = 4;
|
||||
await expect(escaped.putInput(input)).rejects.toThrow('finished');
|
||||
await f.transact(async tx => {
|
||||
expect(tx.account.cash).toBe(10000);
|
||||
(await tx.getOrder('order'))!.report.status = 'rejected';
|
||||
(await tx.strategies())[0]!.enabled = false;
|
||||
(await tx.nextInput())!.status = 'applied';
|
||||
(await tx.nextIntent())!.status = 'dispatched';
|
||||
(await tx.nextJournal(0))!.payload.account.cash = 5;
|
||||
});
|
||||
await f.transact(async tx => {
|
||||
expect(await tx.openOrders()).toEqual([order]);
|
||||
expect(await tx.strategies()).toEqual([checkpoint]);
|
||||
expect(await tx.nextInput()).toEqual(input);
|
||||
expect(await tx.nextIntent()).toEqual(intent);
|
||||
expect((await tx.nextJournal(0))?.payload.account.cash).toBe(10000);
|
||||
});
|
||||
});
|
||||
|
||||
test('uncloneable callback results roll back before publishing any staged writes', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
f.transact(async tx => {
|
||||
tx.account.cash = 0;
|
||||
await tx.putOrder(order);
|
||||
return () => {};
|
||||
})
|
||||
).rejects.toThrow();
|
||||
await f.transact(async tx => {
|
||||
expect(tx.account.cash).toBe(10000);
|
||||
expect(await tx.openOrders()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test('transactions serialize and a failed predecessor does not poison the queue', async () => {
|
||||
const f = await fixture();
|
||||
const results = await Promise.allSettled([
|
||||
f.transact(async tx => {
|
||||
tx.account.cash -= 1;
|
||||
await Promise.resolve();
|
||||
}),
|
||||
f.transact(async tx => {
|
||||
tx.account.cash = -1;
|
||||
throw new Error('rollback');
|
||||
}),
|
||||
f.transact(async tx => {
|
||||
tx.account.cash -= 2;
|
||||
}),
|
||||
]);
|
||||
expect(results.map(result => result.status)).toEqual(['fulfilled', 'rejected', 'fulfilled']);
|
||||
expect(await f.transact(async tx => tx.account.cash)).toBe(9997);
|
||||
});
|
||||
|
||||
test('pending indexes reflect staged updates, and rollback preserves their previous heads', async () => {
|
||||
const f = await fixture();
|
||||
await f.transact(async tx => {
|
||||
await tx.putOrder(order);
|
||||
await tx.putInput(input);
|
||||
await tx.putInput({ ...input, id: '2', sequence: 2 });
|
||||
await tx.putIntent(intent);
|
||||
await tx.putIntent({
|
||||
...intent,
|
||||
clientOrderId: 'next',
|
||||
sequence: 2,
|
||||
request: { ...request, clientOrderId: 'next' },
|
||||
});
|
||||
});
|
||||
const drain = async (tx: ExecutionTransaction) => {
|
||||
await tx.putOrder({ ...order, report: { ...order.report, status: 'filled' } });
|
||||
await tx.putInput({ ...input, status: 'applied' });
|
||||
await tx.putIntent({ ...intent, status: 'dispatched' });
|
||||
expect(await tx.openOrders()).toEqual([]);
|
||||
expect((await tx.nextInput())?.id).toBe('2');
|
||||
expect((await tx.nextIntent())?.clientOrderId).toBe('next');
|
||||
};
|
||||
await expect(
|
||||
f.transact(async tx => {
|
||||
await drain(tx);
|
||||
throw new Error('rollback');
|
||||
})
|
||||
).rejects.toThrow('rollback');
|
||||
await f.transact(async tx => {
|
||||
expect(await tx.openOrders()).toEqual([order]);
|
||||
expect(await tx.nextInput()).toEqual(input);
|
||||
expect(await tx.nextIntent()).toEqual(intent);
|
||||
await drain(tx);
|
||||
});
|
||||
await f.transact(async tx => {
|
||||
expect(await tx.openOrders()).toEqual([]);
|
||||
expect((await tx.nextInput())?.id).toBe('2');
|
||||
expect((await tx.nextIntent())?.clientOrderId).toBe('next');
|
||||
});
|
||||
});
|
||||
|
||||
test('journal lookup supports nonzero sequences, gaps at the cursor and staged appends', async () => {
|
||||
const f = await fixture({ ...initial, strategySequence: 20 });
|
||||
await f.transact(async tx => {
|
||||
await tx.appendJournal(journal);
|
||||
await tx.appendJournal(journal);
|
||||
});
|
||||
await f.transact(async tx => {
|
||||
await tx.appendJournal(journal);
|
||||
for (const [cursor, expected] of [
|
||||
[-1, 21],
|
||||
[20, 21],
|
||||
[21, 22],
|
||||
[22, 23],
|
||||
[23, undefined],
|
||||
[100, undefined],
|
||||
]) {
|
||||
expect((await tx.nextJournal(cursor!))?.sequence).toBe(expected);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('sequence exhaustion cannot commit a partial journal or account change', async () => {
|
||||
const f = await fixture({ ...initial, strategySequence: Number.MAX_SAFE_INTEGER });
|
||||
await expect(
|
||||
f.transact(async tx => {
|
||||
tx.account.cash = 1;
|
||||
await tx.appendJournal(journal);
|
||||
})
|
||||
).rejects.toThrow('exhausted');
|
||||
expect(await f.transact(async tx => tx.account.cash)).toBe(10000);
|
||||
});
|
||||
|
||||
test('pending-intent ties use deterministic sequence, strategy and client ID order', async () => {
|
||||
const f = await fixture();
|
||||
await f.transact(async tx => {
|
||||
for (const [strategyId, clientOrderId, sequence] of [
|
||||
['b', '1', 1],
|
||||
['a', '2', 1],
|
||||
['a', '10', 1],
|
||||
['0', '0', 2],
|
||||
] as const) {
|
||||
await tx.putIntent({
|
||||
...intent,
|
||||
strategyId,
|
||||
clientOrderId,
|
||||
sequence,
|
||||
request: { ...request, clientOrderId },
|
||||
});
|
||||
}
|
||||
});
|
||||
for (const expected of ['10', '2', '1', '0']) {
|
||||
await f.transact(async tx => {
|
||||
const next = (await tx.nextIntent())!;
|
||||
expect(next.clientOrderId).toBe(expected);
|
||||
await tx.putIntent({ ...next, status: 'dispatched' });
|
||||
});
|
||||
}
|
||||
expect(await f.transact(tx => tx.nextIntent())).toBeUndefined();
|
||||
});
|
||||
|
||||
test('duplicate financial identities are indexed safely, including special JavaScript keys', async () => {
|
||||
const f = await fixture();
|
||||
await f.transact(async tx => {
|
||||
await tx.putOrder(order);
|
||||
expect(await tx.findOrder('__proto__')).toEqual(order);
|
||||
expect(await tx.insertFill('order', fill)).toBe(true);
|
||||
expect(await tx.insertFill('order', fill)).toBe(false);
|
||||
expect(await tx.recordEvent('constructor', 'hash')).toBe(true);
|
||||
expect(await tx.recordEvent('constructor', 'hash')).toBe(false);
|
||||
});
|
||||
await expect(
|
||||
f.transact(tx => tx.putOrder({ ...order, report: { ...order.report, orderId: 'duplicate' } }))
|
||||
).rejects.toThrow('already exists');
|
||||
await expect(f.transact(tx => tx.recordEvent('constructor', 'different'))).rejects.toThrow(
|
||||
'Conflicting'
|
||||
);
|
||||
expect(await f.transact(tx => tx.insertFill('order', fill))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -17,7 +17,7 @@ import {
|
|||
import {
|
||||
canonicalWorkerUrl,
|
||||
readCanonicalBuildIdentity,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
} from '@stock-bot/trading-runtime/canonical-build';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
|
||||
|
||||
test('canonical mean-reversion selection requires its exact version and explicit compatible parameters', () => {
|
||||
|
|
|
|||
|
|
@ -4,12 +4,12 @@ import {
|
|||
meanReversionStrategySelectionSchema,
|
||||
type MeanReversionSignalParameters,
|
||||
type MeanReversionStrategySelection,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
StrategyContext,
|
||||
StrategyProgram,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import type { PublishedObservation } from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
calculateMeanReversionSignals,
|
||||
createMeanReversionStrategy,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import {
|
||||
parseReplayReportResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const policy: CanonicalMetricsInput = {
|
||||
|
|
|
|||
|
|
@ -4,15 +4,15 @@ import { parseFinancialDecimal, type FinancialStrategyIntent } from '@stock-bot/
|
|||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
StrategyContext,
|
||||
StrategyProgram,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import type {
|
||||
ReplayProjectionResult,
|
||||
ReplayReportResult,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import {
|
||||
parseReplayReportValue,
|
||||
type ReplayConfig,
|
||||
type ReplayReportResult,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
const policy: CanonicalMetricsInput = {
|
||||
version: 1,
|
||||
|
|
|
|||
|
|
@ -9,14 +9,13 @@ import {
|
|||
builtinStrategySelectionSchema,
|
||||
smaStrategySelectionSchema,
|
||||
type SmaStrategySelection,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
StrategyContext,
|
||||
StrategyProgram,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { strategyAliases } from '../../apps/stock/orchestrator/src/contracts/strategy-names';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import type { PublishedObservation } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { strategyAliases } from '@stock-bot/stock-config/strategy-names';
|
||||
import { validateBuiltinStrategyBindings } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import {
|
||||
createSmaStrategy as createBuiltinStrategy,
|
||||
|
|
@ -146,7 +145,6 @@ test('sma_registry_alias selects only the explicit canonical version and leaves
|
|||
]) {
|
||||
expect(() => builtinStrategySelectionSchema.parse({ ...selection(), ...patch })).toThrow();
|
||||
}
|
||||
expect(typeof createBuiltinStrategyRegistry().create).toBe('function');
|
||||
});
|
||||
|
||||
test('binding validation rejects wrong owners, mode, cadence, instrument and unknown series before replay', () => {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/st
|
|||
import {
|
||||
replayIdentitySchema,
|
||||
type ReplayResultFormat,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ import type {
|
|||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { parseFinancialDecimal as decimal } from '@stock-bot/types';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import type {
|
||||
CreateBacktestRequest,
|
||||
Run,
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import {
|
|||
import {
|
||||
StorageService,
|
||||
type HistoricalBar,
|
||||
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
} from '@stock-bot/trading-runtime/historical-storage';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
createDatasetV2,
|
||||
validateDatasetV2,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { retainResearchDataset } from '../../apps/stock/orchestrator/src/data/retained-research-dataset';
|
||||
import { retainResearchDataset } from '@stock-bot/trading-runtime/retained-dataset';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service';
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,206 +0,0 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
|
||||
import { config, makeExecution, order, quote, start } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const runId = '00000000-0000-4000-8000-000000000003';
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
const repository = new BacktestExecutionRepository();
|
||||
const runtime = makeExecution(repository);
|
||||
await runtime.execution.initialize(
|
||||
{
|
||||
...config,
|
||||
runId,
|
||||
commission: 0.01,
|
||||
riskLimits: {
|
||||
maxOrderSize: 10000,
|
||||
maxPositionSize: 10000,
|
||||
maxDailyLoss: 1000000,
|
||||
maxSymbolExposure: 1000000,
|
||||
maxGrossExposure: 1000000,
|
||||
},
|
||||
},
|
||||
runtime.engine
|
||||
);
|
||||
cleanup.push(() => runtime.execution.shutdown());
|
||||
return { ...runtime, repository };
|
||||
}
|
||||
|
||||
describe('fee-inclusive legacy capital commitments', () => {
|
||||
test('fee_budget_10000: an otherwise fully funded buy rejects without financial mutation', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q'));
|
||||
const before = await execution.getAccount();
|
||||
|
||||
const report = await execution.submitOrder(order('unfunded', 'buy', 100));
|
||||
|
||||
expect(report.status).toBe('rejected');
|
||||
expect(report.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
expect(report.fills).toEqual([]);
|
||||
expect(await execution.getAccount()).toEqual(before);
|
||||
expect(await execution.getPositions()).toEqual([]);
|
||||
});
|
||||
|
||||
test('fee_budget_99: entry fees leave exactly one unit of cash', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q'));
|
||||
|
||||
const report = await execution.submitOrder(order('funded', 'buy', 99));
|
||||
|
||||
expect(report.status).toBe('filled');
|
||||
expect(report.fills.map(fill => fill.commission)).toEqual([99]);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
expect((await execution.getAccount()).equity).toBe(9901);
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(99);
|
||||
});
|
||||
|
||||
test('pending_fee_commitments and cancelled_commitment_released: two commitments of 5050 cannot fit 10000', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('a', 100, 0));
|
||||
await execution.onMarketData(quote('b', 100, 0, start, 'B'));
|
||||
const first = await execution.submitOrder(order('first', 'buy', 50));
|
||||
expect(first.status).toBe('accepted');
|
||||
expect(first.fills).toEqual([]);
|
||||
|
||||
const second = await execution.submitOrder({ ...order('second', 'buy', 50), symbol: 'B' });
|
||||
expect(second.status).toBe('rejected');
|
||||
expect(second.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
expect((await execution.getAccount()).cash).toBe(10000);
|
||||
|
||||
expect(await execution.cancelOrder(first.orderId)).toBe(true);
|
||||
const replacement = await execution.submitOrder({
|
||||
...order('replacement', 'buy', 99),
|
||||
symbol: 'B',
|
||||
});
|
||||
expect(replacement.status).toBe('accepted');
|
||||
await execution.onMarketData(quote('b-fill', 100, 99, start + 1, 'B'));
|
||||
expect((await execution.getOrderStatus(replacement.orderId))?.status).toBe('filled');
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
expect((await execution.getOrderStatus(first.orderId))?.fills).toEqual([]);
|
||||
});
|
||||
|
||||
test('partial_fee_not_double_counted: fills 10 then 89 charge 99 once, including duplicate events', async () => {
|
||||
const { execution } = await fixture();
|
||||
const firstQuote = quote('q1', 100, 10);
|
||||
await execution.onMarketData(firstQuote);
|
||||
const first = await execution.submitOrder(order('partial', 'buy', 99));
|
||||
expect(first.status).toBe('partiallyFilled');
|
||||
expect(first.fills.map(fill => [fill.quantity, fill.commission])).toEqual([[10, 10]]);
|
||||
expect((await execution.getAccount()).cash).toBe(8990);
|
||||
|
||||
expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(first);
|
||||
expect(await execution.onMarketData(firstQuote)).toBe(false);
|
||||
const nextQuote = quote('q2', 100, 89, start + 1);
|
||||
await execution.onMarketData(nextQuote);
|
||||
const complete = await execution.getOrderStatus(first.orderId);
|
||||
expect(complete?.status).toBe('filled');
|
||||
expect(complete?.fills.map(fill => [fill.quantity, fill.commission])).toEqual([
|
||||
[10, 10],
|
||||
[89, 89],
|
||||
]);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
const beforeRetry = await execution.getAccount();
|
||||
expect(await execution.onMarketData(nextQuote)).toBe(false);
|
||||
expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(complete);
|
||||
expect(await execution.getAccount()).toEqual(beforeRetry);
|
||||
});
|
||||
|
||||
test('frozen_order_fee_policy: pending commitments retain their original commission', async () => {
|
||||
const { execution, repository } = await fixture();
|
||||
await execution.onMarketData(quote('q', 100, 0));
|
||||
const first = await execution.submitOrder(order('first', 'buy', 50));
|
||||
expect(first.status).toBe('accepted');
|
||||
await repository.transact(runId, async tx => {
|
||||
tx.account.commission = 0;
|
||||
});
|
||||
|
||||
const second = await execution.submitOrder(order('second', 'buy', 50));
|
||||
expect(second.status).toBe('rejected');
|
||||
expect(second.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
await execution.onMarketData(quote('fill', 100, 50, start + 1));
|
||||
expect((await execution.getOrderStatus(first.orderId))?.fills[0]?.commission).toBe(50);
|
||||
expect((await execution.getAccount()).cash).toBe(4950);
|
||||
});
|
||||
|
||||
test('a partially filled pending order reserves only its unpaid remaining fees for another order', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q1', 100, 10));
|
||||
const partial = await execution.submitOrder(order('partial', 'buy', 50));
|
||||
expect(partial.status).toBe('partiallyFilled');
|
||||
expect(partial.fills[0]?.commission).toBe(10);
|
||||
|
||||
const pending = await execution.submitOrder(order('other', 'buy', 49));
|
||||
expect(pending.status).toBe('accepted');
|
||||
await execution.onMarketData(quote('q2', 100, 89, start + 1));
|
||||
const first = await execution.getOrderStatus(partial.orderId);
|
||||
const second = await execution.getOrderStatus(pending.orderId);
|
||||
expect(first?.status).toBe('filled');
|
||||
expect(first?.fills.map(fill => fill.commission)).toEqual([10, 40]);
|
||||
expect(second?.status).toBe('filled');
|
||||
expect(second?.fills.map(fill => fill.commission)).toEqual([49]);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
});
|
||||
|
||||
test('frozen_order_fee_policy: fill-time admission uses stored rather than current commission', async () => {
|
||||
const { execution, repository } = await fixture();
|
||||
await execution.onMarketData(quote('q', 100, 0));
|
||||
const pending = await execution.submitOrder(order('pending', 'buy', 99));
|
||||
expect(pending.status).toBe('accepted');
|
||||
await repository.transact(runId, async tx => {
|
||||
tx.account.commission = 0.5;
|
||||
});
|
||||
|
||||
await execution.onMarketData(quote('fill', 100, 99, start + 1));
|
||||
const report = await execution.getOrderStatus(pending.orderId);
|
||||
expect(report?.status).toBe('filled');
|
||||
expect(report?.fills[0]?.commission).toBe(99);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
});
|
||||
|
||||
test('fill-time repricing cannot consume capital reserved for unpaid fees', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q', 99, 0));
|
||||
const pending = await execution.submitOrder(order('pending', 'buy', 100));
|
||||
expect(pending.status).toBe('accepted');
|
||||
|
||||
await execution.onMarketData(quote('gap', 100, 100, start + 1));
|
||||
const report = await execution.getOrderStatus(pending.orderId);
|
||||
expect(report?.status).toBe('cancelled');
|
||||
expect(report?.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
expect(report?.fills).toEqual([]);
|
||||
expect((await execution.getAccount()).cash).toBe(10000);
|
||||
});
|
||||
|
||||
test('existing long/short reversal behavior is unchanged', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q'));
|
||||
for (const [id, side, quantity] of [
|
||||
['long', 'buy', 10],
|
||||
['reverse', 'sell', 20],
|
||||
['close', 'buy', 10],
|
||||
] as const) {
|
||||
expect((await execution.submitOrder(order(id, side, quantity))).status).toBe('filled');
|
||||
}
|
||||
expect((await execution.getAccount()).cash).toBe(9960);
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(0);
|
||||
});
|
||||
|
||||
test('reducing-order exemption still permits an insolvent short cover under legacy policy', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('short', 100, 99));
|
||||
expect((await execution.submitOrder(order('short', 'sell', 99))).status).toBe('filled');
|
||||
await execution.onMarketData(quote('gap', 200, 99, start + 1));
|
||||
|
||||
const report = await execution.submitOrder(order('cover', 'buy', 99));
|
||||
expect(report.status).toBe('filled');
|
||||
expect(report.fills[0]?.commission).toBe(198);
|
||||
expect((await execution.getAccount()).cash).toBe(-197);
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { atr, ema, macd, rsi, trailingSimpleRsi } from '@stock-bot/calculations/indicators';
|
||||
import { IncrementalEMA, IncrementalRSI, TechnicalIndicators } from '@stock-bot/engine';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||
import {
|
||||
calculateATR,
|
||||
calculateBollingerBands,
|
||||
|
|
@ -112,7 +111,6 @@ test('mean-reversion/v2 keeps exact rolling-RSI arithmetic and checkpoint identi
|
|||
}
|
||||
}
|
||||
expect(trailingSimpleRsi([1, 1, 1, 1], 3, 100)).toBe(100);
|
||||
expect(MeanReversionStrategy.prototype.getCheckpointVersion()).toBe('mean-reversion/v2');
|
||||
});
|
||||
|
||||
test('chart adapters map real source timestamps, warm-up and final rounding only', () => {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import {
|
|||
loadDataset,
|
||||
validateDataset,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { StorageService } from '@stock-bot/trading-runtime/historical-storage';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import {
|
|||
HistoricalStorageError,
|
||||
StorageService,
|
||||
type HistoricalStorageProvider,
|
||||
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
} from '@stock-bot/trading-runtime/historical-storage';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { end, identity, intradayResponse, metadata, start } from '../fixtures/intraday/eod';
|
||||
|
||||
|
|
|
|||
|
|
@ -1,199 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { config, logger } from '../fixtures/execution';
|
||||
|
||||
function fixture(failAt?: string) {
|
||||
const calls: string[] = [];
|
||||
const failure = new Error('injected lifecycle failure');
|
||||
const failures = new Map<string, unknown>();
|
||||
const resources = new Set<string>();
|
||||
if (failAt) {
|
||||
failures.set(failAt, failure);
|
||||
}
|
||||
const record = async (step: string) => {
|
||||
calls.push(step);
|
||||
const [service, operation] = step.split('.');
|
||||
if (!service || !operation) {
|
||||
throw new Error('Invalid lifecycle fixture step');
|
||||
}
|
||||
if (operation === 'shutdown') {
|
||||
resources.delete(service);
|
||||
} else {
|
||||
resources.add(service);
|
||||
}
|
||||
if (failures.has(step)) {
|
||||
throw failures.get(step);
|
||||
}
|
||||
};
|
||||
const mode = new ModeManager({
|
||||
logger,
|
||||
execution: {
|
||||
initialize: () => record('execution.initialize'),
|
||||
shutdown: () => record('execution.shutdown'),
|
||||
},
|
||||
strategies: {
|
||||
restoreStrategies: () => record('strategies.restore'),
|
||||
shutdown: () => record('strategies.shutdown'),
|
||||
},
|
||||
marketData: {
|
||||
initialize: () => record('market.initialize'),
|
||||
shutdown: () => record('market.shutdown'),
|
||||
},
|
||||
});
|
||||
return { mode, calls, failure, failures, resources };
|
||||
}
|
||||
|
||||
describe('explicit mode lifecycle dependencies', () => {
|
||||
test('paper recovery completes before the feed starts; shutdown drains the feed before strategies and execution', async () => {
|
||||
const f = fixture();
|
||||
await f.mode.initializeMode({ mode: 'paper', startingCapital: 10000 });
|
||||
expect(f.calls).toEqual(['execution.initialize', 'strategies.restore', 'market.initialize']);
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls.slice(3)).toEqual([
|
||||
'market.shutdown',
|
||||
'strategies.shutdown',
|
||||
'execution.shutdown',
|
||||
]);
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
expect(f.mode.getConfig()).toBeNull();
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls).toHaveLength(6);
|
||||
});
|
||||
|
||||
test('backtest mode replaces the current engine without restoring paper strategies', async () => {
|
||||
const f = fixture();
|
||||
await f.mode.initializeMode(config);
|
||||
const prior = f.mode.getTradingEngine();
|
||||
await f.mode.initializeMode(config);
|
||||
expect(f.mode.getTradingEngine()).not.toBe(prior);
|
||||
expect(f.calls).toEqual([
|
||||
'execution.initialize',
|
||||
'market.initialize',
|
||||
'market.shutdown',
|
||||
'strategies.shutdown',
|
||||
'execution.shutdown',
|
||||
'execution.initialize',
|
||||
'market.initialize',
|
||||
]);
|
||||
await f.mode.shutdown();
|
||||
});
|
||||
|
||||
test.each(['market.shutdown', 'strategies.shutdown', 'execution.shutdown'])(
|
||||
'%s failure still closes every other dependency and clears the mode engine',
|
||||
async failAt => {
|
||||
const f = fixture(failAt);
|
||||
await f.mode.initializeMode(config);
|
||||
await expect(f.mode.shutdown()).rejects.toBe(f.failure);
|
||||
expect(f.calls.slice(2)).toEqual([
|
||||
'market.shutdown',
|
||||
'strategies.shutdown',
|
||||
'execution.shutdown',
|
||||
]);
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
expect(f.mode.getConfig()).toBeNull();
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls).toHaveLength(5);
|
||||
}
|
||||
);
|
||||
|
||||
const paper = { mode: 'paper' as const, startingCapital: 10000 };
|
||||
const initialization = ['execution.initialize', 'strategies.restore', 'market.initialize'];
|
||||
const cleanup = ['market.shutdown', 'strategies.shutdown', 'execution.shutdown'];
|
||||
|
||||
test.each(initialization)(
|
||||
'partial acquisition in %s cleans up attempted stages and allows retry without a success event',
|
||||
async failAt => {
|
||||
const f = fixture(failAt);
|
||||
const events: unknown[] = [];
|
||||
f.mode.on('modeChanged', changed => events.push(changed));
|
||||
await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure);
|
||||
|
||||
const attempted = initialization.slice(0, initialization.indexOf(failAt) + 1);
|
||||
const acquired = new Set(attempted.map(step => step.split('.')[0]));
|
||||
const applicableCleanup = cleanup.filter(step => acquired.has(step.split('.')[0]));
|
||||
expect(f.calls).toEqual([...attempted, ...applicableCleanup]);
|
||||
expect(f.resources.size).toBe(0);
|
||||
expect(events).toEqual([]);
|
||||
expect(f.mode.getConfig()).toBeNull();
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
|
||||
const cleanupCount = f.calls.length;
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls).toHaveLength(cleanupCount);
|
||||
f.failures.clear();
|
||||
await f.mode.initializeMode(paper);
|
||||
expect(f.calls.slice(cleanupCount)).toEqual(initialization);
|
||||
expect(events).toEqual([paper]);
|
||||
expect(f.mode.getConfig()).toEqual(paper);
|
||||
expect(f.mode.getTradingEngine()).toBeDefined();
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls.slice(cleanupCount + initialization.length)).toEqual(cleanup);
|
||||
expect(f.resources.size).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
test.each(cleanup)(
|
||||
'%s cleanup failure does not mask initialization error or skip remaining cleanup',
|
||||
async cleanupFailure => {
|
||||
const f = fixture('market.initialize');
|
||||
f.failures.set(cleanupFailure, new Error('injected cleanup failure'));
|
||||
await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure);
|
||||
expect(f.calls).toEqual([...initialization, ...cleanup]);
|
||||
expect(f.resources.size).toBe(0);
|
||||
expect(f.mode.getConfig()).toBeNull();
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
|
||||
f.failures.clear();
|
||||
await f.mode.initializeMode(paper);
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls).toEqual([...initialization, ...cleanup, ...initialization, ...cleanup]);
|
||||
}
|
||||
);
|
||||
|
||||
test('failed mode replacement does not expose the prior or partially created engine', async () => {
|
||||
const f = fixture();
|
||||
await f.mode.initializeMode(config);
|
||||
const prior = f.mode.getTradingEngine();
|
||||
f.failures.set('strategies.restore', f.failure);
|
||||
await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure);
|
||||
expect(f.mode.getConfig()).toBeNull();
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
|
||||
f.failures.clear();
|
||||
await f.mode.initializeMode(paper);
|
||||
expect(f.mode.getTradingEngine()).not.toBe(prior);
|
||||
await f.mode.shutdown();
|
||||
});
|
||||
|
||||
test('invalid configuration and disabled live trading reject before lifecycle side effects', async () => {
|
||||
const f = fixture();
|
||||
await expect(f.mode.initializeMode({ mode: 'paper', startingCapital: -1 })).rejects.toThrow();
|
||||
expect(f.calls).toEqual([]);
|
||||
expect(f.mode.getConfig()).toBeNull();
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
|
||||
const live = {
|
||||
mode: 'live' as const,
|
||||
broker: 'disabled',
|
||||
accountId: 'disabled',
|
||||
accountType: 'cash' as const,
|
||||
riskLimits: {
|
||||
maxPositionSize: 1,
|
||||
maxDailyLoss: 1,
|
||||
maxOrderSize: 1,
|
||||
maxGrossExposure: 1,
|
||||
maxSymbolExposure: 1,
|
||||
},
|
||||
};
|
||||
await expect(f.mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
|
||||
expect(f.calls).toEqual([]);
|
||||
await f.mode.initializeMode(paper);
|
||||
const engine = f.mode.getTradingEngine();
|
||||
await expect(f.mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
|
||||
await expect(f.mode.initializeMode({ mode: 'paper', startingCapital: -1 })).rejects.toThrow();
|
||||
expect(f.calls).toEqual(initialization);
|
||||
expect(f.mode.getConfig()).toEqual(paper);
|
||||
expect(f.mode.getTradingEngine()).toBe(engine);
|
||||
await f.mode.shutdown();
|
||||
});
|
||||
});
|
||||
|
|
@ -14,7 +14,7 @@ import {
|
|||
parseReplayProjectionResult,
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const intent = (quantity = '2') => ({
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import {
|
|||
parseReplayReportResult,
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const hold = () => ({ mode: 'target' as const, targets: [] });
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest
|
|||
import {
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
|
|
|||
|
|
@ -1,250 +0,0 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { TradingEngine } from '@stock-bot/engine';
|
||||
import { createOrderRoutes } from '../../apps/stock/orchestrator/src/api/rest/orders';
|
||||
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import type { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
|
||||
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import {
|
||||
BaseStrategy,
|
||||
type Signal,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type { MarketData } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
});
|
||||
async function fixture() {
|
||||
const runtime = makeExecution();
|
||||
await runtime.execution.initialize(config, runtime.engine);
|
||||
cleanup.push(() => runtime.execution.shutdown());
|
||||
return runtime;
|
||||
}
|
||||
describe('one simulation execution gateway', () => {
|
||||
test('identical client IDs return one order/fill; conflicting retries cannot mutate accounting', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q1'));
|
||||
const reports = await Promise.all([
|
||||
execution.submitOrder(order('id')),
|
||||
execution.submitOrder(order('id')),
|
||||
]);
|
||||
expect(reports[0]).toEqual(reports[1]);
|
||||
expect(reports[0]!.status).toBe('filled');
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(10);
|
||||
await expect(execution.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf(
|
||||
ExecutionConflictError
|
||||
);
|
||||
expect((await execution.getAccount()).cash).toBe(8999);
|
||||
});
|
||||
test('quote liquidity is consumed once; partial fills complete across distinct events only', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q1', 100, 3));
|
||||
const first = await execution.submitOrder(order('partial', 'buy', 10));
|
||||
expect(first.status).toBe('partiallyFilled');
|
||||
expect(first.fills[0]?.quantity).toBe(3);
|
||||
expect(await execution.onMarketData(quote('q1', 100, 3))).toBe(false);
|
||||
await execution.onMarketData(quote('q2', 100, 4, start + 1));
|
||||
expect((await execution.getOrderStatus(first.orderId))?.fills.map(f => f.quantity)).toEqual([
|
||||
3, 4,
|
||||
]);
|
||||
await execution.onMarketData(quote('q3', 100, 50, start + 2));
|
||||
const report = await execution.getOrderStatus(first.orderId);
|
||||
expect(report?.status).toBe('filled');
|
||||
expect(report?.fills.map(f => f.quantity)).toEqual([3, 4, 3]);
|
||||
expect((await execution.getAccount()).cash).toBe(8999);
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(10);
|
||||
});
|
||||
test('long/short partial closes and reversals conserve equity and charge commission exactly once', async () => {
|
||||
const { execution, engine } = await fixture();
|
||||
for (const [i, side, price, quantity] of [
|
||||
[0, 'buy', 100, 10],
|
||||
[1, 'sell', 110, 4],
|
||||
[2, 'sell', 90, 10],
|
||||
[3, 'buy', 80, 4],
|
||||
] as const) {
|
||||
await execution.onMarketData(quote('q' + i, price, 100, start + i));
|
||||
await execution.submitOrder(order('o' + i, side, quantity));
|
||||
}
|
||||
const account = await execution.getAccount();
|
||||
expect(account.cash).toBeCloseTo(10017.34, 8);
|
||||
expect(account.equity).toBe(account.cash);
|
||||
expect(account.realizedPnl).toBeCloseTo(17.34, 8);
|
||||
expect(account.dailyPnl).toBe(account.realizedPnl);
|
||||
expect(account.positions.A?.quantity).toBe(0);
|
||||
expect(account.positions.A?.averagePrice).toBe(0);
|
||||
const [native] = engine.getTotalPnl();
|
||||
expect(native).toBeCloseTo(account.realizedPnl, 8);
|
||||
});
|
||||
test('pending reservations and projected notional enforce limits across symbols', async () => {
|
||||
const { execution, engine } = await fixture();
|
||||
await execution.initialize(
|
||||
{
|
||||
...config,
|
||||
riskLimits: {
|
||||
maxOrderSize: 100,
|
||||
maxPositionSize: 100,
|
||||
maxDailyLoss: 100,
|
||||
maxSymbolExposure: 800,
|
||||
maxGrossExposure: 1000,
|
||||
},
|
||||
},
|
||||
engine
|
||||
);
|
||||
await execution.onMarketData(quote('a', 100, 0));
|
||||
await execution.onMarketData(quote('b', 100, 0, start, 'B'));
|
||||
expect((await execution.submitOrder(order('pending', 'buy', 6))).status).toBe('accepted');
|
||||
expect((await execution.submitOrder(order('over', 'buy', 3))).status).toBe('rejected');
|
||||
const other = { ...order('b', 'buy', 5), symbol: 'B' };
|
||||
expect((await execution.submitOrder(other)).status).toBe('rejected');
|
||||
expect(await execution.getPositions()).toHaveLength(0);
|
||||
});
|
||||
test('IOC/FOK and limits have truthful states; cancellations cannot cancel an already filled order', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q', 100, 3));
|
||||
const fok = await execution.submitOrder({ ...order('fok'), timeInForce: 'FOK' });
|
||||
expect(fok.status).toBe('cancelled');
|
||||
expect(fok.fills).toHaveLength(0);
|
||||
const ioc = await execution.submitOrder({ ...order('ioc'), timeInForce: 'IOC' });
|
||||
expect(ioc.status).toBe('cancelled');
|
||||
expect(ioc.fills[0]?.quantity).toBe(3);
|
||||
const limit = await execution.submitOrder({
|
||||
...order('limit', 'buy', 1),
|
||||
orderType: 'limit',
|
||||
limitPrice: 90,
|
||||
});
|
||||
expect(limit.status).toBe('accepted');
|
||||
expect(await execution.cancelOrder(limit.orderId)).toBe(true);
|
||||
await execution.onMarketData(quote('q2', 80, 100, start + 1));
|
||||
expect((await execution.getOrderStatus(limit.orderId))?.fills).toHaveLength(0);
|
||||
const filled = await execution.submitOrder(order('filled', 'buy', 1));
|
||||
expect(await execution.cancelOrder(filled.orderId)).toBe(false);
|
||||
});
|
||||
test('invalid/stale state cannot masquerade as acceptance and event conflicts roll back', async () => {
|
||||
const { execution } = await fixture();
|
||||
expect((await execution.submitOrder(order('missing'))).status).toBe('rejected');
|
||||
await execution.onMarketData(quote('q'));
|
||||
await expect(execution.onMarketData(quote('q', 101))).rejects.toBeInstanceOf(
|
||||
ExecutionConflictError
|
||||
);
|
||||
await expect(
|
||||
execution.onMarketData(quote('older', 100, 100, start - 1))
|
||||
).rejects.toBeInstanceOf(ExecutionConflictError);
|
||||
const stop = await execution.submitOrder({
|
||||
...order('stop'),
|
||||
orderType: 'stop',
|
||||
stopPrice: 100,
|
||||
});
|
||||
expect(stop.status).toBe('rejected');
|
||||
expect(stop.rejectionReason).toContain('Unsupported');
|
||||
expect((await execution.getAccount()).cash).toBe(10000);
|
||||
});
|
||||
test('HTTP requires an idempotency ID and returns conflict for mismatched reuse', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q'));
|
||||
const routes = createOrderRoutes({ logger, custom: { ExecutionService: execution } });
|
||||
const send = (body: object) =>
|
||||
routes.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const { clientOrderId: _, ...missing } = order('id');
|
||||
expect((await send(missing)).status).toBe(400);
|
||||
expect((await send(order('id'))).status).toBe(201);
|
||||
expect((await send(order('id', 'buy', 20))).status).toBe(409);
|
||||
});
|
||||
test('unsupported live initialization cannot alter an existing simulation account', async () => {
|
||||
const { execution, engine } = await fixture();
|
||||
const live = {
|
||||
mode: 'live' as const,
|
||||
broker: 'none',
|
||||
accountId: 'none',
|
||||
accountType: 'cash' as const,
|
||||
riskLimits: {
|
||||
maxOrderSize: 10,
|
||||
maxPositionSize: 10,
|
||||
maxDailyLoss: 10,
|
||||
maxSymbolExposure: 100,
|
||||
maxGrossExposure: 100,
|
||||
},
|
||||
};
|
||||
await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
|
||||
expect((await execution.getAccount()).cash).toBe(10000);
|
||||
const lifecycle = { initialize: async () => {}, shutdown: async () => {} };
|
||||
const mode = new ModeManager({
|
||||
logger,
|
||||
marketData: lifecycle,
|
||||
execution,
|
||||
strategies: { restoreStrategies: async () => {}, shutdown: async () => {} },
|
||||
});
|
||||
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
|
||||
expect(() => new TradingEngine('live', { broker: 'none', accountId: 'none' })).toThrow(
|
||||
'Live trading is disabled'
|
||||
);
|
||||
expect(() => engine.submitOrder({ ...order('direct'), id: 'direct' })).toThrow(
|
||||
'execution gateway'
|
||||
);
|
||||
});
|
||||
test('batch delivery is ordered, subscribed once, deduplicated, and routes every strategy order through risk', async () => {
|
||||
const { execution } = await fixture();
|
||||
class Strategy extends BaseStrategy {
|
||||
calls: number[] = [];
|
||||
protected updateIndicators(data: MarketData) {
|
||||
this.calls.push(data.data.timestamp);
|
||||
}
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
|
||||
}
|
||||
protected async onStart() {}
|
||||
protected async onStop() {}
|
||||
protected onConfigUpdate() {}
|
||||
}
|
||||
const market: MarketDataService = new MarketDataService({
|
||||
logger,
|
||||
storage: new StorageService(logger, null, null),
|
||||
drainStrategies: () => manager.drain(),
|
||||
});
|
||||
const manager: StrategyManager = new StrategyManager({
|
||||
logger,
|
||||
execution,
|
||||
marketData: market,
|
||||
createStrategy: config => new Strategy(config, {} as ModeManager, execution),
|
||||
});
|
||||
manager.setupEventListeners();
|
||||
manager.setupEventListeners();
|
||||
const strategy = new Strategy(
|
||||
{
|
||||
id: 'strategy',
|
||||
name: 'fixture',
|
||||
enabled: true,
|
||||
parameters: {},
|
||||
symbols: ['A'],
|
||||
allocation: 1,
|
||||
},
|
||||
{} as ModeManager,
|
||||
execution
|
||||
);
|
||||
// Inject only the strategy fixture; market delivery, gateway, accounting, and native projection are real.
|
||||
await manager.attachStrategy(strategy);
|
||||
cleanup.push(() => manager.shutdown());
|
||||
const first = quote('1');
|
||||
const second = quote('2', 100, 100, start + 1);
|
||||
market.emit('marketDataBatch', [first]);
|
||||
market.emit('marketData', first);
|
||||
market.emit('marketDataBatch', [first, second]);
|
||||
await manager.drain();
|
||||
expect(strategy.calls).toEqual([start, start + 1]);
|
||||
expect(strategy.getPosition('A')).toBe(2);
|
||||
expect((await execution.getAccount()).strategyPositions.strategy?.A).toBe(2);
|
||||
expect(market.listenerCount('marketDataBatch')).toBe(1);
|
||||
market.ingest(quote('3', 100, 100, start + 2));
|
||||
await market.flush();
|
||||
expect(strategy.calls).toEqual([start, start + 1, start + 2]);
|
||||
expect(strategy.getPosition('A')).toBe(3);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,7 +3,7 @@ import { expect, test } from 'bun:test';
|
|||
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import type { PaperConfigurationInput } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import type { PaperConfigurationInput } from '@stock-bot/stock-config/paper-runtime';
|
||||
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ import {
|
|||
compareEventKeys,
|
||||
parseFinancialTransactionResult,
|
||||
type CanonicalMatchingCommand,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
|
||||
} from '@stock-bot/stock-config/canonical-execution';
|
||||
import {
|
||||
PaperRuntimeError,
|
||||
type PaperConfigurationInput,
|
||||
type PaperFrameInput,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
} from '@stock-bot/stock-config/paper-runtime';
|
||||
import type { CanonicalAccount } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
import {
|
||||
planPaperFrame,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
|
|||
import { join } from 'node:path';
|
||||
import { expect, test } from 'bun:test';
|
||||
import { loadedNativeIdentity } from '@stock-bot/engine';
|
||||
import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
|
||||
import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity';
|
||||
|
||||
test('paper identity names the actual bundle and loaded immutable native bytes, not the research worker', async () => {
|
||||
const identity = await readPaperHostIdentity();
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
|
||||
import { createHttpSecurity } from '@stock-bot/di/http-security';
|
||||
import {
|
||||
PaperRuntimeError,
|
||||
type PaperConfigurationInput,
|
||||
|
|
@ -10,8 +8,9 @@ import {
|
|||
type PaperFrameInput,
|
||||
type PaperReadiness,
|
||||
type PaperRuntime,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
} from '@stock-bot/stock-config/paper-runtime';
|
||||
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
|
||||
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { paperFeedFrame } from '../fixtures/paper-feed';
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts
|
|||
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
||||
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
|
||||
import { mapBacktest, mapRun } from '../../apps/stock/web-api/src/services/backtests/mapping';
|
||||
import { RunControls } from '../../apps/stock/web-app/src/features/backtest/components/RunControls';
|
||||
import { RunControlsCompact } from '../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const original = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
|
|
@ -109,20 +109,20 @@ test('real server backtest/run mappings survive JSON serialization and display t
|
|||
respond(run());
|
||||
const savedRun = await backtest.backtestApiV2.getRun(runId);
|
||||
expect(savedRun.currentDate).toBe(now.toISOString());
|
||||
expect(savedRun.progress).toBe(12.5);
|
||||
expect(savedRun.completedAt).toBeNull();
|
||||
expect(savedRun.dataset?.state).toBe('unknown');
|
||||
const noop = () => {};
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(RunControls, {
|
||||
createElement(RunControlsCompact, {
|
||||
run: savedRun,
|
||||
onPause: noop,
|
||||
onResume: noop,
|
||||
cancelRequested: false,
|
||||
onCancel: noop,
|
||||
onSpeedChange: noop,
|
||||
onRerun: noop,
|
||||
})
|
||||
);
|
||||
expect(html).toContain(now.toLocaleString());
|
||||
expect(html).toContain('12.5%');
|
||||
expect(html).toContain('Running');
|
||||
expect(html).toContain('13%');
|
||||
});
|
||||
|
||||
test('existing optional fields remain optional without accepting malformed rendered fields', async () => {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import {
|
|||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@ import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/t
|
|||
import {
|
||||
canonicalWorkerUrl,
|
||||
readCanonicalBuildIdentity,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
} from '@stock-bot/trading-runtime/canonical-build';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import {
|
||||
nativeWorkerRequestSchema,
|
||||
|
|
|
|||
|
|
@ -1,183 +0,0 @@
|
|||
/**
|
||||
* Integration Test Setup
|
||||
*
|
||||
* Sets up test containers and real database instances for integration testing.
|
||||
* This file is executed before integration tests run.
|
||||
*/
|
||||
import { GenericContainer } from 'testcontainers';
|
||||
import { MongoMemoryServer } from 'mongodb-memory-server';
|
||||
let questdbContainer;
|
||||
let postgresContainer;
|
||||
let mongoContainer;
|
||||
let mongoMemoryServer;
|
||||
/**
|
||||
* Global setup for integration tests
|
||||
* Starts real database containers for testing
|
||||
*/
|
||||
beforeAll(async () => {
|
||||
console.log('🚀 Starting integration test containers...');
|
||||
try {
|
||||
// Start QuestDB container
|
||||
console.log('📊 Starting QuestDB container...');
|
||||
questdbContainer = await new GenericContainer('questdb/questdb:7.3.10')
|
||||
.withExposedPorts(9000, 8812, 9009)
|
||||
.withEnvironment({
|
||||
'QDB_TELEMETRY_ENABLED': 'false',
|
||||
'QDB_LOG_LEVEL': 'ERROR'
|
||||
})
|
||||
.withStartupTimeout(60000)
|
||||
.start();
|
||||
// Start PostgreSQL container
|
||||
console.log('🐘 Starting PostgreSQL container...');
|
||||
postgresContainer = await new GenericContainer('postgres:15-alpine')
|
||||
.withExposedPorts(5432)
|
||||
.withEnvironment({
|
||||
'POSTGRES_DB': 'trading_bot_test',
|
||||
'POSTGRES_USER': 'trading_admin',
|
||||
'POSTGRES_PASSWORD': 'trading_pass_test'
|
||||
})
|
||||
.withStartupTimeout(60000)
|
||||
.start();
|
||||
// Start MongoDB container
|
||||
console.log('🍃 Starting MongoDB container...');
|
||||
mongoContainer = await new GenericContainer('mongo:7-jammy')
|
||||
.withExposedPorts(27017)
|
||||
.withEnvironment({
|
||||
'MONGO_INITDB_ROOT_USERNAME': 'trading_admin',
|
||||
'MONGO_INITDB_ROOT_PASSWORD': 'trading_mongo_test',
|
||||
'MONGO_INITDB_DATABASE': 'trading_bot_test'
|
||||
})
|
||||
.withStartupTimeout(60000)
|
||||
.start();
|
||||
// Update environment variables for tests
|
||||
process.env.QUESTDB_HOST = questdbContainer.getHost();
|
||||
process.env.QUESTDB_HTTP_PORT = questdbContainer.getMappedPort(9000).toString();
|
||||
process.env.QUESTDB_PG_PORT = questdbContainer.getMappedPort(8812).toString();
|
||||
process.env.QUESTDB_INFLUX_PORT = questdbContainer.getMappedPort(9009).toString();
|
||||
process.env.POSTGRES_HOST = postgresContainer.getHost();
|
||||
process.env.POSTGRES_PORT = postgresContainer.getMappedPort(5432).toString();
|
||||
process.env.MONGODB_HOST = mongoContainer.getHost();
|
||||
process.env.MONGODB_PORT = mongoContainer.getMappedPort(27017).toString();
|
||||
console.log('✅ All containers started successfully!');
|
||||
console.log(`📊 QuestDB: http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`);
|
||||
console.log(`🐘 PostgreSQL: ${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}`);
|
||||
console.log(`🍃 MongoDB: ${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}`);
|
||||
}
|
||||
catch (error) {
|
||||
console.error('❌ Failed to start test containers:', error);
|
||||
// Try to use MongoDB Memory Server as fallback
|
||||
console.log('🔄 Falling back to MongoDB Memory Server...');
|
||||
try {
|
||||
mongoMemoryServer = await MongoMemoryServer.create({
|
||||
instance: {
|
||||
dbName: 'trading_bot_test'
|
||||
}
|
||||
});
|
||||
const mongoUri = mongoMemoryServer.getUri();
|
||||
const mongoUrl = new URL(mongoUri);
|
||||
process.env.MONGODB_HOST = mongoUrl.hostname;
|
||||
process.env.MONGODB_PORT = mongoUrl.port;
|
||||
process.env.MONGODB_URI = mongoUri;
|
||||
console.log('✅ MongoDB Memory Server started as fallback');
|
||||
}
|
||||
catch (fallbackError) {
|
||||
console.error('❌ Failed to start MongoDB Memory Server:', fallbackError);
|
||||
throw fallbackError;
|
||||
}
|
||||
// For other databases, use localhost defaults if containers fail
|
||||
if (!questdbContainer) {
|
||||
console.log('⚠️ Using localhost QuestDB (ensure it\'s running)');
|
||||
process.env.QUESTDB_HOST = 'localhost';
|
||||
process.env.QUESTDB_HTTP_PORT = '9000';
|
||||
process.env.QUESTDB_PG_PORT = '8812';
|
||||
process.env.QUESTDB_INFLUX_PORT = '9009';
|
||||
}
|
||||
if (!postgresContainer) {
|
||||
console.log('⚠️ Using localhost PostgreSQL (ensure it\'s running)');
|
||||
process.env.POSTGRES_HOST = 'localhost';
|
||||
process.env.POSTGRES_PORT = '5432';
|
||||
}
|
||||
}
|
||||
}, 120000); // 2 minutes timeout for container startup
|
||||
/**
|
||||
* Global cleanup for integration tests
|
||||
* Stops all test containers
|
||||
*/
|
||||
afterAll(async () => {
|
||||
console.log('🧹 Cleaning up integration test containers...');
|
||||
const cleanup = async (container, name) => {
|
||||
if (container) {
|
||||
try {
|
||||
await container.stop();
|
||||
console.log(`✅ ${name} container stopped`);
|
||||
}
|
||||
catch (error) {
|
||||
console.warn(`⚠️ Failed to stop ${name} container:`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all([
|
||||
cleanup(questdbContainer, 'QuestDB'),
|
||||
cleanup(postgresContainer, 'PostgreSQL'),
|
||||
cleanup(mongoContainer, 'MongoDB')
|
||||
]);
|
||||
if (mongoMemoryServer) {
|
||||
try {
|
||||
await mongoMemoryServer.stop();
|
||||
console.log('✅ MongoDB Memory Server stopped');
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('⚠️ Failed to stop MongoDB Memory Server:', error);
|
||||
}
|
||||
}
|
||||
console.log('🎉 Integration test cleanup complete!');
|
||||
}, 30000);
|
||||
/**
|
||||
* Wait for database services to be ready
|
||||
*/
|
||||
export const waitForServices = async (timeout = 30000) => {
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < timeout) {
|
||||
try {
|
||||
// Check if QuestDB HTTP interface is ready
|
||||
const questdbUrl = `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}/status`;
|
||||
const response = await fetch(questdbUrl);
|
||||
if (response.ok) {
|
||||
console.log('✅ QuestDB is ready');
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
// Service not ready yet, continue waiting
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
throw new Error('Services did not become ready within timeout');
|
||||
};
|
||||
/**
|
||||
* Test utilities for integration tests
|
||||
*/
|
||||
export const integrationTestHelpers = {
|
||||
/**
|
||||
* Get QuestDB HTTP URL
|
||||
*/
|
||||
getQuestDBUrl: () => `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`,
|
||||
/**
|
||||
* Get PostgreSQL connection string
|
||||
*/
|
||||
getPostgresUrl: () => `postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DB}`,
|
||||
/**
|
||||
* Get MongoDB connection string
|
||||
*/
|
||||
getMongoUrl: () => {
|
||||
if (process.env.MONGODB_URI) {
|
||||
return process.env.MONGODB_URI;
|
||||
}
|
||||
return `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DATABASE}`;
|
||||
},
|
||||
/**
|
||||
* Wait for services to be ready
|
||||
*/
|
||||
waitForServices
|
||||
};
|
||||
//# sourceMappingURL=setup.js.map
|
||||
|
|
@ -1,208 +0,0 @@
|
|||
/**
|
||||
* Integration Test Setup
|
||||
*
|
||||
* Sets up test containers and real database instances for integration testing.
|
||||
* This file is executed before integration tests run.
|
||||
*/
|
||||
|
||||
import { GenericContainer, StartedTestContainer } from 'testcontainers';
|
||||
import { MongoMemoryServer } from 'mongodb-memory-server';
|
||||
|
||||
let questdbContainer: StartedTestContainer;
|
||||
let postgresContainer: StartedTestContainer;
|
||||
let mongoContainer: StartedTestContainer;
|
||||
let mongoMemoryServer: MongoMemoryServer;
|
||||
|
||||
/**
|
||||
* Global setup for integration tests
|
||||
* Starts real database containers for testing
|
||||
*/
|
||||
beforeAll(async () => {
|
||||
console.log('🚀 Starting integration test containers...');
|
||||
|
||||
try {
|
||||
// Start QuestDB container
|
||||
console.log('📊 Starting QuestDB container...');
|
||||
questdbContainer = await new GenericContainer('questdb/questdb:7.3.10')
|
||||
.withExposedPorts(9000, 8812, 9009)
|
||||
.withEnvironment({
|
||||
'QDB_TELEMETRY_ENABLED': 'false',
|
||||
'QDB_LOG_LEVEL': 'ERROR'
|
||||
})
|
||||
.withStartupTimeout(60000)
|
||||
.start();
|
||||
|
||||
// Start PostgreSQL container
|
||||
console.log('🐘 Starting PostgreSQL container...');
|
||||
postgresContainer = await new GenericContainer('postgres:15-alpine')
|
||||
.withExposedPorts(5432)
|
||||
.withEnvironment({
|
||||
'POSTGRES_DB': 'trading_bot_test',
|
||||
'POSTGRES_USER': 'trading_admin',
|
||||
'POSTGRES_PASSWORD': 'trading_pass_test'
|
||||
})
|
||||
.withStartupTimeout(60000)
|
||||
.start();
|
||||
|
||||
// Start MongoDB container
|
||||
console.log('🍃 Starting MongoDB container...');
|
||||
mongoContainer = await new GenericContainer('mongo:7-jammy')
|
||||
.withExposedPorts(27017)
|
||||
.withEnvironment({
|
||||
'MONGO_INITDB_ROOT_USERNAME': 'trading_admin',
|
||||
'MONGO_INITDB_ROOT_PASSWORD': 'trading_mongo_test',
|
||||
'MONGO_INITDB_DATABASE': 'trading_bot_test'
|
||||
})
|
||||
.withStartupTimeout(60000)
|
||||
.start();
|
||||
|
||||
// Update environment variables for tests
|
||||
process.env.QUESTDB_HOST = questdbContainer.getHost();
|
||||
process.env.QUESTDB_HTTP_PORT = questdbContainer.getMappedPort(9000).toString();
|
||||
process.env.QUESTDB_PG_PORT = questdbContainer.getMappedPort(8812).toString();
|
||||
process.env.QUESTDB_INFLUX_PORT = questdbContainer.getMappedPort(9009).toString();
|
||||
|
||||
process.env.POSTGRES_HOST = postgresContainer.getHost();
|
||||
process.env.POSTGRES_PORT = postgresContainer.getMappedPort(5432).toString();
|
||||
|
||||
process.env.MONGODB_HOST = mongoContainer.getHost();
|
||||
process.env.MONGODB_PORT = mongoContainer.getMappedPort(27017).toString();
|
||||
|
||||
console.log('✅ All containers started successfully!');
|
||||
console.log(`📊 QuestDB: http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`);
|
||||
console.log(`🐘 PostgreSQL: ${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}`);
|
||||
console.log(`🍃 MongoDB: ${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to start test containers:', error);
|
||||
|
||||
// Try to use MongoDB Memory Server as fallback
|
||||
console.log('🔄 Falling back to MongoDB Memory Server...');
|
||||
try {
|
||||
mongoMemoryServer = await MongoMemoryServer.create({
|
||||
instance: {
|
||||
dbName: 'trading_bot_test'
|
||||
}
|
||||
});
|
||||
|
||||
const mongoUri = mongoMemoryServer.getUri();
|
||||
const mongoUrl = new URL(mongoUri);
|
||||
process.env.MONGODB_HOST = mongoUrl.hostname;
|
||||
process.env.MONGODB_PORT = mongoUrl.port;
|
||||
process.env.MONGODB_URI = mongoUri;
|
||||
|
||||
console.log('✅ MongoDB Memory Server started as fallback');
|
||||
} catch (fallbackError) {
|
||||
console.error('❌ Failed to start MongoDB Memory Server:', fallbackError);
|
||||
throw fallbackError;
|
||||
}
|
||||
|
||||
// For other databases, use localhost defaults if containers fail
|
||||
if (!questdbContainer) {
|
||||
console.log('⚠️ Using localhost QuestDB (ensure it\'s running)');
|
||||
process.env.QUESTDB_HOST = 'localhost';
|
||||
process.env.QUESTDB_HTTP_PORT = '9000';
|
||||
process.env.QUESTDB_PG_PORT = '8812';
|
||||
process.env.QUESTDB_INFLUX_PORT = '9009';
|
||||
}
|
||||
|
||||
if (!postgresContainer) {
|
||||
console.log('⚠️ Using localhost PostgreSQL (ensure it\'s running)');
|
||||
process.env.POSTGRES_HOST = 'localhost';
|
||||
process.env.POSTGRES_PORT = '5432';
|
||||
}
|
||||
}
|
||||
}, 120000); // 2 minutes timeout for container startup
|
||||
|
||||
/**
|
||||
* Global cleanup for integration tests
|
||||
* Stops all test containers
|
||||
*/
|
||||
afterAll(async () => {
|
||||
console.log('🧹 Cleaning up integration test containers...');
|
||||
|
||||
const cleanup = async (container: StartedTestContainer | undefined, name: string) => {
|
||||
if (container) {
|
||||
try {
|
||||
await container.stop();
|
||||
console.log(`✅ ${name} container stopped`);
|
||||
} catch (error) {
|
||||
console.warn(`⚠️ Failed to stop ${name} container:`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await Promise.all([
|
||||
cleanup(questdbContainer, 'QuestDB'),
|
||||
cleanup(postgresContainer, 'PostgreSQL'),
|
||||
cleanup(mongoContainer, 'MongoDB')
|
||||
]);
|
||||
|
||||
if (mongoMemoryServer) {
|
||||
try {
|
||||
await mongoMemoryServer.stop();
|
||||
console.log('✅ MongoDB Memory Server stopped');
|
||||
} catch (error) {
|
||||
console.warn('⚠️ Failed to stop MongoDB Memory Server:', error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('🎉 Integration test cleanup complete!');
|
||||
}, 30000);
|
||||
|
||||
/**
|
||||
* Wait for database services to be ready
|
||||
*/
|
||||
export const waitForServices = async (timeout: number = 30000): Promise<void> => {
|
||||
const start = Date.now();
|
||||
|
||||
while (Date.now() - start < timeout) {
|
||||
try {
|
||||
// Check if QuestDB HTTP interface is ready
|
||||
const questdbUrl = `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}/status`;
|
||||
const response = await fetch(questdbUrl);
|
||||
|
||||
if (response.ok) {
|
||||
console.log('✅ QuestDB is ready');
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
// Service not ready yet, continue waiting
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
throw new Error('Services did not become ready within timeout');
|
||||
};
|
||||
|
||||
/**
|
||||
* Test utilities for integration tests
|
||||
*/
|
||||
export const integrationTestHelpers = {
|
||||
/**
|
||||
* Get QuestDB HTTP URL
|
||||
*/
|
||||
getQuestDBUrl: () => `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`,
|
||||
|
||||
/**
|
||||
* Get PostgreSQL connection string
|
||||
*/
|
||||
getPostgresUrl: () =>
|
||||
`postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DB}`,
|
||||
|
||||
/**
|
||||
* Get MongoDB connection string
|
||||
*/
|
||||
getMongoUrl: () => {
|
||||
if (process.env.MONGODB_URI) {
|
||||
return process.env.MONGODB_URI;
|
||||
}
|
||||
return `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DATABASE}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Wait for services to be ready
|
||||
*/
|
||||
waitForServices
|
||||
};
|
||||
|
|
@ -13,7 +13,7 @@ import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historic
|
|||
import {
|
||||
StorageService,
|
||||
type HistoricalBar,
|
||||
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
} from '@stock-bot/trading-runtime/historical-storage';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import { previewDatasetPreparation } from '../../apps/stock/web-api/src/services/dataset-preparation.service';
|
||||
import { prepareStoredDataset } from '../../apps/stock/web-api/src/services/stored-dataset-preparation';
|
||||
|
|
|
|||
|
|
@ -1,468 +0,0 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
movingAverageCrossover,
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import {
|
||||
IncrementalSMA,
|
||||
BacktestEngine as NativeEngine,
|
||||
TechnicalIndicators,
|
||||
} from '@stock-bot/engine';
|
||||
import { BacktestExecutionSettingsSchema } from '@stock-bot/stock-config/backtest';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { resolveNativeStrategies } from '../../apps/stock/orchestrator/src/backtest/native-strategies';
|
||||
import { backtestStrategies } from '../../apps/stock/orchestrator/src/backtest/strategy-plan';
|
||||
import {
|
||||
nativeMeanReversionParameters,
|
||||
nativeMomentumParameters,
|
||||
nativePairsParameters,
|
||||
nativeSmaParameters,
|
||||
typescriptMeanReversionParameters,
|
||||
typescriptSmaParameters,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategies';
|
||||
import {
|
||||
builtinStrategy,
|
||||
normalizeStrategyName,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategy-names';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';
|
||||
import type { StrategyConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution, start } from '../fixtures/execution';
|
||||
import { makeStrategyManager } from '../fixtures/strategy-recovery';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
});
|
||||
const definition: StrategyConfig = {
|
||||
id: 'sma',
|
||||
name: 'sma-crossover',
|
||||
enabled: true,
|
||||
parameters: {},
|
||||
symbols: ['A.US'],
|
||||
allocation: 1,
|
||||
};
|
||||
function nativeEngine() {
|
||||
return new NativeEngine({
|
||||
name: 'contracts',
|
||||
symbols: ['A.US'],
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: 10000,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
}
|
||||
const bar = (close: number, index: number, symbol = 'A.US') => ({
|
||||
type: 'bar' as const,
|
||||
eventId: symbol + ':' + index,
|
||||
data: {
|
||||
symbol,
|
||||
close,
|
||||
open: close,
|
||||
high: close + 0.1,
|
||||
low: close - 0.1,
|
||||
volume: 1000,
|
||||
timestamp: start + index * 86400000,
|
||||
},
|
||||
});
|
||||
async function runtime(parameters: Record<string, unknown> = {}, name = definition.name) {
|
||||
const f = makeExecution();
|
||||
await f.execution.initialize({ ...config, commission: 0 }, f.engine);
|
||||
cleanup.push(() => f.execution.shutdown());
|
||||
const mode = { getTradingEngine: () => f.engine } as ModeManager;
|
||||
const manager = makeStrategyManager({ execution: f.execution, modeManager: mode });
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await manager.initializeStrategies([{ ...definition, name, parameters }]);
|
||||
return { ...f, manager, mode, strategy: manager.getStrategy('sma')! };
|
||||
}
|
||||
|
||||
describe('explicit strategy contracts and shared planning', () => {
|
||||
test('aliases have one canonical identity across registries and native planning', () => {
|
||||
for (const name of [
|
||||
'SMA',
|
||||
' sma-crossover ',
|
||||
'sma_crossover',
|
||||
'Simple Moving Average Crossover',
|
||||
'moving-average',
|
||||
]) {
|
||||
expect(builtinStrategy(name)).toBe('sma_crossover');
|
||||
expect(resolveNativeStrategies({ ...config, strategy: name })[0]?.strategy).toBe(
|
||||
'sma_crossover'
|
||||
);
|
||||
}
|
||||
expect(normalizeStrategyName(' Mean-Reversion ')).toBe('meanreversion');
|
||||
expect(builtinStrategy('unknown')).toBeUndefined();
|
||||
});
|
||||
|
||||
test('both backends use the same shared-default then per-strategy override rule', () => {
|
||||
const request = {
|
||||
...config,
|
||||
config: { fastPeriod: 2, slowPeriod: 9, commission: 0, slippage: 0 },
|
||||
strategies: [
|
||||
{ name: 'sma', enabled: true, config: { slowPeriod: 5 } },
|
||||
{ name: 'not-installed', enabled: false, config: {} },
|
||||
{ name: 'sma_crossover', enabled: true, config: { fastPeriod: 3 } },
|
||||
],
|
||||
};
|
||||
const before = structuredClone(request);
|
||||
for (const backend of ['typescript', 'native'] as const) {
|
||||
const plan = backtestStrategies(request, backend);
|
||||
expect(plan.map(entry => [entry.parameters.fastPeriod, entry.parameters.slowPeriod])).toEqual(
|
||||
[
|
||||
[2, 5],
|
||||
[3, 9],
|
||||
]
|
||||
);
|
||||
expect(plan.every(entry => !('commission' in entry.parameters))).toBe(true);
|
||||
}
|
||||
expect(request).toEqual(before);
|
||||
const custom = backtestStrategies(
|
||||
{ ...config, strategy: 'custom-extension', config: { vendorOption: 42 } },
|
||||
'typescript'
|
||||
);
|
||||
expect(custom[0]?.parameters).toMatchObject({
|
||||
vendorOption: 42,
|
||||
initialCapital: config.initialCapital,
|
||||
});
|
||||
});
|
||||
|
||||
test('periods and units have explicit defaults and fail rather than coerce or truncate', () => {
|
||||
expect(typescriptSmaParameters.parse({})).toMatchObject({
|
||||
fastPeriod: 5,
|
||||
slowPeriod: 15,
|
||||
positionFraction: 0.1,
|
||||
minHoldingBars: 3,
|
||||
});
|
||||
expect(nativeSmaParameters.parse({})).toEqual({ fastPeriod: 5, slowPeriod: 15, quantity: 100 });
|
||||
for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) {
|
||||
expect(nativeSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false);
|
||||
}
|
||||
expect(typescriptSmaParameters.safeParse({ fastPeriod: 20, slowPeriod: 5 }).success).toBe(
|
||||
false
|
||||
);
|
||||
for (const bad of [0, -1, Infinity, 1e10]) {
|
||||
expect(nativeSmaParameters.safeParse({ quantity: bad }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ quantity: bad }).success).toBe(false);
|
||||
}
|
||||
expect(typescriptSmaParameters.safeParse({ positionFraction: 2 }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ positionSize: 100 }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ fastPreriod: 3 }).success).toBe(false);
|
||||
expect(nativeSmaParameters.safeParse({ positionFraction: 0.1 }).success).toBe(false);
|
||||
});
|
||||
|
||||
test('mixed execution settings never reach built-in parameters or alter run-wide precedence', () => {
|
||||
const mixed = {
|
||||
...config,
|
||||
config: {
|
||||
...BacktestExecutionSettingsSchema.parse(config),
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
useTypeScriptImplementation: false,
|
||||
},
|
||||
strategies: [
|
||||
{ name: 'disabled', enabled: false, config: {} },
|
||||
{
|
||||
name: 'sma',
|
||||
enabled: true,
|
||||
config: { slowPeriod: 9, dataFrequency: '1m', commission: 0.1 },
|
||||
},
|
||||
{ name: 'sma_crossover', enabled: true, config: { fastPeriod: 2 } },
|
||||
],
|
||||
};
|
||||
const before = structuredClone(mixed);
|
||||
for (const backend of ['native', 'typescript'] as const) {
|
||||
const plan = backtestStrategies(mixed, backend);
|
||||
expect(
|
||||
plan.map(entry => [entry.index, entry.parameters.fastPeriod, entry.parameters.slowPeriod])
|
||||
).toEqual([
|
||||
[0, 3, 9],
|
||||
[1, 2, 7],
|
||||
]);
|
||||
for (const entry of plan) {
|
||||
expect(entry.parameters).not.toHaveProperty('dataFrequency');
|
||||
expect(entry.parameters).not.toHaveProperty('commission');
|
||||
expect(entry.parameters).not.toHaveProperty('useTypeScriptImplementation');
|
||||
if (backend === 'typescript') {
|
||||
expect(entry.parameters.initialCapital).toBe(config.initialCapital);
|
||||
}
|
||||
}
|
||||
for (const parameters of [{ fastPreriod: 3 }, { dataFrequncy: '1d' }]) {
|
||||
expect(() => backtestStrategies({ ...config, config: parameters }, backend)).toThrow(
|
||||
'Unrecognized'
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(resolveNativeStrategies(mixed).map(entry => entry.id)).toEqual([
|
||||
'backtest-strategy-0',
|
||||
'backtest-strategy-1',
|
||||
]);
|
||||
expect(mixed).toEqual(before);
|
||||
expect(mixed.dataFrequency).toBe('1d');
|
||||
});
|
||||
|
||||
test('custom factories retain their existing extension bag, including names also used by execution', () => {
|
||||
const parameters = {
|
||||
vendorOption: { window: 9 },
|
||||
dataFrequency: 'feature cadence',
|
||||
commission: 12,
|
||||
};
|
||||
const custom = backtestStrategies(
|
||||
{ ...config, strategy: 'custom', config: parameters },
|
||||
'typescript'
|
||||
);
|
||||
expect(custom[0]?.parameters).toMatchObject({
|
||||
...parameters,
|
||||
initialCapital: config.initialCapital,
|
||||
});
|
||||
(custom[0]!.parameters.vendorOption as { window: number }).window = 100;
|
||||
expect(parameters.vendorOption.window).toBe(9);
|
||||
});
|
||||
|
||||
test('mean reversion and native-only strategies validate their actual, different contracts', () => {
|
||||
const mean = typescriptMeanReversionParameters.parse({ lookbackPeriod: 80 });
|
||||
expect(mean.trendPeriod).toBe(80);
|
||||
expect(mean.entryThreshold).toBe(2);
|
||||
expect(typescriptMeanReversionParameters.safeParse({ exitZScore: 3 }).success).toBe(false);
|
||||
expect(
|
||||
typescriptMeanReversionParameters.safeParse({ rsiOversold: 80, rsiOverbought: 20 }).success
|
||||
).toBe(false);
|
||||
expect(
|
||||
typescriptMeanReversionParameters.safeParse({ lookbackPeriod: 30, trendPeriod: 20 }).success
|
||||
).toBe(false);
|
||||
expect(nativeMeanReversionParameters.safeParse({ exitZScore: 0.5 }).success).toBe(false);
|
||||
expect(nativeMeanReversionParameters.safeParse({ lookbackPeriod: 0 }).success).toBe(false);
|
||||
expect(nativeMomentumParameters.safeParse({ momentumThreshold: NaN }).success).toBe(false);
|
||||
expect(nativePairsParameters.safeParse({ pairA: 'A.US', pairB: 'A.US' }).success).toBe(false);
|
||||
expect(() =>
|
||||
backtestStrategies(
|
||||
{ ...config, strategy: 'pairs', config: { pairA: 'A.US', pairB: 'C.US' } },
|
||||
'native'
|
||||
)
|
||||
).toThrow('included in backtest symbols');
|
||||
});
|
||||
|
||||
test('invalid native plans fail before loading input and unsupported execution flags are explicit', () => {
|
||||
expect(() => backtestStrategies({ ...config, strategies: [] }, 'native')).toThrow('No enabled');
|
||||
expect(() => backtestStrategies({ ...config, strategies: [] }, 'typescript')).toThrow(
|
||||
'No enabled'
|
||||
);
|
||||
expect(() =>
|
||||
resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: true } })
|
||||
).toThrow('does not execute TypeScript');
|
||||
expect(() =>
|
||||
resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: 'false' } })
|
||||
).toThrow();
|
||||
expect(
|
||||
backtestStrategies({ ...config, config: { useTypeScriptImplementation: true } }, 'typescript')
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('the TypeScript backend rejects invalid settings before calling a dataset resolver', async () => {
|
||||
const f = await runtime();
|
||||
const storage = new StorageService(logger, null, null);
|
||||
const backend = new BacktestEngine({
|
||||
logger,
|
||||
execution: f.execution,
|
||||
storage,
|
||||
strategies: f.manager,
|
||||
getTradingEngine: () => f.engine,
|
||||
});
|
||||
cleanup.push(() => backend.shutdown());
|
||||
let reads = 0;
|
||||
await expect(
|
||||
backend.runBacktest({ ...config, config: { fastPeriod: 5, slowPeriod: 2 } }, async () => {
|
||||
reads++;
|
||||
throw new Error('Must not load data');
|
||||
})
|
||||
).rejects.toThrow('SMA periods must satisfy');
|
||||
expect(reads).toBe(0);
|
||||
});
|
||||
|
||||
test('definitions are detached and rejected inactive edits leave effective settings intact', async () => {
|
||||
const f = await runtime();
|
||||
const input = { ...definition, parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 7 } };
|
||||
const strategy = new SmaCrossoverStrategy(input, f.mode, f.execution);
|
||||
input.parameters.fastPeriod = 0;
|
||||
const view = strategy.getConfig();
|
||||
view.parameters.slowPeriod = 0;
|
||||
expect(strategy.getConfig().parameters).toMatchObject({
|
||||
fastPeriod: 2,
|
||||
slowPeriod: 3,
|
||||
quantity: 7,
|
||||
});
|
||||
await expect(
|
||||
strategy.updateConfig({ parameters: { fastPeriod: 9, slowPeriod: 3 } })
|
||||
).rejects.toThrow('SMA periods');
|
||||
expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 2, slowPeriod: 3 });
|
||||
await strategy.updateConfig({ parameters: { fastPeriod: 3, slowPeriod: 8 } });
|
||||
expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 3, slowPeriod: 8 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('shared trailing-window math and native parity', () => {
|
||||
test('warm-up never manufactures zero averages or first-window crossovers', () => {
|
||||
expect(trailingMean([3, 2], 3)).toBeUndefined();
|
||||
expect(movingAverageCrossover([3, 2, 1], 2, 3)).toBeUndefined();
|
||||
expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)).toMatchObject({
|
||||
goldenCross: true,
|
||||
deathCross: false,
|
||||
});
|
||||
expect(movingAverageCrossover([1, 2, 3, 1], 2, 3)).toMatchObject({
|
||||
goldenCross: false,
|
||||
deathCross: false,
|
||||
});
|
||||
expect(movingAverageCrossover([1, 2, 3, 0.5], 2, 3)).toMatchObject({
|
||||
goldenCross: false,
|
||||
deathCross: true,
|
||||
});
|
||||
expect(trailingPopulationDeviation([10, 10, 10], 3)).toBe(0);
|
||||
for (const period of [0, -1, 1.5, Infinity])
|
||||
expect(() => trailingMean([1, 2, 3], period)).toThrow();
|
||||
expect(() => trailingMean([1, NaN, 3], 3)).toThrow('finite');
|
||||
expect(() => trailingMean([Number.MAX_VALUE, Number.MAX_VALUE], 2)).toThrow('overflow');
|
||||
});
|
||||
|
||||
test('scalar SMA and population deviation match native batch and incremental indicators', () => {
|
||||
const native = new TechnicalIndicators();
|
||||
const prices = Array.from(
|
||||
{ length: 130 },
|
||||
(_, index) => 100 + Math.sin(index / 3) * 8 + index / 100
|
||||
);
|
||||
for (const period of [2, 5, 15, 80]) {
|
||||
const rolling = new IncrementalSMA(period);
|
||||
const series = native.calculateSma(prices, period);
|
||||
const bands = JSON.parse(native.calculateBollingerBands(prices, period, 2));
|
||||
for (let index = 0; index < prices.length; index++) {
|
||||
const value = rolling.update(prices[index]!);
|
||||
const scalar = trailingMean(prices.slice(0, index + 1), period);
|
||||
if (scalar === undefined) {
|
||||
expect(value == null).toBe(true);
|
||||
continue;
|
||||
}
|
||||
expect(value!).toBeCloseTo(scalar, 9);
|
||||
expect(series[index + 1 - period]!).toBeCloseTo(scalar, 9);
|
||||
const deviation = trailingPopulationDeviation(prices.slice(0, index + 1), period)!;
|
||||
expect(
|
||||
(bands.upper[index + 1 - period] - bands.middle[index + 1 - period]) / 2
|
||||
).toBeCloseTo(deviation, 8);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('configured SMA periods and explicit shares reach real fills in both backends', async () => {
|
||||
const f = await runtime({ fastPeriod: 2, slowPeriod: 3, quantity: 7, minHoldingBars: 0 });
|
||||
const prices = [3, 2, 1, 4];
|
||||
for (let i = 0; i < 3; i++) await f.manager.onMarketData(bar(prices[i]!, i));
|
||||
expect((await f.execution.getAccount()).positions['A.US']).toBeUndefined();
|
||||
await f.manager.onMarketData(bar(prices[3]!, 3));
|
||||
expect((await f.execution.getAccount()).positions['A.US']?.quantity).toBe(7);
|
||||
const native = nativeEngine();
|
||||
native.addNativeStrategy('sma_crossover', 'sma', 'id', {
|
||||
fastPeriod: 2,
|
||||
slowPeriod: 3,
|
||||
quantity: 7,
|
||||
});
|
||||
native.loadMarketData(
|
||||
prices.map((price, i) => ({ ...bar(price, i).data, type: 'bar', vwap: price }))
|
||||
);
|
||||
const result = JSON.parse(native.run());
|
||||
// Native backtests liquidate at the end; that exit is not a second strategy entry.
|
||||
expect(result.trades).toHaveLength(2);
|
||||
expect(result.trades[0]).toMatchObject({ side: 'buy', quantity: 7, symbol: 'A.US' });
|
||||
expect(result.trades[1]).toMatchObject({ side: 'sell', quantity: 7, symbol: 'A.US' });
|
||||
expect(() => native.addNativeStrategy('sma_crossover', 'late', 'late', {})).toThrow('consumed');
|
||||
});
|
||||
|
||||
test('configured long windows remain checkpointable and preserve state through replacement', async () => {
|
||||
const settings = { fastPeriod: 5, slowPeriod: 80, quantity: 1 };
|
||||
const f = await runtime(settings);
|
||||
for (let i = 0; i < 90; i++) await f.manager.onMarketData(bar(100 + Math.sin(i / 3), i));
|
||||
const state = f.strategy.captureCheckpoint();
|
||||
const replacement = new SmaCrossoverStrategy(f.strategy.getConfig(), f.mode, f.execution);
|
||||
replacement.restoreCheckpoint(state);
|
||||
expect(replacement.captureCheckpoint()).toEqual(state);
|
||||
expect(replacement.getCheckpointVersion()).toBe('sma-crossover-fixed/v2');
|
||||
const mean = await runtime({ lookbackPeriod: 80 }, 'mean-reversion');
|
||||
const prices = Array.from({ length: 90 }, (_, i) => 100 + Math.sin(i / 3));
|
||||
for (let i = 0; i < prices.length; i++) {
|
||||
await mean.manager.onMarketData(bar(prices[i]!, i));
|
||||
}
|
||||
const meanState = mean.strategy.captureCheckpoint();
|
||||
expect(meanState).toMatchObject({
|
||||
indicators: {
|
||||
priceHistory: [['A.US', prices]],
|
||||
indicators: [
|
||||
[
|
||||
'A.US',
|
||||
{
|
||||
mean: trailingMean(prices, 80),
|
||||
trendMean: trailingMean(prices, 80),
|
||||
stdDev: trailingPopulationDeviation(prices, 80),
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
const restoredMean = new MeanReversionStrategy(
|
||||
mean.strategy.getConfig(),
|
||||
mean.mode,
|
||||
mean.execution
|
||||
);
|
||||
restoredMean.restoreCheckpoint(meanState);
|
||||
expect(restoredMean.captureCheckpoint()).toEqual(meanState);
|
||||
expect(restoredMean.getConfig().parameters.trendPeriod).toBe(80);
|
||||
});
|
||||
|
||||
test('v2 cannot silently reset a legacy paper definition; explicit new IDs preserve old registration', async () => {
|
||||
const f = makeExecution();
|
||||
await f.execution.initialize(config, f.engine);
|
||||
cleanup.push(() => f.execution.shutdown());
|
||||
const mode = { getTradingEngine: () => f.engine } as ModeManager;
|
||||
const legacy = new SmaCrossoverStrategy(definition, mode, f.execution);
|
||||
legacy.getCheckpointVersion = () => 'sma-crossover-fixed/v1';
|
||||
await f.execution.registerStrategy(legacy);
|
||||
const before = await f.execution.getRecoveryStatus();
|
||||
const upgraded = new SmaCrossoverStrategy(definition, mode, f.execution);
|
||||
await expect(f.execution.registerStrategy(upgraded)).rejects.toThrow('version changed');
|
||||
expect(await f.execution.getRecoveryStatus()).toEqual(before);
|
||||
await f.execution.pauseStrategy('sma');
|
||||
const fresh = new SmaCrossoverStrategy({ ...definition, id: 'sma-v2' }, mode, f.execution);
|
||||
await f.execution.registerStrategy(fresh);
|
||||
expect((await f.execution.getRecoveryStatus()).strategies).toMatchObject([
|
||||
{ strategyId: 'sma', enabled: false, version: 'sma-crossover-fixed/v1' },
|
||||
{ strategyId: 'sma-v2', enabled: true, version: 'sma-crossover-fixed/v2' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('native parameter trust boundary', () => {
|
||||
test('native bindings reject invalid numeric types, fractions, infinities and unknown keys independently', () => {
|
||||
const engine = nativeEngine();
|
||||
for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) {
|
||||
expect(() =>
|
||||
engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: bad })
|
||||
).toThrow('SMA periods');
|
||||
}
|
||||
for (const [name, parameters] of [
|
||||
['sma_crossover', { fastPreriod: 3 }],
|
||||
['sma_crossover', { quantity: -1 }],
|
||||
['mean_reversion', { lookbackPeriod: 0 }],
|
||||
['mean_reversion', { lookbackPeriod: 1.5 }],
|
||||
['mean_reversion', { entryThreshold: NaN }],
|
||||
['momentum', { positionSize: Infinity }],
|
||||
['momentum', { momentumThreshold: '5' }],
|
||||
['pairs_trading', { pairA: 'A.US', pairB: 'A.US' }],
|
||||
] as const) {
|
||||
expect(() => engine.addNativeStrategy(name, 'invalid', 'invalid', parameters)).toThrow();
|
||||
}
|
||||
expect(() =>
|
||||
engine.addNativeStrategy('sma_crossover', 'defaults', 'defaults', {})
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { canonicalJson as neutralCanonicalJson } from '../../apps/stock/orchestrator/src/canonical-json';
|
||||
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
|
||||
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
|
||||
import { config, makeExecution, order, quote, start } from '../fixtures/execution';
|
||||
import {
|
||||
attachCounter,
|
||||
CounterStrategy,
|
||||
FaultRepository,
|
||||
recoveryConfig,
|
||||
} from '../fixtures/strategy-recovery';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture() {
|
||||
const repository = new FaultRepository(new BacktestExecutionRepository());
|
||||
const { execution, engine } = makeExecution(repository);
|
||||
await execution.initialize(config, engine);
|
||||
cleanup.push(() => execution.shutdown());
|
||||
const { manager, strategy } = await attachCounter(execution);
|
||||
cleanup.push(() => manager.shutdown());
|
||||
return { repository, execution, manager, strategy };
|
||||
}
|
||||
const isPending = (value: unknown) => (value as { status?: string }).status === 'pending';
|
||||
const isDispatched = (value: unknown) => (value as { status?: string }).status === 'dispatched';
|
||||
|
||||
describe('transactional strategy recovery', () => {
|
||||
test('input order is its admission sequence, not JavaScript numeric object-key enumeration', async () => {
|
||||
const f = await fixture();
|
||||
await f.execution.enqueueMarketData(quote('10'));
|
||||
await f.execution.enqueueMarketData(quote('2', 110, 100, start + 1));
|
||||
await f.manager.recover();
|
||||
expect(f.strategy.equities).toEqual([10000, 10009.9]);
|
||||
});
|
||||
test('a failed decision restores indicators and leaves later admitted inputs recoverable', async () => {
|
||||
const f = await fixture();
|
||||
f.strategy.failDecision = true;
|
||||
await f.execution.enqueueMarketData(quote('one'));
|
||||
await f.execution.enqueueMarketData(quote('two', 110, 100, start + 1));
|
||||
await expect(f.manager.recover()).rejects.toThrow('decision failure');
|
||||
expect(f.strategy.count).toBe(0);
|
||||
expect(f.strategy.getPosition('A')).toBe(0);
|
||||
expect((await f.execution.getRecoveryStatus()).pendingInputs).toBe(true);
|
||||
await expect(f.execution.submitOrder(order('manual'))).rejects.toThrow('backlog');
|
||||
f.strategy.failDecision = false;
|
||||
await f.manager.recover();
|
||||
expect(f.strategy.count).toBe(2);
|
||||
expect(f.strategy.getPosition('A')).toBe(2);
|
||||
expect(f.strategy.equities).toEqual([10000, 10009.9]);
|
||||
expect((await f.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
||||
await f.manager.onMarketData(quote('one'));
|
||||
expect(f.strategy.count).toBe(2);
|
||||
});
|
||||
test.each(['before', 'after'] as const)(
|
||||
'checkpoint + intent roll back together on a %s intent-write failure',
|
||||
async stage => {
|
||||
const f = await fixture();
|
||||
f.repository.fault = { method: 'putIntent', matches: isPending, stage };
|
||||
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('transaction failure');
|
||||
expect(f.strategy.count).toBe(0);
|
||||
expect((await f.execution.getAccount()).cash).toBe(10000);
|
||||
expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false);
|
||||
await f.manager.recover();
|
||||
expect(f.strategy.count).toBe(1);
|
||||
expect(f.strategy.getPosition('A')).toBe(1);
|
||||
}
|
||||
);
|
||||
test('a lost checkpoint commit acknowledgement resumes from durable state, not a second decision', async () => {
|
||||
const f = await fixture();
|
||||
f.repository.fault = { method: 'putIntent', matches: isPending, stage: 'commit' };
|
||||
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('commit acknowledgement');
|
||||
expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(true);
|
||||
await f.manager.shutdown();
|
||||
const restarted = await attachCounter(f.execution);
|
||||
cleanup.push(() => restarted.manager.shutdown());
|
||||
expect(restarted.strategy.count).toBe(1);
|
||||
expect(restarted.strategy.getPosition('A')).toBe(1);
|
||||
expect(restarted.strategy.getPerformance().trades).toBe(1);
|
||||
await restarted.manager.onMarketData(quote('one'));
|
||||
expect(restarted.strategy.count).toBe(1);
|
||||
});
|
||||
test.each(['after', 'commit'] as const)(
|
||||
'outbox dispatch is idempotent after a %s dispatch-status failure',
|
||||
async stage => {
|
||||
const f = await fixture();
|
||||
f.repository.fault = { method: 'putIntent', matches: isDispatched, stage };
|
||||
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('injected');
|
||||
await f.manager.recover();
|
||||
expect(f.strategy.count).toBe(1);
|
||||
expect(f.strategy.getPosition('A')).toBe(1);
|
||||
expect(f.strategy.getPerformance().trades).toBe(1);
|
||||
expect((await f.execution.getAccount()).cash).toBe(9899.9);
|
||||
expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false);
|
||||
}
|
||||
);
|
||||
test('fill callback failure cannot lose a committed fill or advance its checkpoint', async () => {
|
||||
const f = await fixture();
|
||||
f.strategy.failFill = true;
|
||||
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('fill callback');
|
||||
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1);
|
||||
expect(f.strategy.getPosition('A')).toBe(0);
|
||||
expect(f.strategy.getPerformance().trades).toBe(0);
|
||||
f.strategy.failFill = false;
|
||||
await f.manager.recover();
|
||||
await f.manager.recover();
|
||||
expect(f.strategy.getPosition('A')).toBe(1);
|
||||
expect(f.strategy.getPerformance().trades).toBe(1);
|
||||
});
|
||||
test('shutdown preserves unfilled orders, indicator history, and committed cursor', async () => {
|
||||
const f = await fixture();
|
||||
await f.manager.onMarketData(quote('one', 100, 0));
|
||||
const before = f.strategy.captureCheckpoint();
|
||||
await f.manager.shutdown();
|
||||
const restarted = await attachCounter(f.execution);
|
||||
cleanup.push(() => restarted.manager.shutdown());
|
||||
expect(restarted.strategy.captureCheckpoint()).toEqual(before);
|
||||
expect((await f.execution.getStrategySnapshot('counter')).orders).toHaveLength(1);
|
||||
await restarted.manager.onMarketData(quote('two', 100, 100, start + 1));
|
||||
expect(restarted.strategy.getPerformance().trades).toBe(2);
|
||||
});
|
||||
test('configuration and implementation versions cannot silently reset an existing strategy', async () => {
|
||||
const f = await fixture();
|
||||
await f.manager.onMarketData(quote('one'));
|
||||
await f.manager.shutdown();
|
||||
const changed = new CounterStrategy(f.execution, {
|
||||
...recoveryConfig,
|
||||
parameters: { changed: true },
|
||||
});
|
||||
await expect(attachCounter(f.execution, changed)).rejects.toThrow('version changed');
|
||||
const version = new CounterStrategy(f.execution);
|
||||
version.version = 'counter/v2';
|
||||
await expect(attachCounter(f.execution, version)).rejects.toThrow('version changed');
|
||||
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1);
|
||||
});
|
||||
test('disabled-period inputs do not become retroactive trades when re-enabled', async () => {
|
||||
const f = await fixture();
|
||||
await f.manager.onMarketData(quote('one'));
|
||||
await f.manager.disableStrategy('counter');
|
||||
await f.manager.onMarketData(quote('two', 100, 100, start + 1));
|
||||
await f.manager.enableStrategy('counter');
|
||||
await f.manager.recover();
|
||||
expect(f.strategy.count).toBe(1);
|
||||
await f.manager.onMarketData(quote('three', 100, 100, start + 2));
|
||||
expect(f.strategy.count).toBe(2);
|
||||
});
|
||||
test('observers run only after checkpoint commit and cannot roll back financial intent', async () => {
|
||||
const f = await fixture();
|
||||
let signals = 0;
|
||||
f.strategy.on('signal', () => {
|
||||
signals++;
|
||||
throw new Error('observer');
|
||||
});
|
||||
f.execution.setObserver(async () => {
|
||||
throw new Error('observer');
|
||||
});
|
||||
await f.manager.onMarketData(quote('one'));
|
||||
expect(signals).toBe(1);
|
||||
expect(f.strategy.count).toBe(1);
|
||||
expect(f.strategy.getPosition('A')).toBe(1);
|
||||
});
|
||||
test('checkpoint serialization rejects lossy or non-finite state', () => {
|
||||
for (const value of [NaN, Infinity, undefined, new Map(), new Date(), { hidden: undefined }]) {
|
||||
expect(() => canonicalJson(value)).toThrow('plain JSON');
|
||||
}
|
||||
expect(canonicalJson({ b: 1, a: [2] })).toBe(canonicalJson({ a: [2], b: 1 }));
|
||||
});
|
||||
test('canonical serialization retains historical bytes and the compatibility export', () => {
|
||||
expect(canonicalJson).toBe(neutralCanonicalJson);
|
||||
const value = JSON.parse(
|
||||
'{"z":-0,"𐀀":3,"a":[{"z":2,"a":1},null,true],"\\ue000":4,"__proto__":{"b":2,"a":1},"10":10,"2":2}'
|
||||
);
|
||||
const expected =
|
||||
'{"2":2,"10":10,"__proto__":{"a":1,"b":2},"a":[{"a":1,"z":2},null,true],"z":0,"𐀀":3,"\ue000":4}';
|
||||
expect(canonicalJson(value)).toBe(expected);
|
||||
expect(neutralCanonicalJson(value)).toBe(expected);
|
||||
});
|
||||
test('a callback cannot open a nested repository transaction and deadlock its account', async () => {
|
||||
const f = await fixture();
|
||||
f.strategy.onDecision = async () => {
|
||||
await f.execution.getOrderStatus('anything');
|
||||
};
|
||||
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow(
|
||||
'cannot perform repository I/O'
|
||||
);
|
||||
expect(f.strategy.count).toBe(0);
|
||||
});
|
||||
test('a reused intent ID cannot replace a dispatched request or advance its next decision', async () => {
|
||||
const f = await fixture();
|
||||
f.strategy.onDecision = async () => {
|
||||
f.execution.captureStrategyOrder(order('fixed-id', 'buy', 1), 'counter');
|
||||
};
|
||||
await f.manager.onMarketData(quote('one'));
|
||||
await expect(f.manager.onMarketData(quote('two', 100, 100, start + 1))).rejects.toThrow(
|
||||
'Conflicting strategy order intent'
|
||||
);
|
||||
expect(f.strategy.count).toBe(1);
|
||||
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,122 +0,0 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';
|
||||
import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
|
||||
import { config, makeExecution, quote } from '../fixtures/execution';
|
||||
import {
|
||||
CounterStrategy,
|
||||
makeStrategyManager,
|
||||
recoveryConfig,
|
||||
} from '../fixtures/strategy-recovery';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
const { execution, engine } = makeExecution();
|
||||
await execution.initialize(config, engine);
|
||||
cleanup.push(() => execution.shutdown());
|
||||
const modeManager = { getTradingEngine: () => engine } as ModeManager;
|
||||
return {
|
||||
execution,
|
||||
dependencies: { modeManager, execution },
|
||||
};
|
||||
}
|
||||
|
||||
describe('strategy registration and expansion', () => {
|
||||
test('custom lazy factories integrate with ordinary initialization, recovery and restart', async () => {
|
||||
const f = await fixture();
|
||||
let created = 0;
|
||||
const registry = new StrategyRegistry().register(
|
||||
['fixture', 'custom-alias'],
|
||||
(config, dependencies) => {
|
||||
created++;
|
||||
expect(dependencies.execution).toBe(f.execution);
|
||||
return new CounterStrategy(dependencies.execution, config);
|
||||
}
|
||||
);
|
||||
expect(created).toBe(0);
|
||||
const marketData = new EventEmitter();
|
||||
const manager = makeStrategyManager({ ...f.dependencies, registry, marketData });
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await manager.initializeStrategies([{ ...recoveryConfig, name: ' Custom-Alias ' }]);
|
||||
expect(marketData.listenerCount('marketDataBatch')).toBe(1);
|
||||
marketData.emit('marketDataBatch', [quote('first')]);
|
||||
await manager.drain();
|
||||
expect((manager.getStrategy('counter') as CounterStrategy).count).toBe(1);
|
||||
await manager.shutdown();
|
||||
expect(marketData.listenerCount('marketDataBatch')).toBe(0);
|
||||
const restarted = makeStrategyManager({ ...f.dependencies, registry, marketData });
|
||||
cleanup.push(() => restarted.shutdown());
|
||||
await restarted.restoreStrategies();
|
||||
restarted.setupEventListeners();
|
||||
expect(marketData.listenerCount('marketDataBatch')).toBe(1);
|
||||
expect(created).toBe(2);
|
||||
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(1);
|
||||
marketData.emit('marketDataBatch', [quote('second')]);
|
||||
await restarted.drain();
|
||||
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(2);
|
||||
});
|
||||
|
||||
test('aliases are normalized and registration conflicts fail atomically', async () => {
|
||||
const f = await fixture();
|
||||
const registry = new StrategyRegistry().register(
|
||||
['fixture'],
|
||||
config => new CounterStrategy(f.execution, config)
|
||||
);
|
||||
const factory = () => new CounterStrategy(f.execution);
|
||||
expect(() => registry.register(['new', 'FIXTURE'], factory)).toThrow('already registered');
|
||||
await expect(
|
||||
registry.create({ ...recoveryConfig, name: 'new' }, f.dependencies)
|
||||
).rejects.toThrow('Unknown strategy');
|
||||
for (const aliases of [[], [''], [' '], ['duplicate', 'DUPLICATE']]) {
|
||||
expect(() => registry.register(aliases, factory)).toThrow('nonempty and distinct');
|
||||
}
|
||||
expect(
|
||||
(await registry.create({ ...recoveryConfig, name: ' FIXTURE ' }, f.dependencies)).getConfig()
|
||||
.id
|
||||
).toBe('counter');
|
||||
});
|
||||
|
||||
test('built-in aliases keep their implementations and unknown names fail closed', async () => {
|
||||
const f = await fixture();
|
||||
const registry = createBuiltinStrategyRegistry();
|
||||
for (const name of ['meanreversion', 'mean-reversion']) {
|
||||
const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies);
|
||||
expect(strategy).toBeInstanceOf(MeanReversionStrategy);
|
||||
expect(strategy.getCheckpointVersion()).toBe('mean-reversion/v2');
|
||||
}
|
||||
for (const name of ['smacrossover', 'sma-crossover', 'moving-average']) {
|
||||
const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies);
|
||||
expect(strategy).toBeInstanceOf(SmaCrossoverStrategy);
|
||||
expect(strategy.getCheckpointVersion()).toBe('sma-crossover-fixed/v2');
|
||||
}
|
||||
for (const name of ['mlenhanced', 'ml-enhanced']) {
|
||||
expect(
|
||||
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
|
||||
).toBeUndefined();
|
||||
}
|
||||
await expect(
|
||||
registry.create({ ...recoveryConfig, name: 'missing' }, f.dependencies)
|
||||
).rejects.toThrow('Unknown strategy: missing');
|
||||
});
|
||||
|
||||
test('factory failures propagate before an invalid strategy can be activated', async () => {
|
||||
const f = await fixture();
|
||||
const registry = new StrategyRegistry().register(['fixture'], async () => {
|
||||
throw new Error('factory failed');
|
||||
});
|
||||
const manager = makeStrategyManager({ ...f.dependencies, registry });
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed');
|
||||
expect(manager.getActiveStrategies()).toEqual([]);
|
||||
expect(await f.execution.registeredStrategies()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -13,7 +13,7 @@ import type {
|
|||
StrategyContext,
|
||||
StrategyDiagnosticSnapshot,
|
||||
StrategyProgram,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const hold = () => ({ mode: 'target' as const, targets: [] });
|
||||
|
|
|
|||
|
|
@ -1,204 +0,0 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
|
||||
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
type OrchestratorServices,
|
||||
} from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A.US', 'B.US'],
|
||||
startDate: '2024-01-01T00:00:00Z',
|
||||
endDate: '2024-03-15T00:00:00Z',
|
||||
initialCapital: 10000,
|
||||
dataFrequency: '1d',
|
||||
speed: 'max',
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
});
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
});
|
||||
async function fixture() {
|
||||
const services: OrchestratorServices = { logger };
|
||||
const storage = new StorageService(services.logger, null, null, {
|
||||
allowSyntheticData: true,
|
||||
syntheticSeed: 42,
|
||||
});
|
||||
const market: MarketDataService = new MarketDataService({
|
||||
logger,
|
||||
storage,
|
||||
drainStrategies: () => manager.drain(),
|
||||
});
|
||||
const execution = new ExecutionService(services, storage);
|
||||
const registry = createBuiltinStrategyRegistry();
|
||||
const manager: StrategyManager = new StrategyManager({
|
||||
logger,
|
||||
marketData: market,
|
||||
execution,
|
||||
createStrategy: config => registry.create(config, { execution, modeManager: mode }),
|
||||
});
|
||||
const mode: ModeManager = new ModeManager({
|
||||
logger,
|
||||
marketData: market,
|
||||
execution,
|
||||
strategies: manager,
|
||||
});
|
||||
const backend = new BacktestEngine({
|
||||
logger,
|
||||
storage,
|
||||
strategies: manager,
|
||||
execution,
|
||||
getTradingEngine: () => mode.getTradingEngine(),
|
||||
});
|
||||
await mode.initializeMode(config);
|
||||
cleanup.push(async () => {
|
||||
await backend.shutdown();
|
||||
await mode.shutdown();
|
||||
});
|
||||
return { services, storage, execution, manager, mode, backend };
|
||||
}
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(done => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe('composed TypeScript backtests', () => {
|
||||
test('completed results and repeatable exports agree with the authoritative ledger', async () => {
|
||||
const f = await fixture();
|
||||
const result = await f.backend.runBacktest(config);
|
||||
const account = await f.execution.getAccount();
|
||||
expect(result.status).toBe('completed');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(result.equity.at(-1)?.value).toBe(account.equity);
|
||||
expect(result.metrics.totalReturn).toBeCloseTo(
|
||||
((account.equity - config.initialCapital) / config.initialCapital) * 100
|
||||
);
|
||||
expect(result.positions.every(position => position.quantity !== 0)).toBe(true);
|
||||
for (const position of result.positions) {
|
||||
const quote = account.quotes[position.symbol]!;
|
||||
expect(position.currentPrice).toBe((quote.bid + quote.ask) / 2);
|
||||
}
|
||||
const first = await f.backend.exportResults();
|
||||
expect(JSON.parse(first).summary.totalTrades).toBe(result.trades.length);
|
||||
expect(JSON.parse(first).equityCurve.map((point: { value: number }) => point.value)).toEqual(
|
||||
result.equity.map(point => point.value)
|
||||
);
|
||||
result.equity[0]!.value = -1;
|
||||
await f.backend.exportResults('csv');
|
||||
await f.backend.exportResults('html');
|
||||
expect(await f.backend.exportResults()).toBe(first);
|
||||
expect(f.backend.getStatus()).toMatchObject({
|
||||
isRunning: false,
|
||||
isPaused: false,
|
||||
progress: 100,
|
||||
});
|
||||
});
|
||||
|
||||
test('service reuse does not leak symbols, indicators, equity or exports across runs', async () => {
|
||||
const f = await fixture();
|
||||
const first = await f.backend.runBacktest(config);
|
||||
const secondConfig = { ...config, symbols: ['C.US'] };
|
||||
await f.mode.initializeMode(secondConfig);
|
||||
const second = await f.backend.runBacktest(secondConfig);
|
||||
expect(Object.keys(second.ohlcData)).toEqual(['C.US']);
|
||||
expect(second.trades.every(trade => trade.symbol === 'C.US')).toBe(true);
|
||||
await f.mode.initializeMode(config);
|
||||
const repeated = await f.backend.runBacktest(config);
|
||||
expect(repeated.trades).toEqual(first.trades);
|
||||
expect(repeated.metrics).toEqual(first.metrics);
|
||||
expect(repeated.equity).toEqual(first.equity);
|
||||
});
|
||||
|
||||
test('overlapping runs fail before they can reset the active read or its controls', async () => {
|
||||
const f = await fixture();
|
||||
const gate = deferred<void>();
|
||||
let loads = 0;
|
||||
const run = f.backend.runBacktest(config, async load => {
|
||||
loads++;
|
||||
await gate.promise;
|
||||
return load();
|
||||
});
|
||||
const settled = run.catch(error => error);
|
||||
await expect(f.backend.runBacktest(config)).rejects.toThrow('already running');
|
||||
await expect(f.backend.exportResults()).rejects.toThrow('unfinished');
|
||||
expect(loads).toBe(1);
|
||||
await f.backend.stopBacktest();
|
||||
expect(await settled).toBeInstanceOf(BacktestCancelledError);
|
||||
gate.resolve();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
expect(f.manager.getAllStrategies()).toEqual([]);
|
||||
await expect(f.backend.exportResults()).rejects.toThrow('No completed');
|
||||
expect(f.backend.getStatus()).toMatchObject({ isRunning: false, progress: 0 });
|
||||
});
|
||||
|
||||
test('cancellation at progress never returns a partial completed result or a reusable export', async () => {
|
||||
const f = await fixture();
|
||||
const updates: number[] = [];
|
||||
f.backend.on('progress', update => {
|
||||
updates.push(update.progress);
|
||||
void f.backend.stopBacktest();
|
||||
});
|
||||
const outcome = await f.backend.runBacktest(config).catch(error => error);
|
||||
expect(outcome).toBeInstanceOf(BacktestCancelledError);
|
||||
expect(updates).not.toContain(100);
|
||||
expect(f.backend.getStatus()).toMatchObject({ isRunning: false, isPaused: false });
|
||||
await expect(f.backend.exportResults()).rejects.toThrow('No completed');
|
||||
});
|
||||
|
||||
test('pause gates the next input, and resume produces the same ledger result', async () => {
|
||||
const f = await fixture();
|
||||
const paused = deferred<void>();
|
||||
const original = f.manager.onMarketData.bind(f.manager);
|
||||
let received = 0;
|
||||
f.manager.onMarketData = async data => {
|
||||
await original(data);
|
||||
if (++received === 1) {
|
||||
await f.backend.pauseBacktest();
|
||||
paused.resolve();
|
||||
}
|
||||
};
|
||||
const run = f.backend.runBacktest(config);
|
||||
await paused.promise;
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
expect(received).toBe(1);
|
||||
expect(f.backend.getStatus().isPaused).toBe(true);
|
||||
await f.backend.resumeBacktest();
|
||||
const result = await run;
|
||||
expect(result.status).toBe('completed');
|
||||
expect(result.equity.at(-1)?.value).toBe((await f.execution.getAccount()).equity);
|
||||
});
|
||||
|
||||
test('unavailable financial state fails instead of fabricating initial-capital performance', async () => {
|
||||
const f = await fixture();
|
||||
f.execution.getAccount = async () => {
|
||||
throw new Error('Ledger unavailable');
|
||||
};
|
||||
await expect(f.backend.runBacktest(config)).rejects.toThrow('Ledger unavailable');
|
||||
expect(f.backend.getStatus().isRunning).toBe(false);
|
||||
await expect(f.backend.exportResults()).rejects.toThrow('No completed');
|
||||
});
|
||||
|
||||
test('observer failures cannot change the result, and shutdown closes future admission', async () => {
|
||||
const f = await fixture();
|
||||
f.backend.on('progress', () => {
|
||||
throw new Error('observer failed');
|
||||
});
|
||||
expect((await f.backend.runBacktest(config)).status).toBe('completed');
|
||||
await f.backend.shutdown();
|
||||
await expect(f.backend.runBacktest(config)).rejects.toThrow('shutting down');
|
||||
});
|
||||
});
|
||||
|
|
@ -11,7 +11,7 @@ import {
|
|||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { readCanonicalBuildIdentity } from '../../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build';
|
||||
import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ import { Pool } from 'pg';
|
|||
import { stageFinancialTransaction } from '@stock-bot/engine';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
parseFinancialTransactionResult,
|
||||
type CanonicalMatchingConfig,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
} from '@stock-bot/stock-config/canonical-execution';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import {
|
||||
canonicalPaperInputSchema,
|
||||
type CanonicalExecutionRepository,
|
||||
|
|
@ -20,7 +20,6 @@ import {
|
|||
} from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution';
|
||||
import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
|
||||
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
|
||||
import {
|
||||
|
|
@ -535,20 +534,10 @@ describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => {
|
|||
]) {
|
||||
await expect(f.make({ programs: [program] })).rejects.toThrow('definition');
|
||||
}
|
||||
const legacy = new PostgresExecutionRepository(f.postgres);
|
||||
await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow(
|
||||
'canonical adapter'
|
||||
);
|
||||
await expect(legacy.initialize(f.config.risk.ledger.accountId, {} as never)).rejects.toThrow(
|
||||
'canonical adapter'
|
||||
);
|
||||
await f.pool.query(
|
||||
'UPDATE simulation_accounts SET state = \'{"kind":"canonical-paper","version":99}\''
|
||||
);
|
||||
await expect(f.make()).rejects.toThrow('explicit migration');
|
||||
await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow(
|
||||
'canonical adapter'
|
||||
);
|
||||
await f.pool.query('UPDATE simulation_accounts SET state = \'{"cash":100}\'');
|
||||
await expect(f.make()).rejects.toThrow('explicit migration');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src
|
|||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { StorageService } from '@stock-bot/trading-runtime/historical-storage';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,235 +0,0 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
|
||||
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
});
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety'))
|
||||
throw new Error('Dedicated safety database required');
|
||||
const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
const sql = readFileSync(
|
||||
new URL('../../database/postgres/init/11-simulation-execution-ledger.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await pool.query(sql);
|
||||
await pool.query(sql);
|
||||
await pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
let now = start;
|
||||
const make = async (
|
||||
limits = {
|
||||
maxOrderSize: 100,
|
||||
maxPositionSize: 100,
|
||||
maxDailyLoss: 100,
|
||||
maxGrossExposure: 10000,
|
||||
maxSymbolExposure: 10000,
|
||||
}
|
||||
) => {
|
||||
const runtime = makeExecution(new PostgresExecutionRepository(postgres), () => now);
|
||||
await runtime.execution.initialize(
|
||||
{
|
||||
mode: 'paper',
|
||||
accountId: 'fixture',
|
||||
startingCapital: config.initialCapital,
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
maxQuoteAgeMs: 1000,
|
||||
riskLimits: limits,
|
||||
},
|
||||
runtime.engine
|
||||
);
|
||||
cleanup.push(() => runtime.execution.shutdown());
|
||||
return runtime.execution;
|
||||
};
|
||||
const execution = await make();
|
||||
return {
|
||||
pool,
|
||||
postgres,
|
||||
execution,
|
||||
make,
|
||||
setTime(time: number) {
|
||||
now = time;
|
||||
},
|
||||
};
|
||||
}
|
||||
describe.skipIf(!url)('paper execution ledger on real PostgreSQL', () => {
|
||||
test('competing service instances deduplicate the same client ID, fill and account transaction', async () => {
|
||||
const f = await fixture();
|
||||
const second = await f.make();
|
||||
await f.execution.onMarketData(quote('q'));
|
||||
const reports = await Promise.all([
|
||||
f.execution.submitOrder(order('id')),
|
||||
second.submitOrder(order('id')),
|
||||
]);
|
||||
expect(reports[0]).toEqual(reports[1]);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1);
|
||||
const fills = (await f.pool.query('SELECT payload FROM simulation_fills')).rows;
|
||||
expect(fills).toHaveLength(1);
|
||||
expect(fills[0].payload.pnl).toBe(-1);
|
||||
expect((await second.getAccount()).cash).toBe(8999);
|
||||
expect((await second.getPositions())[0]?.quantity).toBe(10);
|
||||
await expect(second.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf(
|
||||
ExecutionConflictError
|
||||
);
|
||||
});
|
||||
test('a fill-write failure rolls back acceptance and cash/positions together; retry has no phantom fill', async () => {
|
||||
const f = await fixture();
|
||||
await f.execution.onMarketData(quote('q'));
|
||||
let events = 0;
|
||||
f.execution.on('fill', () => events++);
|
||||
await f.pool.query(`CREATE FUNCTION reject_fill() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
RAISE EXCEPTION 'injected fill failure'; END $$;
|
||||
CREATE TRIGGER reject_fill BEFORE INSERT ON simulation_fills FOR EACH ROW EXECUTE FUNCTION reject_fill();`);
|
||||
await expect(f.execution.submitOrder(order('id'))).rejects.toThrow('injected fill failure');
|
||||
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0);
|
||||
expect((await f.execution.getAccount()).cash).toBe(10000);
|
||||
expect(events).toBe(0);
|
||||
await f.pool.query('DROP TRIGGER reject_fill ON simulation_fills');
|
||||
expect((await f.execution.submitOrder(order('id'))).status).toBe('filled');
|
||||
expect(events).toBe(1);
|
||||
});
|
||||
test('restart restores partial orders, consumed liquidity, cash and strategy positions without refilling duplicates', async () => {
|
||||
const f = await fixture();
|
||||
await f.execution.onMarketData(quote('q1', 100, 3));
|
||||
const first = await f.execution.submitOrder(order('id'), { strategyId: 'strategy' });
|
||||
expect(first.status).toBe('partiallyFilled');
|
||||
await f.execution.shutdown();
|
||||
const second = await f.make();
|
||||
expect((await second.getStrategySnapshot('strategy')).positions.A).toBe(3);
|
||||
expect((await second.getStrategySnapshot('strategy')).orders).toHaveLength(1);
|
||||
expect(await second.onMarketData(quote('q1', 100, 3))).toBe(false);
|
||||
f.setTime(start + 1);
|
||||
await second.onMarketData(quote('q2', 100, 7, start + 1));
|
||||
expect((await second.getOrderStatus(first.orderId))?.status).toBe('filled');
|
||||
expect((await second.getAccount()).cash).toBe(8999);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(2);
|
||||
});
|
||||
test('account locking serializes projected-risk reservations across producers', async () => {
|
||||
const f = await fixture();
|
||||
const limits = {
|
||||
maxOrderSize: 100,
|
||||
maxPositionSize: 100,
|
||||
maxDailyLoss: 100,
|
||||
maxGrossExposure: 1000,
|
||||
maxSymbolExposure: 1000,
|
||||
};
|
||||
const first = await f.make(limits),
|
||||
second = await f.make(limits);
|
||||
await first.onMarketData(quote('q', 100, 0));
|
||||
const reports = await Promise.all([
|
||||
first.submitOrder(order('a', 'buy', 7)),
|
||||
second.submitOrder(order('b', 'buy', 7)),
|
||||
]);
|
||||
expect(reports.map(r => r.status).sort()).toEqual(['accepted', 'rejected']);
|
||||
expect((await f.execution.getAccount()).cash).toBe(10000);
|
||||
});
|
||||
test('duplicate and conflicting market IDs cannot reapply fills, even after a restart', async () => {
|
||||
const f = await fixture();
|
||||
await f.execution.onMarketData(quote('q', 100, 3));
|
||||
const report = await f.execution.submitOrder(order('id'));
|
||||
const second = await f.make();
|
||||
await expect(second.onMarketData(quote('q', 200, 3))).rejects.toBeInstanceOf(
|
||||
ExecutionConflictError
|
||||
);
|
||||
expect(await second.onMarketData(quote('q', 100, 3))).toBe(false);
|
||||
expect((await second.getOrderStatus(report.orderId))?.fills).toHaveLength(1);
|
||||
expect((await second.getAccount()).cash).toBe(9699.7);
|
||||
});
|
||||
test('daily P&L uses deltas; loss limit blocks new risk but permits reduction and resets at UTC midnight', async () => {
|
||||
const f = await fixture();
|
||||
const e = await f.make({
|
||||
maxOrderSize: 100,
|
||||
maxPositionSize: 100,
|
||||
maxDailyLoss: 1,
|
||||
maxGrossExposure: 10000,
|
||||
maxSymbolExposure: 10000,
|
||||
});
|
||||
await e.onMarketData(quote('q'));
|
||||
await e.submitOrder(order('open'));
|
||||
expect((await e.submitOrder(order('blocked', 'buy', 1))).status).toBe('rejected');
|
||||
expect((await e.submitOrder(order('close', 'sell', 10))).status).toBe('filled');
|
||||
expect((await e.getAccount()).dailyPnl).toBe(-2);
|
||||
f.setTime(start + 86400000);
|
||||
await e.onMarketData(quote('new-day', 100, 100, start + 86400000));
|
||||
expect((await e.getAccount()).dailyPnl).toBe(0);
|
||||
expect((await e.submitOrder(order('new-day-order', 'buy', 1))).status).toBe('filled');
|
||||
});
|
||||
test('stale quotes reject submission; day orders expire and unfilled cancellation survives restart', async () => {
|
||||
const f = await fixture();
|
||||
await f.execution.onMarketData(quote('q', 100, 0));
|
||||
const day = await f.execution.submitOrder(order('day'));
|
||||
const gtc = await f.execution.submitOrder({ ...order('gtc'), timeInForce: 'GTC' });
|
||||
f.setTime(start + 2000);
|
||||
expect((await f.execution.submitOrder(order('stale'))).rejectionReason).toContain('stale');
|
||||
await expect(f.execution.onMarketData(quote('old', 100, 100, start + 1))).rejects.toThrow(
|
||||
'Stale'
|
||||
);
|
||||
f.setTime(start + 86400000);
|
||||
await f.execution.onMarketData(quote('next', 100, 0, start + 86400000));
|
||||
expect((await f.execution.getOrderStatus(day.orderId))?.status).toBe('cancelled');
|
||||
expect(await f.execution.cancelOrder(gtc.orderId)).toBe(true);
|
||||
const second = await f.make();
|
||||
expect((await second.getOrderStatus(gtc.orderId))?.status).toBe('cancelled');
|
||||
});
|
||||
test('observer exceptions cannot change committed fills into reported failure or trigger another fill', async () => {
|
||||
const f = await fixture();
|
||||
await f.execution.onMarketData(quote('q'));
|
||||
f.execution.setObserver(async () => {
|
||||
throw new Error('observer disconnected');
|
||||
});
|
||||
const report = await f.execution.submitOrder(order('id'));
|
||||
expect(report.status).toBe('filled');
|
||||
expect((await f.execution.submitOrder(order('id'))).orderId).toBe(report.orderId);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('pending orders retain their accepted commission policy after account configuration changes', async () => {
|
||||
const f = await fixture();
|
||||
await f.execution.onMarketData(quote('q1', 100, 3));
|
||||
const original = await f.execution.submitOrder(order('pending'));
|
||||
const changed = makeExecution(new PostgresExecutionRepository(f.postgres), () => start + 1);
|
||||
await changed.execution.initialize(
|
||||
{
|
||||
mode: 'paper',
|
||||
accountId: 'fixture',
|
||||
startingCapital: 10000,
|
||||
commission: 0.01,
|
||||
slippage: 0,
|
||||
},
|
||||
changed.engine
|
||||
);
|
||||
cleanup.push(() => changed.execution.shutdown());
|
||||
await changed.execution.onMarketData(quote('q2', 100, 10, start + 1));
|
||||
const report = await changed.execution.getOrderStatus(original.orderId);
|
||||
expect(report?.fills.reduce((n, fill) => n + fill.commission, 0)).toBe(1);
|
||||
const next = await changed.execution.submitOrder(order('new', 'buy', 1));
|
||||
expect(next.fills[0]?.commission).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -13,8 +13,8 @@ import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestra
|
|||
import {
|
||||
readPaperDeployment,
|
||||
verifyPaperEvidenceCustody,
|
||||
} from '../../apps/stock/orchestrator/src/paper/paper-deployment-custody';
|
||||
import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
|
||||
} from '@stock-bot/trading-runtime/paper-deployment-custody';
|
||||
import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity';
|
||||
import { PaperDeploymentHost } from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import { createHttpSecurity, ServiceContainerBuilder } from '@stock-bot/di';
|
|||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import type { PaperRuntime } from '@stock-bot/stock-config/paper-runtime';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
|
|
|
|||
|
|
@ -1,373 +0,0 @@
|
|||
import { fork } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
|
||||
import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
|
||||
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger, makeExecution, quote, start } from '../fixtures/execution';
|
||||
import {
|
||||
attachCounter,
|
||||
CounterStrategy,
|
||||
makeStrategyManager,
|
||||
recoveryConfig,
|
||||
} from '../fixtures/strategy-recovery';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query('CREATE SCHEMA ' + schema);
|
||||
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query('DROP SCHEMA ' + schema + ' CASCADE');
|
||||
await admin.end();
|
||||
});
|
||||
for (const migration of ['11-simulation-execution-ledger.sql', '13-strategy-recovery.sql']) {
|
||||
await pool.query(
|
||||
readFileSync(new URL('../../database/postgres/init/' + migration, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
let now = start + 100;
|
||||
const make = async (
|
||||
accountId = 'fixture',
|
||||
repository: ExecutionRepository = new PostgresExecutionRepository(postgres)
|
||||
) => {
|
||||
const runtime = makeExecution(repository, () => now);
|
||||
await runtime.execution.initialize(
|
||||
{
|
||||
mode: 'paper',
|
||||
accountId,
|
||||
startingCapital: 10000,
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
maxQuoteAgeMs: 1000,
|
||||
},
|
||||
runtime.engine
|
||||
);
|
||||
cleanup.push(() => runtime.execution.shutdown());
|
||||
return runtime;
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
postgres,
|
||||
schema,
|
||||
make,
|
||||
setTime: (time: number) => {
|
||||
now = time;
|
||||
},
|
||||
getTime: () => now,
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
|
||||
test('paper mode restores registered strategies and drains their inbox before starting the feed', async () => {
|
||||
const f = await fixture();
|
||||
const original = await f.make();
|
||||
const config = {
|
||||
...recoveryConfig,
|
||||
id: 'sma',
|
||||
name: 'sma-crossover',
|
||||
parameters: { initialCapital: 10000 },
|
||||
};
|
||||
const prior = makeStrategyManager({
|
||||
execution: original.execution,
|
||||
modeManager: { getTradingEngine: () => original.engine } as ModeManager,
|
||||
});
|
||||
await prior.initializeStrategies([config]);
|
||||
await prior.onMarketData(quote('one'));
|
||||
await prior.shutdown();
|
||||
await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1));
|
||||
const services: OrchestratorServices = { logger, postgres: f.postgres };
|
||||
const storage = new StorageService(services.logger, null, null);
|
||||
const execution = new ExecutionService(services, storage, { clock: f.getTime });
|
||||
let feedStarted = false;
|
||||
class OfflineMarket extends MarketDataService {
|
||||
override async initialize() {
|
||||
feedStarted = true;
|
||||
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(false);
|
||||
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
||||
}
|
||||
}
|
||||
const market: MarketDataService = new OfflineMarket({
|
||||
logger,
|
||||
storage,
|
||||
drainStrategies: () => manager.drain(),
|
||||
});
|
||||
const registry = createBuiltinStrategyRegistry();
|
||||
const manager: StrategyManager = new StrategyManager({
|
||||
logger,
|
||||
execution,
|
||||
marketData: market,
|
||||
createStrategy: config => registry.create(config, { execution, modeManager: mode }),
|
||||
});
|
||||
const mode: ModeManager = new ModeManager({
|
||||
logger,
|
||||
marketData: market,
|
||||
execution,
|
||||
strategies: manager,
|
||||
});
|
||||
cleanup.push(() => mode.shutdown());
|
||||
await mode.initializeMode({
|
||||
mode: 'paper',
|
||||
accountId: 'fixture',
|
||||
startingCapital: 10000,
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
maxQuoteAgeMs: 1000,
|
||||
});
|
||||
expect(feedStarted).toBe(true);
|
||||
expect(manager.getActiveStrategies()).toEqual(['sma']);
|
||||
});
|
||||
test.each(['decision', 'checkpoint', 'dispatch'] as const)(
|
||||
'hard kill at %s resumes without skipped decisions or duplicate fills',
|
||||
async phase => {
|
||||
const f = await fixture();
|
||||
const { execution } = await f.make();
|
||||
const initial = await attachCounter(execution);
|
||||
await initial.manager.shutdown();
|
||||
await execution.enqueueMarketData(quote('one'));
|
||||
const child = fork(
|
||||
fileURLToPath(new URL('../fixtures/strategy-crash-owner.ts', import.meta.url)),
|
||||
[],
|
||||
{
|
||||
execPath: process.execPath,
|
||||
execArgv: [],
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
env: { ...process.env, STRATEGY_FIXTURE_SCHEMA: f.schema, STRATEGY_FIXTURE_PHASE: phase },
|
||||
}
|
||||
);
|
||||
const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));
|
||||
cleanup.push(async () => {
|
||||
child.kill('SIGKILL');
|
||||
await exited;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error('Crash fixture boundary timeout')), 5000);
|
||||
child.once('message', message => {
|
||||
clearTimeout(timeout);
|
||||
if ((message as { phase: string }).phase === phase) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error('Wrong crash boundary'));
|
||||
}
|
||||
});
|
||||
child.once('exit', () => {
|
||||
clearTimeout(timeout);
|
||||
reject(new Error('Crash fixture exited before its boundary'));
|
||||
});
|
||||
});
|
||||
child.kill('SIGKILL');
|
||||
await exited;
|
||||
const restarted = await f.make();
|
||||
const resumed = await attachCounter(restarted.execution);
|
||||
cleanup.push(() => resumed.manager.shutdown());
|
||||
expect(resumed.strategy.count).toBe(1);
|
||||
expect(resumed.strategy.getPosition('A')).toBe(1);
|
||||
expect(resumed.strategy.getPerformance().trades).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
|
||||
await resumed.manager.onMarketData(quote('one'));
|
||||
expect(resumed.strategy.count).toBe(1);
|
||||
expect((await restarted.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
test('checkpoint and order-intent SQL writes roll back together on an injected trigger failure', async () => {
|
||||
const f = await fixture();
|
||||
const { execution } = await f.make();
|
||||
const { manager, strategy } = await attachCounter(execution);
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_intent() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected intent failure'; END $$;
|
||||
CREATE TRIGGER reject_intent BEFORE INSERT ON simulation_strategy_intents FOR EACH ROW EXECUTE FUNCTION reject_intent()`);
|
||||
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('intent failure');
|
||||
expect(strategy.count).toBe(0);
|
||||
expect(
|
||||
(await f.pool.query('SELECT payload FROM simulation_strategy_checkpoints')).rows[0].payload
|
||||
.cursor
|
||||
).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_strategy_intents')).rows).toHaveLength(0);
|
||||
await f.pool.query('DROP TRIGGER reject_intent ON simulation_strategy_intents');
|
||||
await manager.recover();
|
||||
expect(strategy.count).toBe(1);
|
||||
expect(strategy.getPosition('A')).toBe(1);
|
||||
});
|
||||
|
||||
test('input admission survives a rollback before quote application and journal creation', async () => {
|
||||
const f = await fixture();
|
||||
const { execution } = await f.make();
|
||||
const { manager } = await attachCounter(execution);
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_input_apply() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected application failure'; END $$;
|
||||
CREATE TRIGGER reject_input_apply BEFORE UPDATE ON simulation_market_inputs FOR EACH ROW EXECUTE FUNCTION reject_input_apply()`);
|
||||
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('application failure');
|
||||
expect((await execution.getAccount()).quotes.A).toBeUndefined();
|
||||
expect((await f.pool.query('SELECT * FROM simulation_strategy_journal')).rows).toHaveLength(0);
|
||||
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(true);
|
||||
await manager.shutdown();
|
||||
await f.pool.query('DROP TRIGGER reject_input_apply ON simulation_market_inputs');
|
||||
const restarted = await f.make();
|
||||
const resumed = await attachCounter(restarted.execution);
|
||||
cleanup.push(() => resumed.manager.shutdown());
|
||||
expect(resumed.strategy.count).toBe(1);
|
||||
expect(resumed.strategy.getPosition('A')).toBe(1);
|
||||
});
|
||||
|
||||
test('competing owners restore the locked checkpoint before every decision and consume one intent', async () => {
|
||||
const f = await fixture();
|
||||
const one = await f.make(),
|
||||
two = await f.make();
|
||||
const first = await attachCounter(one.execution),
|
||||
second = await attachCounter(two.execution);
|
||||
cleanup.push(
|
||||
() => first.manager.shutdown(),
|
||||
() => second.manager.shutdown()
|
||||
);
|
||||
await one.execution.enqueueMarketData(quote('one'));
|
||||
await Promise.all([first.manager.recover(), second.manager.recover()]);
|
||||
await Promise.all([first.manager.recover(), second.manager.recover()]);
|
||||
expect(first.strategy.count).toBe(1);
|
||||
expect(second.strategy.count).toBe(1);
|
||||
expect(first.strategy.getPosition('A')).toBe(1);
|
||||
expect(second.strategy.getPosition('A')).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('stale admitted inputs restore indicators but never fabricate stale paper fills', async () => {
|
||||
const f = await fixture();
|
||||
const { execution } = await f.make();
|
||||
const { manager, strategy } = await attachCounter(execution);
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await execution.enqueueMarketData(quote('one'));
|
||||
f.setTime(start + 5000);
|
||||
await manager.recover();
|
||||
expect(strategy.count).toBe(1);
|
||||
expect(strategy.getPosition('A')).toBe(0);
|
||||
const orders = (await f.pool.query('SELECT payload FROM simulation_orders')).rows;
|
||||
expect(orders[0].payload.report.status).toBe('rejected');
|
||||
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('real SMA indicator checkpoints reproduce an uninterrupted run across process replacement', async () => {
|
||||
const f = await fixture();
|
||||
const smaConfig = {
|
||||
...recoveryConfig,
|
||||
id: 'sma',
|
||||
name: 'sma-crossover',
|
||||
parameters: { initialCapital: 10000 },
|
||||
};
|
||||
const makeManager = async (account: string) => {
|
||||
const runtime = await f.make(account);
|
||||
const manager = makeStrategyManager({
|
||||
execution: runtime.execution,
|
||||
modeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
|
||||
});
|
||||
await manager.initializeStrategies([smaConfig]);
|
||||
cleanup.push(() => manager.shutdown());
|
||||
return { ...runtime, manager };
|
||||
};
|
||||
const bars = Array.from({ length: 45 }, (_, index) => {
|
||||
const price = 100 + Math.sin(index / 3) * 8;
|
||||
return {
|
||||
type: 'bar' as const,
|
||||
eventId: 'bar-' + index,
|
||||
data: {
|
||||
symbol: 'A',
|
||||
timestamp: start + index * 86400000,
|
||||
open: price,
|
||||
high: price + 1,
|
||||
low: price - 1,
|
||||
close: price,
|
||||
volume: 100000,
|
||||
},
|
||||
};
|
||||
});
|
||||
const baseline = await makeManager('baseline');
|
||||
for (const bar of bars) {
|
||||
f.setTime(bar.data.timestamp);
|
||||
await baseline.manager.onMarketData(bar);
|
||||
}
|
||||
f.setTime(start);
|
||||
const interrupted = await makeManager('interrupted');
|
||||
for (const bar of bars.slice(0, 22)) {
|
||||
f.setTime(bar.data.timestamp);
|
||||
await interrupted.manager.onMarketData(bar);
|
||||
}
|
||||
await interrupted.manager.shutdown();
|
||||
const restarted = await makeManager('interrupted');
|
||||
for (const bar of bars.slice(22)) {
|
||||
f.setTime(bar.data.timestamp);
|
||||
await restarted.manager.onMarketData(bar);
|
||||
}
|
||||
const meaningfulState = (manager: StrategyManager) => {
|
||||
const {
|
||||
seenFills: _seenFills,
|
||||
pendingOrders: _pendingOrders,
|
||||
...state
|
||||
} = manager.getStrategy('sma')!.captureCheckpoint() as Record<string, unknown>;
|
||||
return state;
|
||||
};
|
||||
expect(meaningfulState(restarted.manager)).toEqual(meaningfulState(baseline.manager));
|
||||
expect((await restarted.execution.getAccount()).cash).toBe(
|
||||
(await baseline.execution.getAccount()).cash
|
||||
);
|
||||
expect(
|
||||
(await f.pool.query("SELECT * FROM simulation_fills WHERE account_id = 'baseline'")).rows
|
||||
.length
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('uncheckpointed ML paper strategies fail before model startup and migration replay preserves history', async () => {
|
||||
const f = await fixture();
|
||||
const { execution, engine } = await f.make();
|
||||
const manager = makeStrategyManager({
|
||||
execution,
|
||||
modeManager: { getTradingEngine: () => engine } as ModeManager,
|
||||
});
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await expect(
|
||||
manager.initializeStrategies([{ ...recoveryConfig, name: 'ml-enhanced' }])
|
||||
).rejects.toThrow('versioned checkpoint');
|
||||
expect((await f.pool.query('SELECT * FROM simulation_strategy_checkpoints')).rows).toHaveLength(
|
||||
0
|
||||
);
|
||||
const active = await attachCounter(execution);
|
||||
cleanup.push(() => active.manager.shutdown());
|
||||
await active.manager.onMarketData(quote('one'));
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
|
||||
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
||||
});
|
||||
});
|
||||
112
test/setup.js
112
test/setup.js
|
|
@ -1,112 +0,0 @@
|
|||
"use strict";
|
||||
/**
|
||||
* Bun Test Setup File for Stock Bot Trading Platform
|
||||
*
|
||||
* Global test configuration and utilities available across all tests.
|
||||
* This file is executed before each test via bunfig.toml preload.
|
||||
*/
|
||||
// Increase test timeout if needed (already configured in bunfig.toml)
|
||||
// Bun.timeout = 30000;
|
||||
// Store original console methods to allow restoration
|
||||
const originalConsole = global.console;
|
||||
// Mock console methods to reduce noise during tests
|
||||
// These can be restored with testHelpers.restoreConsole()
|
||||
console.log = () => { };
|
||||
console.debug = () => { };
|
||||
console.info = () => { };
|
||||
console.warn = () => { };
|
||||
console.error = () => { };
|
||||
global.testHelpers = {
|
||||
/**
|
||||
* Sleep utility for async tests
|
||||
*/
|
||||
sleep: (ms) => new Promise(resolve => setTimeout(resolve, ms)),
|
||||
/**
|
||||
* Consistent mock timestamp for tests
|
||||
*/
|
||||
mockTimestamp: () => new Date('2024-01-01T12:00:00Z'),
|
||||
/**
|
||||
* Generate test OHLCV data
|
||||
*/
|
||||
generateTestOHLCV: (symbol = 'AAPL', overrides = {}) => ({
|
||||
symbol,
|
||||
open: 150.0,
|
||||
high: 153.0,
|
||||
low: 149.0,
|
||||
close: 152.5,
|
||||
volume: 10000,
|
||||
timestamp: global.testHelpers.mockTimestamp(),
|
||||
...overrides
|
||||
}),
|
||||
/**
|
||||
* Generate test trade data
|
||||
*/
|
||||
generateTestTrade: (symbol = 'AAPL', overrides = {}) => ({
|
||||
symbol,
|
||||
price: 152.5,
|
||||
size: 100,
|
||||
timestamp: global.testHelpers.mockTimestamp(),
|
||||
exchange: 'NASDAQ',
|
||||
conditions: ['@', 'T'],
|
||||
...overrides
|
||||
}),
|
||||
/**
|
||||
* Generate test quote data
|
||||
*/
|
||||
generateTestQuote: (symbol = 'AAPL', overrides = {}) => ({
|
||||
symbol,
|
||||
bidPrice: 152.45,
|
||||
bidSize: 200,
|
||||
askPrice: 152.55,
|
||||
askSize: 150,
|
||||
timestamp: global.testHelpers.mockTimestamp(),
|
||||
...overrides
|
||||
}),
|
||||
/**
|
||||
* Create a mock logger
|
||||
*/
|
||||
mockLogger: () => ({
|
||||
debug: () => { },
|
||||
info: () => { },
|
||||
warn: () => { },
|
||||
error: () => { },
|
||||
critical: () => { },
|
||||
}),
|
||||
/**
|
||||
* Restore console methods
|
||||
*/
|
||||
restoreConsole: () => {
|
||||
global.console = originalConsole;
|
||||
}
|
||||
};
|
||||
// Set up spyOn utilities
|
||||
// Similar to jest.spyOn but using Bun's built-in spy functionality
|
||||
// This makes it easier to migrate from Jest
|
||||
global.spyOn = function (object, method) {
|
||||
const original = object[method];
|
||||
const mock = function (...args) {
|
||||
mock.mock.calls.push(args);
|
||||
return mock.mockImplementation ? mock.mockImplementation(...args) : original.apply(object, args);
|
||||
};
|
||||
mock.mock = { calls: [] };
|
||||
mock.mockClear = () => { mock.mock.calls = []; return mock; };
|
||||
mock.mockReset = () => {
|
||||
mock.mock.calls = [];
|
||||
mock.mockImplementation = null;
|
||||
return mock;
|
||||
};
|
||||
mock.mockImplementation = null;
|
||||
mock.mockReturnValue = (value) => {
|
||||
mock.mockImplementation = () => value;
|
||||
return mock;
|
||||
};
|
||||
mock.mockResolvedValue = (value) => {
|
||||
return mock.mockReturnValue(Promise.resolve(value));
|
||||
};
|
||||
mock.mockRejectedValue = (value) => {
|
||||
return mock.mockReturnValue(Promise.reject(value));
|
||||
};
|
||||
object[method] = mock;
|
||||
return mock;
|
||||
};
|
||||
//# sourceMappingURL=setup.js.map
|
||||
|
|
@ -197,6 +197,54 @@ describe('MongoDBClient read-only enforcement', () => {
|
|||
).rejects.toThrow(/aggregation stage "\$merge" is forbidden/);
|
||||
});
|
||||
|
||||
test('wraps getDatabase/getCollection/collection in fail-closed read-only proxies', () => {
|
||||
const fakeCollection = {
|
||||
collectionName: 'qmSymbols',
|
||||
find: () => ({ toArray: async () => [{ symbol: 'AAPL' }] }),
|
||||
aggregate: () => ({ toArray: async () => [] }),
|
||||
insertOne: async () => ({}),
|
||||
updateOne: async () => ({}),
|
||||
deleteOne: async () => ({}),
|
||||
bulkWrite: async () => ({}),
|
||||
drop: async () => true,
|
||||
};
|
||||
const fakeDb = {
|
||||
databaseName: 'stock',
|
||||
collection: () => fakeCollection,
|
||||
listCollections: () => ({ toArray: async () => [] }),
|
||||
createCollection: async () => ({}),
|
||||
dropCollection: async () => true,
|
||||
dropDatabase: async () => true,
|
||||
command: async () => ({}),
|
||||
};
|
||||
const attached = new MongoDBClient(
|
||||
{ host: 'localhost', port: 27017, database: 'stock', readOnly: true },
|
||||
logger
|
||||
);
|
||||
Object.assign(attached, {
|
||||
client: { db: () => fakeDb },
|
||||
db: fakeDb,
|
||||
isConnected: true,
|
||||
});
|
||||
|
||||
// Safe read accessors succeed
|
||||
expect(attached.getDatabase().databaseName).toBe('stock');
|
||||
expect(typeof attached.getDatabase().collection('qmSymbols').find).toBe('function');
|
||||
|
||||
// Escape-hatch mutations on getDatabase(), getDb(), database, getCollection(), collection() fail closed
|
||||
expect(() => attached.getDatabase().createCollection('evil')).toThrow(/read-only mode/);
|
||||
expect(() => attached.getDb().dropDatabase()).toThrow(/read-only mode/);
|
||||
expect(() => attached.database!.command({ dropDatabase: 1 })).toThrow(/read-only mode/);
|
||||
expect(() => attached.getCollection('qmSymbols').insertOne({ a: 1 })).toThrow(/read-only mode/);
|
||||
expect(() => attached.collection('qmSymbols').bulkWrite([])).toThrow(/read-only mode/);
|
||||
expect(() => attached.getDatabase().collection('qmSymbols').deleteOne({})).toThrow(
|
||||
/read-only mode/
|
||||
);
|
||||
expect(() =>
|
||||
attached.getCollection('qmSymbols').aggregate([{ $out: 'hijack' }])
|
||||
).toThrow(/aggregation stage "\$out" is forbidden/);
|
||||
});
|
||||
|
||||
test('ServiceContainerBuilder resolves readUri and read-only mode when mongoReadOnly=true', async () => {
|
||||
const cfg = makeConfig({ environment: 'development' });
|
||||
const { container, shutdown } = await new ServiceContainerBuilder()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue