feat(research): run stateful TypeScript strategies on canonical replay
This commit is contained in:
parent
0870b55830
commit
2bcadbd117
14 changed files with 1864 additions and 33 deletions
78
apps/stock/orchestrator/src/contracts/canonical-strategy.ts
Normal file
78
apps/stock/orchestrator/src/contracts/canonical-strategy.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
/** Trusted synchronous strategy author contract. No execution or native capabilities. */
|
||||
import type { DecisionIdentity, FinancialStrategyIntent } from '@stock-bot/types';
|
||||
import type {
|
||||
DecisionContext,
|
||||
NativeOrderStatus,
|
||||
PublishedObservation,
|
||||
ReplayIdentity,
|
||||
} from './native-replay';
|
||||
|
||||
export type DeepReadonly<T> = T extends string | number | boolean | null | undefined
|
||||
? T
|
||||
: T extends object
|
||||
? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }
|
||||
: T;
|
||||
|
||||
/** Copied native admission outcomes, not a later fill-event stream. */
|
||||
export interface StrategyAdmissionFeedback {
|
||||
decision: DecisionIdentity;
|
||||
revision: number;
|
||||
orders: {
|
||||
orderId: string;
|
||||
instrumentId: string;
|
||||
decision: DecisionIdentity;
|
||||
status: NativeOrderStatus;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface StrategyContext<State = unknown> {
|
||||
readonly ownerId: string;
|
||||
readonly strategyId: string;
|
||||
readonly strategyVersion: string;
|
||||
readonly decisionSequence: number;
|
||||
readonly now: number;
|
||||
readonly barrier: DeepReadonly<DecisionContext['barrier']>;
|
||||
/** The exact same read-only account view is shared by all due callbacks. */
|
||||
readonly portfolio: DeepReadonly<DecisionContext['view']>;
|
||||
readonly positions: DeepReadonly<DecisionContext['view']['portfolio']['positions']>;
|
||||
readonly observations: readonly DeepReadonly<PublishedObservation>[];
|
||||
readonly previousAdmission: DeepReadonly<StrategyAdmissionFeedback> | null;
|
||||
readonly state: DeepReadonly<State>;
|
||||
/** Valid only during this synchronous callback; never use Math.random for decisions. */
|
||||
readonly random: () => number;
|
||||
}
|
||||
|
||||
export interface StrategyProgram<State = unknown> {
|
||||
readonly ownerId: string;
|
||||
readonly strategyId: string;
|
||||
readonly strategyVersion: string;
|
||||
readonly mode: 'target' | 'orders';
|
||||
readonly seed: number;
|
||||
/** Finite plain JSON, checked and detached before the native attempt starts. */
|
||||
readonly initialState: State;
|
||||
decide(context: StrategyContext<State>): {
|
||||
nextState: State;
|
||||
intent: FinancialStrategyIntent;
|
||||
};
|
||||
}
|
||||
|
||||
export interface StrategyDiagnostic {
|
||||
ownerId: string;
|
||||
strategyId: string;
|
||||
strategyVersion: string;
|
||||
nextDecisionSequence: number;
|
||||
state: unknown;
|
||||
rng: { algorithm: 'lcg32-v1'; seed: number; state: number; draws: number };
|
||||
observationCount: number;
|
||||
previousAdmission: StrategyAdmissionFeedback | null;
|
||||
}
|
||||
|
||||
/** Last confirmed strategy transitions only. This cannot restore financial state.
|
||||
* Retry always starts a fresh native session and recomputes from original inputs. */
|
||||
export interface StrategyDiagnosticSnapshot {
|
||||
version: 1;
|
||||
identity: ReplayIdentity;
|
||||
committedBarriers: number;
|
||||
lastBarrierId: string | null;
|
||||
strategies: StrategyDiagnostic[];
|
||||
}
|
||||
|
|
@ -162,6 +162,7 @@ const outcomeSchema = z
|
|||
export const submissionSchema = z
|
||||
.object({ identity: replayIdentitySchema, outcome: outcomeSchema })
|
||||
.strict();
|
||||
export type ReplaySubmissionOutcome = z.infer<typeof outcomeSchema>;
|
||||
const resultSchema = z
|
||||
.object({
|
||||
identity: replayIdentitySchema,
|
||||
|
|
@ -178,6 +179,70 @@ export type ReplayStep = z.infer<typeof stepSchema>;
|
|||
export type ReplayResult = z.infer<typeof resultSchema>;
|
||||
const nonnegative = decimal.refine(value => !value.startsWith('-'));
|
||||
const positive = nonnegative.refine(value => value !== '0.00000000');
|
||||
const nativeOrderStatusSchema = z.union([
|
||||
z.enum(['Open', 'Filled', 'Cancelled', 'Expired']),
|
||||
z
|
||||
.object({
|
||||
Rejected: z.enum([
|
||||
'OrderSize',
|
||||
'PositionSize',
|
||||
'SymbolExposure',
|
||||
'GrossExposure',
|
||||
'InsufficientCash',
|
||||
'InsufficientInventory',
|
||||
'MissingMark',
|
||||
'StaleMark',
|
||||
'DailyLoss',
|
||||
'Drawdown',
|
||||
'InactiveOrder',
|
||||
]),
|
||||
})
|
||||
.strict(),
|
||||
]);
|
||||
export type NativeOrderStatus = z.infer<typeof nativeOrderStatusSchema>;
|
||||
const managedOrderSchema = z
|
||||
.object({
|
||||
order: z
|
||||
.object({
|
||||
orderId: id,
|
||||
decision: z.object({ ownerId: id, decisionId: id, sequence: counter }).strict(),
|
||||
instrumentId: id,
|
||||
side: z.enum(['buy', 'sell']),
|
||||
quantity: positive,
|
||||
limitPrice: positive.nullable(),
|
||||
origin: z.enum(['Explicit', 'Target']),
|
||||
})
|
||||
.strict(),
|
||||
timeInForce: z.enum(['DAY', 'GTC', 'IOC', 'FOK']),
|
||||
submittedAt: z
|
||||
.object({
|
||||
at: time,
|
||||
phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']),
|
||||
instrumentId: id,
|
||||
sourceSequence: counter,
|
||||
})
|
||||
.strict(),
|
||||
readyAt: time,
|
||||
venueSession: id.nullable(),
|
||||
remaining: nonnegative,
|
||||
filled: nonnegative,
|
||||
status: nativeOrderStatusSchema,
|
||||
admissionSequence: counter,
|
||||
})
|
||||
.strict();
|
||||
const admissionEffectSchema = z.union([
|
||||
z.object({ Order: managedOrderSchema }).strict(),
|
||||
z.object({ Risk: z.record(z.unknown()) }).strict(),
|
||||
z.object({ Operator: z.record(z.unknown()) }).strict(),
|
||||
]);
|
||||
/** Decode only the existing native facts needed for strategy admission feedback.
|
||||
* Other nested risk/ledger diagnostics are never interpreted as TS accounting. */
|
||||
export function nativeAdmissionOrders(effects: ReplaySubmissionOutcome['effects']) {
|
||||
return effects.flatMap(effect => {
|
||||
const parsed = admissionEffectSchema.parse(effect);
|
||||
return 'Order' in parsed ? [parsed.Order] : [];
|
||||
});
|
||||
}
|
||||
const ownerValuationSchema = z
|
||||
.object({
|
||||
ownerId: id,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue