import { EventEmitter } from 'node:events'; import { z } from 'zod'; import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; import type { ExecutionRepository, ExecutionTransaction, } from '../../apps/stock/orchestrator/src/execution/repository'; import type { ExecutionService, StrategyFill, } from '../../apps/stock/orchestrator/src/services/ExecutionService'; import { BaseStrategy, type Signal, } from '../../apps/stock/orchestrator/src/strategies/BaseStrategy'; import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; import type { StrategyDependencies, StrategyRegistry, } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry'; import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types'; import { logger } from './execution'; export const recoveryConfig: StrategyConfig = { id: 'counter', name: 'fixture', symbols: ['A'], parameters: {}, allocation: 1, enabled: true, }; export function makeStrategyManager({ execution, modeManager, registry = createBuiltinStrategyRegistry(), marketData = new EventEmitter(), }: StrategyDependencies & { registry?: StrategyRegistry; marketData?: EventEmitter }) { return new StrategyManager({ logger, execution, marketData, createStrategy: config => registry.create(config, { execution, modeManager }), }); } export class CounterStrategy extends BaseStrategy { count = 0; equities: number[] = []; failDecision = false; failFill = false; onDecision?: () => Promise; version = 'counter/v1'; constructor(execution: ExecutionService, config = recoveryConfig) { super(config, {} as ModeManager, execution); } override getCheckpointVersion() { return this.version; } protected override captureIndicators() { return { count: this.count, equities: this.equities }; } protected override restoreIndicators(input: unknown) { const state = z .object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) }) .parse(input); this.count = state.count; this.equities = state.equities; } protected updateIndicators() { this.count++; } protected async generateSignal(data: MarketData): Promise { this.equities.push((await this.executionService.getAccount()).equity); await this.onDecision?.(); if (this.failDecision) { throw new Error('injected decision failure'); } return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } }; } override async onFill(fill: StrategyFill) { await super.onFill(fill); if (this.failFill) { throw new Error('injected fill callback failure'); } } } export async function attachCounter( execution: ExecutionService, strategy = new CounterStrategy(execution) ) { const manager = new StrategyManager({ logger, execution, marketData: new EventEmitter(), createStrategy: () => { throw new Error('Counter fixtures attach their strategies directly'); }, }); try { await manager.attachStrategy(strategy); } catch (error) { await manager.shutdown(); throw error; } return { manager, strategy }; } export class FaultRepository implements ExecutionRepository { fault?: { method: keyof ExecutionTransaction; matches: (argument: unknown) => boolean; stage: 'before' | 'after' | 'commit'; hook?: () => Promise; }; constructor(private readonly delegate: ExecutionRepository) {} initialize(...args: Parameters) { return this.delegate.initialize(...args); } async transact(account: string, work: (tx: ExecutionTransaction) => Promise): Promise { let matched: typeof this.fault; const result = await this.delegate.transact(account, tx => work( new Proxy(tx, { get: (target, key: keyof ExecutionTransaction) => { const value = target[key]; if (typeof value !== 'function') { return value; } return async (...args: unknown[]) => { const fault = this.fault; const hit = fault && key === fault.method && fault.matches(args[0]); if (hit) { this.fault = undefined; matched = fault; } if (hit && fault.stage === 'before') { throw new Error('injected transaction failure'); } const answer = await Reflect.apply(value, target, args); if (hit && fault.stage === 'after') { throw new Error('injected transaction failure'); } return answer; }; }, }) ) ); if (matched?.stage === 'commit') { if (matched.hook) { await matched.hook(); } throw new Error('injected lost commit acknowledgement'); } return result; } }