126 lines
4.1 KiB
TypeScript
126 lines
4.1 KiB
TypeScript
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 { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
|
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 class CounterStrategy extends BaseStrategy {
|
|
count = 0;
|
|
equities: number[] = [];
|
|
failDecision = false;
|
|
failFill = false;
|
|
onDecision?: () => Promise<void>;
|
|
version = 'counter/v1';
|
|
constructor(execution: ExecutionService, config = recoveryConfig) {
|
|
super(config, {} as ModeManager, execution);
|
|
}
|
|
override getCheckpointVersion() {
|
|
return this.version;
|
|
}
|
|
protected override captureIndicators() {
|
|
return { count: this.count, equities: this.equities };
|
|
}
|
|
protected override restoreIndicators(input: unknown) {
|
|
const state = z
|
|
.object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) })
|
|
.parse(input);
|
|
this.count = state.count;
|
|
this.equities = state.equities;
|
|
}
|
|
protected updateIndicators() {
|
|
this.count++;
|
|
}
|
|
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
|
this.equities.push((await this.executionService.getAccount()).equity);
|
|
await this.onDecision?.();
|
|
if (this.failDecision) {
|
|
throw new Error('injected decision failure');
|
|
}
|
|
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
|
|
}
|
|
override async onFill(fill: StrategyFill) {
|
|
await super.onFill(fill);
|
|
if (this.failFill) {
|
|
throw new Error('injected fill callback failure');
|
|
}
|
|
}
|
|
}
|
|
export async function attachCounter(
|
|
execution: ExecutionService,
|
|
strategy = new CounterStrategy(execution)
|
|
) {
|
|
const manager = new StrategyManager({ logger, custom: { ExecutionService: execution } });
|
|
await manager.attachStrategy(strategy);
|
|
return { manager, strategy };
|
|
}
|
|
|
|
export class FaultRepository implements ExecutionRepository {
|
|
fault?: {
|
|
method: keyof ExecutionTransaction;
|
|
matches: (argument: unknown) => boolean;
|
|
stage: 'before' | 'after' | 'commit';
|
|
hook?: () => Promise<void>;
|
|
};
|
|
constructor(private readonly delegate: ExecutionRepository) {}
|
|
initialize(...args: Parameters<ExecutionRepository['initialize']>) {
|
|
return this.delegate.initialize(...args);
|
|
}
|
|
async transact<T>(account: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
|
|
let matched: typeof this.fault;
|
|
const result = await this.delegate.transact(account, tx =>
|
|
work(
|
|
new Proxy(tx, {
|
|
get: (target, key: keyof ExecutionTransaction) => {
|
|
const value = target[key];
|
|
if (typeof value !== 'function') {
|
|
return value;
|
|
}
|
|
return async (...args: unknown[]) => {
|
|
const fault = this.fault;
|
|
const hit = fault && key === fault.method && fault.matches(args[0]);
|
|
if (hit) {
|
|
this.fault = undefined;
|
|
matched = fault;
|
|
}
|
|
if (hit && fault.stage === 'before') {
|
|
throw new Error('injected transaction failure');
|
|
}
|
|
const answer = await Reflect.apply(value, target, args);
|
|
if (hit && fault.stage === 'after') {
|
|
throw new Error('injected transaction failure');
|
|
}
|
|
return answer;
|
|
};
|
|
},
|
|
})
|
|
)
|
|
);
|
|
if (matched?.stage === 'commit') {
|
|
if (matched.hook) {
|
|
await matched.hook();
|
|
}
|
|
throw new Error('injected lost commit acknowledgement');
|
|
}
|
|
return result;
|
|
}
|
|
}
|