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
39
libs/research/examples/fresh-position.ts
Normal file
39
libs/research/examples/fresh-position.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import type { FinancialDecimal, StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution';
|
||||
|
||||
/** Authoring example only: request a fixed holding when the selected series is fresh.
|
||||
* This demonstrates the callback contract, not a validated trading hypothesis. */
|
||||
export function createStrategy(
|
||||
selection: RetainedProgramSelection
|
||||
): StrategyProgram<{ decisions: number }> {
|
||||
const shares = selection.parameters.shares;
|
||||
if (typeof shares !== 'number' || !Number.isSafeInteger(shares) || shares < 0) {
|
||||
throw new Error('shares must be a nonnegative safe integer');
|
||||
}
|
||||
// The checked integer gives an exact canonical decimal with no runtime imports.
|
||||
// Rust still validates intent quantities and enforces all financial constraints.
|
||||
const quantity = `${shares}.00000000` as FinancialDecimal;
|
||||
return {
|
||||
ownerId: selection.ownerId,
|
||||
strategyId: selection.strategyId,
|
||||
strategyVersion: selection.strategyVersion,
|
||||
seed: selection.seed,
|
||||
mode: 'target',
|
||||
initialState: { decisions: 0 },
|
||||
decide(context) {
|
||||
const fresh = context.barrier.inputs.some(
|
||||
input =>
|
||||
input.series_id === selection.seriesId &&
|
||||
typeof input.availability === 'object' &&
|
||||
'Fresh' in input.availability
|
||||
);
|
||||
return {
|
||||
nextState: { decisions: context.state.decisions + 1 },
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets: fresh ? [{ instrumentId: selection.instrumentId, quantity }] : [],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -10,7 +10,8 @@
|
|||
".": "./src/index.ts",
|
||||
"./dataset-contracts": "./src/dataset-contracts.ts",
|
||||
"./datasets": "./src/datasets.ts",
|
||||
"./results": "./src/results.ts"
|
||||
"./results": "./src/results.ts",
|
||||
"./strategy-api": "./src/strategy-api.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc"
|
||||
|
|
|
|||
107
libs/research/src/strategy-api.ts
Normal file
107
libs/research/src/strategy-api.ts
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
/**
|
||||
* Strategy-facing types for synchronous decisions on the canonical engine.
|
||||
* The execution host supplies these values and owns time,
|
||||
* order admission and accounting. Implementations return intent, not broker calls.
|
||||
*/
|
||||
import type {
|
||||
DecisionContext,
|
||||
NativeOrderStatus,
|
||||
PublishedObservation,
|
||||
ReplayIdentity,
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import type { DecisionIdentity, FinancialStrategyIntent } from '@stock-bot/types';
|
||||
|
||||
export type { DecisionIdentity, FinancialDecimal, FinancialStrategyIntent } from '@stock-bot/types';
|
||||
|
||||
export type DeepReadonly<T> = T extends string | number | boolean | null | undefined
|
||||
? T
|
||||
: T extends object
|
||||
? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }
|
||||
: T;
|
||||
|
||||
/**
|
||||
* Order outcomes copied when the previous decision batch was admitted.
|
||||
* These are not later fill notifications: inspect current positions and the
|
||||
* account view to learn what has executed since that decision.
|
||||
*/
|
||||
export interface StrategyAdmissionFeedback {
|
||||
decision: DecisionIdentity;
|
||||
revision: number;
|
||||
orders: {
|
||||
orderId: string;
|
||||
instrumentId: string;
|
||||
decision: DecisionIdentity;
|
||||
status: NativeOrderStatus;
|
||||
}[];
|
||||
}
|
||||
|
||||
/** Read-only input to one owner at an engine-defined decision barrier. */
|
||||
export interface StrategyContext<State = unknown> {
|
||||
readonly ownerId: string;
|
||||
readonly strategyId: string;
|
||||
readonly strategyVersion: string;
|
||||
/** Monotonic per-owner identity; advances after confirmed batch admission. */
|
||||
readonly decisionSequence: number;
|
||||
/** Engine availability time in milliseconds, never the host's wall clock. */
|
||||
readonly now: number;
|
||||
/** Due owners, account revision and freshness of the required input series. */
|
||||
readonly barrier: DeepReadonly<DecisionContext['barrier']>;
|
||||
/** The exact same read-only account view is shared by all due callbacks. */
|
||||
readonly portfolio: DeepReadonly<DecisionContext['view']>;
|
||||
/** Already filtered to this owner; portfolio contains the account-wide view. */
|
||||
readonly positions: DeepReadonly<DecisionContext['view']['portfolio']['positions']>;
|
||||
/** Published since this owner's last callback, buffered across slower cadences. */
|
||||
readonly observations: readonly DeepReadonly<PublishedObservation>[];
|
||||
readonly previousAdmission: DeepReadonly<StrategyAdmissionFeedback> | null;
|
||||
/** Last confirmed JSON state, or initialState before the first decision. */
|
||||
readonly state: DeepReadonly<State>;
|
||||
/** Valid only during this synchronous callback; never use Math.random for decisions. */
|
||||
readonly random: () => number;
|
||||
}
|
||||
|
||||
/**
|
||||
* One strategy instance bound to one configured financial owner and intent mode.
|
||||
* Keep decision history in explicit state so a fresh attempt can recompute it.
|
||||
* Native risk rules still apply to every returned intent.
|
||||
*/
|
||||
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;
|
||||
/**
|
||||
* Propose the next JSON state and target holdings or explicit order actions.
|
||||
* A target quantity is this owner's desired total, not an incremental buy.
|
||||
* Return synchronously: state and seeded RNG advances become confirmed only
|
||||
* after Rust acknowledges the whole decision batch, including any rejections.
|
||||
*/
|
||||
decide(context: StrategyContext<State>): {
|
||||
nextState: State;
|
||||
intent: FinancialStrategyIntent;
|
||||
};
|
||||
}
|
||||
|
||||
/** Confirmed callback state for inspection; it does not contain the native ledger. */
|
||||
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[];
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue