feat(strategies): add canonical regime-aware mean reversion
This commit is contained in:
parent
75abae2cfc
commit
6a67ae8683
24 changed files with 1910 additions and 88 deletions
|
|
@ -0,0 +1,71 @@
|
|||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type { NativeBacktestWorker } from '../src/backtest/NativeBacktestWorker';
|
||||
import { replayIdentitySchema } from '../src/contracts/native-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
type StrategyReplayRequest,
|
||||
} from '../src/contracts/strategy-replay';
|
||||
|
||||
/** Four explicit comparisons, not an optimizer. Both ablations retain identical
|
||||
* warmup, dataset, thresholds, seeds and engine policies except the named change.
|
||||
* Costs are supplied by the caller; this example never fits or chooses thresholds. */
|
||||
export function createRegimeComparisons(
|
||||
input: StrategyReplayRequest,
|
||||
alternativeCosts: { feeRate: string; slippageRate: string }
|
||||
) {
|
||||
const baseline = strategyReplayRequestSchema.parse(input);
|
||||
if (!baseline.strategies.some(strategy => strategy.strategyId === 'mean_reversion')) {
|
||||
throw new Error('Regime comparison requires a canonical mean-reversion selection');
|
||||
}
|
||||
return ([false, true] as const).flatMap(changeCosts =>
|
||||
(['volatility', 'none'] as const).map(regimeFilter => {
|
||||
const request = structuredClone(baseline);
|
||||
request.resultFormat = 'report';
|
||||
for (const strategy of request.strategies) {
|
||||
if (strategy.strategyId === 'mean_reversion') {
|
||||
strategy.parameters.regimeFilter = regimeFilter;
|
||||
}
|
||||
}
|
||||
if (changeCosts) {
|
||||
request.config.matching.risk.feeRate = parseFinancialDecimal(alternativeCosts.feeRate);
|
||||
request.config.matching.slippageRate = parseFinancialDecimal(alternativeCosts.slippageRate);
|
||||
}
|
||||
return {
|
||||
label: `${regimeFilter}${changeCosts ? '-alternative-costs' : ''}`,
|
||||
request: strategyReplayRequestSchema.parse(request),
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** Uses the existing isolated worker, never paper services. Caller owns worker
|
||||
* lifecycle and stores these exact requests/results with code/engine artifacts.
|
||||
* This is diagnostic comparison only: R08 walk-forward/holdout validation is
|
||||
* still required before drawing conclusions about strategy performance. */
|
||||
export async function runRegimeComparisons(
|
||||
worker: Pick<NativeBacktestWorker, 'execute'>,
|
||||
input: StrategyReplayRequest,
|
||||
alternativeCosts: { feeRate: string; slippageRate: string },
|
||||
signal: AbortSignal
|
||||
) {
|
||||
const trials = createRegimeComparisons(input, alternativeCosts);
|
||||
const results = [];
|
||||
for (const trial of trials) {
|
||||
signal.throwIfAborted();
|
||||
const raw = await worker.execute(trial.request, signal, () => {});
|
||||
const dataset = trial.request.dataset as { manifest?: { hash?: unknown } } | null;
|
||||
const result = parseStrategyReplayResult(raw, {
|
||||
strategies: trial.request.strategies,
|
||||
identity: replayIdentitySchema.parse({
|
||||
version: 1,
|
||||
sessionId: trial.request.config.matching.risk.ledger.sessionId,
|
||||
datasetHash: dataset?.manifest?.hash,
|
||||
}),
|
||||
policy: trial.request.config,
|
||||
format: 'report',
|
||||
});
|
||||
results.push({ ...trial, result });
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import type { StrategyReplayResult } from '../contracts/strategy-replay';
|
|||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../strategies/canonical-sma';
|
||||
} from '../strategies/canonical-builtins';
|
||||
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
|
||||
import { resolveNativeStrategies } from './native-strategies';
|
||||
import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol';
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ import { ExecutionService } from './services/ExecutionService';
|
|||
import { MarketDataService } from './services/MarketDataService';
|
||||
import { StorageService } from './services/StorageService';
|
||||
import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies';
|
||||
import { createBuiltinStrategy } from './strategies/canonical-sma';
|
||||
import { createBuiltinStrategy } from './strategies/canonical-builtins';
|
||||
import { StrategyManager } from './strategies/StrategyManager';
|
||||
import type { StrategyRegistry } from './strategies/StrategyRegistry';
|
||||
import type { OrchestratorServices as IServiceContainer } from './types';
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ const identity = z
|
|||
);
|
||||
const period = z.number().int().min(1).max(maxStrategyPeriod);
|
||||
|
||||
export const builtinStrategySelectionSchema = z
|
||||
export const smaStrategySelectionSchema = z
|
||||
.object({
|
||||
ownerId: identity,
|
||||
strategyId: z
|
||||
|
|
@ -48,4 +48,61 @@ export const builtinStrategySelectionSchema = z
|
|||
})
|
||||
.strict();
|
||||
|
||||
export const meanReversionStrategySelectionSchema = z
|
||||
.object({
|
||||
ownerId: identity,
|
||||
strategyId: z
|
||||
.string()
|
||||
.refine(
|
||||
value => builtinStrategy(value) === 'mean_reversion',
|
||||
'Unsupported canonical strategy'
|
||||
)
|
||||
.transform(() => 'mean_reversion' as const),
|
||||
strategyVersion: z.literal('mean-reversion-regime-long-only/v1'),
|
||||
seed: z.number().int().min(0).max(0xffffffff),
|
||||
instrumentId: identity,
|
||||
seriesId: identity,
|
||||
ownerBudget: z
|
||||
.string()
|
||||
.transform(value => parseFinancialDecimal(value))
|
||||
.refine(
|
||||
value => !value.startsWith('-') && value !== '0.00000000',
|
||||
'Owner budget must be positive'
|
||||
),
|
||||
parameters: z
|
||||
.object({
|
||||
lookbackPeriod: period.min(2),
|
||||
trendPeriod: period.min(3),
|
||||
momentumPeriod: period,
|
||||
volatilityPeriod: period.min(2),
|
||||
entryZScore: z.number().finite().positive(),
|
||||
exitZScore: z.number().finite().nonnegative(),
|
||||
minTrendReturn: z.number().finite().gt(-1),
|
||||
minMomentumReturn: z.number().finite().gt(-1),
|
||||
maxVolatility: z.number().finite().nonnegative(),
|
||||
minNotionalVolume: z
|
||||
.string()
|
||||
.transform(value => parseFinancialDecimal(value))
|
||||
.refine(value => !value.startsWith('-'), 'Notional volume must be nonnegative'),
|
||||
regimeFilter: z.enum(['volatility', 'none']),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
value => value.trendPeriod > value.lookbackPeriod,
|
||||
'Trend period must exceed the mean-reversion lookback'
|
||||
)
|
||||
.refine(
|
||||
value => value.exitZScore < value.entryZScore,
|
||||
'Exit threshold must be below the entry threshold'
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const builtinStrategySelectionSchema = z.union([
|
||||
smaStrategySelectionSchema,
|
||||
meanReversionStrategySelectionSchema,
|
||||
]);
|
||||
export type SmaStrategySelection = z.infer<typeof smaStrategySelectionSchema>;
|
||||
export type MeanReversionStrategySelection = z.infer<typeof meanReversionStrategySelectionSchema>;
|
||||
export type MeanReversionSignalParameters = MeanReversionStrategySelection['parameters'];
|
||||
export type BuiltinStrategySelection = z.infer<typeof builtinStrategySelectionSchema>;
|
||||
|
|
|
|||
48
apps/stock/orchestrator/src/strategies/canonical-builtins.ts
Normal file
48
apps/stock/orchestrator/src/strategies/canonical-builtins.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
|
||||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
type BuiltinStrategySelection,
|
||||
} from '../contracts/builtin-strategy';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import type { ReplayConfig } from '../contracts/native-replay';
|
||||
import { createMeanReversionStrategy } from './canonical-mean-reversion';
|
||||
import { createSmaStrategy } from './canonical-sma';
|
||||
|
||||
/** The small trusted built-in boundary; strategy versions never select legacy implementations. */
|
||||
export function createBuiltinStrategy(input: BuiltinStrategySelection): StrategyProgram {
|
||||
const selection = builtinStrategySelectionSchema.parse(input);
|
||||
switch (selection.strategyId) {
|
||||
case 'sma_crossover':
|
||||
return createSmaStrategy(selection);
|
||||
case 'mean_reversion':
|
||||
return createMeanReversionStrategy(selection);
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate dataset/cadence membership before opening the native session. */
|
||||
export function validateBuiltinStrategyBindings(
|
||||
selections: readonly BuiltinStrategySelection[],
|
||||
load: { config: ReplayConfig; manifest: Pick<HistoricalDatasetManifestV2, 'series'> }
|
||||
): void {
|
||||
const parsed = selections.map(selection => builtinStrategySelectionSchema.parse(selection));
|
||||
const owners = load.config.matching.owners;
|
||||
if (
|
||||
new Set(parsed.map(selection => selection.ownerId)).size !== parsed.length ||
|
||||
parsed.length !== owners.length ||
|
||||
owners.some(owner => owner.mode !== 'Target' || !parsed.some(s => s.ownerId === owner.ownerId))
|
||||
) {
|
||||
throw new Error('Canonical built-ins must exactly match target-mode owners');
|
||||
}
|
||||
for (const selection of parsed) {
|
||||
const series = load.manifest.series.find(item => item.id === selection.seriesId);
|
||||
const cadence = load.config.cadence.filter(item => item.owner_id === selection.ownerId);
|
||||
if (
|
||||
series?.instrumentId !== selection.instrumentId ||
|
||||
!load.config.matching.series.some(item => item.instrumentId === selection.instrumentId) ||
|
||||
cadence.length !== 1 ||
|
||||
!cadence[0]?.series_ids.includes(selection.seriesId)
|
||||
) {
|
||||
throw new Error('Canonical strategy requires its instrument/series in its owner cadence');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,259 @@
|
|||
import { z } from 'zod';
|
||||
import { trailingMean, trailingPopulationDeviation } from '@stock-bot/calculations/indicators';
|
||||
import { simpleReturns } from '@stock-bot/calculations/returns';
|
||||
import { parseFinancialDecimal, type FinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
meanReversionStrategySelectionSchema,
|
||||
type MeanReversionSignalParameters,
|
||||
type MeanReversionStrategySelection,
|
||||
} from '../contracts/builtin-strategy';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import { wholeShareTarget } from './canonical-sizing';
|
||||
|
||||
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const decimal = z.string().transform(value => parseFinancialDecimal(value));
|
||||
const nonnegative = decimal.refine(value => !value.startsWith('-'));
|
||||
const positive = nonnegative.refine(value => value !== '0.00000000');
|
||||
const zero = parseFinancialDecimal('0');
|
||||
const units = (value: FinancialDecimal) => BigInt(value.replace('.', ''));
|
||||
const historySize = (parameters: MeanReversionSignalParameters) =>
|
||||
Math.max(
|
||||
parameters.lookbackPeriod,
|
||||
parameters.trendPeriod,
|
||||
parameters.momentumPeriod + 1,
|
||||
parameters.volatilityPeriod + 1
|
||||
);
|
||||
|
||||
export interface MeanReversionStrategyState {
|
||||
version: 1;
|
||||
selectionKey: string;
|
||||
closes: number[];
|
||||
lastObservation: {
|
||||
eventTime: number;
|
||||
availableAt: number;
|
||||
sourceSequence: number;
|
||||
close: FinancialDecimal;
|
||||
volume: FinancialDecimal;
|
||||
} | null;
|
||||
targetQuantity: FinancialDecimal | null;
|
||||
}
|
||||
|
||||
/** Periods count admitted observations, never elapsed time. Gaps add no synthetic
|
||||
* bars. Returns are fractions and volatility is per-observation population
|
||||
* deviation of simple returns, not annualized or a calibrated regime model. */
|
||||
export function calculateMeanReversionSignals(
|
||||
closes: readonly number[],
|
||||
parameters: MeanReversionSignalParameters
|
||||
):
|
||||
| {
|
||||
mean: number;
|
||||
zScore: number;
|
||||
trendReturn: number;
|
||||
momentumReturn: number;
|
||||
volatility: number;
|
||||
regime: 'low' | 'high';
|
||||
}
|
||||
| undefined {
|
||||
const params = meanReversionStrategySelectionSchema.shape.parameters.parse(parameters);
|
||||
if (closes.some(close => !Number.isFinite(close) || close <= 0)) {
|
||||
throw new Error('Mean-reversion closes must be finite and positive');
|
||||
}
|
||||
if (closes.length < historySize(params)) {
|
||||
return undefined;
|
||||
}
|
||||
const mean = trailingMean(closes, params.lookbackPeriod);
|
||||
const deviation = trailingPopulationDeviation(closes, params.lookbackPeriod);
|
||||
const trendMean = trailingMean(closes, params.trendPeriod);
|
||||
const last = closes.at(-1);
|
||||
const lagged = closes.at(-1 - params.momentumPeriod);
|
||||
const volatility = trailingPopulationDeviation(
|
||||
simpleReturns(closes.slice(-params.volatilityPeriod - 1)),
|
||||
params.volatilityPeriod
|
||||
);
|
||||
if (
|
||||
mean === undefined ||
|
||||
deviation === undefined ||
|
||||
trendMean === undefined ||
|
||||
last === undefined ||
|
||||
lagged === undefined ||
|
||||
volatility === undefined
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const zScore = deviation === 0 ? 0 : (last - mean) / deviation;
|
||||
const trendReturn = mean / trendMean - 1;
|
||||
const momentumReturn = last / lagged - 1;
|
||||
if (![zScore, trendReturn, momentumReturn].every(Number.isFinite)) {
|
||||
throw new Error('Mean-reversion signal overflow');
|
||||
}
|
||||
return {
|
||||
mean,
|
||||
zScore,
|
||||
trendReturn,
|
||||
momentumReturn,
|
||||
volatility,
|
||||
regime: volatility <= params.maxVolatility ? 'low' : 'high',
|
||||
};
|
||||
}
|
||||
|
||||
/** Fixed-budget desired exposure only. Rust owns admission, fills, fees and risk. */
|
||||
export function createMeanReversionStrategy(
|
||||
input: MeanReversionStrategySelection
|
||||
): StrategyProgram<MeanReversionStrategyState> {
|
||||
const selection = meanReversionStrategySelectionSchema.parse(input);
|
||||
const parameters = selection.parameters;
|
||||
const selectionKey = JSON.stringify(selection);
|
||||
const size = historySize(parameters);
|
||||
const stateSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
selectionKey: z.literal(selectionKey),
|
||||
closes: z.array(z.number().finite().positive()).max(size),
|
||||
lastObservation: z
|
||||
.object({
|
||||
eventTime: time,
|
||||
availableAt: time,
|
||||
sourceSequence: counter,
|
||||
close: positive,
|
||||
volume: nonnegative,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.availableAt >= value.eventTime)
|
||||
.nullable(),
|
||||
targetQuantity: nonnegative.nullable(),
|
||||
})
|
||||
.strict()
|
||||
.refine(state => {
|
||||
if (!state.lastObservation) {
|
||||
return state.closes.length === 0 && state.targetQuantity === null;
|
||||
}
|
||||
return (
|
||||
state.closes.at(-1) === Number(state.lastObservation.close) &&
|
||||
(state.targetQuantity === null || state.closes.length === size)
|
||||
);
|
||||
}, 'Inconsistent mean-reversion checkpoint');
|
||||
|
||||
return {
|
||||
ownerId: selection.ownerId,
|
||||
strategyId: selection.strategyId,
|
||||
strategyVersion: selection.strategyVersion,
|
||||
seed: selection.seed,
|
||||
mode: 'target',
|
||||
initialState: {
|
||||
version: 1,
|
||||
selectionKey,
|
||||
closes: [],
|
||||
lastObservation: null,
|
||||
targetQuantity: null,
|
||||
},
|
||||
decide(context) {
|
||||
const nextState = stateSchema.parse(context.state);
|
||||
if (nextState.lastObservation && nextState.lastObservation.availableAt > context.now) {
|
||||
throw new Error('Mean-reversion checkpoint contains future observations');
|
||||
}
|
||||
let advanced = false;
|
||||
for (const observation of context.observations) {
|
||||
if (observation.series_id !== selection.seriesId) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
observation.instrument_id !== selection.instrumentId ||
|
||||
observation.available_at > context.now ||
|
||||
observation.event_time > observation.available_at ||
|
||||
observation.interval_end > observation.available_at ||
|
||||
observation.interval_start > observation.interval_end
|
||||
) {
|
||||
throw new Error('Mean-reversion observation binding or availability mismatch');
|
||||
}
|
||||
const previous = nextState.lastObservation;
|
||||
if (
|
||||
previous &&
|
||||
(observation.event_time < previous.eventTime ||
|
||||
(observation.event_time === previous.eventTime &&
|
||||
observation.source_sequence <= previous.sourceSequence))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const close = positive.parse(observation.close);
|
||||
const volume = nonnegative.parse(observation.volume);
|
||||
nextState.closes.push(Number(close));
|
||||
if (nextState.closes.length > size) {
|
||||
nextState.closes.shift();
|
||||
}
|
||||
nextState.lastObservation = {
|
||||
eventTime: time.parse(observation.event_time),
|
||||
availableAt: time.parse(observation.available_at),
|
||||
sourceSequence: counter.parse(observation.source_sequence),
|
||||
close,
|
||||
volume,
|
||||
};
|
||||
advanced = true;
|
||||
}
|
||||
const availability = context.barrier.inputs.find(
|
||||
item => item.series_id === selection.seriesId
|
||||
)?.availability;
|
||||
const fresh =
|
||||
typeof availability === 'object' && 'Fresh' in availability ? availability.Fresh : null;
|
||||
const last = nextState.lastObservation;
|
||||
const noTarget = () => ({ nextState, intent: { mode: 'target' as const, targets: [] } });
|
||||
if (
|
||||
!advanced ||
|
||||
!last ||
|
||||
!fresh ||
|
||||
fresh.event_time !== last.eventTime ||
|
||||
fresh.available_at !== last.availableAt
|
||||
) {
|
||||
return noTarget();
|
||||
}
|
||||
const signals = calculateMeanReversionSignals(nextState.closes, parameters);
|
||||
if (!signals) {
|
||||
return noTarget();
|
||||
}
|
||||
const owned = nonnegative.parse(
|
||||
context.positions.find(
|
||||
position =>
|
||||
position.ownerId === selection.ownerId &&
|
||||
position.instrumentId === selection.instrumentId
|
||||
)?.quantity ?? zero
|
||||
);
|
||||
if (nextState.targetQuantity === null && units(owned) > 0n) {
|
||||
nextState.targetQuantity = owned;
|
||||
}
|
||||
const desired = nextState.targetQuantity;
|
||||
if (desired === zero && units(owned) > 0n) {
|
||||
// A pending exit must not be cancelled by entry-only filters or a partial sell.
|
||||
} else if (
|
||||
signals.zScore >= -parameters.exitZScore &&
|
||||
(units(owned) > 0n || (desired !== null && units(desired) > 0n))
|
||||
) {
|
||||
nextState.targetQuantity = zero;
|
||||
} else {
|
||||
const canEnter =
|
||||
signals.zScore <= -parameters.entryZScore &&
|
||||
signals.trendReturn >= parameters.minTrendReturn &&
|
||||
signals.momentumReturn >= parameters.minMomentumReturn &&
|
||||
units(last.close) * units(last.volume) >=
|
||||
units(parameters.minNotionalVolume) * 100_000_000n &&
|
||||
(parameters.regimeFilter === 'none' || signals.volatility <= parameters.maxVolatility);
|
||||
if (desired !== null && units(desired) > 0n) {
|
||||
if (!canEnter) {
|
||||
nextState.targetQuantity = units(desired) < units(owned) ? desired : owned;
|
||||
}
|
||||
} else if (units(owned) === 0n && canEnter) {
|
||||
nextState.targetQuantity = wholeShareTarget(selection.ownerBudget, last.close);
|
||||
}
|
||||
}
|
||||
return {
|
||||
nextState,
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets:
|
||||
nextState.targetQuantity === null
|
||||
? []
|
||||
: [{ instrumentId: selection.instrumentId, quantity: nextState.targetQuantity }],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
10
apps/stock/orchestrator/src/strategies/canonical-sizing.ts
Normal file
10
apps/stock/orchestrator/src/strategies/canonical-sizing.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { parseFinancialDecimal, type FinancialDecimal } from '@stock-bot/types';
|
||||
|
||||
/** Whole-share desired exposure only; Rust admits orders, reserves fees and accounts for fills. */
|
||||
export function wholeShareTarget(
|
||||
budget: FinancialDecimal,
|
||||
price: FinancialDecimal
|
||||
): FinancialDecimal {
|
||||
const units = (value: FinancialDecimal) => BigInt(value.replace('.', ''));
|
||||
return parseFinancialDecimal((units(budget) / units(price)).toString());
|
||||
}
|
||||
|
|
@ -1,16 +1,12 @@
|
|||
import { z } from 'zod';
|
||||
import { movingAverageCrossover } from '@stock-bot/calculations/indicators';
|
||||
import { parseFinancialDecimal, type FinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
parseFinancialDecimal,
|
||||
type FinancialDecimal,
|
||||
type HistoricalDatasetManifestV2,
|
||||
} from '@stock-bot/types';
|
||||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
type BuiltinStrategySelection,
|
||||
smaStrategySelectionSchema,
|
||||
type SmaStrategySelection,
|
||||
} from '../contracts/builtin-strategy';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import type { ReplayConfig } from '../contracts/native-replay';
|
||||
import { wholeShareTarget } from './canonical-sizing';
|
||||
|
||||
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
|
|
@ -32,45 +28,11 @@ export interface SmaStrategyState {
|
|||
targetQuantity: FinancialDecimal | null;
|
||||
}
|
||||
|
||||
/** Validate dataset/cadence membership before opening the native session. */
|
||||
export function validateBuiltinStrategyBindings(
|
||||
selections: readonly BuiltinStrategySelection[],
|
||||
load: { config: ReplayConfig; manifest: Pick<HistoricalDatasetManifestV2, 'series'> }
|
||||
): void {
|
||||
const parsed = selections.map(selection => builtinStrategySelectionSchema.parse(selection));
|
||||
const owners = load.config.matching.owners;
|
||||
if (
|
||||
new Set(parsed.map(selection => selection.ownerId)).size !== parsed.length ||
|
||||
parsed.length !== owners.length ||
|
||||
owners.some(owner => owner.mode !== 'Target' || !parsed.some(s => s.ownerId === owner.ownerId))
|
||||
) {
|
||||
throw new Error('Canonical built-ins must exactly match target-mode owners');
|
||||
}
|
||||
for (const selection of parsed) {
|
||||
const series = load.manifest.series.find(item => item.id === selection.seriesId);
|
||||
const cadence = load.config.cadence.filter(item => item.owner_id === selection.ownerId);
|
||||
if (
|
||||
series?.instrumentId !== selection.instrumentId ||
|
||||
!load.config.matching.series.some(item => item.instrumentId === selection.instrumentId) ||
|
||||
cadence.length !== 1 ||
|
||||
!cadence[0]?.series_ids.includes(selection.seriesId)
|
||||
) {
|
||||
throw new Error('Canonical SMA requires its instrument/series in its owner cadence');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whole-share intent sizing only. Rust remains authoritative for all financial effects. */
|
||||
function desiredShares(budget: FinancialDecimal, price: FinancialDecimal): FinancialDecimal {
|
||||
const units = (value: FinancialDecimal) => BigInt(value.replace('.', ''));
|
||||
return parseFinancialDecimal((units(budget) / units(price)).toString());
|
||||
}
|
||||
|
||||
/** One explicitly versioned long-only program; legacy factories remain unchanged. */
|
||||
export function createBuiltinStrategy(
|
||||
selectionInput: BuiltinStrategySelection
|
||||
export function createSmaStrategy(
|
||||
selectionInput: SmaStrategySelection
|
||||
): StrategyProgram<SmaStrategyState> {
|
||||
const selection = builtinStrategySelectionSchema.parse(selectionInput);
|
||||
const selection = smaStrategySelectionSchema.parse(selectionInput);
|
||||
const { fastPeriod, slowPeriod } = selection.parameters;
|
||||
const selectionKey = JSON.stringify(selection);
|
||||
const stateSchema = z
|
||||
|
|
@ -183,7 +145,7 @@ export function createBuiltinStrategy(
|
|||
return { nextState, intent: { mode: 'target', targets: [] } };
|
||||
}
|
||||
if (nextState.lastCrossover === 'golden' && nextState.targetQuantity === null) {
|
||||
nextState.targetQuantity = desiredShares(selection.ownerBudget, last.close);
|
||||
nextState.targetQuantity = wholeShareTarget(selection.ownerBudget, last.close);
|
||||
}
|
||||
return {
|
||||
nextState,
|
||||
|
|
|
|||
|
|
@ -451,3 +451,19 @@ The existing ingestion service has no working producer for its legacy paper Sock
|
|||
Validation: `bun run check` passed build, source/contracts, 82 tooling, 43 utility, 44 calculation, 454 integration and 150 Rust tests (four manual tests ignored), plus lint. Full isolated PostgreSQL/Redis suite: **104 tests / 719 assertions**. Strict new-test TypeScript, scoped lint/format and diff checks passed. Final release addon matches this checkout's native library; **55 tests / 481 assertions** passed against it. No performance measurements were run. Exact commands, hashes and raw logs are in `manifest.json` → `seventeenth_wave_validation` and `/tmp/stock-bot-wave17.JfETUx/`.
|
||||
|
||||
Sandbox-only connection/child-process restrictions were rerun with escalation; only the exact stalled test process was stopped. Both exact disposable fixture containers were stopped after validation. Development services, worktrees and logs were retained. No S04 commit, push, PR, default cutover or trading activation occurred. The current trusted HTTP feed boundary still needs a real provider producer and operational calendars. **Next after acceptance/commit: S05**, a small composable multi-signal/regime strategy example; performance remains deferred. R01/R11 still need ADR-006.
|
||||
|
||||
|
||||
## Eighteenth-wave execution — 2026-10-23
|
||||
|
||||
S04 is accepted and committed as `75abae2`, superseding its uncommitted handoff above. S05 proceeds under its [pinned execution contract](backlog/tasks/S05.md#execution-contract--2026-10-23). Root owns shared selection/dispatch, integration and durable restart coverage; separate strategy and native-verification owners use worktrees under `/tmp/stock-bot-wave18.V1G17v/`, with independent review.
|
||||
|
||||
One new long-only mean-reversion program composes explicit trend/momentum/reversion filters and fixed per-observation volatility gating. Both regime/no-regime modes share warmup. Native target reconciliation handles partial entries and persistent exits; no TS accounting or Rust financial changes. R08 remains the gate for performance conclusions. Performance engineering, services, default cutover and trading activation remain out of scope.
|
||||
|
||||
|
||||
**Validated handoff:** S05 is `review` / `validated_uncommitted`. Twenty source/test/config files integrate one small canonical dispatcher, a distinct versioned mean-reversion program, shared exact desired-share sizing, native/worker verification and one durable restart regression. SMA calculations/checkpoint semantics and Rust financial code are unchanged. Independent G1/G2 review accepted the integrated source and public malformed-selection tests; strict final test types passed.
|
||||
|
||||
The [comparison example](../../apps/stock/orchestrator/examples/canonical-regime-research.ts) creates four explicit requests: volatility filter on/off under baseline and caller-supplied alternative costs. Inputs, versions, seeds and policies accompany native reports. It adds no experiment scheduler or optimizer. Periods count observed bars; volatility is not elapsed-time normalized. Initial owner budgets size desired shares and do not guarantee realized spend through gaps/fees. R08 remains necessary before conclusions about trading performance.
|
||||
|
||||
Validation: `bun run check` passed build/source/contracts, 82 tooling, 43 utility, 44 calculation, 479 integration and 150 Rust tests (four manual ignored), plus lint. The final added public-schema matrix passed separately. Full disposable PostgreSQL/Redis suite: **105 tests / 728 assertions**. Final strict new-test types, scoped lint/format and diff checks passed. **98 tests / 580 assertions** passed against the final release addon, including the added matrix, worker reports, SMA regressions and durable recovery. Exact commands, hashes and logs are recorded in `manifest.json` → `eighteenth_wave_validation` and `/tmp/stock-bot-wave18.V1G17v/`.
|
||||
|
||||
Only the two exact disposable test containers and identified sandbox-stalled verifier test processes were stopped; development resources, worktrees and logs remain. No S05 commit, push, PR, optimization, benchmark measurement, default cutover or trading activation occurred. Next after acceptance/commit: **R01 immutable strategy versions and R11 dataset workbench integration**, subject to the pending [ADR-006 research-product decision](architecture/decisions/006-research-product.md). Performance work remains deferred.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First sixteen waves committed; S04 is validated and awaiting acceptance/commit.** S03 is accepted as `c01e96e`. P08 remains deferred at the owner's request. S04 adds explicit canonical paper-feed custody, readiness and operator controls; the repository has no functioning vendor stream to claim as verified. Consult manifest execution_scope and [current wave](../ROADMAP.md#seventeenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated.
|
||||
**First seventeen waves committed; S05 is validated and awaiting acceptance/commit.** S04 is accepted as `75abae2`. P08 remains deferred at the owner's request. S05 adds a small composable mean-reversion/regime strategy on the canonical runtime; S04 still requires an external producer for operational feed readiness. Consult manifest execution_scope and [current wave](../ROADMAP.md#eighteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -55,8 +55,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [S01 Run deterministic TypeScript decisions on Rust sessions](tasks/S01.md) | P0 / done | F07, ADR-004, ADR-005 | — | TypeScript trading infrastructure / M |
|
||||
| [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / done | S01 | — | TypeScript strategy/quant engineering / M |
|
||||
| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / done | S01, C06, ADR-005 | — | Durable execution/Rust integration / L |
|
||||
| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / review | S02, S03 | — | TypeScript trading infrastructure / M |
|
||||
| [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / ready | S02, F08 | R08 | Quant strategy research / M |
|
||||
| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / done | S02, S03 | — | TypeScript trading infrastructure / M |
|
||||
| [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / review | S02, F08 | R08 | Quant strategy research / M |
|
||||
| [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / blocked | S03, S04, R05 | — | TypeScript trading infrastructure / M |
|
||||
|
||||
### E5 — Existing web backtest vertical slice
|
||||
|
|
@ -118,4 +118,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.
|
||||
|
||||
The first sixteen waves are committed. **S04 is validated and uncommitted; performance work is deferred by the owner.** S05 is also code/ADR-ready but outside this wave. R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation.
|
||||
The first seventeen waves are committed. **S05 is validated and uncommitted; performance work remains deferred by the owner.** R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation.
|
||||
|
|
|
|||
|
|
@ -1,20 +1,16 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-23.38",
|
||||
"plan_revision": "2026-10-23.40",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "seventeenth_wave_review",
|
||||
"plan_status": "eighteenth_wave_review",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: commit and continue after validated S03 handoff (2026-10-23). S03 accepted/committed c01e96e; S04 prerequisites satisfied. Performance work remains deferred.",
|
||||
"tasks": [
|
||||
"S04"
|
||||
"S05"
|
||||
],
|
||||
"permissions": [
|
||||
"accepted_wave16_commits",
|
||||
"isolated_implementation",
|
||||
"local_correctness_tests",
|
||||
"local_integration_review",
|
||||
"planning_progress_updates"
|
||||
"S05 isolated implementation, correctness tests, independent review and planning updates; S04 commit authorized and completed"
|
||||
],
|
||||
"excluded": [
|
||||
"performance_profiling_or_optimization",
|
||||
|
|
@ -30,6 +26,12 @@
|
|||
"ADR-006",
|
||||
"ADR-007",
|
||||
"ADR-008"
|
||||
],
|
||||
"exclusions": [
|
||||
"Performance profiling/optimization/benchmarks",
|
||||
"New-wave commits, push, PR or trading activation",
|
||||
"Default cutover or unapproved ADR policies",
|
||||
"Other backlog tasks"
|
||||
]
|
||||
},
|
||||
"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.",
|
||||
|
|
@ -1091,7 +1093,7 @@
|
|||
"epic": "E4",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "review",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"S02",
|
||||
"S03"
|
||||
|
|
@ -1111,12 +1113,12 @@
|
|||
"assignment": "/root/s04_controls_audit",
|
||||
"branch": "wave17/s04-control",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "75abae2cfc65229f65273bebc2ea9ef3148cce60",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"worktree": "/tmp/stock-bot-wave17.JfETUx/control",
|
||||
"integration_base": "c01e96e4dd2879d0c728e57b48f5b6172adecd0f",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"integration_state": "validated_committed",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/s04_feed_audit",
|
||||
|
|
@ -1142,7 +1144,7 @@
|
|||
"epic": "E4",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"S02",
|
||||
"F08"
|
||||
|
|
@ -1159,14 +1161,33 @@
|
|||
"write_locks": [
|
||||
"example-strategy"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"branch": null,
|
||||
"parallel_policy": "Root owns shared contracts/dispatcher and one durable restart test; strategy owner owns new program/direct tests; verifier owns disjoint replay fixture/native-worker tests; independent read-only review.",
|
||||
"assignment": "/root/s04_controls_audit",
|
||||
"branch": "wave18/s05-strategy",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [
|
||||
"R08"
|
||||
],
|
||||
"worktree": "/tmp/stock-bot-wave18.V1G17v/strategy",
|
||||
"integration_base": "75abae2cfc65229f65273bebc2ea9ef3148cce60",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/s04_controls_audit",
|
||||
"scope": "canonical-mean-reversion.ts and direct strategy tests",
|
||||
"worktree": "/tmp/stock-bot-wave18.V1G17v/strategy"
|
||||
},
|
||||
{
|
||||
"owner": "/root/s04_feed_audit",
|
||||
"scope": "canonical-regime-research fixture and native replay/worker verification",
|
||||
"worktree": "/tmp/stock-bot-wave18.V1G17v/verification"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "shared selection contract, dispatcher/import seam, durable restart test, example recipe and integration/planning"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -6093,7 +6114,7 @@
|
|||
"Explicit recoverPending acknowledgement permits original-time replay of already-admitted work; activation succeeds only after recovery and final readiness. No silent skipping or restamping."
|
||||
],
|
||||
"seventeenth_wave_validation": {
|
||||
"state": "validated_uncommitted",
|
||||
"state": "validated_committed",
|
||||
"work_root": "/tmp/stock-bot-wave17.JfETUx",
|
||||
"committed_before_implementation": {
|
||||
"S03": "c01e96e4dd2879d0c728e57b48f5b6172adecd0f"
|
||||
|
|
@ -6226,6 +6247,156 @@
|
|||
"d96d9a126e665226aeebc191b5b58e25eb29165cbabb4c099201f01e6364ef7f"
|
||||
]
|
||||
},
|
||||
"next": "Accept/commit S04, then S05 composable multi-signal/regime example. R01/R11 still need ADR-006; performance remains deferred."
|
||||
"next": "Accept/commit S04, then S05 composable multi-signal/regime example. R01/R11 still need ADR-006; performance remains deferred.",
|
||||
"completed_commit": "75abae2cfc65229f65273bebc2ea9ef3148cce60"
|
||||
},
|
||||
"eighteenth_wave": [
|
||||
"S05"
|
||||
],
|
||||
"eighteenth_wave_base": "75abae2cfc65229f65273bebc2ea9ef3148cce60",
|
||||
"eighteenth_wave_notes": [
|
||||
"User commit-and-continue authorizes S05 after S04 acceptance; performance remains deferred.",
|
||||
"Small second trusted TS built-in on the unchanged canonical Rust financial core; no general signal/regime framework or alpha claim.",
|
||||
"Source and decision tests may integrate before R08; research validation conclusions remain gated."
|
||||
],
|
||||
"eighteenth_wave_validation": {
|
||||
"state": "validated_uncommitted",
|
||||
"work_root": "/tmp/stock-bot-wave18.V1G17v",
|
||||
"committed_before_implementation": {
|
||||
"S04": "75abae2cfc65229f65273bebc2ea9ef3148cce60"
|
||||
},
|
||||
"scope": [
|
||||
"Distinct versioned trusted long-only mean-reversion strategy with ordinary trend/momentum/reversion/volatility functions",
|
||||
"Small exhaustive canonical built-in dispatcher; unchanged SMA semantics and shared exact desired-share sizing",
|
||||
"Existing native worker and opt-in paper composition accept either trusted built-in",
|
||||
"Four explicit regime/no-regime and alternative-cost diagnostic requests, retaining exact inputs/results",
|
||||
"Independent native ownership/risk/worker fixtures, public-schema matrix and one durable fractional recovery regression"
|
||||
],
|
||||
"source_integration": {
|
||||
"files": 20,
|
||||
"exact_hashes": {
|
||||
"apps/stock/orchestrator/examples/canonical-regime-research.ts": "e8dfb0868c01eeaa2477b4b9508fe0e3f43c0b2d8fdcf1d27eb6faffdcfe73c2",
|
||||
"apps/stock/orchestrator/src/backtest/native-worker.ts": "740bf6ba6f7a871a7e87efa53320cc93052cc5e7b8f7256417a40bfff2880435",
|
||||
"apps/stock/orchestrator/src/container.ts": "06b011668f39eefa62c1c94a3770af926ca8f30ceef9fc9cbc7f6d63c1c0ea45",
|
||||
"apps/stock/orchestrator/src/contracts/builtin-strategy.ts": "11f0be101bee4d7515de84fcb730e502f4f5092f6747f6edb0594e29f9335e00",
|
||||
"apps/stock/orchestrator/src/strategies/canonical-builtins.ts": "a91af8965c3e414c47a0d991e8fb4a5a784454c0a4c71dcb4cfbde884ab8c510",
|
||||
"apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts": "8ebd12b41e6e1d3e088d0a5309978986b45fc28ab3b1789394fc782149b65eaa",
|
||||
"apps/stock/orchestrator/src/strategies/canonical-sizing.ts": "cbc33976d2a5a94cfb676aedd510e327e740da19d8f8ca8a455447f73d5fb858",
|
||||
"apps/stock/orchestrator/src/strategies/canonical-sma.ts": "03a15b17537abca285e6082cc1da8f62c7be42a453cc69f32b7c378f9b888176",
|
||||
"test/fixtures/canonical-regime-research.ts": "49a03799c10b8731efc76b18cc81a166de66501cbb3a40e6a2dfbbd6c90d2e40",
|
||||
"test/fixtures/canonical-sma.ts": "bd1de6c04a70f82cda805e6f3b9703e5cbc9f79d7db8c118baaa10043b754928",
|
||||
"test/fixtures/canonical-strategy-worker.ts": "764e1b18980bec563803f8520552513cb50bcbc1cc0c3d1f4735f43f74468f32",
|
||||
"test/integration/canonical-builtins.test.ts": "57c65793f28ecb99aafe94998001cb0b3bd049bbafc8bb8aaceabbeef350dd0e",
|
||||
"test/integration/canonical-mean-reversion.test.ts": "be7be4a596dcefa4e58daec7a1ad9ef9fa941a809195c5787594f8900dc66026",
|
||||
"test/integration/canonical-regime-research.test.ts": "425b04ebd2d2beaf747a751b0b1cdc495000a4f1eabd4f9ca572bc2c21ebceea",
|
||||
"test/integration/canonical-sma.test.ts": "de2c27a56d7462ed7c979547adaee94172da275c1e16de73bcc89dea796b2953",
|
||||
"test/integration/canonical-strategy-worker.test.ts": "8ba7c2b087c5407719eb72942f1af28f6c79da82557dbf2a3f218cfa8771caf8",
|
||||
"test/integration/regime-research-example.test.ts": "e4037292c735aaae14e0a8052c45fff77c33e95ba21439fabf773dca1af645a6",
|
||||
"test/postgres/canonical-paper.test.ts": "8c3016116d6c32bb75becacf8e1ba8a850693cb4914df9a44867a8c3833f13e8",
|
||||
"test/postgres/paper-http.test.ts": "c944c207f325de5389732385446dcf741fecf9955635ea8937f8938f05a37c90",
|
||||
"tsconfig.check.json": "1e62c41351267b3690a00463f96300287a3e9bc88529ebd8d533289942a56589"
|
||||
},
|
||||
"source_archive": "/tmp/stock-bot-wave18.V1G17v/s05-integrated-source.tar",
|
||||
"source_archive_sha256": "a35ee1607ec524a49e1390b007cca9e5b034209812f14026c1da3adfab760570",
|
||||
"strategy_archive_sha256": "b3ab174254c2976c7ad8a24725dc5de5871e1d7a3780596525d8fa312cfce5b6",
|
||||
"verification_archive_sha256": "b652be55f6e22716fa7d29f6b370dd88ca486899ef22c919adb0a0912480d34a"
|
||||
},
|
||||
"review": {
|
||||
"reviewer": "/root/s03_review",
|
||||
"result": "G1/G2 accepted; pending strict test types subsequently passed",
|
||||
"findings_resolved": [
|
||||
"Persistent exit target0 precedes entry filters",
|
||||
"Fractional owned targets survive partial entry cancellation without rounding",
|
||||
"Blocked entry remainder is abandoned, not rebuilt while holding",
|
||||
"Both ablation modes retain identical observation-count warmup",
|
||||
"Exact new strategy version and malformed parameter/code rejection matrix"
|
||||
]
|
||||
},
|
||||
"checks": [
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"result": "passed; before final additional schema-matrix test and test-only assertion typing cleanup",
|
||||
"counts": {
|
||||
"tooling": 82,
|
||||
"utilities": 43,
|
||||
"calculations": 44,
|
||||
"integration": 479,
|
||||
"rust": 150,
|
||||
"rust_manual_ignored": 4
|
||||
},
|
||||
"log": "/tmp/stock-bot-wave18.V1G17v/integration-check.log"
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32819/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32820/15 bun run test:postgres",
|
||||
"result": "passed",
|
||||
"tests": 105,
|
||||
"assertions": 728,
|
||||
"log": "/tmp/stock-bot-wave18.V1G17v/integration-postgres.log"
|
||||
},
|
||||
{
|
||||
"command": "bunx tsc --project /tmp/stock-bot-wave18.V1G17v/root-tests-tsconfig.json --noEmit",
|
||||
"result": "passed on final integrated tests including public schema matrix",
|
||||
"log": "/tmp/stock-bot-wave18.V1G17v/root-tests-typecheck-final.log"
|
||||
},
|
||||
{
|
||||
"command": "Scoped ESLint --no-ignore --max-warnings0, Prettier --check and git diff --check; final schema-matrix test separately formatted/linted",
|
||||
"result": "passed",
|
||||
"logs": [
|
||||
"/tmp/stock-bot-wave18.V1G17v/integration-lint.log",
|
||||
"/tmp/stock-bot-wave18.V1G17v/integration-format.log"
|
||||
]
|
||||
},
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release",
|
||||
"result": "passed; addon equals local target/release/libengine.so",
|
||||
"log": "/tmp/stock-bot-wave18.V1G17v/integration-release-build.log"
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32819/stock_bot_safety bun test test/integration/canonical-builtins.test.ts test/integration/canonical-mean-reversion.test.ts test/integration/canonical-regime-research.test.ts test/integration/regime-research-example.test.ts test/integration/canonical-sma.test.ts test/integration/canonical-strategy-worker.test.ts test/postgres/canonical-paper.test.ts scripts/test/native-bindings.test.ts",
|
||||
"result": "passed on final release addon and final source/tests",
|
||||
"tests": 98,
|
||||
"assertions": 580,
|
||||
"log": "/tmp/stock-bot-wave18.V1G17v/integration-release-focused.log"
|
||||
}
|
||||
],
|
||||
"native": {
|
||||
"rust_source_unchanged": true,
|
||||
"final_profile": "release",
|
||||
"final_addon_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103",
|
||||
"local_library_matches": true,
|
||||
"performance_measurements": false
|
||||
},
|
||||
"economic_evidence": [
|
||||
"Two MR owners on one asset retain distinct grossPnl40/10 and fees1.80/1.00 under the explicit fixture",
|
||||
"Mixed SMA/MR real worker trace, projection and report equal direct native replay",
|
||||
"Insufficient funding and position limits still reject via Rust; no strategy bypass",
|
||||
"Partial native entries/exits and same-bar prevention match declared capacity/timing policies",
|
||||
"Every-step durable replacement preserves fractional0.5 holding, target cancellation, final cash1001.91 and fees0.09 exactly",
|
||||
"Four-trial illustrative comparison yields exact native accounting under explicit fee/slippage inputs; no alpha evidence claimed"
|
||||
],
|
||||
"environment_notes": [
|
||||
"Independent native build required escalation after sandbox spawnSync EPERM.",
|
||||
"Verifier sandbox IPC run stalled; exact identified processes3710409/3710825 stopped; outside-sandbox rerun passed.",
|
||||
"Verification fixture expectations corrected to existing terminal-bar no-callback and previous-completed-volume liquidity policies.",
|
||||
"Root example test changed malformed-rate fixture from semantic negative to malformed decimal: native remains financial-policy authority; test-only optional/decimal branding corrections passed strict compilation.",
|
||||
"No frontend or Python source changes; browser/Python gates not rerun. No profiling, benchmarks, optimization or trading operations."
|
||||
],
|
||||
"limitations": [
|
||||
"Illustrative fixed-threshold long-only strategy, not a fitted model or validated alpha; R08 gates walk-forward/holdout conclusions.",
|
||||
"Volatility uses per-observation adjacent simple returns; gaps are not filled or elapsed-time normalized.",
|
||||
"Owner budget sizes initial desired whole shares, not a guaranteed realized spend after gaps/fees; Rust account risk/cash remains authoritative.",
|
||||
"Example returns exact in-memory inputs/results but adds no durable experiment/artifact framework; R01/R05/R06 still own immutable code provenance and saved experiments.",
|
||||
"Legacy/default research paths and web selection remain unchanged; canonical paper is opt-in and still needs an external verified feed producer."
|
||||
],
|
||||
"cleanup": {
|
||||
"status": "completed",
|
||||
"development_resources_untouched": true,
|
||||
"worktrees_and_logs_retained": true,
|
||||
"stopped_container_ids": [
|
||||
"68be5fd0dd5266a8c45dafe6f0a00c74ac0a51ae269e626ad7faa2820f5e3ac0",
|
||||
"02b1fad58921c72a907668a0b46d10bbc26ecddbf6481e3bd6643026f9085927"
|
||||
]
|
||||
},
|
||||
"next": "Accept/commit S05; next product work R01/R11 requires pending ADR-006. Performance remains deferred; no other code/ADR-ready execution task is authorized by this handoff."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ Scheduling source of truth: [manifest entry S05](../manifest.json). No task is a
|
|||
|
||||
## Evidence and root cause
|
||||
|
||||
- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315).
|
||||
- **FIN-04 — Verified:** Native fills notify every strategy. TypeScript realized P&L uses aggregate symbol cost basis, not per-strategy cost basis. [apps/stock/engine/src/backtest/engine.rs:489](../../../../apps/stock/engine/src/backtest/engine.rs#L489); [apps/stock/orchestrator/src/execution/model.ts:108](../../../../apps/stock/orchestrator/src/execution/model.ts#L108).
|
||||
- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
|
||||
- **STR-01 — Reverified:** S01/S02 already provide an isolated owner context and trusted SMA program. `strategies/canonical-sma.ts` still contains the single-strategy factory/binding boundary; extract only that dispatch seam for a second program.
|
||||
- **FIN-04 — Addressed by F02/F04/F05:** Owner basis, cash, fees and target reconciliation are already canonical Rust behavior. Verify independent MR/SMA owners against it; do not recreate those calculations in TypeScript.
|
||||
- **RES-01 — Still relevant:** Experimental Python full-sample preprocessing is not research evidence. S05 uses explicit fixed per-observation thresholds and no fitting; R08 still gates validation/alpha claims.
|
||||
|
||||
## Intended behavior and implementation scope
|
||||
|
||||
|
|
@ -20,11 +20,13 @@ No unrelated refactor, new service or broker activation.
|
|||
|
||||
## Likely files and ownership
|
||||
|
||||
- apps/stock/orchestrator/src/strategies/builtin/
|
||||
- apps/stock/orchestrator/src/strategies/StrategyRegistry.ts
|
||||
- libs/calculations/
|
||||
- apps/stock/orchestrator/src/contracts/builtin-strategy.ts
|
||||
- apps/stock/orchestrator/src/strategies/canonical-{builtins,sizing,sma,mean-reversion}.ts
|
||||
- apps/stock/orchestrator/src/{container,backtest/native-worker}.ts
|
||||
- test/{integration,fixtures,postgres}/canonical-regime*.ts
|
||||
- Existing SMA/worker/paper test import sites and one runnable research example
|
||||
|
||||
Write locks: example-strategy. One agent owns this change. Lock names do not override actual overlapping files.
|
||||
Write locks: example-strategy. One program owner; root owns shared contracts/dispatch, and an independent verifier owns disjoint native fixtures/tests. Lock names do not override actual overlapping files.
|
||||
|
||||
## Dependencies and blockers
|
||||
|
||||
|
|
@ -56,3 +58,25 @@ Keep migrations additive and previous results readable. Do not add a switch that
|
|||
## Handoff
|
||||
|
||||
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
|
||||
|
||||
|
||||
## Execution contract — 2026-10-23
|
||||
|
||||
Base `75abae2` contains accepted S04. This wave adds `mean-reversion-regime-long-only/v1` as a distinct trusted canonical strategy; it does not reinterpret legacy mean-reversion or SMA versions. The existing native worker and opt-in paper composition use one small exhaustive built-in dispatcher. Preserve all existing financial, observation-clock and recovery contracts. No Rust, legacy strategy, generic feature framework, cache, optimizer, UI/default cutover or trading activation changes.
|
||||
|
||||
- Explicit parameters: price lookback >=2; longer trend period; momentum lag >=1; return-volatility window >=2; positive entry z threshold; nonnegative smaller exit z threshold; fractional trend/momentum floors >-1; nonnegative volatility ceiling; nonnegative decimal notional-volume minimum; `regimeFilter: volatility|none`. Owner budget remains an explicit decimal amount.
|
||||
- Pure signals reuse reviewed trailing mean/population deviation/simple returns: z=(latest-mean)/deviation (flat=0); trend=mean/longerMean-1; momentum=latest/laggedClose-1; volatility=population deviation of adjacent simple returns. Periods count observations, not elapsed time; gaps are not filled or time-normalized. Warmup is max(lookback,trend,momentum+1,volatility+1) in both ablation modes.
|
||||
- Entry is the conjunction z<=-entry, trend/momentum>=floors, close*volume>=minimum and volatility<=ceiling. `none` disables only the volatility gate. These are illustrative fixed parameters, not fitted evidence. No RSI or universal score type is needed.
|
||||
- Initial desired quantity is exact floor(ownerBudget/latestClose), without a forced minimum. Rust owns admission, available cash, fees, ownership, fills and all P&L. Retain a stable target while entry gates pass. If a gate fails, permanently cap the target to min(desired, actual owned quantity), abandoning unfilled buys; held fractional fills are preserved exactly. A flat owner may start a new eligible episode.
|
||||
- Exit z>=-exit is evaluated before entry gates. Target zero persists until the owner is flat, even during low volume/high volatility and partial exits. Never cancel an outstanding exit by replacing zero with held quantity. Empty target lists preserve prior commitments; explicit zero/owned targets invoke native reconciliation.
|
||||
- State is bounded detached JSON with exact selection/version binding, original observation identity, history and desired target. Future data rejects; duplicate/older delayed bars cannot rewrite evaluated history. Stale/missing/mismatched barriers may warm state but cannot emit a new target. Fresh decisions require the newest consumed observation to match the barrier.
|
||||
- Verification covers hand calculations and threshold equality, zero variance/warmup, every-prefix state continuation, suffix causality, native partial-fill/owner/risk oracles, mixed SMA/MR worker parity, one durable restart, repeated ablation inputs and explicit fee/slippage sensitivity. No claims of profitable alpha or out-of-sample validation before R08.
|
||||
|
||||
|
||||
## Validated handoff — 2026-10-23
|
||||
|
||||
Implementation and independent G1/G2 review accepted; manifest remains `review` until acceptance/commit. See [wave18 validation](../manifest.json) for exact source hashes, commands, economic oracles and limitations. Existing SMA version/selection serialization remains stable. The MR schema rejects legacy settings, unsupported versions and untrusted code fields.
|
||||
|
||||
Use `createBuiltinStrategy` from `strategies/canonical-builtins.ts` for either trusted canonical version. The new selection is `strategyId: mean_reversion`, `strategyVersion: mean-reversion-regime-long-only/v1`, with all parameters explicit. Both the existing native worker and opt-in canonical paper composition use that dispatcher; legacy/default APIs remain separate.
|
||||
|
||||
[The research example](../../../../apps/stock/orchestrator/examples/canonical-regime-research.ts) takes an existing `StrategyReplayRequest`, an existing `NativeBacktestWorker`, explicit alternative `{feeRate, slippageRate}` and an abort signal. `createRegimeComparisons` returns four detached requests for review; `runRegimeComparisons` executes them serially and returns exact requests/native reports. The caller owns worker lifecycle and artifact/result retention. This is a reproducible diagnostic recipe, not a validation/optimization or saved-experiment framework. No model or code artifact provenance guarantee replaces pending R01/R05/R06.
|
||||
|
|
|
|||
107
test/fixtures/canonical-regime-research.ts
vendored
Normal file
107
test/fixtures/canonical-regime-research.ts
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import {
|
||||
meanReversionStrategySelectionSchema,
|
||||
type BuiltinStrategySelection,
|
||||
type MeanReversionSignalParameters,
|
||||
type MeanReversionStrategySelection,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { nativeReplayFixture } from './native-replay';
|
||||
|
||||
export function canonicalRegimeSelection(
|
||||
ownerId = 'A',
|
||||
options: {
|
||||
ownerBudget?: string;
|
||||
parameters?: Partial<MeanReversionSignalParameters>;
|
||||
} = {}
|
||||
): MeanReversionStrategySelection {
|
||||
return meanReversionStrategySelectionSchema.parse({
|
||||
ownerId,
|
||||
strategyId: 'mean_reversion',
|
||||
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
||||
seed: 42,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: options.ownerBudget ?? '80',
|
||||
parameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0,
|
||||
minTrendReturn: -0.9,
|
||||
minMomentumReturn: -0.9,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: '0',
|
||||
regimeFilter: 'volatility',
|
||||
...options.parameters,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Small economic oracle, not a profitable-strategy claim: with the default
|
||||
* selection, the third completed close8 requests ten shares, filled at next
|
||||
* open7. The fifth close10 requests flat, filled at next open11. Gross40,
|
||||
* fees1.80 at1%, final equity10038.20. No unobserved close is executable. */
|
||||
export function canonicalRegimeResearchFixture(
|
||||
options: {
|
||||
selections?: readonly BuiltinStrategySelection[];
|
||||
closes?: readonly number[];
|
||||
opens?: readonly number[];
|
||||
volumes?: readonly number[];
|
||||
availabilitySteps?: readonly number[];
|
||||
tradeStartStep?: number;
|
||||
feeRate?: string;
|
||||
slippageRate?: string;
|
||||
} = {}
|
||||
) {
|
||||
const closes = options.closes ?? [10, 10, 8, 7, 10, 10];
|
||||
const opens = options.opens ?? [10, 10, 10, 7, 9, 11];
|
||||
if (
|
||||
opens.length !== closes.length ||
|
||||
(options.volumes && options.volumes.length !== closes.length) ||
|
||||
(options.availabilitySteps && options.availabilitySteps.length !== closes.length)
|
||||
) {
|
||||
throw new Error('Research fixture columns must have equal lengths');
|
||||
}
|
||||
const selections = options.selections ?? [canonicalRegimeSelection()];
|
||||
const fixture = nativeReplayFixture(
|
||||
closes.length,
|
||||
1,
|
||||
selections.map(item => item.ownerId)
|
||||
);
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
fixture.dataset.manifest;
|
||||
const dataset = createDatasetV2({
|
||||
metadata: {
|
||||
calendars,
|
||||
series,
|
||||
executionSeries,
|
||||
bounds: {
|
||||
...bounds,
|
||||
tradeStart: fixture.start + (options.tradeStartStep ?? 1) * fixture.minute,
|
||||
},
|
||||
universe,
|
||||
corporateActions,
|
||||
},
|
||||
bars: fixture.dataset.bars.map((bar, index) => {
|
||||
const open = opens[index]!,
|
||||
close = closes[index]!;
|
||||
return {
|
||||
seriesId: bar.seriesId,
|
||||
timestamp: bar.intervalStart,
|
||||
availableAt:
|
||||
fixture.start + (options.availabilitySteps?.[index] ?? index + 1) * fixture.minute,
|
||||
sourceSequence: bar.sourceSequence,
|
||||
open,
|
||||
high: Math.max(open, close),
|
||||
low: Math.min(open, close),
|
||||
close,
|
||||
volume: options.volumes?.[index] ?? 1000,
|
||||
};
|
||||
}),
|
||||
});
|
||||
fixture.config.matching.risk.feeRate = options.feeRate ?? '0.01';
|
||||
fixture.config.matching.slippageRate = options.slippageRate ?? '0';
|
||||
return { ...fixture, dataset, selections: [...selections] };
|
||||
}
|
||||
4
test/fixtures/canonical-sma.ts
vendored
4
test/fixtures/canonical-sma.ts
vendored
|
|
@ -1,4 +1,4 @@
|
|||
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { nativeReplayFixture } from './native-replay';
|
||||
|
||||
|
|
@ -48,7 +48,7 @@ export function canonicalSmaFixture(
|
|||
}),
|
||||
});
|
||||
const selections = owners.map(ownerId =>
|
||||
builtinStrategySelectionSchema.parse({
|
||||
smaStrategySelectionSchema.parse({
|
||||
ownerId,
|
||||
strategyId: 'sma',
|
||||
strategyVersion: 'sma-crossover-long-only/v1',
|
||||
|
|
|
|||
2
test/fixtures/canonical-strategy-worker.ts
vendored
2
test/fixtures/canonical-strategy-worker.ts
vendored
|
|
@ -4,7 +4,7 @@ import { strategyReplayRequestSchema } from '../../apps/stock/orchestrator/src/c
|
|||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
|
||||
function send(message: unknown): Promise<void> {
|
||||
return new Promise((resolve, reject) =>
|
||||
|
|
|
|||
44
test/integration/canonical-builtins.test.ts
Normal file
44
test/integration/canonical-builtins.test.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
|
||||
|
||||
test('canonical mean-reversion selection requires its exact version and explicit compatible parameters', () => {
|
||||
const selection = canonicalRegimeSelection();
|
||||
for (const alias of ['mean_reversion', 'mean-reversion', ' Mean Reversion ']) {
|
||||
expect(builtinStrategySelectionSchema.parse({ ...selection, strategyId: alias })).toEqual(
|
||||
selection
|
||||
);
|
||||
}
|
||||
const { maxVolatility: _ceiling, ...missing } = selection.parameters;
|
||||
for (const patch of [
|
||||
{ strategyId: 'sma' },
|
||||
{ strategyVersion: 'mean-reversion/v2' },
|
||||
{ strategyVersion: 'mean-reversion-regime-long-only/v2' },
|
||||
{ ownerBudget: '0' },
|
||||
{ ownerBudget: '-1' },
|
||||
{ ownerBudget: 'invalid' },
|
||||
{ parameters: missing },
|
||||
{ parameters: {} },
|
||||
{ parameters: { ...selection.parameters, lookbackPeriod: 1 } },
|
||||
{ parameters: { ...selection.parameters, trendPeriod: 2 } },
|
||||
{ parameters: { ...selection.parameters, momentumPeriod: 0 } },
|
||||
{ parameters: { ...selection.parameters, volatilityPeriod: 1 } },
|
||||
{ parameters: { ...selection.parameters, entryZScore: 0 } },
|
||||
{ parameters: { ...selection.parameters, exitZScore: 1 } },
|
||||
{ parameters: { ...selection.parameters, minTrendReturn: -1 } },
|
||||
{ parameters: { ...selection.parameters, minMomentumReturn: -1 } },
|
||||
{ parameters: { ...selection.parameters, maxVolatility: Infinity } },
|
||||
{ parameters: { ...selection.parameters, maxVolatility: -0.01 } },
|
||||
{ parameters: { ...selection.parameters, minNotionalVolume: '-1' } },
|
||||
{ parameters: { ...selection.parameters, minNotionalVolume: 'invalid' } },
|
||||
{ parameters: { ...selection.parameters, regimeFilter: 'fitted' } },
|
||||
{ parameters: { ...selection.parameters, rsiOversold: 30 } },
|
||||
{ parameters: { ...selection.parameters, quantity: 10 } },
|
||||
{ parameters: { ...selection.parameters, maxPositionQuantity: '99999' } },
|
||||
{ initialState: {} },
|
||||
{ source: 'return buy()' },
|
||||
{ decide: () => ({}) },
|
||||
]) {
|
||||
expect(() => builtinStrategySelectionSchema.parse({ ...selection, ...patch })).toThrow();
|
||||
}
|
||||
});
|
||||
462
test/integration/canonical-mean-reversion.test.ts
Normal file
462
test/integration/canonical-mean-reversion.test.ts
Normal file
|
|
@ -0,0 +1,462 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
meanReversionStrategySelectionSchema,
|
||||
type MeanReversionSignalParameters,
|
||||
type MeanReversionStrategySelection,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/builtin-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 {
|
||||
calculateMeanReversionSignals,
|
||||
createMeanReversionStrategy,
|
||||
type MeanReversionStrategyState,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-mean-reversion';
|
||||
|
||||
const d = parseFinancialDecimal;
|
||||
function selection(
|
||||
parameters: Partial<MeanReversionSignalParameters> = {},
|
||||
patch: Partial<MeanReversionStrategySelection> = {}
|
||||
) {
|
||||
return meanReversionStrategySelectionSchema.parse({
|
||||
ownerId: 'A',
|
||||
strategyId: 'mean_reversion',
|
||||
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
||||
seed: 7,
|
||||
instrumentId: 'X',
|
||||
seriesId: 'X:bar',
|
||||
ownerBudget: '80',
|
||||
parameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0.2,
|
||||
minTrendReturn: -0.9,
|
||||
minMomentumReturn: -0.9,
|
||||
maxVolatility: 10,
|
||||
minNotionalVolume: '0',
|
||||
regimeFilter: 'volatility',
|
||||
...parameters,
|
||||
},
|
||||
...patch,
|
||||
});
|
||||
}
|
||||
function observation(
|
||||
close: string,
|
||||
sequence: number,
|
||||
patch: Partial<PublishedObservation> = {}
|
||||
): PublishedObservation {
|
||||
return {
|
||||
series_id: 'X:bar',
|
||||
instrument_id: 'X',
|
||||
interval_start: sequence,
|
||||
interval_end: sequence + 1,
|
||||
event_time: sequence + 1,
|
||||
available_at: sequence + 1,
|
||||
source_sequence: sequence,
|
||||
open: d(close),
|
||||
high: d(close),
|
||||
low: d(close),
|
||||
close: d(close),
|
||||
volume: d('100'),
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
function position(ownerId = 'A', quantity = '2.5', instrumentId = 'X') {
|
||||
return {
|
||||
ownerId,
|
||||
instrumentId,
|
||||
quantity: d(quantity),
|
||||
remainingCost: d('0'),
|
||||
realizedGrossPnl: d('0'),
|
||||
};
|
||||
}
|
||||
function context(
|
||||
state: MeanReversionStrategyState,
|
||||
observations: PublishedObservation[],
|
||||
patch: Partial<StrategyContext<MeanReversionStrategyState>> = {}
|
||||
): StrategyContext<MeanReversionStrategyState> {
|
||||
const last = observations.at(-1);
|
||||
const now = last?.available_at ?? state.lastObservation?.availableAt ?? 0;
|
||||
const riskSession = { calendarId: 'test', calendarRevision: '1', sessionId: 'test', startsAt: 0 };
|
||||
return {
|
||||
ownerId: 'A',
|
||||
strategyId: 'mean_reversion',
|
||||
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
||||
decisionSequence: 0,
|
||||
now,
|
||||
barrier: {
|
||||
barrier_id: 'test',
|
||||
at: now,
|
||||
revision: 0,
|
||||
owner_ids: ['A'],
|
||||
observation_count: observations.length,
|
||||
inputs: [
|
||||
{
|
||||
series_id: 'X:bar',
|
||||
availability: last
|
||||
? { Fresh: { event_time: last.event_time, available_at: last.available_at } }
|
||||
: 'Missing',
|
||||
},
|
||||
],
|
||||
},
|
||||
portfolio: {
|
||||
admissionRevision: 0,
|
||||
equity: d('10000'),
|
||||
availableCash: d('10000'),
|
||||
orders: [],
|
||||
reservations: [],
|
||||
portfolio: {
|
||||
version: 1,
|
||||
sessionId: 'test',
|
||||
accountId: 'test',
|
||||
revision: 0,
|
||||
baseCurrency: 'USD',
|
||||
reserveOwnerId: 'reserve',
|
||||
cash: d('10000'),
|
||||
positions: [],
|
||||
fees: [],
|
||||
riskSession,
|
||||
},
|
||||
risk: {
|
||||
dailyBaseline: d('10000'),
|
||||
peakEquity: d('10000'),
|
||||
dailyHalted: false,
|
||||
drawdownHalted: false,
|
||||
riskSession,
|
||||
lastEventTime: now,
|
||||
},
|
||||
},
|
||||
positions: [],
|
||||
observations,
|
||||
previousAdmission: null,
|
||||
state,
|
||||
random: () => {
|
||||
throw new Error('Mean reversion must not consume randomness');
|
||||
},
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
function decide(
|
||||
program: StrategyProgram<MeanReversionStrategyState>,
|
||||
closes: string[],
|
||||
state = program.initialState,
|
||||
offset = 0,
|
||||
patch: Partial<StrategyContext<MeanReversionStrategyState>> = {}
|
||||
) {
|
||||
return program.decide(
|
||||
context(
|
||||
state,
|
||||
closes.map((close, i) => observation(close, offset + i)),
|
||||
patch
|
||||
)
|
||||
);
|
||||
}
|
||||
const target = (quantity: string) => ({
|
||||
mode: 'target' as const,
|
||||
targets: [{ instrumentId: 'X', quantity: d(quantity) }],
|
||||
});
|
||||
const none = { mode: 'target' as const, targets: [] };
|
||||
|
||||
test('signal_composition_units use population deviation, fractional returns and inclusive volatility regimes', () => {
|
||||
const params = selection().parameters;
|
||||
const signals = calculateMeanReversionSignals([100, 110, 99], params)!;
|
||||
expect(signals.mean).toBe(104.5);
|
||||
expect(signals.zScore).toBe(-1);
|
||||
expect(signals.trendReturn).toBeCloseTo(104.5 / 103 - 1, 12);
|
||||
expect(signals.momentumReturn).toBeCloseTo(-0.1, 12);
|
||||
expect(signals.volatility).toBeCloseTo(0.1, 12);
|
||||
expect(
|
||||
calculateMeanReversionSignals([100, 110, 99], { ...params, maxVolatility: signals.volatility })!
|
||||
.regime
|
||||
).toBe('low');
|
||||
expect(
|
||||
calculateMeanReversionSignals([100, 110, 99], {
|
||||
...params,
|
||||
maxVolatility: signals.volatility - 1e-10,
|
||||
})!.regime
|
||||
).toBe('high');
|
||||
expect(calculateMeanReversionSignals([10, 10, 10], params)).toEqual({
|
||||
mean: 10,
|
||||
zScore: 0,
|
||||
trendReturn: 0,
|
||||
momentumReturn: 0,
|
||||
volatility: 0,
|
||||
regime: 'low',
|
||||
});
|
||||
for (const close of [0, -1, Number.NaN, Infinity]) {
|
||||
expect(() => calculateMeanReversionSignals([10, 10, close], params)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('both ablation modes require identical complete warmup and flat prices create no entry', () => {
|
||||
for (const regimeFilter of ['none', 'volatility'] as const) {
|
||||
const selected = selection({ momentumPeriod: 4, volatilityPeriod: 6, regimeFilter });
|
||||
expect(
|
||||
calculateMeanReversionSignals([10, 10, 10, 10, 10, 10], selected.parameters)
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
calculateMeanReversionSignals([10, 10, 10, 10, 10, 10, 10], selected.parameters)
|
||||
).toBeDefined();
|
||||
const program = createMeanReversionStrategy(selected);
|
||||
expect(decide(program, ['10', '10', '10', '10', '10', '8']).intent).toEqual(none);
|
||||
expect(decide(program, ['10', '10', '10', '10', '10', '10', '10']).intent).toEqual(none);
|
||||
}
|
||||
});
|
||||
|
||||
test('inclusive entry conjunction uses exact notional volume and a fixed whole-share budget', () => {
|
||||
const signals = calculateMeanReversionSignals([100, 110, 99], selection().parameters)!;
|
||||
const parameters = {
|
||||
minTrendReturn: signals.trendReturn,
|
||||
minMomentumReturn: signals.momentumReturn,
|
||||
maxVolatility: signals.volatility,
|
||||
minNotionalVolume: d('198'),
|
||||
};
|
||||
const run = (overrides: Partial<MeanReversionSignalParameters> = {}) => {
|
||||
const program = createMeanReversionStrategy(
|
||||
selection({ ...parameters, ...overrides }, { ownerBudget: d('990') })
|
||||
);
|
||||
return program.decide(
|
||||
context(
|
||||
program.initialState,
|
||||
[100, 110, 99].map((close, i) => observation(String(close), i, { volume: d('2') }))
|
||||
)
|
||||
);
|
||||
};
|
||||
expect(run().intent).toEqual(target('10'));
|
||||
for (const changed of [
|
||||
{ entryZScore: 1.00001 },
|
||||
{ minTrendReturn: signals.trendReturn + 1e-6 },
|
||||
{ minMomentumReturn: signals.momentumReturn + 1e-6 },
|
||||
{ minNotionalVolume: d('198.00000001') },
|
||||
{ maxVolatility: signals.volatility - 1e-6 },
|
||||
]) {
|
||||
expect(run(changed).intent).toEqual(none);
|
||||
}
|
||||
expect(run({ maxVolatility: 0, regimeFilter: 'none' }).intent).toEqual(target('10'));
|
||||
expect(
|
||||
run({ maxVolatility: 0, regimeFilter: 'none', minNotionalVolume: d('199') }).intent
|
||||
).toEqual(none);
|
||||
const poor = createMeanReversionStrategy(selection({}, { ownerBudget: d('7.99') }));
|
||||
expect(decide(poor, ['10', '10', '8']).intent).toEqual(target('0'));
|
||||
const exact = createMeanReversionStrategy(
|
||||
selection(
|
||||
{ entryZScore: 0.5, minNotionalVolume: d('900000000.00000003') },
|
||||
{ ownerBudget: d('0.0000003') }
|
||||
)
|
||||
);
|
||||
const rows = ['0.00000005', '0.00000005', '0.00000003'].map((close, i) =>
|
||||
observation(close, i, { volume: d('30000000000000001') })
|
||||
);
|
||||
expect(exact.decide(context(exact.initialState, rows)).intent).toEqual(target('10'));
|
||||
const insufficient = structuredClone(rows);
|
||||
insufficient[2]!.volume = d('30000000000000000');
|
||||
expect(exact.decide(context(exact.initialState, insufficient)).intent).toEqual(none);
|
||||
});
|
||||
|
||||
test('only the final fresh prefix can create intent; intermediate entry or exit signals have no phantom effect', () => {
|
||||
const program = createMeanReversionStrategy(selection());
|
||||
expect(decide(program, ['10', '10', '8', '10']).intent).toEqual(none);
|
||||
const entered = decide(program, ['10', '10', '8']);
|
||||
expect(entered.intent).toEqual(target('10'));
|
||||
// Intermediate 12 would exit, but it was not a decision barrier.
|
||||
expect(
|
||||
decide(program, ['12', '7'], entered.nextState, 3, { positions: [position('A', '10')] }).intent
|
||||
).toEqual(target('10'));
|
||||
});
|
||||
|
||||
test('future suffix changes cannot alter earlier state or decisions; observed gaps do not synthesize history', () => {
|
||||
const program = createMeanReversionStrategy(selection());
|
||||
const prefix = ['10', '10', '8'];
|
||||
const trace = (suffix: string[]) => {
|
||||
let state = program.initialState;
|
||||
return [...prefix, ...suffix].map((close, index) => {
|
||||
const result = decide(program, [close], state, index);
|
||||
state = result.nextState;
|
||||
return result;
|
||||
});
|
||||
};
|
||||
expect(trace(['7', '10']).slice(0, 3)).toEqual(trace(['700', '0.01']).slice(0, 3));
|
||||
const regular = decide(program, prefix);
|
||||
const gaps = program.decide(
|
||||
context(
|
||||
program.initialState,
|
||||
prefix.map((close, i) => observation(close, i * 1000))
|
||||
)
|
||||
);
|
||||
expect(gaps.intent).toEqual(regular.intent);
|
||||
expect(gaps.nextState.closes).toEqual(regular.nextState.closes);
|
||||
});
|
||||
|
||||
test('stale, missing or mismatched availability only advances history; delayed and duplicate physical bars cannot rewrite it', () => {
|
||||
const program = createMeanReversionStrategy(selection());
|
||||
const entered = decide(program, ['10', '10', '8']);
|
||||
for (const availability of [
|
||||
'Missing',
|
||||
{ Stale: { event_time: 4, available_at: 4 } },
|
||||
{ Fresh: { event_time: 400, available_at: 400 } },
|
||||
] as const) {
|
||||
const input = context(entered.nextState, [observation('12', 3)]);
|
||||
const result = program.decide({
|
||||
...input,
|
||||
barrier: { ...input.barrier, inputs: [{ series_id: 'X:bar', availability }] },
|
||||
});
|
||||
expect(result.intent).toEqual(none);
|
||||
expect(result.nextState.targetQuantity).toBe(d('10'));
|
||||
expect(result.nextState.closes).toEqual([10, 8, 12]);
|
||||
}
|
||||
const delayed = program.decide(
|
||||
context(entered.nextState, [observation('0.01', 1, { available_at: 10 })], { now: 10 })
|
||||
);
|
||||
expect(delayed.nextState).toEqual(entered.nextState);
|
||||
expect(delayed.intent).toEqual(none);
|
||||
expect(program.decide(context(entered.nextState, [observation('80', 2)])).nextState).toEqual(
|
||||
entered.nextState
|
||||
);
|
||||
expect(program.decide(context(entered.nextState, [])).intent).toEqual(none);
|
||||
for (const row of [
|
||||
observation('7', 3, { available_at: 99 }),
|
||||
observation('7', 3, { event_time: 99 }),
|
||||
observation('7', 3, { instrument_id: 'OTHER' }),
|
||||
]) {
|
||||
expect(() => program.decide(context(entered.nextState, [row], { now: 4 }))).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('entry-only filters cannot block exit or cancel a partially filled exit target', () => {
|
||||
const program = createMeanReversionStrategy(
|
||||
selection({ maxVolatility: 0.15, minNotionalVolume: d('1') })
|
||||
);
|
||||
const entered = decide(program, ['10', '10', '8']);
|
||||
const exit = program.decide(
|
||||
context(entered.nextState, [observation('12', 3, { volume: d('0') })], {
|
||||
positions: [position('A', '2.5')],
|
||||
})
|
||||
);
|
||||
expect(exit.intent).toEqual(target('0'));
|
||||
const partial = program.decide(
|
||||
context(exit.nextState, [observation('1', 4, { volume: d('0') })], {
|
||||
positions: [position('A', '1.25')],
|
||||
})
|
||||
);
|
||||
expect(partial.intent).toEqual(target('0'));
|
||||
expect(partial.nextState.targetQuantity).toBe(d('0'));
|
||||
});
|
||||
|
||||
test('failed entry gates cancel unfilled remainder permanently; fractional owned exposure does not rebuild on recovery', () => {
|
||||
const program = createMeanReversionStrategy(selection({ minNotionalVolume: d('1') }));
|
||||
const entered = decide(program, ['10', '10', '8']);
|
||||
const rejected = decide(program, ['7'], entered.nextState, 3, {
|
||||
previousAdmission: {
|
||||
decision: {
|
||||
ownerId: 'A',
|
||||
decisionId: 'A:0',
|
||||
sequence: 0,
|
||||
},
|
||||
revision: 1,
|
||||
orders: [
|
||||
{
|
||||
orderId: 'denied-entry',
|
||||
instrumentId: 'X',
|
||||
decision: { ownerId: 'A', decisionId: 'A:0', sequence: 0 },
|
||||
status: { Rejected: 'InsufficientCash' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(rejected.intent).toEqual(target('10'));
|
||||
for (const owned of ['0', '2.5']) {
|
||||
const clipped = program.decide(
|
||||
context(entered.nextState, [observation('7', 3, { volume: d('0') })], {
|
||||
positions: owned === '0' ? [] : [position('A', owned)],
|
||||
})
|
||||
);
|
||||
expect(clipped.intent).toEqual(target(owned));
|
||||
const recovered = decide(program, ['6'], clipped.nextState, 4, {
|
||||
positions: owned === '0' ? [] : [position('A', owned)],
|
||||
});
|
||||
expect(recovered.intent).toEqual(target(owned === '0' ? '13' : '2.5'));
|
||||
}
|
||||
});
|
||||
|
||||
test('trend, momentum, volatility and z-score entry failures also cap pending exposure to actual holdings', () => {
|
||||
const cases: {
|
||||
parameters: Partial<MeanReversionSignalParameters>;
|
||||
prefix: string[];
|
||||
next: string;
|
||||
}[] = [
|
||||
{ parameters: { minTrendReturn: -0.05 }, prefix: ['10', '10', '8'], next: '7' },
|
||||
{ parameters: { minMomentumReturn: -0.3 }, prefix: ['10', '10', '8'], next: '4' },
|
||||
{ parameters: { maxVolatility: 0.15 }, prefix: ['10', '10', '8'], next: '1' },
|
||||
{
|
||||
parameters: { lookbackPeriod: 3, trendPeriod: 4 },
|
||||
prefix: ['10', '10', '10', '8'],
|
||||
next: '7.5',
|
||||
},
|
||||
];
|
||||
for (const { parameters, prefix, next } of cases) {
|
||||
const program = createMeanReversionStrategy(selection(parameters));
|
||||
const entered = decide(program, prefix);
|
||||
expect(entered.intent).toEqual(target('10'));
|
||||
expect(
|
||||
decide(program, [next], entered.nextState, prefix.length, {
|
||||
positions: [position('A', '2.5')],
|
||||
}).intent
|
||||
).toEqual(target('2.5'));
|
||||
}
|
||||
});
|
||||
|
||||
test('owner isolation adopts only existing owned exposure and never pyramids another owner quantity', () => {
|
||||
const program = createMeanReversionStrategy(selection({ minNotionalVolume: d('1000000') }));
|
||||
expect(
|
||||
decide(program, ['10', '10', '8'], program.initialState, 0, {
|
||||
positions: [position('B', '99')],
|
||||
}).intent
|
||||
).toEqual(none);
|
||||
expect(
|
||||
decide(program, ['10', '10', '8'], program.initialState, 0, {
|
||||
positions: [position('B', '99'), position('A', '3.25')],
|
||||
}).intent
|
||||
).toEqual(target('3.25'));
|
||||
expect(
|
||||
decide(program, ['10', '8', '10'], program.initialState, 0, {
|
||||
positions: [position('A', '3.25')],
|
||||
}).intent
|
||||
).toEqual(target('0'));
|
||||
});
|
||||
|
||||
test('checkpoint validation and detachment preserve inputs, reject incompatible state, and bound retained history', () => {
|
||||
const selected = selection();
|
||||
const program = createMeanReversionStrategy(selected);
|
||||
selected.parameters.entryZScore = 99;
|
||||
const initial = structuredClone(program.initialState);
|
||||
const entered = decide(program, ['10', '10', '8']);
|
||||
expect(entered.intent).toEqual(target('10'));
|
||||
expect(program.initialState).toEqual(initial);
|
||||
const restored = JSON.parse(JSON.stringify(entered.nextState)) as MeanReversionStrategyState;
|
||||
expect(decide(createMeanReversionStrategy(selection()), ['7'], restored, 3)).toEqual(
|
||||
decide(program, ['7'], entered.nextState, 3)
|
||||
);
|
||||
for (const state of [
|
||||
{ ...restored, version: 2 },
|
||||
{ ...restored, selectionKey: 'other' },
|
||||
{ ...restored, closes: [] },
|
||||
{ ...restored, targetQuantity: d('-1') },
|
||||
{ ...restored, unknown: true },
|
||||
]) {
|
||||
expect(() => decide(program, ['7'], state as MeanReversionStrategyState, 3)).toThrow();
|
||||
}
|
||||
expect(() => program.decide(context(restored, [], { now: 1 }))).toThrow('future');
|
||||
const next = decide(program, ['7', '6', '5', '4'], restored, 3);
|
||||
expect(next.nextState.closes).toEqual([6, 5, 4]);
|
||||
next.nextState.closes[0] = 999;
|
||||
expect(restored.closes).toEqual([10, 10, 8]);
|
||||
expect(() =>
|
||||
decide(createMeanReversionStrategy(selection({}, { ownerId: 'B' })), ['7'], restored, 3)
|
||||
).toThrow();
|
||||
});
|
||||
417
test/integration/canonical-regime-research.test.ts
Normal file
417
test/integration/canonical-regime-research.test.ts
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal, type FinancialStrategyIntent } from '@stock-bot/types';
|
||||
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 type {
|
||||
StrategyContext,
|
||||
StrategyProgram,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type {
|
||||
ReplayProjectionResult,
|
||||
ReplayReportResult,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategy-replay';
|
||||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import {
|
||||
canonicalRegimeResearchFixture,
|
||||
canonicalRegimeSelection,
|
||||
} from '../fixtures/canonical-regime-research';
|
||||
|
||||
const d = parseFinancialDecimal;
|
||||
type Fixture = ReturnType<typeof canonicalRegimeResearchFixture>;
|
||||
type DecisionRecord = {
|
||||
ownerId: string;
|
||||
at: number;
|
||||
sequence: number;
|
||||
observed: { eventTime: number; availableAt: number; close: string }[];
|
||||
positions: StrategyContext['positions'];
|
||||
portfolio: StrategyContext['portfolio'];
|
||||
state: unknown;
|
||||
intent: FinancialStrategyIntent;
|
||||
};
|
||||
|
||||
function run(fixture: Fixture, eventBudget = 1) {
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
validateBuiltinStrategyBindings(fixture.selections, load);
|
||||
const records: DecisionRecord[] = [];
|
||||
const programs = fixture.selections.map(selection => {
|
||||
const strategy = createBuiltinStrategy(selection);
|
||||
return {
|
||||
...strategy,
|
||||
decide(context: StrategyContext) {
|
||||
const output = strategy.decide(context);
|
||||
records.push({
|
||||
ownerId: context.ownerId,
|
||||
at: context.now,
|
||||
sequence: context.decisionSequence,
|
||||
observed: context.observations.map(row => ({
|
||||
eventTime: row.event_time,
|
||||
availableAt: row.available_at,
|
||||
close: row.close,
|
||||
})),
|
||||
positions: context.positions,
|
||||
portfolio: context.portfolio,
|
||||
state: structuredClone(output.nextState),
|
||||
intent: structuredClone(output.intent),
|
||||
});
|
||||
return output;
|
||||
},
|
||||
} satisfies StrategyProgram;
|
||||
});
|
||||
return {
|
||||
...runStrategyReplay(load, programs, { resultFormat: 'report', eventBudget }),
|
||||
records,
|
||||
};
|
||||
}
|
||||
|
||||
function economicHash(result: ReplayProjectionResult | ReplayReportResult): string {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify({ projection: result.projection, view: result.view }))
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
function target(record: DecisionRecord) {
|
||||
return record.intent.mode === 'target' ? record.intent.targets[0]?.quantity : undefined;
|
||||
}
|
||||
|
||||
test('MR hand oracle buys and exits at next opens with authoritative basis, commissions and terminal equity', () => {
|
||||
const fixture = canonicalRegimeResearchFixture();
|
||||
const result = run(fixture);
|
||||
expect(
|
||||
result.records.filter(row => row.at < fixture.start + 3 * fixture.minute).map(target)
|
||||
).toEqual([undefined, undefined]);
|
||||
expect(target(result.records.find(row => row.at === fixture.start + 3 * fixture.minute)!)).toBe(
|
||||
d('10')
|
||||
);
|
||||
expect(
|
||||
result.result.projection.fills.map(fill => ({
|
||||
at: fill.eventTime,
|
||||
quantity: fill.quantityDelta,
|
||||
price: fill.price,
|
||||
fee: fill.fee.amount,
|
||||
releasedBasis: fill.releasedBasis,
|
||||
realizedGrossPnl: fill.realizedGrossPnl,
|
||||
}))
|
||||
).toEqual([
|
||||
{
|
||||
at: fixture.start + 3 * fixture.minute,
|
||||
quantity: d('10'),
|
||||
price: d('7'),
|
||||
fee: d('0.7'),
|
||||
releasedBasis: d('0'),
|
||||
realizedGrossPnl: d('0'),
|
||||
},
|
||||
{
|
||||
at: fixture.start + 5 * fixture.minute,
|
||||
quantity: d('-10'),
|
||||
price: d('11'),
|
||||
fee: d('1.1'),
|
||||
releasedBasis: d('70'),
|
||||
realizedGrossPnl: d('40'),
|
||||
},
|
||||
]);
|
||||
expect(result.result.projection.valuation).toMatchObject({
|
||||
cash: d('10038.2'),
|
||||
equity: d('10038.2'),
|
||||
markedHoldings: d('0'),
|
||||
remainingCost: d('0'),
|
||||
realizedGrossPnl: d('40'),
|
||||
fees: d('1.8'),
|
||||
});
|
||||
expect(result.diagnostics.strategies[0]!.state).toMatchObject({ targetQuantity: d('0') });
|
||||
});
|
||||
|
||||
test('two differently configured MR owners share native portfolio barriers but retain independent history, inventory, basis and fees', () => {
|
||||
const fixture = canonicalRegimeResearchFixture({
|
||||
selections: [
|
||||
canonicalRegimeSelection('B', {
|
||||
ownerBudget: '35',
|
||||
parameters: { lookbackPeriod: 3, trendPeriod: 4 },
|
||||
}),
|
||||
canonicalRegimeSelection('A'),
|
||||
],
|
||||
});
|
||||
const result = run(fixture);
|
||||
const beforeExit = result.records.filter(row => row.at === fixture.start + 5 * fixture.minute);
|
||||
expect(beforeExit).toHaveLength(2);
|
||||
expect(beforeExit[0]!.portfolio).toBe(beforeExit[1]!.portfolio);
|
||||
expect(
|
||||
beforeExit.map(row => [
|
||||
row.ownerId,
|
||||
row.positions.map(position => [position.ownerId, position.quantity, position.remainingCost]),
|
||||
])
|
||||
).toEqual([
|
||||
['B', [['B', d('5'), d('45')]]],
|
||||
['A', [['A', d('10'), d('70')]]],
|
||||
]);
|
||||
expect(
|
||||
result.result.projection.fills.map(fill => [
|
||||
fill.ownerId,
|
||||
fill.quantityDelta,
|
||||
fill.price,
|
||||
fill.releasedBasis,
|
||||
])
|
||||
).toEqual([
|
||||
['A', d('10'), d('7'), d('0')],
|
||||
['B', d('5'), d('9'), d('0')],
|
||||
['A', d('-10'), d('11'), d('70')],
|
||||
['B', d('-5'), d('11'), d('45')],
|
||||
]);
|
||||
expect(
|
||||
result.result.projection.valuation.owners
|
||||
.filter(owner => owner.ownerId !== 'reserve')
|
||||
.map(owner => [owner.ownerId, owner.realizedGrossPnl, owner.fees, owner.remainingCost])
|
||||
).toEqual([
|
||||
['A', d('40'), d('1.8'), d('0')],
|
||||
['B', d('10'), d('1'), d('0')],
|
||||
]);
|
||||
expect(result.result.projection.valuation.equity).toBe(d('10047.2'));
|
||||
const [a, b] = result.diagnostics.strategies;
|
||||
// The terminal close marks equity; tradeEnd itself does not create another decision.
|
||||
expect(a!.state).toMatchObject({ closes: [8, 7, 10], targetQuantity: d('0') });
|
||||
expect(b!.state).toMatchObject({ closes: [10, 8, 7, 10], targetQuantity: d('0') });
|
||||
expect(a!.state).not.toEqual(b!.state);
|
||||
expect(
|
||||
result.records.every(row => row.positions.every(position => position.ownerId === row.ownerId))
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test.each(['trace', 'projection', 'report'] as const)(
|
||||
'actual %s worker supports mixed MR/SMA selections with the same native decisions and finance as direct replay',
|
||||
async resultFormat => {
|
||||
const fixture = canonicalRegimeResearchFixture({
|
||||
selections: [
|
||||
canonicalRegimeSelection('A'),
|
||||
smaStrategySelectionSchema.parse({
|
||||
ownerId: 'B',
|
||||
strategyId: 'sma',
|
||||
strategyVersion: 'sma-crossover-long-only/v1',
|
||||
seed: 43,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '30',
|
||||
parameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
}),
|
||||
],
|
||||
});
|
||||
const input = strategyReplayRequestSchema.parse({
|
||||
type: 'runStrategyReplay',
|
||||
version: 1,
|
||||
dataset: fixture.dataset,
|
||||
config: fixture.config,
|
||||
strategies: fixture.selections,
|
||||
eventBudget: 2,
|
||||
resultFormat,
|
||||
});
|
||||
const load = prepareReplayLoad(fixture.dataset, input.config);
|
||||
const expected = runStrategyReplay(load, input.strategies.map(createBuiltinStrategy), {
|
||||
resultFormat,
|
||||
eventBudget: 1,
|
||||
});
|
||||
const worker = new NativeBacktestWorker();
|
||||
const output = await worker.execute(input, new AbortController().signal, () => {});
|
||||
const parsed = parseStrategyReplayResult(output, {
|
||||
strategies: input.strategies,
|
||||
identity: load.identity,
|
||||
policy: input.config,
|
||||
format: resultFormat,
|
||||
});
|
||||
expect(parsed.result).toEqual(expected.result);
|
||||
expect(parsed.strategies.map(item => [item.ownerId, item.strategyId])).toEqual([
|
||||
['A', 'mean_reversion'],
|
||||
['B', 'sma_crossover'],
|
||||
]);
|
||||
expect(
|
||||
parsed.result.view.portfolio.positions.find(position => position.ownerId === 'B')
|
||||
).toMatchObject({ quantity: d('3'), remainingCost: d('33') });
|
||||
if ('projection' in parsed.result) {
|
||||
expect(parsed.result.projection.valuation).toMatchObject({
|
||||
equity: d('10034.87'),
|
||||
fees: d('2.13'),
|
||||
remainingCost: d('33'),
|
||||
unrealizedPnl: d('-3'),
|
||||
});
|
||||
}
|
||||
if (resultFormat === 'report') {
|
||||
expect(await worker.execute(input, new AbortController().signal, () => {})).toBe(output);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
test('fee-inclusive cash and portfolio risk rejections remain Rust authority for MR targets', () => {
|
||||
for (const mode of ['fee-funding', 'position-limit'] as const) {
|
||||
const fixture = canonicalRegimeResearchFixture();
|
||||
if (mode === 'fee-funding') {
|
||||
fixture.config.matching.risk.ledger.initialCapital = '80';
|
||||
} else {
|
||||
fixture.config.matching.risk.maxPositionQuantity = '5';
|
||||
}
|
||||
const result = run(fixture);
|
||||
expect(result.records.some(row => target(row) === d('10'))).toBe(true);
|
||||
expect(result.result.projection.fills).toEqual([]);
|
||||
expect(result.result.projection.valuation).toMatchObject({
|
||||
cash: d(mode === 'fee-funding' ? '80' : '10000'),
|
||||
fees: d('0'),
|
||||
remainingCost: d('0'),
|
||||
});
|
||||
const trace = runStrategyReplay(
|
||||
prepareReplayLoad(fixture.dataset, fixture.config),
|
||||
fixture.selections.map(createBuiltinStrategy),
|
||||
{ resultFormat: 'trace' }
|
||||
);
|
||||
expect(JSON.stringify(trace.result.receipts)).toContain(
|
||||
mode === 'fee-funding' ? 'InsufficientCash' : 'PositionSize'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('partial entry commitments are cancelled when gates fail, never rebuilt while held, and low-volume exits still fill', () => {
|
||||
const fixture = canonicalRegimeResearchFixture({
|
||||
selections: [canonicalRegimeSelection('A', { parameters: { minNotionalVolume: d('200') } })],
|
||||
closes: [10, 10, 8, 7, 6, 10, 10, 10],
|
||||
opens: [10, 10, 10, 7, 6, 9, 11, 11],
|
||||
volumes: [1000, 1000, 30, 10, 1000, 10, 1000, 1000],
|
||||
});
|
||||
// Native Open mode uses previously available completed volume: 30*.1 fills
|
||||
// three shares, then the later low-volume exit fills one and two at11.
|
||||
fixture.config.participation_rate = '0.1';
|
||||
const result = run(fixture);
|
||||
expect(
|
||||
result.records.filter(row => row.at >= fixture.start + 3 * fixture.minute).map(target)
|
||||
).toEqual([d('10'), d('3'), d('3'), d('0'), d('0')]);
|
||||
expect(result.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])).toEqual([
|
||||
[d('3'), d('7')],
|
||||
[d('-1'), d('11')],
|
||||
[d('-2'), d('11')],
|
||||
]);
|
||||
expect(result.result.projection.valuation).toMatchObject({
|
||||
equity: d('10011.46'),
|
||||
fees: d('0.54'),
|
||||
remainingCost: d('0'),
|
||||
});
|
||||
});
|
||||
|
||||
test('future suffix mutations cannot alter earlier MR decisions, observation availability or held inventory', () => {
|
||||
const original = canonicalRegimeResearchFixture();
|
||||
const mutated = canonicalRegimeResearchFixture({
|
||||
closes: [10, 10, 8, 7, 1, 500],
|
||||
opens: [10, 10, 10, 7, 80, 100],
|
||||
});
|
||||
expect(mutated.dataset.manifest.hash).not.toBe(original.dataset.manifest.hash);
|
||||
const baseline = run(original),
|
||||
changed = run(mutated);
|
||||
const prefix = (records: DecisionRecord[]) =>
|
||||
records
|
||||
.filter(row => row.at <= original.start + 4 * original.minute)
|
||||
.map(({ ownerId, at, sequence, observed, positions, state, intent }) => ({
|
||||
ownerId,
|
||||
at,
|
||||
sequence,
|
||||
observed,
|
||||
positions,
|
||||
state,
|
||||
intent,
|
||||
}));
|
||||
expect(prefix(changed.records)).toEqual(prefix(baseline.records));
|
||||
for (const row of [...baseline.records, ...changed.records]) {
|
||||
expect(row.observed.every(observation => observation.availableAt <= row.at)).toBe(true);
|
||||
}
|
||||
expect(
|
||||
changed.result.projection.fills.filter(
|
||||
fill => fill.eventTime <= original.start + 3 * original.minute
|
||||
)
|
||||
).toEqual(
|
||||
baseline.result.projection.fills.filter(
|
||||
fill => fill.eventTime <= original.start + 3 * original.minute
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
test('fixed versioned inputs reproduce identical strategy state, economic hashes and native finance across event budgets', () => {
|
||||
const fixture = canonicalRegimeResearchFixture();
|
||||
const before = JSON.stringify(fixture);
|
||||
const first = run(fixture, 1),
|
||||
second = run(fixture, 64),
|
||||
third = run(canonicalRegimeResearchFixture(), 3);
|
||||
expect(JSON.stringify(fixture)).toBe(before);
|
||||
expect(second.result).toEqual(first.result);
|
||||
expect(third.result).toEqual(first.result);
|
||||
expect(second.diagnostics).toEqual(first.diagnostics);
|
||||
expect(third.diagnostics).toEqual(first.diagnostics);
|
||||
expect(economicHash(second.result)).toBe(economicHash(first.result));
|
||||
expect(economicHash(third.result)).toBe(economicHash(first.result));
|
||||
});
|
||||
|
||||
test('no-regime ablation changes only the volatility entry gate and retains identical observation warmup', () => {
|
||||
const filtered = canonicalRegimeSelection('A', { parameters: { maxVolatility: 0.05 } });
|
||||
const unfiltered = canonicalRegimeSelection('A', {
|
||||
parameters: { maxVolatility: 0.05, regimeFilter: 'none' },
|
||||
});
|
||||
expect(unfiltered).toEqual({
|
||||
...filtered,
|
||||
parameters: { ...filtered.parameters, regimeFilter: 'none' },
|
||||
});
|
||||
const filteredFixture = canonicalRegimeResearchFixture({ selections: [filtered] });
|
||||
const unfilteredFixture = canonicalRegimeResearchFixture({ selections: [unfiltered] });
|
||||
expect(filteredFixture.dataset.manifest.hash).toBe(unfilteredFixture.dataset.manifest.hash);
|
||||
expect(filteredFixture.config).toEqual(unfilteredFixture.config);
|
||||
const withRegime = run(filteredFixture),
|
||||
withoutRegime = run(unfilteredFixture);
|
||||
expect(withRegime.records.map(row => [row.at, row.observed])).toEqual(
|
||||
withoutRegime.records.map(row => [row.at, row.observed])
|
||||
);
|
||||
expect(withRegime.records.slice(0, 2).map(target)).toEqual([undefined, undefined]);
|
||||
expect(withoutRegime.records.slice(0, 2).map(target)).toEqual([undefined, undefined]);
|
||||
expect(withRegime.records[2]!.state).toMatchObject({ closes: [10, 10, 8] });
|
||||
expect(withoutRegime.records[2]!.state).toMatchObject({ closes: [10, 10, 8] });
|
||||
expect(target(withRegime.records[2]!)).toBeUndefined();
|
||||
expect(target(withoutRegime.records[2]!)).toBe(d('10'));
|
||||
expect(withRegime.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])).toEqual([
|
||||
[d('11'), d('9')],
|
||||
[d('-11'), d('11')],
|
||||
]);
|
||||
expect(
|
||||
withoutRegime.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])
|
||||
).toEqual([
|
||||
[d('10'), d('7')],
|
||||
[d('-10'), d('11')],
|
||||
]);
|
||||
});
|
||||
|
||||
test('fixed fee and slippage alternatives retain provenance and give hand-computed native cost sensitivity', () => {
|
||||
const recipes = [
|
||||
{ feeRate: '0', slippageRate: '0', equity: '10040', fees: '0', prices: ['7', '11'] },
|
||||
{ feeRate: '0.01', slippageRate: '0', equity: '10038.2', fees: '1.8', prices: ['7', '11'] },
|
||||
{
|
||||
feeRate: '0.01',
|
||||
slippageRate: '0.01',
|
||||
equity: '10036.404',
|
||||
fees: '1.796',
|
||||
prices: ['7.07', '10.89'],
|
||||
},
|
||||
];
|
||||
const baseline = canonicalRegimeResearchFixture();
|
||||
for (const recipe of recipes) {
|
||||
const fixture = canonicalRegimeResearchFixture(recipe);
|
||||
expect(fixture.dataset.manifest.hash).toBe(baseline.dataset.manifest.hash);
|
||||
expect(fixture.selections).toEqual(baseline.selections);
|
||||
const result = run(fixture);
|
||||
expect(result.result.projection.valuation).toMatchObject({
|
||||
equity: d(recipe.equity),
|
||||
fees: d(recipe.fees),
|
||||
});
|
||||
expect(result.result.projection.fills.map(fill => fill.price)).toEqual(recipe.prices.map(d));
|
||||
expect(economicHash(run(canonicalRegimeResearchFixture(recipe)).result)).toBe(
|
||||
economicHash(result.result)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
@ -7,7 +7,8 @@ import {
|
|||
} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
type BuiltinStrategySelection,
|
||||
smaStrategySelectionSchema,
|
||||
type SmaStrategySelection,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import type {
|
||||
StrategyContext,
|
||||
|
|
@ -16,16 +17,16 @@ import type {
|
|||
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';
|
||||
import { validateBuiltinStrategyBindings } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
createSmaStrategy as createBuiltinStrategy,
|
||||
type SmaStrategyState,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const d = parseFinancialDecimal;
|
||||
function selection(overrides: Partial<BuiltinStrategySelection> = {}) {
|
||||
return builtinStrategySelectionSchema.parse({
|
||||
function selection(overrides: Partial<SmaStrategySelection> = {}) {
|
||||
return smaStrategySelectionSchema.parse({
|
||||
...canonicalSmaFixture().selections[0],
|
||||
...overrides,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import {
|
|||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
function request(resultFormat: ReplayResultFormat = 'trace', owners = ['A']) {
|
||||
|
|
|
|||
110
test/integration/regime-research-example.test.ts
Normal file
110
test/integration/regime-research-example.test.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
createRegimeComparisons,
|
||||
runRegimeComparisons,
|
||||
} from '../../apps/stock/orchestrator/examples/canonical-regime-research';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import type { StrategyReplayRequest } from '../../apps/stock/orchestrator/src/contracts/strategy-replay';
|
||||
import {
|
||||
canonicalRegimeResearchFixture,
|
||||
canonicalRegimeSelection,
|
||||
} from '../fixtures/canonical-regime-research';
|
||||
|
||||
function request(): StrategyReplayRequest {
|
||||
const fixture = canonicalRegimeResearchFixture({
|
||||
selections: [canonicalRegimeSelection('A', { parameters: { maxVolatility: 0.05 } })],
|
||||
});
|
||||
return {
|
||||
type: 'runStrategyReplay',
|
||||
version: 1,
|
||||
dataset: fixture.dataset,
|
||||
config: fixture.config,
|
||||
strategies: fixture.selections,
|
||||
eventBudget: 2,
|
||||
resultFormat: 'report',
|
||||
};
|
||||
}
|
||||
const costs = { feeRate: '0.02', slippageRate: '0.01' };
|
||||
|
||||
test('comparison inputs are detached, explicit and differ only by declared filter/cost changes', () => {
|
||||
const input = request();
|
||||
const original = structuredClone(input);
|
||||
const trials = createRegimeComparisons(input, costs);
|
||||
expect(trials.map(trial => trial.label)).toEqual([
|
||||
'volatility',
|
||||
'none',
|
||||
'volatility-alternative-costs',
|
||||
'none-alternative-costs',
|
||||
]);
|
||||
const [on, off, higherOn, higherOff] = trials.map(trial => structuredClone(trial.request));
|
||||
for (const candidate of [on!, off!, higherOn!, higherOff!]) {
|
||||
expect(candidate.dataset).toEqual(original.dataset);
|
||||
expect(candidate.strategies[0]!.strategyVersion).toBe('mean-reversion-regime-long-only/v1');
|
||||
const strategy = candidate.strategies[0]!;
|
||||
if (strategy.strategyId === 'mean_reversion') {
|
||||
strategy.parameters.regimeFilter = 'volatility';
|
||||
}
|
||||
candidate.config.matching.risk.feeRate = parseFinancialDecimal('0.01');
|
||||
candidate.config.matching.slippageRate = parseFinancialDecimal('0');
|
||||
}
|
||||
expect(off!).toEqual(on!);
|
||||
expect(higherOn!).toEqual(on!);
|
||||
expect(higherOff!).toEqual(on!);
|
||||
trials[0]!.request.config.matching.risk.ledger.accountId = 'changed';
|
||||
expect(input).toEqual(original);
|
||||
expect(trials[1]!.request.config.matching.risk.ledger.accountId).toBe(
|
||||
original.config.matching.risk.ledger.accountId
|
||||
);
|
||||
});
|
||||
|
||||
test('malformed costs and cancellation cannot submit a trial', async () => {
|
||||
let calls = 0;
|
||||
const worker = {
|
||||
execute: async () => {
|
||||
calls++;
|
||||
throw new Error('unexpected submit');
|
||||
},
|
||||
};
|
||||
await expect(
|
||||
runRegimeComparisons(
|
||||
worker,
|
||||
request(),
|
||||
{ ...costs, feeRate: 'invalid' },
|
||||
new AbortController().signal
|
||||
)
|
||||
).rejects.toThrow();
|
||||
const controller = new AbortController();
|
||||
controller.abort(new Error('cancelled'));
|
||||
await expect(runRegimeComparisons(worker, request(), costs, controller.signal)).rejects.toThrow(
|
||||
'cancelled'
|
||||
);
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
test('four actual worker reports preserve exact inputs and reproduce the small economic oracle', async () => {
|
||||
const input = request();
|
||||
const result = await runRegimeComparisons(
|
||||
new NativeBacktestWorker(),
|
||||
input,
|
||||
costs,
|
||||
new AbortController().signal
|
||||
);
|
||||
expect(result).toHaveLength(4);
|
||||
expect(result.map(trial => trial.result.result.view.equity)).toEqual(
|
||||
['10019.80000000', '10038.20000000', '10015.40440000', '10034.60800000'].map(
|
||||
parseFinancialDecimal
|
||||
)
|
||||
);
|
||||
expect(result.map(trial => trial.result.strategies)).toEqual(
|
||||
result.map(trial => trial.request.strategies)
|
||||
);
|
||||
expect(
|
||||
await runRegimeComparisons(
|
||||
new NativeBacktestWorker(),
|
||||
input,
|
||||
costs,
|
||||
new AbortController().signal
|
||||
)
|
||||
).toEqual(result);
|
||||
});
|
||||
|
|
@ -20,7 +20,7 @@ import type {
|
|||
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-sma';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import {
|
||||
canonicalConfig,
|
||||
counterProgram,
|
||||
|
|
@ -835,6 +835,68 @@ describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => {
|
|||
expect(filled.some(order => order.order.side === 'buy')).toBe(true);
|
||||
expect(filled.some(order => order.order.side === 'sell')).toBe(true);
|
||||
});
|
||||
test('canonical regime strategy retains fractional entry cancellation and exit through every durable restart', async () => {
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
ownerId: 'A',
|
||||
strategyId: 'mean_reversion',
|
||||
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
||||
seed: 7,
|
||||
instrumentId: 'X',
|
||||
seriesId: 'X:quote',
|
||||
ownerBudget: '80',
|
||||
parameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0,
|
||||
minTrendReturn: -0.5,
|
||||
minMomentumReturn: -0.5,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: '1',
|
||||
regimeFilter: 'volatility',
|
||||
},
|
||||
});
|
||||
const run = async (restart: boolean) => {
|
||||
const f = await fixture(canonicalConfig(), [createBuiltinStrategy(selection)]);
|
||||
let host = f.host;
|
||||
await send(host, openInput());
|
||||
for (const [index, close] of ['10', '10', '8', '7', '10', '10'].entries()) {
|
||||
const mark = markInput(index + 1, ['A'], close);
|
||||
if (index >= 3) {
|
||||
mark.observations[0]!.volume = parseFinancialDecimal('0');
|
||||
}
|
||||
await send(host, mark);
|
||||
if (restart) {
|
||||
host = await f.make({ programs: [createBuiltinStrategy(selection)] });
|
||||
}
|
||||
if (index === 3) {
|
||||
expect((await host.snapshot()).owners[0]!.diagnostic.state).toMatchObject({
|
||||
targetQuantity: parseFinancialDecimal('0.5'),
|
||||
});
|
||||
}
|
||||
const price = ['10', '10', '7', '9', '11', '10'][index]!;
|
||||
await send(host, quoteInput(index + 1, index === 2 ? '0.5' : '100', price));
|
||||
if (restart) {
|
||||
host = await f.make({ programs: [createBuiltinStrategy(selection)] });
|
||||
}
|
||||
}
|
||||
return { snapshot: await host.snapshot(), journal: await host.journal() };
|
||||
};
|
||||
const uninterrupted = await run(false);
|
||||
expect(await run(true)).toEqual(uninterrupted);
|
||||
const view = uninterrupted.snapshot.account.view;
|
||||
expect(view.portfolio.cash).toBe(parseFinancialDecimal('1001.91'));
|
||||
expect(view.equity).toBe(parseFinancialDecimal('1001.91'));
|
||||
const position = view.portfolio.positions.find(position => position.ownerId === 'A')!;
|
||||
expect(position.quantity).toBe(parseFinancialDecimal('0'));
|
||||
expect(position.remainingCost).toBe(parseFinancialDecimal('0'));
|
||||
expect(position.realizedGrossPnl).toBe(parseFinancialDecimal('2'));
|
||||
expect(view.portfolio.fees.find(fee => fee.ownerId === 'A')!.amount).toBe(
|
||||
parseFinancialDecimal('0.09')
|
||||
);
|
||||
});
|
||||
test('a native failed admission prefix atomically makes its durable batch terminal', async () => {
|
||||
const max = '792281625142643375935.43950335';
|
||||
const config = ordersConfig();
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/pa
|
|||
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 { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
type OrchestratorServices,
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@
|
|||
"apps/stock/**/src/**/*.tsx",
|
||||
"tools/**/src/**/*.ts",
|
||||
"apps/stock/orchestrator/examples/multi-strategy-backtest.ts",
|
||||
"apps/stock/orchestrator/examples/canonical-regime-research.ts",
|
||||
"libs/core/services/test/contracts.type-test.ts"
|
||||
],
|
||||
"exclude": ["node_modules", "**/dist/**", "**/*.test.ts", "**/*.spec.ts"]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue