feat(strategies): publish type-only strategy authoring API (CL31)
This commit is contained in:
parent
a411f9a665
commit
3a63b2039e
13 changed files with 300 additions and 121 deletions
105
scripts/test/public-strategy-api.test.ts
Normal file
105
scripts/test/public-strategy-api.test.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import { mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { expect, test } from 'bun:test';
|
||||
import ts from 'typescript';
|
||||
import type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { createStrategy } from '../../libs/research/examples/fresh-position';
|
||||
import { nativeReplayFixture } from '../../test/fixtures/native-replay';
|
||||
import { runtimeImports } from '../runtime-imports';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const example = join(root, 'libs/research/examples/fresh-position.ts');
|
||||
|
||||
test('a standalone author compiles against package exports without workspace aliases or private host sources', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'stock-bot-public-strategy-types-'));
|
||||
try {
|
||||
await symlink(join(root, 'node_modules'), join(directory, 'node_modules'), 'dir');
|
||||
const entry = join(directory, 'strategy.ts');
|
||||
await writeFile(entry, await readFile(example));
|
||||
const program = ts.createProgram([entry], {
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
module: ts.ModuleKind.ESNext,
|
||||
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
||||
strict: true,
|
||||
noUncheckedIndexedAccess: true,
|
||||
verbatimModuleSyntax: true,
|
||||
skipLibCheck: true,
|
||||
noEmit: true,
|
||||
types: [],
|
||||
});
|
||||
const diagnostics = ts.getPreEmitDiagnostics(program);
|
||||
expect(
|
||||
diagnostics.map(item => ts.flattenDiagnosticMessageText(item.messageText, '\n'))
|
||||
).toEqual([]);
|
||||
const files = program.getSourceFiles().map(file => file.fileName);
|
||||
expect(files.some(file => file.endsWith('/research/src/strategy-api.ts'))).toBe(true);
|
||||
expect(files.some(file => file.includes('/apps/stock/orchestrator/'))).toBe(false);
|
||||
expect(files.some(file => file.includes('/apps/stock/engine/'))).toBe(false);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('the public authoring entrypoint has no runtime imports or exported runtime capabilities', async () => {
|
||||
const path = join(root, 'libs/research/src/strategy-api.ts');
|
||||
const source = await readFile(path, 'utf8');
|
||||
expect(runtimeImports(path, source)).toEqual([]);
|
||||
const transformed = new Bun.Transpiler({ loader: 'ts', target: 'browser' }).transformSync(source);
|
||||
expect(runtimeImports('strategy-api.js', transformed)).toEqual([]);
|
||||
expect(Object.keys(await import('@stock-bot/research/strategy-api'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('public-only author source packages without runtime imports and preserves native decisions and checkpoints', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'stock-bot-public-strategy-package-'));
|
||||
try {
|
||||
const source = await readFile(example, 'utf8');
|
||||
const transformed = new Bun.Transpiler({ loader: 'ts', target: 'browser' }).transformSync(
|
||||
source
|
||||
);
|
||||
expect(runtimeImports('strategy.mjs', transformed)).toEqual([]);
|
||||
for (const forbidden of ['@stock-bot/', 'engine.node', 'process.env', 'StrategyController']) {
|
||||
expect(transformed).not.toContain(forbidden);
|
||||
}
|
||||
const artifact = join(directory, 'strategy.mjs');
|
||||
await writeFile(artifact, transformed);
|
||||
const { createStrategy: packaged } = (await import(pathToFileURL(artifact).href)) as {
|
||||
createStrategy: typeof createStrategy;
|
||||
};
|
||||
const selection: RetainedProgramSelection = {
|
||||
ownerId: 'A',
|
||||
strategyId: 'fresh-position-example',
|
||||
strategyVersion: '1',
|
||||
seed: 7,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: parseFinancialDecimal('100'),
|
||||
parameters: { shares: 1 },
|
||||
};
|
||||
const f = nativeReplayFixture(6, 1, ['A']);
|
||||
// Derive the exact fixture series ID; authored code still sees only published inputs.
|
||||
selection.seriesId = f.config.cadence[0]!.series_ids[0]!;
|
||||
const load = prepareReplayLoad(f.dataset, f.config);
|
||||
const expected = runStrategyReplay(load, [createStrategy(selection)], {
|
||||
resultFormat: 'trace',
|
||||
});
|
||||
const actual = runStrategyReplay(load, [packaged(selection)], { resultFormat: 'trace' });
|
||||
expect(actual.result).toEqual(expected.result);
|
||||
expect(actual.diagnostics).toEqual(expected.diagnostics);
|
||||
expect(actual.diagnostics.strategies[0]?.nextDecisionSequence).toBeGreaterThan(0);
|
||||
expect(actual.diagnostics.strategies[0]?.state).toEqual({
|
||||
decisions: actual.diagnostics.strategies[0]?.nextDecisionSequence,
|
||||
});
|
||||
for (const shares of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, '1']) {
|
||||
expect(() => packaged({ ...selection, parameters: { shares } })).toThrow(
|
||||
'shares must be a nonnegative safe integer'
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue