Compare commits
4 commits
6d357af983
...
c5b93eb8fd
| Author | SHA1 | Date | |
|---|---|---|---|
| c5b93eb8fd | |||
| fe00ecd0e2 | |||
| 43ffb547be | |||
| ee670a3bd1 |
25 changed files with 1406 additions and 97 deletions
|
|
@ -6,6 +6,7 @@ use chrono::{DateTime, Utc};
|
|||
use napi::bindgen_prelude::*;
|
||||
use napi_derive::napi;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
|
|
@ -213,28 +214,47 @@ impl BacktestEngine {
|
|||
serde_json::to_string(&result).map_err(|e| Error::from_reason(e.to_string()))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn load_market_data(&self, data: Vec<napi::JsObject>) -> Result<()> {
|
||||
// Convert JS objects to MarketData
|
||||
let market_data: Vec<MarketUpdate> = data
|
||||
.into_iter()
|
||||
.filter_map(|obj| parse_market_data(obj).ok())
|
||||
.collect();
|
||||
|
||||
// Load data into the historical data source
|
||||
if let Some(engine) = self.inner.lock().as_ref() {
|
||||
// Access the market data source through the engine
|
||||
let mut data_source = engine.market_data_source.write();
|
||||
if let Some(historical_source) = data_source
|
||||
.as_any_mut()
|
||||
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>(
|
||||
) {
|
||||
historical_source.load_data(market_data);
|
||||
} else {
|
||||
#[napi(ts_args_type = "data: Array<object>")]
|
||||
pub fn load_market_data(&self, data: Vec<napi::JsUnknown>) -> Result<()> {
|
||||
// Validate the complete replacement before touching the historical source.
|
||||
let mut market_data: Vec<MarketUpdate> = Vec::with_capacity(data.len());
|
||||
let mut previous_time = None;
|
||||
let mut identities_at_time = HashMap::new();
|
||||
for (index, obj) in data.into_iter().enumerate() {
|
||||
let row_error =
|
||||
|reason| Error::from_reason(format!("Market data row {index}: {reason}"));
|
||||
let update = napi::JsObject::try_from(obj)
|
||||
.and_then(parse_market_data)
|
||||
.map_err(|error| row_error(error.reason))?;
|
||||
if previous_time.is_some_and(|previous| update.timestamp < previous) {
|
||||
return Err(row_error("Timestamps must be nondecreasing".to_string()));
|
||||
}
|
||||
} else {
|
||||
if previous_time != Some(update.timestamp) {
|
||||
identities_at_time.clear();
|
||||
}
|
||||
// Identical duplicates also replay a strategy twice, so reject them too.
|
||||
if let Some(first_index) = identities_at_time.insert(update.symbol.clone(), index) {
|
||||
return Err(row_error(format!(
|
||||
"Duplicate bar identity {} at {}ms (first at row {})",
|
||||
update.symbol,
|
||||
update.timestamp.timestamp_millis(),
|
||||
first_index
|
||||
)));
|
||||
}
|
||||
previous_time = Some(update.timestamp);
|
||||
market_data.push(update);
|
||||
}
|
||||
|
||||
let guard = self.inner.lock();
|
||||
let engine = guard
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
|
||||
let mut data_source = engine.market_data_source.write();
|
||||
let historical_source = data_source
|
||||
.as_any_mut()
|
||||
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>()
|
||||
.ok_or_else(|| Error::from_reason("Historical market data source unavailable"))?;
|
||||
historical_source.load_data(market_data);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -269,26 +289,65 @@ fn parse_backtest_config(obj: napi::JsObject) -> Result<BacktestConfig> {
|
|||
|
||||
fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
|
||||
let symbol: String = obj.get_named_property("symbol")?;
|
||||
let timestamp: i64 = obj.get_named_property("timestamp")?;
|
||||
if symbol.trim().is_empty() {
|
||||
return Err(Error::from_reason("Symbol must be nonempty"));
|
||||
}
|
||||
let timestamp: f64 = obj.get_named_property("timestamp")?;
|
||||
// Reading as i64 first would silently truncate fractional JS timestamps.
|
||||
if !timestamp.is_finite()
|
||||
|| timestamp.fract() != 0.0
|
||||
|| timestamp.abs() > 9_007_199_254_740_991.0
|
||||
{
|
||||
return Err(Error::from_reason(
|
||||
"Timestamp must be a safe integer epoch millisecond",
|
||||
));
|
||||
}
|
||||
let timestamp = DateTime::<Utc>::from_timestamp_millis(timestamp as i64)
|
||||
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?;
|
||||
let data_type: String = obj.get_named_property("type")?;
|
||||
|
||||
let data = if data_type == "bar" {
|
||||
crate::MarketDataType::Bar(crate::Bar {
|
||||
open: obj.get_named_property("open")?,
|
||||
high: obj.get_named_property("high")?,
|
||||
low: obj.get_named_property("low")?,
|
||||
close: obj.get_named_property("close")?,
|
||||
volume: obj.get_named_property("volume")?,
|
||||
vwap: obj.get_named_property("vwap").ok(),
|
||||
})
|
||||
} else {
|
||||
return Err(Error::from_reason("Unsupported market data type"));
|
||||
if data_type != "bar" {
|
||||
return Err(Error::from_reason(format!(
|
||||
"Unsupported market data type: {data_type}"
|
||||
)));
|
||||
}
|
||||
let bar = crate::Bar {
|
||||
open: obj.get_named_property("open")?,
|
||||
high: obj.get_named_property("high")?,
|
||||
low: obj.get_named_property("low")?,
|
||||
close: obj.get_named_property("close")?,
|
||||
volume: obj.get_named_property("volume")?,
|
||||
vwap: obj.get_named_property("vwap")?,
|
||||
};
|
||||
for (field, price) in [
|
||||
("open", bar.open),
|
||||
("high", bar.high),
|
||||
("low", bar.low),
|
||||
("close", bar.close),
|
||||
] {
|
||||
if !price.is_finite() || price <= 0.0 {
|
||||
return Err(Error::from_reason(format!(
|
||||
"{field} must be positive and finite"
|
||||
)));
|
||||
}
|
||||
}
|
||||
if bar.high < bar.open.max(bar.close) || bar.low > bar.open.min(bar.close) {
|
||||
return Err(Error::from_reason("Invalid OHLC range"));
|
||||
}
|
||||
if !bar.volume.is_finite() || bar.volume < 0.0 {
|
||||
return Err(Error::from_reason("Volume must be nonnegative and finite"));
|
||||
}
|
||||
if bar
|
||||
.vwap
|
||||
.is_some_and(|price| !price.is_finite() || price <= 0.0)
|
||||
{
|
||||
return Err(Error::from_reason(
|
||||
"VWAP must be positive and finite when provided",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(crate::MarketUpdate {
|
||||
symbol,
|
||||
timestamp: DateTime::<Utc>::from_timestamp(timestamp / 1000, 0)
|
||||
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?,
|
||||
data,
|
||||
timestamp,
|
||||
data: crate::MarketDataType::Bar(bar),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,12 +18,29 @@ import { StrategyManager } from './strategies/StrategyManager';
|
|||
import type { StrategyRegistry } from './strategies/StrategyRegistry';
|
||||
import type { OrchestratorServices as IServiceContainer } from './types';
|
||||
|
||||
export type OrchestratorRole = 'paper' | 'research-only';
|
||||
|
||||
export function assertSupportedComposition(role: OrchestratorRole, useRustEngine: boolean): void {
|
||||
if (role !== 'paper' && role !== 'research-only') {
|
||||
throw new Error('Unsupported runtime role: expected paper or research-only');
|
||||
}
|
||||
if (typeof useRustEngine !== 'boolean') {
|
||||
throw new Error('Runtime useRustEngine option must be a boolean');
|
||||
}
|
||||
if (role !== 'research-only' && !useRustEngine) {
|
||||
throw new Error(
|
||||
'Unsupported runtime combination: TypeScript backtests require a research-only composition; paper requires the isolated native engine'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register orchestrator-specific services in the DI container
|
||||
*/
|
||||
export async function registerOrchestratorServices(
|
||||
container: AwilixContainer<ServiceDefinitions>,
|
||||
options: {
|
||||
role?: OrchestratorRole;
|
||||
initializeMode?: boolean;
|
||||
useRustEngine?: boolean;
|
||||
allowSyntheticData?: boolean;
|
||||
|
|
@ -32,6 +49,11 @@ export async function registerOrchestratorServices(
|
|||
strategyRegistry?: StrategyRegistry;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const role = options.role === undefined ? 'paper' : options.role;
|
||||
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
|
||||
assertSupportedComposition(role, useRustEngine);
|
||||
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
|
||||
|
||||
// Create a service adapter that provides the expected interface
|
||||
const services = container.resolve('serviceContainer') as IServiceContainer;
|
||||
const custom = services.custom ?? {};
|
||||
|
|
@ -55,7 +77,7 @@ export async function registerOrchestratorServices(
|
|||
storage: storageService,
|
||||
drainStrategies: () => strategyManager.drain(),
|
||||
});
|
||||
const executionService = new ExecutionService(services, storageService);
|
||||
const executionService = new ExecutionService(services, storageService, { allowedMode });
|
||||
const analyticsService = new AnalyticsService(services);
|
||||
const registry = options.strategyRegistry ?? createBuiltinStrategyRegistry();
|
||||
const strategyManager: StrategyManager = new StrategyManager({
|
||||
|
|
@ -65,13 +87,14 @@ export async function registerOrchestratorServices(
|
|||
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
|
||||
});
|
||||
const modeManager: ModeManager = new ModeManager({
|
||||
allowedMode,
|
||||
logger: services.logger,
|
||||
marketData: marketDataService,
|
||||
execution: executionService,
|
||||
storage: storageService,
|
||||
strategies: strategyManager,
|
||||
});
|
||||
const backtestEngine = options.useRustEngine
|
||||
const backtestEngine = useRustEngine
|
||||
? new RustBacktestAdapter(
|
||||
{ logger: services.logger, storage: storageService },
|
||||
{
|
||||
|
|
@ -93,12 +116,12 @@ export async function registerOrchestratorServices(
|
|||
);
|
||||
const backtestRunner = new BacktestRunner({
|
||||
engine: backtestEngine,
|
||||
engineName: options.useRustEngine ? 'native' : 'typescript',
|
||||
engineName: useRustEngine ? 'native' : 'typescript',
|
||||
repository: services.postgres
|
||||
? new PostgresBacktestRunRepository(services.postgres)
|
||||
: new UnavailableBacktestRunRepository(),
|
||||
logger: services.logger,
|
||||
prepare: options.useRustEngine ? undefined : config => modeManager.initializeMode(config),
|
||||
prepare: useRustEngine ? undefined : config => modeManager.initializeMode(config),
|
||||
});
|
||||
|
||||
// Store custom services
|
||||
|
|
@ -150,7 +173,7 @@ export async function registerOrchestratorServices(
|
|||
strategyManager.setupEventListeners();
|
||||
|
||||
// Initialize mode manager with default paper trading mode
|
||||
if (options.initializeMode !== false) {
|
||||
if (role === 'paper' && options.initializeMode !== false) {
|
||||
await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 });
|
||||
}
|
||||
// Start job consumption only after the shared graph and initial mode are ready.
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ export class ModeManager extends EventEmitter {
|
|||
private isInitialized = false;
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
allowedMode?: 'paper' | 'backtest';
|
||||
logger: Pick<Logger, 'info'>;
|
||||
marketData: Pick<MarketDataService, 'initialize' | 'shutdown'>;
|
||||
execution: Pick<ExecutionService, 'initialize' | 'shutdown'>;
|
||||
|
|
@ -37,6 +38,11 @@ export class ModeManager extends EventEmitter {
|
|||
if (config.mode === 'live') {
|
||||
throw new Error('Live trading is disabled: no real broker adapter exists');
|
||||
}
|
||||
if (this.dependencies.allowedMode && config.mode !== this.dependencies.allowedMode) {
|
||||
throw new Error(
|
||||
`Runtime composition only permits ${this.dependencies.allowedMode} mode; cannot initialize ${config.mode}`
|
||||
);
|
||||
}
|
||||
// Validate config based on mode
|
||||
switch (config.mode) {
|
||||
case 'backtest':
|
||||
|
|
|
|||
|
|
@ -60,7 +60,11 @@ export class ExecutionService extends EventEmitter {
|
|||
constructor(
|
||||
private readonly container: OrchestratorServices,
|
||||
_storage: StorageService,
|
||||
private readonly options: { repository?: ExecutionRepository; clock?: () => number } = {}
|
||||
private readonly options: {
|
||||
repository?: ExecutionRepository;
|
||||
clock?: () => number;
|
||||
allowedMode?: 'paper' | 'backtest';
|
||||
} = {}
|
||||
) {
|
||||
super();
|
||||
this.simulation = new SimulationExecution({
|
||||
|
|
@ -93,6 +97,11 @@ export class ExecutionService extends EventEmitter {
|
|||
'Live trading is disabled: no real broker adapter exists'
|
||||
);
|
||||
}
|
||||
if (this.options.allowedMode && config.mode !== this.options.allowedMode) {
|
||||
throw new UnsupportedExecutionError(
|
||||
`Runtime composition only permits ${this.options.allowedMode} mode; cannot initialize ${config.mode}`
|
||||
);
|
||||
}
|
||||
await this.tail;
|
||||
this.closing = false;
|
||||
this.mode = undefined;
|
||||
|
|
|
|||
|
|
@ -1,10 +1,22 @@
|
|||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { registerOrchestratorServices } from './container';
|
||||
import {
|
||||
assertSupportedComposition,
|
||||
registerOrchestratorServices,
|
||||
type OrchestratorRole,
|
||||
} from './container';
|
||||
import type { OrchestratorServices } from './types';
|
||||
|
||||
/** Use the shared builder for connection setup and adapter ownership. */
|
||||
export async function createContainer(config: StockAppConfig) {
|
||||
export async function createContainer(
|
||||
config: StockAppConfig,
|
||||
options: { role?: OrchestratorRole } = {}
|
||||
) {
|
||||
const role = options.role === undefined ? 'paper' : options.role;
|
||||
const configuredEngine = config.services?.orchestrator?.backtesting?.useRustEngine;
|
||||
const useRustEngine = configuredEngine === undefined ? true : configuredEngine;
|
||||
// Fail before opening connections as well as before registering runtime services.
|
||||
assertSupportedComposition(role, useRustEngine);
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withConfig(config)
|
||||
.withOptions({
|
||||
|
|
@ -18,7 +30,8 @@ export async function createContainer(config: StockAppConfig) {
|
|||
})
|
||||
.build();
|
||||
await registerOrchestratorServices(container, {
|
||||
useRustEngine: config.services?.orchestrator?.backtesting?.useRustEngine ?? true,
|
||||
role,
|
||||
useRustEngine,
|
||||
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
|
||||
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
|
||||
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { BACKTEST_DEFAULTS } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, BacktestRunTrade } from '@stock-bot/types';
|
||||
import type { BacktestRunProvenance, BacktestRunResult, BacktestRunTrade } from '@stock-bot/types';
|
||||
|
||||
type StoredTrade = Omit<BacktestRunTrade, 'kind' | 'timestamp' | 'price'> &
|
||||
Partial<Pick<BacktestRunTrade, 'kind' | 'timestamp' | 'price'>>;
|
||||
|
|
@ -32,11 +32,65 @@ export interface StoredBacktestResult {
|
|||
};
|
||||
}
|
||||
|
||||
/** Read-only compatibility conversion. Stored rows and metric units are never rewritten. */
|
||||
function resultProvenance(row: StoredBacktestResult): BacktestRunProvenance {
|
||||
const limitations = [
|
||||
{
|
||||
code: 'unversioned-execution',
|
||||
message:
|
||||
'Engine build, financial semantics version and strategy artifact were not recorded. Current terminal-equity and fee-funding fixes do not certify this saved run.',
|
||||
},
|
||||
{
|
||||
code: 'same-bar-execution',
|
||||
message:
|
||||
'Existing simulators can observe a completed bar and fill at its close. These results do not establish next-event execution or freedom from look-ahead bias.',
|
||||
},
|
||||
{
|
||||
code: 'funding-policy',
|
||||
message:
|
||||
'Native and TypeScript engines have different funding checks; short and reducing-order financing is not a canonical cash or margin model.',
|
||||
},
|
||||
{
|
||||
code: 'strategy-attribution',
|
||||
message:
|
||||
'Positions and cost basis are aggregated by symbol. Shared-asset strategy ownership and P&L attribution are not independently reconciled.',
|
||||
},
|
||||
];
|
||||
if (!row.configuration) {
|
||||
limitations.push({
|
||||
code: 'missing-configuration',
|
||||
message:
|
||||
'No frozen run configuration was saved. The compatibility config may use the current mutable definition and defaults; it is not evidence of historical inputs.',
|
||||
});
|
||||
}
|
||||
if (row.engine === 'typescript') {
|
||||
limitations.push({
|
||||
code: 'exposure-convention',
|
||||
message:
|
||||
'TypeScript exposure sums closed-trade durations, so overlapping positions can be counted twice and open positions omitted. It is not portfolio exposure time.',
|
||||
});
|
||||
} else {
|
||||
limitations.push({
|
||||
code: 'unavailable-risk-metrics',
|
||||
message:
|
||||
'Native exposure and VaR include placeholders, which are shown as unavailable. For unknown engines, zero exposure cannot be distinguished from a placeholder. Native daily-return grouping and Sharpe/Sortino conventions need correction; stored computed statistics are retained but are not comparable across engines. Unknown-engine historical metric conventions cannot be verified.',
|
||||
});
|
||||
}
|
||||
return {
|
||||
configurationSource: row.configuration ? 'stored-snapshot' : 'legacy-definition-fallback',
|
||||
datasetHash: row.configuration?.dataset?.hash ?? null,
|
||||
// Neither the stored engine name nor a mutable strategy name identifies a build/artifact.
|
||||
engineVersion: null,
|
||||
economicsVersion: null,
|
||||
strategyArtifactHash: null,
|
||||
limitations,
|
||||
};
|
||||
}
|
||||
|
||||
/** Read-only compatibility conversion. Stored rows are never rewritten. */
|
||||
export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunResult {
|
||||
const legacy = !row.configuration;
|
||||
const metrics = { ...row.metrics };
|
||||
const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? 0 };
|
||||
const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? null };
|
||||
const trades = row.trades.map(trade => {
|
||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||
const price = trade.price ?? trade.entryPrice;
|
||||
|
|
@ -63,7 +117,9 @@ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunR
|
|||
metrics.totalTrades = trades.length;
|
||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
analytics.exposureTime /= 100;
|
||||
if (analytics.exposureTime !== null) {
|
||||
analytics.exposureTime /= 100;
|
||||
}
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
|
|
@ -78,12 +134,21 @@ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunR
|
|||
);
|
||||
}
|
||||
}
|
||||
if (row.engine !== 'typescript' && analytics.exposureTime === 0) {
|
||||
// Native writes placeholder exposure. Unknown-engine historical zero cannot be
|
||||
// distinguished from that placeholder; retain nonzero stored legacy evidence.
|
||||
analytics.exposureTime = null;
|
||||
}
|
||||
if (row.engine !== 'typescript' && analytics.riskMetrics?.value_at_risk_95 === 0) {
|
||||
analytics.riskMetrics = { ...analytics.riskMetrics, value_at_risk_95: null };
|
||||
}
|
||||
return {
|
||||
runId: row.run_id,
|
||||
backtestId: row.backtest_id,
|
||||
status: row.run_status ?? 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
engine: row.engine ?? 'legacy',
|
||||
provenance: resultProvenance(row),
|
||||
...(legacy ? { legacy: true } : {}),
|
||||
config: row.configuration ?? {
|
||||
parameters: row.backtest_config ?? {},
|
||||
|
|
|
|||
|
|
@ -331,7 +331,8 @@ export function BacktestDetailPageV2() {
|
|||
)}
|
||||
</h1>
|
||||
<p className="text-xs text-text-secondary">
|
||||
{backtest?.strategy || ''} • {backtest?.symbols.join(', ') || ''}
|
||||
Current definition: {backtest?.strategy || ''} •{' '}
|
||||
{backtest?.symbols.join(', ') || ''}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import type { Position } from '../types/backtest.types';
|
|||
import { BacktestChart } from './BacktestChart';
|
||||
import { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
|
||||
import { PositionsSummary } from './PositionsSummary';
|
||||
import { ResultProvenance } from './ResultProvenance';
|
||||
|
||||
interface BacktestPlaybackProps {
|
||||
result: RunResult | null;
|
||||
|
|
@ -68,6 +69,10 @@ export const BacktestPlayback = memo(function BacktestPlayback({
|
|||
</ErrorBoundary>
|
||||
</div>
|
||||
|
||||
<div className="flex-shrink-0 max-h-64 overflow-y-auto">
|
||||
<ResultProvenance result={result} />
|
||||
</div>
|
||||
|
||||
{/* Performance Metrics and Positions - Fixed height section */}
|
||||
<div className="flex-shrink-0 grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<CompactPerformanceMetrics result={result} isLoading={isLoading} />
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ interface ExtendedMetrics {
|
|||
maxDrawdown?: number | null;
|
||||
winRate?: number | null;
|
||||
totalProfit?: number | null;
|
||||
totalPnl?: number | null;
|
||||
profitFactor?: number | null;
|
||||
totalTrades?: number | null;
|
||||
avgWin?: number | null;
|
||||
|
|
@ -55,10 +56,13 @@ export function CompactPerformanceMetrics({ result, isLoading }: CompactPerforma
|
|||
...metrics,
|
||||
};
|
||||
|
||||
// Calculate totalProfit if not provided
|
||||
// Never infer a historical cash amount from a mutable legacy definition's capital.
|
||||
const totalProfit =
|
||||
allMetrics.totalProfit ??
|
||||
(typeof allMetrics.totalReturn === 'number' && typeof result.config?.initialCapital === 'number'
|
||||
allMetrics.totalPnl ??
|
||||
(result.provenance?.configurationSource === 'stored-snapshot' &&
|
||||
typeof allMetrics.totalReturn === 'number' &&
|
||||
typeof result.config?.initialCapital === 'number'
|
||||
? allMetrics.totalReturn * result.config.initialCapital
|
||||
: undefined);
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,89 @@
|
|||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
|
||||
/** Display saved evidence only; the mutable definition remains a separate settings view. */
|
||||
export function ResultProvenance({ result }: { result: BacktestRunResult }) {
|
||||
const provenance = result.provenance;
|
||||
const config = provenance?.configurationSource === 'stored-snapshot' ? result.config : null;
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-label="Result provenance and limitations"
|
||||
className="bg-surface-secondary border border-warning/40 rounded-lg p-3 text-sm space-y-2"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h3 className="font-medium text-text-primary">Saved run evidence</h3>
|
||||
<span className="text-xs text-warning">Research only · Unverified economics</span>
|
||||
</div>
|
||||
<p className="text-text-secondary">
|
||||
Completion is not financial validation. Do not use this result alone as evidence for
|
||||
promotion to paper or live trading.
|
||||
</p>
|
||||
<p className="text-text-secondary">
|
||||
Known limitations: same-bar execution, funding constraints, strategy attribution and metric
|
||||
conventions.
|
||||
</p>
|
||||
<details>
|
||||
<summary className="cursor-pointer text-text-primary">
|
||||
Configuration, provenance and simulation limitations
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3">
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-text-secondary break-words">
|
||||
<div>
|
||||
<dt>Run</dt>
|
||||
<dd>{result.runId}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Recorded engine</dt>
|
||||
<dd>{result.engine === 'legacy' ? 'Unknown' : result.engine}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Engine build</dt>
|
||||
<dd>{provenance?.engineVersion ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Financial semantics version</dt>
|
||||
<dd>{provenance?.economicsVersion ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Strategy artifact</dt>
|
||||
<dd>{provenance?.strategyArtifactHash ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Dataset hash</dt>
|
||||
<dd>{provenance?.datasetHash ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{config ? (
|
||||
<div>
|
||||
<h4 className="font-medium text-text-primary">Stored run configuration</h4>
|
||||
<p className="text-text-secondary">
|
||||
Exact saved snapshot, including parameters and data policy when recorded. This is
|
||||
not the current editable definition.
|
||||
</p>
|
||||
<pre className="mt-2 overflow-auto max-h-64 text-xs text-text-secondary">
|
||||
{JSON.stringify(config, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-text-secondary">
|
||||
Stored run configuration: Unknown. Current strategy settings and defaults are not
|
||||
historical evidence.
|
||||
</p>
|
||||
)}
|
||||
{provenance ? (
|
||||
<ul className="list-disc pl-5 space-y-1 text-text-secondary">
|
||||
{provenance.limitations.map(limitation => (
|
||||
<li key={limitation.code}>{limitation.message}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-text-secondary">
|
||||
Provenance metadata is unavailable from this API. Execution timing, funding, strategy
|
||||
attribution and metric conventions are unverified.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -78,7 +78,7 @@ export interface BacktestResult {
|
|||
positions: Position[];
|
||||
trades: Trade[];
|
||||
performanceData: PerformanceDataPoint[];
|
||||
analytics?: { exposureTime?: number };
|
||||
analytics?: { exposureTime?: number | null };
|
||||
}
|
||||
|
||||
export interface OrderBookLevel {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# First development wave: four independent assignments
|
||||
|
||||
**First wave completed and committed on 2026-10-22.** The owner authorized implementation with “make a commit and start,” then authorized the implementation and handoff commits with “do all comits.” The canonical manifest records this completed scope; later tasks, pushes, PRs and trading operations remain unauthorized. The assignments below are retained for traceability.
|
||||
**First wave completed and committed on 2026-10-22.** The owner authorized implementation with “make a commit and start,” then authorized the implementation and handoff commits with “do all comits.” The assignments and execution record below are retained for traceability. Subsequent wave authorization is tracked in the canonical manifest and ROADMAP; this historical record does not grant it.
|
||||
|
||||
Choose **C01, C03, C04, W01**. They have no code/ADR prerequisites beyond global execution approval and no shared authored source files. Recommend three implementers plus one coordinator/read-only reviewer; start C01/C03/W01 and rotate C04 into the first free slot. If runtime cleanup is more urgent than the interim funding fix, start C04 before C03. This is capacity management, not a dependency.
|
||||
|
||||
|
|
@ -299,4 +299,4 @@ bun test test/integration/fee-funding.test.ts test/integration/order-execution.t
|
|||
|
||||
The native addon was rebuilt from the integrated source; its path/hash are recorded in the manifest. Native subprocess builds/IPC and disposable database access required sandbox escalation. Existing Rust warnings and frontend build warnings remain; no unrelated cleanup was included. W01 adds pinned `happy-dom@21.0.4` for 18 React interaction tests under Bun, not a second test runner or a browser E2E claim.
|
||||
|
||||
Limits: this wave does not fix same-bar look-ahead execution, establish canonical Rust financial authority, change legacy short/reducing-order funding semantics, or satisfy W04's real-browser release gate. ADR-002/003/007 remain approval-gated. Worktrees are retained for handoff; temporary PostgreSQL/Redis fixture containers were removed. C06/W02 are now ready but have not been authorized or started.
|
||||
Limits: this wave does not fix same-bar look-ahead execution, establish canonical Rust financial authority, change legacy short/reducing-order funding semantics, or satisfy W04's real-browser release gate. ADR-002/003/007 remain approval-gated. Worktrees are retained for handoff; temporary PostgreSQL/Redis fixture containers were removed. At this wave's completion C06/W02 became ready; their subsequent authorization/status is recorded in the canonical manifest.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
# Revised development roadmap
|
||||
|
||||
Baseline `b7aeca4` · reviewed 2026-10-22 · **First wave completed and committed; see manifest execution_scope**
|
||||
Baseline `b7aeca4` · reviewed 2026-10-22 · **Second wave committed; O01/P01 continuation authorized; see manifest execution_scope**
|
||||
|
||||
Authorization update: the owner requested a planning commit and implementation start, then authorized all pending commits. C01/C03/C04/W01 are completed, reviewed, validated and committed. Later tasks and economic/timing/trust-model decisions remain gated. Historical review statements describe the planning phase, not current authorization. No push, PR or trading operation is authorized.
|
||||
Authorization update: the first and second waves are independently reviewed, validated and committed. The owner's “do all the commits and continue” authorizes the second-wave closeout and continuation with next-ready O01/P01. Other tasks and economic/timing/trust-model decisions remain gated. Third-wave implementation commits, pushes, PRs and trading operations are not authorized.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
|
|
@ -81,7 +81,27 @@ Completed wave; the table records its original rationale. Exact prompts, paths,
|
|||
|
||||
Recommend **3 simultaneous implementers**, reserving one slot for coordination/independent review. Start C01 + C03 + W01; rotate C04 into the first freed slot, or start C04 first if runtime containment is the immediate operational need. These four have no mutual code dependencies and disjoint writable files. Four concurrent implementers are technically possible but not recommended without separate review capacity.
|
||||
|
||||
Next-ready work: C02, C06, W02, P01 and O01; execution still requires owner approval. F01/D01 require their ADR approvals as well. W02 follows W01 because they edit the same detail page, not because it requires the new engine.
|
||||
Next wave: O01 and P01 are authorized. F01/D01 still require their ADR approvals. W04 remains blocked on W03/O01; subsequent work is not included in this execution scope.
|
||||
|
||||
## Second-wave handoff — 2026-10-22
|
||||
|
||||
All three tasks are `done` / `validated_committed` following owner approval: C02 `ee670a3`, C06 `43ffb54`, W02 `fe00ecd`. Worktrees are retained under `/tmp/stock-bot-wave2.M9vHDK/`.
|
||||
|
||||
| Task | Implemented and verified |
|
||||
| --- | --- |
|
||||
| C02 | Whole-load native validation preserves previously admitted data on any invalid row. Indexed errors cover malformed rows, OHLCV/VWAP, timestamps and unsupported types. 1001ms/1999ms remain distinct. Identical/conflicting duplicates and decreasing timestamps now reject explicitly; optional VWAP and zero volume remain accepted. |
|
||||
| C06 | Default paper composition uses native research. Legacy TS requires explicit `role: 'research-only'`; startup and both exposed mode initializers reject cross-role activation before effects. Real paper account/ledger/checkpoint hashes and lifecycle stay unchanged through native success/cancel/failure jobs, and the paper feed continues afterward. No second execution framework was added. |
|
||||
| W02 | Saved configuration and dataset evidence are distinguished from mutable legacy display fallbacks. Missing artifact/build versions stay unknown; known metric placeholders are unavailable while measured TS zeros remain visible. Limitations appear beside performance, and mutable legacy capital cannot fabricate cash profit. No stored results or financial calculations were rewritten. |
|
||||
|
||||
Combined integration gates:
|
||||
|
||||
- `CARGO_BUILD_JOBS=2 bun run check`: passed all gates; 54 tooling, 43 utility, 35 calculation, 293 integration and 37 Rust tests, with no failures. Build, typecheck, contracts, lint and secret audit passed. The 47 native bridge cases are included in integration, not an additional count.
|
||||
- `bun run test:postgres` against disposable `stock_bot_safety` PostgreSQL and Redis DB15: 47 passed, 267 assertions. Includes two real-ledger research-isolation regressions. Temporary fixture containers were removed after validation; development databases/services were untouched.
|
||||
- `git diff --check`: passed. All 21 authored implementation/test files match reviewed worktrees; the rebuilt integration addon hash is in the manifest.
|
||||
|
||||
Native subprocess builds/IPC and fixture networking required sandbox escalation. Existing Rust/frontend build warnings remain. Explicit linting of the old W01 test harness still reports its unchanged test-only curly findings; the repository lint gate and new scoped code checks pass. No real-browser E2E coverage is claimed here.
|
||||
|
||||
Limits: composition guards are not an untrusted-code sandbox; same-bar execution, canonical Rust accounting and owner-aware funding remain future tasks. ADR-002/003/004 still gate F01, and ADR-007 gates AI isolation. No push, PR or trading operation occurred. Subsequent O01/P01 work is tracked separately in the manifest.
|
||||
|
||||
## Deferred and rejected
|
||||
|
||||
|
|
@ -97,4 +117,4 @@ Rejected: competing TS/web simulators, wholesale Rust rewrite, hand-written deci
|
|||
|
||||
Only [manifest.json](backlog/manifest.json) owns status/assignment/dependencies. [Task files](backlog/README.md) own scope/acceptance. Read the reusable [implementation](agents/implementation.md), [review](agents/review.md), [integration](agents/integration.md), [planning](agents/planning.md) briefs and [quality gates](QUALITY-GATES.md).
|
||||
|
||||
Approval of planning artifacts is not permission to commit, push or create PRs. No application changes, runtime benchmarks or application-test pass claims are made by this revision.
|
||||
Approval of planning artifacts is not permission to commit, push or create PRs. Historical planning-only statements refer to the original audit; later execution records and the canonical manifest identify actual implementation, authorization and validation evidence.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First wave completed and committed; consult manifest execution_scope.** Start with [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). Other tasks and unresolved policies remain gated.
|
||||
**First and second waves committed; continuation with O01/P01 authorized.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). Other tasks and unresolved policies remain gated.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -19,11 +19,11 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [C01 Correct native terminal valuation](tasks/C01.md) | P0 / done | None | — | Rust financial correctness / S |
|
||||
| [C02 Reject malformed native data and preserve milliseconds](tasks/C02.md) | P1 / ready | None | — | Rust/NAPI boundary / S |
|
||||
| [C02 Reject malformed native data and preserve milliseconds](tasks/C02.md) | P1 / done | None | — | Rust/NAPI boundary / S |
|
||||
| [C03 Close the existing TypeScript fee-funding hole](tasks/C03.md) | P0 / done | None | — | Trading infrastructure implementation / M |
|
||||
| [C04 Make partial runtime initialization recoverable](tasks/C04.md) | P1 / done | None | — | Trading infrastructure implementation / S |
|
||||
| [C05 Create economic regression fixtures independent of implementations](tasks/C05.md) | P0 / merged → F01 | None | — | Quantitative correctness/test engineering / M |
|
||||
| [C06 Contain legacy research/paper interference without a second runtime](tasks/C06.md) | P0 / ready | C04 | — | Trading infrastructure implementation / S |
|
||||
| [C06 Contain legacy research/paper interference without a second runtime](tasks/C06.md) | P0 / done | C04 | — | Trading infrastructure implementation / S |
|
||||
|
||||
### E2 — Canonical Rust financial engine
|
||||
|
||||
|
|
@ -63,7 +63,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [W01 Make existing run controls and selection truthful](tasks/W01.md) | P1 / done | None | — | Full-stack React/API / M |
|
||||
| [W02 Expose result provenance and legacy correctness limitations](tasks/W02.md) | P1 / ready | W01 | — | Full-stack research UX / M |
|
||||
| [W02 Expose result provenance and legacy correctness limitations](tasks/W02.md) | P1 / done | W01 | — | Full-stack research UX / M |
|
||||
| [W03 Separate save, submit and repeat-safe run creation](tasks/W03.md) | P1 / blocked | O01 | — | Full-stack durable workflow / M |
|
||||
| [W04 Verify the first research vertical slice in a browser](tasks/W04.md) | P1 / blocked | W01, W02, W03, C06 | — | Full-stack test engineering / M |
|
||||
|
||||
|
|
@ -115,4 +115,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
First wave: **C01, C03, C04, W01** are implemented, independently reviewed, validated and committed with owner approval. C06 and W02 are now ready; no later task is authorized or started. Commit references, commands, results and limitations are recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22) and the canonical manifest.
|
||||
First wave **C01, C03, C04, W01** and second wave **C06, C02, W02** are independently reviewed, validated and committed with owner approval. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), [second-wave handoff](../ROADMAP.md#second-wave-handoff--2026-10-22) and the manifest. Only **O01/P01** are authorized next; pending architecture policies and other tasks remain gated.
|
||||
|
|
|
|||
|
|
@ -1,37 +1,35 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-22.4",
|
||||
"plan_revision": "2026-10-22.6",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "first_wave_complete",
|
||||
"plan_status": "third_wave_authorized",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: make a commit and start (2026-10-22)",
|
||||
"authorized_by": "User: do all the commits and continue (2026-10-22); continue with next-ready O01 + P01",
|
||||
"tasks": [
|
||||
"C01",
|
||||
"C03",
|
||||
"C04",
|
||||
"W01"
|
||||
"O01",
|
||||
"P01"
|
||||
],
|
||||
"permissions": [
|
||||
"planning_snapshot_commit",
|
||||
"isolated_implementation",
|
||||
"local_tests",
|
||||
"bounded_local_benchmarks",
|
||||
"local_integration_review",
|
||||
"first_wave_implementation_commits",
|
||||
"planning_closeout_commit"
|
||||
"planning_progress_updates"
|
||||
],
|
||||
"excluded": [
|
||||
"third_wave_commits_without_further_approval",
|
||||
"push",
|
||||
"pull_requests",
|
||||
"live_or_paper_operations",
|
||||
"later_wave_implementation_without_approval"
|
||||
"other_backlog_tasks"
|
||||
],
|
||||
"pending_policy_decisions": [
|
||||
"ADR-002",
|
||||
"ADR-003",
|
||||
"ADR-004",
|
||||
"ADR-007"
|
||||
],
|
||||
"commit_authorized_by": "User: do all comits (2026-10-22)"
|
||||
]
|
||||
},
|
||||
"canonical_metadata": "This manifest alone owns task status, dependency edges, approvals, assignments and write locks. Task Markdown owns scope and acceptance criteria. Index/roadmap are derived views.",
|
||||
"decisions": [
|
||||
|
|
@ -158,7 +156,7 @@
|
|||
"epic": "E1",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "ready",
|
||||
"status": "done",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/C02.md",
|
||||
|
|
@ -171,12 +169,18 @@
|
|||
"native-public-api"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"branch": null,
|
||||
"assignment": "/root/wave2_c02",
|
||||
"branch": "wave2/c02-native-data-validation",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "ee670a3bd18b32195f9b69a48fbccc1409e55cd1",
|
||||
"blocker": null,
|
||||
"release_gates": []
|
||||
"release_gates": [],
|
||||
"worktree": "/tmp/stock-bot-wave2.M9vHDK/c02",
|
||||
"integration_base": "6d357af9836fee38566945019431e93dffc228da",
|
||||
"integration_state": "validated_committed",
|
||||
"review_notes": "Independent source review and combined integration gates passed; owner authorized implementation commits. See completed_commit and ROADMAP second-wave handoff.",
|
||||
"verification_reference": "ROADMAP.md#second-wave-handoff--2026-10-22",
|
||||
"reviewed_by": "/root/skeptical_core_review"
|
||||
},
|
||||
{
|
||||
"id": "C03",
|
||||
|
|
@ -275,7 +279,7 @@
|
|||
"epic": "E1",
|
||||
"priority": "P0",
|
||||
"severity": "Critical",
|
||||
"status": "ready",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"C04"
|
||||
],
|
||||
|
|
@ -291,12 +295,18 @@
|
|||
"runtime-composition"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"branch": null,
|
||||
"assignment": "/root/wave2_c06",
|
||||
"branch": "wave2/c06-runtime-containment",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "43ffb547bedd31227545ee1991d56ec04b079349",
|
||||
"blocker": null,
|
||||
"release_gates": []
|
||||
"release_gates": [],
|
||||
"worktree": "/tmp/stock-bot-wave2.M9vHDK/c06",
|
||||
"integration_base": "6d357af9836fee38566945019431e93dffc228da",
|
||||
"integration_state": "validated_committed",
|
||||
"review_notes": "Independent source review and combined integration gates passed; owner authorized implementation commits. See completed_commit and ROADMAP second-wave handoff.",
|
||||
"verification_reference": "ROADMAP.md#second-wave-handoff--2026-10-22",
|
||||
"reviewed_by": "/root/skeptical_core_review"
|
||||
},
|
||||
{
|
||||
"id": "F01",
|
||||
|
|
@ -905,7 +915,7 @@
|
|||
"epic": "E5",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "ready",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"W01"
|
||||
],
|
||||
|
|
@ -923,12 +933,18 @@
|
|||
"result-contract"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"branch": null,
|
||||
"assignment": "/root/wave2_w02",
|
||||
"branch": "wave2/w02-result-provenance",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "fe00ecd0e2a1414ae07435808924fe45cfdb348c",
|
||||
"blocker": null,
|
||||
"release_gates": []
|
||||
"release_gates": [],
|
||||
"worktree": "/tmp/stock-bot-wave2.M9vHDK/w02",
|
||||
"integration_base": "6d357af9836fee38566945019431e93dffc228da",
|
||||
"integration_state": "validated_committed",
|
||||
"review_notes": "Independent source review and combined integration gates passed; owner authorized implementation commits. See completed_commit and ROADMAP second-wave handoff.",
|
||||
"verification_reference": "ROADMAP.md#second-wave-handoff--2026-10-22",
|
||||
"reviewed_by": "/root/skeptical_product_review"
|
||||
},
|
||||
{
|
||||
"id": "W03",
|
||||
|
|
@ -1804,7 +1820,7 @@
|
|||
}
|
||||
],
|
||||
"review_note": "Independent skeptical revision: four superseded tasks retain stable IDs; deferred work is not a dependency of scheduled tasks. Release gates are distinct from implementation prerequisites.",
|
||||
"integration_base": "1148673",
|
||||
"integration_base": "6d357af9836fee38566945019431e93dffc228da",
|
||||
"validation": {
|
||||
"date": "2026-10-22",
|
||||
"integration_base": "1148673",
|
||||
|
|
@ -1850,5 +1866,127 @@
|
|||
"C04": "3d26da07f549a9b2cde5c6811918b4404dd22bb0",
|
||||
"W01": "67f12b49a070a4ed91d83ba1518d8deb6ff75333"
|
||||
}
|
||||
}
|
||||
},
|
||||
"execution_history": [
|
||||
{
|
||||
"wave": "first_wave",
|
||||
"scope": {
|
||||
"authorized_by": "User: make a commit and start (2026-10-22)",
|
||||
"tasks": [
|
||||
"C01",
|
||||
"C03",
|
||||
"C04",
|
||||
"W01"
|
||||
],
|
||||
"permissions": [
|
||||
"planning_snapshot_commit",
|
||||
"isolated_implementation",
|
||||
"local_tests",
|
||||
"local_integration_review",
|
||||
"first_wave_implementation_commits",
|
||||
"planning_closeout_commit"
|
||||
],
|
||||
"excluded": [
|
||||
"push",
|
||||
"pull_requests",
|
||||
"live_or_paper_operations",
|
||||
"later_wave_implementation_without_approval"
|
||||
],
|
||||
"pending_policy_decisions": [
|
||||
"ADR-002",
|
||||
"ADR-003",
|
||||
"ADR-007"
|
||||
],
|
||||
"commit_authorized_by": "User: do all comits (2026-10-22)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"wave": "second_wave",
|
||||
"scope": {
|
||||
"authorized_by": "User: do it, following recommendation C06 + C02 + W02 (2026-10-22)",
|
||||
"tasks": [
|
||||
"C06",
|
||||
"C02",
|
||||
"W02"
|
||||
],
|
||||
"permissions": [
|
||||
"isolated_implementation",
|
||||
"local_tests",
|
||||
"local_integration_review",
|
||||
"planning_progress_updates",
|
||||
"second_wave_implementation_commits",
|
||||
"planning_closeout_commit"
|
||||
],
|
||||
"excluded": [
|
||||
"push",
|
||||
"pull_requests",
|
||||
"live_or_paper_operations",
|
||||
"other_backlog_tasks"
|
||||
],
|
||||
"pending_policy_decisions": [
|
||||
"ADR-002",
|
||||
"ADR-003",
|
||||
"ADR-004",
|
||||
"ADR-007"
|
||||
],
|
||||
"commit_authorized_by": "User: do all the commits and continue (2026-10-22)"
|
||||
}
|
||||
}
|
||||
],
|
||||
"second_wave": [
|
||||
"C06",
|
||||
"C02",
|
||||
"W02"
|
||||
],
|
||||
"second_wave_validation": {
|
||||
"date": "2026-10-22",
|
||||
"integration_base": "6d357af9836fee38566945019431e93dffc228da",
|
||||
"application_commit": "fe00ecd0e2a1414ae07435808924fe45cfdb348c",
|
||||
"repository_check": {
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"status": "passed",
|
||||
"tooling": 54,
|
||||
"utils": 43,
|
||||
"calculations": 35,
|
||||
"integration": 293,
|
||||
"native": 37,
|
||||
"failed": 0
|
||||
},
|
||||
"postgres_recovery_tests": {
|
||||
"command": "bun run test:postgres",
|
||||
"passed": 47,
|
||||
"failed": 0,
|
||||
"assertions": 267,
|
||||
"environment": "Disposable stock_bot_safety PostgreSQL and dedicated Redis DB15; development services untouched"
|
||||
},
|
||||
"baseline_selected_integration": {
|
||||
"passed": 86,
|
||||
"failed": 0
|
||||
},
|
||||
"native_bridge_tests": {
|
||||
"passed": 47,
|
||||
"included_in_integration": true
|
||||
},
|
||||
"native_addon": {
|
||||
"path": "apps/stock/engine/dist/engine.node",
|
||||
"sha256": "833332fbfefcc65e91671d5b42bb714f6e257a7689c18c79acbd740efcc2a791",
|
||||
"build": "Rebuilt from integrated source"
|
||||
},
|
||||
"notes": [
|
||||
"All 21 authored implementation/test files match reviewed isolated worktrees.",
|
||||
"Native builds/IPC and disposable database access required sandbox escalation.",
|
||||
"W02 uses interaction/SSR tests, not real-browser release certification.",
|
||||
"Existing Rust/build warnings and unchanged test-only W01 harness curly lint findings remain; repository lint gate passes.",
|
||||
"Same-bar execution, canonical Rust accounting and pending ADR approvals are unchanged."
|
||||
],
|
||||
"application_commits": {
|
||||
"C02": "ee670a3bd18b32195f9b69a48fbccc1409e55cd1",
|
||||
"C06": "43ffb547bedd31227545ee1991d56ec04b079349",
|
||||
"W02": "fe00ecd0e2a1414ae07435808924fe45cfdb348c"
|
||||
}
|
||||
},
|
||||
"third_wave": [
|
||||
"O01",
|
||||
"P01"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,6 +57,17 @@ export interface BacktestRunTrade {
|
|||
duration?: number;
|
||||
}
|
||||
|
||||
/** Read-only evidence from saved results, not a certification of economic correctness. */
|
||||
export interface BacktestRunProvenance {
|
||||
/** Legacy config remains a compatibility display fallback, never historical evidence. */
|
||||
configurationSource: 'stored-snapshot' | 'legacy-definition-fallback';
|
||||
datasetHash: string | null;
|
||||
engineVersion: string | null;
|
||||
economicsVersion: string | null;
|
||||
strategyArtifactHash: string | null;
|
||||
limitations: { code: string; message: string }[];
|
||||
}
|
||||
|
||||
export interface BacktestRunResult {
|
||||
runId: string;
|
||||
backtestId: string;
|
||||
|
|
@ -65,6 +76,8 @@ export interface BacktestRunResult {
|
|||
legacy?: boolean;
|
||||
status: 'completed' | 'cancelled';
|
||||
completedAt: string;
|
||||
/** Optional for older API clients/results. Missing provenance must display as unknown. */
|
||||
provenance?: BacktestRunProvenance;
|
||||
config: BacktestRunConfiguration;
|
||||
metrics: BacktestRunMetrics;
|
||||
equity: { date: string; value: number }[];
|
||||
|
|
@ -83,7 +96,8 @@ export interface BacktestRunResult {
|
|||
}[];
|
||||
/** Returns, drawdowns, and exposure use fractions here as well. */
|
||||
analytics: {
|
||||
exposureTime: number;
|
||||
/** Null when unavailable or a known placeholder; genuine measured zero remains zero. */
|
||||
exposureTime: number | null;
|
||||
drawdownSeries?: { timestamp: number; value: number }[];
|
||||
dailyReturns?: number[];
|
||||
monthlyReturns?: Record<string, number>;
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ export type { BacktestResults } from './backtesting';
|
|||
export type {
|
||||
BacktestRunConfiguration,
|
||||
BacktestRunMetrics,
|
||||
BacktestRunProvenance,
|
||||
BacktestRunTrade,
|
||||
BacktestRunResult,
|
||||
} from './backtest-run';
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ test('compact metrics preserve null ratios and render a genuine zero profit', ()
|
|||
dataFrequency: '1d',
|
||||
parameters: {},
|
||||
},
|
||||
metrics,
|
||||
metrics: { ...metrics, totalProfit: 0 },
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
positions: [],
|
||||
|
|
@ -88,3 +88,34 @@ 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%');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -157,7 +157,7 @@ describe('pure stored backtest result conversion', () => {
|
|||
expect(row).toEqual(before);
|
||||
});
|
||||
|
||||
test('legacy explicit zero fees and absent optional analytics keep their existing defaults', () => {
|
||||
test('legacy explicit zero fees remain compatibility defaults, missing analytics are unknown', () => {
|
||||
const row = fixture();
|
||||
row.backtest_config = {
|
||||
name: 'Legacy',
|
||||
|
|
@ -176,10 +176,108 @@ describe('pure stored backtest result conversion', () => {
|
|||
dataFrequency: '1h',
|
||||
parameters: row.backtest_config,
|
||||
},
|
||||
analytics: { exposureTime: 0 },
|
||||
analytics: { exposureTime: null },
|
||||
});
|
||||
});
|
||||
|
||||
test('legacy_missing_provenance: mutable definition fallback is explicitly not saved evidence', () => {
|
||||
const row = fixture();
|
||||
row.backtest_config = { name: 'Changed later', commission: 0.25 };
|
||||
const result = mapStoredBacktestResult(row);
|
||||
expect(result.config.name).toBe('Changed later'); // Old consumers keep their display fallback.
|
||||
expect(result.provenance).toMatchObject({
|
||||
configurationSource: 'legacy-definition-fallback',
|
||||
datasetHash: null,
|
||||
engineVersion: null,
|
||||
economicsVersion: null,
|
||||
strategyArtifactHash: null,
|
||||
});
|
||||
expect(result.provenance?.limitations.map(item => item.code)).toContain(
|
||||
'missing-configuration'
|
||||
);
|
||||
expect(result.provenance?.limitations.map(item => item.code)).toContain(
|
||||
'unversioned-execution'
|
||||
);
|
||||
});
|
||||
|
||||
test('frozen_config_not_mutable_definition: all stored inputs and dataset identity survive definition edits', () => {
|
||||
const row = fixture();
|
||||
row.engine = 'typescript';
|
||||
row.configuration = {
|
||||
name: 'Frozen strategy',
|
||||
strategy: 'saved-strategy',
|
||||
symbols: ['B.US'],
|
||||
startDate: '2023-01-01',
|
||||
endDate: '2023-02-01',
|
||||
initialCapital: 1000,
|
||||
commission: 0.0007,
|
||||
slippage: 0.0002,
|
||||
dataFrequency: '1m',
|
||||
parameters: { lookback: 14 },
|
||||
dataset: {
|
||||
version: 1,
|
||||
hash: 'a'.repeat(64),
|
||||
instruments: [{ id: 'B.US', symbol: 'B', exchange: 'US' }],
|
||||
startDate: '2023-01-01',
|
||||
endDate: '2023-02-01',
|
||||
interval: '1m',
|
||||
policy: { adjustment: 'raw', timestamp: 'utc-instant' },
|
||||
volumePolicy: 'reported',
|
||||
qualityPolicy: 'reject-invalid-no-interpolation',
|
||||
sources: [],
|
||||
barCount: 10,
|
||||
},
|
||||
};
|
||||
const first = mapStoredBacktestResult(row);
|
||||
row.strategy = 'changed-strategy';
|
||||
row.symbols = ['C.US'];
|
||||
row.initial_capital = 999999;
|
||||
row.backtest_config = { commission: 0.9, slippage: 0.9, dataFrequency: '1d' };
|
||||
const reopened = mapStoredBacktestResult(row);
|
||||
expect(reopened.config).toEqual(first.config);
|
||||
expect(reopened.provenance).toEqual(first.provenance);
|
||||
expect(reopened.provenance).toMatchObject({
|
||||
configurationSource: 'stored-snapshot',
|
||||
datasetHash: 'a'.repeat(64),
|
||||
engineVersion: null,
|
||||
economicsVersion: null,
|
||||
strategyArtifactHash: null,
|
||||
});
|
||||
expect(reopened.provenance?.limitations.map(item => item.code)).not.toContain(
|
||||
'missing-configuration'
|
||||
);
|
||||
});
|
||||
|
||||
test('null_metrics: known placeholders are unavailable without discarding computed statistics or mutating storage', () => {
|
||||
const row = fixture();
|
||||
row.engine = 'native';
|
||||
row.metrics.sharpeRatio = 1.2;
|
||||
row.metrics.sortinoRatio = 1.4;
|
||||
row.analytics = {
|
||||
exposureTime: 0,
|
||||
riskMetrics: { value_at_risk_95: 0, volatility: 0.12, downside_deviation: 0.08 },
|
||||
};
|
||||
const before = structuredClone(row);
|
||||
const result = mapStoredBacktestResult(row);
|
||||
expect(result.analytics.exposureTime).toBeNull();
|
||||
expect(result.analytics.riskMetrics).toEqual({
|
||||
value_at_risk_95: null,
|
||||
volatility: 0.12,
|
||||
downside_deviation: 0.08,
|
||||
});
|
||||
expect(result.metrics.sharpeRatio).toBe(1.2);
|
||||
expect(result.metrics.sortinoRatio).toBe(1.4);
|
||||
expect(row).toEqual(before);
|
||||
row.engine = 'typescript';
|
||||
row.analytics = { exposureTime: 0, riskMetrics: { var95: 0 } };
|
||||
expect(mapStoredBacktestResult(row).analytics).toEqual({
|
||||
exposureTime: 0,
|
||||
riskMetrics: { var95: 0 },
|
||||
});
|
||||
row.engine = 'legacy';
|
||||
expect(mapStoredBacktestResult(row).analytics.exposureTime).toBeNull();
|
||||
});
|
||||
|
||||
test('malformed trade identities fail instead of fabricating an execution time or price', () => {
|
||||
const row = fixture();
|
||||
delete row.trades[0]!.entryDate;
|
||||
|
|
|
|||
119
test/integration/backtest-result-provenance.test.tsx
Normal file
119
test/integration/backtest-result-provenance.test.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { mapStoredBacktestResult } from '../../apps/stock/web-api/src/services/backtest-result';
|
||||
import { CompactPerformanceMetrics } from '../../apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics';
|
||||
import { ResultProvenance } from '../../apps/stock/web-app/src/features/backtest/components/ResultProvenance';
|
||||
|
||||
function result(): BacktestRunResult {
|
||||
return mapStoredBacktestResult({
|
||||
run_id: 'saved-run',
|
||||
backtest_id: 'definition',
|
||||
completed_at: new Date('2024-02-01'),
|
||||
strategy: 'MUTABLE_STRATEGY',
|
||||
symbols: ['CHANGED.US'],
|
||||
initial_capital: 999999,
|
||||
start_date: new Date('2020-01-01'),
|
||||
end_date: new Date('2020-02-01'),
|
||||
backtest_config: { name: 'MUTABLE_NAME', commission: 0.9 },
|
||||
metrics: {
|
||||
totalReturn: 10,
|
||||
sharpeRatio: 1,
|
||||
maxDrawdown: 0.1,
|
||||
winRate: 50,
|
||||
totalTrades: 2,
|
||||
profitFactor: 1.5,
|
||||
avgWin: 1,
|
||||
avgLoss: -1,
|
||||
},
|
||||
trades: [],
|
||||
equity_curve: [],
|
||||
ohlc_data: {},
|
||||
positions: [],
|
||||
execution_time: 2,
|
||||
});
|
||||
}
|
||||
const text = (html: string) => html.replace(/<[^>]*>/g, '');
|
||||
const panel = (saved: BacktestRunResult) =>
|
||||
text(renderToStaticMarkup(createElement(ResultProvenance, { result: saved })));
|
||||
const metrics = (saved: BacktestRunResult) =>
|
||||
text(
|
||||
renderToStaticMarkup(
|
||||
createElement(CompactPerformanceMetrics, { result: saved, isLoading: false })
|
||||
)
|
||||
);
|
||||
|
||||
test('legacy_missing_provenance: panel never substitutes current settings for historical evidence', () => {
|
||||
const saved = result();
|
||||
const rendered = panel(saved);
|
||||
expect(rendered).toContain('Stored run configuration: Unknown');
|
||||
expect(rendered).toContain('Dataset hashUnknown');
|
||||
expect(rendered).toContain('Engine buildUnknown');
|
||||
expect(rendered).toContain('Strategy artifactUnknown');
|
||||
expect(rendered).not.toContain('MUTABLE_STRATEGY');
|
||||
expect(rendered).not.toContain('MUTABLE_NAME');
|
||||
expect(rendered).not.toContain('999999');
|
||||
expect(metrics(saved)).toContain('Total Profit-');
|
||||
saved.metrics.totalPnl = 123;
|
||||
expect(metrics(saved)).toContain('Total Profit$123.00');
|
||||
});
|
||||
|
||||
test('frozen_config_not_mutable_definition: exact snapshot renders and permits capital-derived profit', () => {
|
||||
const saved = result();
|
||||
saved.config = {
|
||||
name: 'Stored strategy',
|
||||
strategy: 'saved-strategy',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-02-01',
|
||||
initialCapital: 1000,
|
||||
commission: 0.0007,
|
||||
slippage: 0,
|
||||
dataFrequency: '1m',
|
||||
parameters: { lookback: 42 },
|
||||
};
|
||||
saved.provenance!.configurationSource = 'stored-snapshot';
|
||||
saved.provenance!.datasetHash = 'a'.repeat(64);
|
||||
const rendered = panel(saved);
|
||||
expect(rendered).toContain('Stored run configuration');
|
||||
expect(rendered).toContain('saved-strategy');
|
||||
expect(rendered).toContain('lookback');
|
||||
expect(rendered).toContain('42');
|
||||
expect(rendered).toContain('0.0007');
|
||||
expect(rendered).toContain('a'.repeat(64));
|
||||
expect(rendered).not.toContain('MUTABLE_STRATEGY');
|
||||
expect(metrics(saved)).toContain('Total Profit$100.00');
|
||||
});
|
||||
|
||||
test('limitation_badge: engine name never establishes version or financial validation', () => {
|
||||
const saved = result();
|
||||
saved.engine = 'native';
|
||||
const rendered = panel(saved);
|
||||
expect(rendered).toContain('Research only · Unverified economics');
|
||||
expect(rendered).toContain('Recorded enginenative');
|
||||
expect(rendered).toContain('Engine buildUnknown');
|
||||
expect(rendered).toContain('same-bar execution');
|
||||
expect(rendered).toContain('funding constraints');
|
||||
expect(rendered).toContain('strategy attribution');
|
||||
expect(rendered).toContain(
|
||||
'Current terminal-equity and fee-funding fixes do not certify this saved run'
|
||||
);
|
||||
});
|
||||
|
||||
test('old API without provenance remains readable but cannot invent historical inputs', () => {
|
||||
const saved = result();
|
||||
delete saved.provenance;
|
||||
expect(panel(saved)).toContain('Provenance metadata is unavailable from this API');
|
||||
expect(panel(saved)).toContain('Stored run configuration: Unknown');
|
||||
expect(metrics(saved)).toContain('Total Profit-');
|
||||
});
|
||||
|
||||
test('null_metrics: missing exposure is unavailable, genuine recorded zeros remain visible', () => {
|
||||
const saved = result();
|
||||
expect(metrics(saved)).toContain('Exposure-');
|
||||
saved.analytics.exposureTime = 0;
|
||||
saved.metrics.totalProfit = 0;
|
||||
expect(metrics(saved)).toContain('Total Profit$0.00');
|
||||
expect(metrics(saved)).toContain('Exposure0.0%');
|
||||
});
|
||||
|
|
@ -537,20 +537,37 @@ describe('actual detail page result states', () => {
|
|||
status === 'failed' ? 'Run failed: Fixture failure' : 'Run cancelled'
|
||||
);
|
||||
expect(host.textContent).not.toContain('No trades executed');
|
||||
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
||||
expect(requests.some(item => item.path.endsWith('/results'))).toBe(false);
|
||||
});
|
||||
}
|
||||
test('completed missing results differ from successful zero trades and retry uses saved results', async () => {
|
||||
await mountPage('completed');
|
||||
expect(host.textContent).toContain('Loading run data');
|
||||
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
||||
await flush(() => click('Trades'));
|
||||
await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404));
|
||||
expect(host.textContent).toContain('saved results are unavailable');
|
||||
expect(host.textContent).not.toContain('No trades executed');
|
||||
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
||||
await flush(() => click('Retry results'));
|
||||
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
||||
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
||||
expect(host.textContent).toContain('No trades executed in this backtest.');
|
||||
expect(host.textContent).not.toContain('saved results are unavailable');
|
||||
});
|
||||
|
||||
test('limitation_badge: completed detail shows unknown legacy provenance beside performance', async () => {
|
||||
await mountPage('completed');
|
||||
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
||||
const evidence = host.querySelector('[aria-label="Result provenance and limitations"]');
|
||||
expect(evidence).not.toBeNull();
|
||||
expect(evidence!.textContent).toContain('Research only · Unverified economics');
|
||||
const details = evidence!.querySelector('details')!;
|
||||
await flush(() => details.querySelector('summary')!.click());
|
||||
expect(details.open).toBe(true);
|
||||
expect(evidence!.textContent).toContain('Stored run configuration: Unknown');
|
||||
expect(evidence!.textContent).toContain('Provenance metadata is unavailable from this API');
|
||||
expect(host.textContent).toContain('Performance');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -166,6 +166,8 @@ async function composedRuntime(
|
|||
};
|
||||
di.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(di, {
|
||||
role: 'research-only',
|
||||
useRustEngine: false,
|
||||
initializeMode: false,
|
||||
...options,
|
||||
});
|
||||
|
|
|
|||
172
test/integration/native-market-data.test.ts
Normal file
172
test/integration/native-market-data.test.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { nativeResultSchema } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
||||
|
||||
function engine() {
|
||||
return new BacktestEngine({
|
||||
name: 'Native data admission',
|
||||
symbols: ['A.US', 'B.US'],
|
||||
startDate: new Date(0).toISOString(),
|
||||
endDate: new Date(4_000).toISOString(),
|
||||
initialCapital: 100,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1m',
|
||||
});
|
||||
}
|
||||
|
||||
function bar(timestamp = 1_001, price = 10): Record<string, unknown> {
|
||||
return {
|
||||
symbol: 'A.US',
|
||||
timestamp,
|
||||
type: 'bar',
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 1_000,
|
||||
vwap: price,
|
||||
};
|
||||
}
|
||||
|
||||
describe('native market-data admission', () => {
|
||||
test('retains distinct millisecond timestamps in replay order', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(1_001, 10), bar(1_999, 11)]);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([
|
||||
[1_001, 10],
|
||||
[1_999, 11],
|
||||
]);
|
||||
expect(result.equity.map(row => Date.parse(row.date))).toEqual([0, 1_001, 1_999]);
|
||||
});
|
||||
|
||||
const invalidFields: Array<[string, unknown]> = [
|
||||
['open', Number.NaN],
|
||||
['open', 0],
|
||||
['open', -1],
|
||||
['high', Number.POSITIVE_INFINITY],
|
||||
['high', 9],
|
||||
['low', Number.NEGATIVE_INFINITY],
|
||||
['low', 11],
|
||||
['close', Number.NaN],
|
||||
['close', '10'],
|
||||
['volume', -1],
|
||||
['volume', Number.NaN],
|
||||
['volume', Number.POSITIVE_INFINITY],
|
||||
['vwap', Number.NaN],
|
||||
['vwap', Number.POSITIVE_INFINITY],
|
||||
['vwap', 0],
|
||||
['vwap', -1],
|
||||
['vwap', '10'],
|
||||
['timestamp', Number.NaN],
|
||||
['timestamp', Number.POSITIVE_INFINITY],
|
||||
['timestamp', 1_500.5],
|
||||
['timestamp', Number.MAX_SAFE_INTEGER + 1],
|
||||
['timestamp', Number.MAX_SAFE_INTEGER],
|
||||
['timestamp', '1500'],
|
||||
['type', 'quote'],
|
||||
['symbol', ' '],
|
||||
];
|
||||
for (const [field, value] of invalidFields) {
|
||||
test(`rejects invalid ${field}=${String(value)} with the zero-based row index`, () => {
|
||||
const subject = engine();
|
||||
expect(() =>
|
||||
subject.loadMarketData([bar(500), { ...bar(1_500), [field]: value }, bar(2_500)])
|
||||
).toThrow(/Market data row 1:/);
|
||||
});
|
||||
}
|
||||
|
||||
for (const field of ['symbol', 'timestamp', 'type', 'open', 'high', 'low', 'close', 'volume']) {
|
||||
test(`rejects missing ${field} with the zero-based row index`, () => {
|
||||
const subject = engine();
|
||||
const incomplete = bar(1_500);
|
||||
delete incomplete[field];
|
||||
expect(() => subject.loadMarketData([bar(500), incomplete, bar(2_500)])).toThrow(
|
||||
/Market data row 1:/
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
for (const value of [null, undefined, 1, 'bar', []]) {
|
||||
test(`rejects a non-record row (${String(value)}) with its index`, () => {
|
||||
const subject = engine();
|
||||
expect(() => subject.loadMarketData([bar(500), value as object, bar(2_500)])).toThrow(
|
||||
/Market data row 1:/
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('a malformed replacement preserves all previously admitted data', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(1_001, 10), bar(1_999, 11)]);
|
||||
expect(() =>
|
||||
subject.loadMarketData([bar(500, 20), { ...bar(1_500, 30), low: 31 }, bar(2_500, 40)])
|
||||
).toThrow(/Market data row 1:/);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([
|
||||
[1_001, 10],
|
||||
[1_999, 11],
|
||||
]);
|
||||
});
|
||||
|
||||
test('an invalid first load does not admit its valid neighboring rows', () => {
|
||||
const subject = engine();
|
||||
expect(() =>
|
||||
subject.loadMarketData([bar(500), { ...bar(1_500), close: Number.NaN }, bar(2_500)])
|
||||
).toThrow(/Market data row 1:/);
|
||||
expect(() => subject.run()).toThrow('No market data loaded');
|
||||
});
|
||||
|
||||
test('a valid replacement after a rejected load succeeds without stale rows', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(500)]);
|
||||
expect(() => subject.loadMarketData([{ ...bar(1_001), type: 'quote' }])).toThrow(
|
||||
/Market data row 0: Unsupported market data type: quote/
|
||||
);
|
||||
subject.loadMarketData([bar(1_999, 11)]);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([[1_999, 11]]);
|
||||
});
|
||||
|
||||
for (const conflicting of [false, true]) {
|
||||
test(`rejects ${conflicting ? 'conflicting' : 'identical'} duplicates without replacing good data`, () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(1_001)]);
|
||||
expect(() => subject.loadMarketData([bar(1_500), bar(1_500, conflicting ? 11 : 10)])).toThrow(
|
||||
/Market data row 1: Duplicate bar identity A\.US at 1500ms \(first at row 0\)/
|
||||
);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => row.timestamp)).toEqual([1_001]);
|
||||
});
|
||||
}
|
||||
|
||||
test('rejects decreasing timestamps instead of relying on an invalid historical seek order', () => {
|
||||
const subject = engine();
|
||||
expect(() => subject.loadMarketData([bar(1_999), bar(1_001)])).toThrow(
|
||||
/Market data row 1: Timestamps must be nondecreasing/
|
||||
);
|
||||
});
|
||||
|
||||
test('accepts distinct same-time symbols, zero volume and optional absent VWAP', () => {
|
||||
const subject = engine();
|
||||
const withoutVwap = { ...bar(1_001), volume: 0 };
|
||||
delete withoutVwap.vwap;
|
||||
subject.loadMarketData([
|
||||
{ ...bar(1_001), symbol: 'B.US', vwap: null },
|
||||
withoutVwap,
|
||||
{ ...bar(1_999), vwap: undefined },
|
||||
]);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']).toHaveLength(2);
|
||||
expect(result.ohlcData['B.US']).toHaveLength(1);
|
||||
expect(result.ohlcData['A.US']?.[0]?.volume).toBe(0);
|
||||
});
|
||||
|
||||
test('rejects loading into a consumed engine explicitly', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar()]);
|
||||
subject.run();
|
||||
expect(() => subject.loadMarketData([bar()])).toThrow('Engine already consumed');
|
||||
});
|
||||
});
|
||||
151
test/integration/research-runtime-isolation.test.ts
Normal file
151
test/integration/research-runtime-isolation.test.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import { asFunction, asValue, createContainer as createDiContainer } from 'awilix';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { defaultRiskLimits } from '../../apps/stock/orchestrator/src/execution/model';
|
||||
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
});
|
||||
|
||||
async function compose(options: Parameters<typeof registerOrchestratorServices>[1] = {}) {
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.build();
|
||||
const services: OrchestratorServices = { logger };
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container, options);
|
||||
const runtime = services.custom!;
|
||||
cleanup.push(async () => {
|
||||
await runtime.BacktestRunner!.shutdown();
|
||||
await runtime.ModeManager!.shutdown();
|
||||
await runtime.StrategyManager!.shutdown();
|
||||
await container.dispose();
|
||||
});
|
||||
return runtime;
|
||||
}
|
||||
|
||||
describe('research runtime composition admission', () => {
|
||||
test.each([true, false])(
|
||||
'legacy_paper_combination_rejected_before_prepare (initializeMode=%s)',
|
||||
async initializeMode => {
|
||||
let resolved = 0;
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
container.register({
|
||||
serviceContainer: asFunction(() => {
|
||||
resolved++;
|
||||
throw new Error('Runtime services must not be resolved');
|
||||
}),
|
||||
});
|
||||
await expect(
|
||||
registerOrchestratorServices(container, { useRustEngine: false, initializeMode })
|
||||
).rejects.toThrow('TypeScript backtests require a research-only composition');
|
||||
expect(resolved).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
test('unsafe application startup fails before connection setup', async () => {
|
||||
const config = {
|
||||
services: { orchestrator: { backtesting: { useRustEngine: false } } },
|
||||
} as StockAppConfig;
|
||||
await expect(createContainer(config)).rejects.toThrow('Unsupported runtime combination');
|
||||
});
|
||||
|
||||
test('unchecked role and backend options fail closed before service resolution', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
for (const options of [
|
||||
{ role: 'research' },
|
||||
{ role: null },
|
||||
{ useRustEngine: 'false' },
|
||||
{ useRustEngine: null },
|
||||
]) {
|
||||
await expect(
|
||||
registerOrchestratorServices(
|
||||
container,
|
||||
options as unknown as Parameters<typeof registerOrchestratorServices>[1]
|
||||
)
|
||||
).rejects.toThrow('role' in options ? 'Unsupported runtime role' : 'must be a boolean');
|
||||
}
|
||||
});
|
||||
|
||||
test('standalone_legacy_research_allowed without automatic paper initialization', async () => {
|
||||
const runtime = await compose({
|
||||
role: 'research-only',
|
||||
useRustEngine: false,
|
||||
allowSyntheticData: true,
|
||||
syntheticSeed: 42,
|
||||
});
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(BacktestEngine);
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
await runtime.ModeManager!.initializeMode(config);
|
||||
const result = await runtime.BacktestEngine!.runBacktest(config);
|
||||
expect(result.status).toBe('completed');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(runtime.ModeManager!.getConfig()).toEqual(config);
|
||||
});
|
||||
|
||||
test('research_only_paper_activation_denied through every exposed initializer', async () => {
|
||||
const runtime = await compose({ role: 'research-only', useRustEngine: false });
|
||||
const mode = runtime.ModeManager!;
|
||||
const execution = runtime.ExecutionService!;
|
||||
await mode.initializeMode(config);
|
||||
const engine = mode.getTradingEngine();
|
||||
const account = await execution.getAccount();
|
||||
const paper = { mode: 'paper' as const, startingCapital: 123 };
|
||||
let shutdowns = 0;
|
||||
mode.on('shutdown', () => shutdowns++);
|
||||
|
||||
await expect(mode.initializeMode(paper)).rejects.toThrow('only permits backtest');
|
||||
await expect(mode.transitionMode('backtest', 'paper', paper)).rejects.toThrow(
|
||||
'only permits backtest'
|
||||
);
|
||||
await expect(execution.initialize(paper, engine)).rejects.toThrow('only permits backtest');
|
||||
const live = {
|
||||
mode: 'live' as const,
|
||||
broker: 'ib',
|
||||
accountId: 'not-a-real-account',
|
||||
accountType: 'cash' as const,
|
||||
riskLimits: { ...defaultRiskLimits },
|
||||
};
|
||||
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
|
||||
await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
|
||||
expect(shutdowns).toBe(0);
|
||||
expect(mode.getTradingEngine()).toBe(engine);
|
||||
expect(mode.getConfig()).toEqual(config);
|
||||
expect(await execution.getAccount()).toEqual(account);
|
||||
});
|
||||
|
||||
test('paper composition defaults to native and cannot be switched to a legacy shared mode', async () => {
|
||||
const runtime = await compose({ initializeMode: false });
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
await expect(runtime.ModeManager!.initializeMode(config)).rejects.toThrow('only permits paper');
|
||||
await expect(
|
||||
runtime.ExecutionService!.initialize(config, makeExecution().engine)
|
||||
).rejects.toThrow('only permits paper');
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
});
|
||||
|
||||
test('research-only native composition also forbids paper startup and activation', async () => {
|
||||
const runtime = await compose({ role: 'research-only' });
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
await expect(
|
||||
runtime.ModeManager!.initializeMode({ mode: 'paper', startingCapital: 10000 })
|
||||
).rejects.toThrow('only permits backtest');
|
||||
});
|
||||
});
|
||||
272
test/postgres/research-runtime-isolation.test.ts
Normal file
272
test/postgres/research-runtime-isolation.test.ts
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { asValue } from 'awilix';
|
||||
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
type OrchestratorServices,
|
||||
} from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger, quote } from '../fixtures/execution';
|
||||
import { CounterStrategy } 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();
|
||||
});
|
||||
|
||||
const research = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['RESEARCH.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
|
||||
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
|
||||
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
|
||||
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id), completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
|
||||
execution_time numeric);`);
|
||||
for (const filename of [
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'11-simulation-execution-ledger.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, 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) });
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.build();
|
||||
const services: OrchestratorServices = { logger, postgres };
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container, {
|
||||
initializeMode: false,
|
||||
nativeExecutionTimeoutMs: 5000,
|
||||
});
|
||||
const runtime = services.custom!;
|
||||
const mode = runtime.ModeManager!;
|
||||
const runner = runtime.BacktestRunner!;
|
||||
const market = runtime.MarketDataService!;
|
||||
const storage = runtime.StorageService!;
|
||||
const execution = runtime.ExecutionService!;
|
||||
const strategies = runtime.StrategyManager!;
|
||||
const feed = { connected: false };
|
||||
// Only the external transport is offline; real admission, ledger, checkpoints and replay run.
|
||||
const feedStart = spyOn(market, 'initialize').mockImplementation(async () => {
|
||||
feed.connected = true;
|
||||
});
|
||||
const originalShutdown = market.shutdown.bind(market);
|
||||
const feedStop = spyOn(market, 'shutdown').mockImplementation(async () => {
|
||||
feed.connected = false;
|
||||
await originalShutdown();
|
||||
});
|
||||
const lifecycle = [
|
||||
feedStart,
|
||||
feedStop,
|
||||
spyOn(execution, 'initialize'),
|
||||
spyOn(execution, 'shutdown'),
|
||||
spyOn(storage, 'initialize'),
|
||||
spyOn(storage, 'shutdown'),
|
||||
spyOn(strategies, 'restoreStrategies'),
|
||||
spyOn(strategies, 'shutdown'),
|
||||
];
|
||||
cleanup.push(async () => {
|
||||
try {
|
||||
await runner.shutdown();
|
||||
await mode.shutdown();
|
||||
await strategies.shutdown();
|
||||
await container.dispose();
|
||||
} finally {
|
||||
for (const method of lifecycle) method.mockRestore();
|
||||
}
|
||||
});
|
||||
await mode.initializeMode({
|
||||
mode: 'paper',
|
||||
accountId: 'paper-fixture',
|
||||
startingCapital: 10000,
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
});
|
||||
const strategy = new CounterStrategy(execution);
|
||||
await strategies.attachStrategy(strategy);
|
||||
await market.subscribeToSymbol('A');
|
||||
market.ingest(quote('paper-one', 100, 100, Date.now()));
|
||||
await market.flush();
|
||||
expect(strategy.count).toBe(1);
|
||||
expect((await execution.getAccount()).cash).toBe(9899.9);
|
||||
|
||||
let failedRead = false;
|
||||
storage.getHistoricalBars = async () => {
|
||||
if (failedRead) throw new Error('Injected research history failure');
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
symbol: research.symbols[0]!,
|
||||
source: 'eod' as const,
|
||||
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
};
|
||||
const stateHash = async () => {
|
||||
const state: unknown[] = [];
|
||||
for (const [table, columns] of [
|
||||
['simulation_accounts', 'id,state'],
|
||||
['simulation_orders', 'id,payload'],
|
||||
['simulation_fills', 'id,payload'],
|
||||
['simulation_events', 'id,fingerprint'],
|
||||
['simulation_market_inputs', 'id,payload'],
|
||||
['simulation_strategy_journal', 'sequence,payload'],
|
||||
['simulation_strategy_checkpoints', 'strategy_id,payload'],
|
||||
['simulation_strategy_intents', 'client_order_id,payload'],
|
||||
]) {
|
||||
const rows = (await pool.query(`SELECT ${columns} FROM ${table}`)).rows;
|
||||
state.push([table, rows.map(row => canonicalJson(row)).sort()]);
|
||||
}
|
||||
return createHash('sha256').update(canonicalJson(state)).digest('hex');
|
||||
};
|
||||
return {
|
||||
services,
|
||||
pool,
|
||||
runner,
|
||||
mode,
|
||||
execution,
|
||||
market,
|
||||
strategies,
|
||||
strategy,
|
||||
feed,
|
||||
stateHash,
|
||||
lifecycleCounts: () => lifecycle.map(method => method.mock.calls.length),
|
||||
failHistory: (fail: boolean) => {
|
||||
failedRead = fail;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('research isolation from a real paper ledger', () => {
|
||||
test('legacy_paper_combination_rejected_before_prepare preserves an active paper graph', async () => {
|
||||
const f = await fixture();
|
||||
const engine = f.mode.getTradingEngine();
|
||||
const before = await f.stateHash();
|
||||
const lifecycle = f.lifecycleCounts();
|
||||
await expect(f.mode.initializeMode(research)).rejects.toThrow('only permits paper');
|
||||
await expect(f.mode.transitionMode('paper', 'backtest', research)).rejects.toThrow(
|
||||
'only permits paper'
|
||||
);
|
||||
await expect(f.execution.initialize(research, engine)).rejects.toThrow('only permits paper');
|
||||
expect(f.mode.getTradingEngine()).toBe(engine);
|
||||
expect(f.mode.isPaperMode()).toBe(true);
|
||||
expect(f.feed.connected).toBe(true);
|
||||
expect(f.lifecycleCounts()).toEqual(
|
||||
lifecycle.map((count, index) => count + (index === 2 ? 1 : 0))
|
||||
);
|
||||
expect(await f.stateHash()).toBe(before);
|
||||
});
|
||||
|
||||
test('native_paper_isolation across successful, cancelled and failed durable jobs', async () => {
|
||||
const f = await fixture();
|
||||
const engine = f.mode.getTradingEngine();
|
||||
const paperConfig = f.mode.getConfig();
|
||||
const before = await f.stateHash();
|
||||
const lifecycle = f.lifecycleCounts();
|
||||
const unchanged = async () => {
|
||||
expect(await f.stateHash()).toBe(before);
|
||||
expect(f.mode.getTradingEngine()).toBe(engine);
|
||||
expect(f.mode.getConfig()).toEqual(paperConfig);
|
||||
expect(f.lifecycleCounts()).toEqual(lifecycle);
|
||||
expect(f.market.listenerCount('marketDataBatch')).toBe(1);
|
||||
expect(f.strategies.getActiveStrategies()).toEqual(['counter']);
|
||||
expect(f.feed.connected).toBe(true);
|
||||
};
|
||||
expect((await f.runner.runBacktest(research)).status).toBe('completed');
|
||||
await unchanged();
|
||||
for (let i = 0; i < 2; i++) {
|
||||
let stopped: Promise<void> | undefined;
|
||||
f.runner.once('progress', () => {
|
||||
stopped = f.runner.stopBacktest();
|
||||
});
|
||||
const outcome = await f.runner.runBacktest(research).catch(error => error);
|
||||
await stopped;
|
||||
expect(stopped).toBeDefined();
|
||||
expect(outcome).toBeInstanceOf(BacktestCancelledError);
|
||||
await unchanged();
|
||||
f.failHistory(true);
|
||||
await expect(f.runner.runBacktest(research)).rejects.toThrow(
|
||||
'Injected research history failure'
|
||||
);
|
||||
f.failHistory(false);
|
||||
await unchanged();
|
||||
}
|
||||
expect((await f.runner.runBacktest(research)).status).toBe('completed');
|
||||
await unchanged();
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT status, count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
|
||||
)
|
||||
).rows
|
||||
).toEqual([
|
||||
{ status: 'cancelled', count: 2 },
|
||||
{ status: 'completed', count: 2 },
|
||||
{ status: 'failed', count: 2 },
|
||||
]);
|
||||
// The existing feed still makes exactly one new durable paper decision after research.
|
||||
f.market.ingest(quote('paper-two', 101, 100, Date.now()));
|
||||
await f.market.flush();
|
||||
expect(f.strategy.count).toBe(2);
|
||||
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2);
|
||||
}, 15000);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue