cli

package
v2.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package cli adapts typed daemon contracts and local workflows into Canary commands, machine-readable output, and terminal rendering. Broker-connected and runtime-state commands call the daemon over its typed Unix-socket protocol, while setup, update, watchlist, and offline research workflows run locally. Handlers return process exit codes; the daemon remains authoritative for broker state, policy decisions, and gated broker writes.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DetectWriteOrigin

func DetectWriteOrigin(stdin io.Reader) string

DetectWriteOrigin classifies this process for broker-write authorization. Any agent marker or a non-TTY stdin classifies as agent; nothing can force a human classification. The daemon treats unknown origins as agent for audit and any origin-specific policy, while broker-write readiness still comes from trading mode, pins, preview tokens, freeze state, and broker checks.

func IsKnown

func IsKnown(name string) bool

IsKnown reports whether name is a registered subcommand. Used by cmd/canary to skip the daemon autospawn for typos and unknown commands — otherwise `canary nonsense` would spawn ibkrd just to fail with "unknown subcommand", which is wasteful and confusing if it tips a dormant install into a long startup.

func PreviewRenderAccount

func PreviewRenderAccount(env *Env, a *rpc.AccountResult)

PreviewRenderAccount renders synthetic account data with the production text renderer.

func PreviewRenderChainExpiries

func PreviewRenderChainExpiries(env *Env, r *rpc.ChainExpiriesResult, withIV bool)

PreviewRenderChainExpiries renders a synthetic expiry list with the production text renderer.

func PreviewRenderChainStrikes

func PreviewRenderChainStrikes(env *Env, c *rpc.ChainResult)

PreviewRenderChainStrikes renders a synthetic strike grid with the production text renderer.

func PreviewRenderHistory

func PreviewRenderHistory(env *Env, r *rpc.HistoryDailyResult)

PreviewRenderHistory renders synthetic daily history with the production text renderer.

func PreviewRenderPositions

func PreviewRenderPositions(env *Env, r *rpc.PositionsResult)

PreviewRenderPositions renders synthetic position rows with the production text renderer.

func PreviewRenderPositionsByUnderlying

func PreviewRenderPositionsByUnderlying(env *Env, r *rpc.PositionsResult)

PreviewRenderPositionsByUnderlying renders synthetic positions grouped by underlying with the production text renderer.

func PreviewRenderQuoteSnapshot

func PreviewRenderQuoteSnapshot(env *Env, qs []rpc.Quote)

PreviewRenderQuoteSnapshot renders synthetic quote rows with the production text renderer.

func PreviewRenderRegime

func PreviewRenderRegime(env *Env, r *rpc.RegimeSnapshotResult)

PreviewRenderRegime renders a synthetic regime snapshot with the production text renderer.

func PreviewRenderScan

func PreviewRenderScan(env *Env, r *rpc.ScanResult)

PreviewRenderScan renders synthetic scanner results with the production text renderer.

func PreviewRenderSize

func PreviewRenderSize(env *Env, r *risk.SizeResult)

PreviewRenderSize renders a synthetic position-size result with the production text renderer.

func PreviewRenderStatus

func PreviewRenderStatus(env *Env, h *rpc.HealthResult)

PreviewRenderStatus renders synthetic daemon health with the production text renderer.

func PreviewRenderStress

func PreviewRenderStress(env *Env, r *rpc.StressResult)

PreviewRenderStress renders a synthetic stress result with the production text renderer.

func PrintUsage

func PrintUsage(w io.Writer)

PrintUsage writes the top-level help text. Commands are listed under their catalog group, in registry order inside each one, so `status` stays the first line. The listing shows the catalog's short form and the full summary stays in `canary <subcommand> --help` — a flat list of 36 long summaries wraps into a wall on an 80-column terminal.

func Run

func Run(ctx context.Context, env *Env, cmd string, args []string) int

Run dispatches the subcommand named by cmd. Returns the process exit code.

Args are reordered so all flags come before positional arguments — Go's flag package stops at the first non-flag token, but users naturally write `canary quote AAPL --json` rather than `canary quote --json AAPL`.

On an unknown subcommand we print the full top-level usage to stderr, not just the bare hint, so a user who typo'd or guessed wrong sees the real list of verbs immediately. Pattern matches git/kubectl/gh.

func RunRestart

func RunRestart(ctx context.Context, args []string, stdout, stderr io.Writer) int

RunRestart is the top-level `canary restart` entrypoint. It intentionally does not take an Env: restart is local process management and must run before the normal autospawn+dial path in cmd/canary/main.go.

func RunStop added in v2.6.0

func RunStop(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) int

RunStop is the top-level `canary stop` entrypoint. Like RunRestart it takes no Env: stopping is local process management and must run before the autospawn path in cmd/canary/main.go, which would otherwise start the very daemon this command exists to stop.

func RunUpdate

func RunUpdate(ctx context.Context, args []string, version string, stdin io.Reader, stdout, stderr io.Writer) int

RunUpdate is the entrypoint cmd/canary/main.go dispatches to. It does not match the CommandFunc signature because update has no Env (no daemon connection) — `update` is registered in cli.commands with Fn=nil and the binary's main.go calls this function directly, the same pattern `setup` uses.

args are the raw CLI args after `canary update`. version is the installed binary's version string (cmd/canary stamps it at build). stdin / stdout / stderr are the process I/O streams.

Returns the process exit code.

func ShouldColor

func ShouldColor(w io.Writer) bool

ShouldColor reports whether ANSI color escapes should be emitted to w. Policy, in order:

  1. CANARY_COLOR=always → on (overrides TTY check)
  2. CANARY_COLOR=never → off
  3. NO_COLOR set (any) → off (https://no-color.org)
  4. w is a character device (interactive terminal) → on
  5. otherwise → off (pipes, file redirects, bytes.Buffer in tests)

Computed once per process and cached on Env.Color so colored renderers don't re-syscall on every value.

Types

type BacktestEventMetrics

type BacktestEventMetrics struct {
	Events                       int      `json:"events"`
	TargetStressEvents           int      `json:"target_stress_events"`
	NonStressEvents              int      `json:"non_stress_events"`
	WatchEvents                  int      `json:"watch_events"`
	WatchTruePositiveEvents      int      `json:"watch_true_positive_events"`
	WatchFalsePositiveEvents     int      `json:"watch_false_positive_events"`
	WatchMissEvents              int      `json:"watch_miss_events"`
	WatchPrecision               *float64 `json:"watch_precision,omitempty"`
	WatchRecall                  *float64 `json:"watch_recall,omitempty"`
	ConfirmedStressEvents        int      `json:"confirmed_stress_events"`
	ConfirmedStressTruePositive  int      `json:"confirmed_stress_true_positive_events"`
	ConfirmedStressFalsePositive int      `json:"confirmed_stress_false_positive_events"`
	ConfirmedStressMiss          int      `json:"confirmed_stress_miss_events"`
	ConfirmedStressPrecision     *float64 `json:"confirmed_stress_precision,omitempty"`
	ConfirmedStressRecall        *float64 `json:"confirmed_stress_recall,omitempty"`
	PanicEvents                  int      `json:"panic_events"`
	PanicRecall                  *float64 `json:"panic_recall,omitempty"`
}

BacktestEventMetrics summarizes episode-level detection so consecutive rows from one stress event are not treated as independent events.

type BacktestLifecycleMetrics

type BacktestLifecycleMetrics struct {
	Observations                        int      `json:"observations"`
	TargetStress                        int      `json:"target_stress"`
	NonStress                           int      `json:"non_stress"`
	LaterConfirmedStress                int      `json:"later_confirmed_stress"`
	MajorStress                         int      `json:"major_stress"`
	EarlyWarning                        int      `json:"early_warning"`
	EarlyWarningTruePositive            int      `json:"early_warning_true_positive"`
	EarlyWarningFalsePositive           int      `json:"early_warning_false_positive"`
	EarlyWarningMiss                    int      `json:"early_warning_miss"`
	EarlyWarningPrecision               *float64 `json:"early_warning_precision,omitempty"`
	EarlyWarningRecall                  *float64 `json:"early_warning_recall,omitempty"`
	EarlyWarningFalseCalmRally          int      `json:"early_warning_false_calm_rally"`
	EarlyWarningMedianLeadDays          *float64 `json:"early_warning_median_lead_days,omitempty"`
	ConfirmedStress                     int      `json:"confirmed_stress"`
	ConfirmedStressTruePositive         int      `json:"confirmed_stress_true_positive"`
	ConfirmedStressFalsePositive        int      `json:"confirmed_stress_false_positive"`
	ConfirmedStressMiss                 int      `json:"confirmed_stress_miss"`
	ConfirmedStressPrecision            *float64 `json:"confirmed_stress_precision,omitempty"`
	ConfirmedStressRecall               *float64 `json:"confirmed_stress_recall,omitempty"`
	PanicCount                          int      `json:"panic_count"`
	PanicTruePositive                   int      `json:"panic_true_positive"`
	PanicMiss                           int      `json:"panic_miss"`
	PanicRecall                         *float64 `json:"panic_recall,omitempty"`
	Stabilization                       int      `json:"stabilization"`
	Opportunity                         int      `json:"opportunity"`
	StabilizationOpportunityFalseStarts int      `json:"stabilization_opportunity_false_starts"`
	DataQualityBlocked                  int      `json:"data_quality_blocked"`
}

BacktestLifecycleMetrics summarizes detection and false-start behavior across stress lifecycle stages.

type Command

type Command struct {
	Name    string
	Summary string
	Usage   string // optional one-line usage example shown in `canary X --help`
	Fn      CommandFunc
}

Command bundles a subcommand's name, one-line summary, optional usage example, and handler. One slice — single source of truth for both the dispatcher and the help table. `status` is listed first because users hitting any other command without a healthy gateway will be redirected here by the gateway_unavailable hint.

func Commands

func Commands() []Command

Commands returns the registered subcommand entries in declaration order. Exported so the MCP server's parity test can assert that every CLI command has an MCP tool counterpart (or is on the documented exclude list).

type CommandFunc

type CommandFunc func(ctx context.Context, env *Env, args []string) int

CommandFunc is the signature implemented by every subcommand handler.

type CommandSpec

type CommandSpec struct {
	Name    string
	Summary string
	// Brief is the listing line for commands whose Summary is too long for
	// a terminal row. `canary <command> --help` and the generated CLI
	// reference always render Summary, so the detail is moved, not lost.
	Brief       string
	Usage       string
	Flags       []FlagSpec
	Subcommands []SubcommandSpec
	Guard       GuardClass
	TUI         TUISupport
	Group       HelpGroup
}

CommandSpec is the user-facing command catalog shared by the one-shot CLI and the TUI. Name/Summary/Usage are copied from Commands() at runtime so the help table and catalog cannot silently drift.

func Catalog

func Catalog() []CommandSpec

Catalog returns the registered commands with shared metadata for the help listing, completion, TUI guard decisions, and flag-value handling.

type DaemonConn

type DaemonConn interface {
	Call(context.Context, string, any, any) error
	Stream(context.Context, string, any, func(json.RawMessage) error) error
}

DaemonConn is the CLI's typed daemon-call surface. *dial.Conn implements it in production; the interface keeps command-flow tests transport-free.

type Env

type Env struct {
	Stdout io.Writer
	Stderr io.Writer
	// Stdin is the interactive input used for live-write confirmation
	// prompts. Nil in tests and non-interactive helper paths.
	Stdin io.Reader
	Conn  DaemonConn
	// Origin is this process's broker-write origin classification
	// (rpc.OrderOrigin*), resolved once in cmd/canary via DetectWriteOrigin.
	// Empty classifies as agent at the daemon (fail closed).
	Origin string
	// Version is the running CLI version stamped by cmd/canary. Empty in
	// renderer tests and local-only helper paths that do not need parity
	// checks against the daemon.
	Version string
	// Color is true when ANSI color escapes should be emitted on Stdout.
	// Computed once in main.go via ShouldColor(Stdout) so renderers don't
	// re-syscall stat() per value. Defaults to false in tests (Stdout is
	// usually a *bytes.Buffer), keeping golden-substring assertions stable.
	Color bool
}

Env is the per-invocation context shared by every subcommand.

type FlagSpec

type FlagSpec struct {
	Name       string
	TakesValue bool
	Values     []string
	Summary    string
}

FlagSpec is the shared flag metadata used by command-line flag hoisting and TUI completion. Values is intentionally small and enum-like; dynamic completion (symbols, watchlist names) lives in the TUI layer.

type GuardClass

type GuardClass string

GuardClass describes whether a command can run directly inside the TUI or needs a human confirmation first. It is metadata only; existing CLI gates still enforce the real safety policy.

const (
	GuardReadOnly GuardClass = "read-only"
	GuardLocal    GuardClass = "local"
	GuardConfirm  GuardClass = "confirm"
)

Guard classifications used by the command catalog.

type HelpGroup added in v2.6.0

type HelpGroup string

HelpGroup buckets commands in the top-level help listing. It is a reading aid for a 36-command registry and carries no policy; guard classes remain the only statement about what a command may do.

const (
	GroupDesk    HelpGroup = "desk"
	GroupMarkets HelpGroup = "markets"
	GroupSystem  HelpGroup = "system"
)

Help groups used by the command catalog.

type HelpGroupSpec added in v2.6.0

type HelpGroupSpec struct {
	Group   HelpGroup
	Title   string
	Tagline string
}

HelpGroupSpec is one heading in the top-level help listing.

func HelpGroups added in v2.6.0

func HelpGroups() []HelpGroupSpec

HelpGroups returns the listing groups in render order. Commands keep registry order inside their group, so `status` stays the first line of the first group.

type OpportunityBacktestClusterMetrics

type OpportunityBacktestClusterMetrics struct {
	Name    string                     `json:"name"`
	Metrics OpportunityBacktestMetrics `json:"metrics"`
}

OpportunityBacktestClusterMetrics associates opportunity metrics with one named market cluster.

type OpportunityBacktestDiagnosticBucket

type OpportunityBacktestDiagnosticBucket struct {
	Name    string                     `json:"name"`
	Class   string                     `json:"class,omitempty"`
	PlanID  string                     `json:"plan_id,omitempty"`
	Metrics OpportunityBacktestMetrics `json:"metrics"`
}

OpportunityBacktestDiagnosticBucket aggregates metrics for one diagnostic class and optional research plan.

type OpportunityBacktestDiagnostics

type OpportunityBacktestDiagnostics struct {
	Reasons  []OpportunityBacktestDiagnosticBucket `json:"reasons,omitempty"`
	Features []OpportunityBacktestDiagnosticBucket `json:"features,omitempty"`
}

OpportunityBacktestDiagnostics groups missed or blocked observations by reason and feature.

func (OpportunityBacktestDiagnostics) IsZero

IsZero reports whether the diagnostic contains no reason or feature buckets.

type OpportunityBacktestEvidence

type OpportunityBacktestEvidence struct {
	Status                          string                           `json:"status"`
	MinObservations                 int                              `json:"min_observations"`
	MinSignalFired                  int                              `json:"min_signal_fired"`
	MinTargetOpportunity            int                              `json:"min_target_opportunity"`
	MinNonOpportunity               int                              `json:"min_non_opportunity"`
	MinSignalInstruments            int                              `json:"min_signal_instruments"`
	MinSignalClusters               int                              `json:"min_signal_clusters"`
	MinHoldoutObservations          int                              `json:"min_holdout_observations"`
	MinHoldoutSignalFired           int                              `json:"min_holdout_signal_fired"`
	MinHoldoutTargetOpportunity     int                              `json:"min_holdout_target_opportunity"`
	MinHoldoutNonOpportunity        int                              `json:"min_holdout_non_opportunity"`
	MinHoldoutSignalInstruments     int                              `json:"min_holdout_signal_instruments"`
	MinHoldoutSignalClusters        int                              `json:"min_holdout_signal_clusters"`
	MinPortfolioFilledSignals       int                              `json:"min_portfolio_filled_signals"`
	MaxSignalInstrumentShare        float64                          `json:"max_signal_instrument_share"`
	MaxSignalClusterShare           float64                          `json:"max_signal_cluster_share"`
	MaxHoldoutSignalInstrumentShare float64                          `json:"max_holdout_signal_instrument_share"`
	MaxHoldoutSignalClusterShare    float64                          `json:"max_holdout_signal_cluster_share"`
	MaxMarkToMarketDrawdownPct      float64                          `json:"max_mark_to_market_drawdown_pct"`
	MaxMarkToMarketGapDays          int                              `json:"max_mark_to_market_gap_days"`
	MinMarkToMarketExcessToDrawdown float64                          `json:"min_mark_to_market_excess_to_drawdown"`
	Needs                           OpportunityBacktestEvidenceNeeds `json:"needs"`
	Reasons                         []string                         `json:"reasons,omitempty"`
}

OpportunityBacktestEvidence reports whether a replay satisfies the minimum sample, holdout, concentration, cost, and mark-to-market evidence gates.

type OpportunityBacktestEvidenceNeeds

type OpportunityBacktestEvidenceNeeds struct {
	AdditionalObservations             int `json:"additional_observations"`
	AdditionalSignalFired              int `json:"additional_signal_fired"`
	AdditionalTargetOpportunity        int `json:"additional_target_opportunity"`
	AdditionalNonOpportunity           int `json:"additional_non_opportunity"`
	AdditionalSignalInstruments        int `json:"additional_signal_instruments"`
	AdditionalSignalClusters           int `json:"additional_signal_clusters"`
	AdditionalHoldoutObservations      int `json:"additional_holdout_observations"`
	AdditionalHoldoutSignalFired       int `json:"additional_holdout_signal_fired"`
	AdditionalHoldoutTargetOpportunity int `json:"additional_holdout_target_opportunity"`
	AdditionalHoldoutNonOpportunity    int `json:"additional_holdout_non_opportunity"`
	AdditionalHoldoutSignalInstruments int `json:"additional_holdout_signal_instruments"`
	AdditionalHoldoutSignalClusters    int `json:"additional_holdout_signal_clusters"`
	UnknownSplitObservations           int `json:"unknown_split_observations"`
	RetrospectiveHoldoutObservations   int `json:"retrospective_holdout_observations"`
	MissingCostSignalFired             int `json:"missing_cost_signal_fired"`
	SignalContextBlocked               int `json:"signal_context_blocked"`
}

OpportunityBacktestEvidenceNeeds quantifies remaining evidence deficits for an opportunity replay.

type OpportunityBacktestMetrics

type OpportunityBacktestMetrics struct {
	Observations                         int      `json:"observations"`
	TargetOpportunity                    int      `json:"target_opportunity"`
	NonOpportunity                       int      `json:"non_opportunity"`
	TuningObservations                   int      `json:"tuning_observations"`
	HoldoutObservations                  int      `json:"holdout_observations"`
	UnknownSplitObservations             int      `json:"unknown_split_observations"`
	RetrospectiveHoldoutObservations     int      `json:"retrospective_holdout_observations"`
	SignalContextBlocked                 int      `json:"signal_context_blocked"`
	HoldoutSignalContextBlocked          int      `json:"holdout_signal_context_blocked"`
	HoldoutTargetOpportunity             int      `json:"holdout_target_opportunity"`
	HoldoutNonOpportunity                int      `json:"holdout_non_opportunity"`
	SignalFired                          int      `json:"signal_fired"`
	HoldoutSignalFired                   int      `json:"holdout_signal_fired"`
	HoldoutCostedSignalFired             int      `json:"holdout_costed_signal_fired"`
	HoldoutMissingCostSignalFired        int      `json:"holdout_missing_cost_signal_fired"`
	HoldoutPositiveNetExcess             int      `json:"holdout_positive_net_excess"`
	HoldoutNegativeNetExcess             int      `json:"holdout_negative_net_excess"`
	HoldoutNetExcessHitRate              *float64 `json:"holdout_net_excess_hit_rate,omitempty"`
	HoldoutNetExcessHitRateLower95       *float64 `json:"holdout_net_excess_hit_rate_lower_95,omitempty"`
	HoldoutAvgNetExcessReturnPct         *float64 `json:"holdout_avg_net_excess_return_pct,omitempty"`
	HoldoutAvgNetExcessReturnLower95Pct  *float64 `json:"holdout_avg_net_excess_return_lower_95_pct,omitempty"`
	HoldoutCostedCandidates              int      `json:"holdout_costed_candidates"`
	HoldoutPositiveCandidateNetExcess    int      `json:"holdout_positive_candidate_net_excess"`
	HoldoutNegativeCandidateNetExcess    int      `json:"holdout_negative_candidate_net_excess"`
	HoldoutCandidateNetExcessHitRate     *float64 `json:"holdout_candidate_net_excess_hit_rate,omitempty"`
	HoldoutAvgCandidateNetExcessPct      *float64 `json:"holdout_avg_candidate_net_excess_pct,omitempty"`
	HoldoutMedianCandidateNetExcessPct   *float64 `json:"holdout_median_candidate_net_excess_pct,omitempty"`
	HoldoutNonFiredCostedCandidates      int      `json:"holdout_non_fired_costed_candidates"`
	HoldoutAvgNonFiredCandidateNetPct    *float64 `json:"holdout_avg_non_fired_candidate_net_pct,omitempty"`
	HoldoutMedianNonFiredCandidateNetPct *float64 `json:"holdout_median_non_fired_candidate_net_pct,omitempty"`
	HoldoutFiredVsCandidateAvgLiftPct    *float64 `json:"holdout_fired_vs_candidate_avg_lift_pct,omitempty"`
	HoldoutFiredVsCandidateMedianLiftPct *float64 `json:"holdout_fired_vs_candidate_median_lift_pct,omitempty"`
	HoldoutFiredVsNonFiredAvgLiftPct     *float64 `json:"holdout_fired_vs_non_fired_avg_lift_pct,omitempty"`
	HoldoutFiredVsNonFiredMedianLiftPct  *float64 `json:"holdout_fired_vs_non_fired_median_lift_pct,omitempty"`
	HoldoutDistinctSignalInstruments     int      `json:"holdout_distinct_signal_instruments"`
	HoldoutMaxSignalInstrument           string   `json:"holdout_max_signal_instrument,omitempty"`
	HoldoutMaxSignalInstrumentFired      int      `json:"holdout_max_signal_instrument_fired,omitempty"`
	HoldoutMaxSignalInstrumentShare      *float64 `json:"holdout_max_signal_instrument_share,omitempty"`
	HoldoutDistinctSignalClusters        int      `json:"holdout_distinct_signal_clusters"`
	HoldoutMaxSignalCluster              string   `json:"holdout_max_signal_cluster,omitempty"`
	HoldoutMaxSignalClusterFired         int      `json:"holdout_max_signal_cluster_fired,omitempty"`
	HoldoutMaxSignalClusterShare         *float64 `json:"holdout_max_signal_cluster_share,omitempty"`
	DistinctSignalInstruments            int      `json:"distinct_signal_instruments"`
	MaxSignalInstrument                  string   `json:"max_signal_instrument,omitempty"`
	MaxSignalInstrumentFired             int      `json:"max_signal_instrument_fired,omitempty"`
	MaxSignalInstrumentShare             *float64 `json:"max_signal_instrument_share,omitempty"`
	DistinctSignalClusters               int      `json:"distinct_signal_clusters"`
	MaxSignalCluster                     string   `json:"max_signal_cluster,omitempty"`
	MaxSignalClusterFired                int      `json:"max_signal_cluster_fired,omitempty"`
	MaxSignalClusterShare                *float64 `json:"max_signal_cluster_share,omitempty"`
	TruePositive                         int      `json:"true_positive"`
	FalsePositive                        int      `json:"false_positive"`
	Miss                                 int      `json:"miss"`
	Precision                            *float64 `json:"precision,omitempty"`
	Recall                               *float64 `json:"recall,omitempty"`
	FalseAlarmRate                       *float64 `json:"false_alarm_rate,omitempty"`
	PositiveExcess                       int      `json:"positive_excess"`
	NegativeExcess                       int      `json:"negative_excess"`
	ExcessHitRate                        *float64 `json:"excess_hit_rate,omitempty"`
	ExcessHitRateLower95                 *float64 `json:"excess_hit_rate_lower_95,omitempty"`
	CostedSignalFired                    int      `json:"costed_signal_fired"`
	MissingCostSignalFired               int      `json:"missing_cost_signal_fired"`
	PositiveNetExcess                    int      `json:"positive_net_excess"`
	NegativeNetExcess                    int      `json:"negative_net_excess"`
	NetExcessHitRate                     *float64 `json:"net_excess_hit_rate,omitempty"`
	NetExcessHitRateLower95              *float64 `json:"net_excess_hit_rate_lower_95,omitempty"`
	CostedCandidates                     int      `json:"costed_candidates"`
	PositiveCandidateNetExcess           int      `json:"positive_candidate_net_excess"`
	NegativeCandidateNetExcess           int      `json:"negative_candidate_net_excess"`
	CandidateNetExcessHitRate            *float64 `json:"candidate_net_excess_hit_rate,omitempty"`
	AvgCandidateNetExcessPct             *float64 `json:"avg_candidate_net_excess_pct,omitempty"`
	MedianCandidateNetExcessPct          *float64 `json:"median_candidate_net_excess_pct,omitempty"`
	NonFiredCostedCandidates             int      `json:"non_fired_costed_candidates"`
	AvgNonFiredCandidateNetPct           *float64 `json:"avg_non_fired_candidate_net_pct,omitempty"`
	MedianNonFiredCandidateNetPct        *float64 `json:"median_non_fired_candidate_net_pct,omitempty"`
	FiredVsCandidateAvgLiftPct           *float64 `json:"fired_vs_candidate_avg_lift_pct,omitempty"`
	FiredVsCandidateMedianLiftPct        *float64 `json:"fired_vs_candidate_median_lift_pct,omitempty"`
	FiredVsNonFiredAvgLiftPct            *float64 `json:"fired_vs_non_fired_avg_lift_pct,omitempty"`
	FiredVsNonFiredMedianLiftPct         *float64 `json:"fired_vs_non_fired_median_lift_pct,omitempty"`
	AvgForwardReturnPct                  *float64 `json:"avg_forward_return_pct,omitempty"`
	AvgBenchmarkReturnPct                *float64 `json:"avg_benchmark_return_pct,omitempty"`
	AvgExcessReturnPct                   *float64 `json:"avg_excess_return_pct,omitempty"`
	AvgExcessReturnLower95Pct            *float64 `json:"avg_excess_return_lower_95_pct,omitempty"`
	MedianExcessReturnPct                *float64 `json:"median_excess_return_pct,omitempty"`
	WorstExcessReturnPct                 *float64 `json:"worst_excess_return_pct,omitempty"`
	BestExcessReturnPct                  *float64 `json:"best_excess_return_pct,omitempty"`
	AvgExecutionCostPct                  *float64 `json:"avg_execution_cost_pct,omitempty"`
	AvgNetExcessReturnPct                *float64 `json:"avg_net_excess_return_pct,omitempty"`
	AvgNetExcessReturnLower95Pct         *float64 `json:"avg_net_excess_return_lower_95_pct,omitempty"`
	MedianNetExcessReturnPct             *float64 `json:"median_net_excess_return_pct,omitempty"`
	WorstNetExcessReturnPct              *float64 `json:"worst_net_excess_return_pct,omitempty"`
	BestNetExcessReturnPct               *float64 `json:"best_net_excess_return_pct,omitempty"`
	AvgMaxAdverseExcursionPct            *float64 `json:"avg_max_adverse_excursion_pct,omitempty"`
	AvgMaxFavorableExcursionPct          *float64 `json:"avg_max_favorable_excursion_pct,omitempty"`
}

OpportunityBacktestMetrics summarizes classification, holdout, cost-adjusted return, concentration, and excursion measurements.

type OpportunityBacktestObservation

type OpportunityBacktestObservation struct {
	Date              string                         `json:"date,omitempty"`
	AsOf              time.Time                      `json:"as_of,omitzero"`
	Case              string                         `json:"case,omitempty"`
	Split             string                         `json:"split,omitempty"`
	SplitProvenance   OpportunitySplitProvenance     `json:"split_provenance,omitzero"`
	FeatureProvenance OpportunityFeatureProvenance   `json:"feature_provenance,omitzero"`
	LabelStatus       string                         `json:"label_status,omitempty"`
	MarketCluster     string                         `json:"market_cluster,omitempty"`
	Theme             string                         `json:"theme,omitempty"`
	Features          OpportunityPointInTimeFeatures `json:"features"`
	Signal            OpportunityBacktestSignal      `json:"signal"`
	Trade             OpportunityBacktestTrade       `json:"trade"`
	Outcome           OpportunityBacktestOutcome     `json:"outcome"`
	Target            OpportunityBacktestTarget      `json:"target"`
	Notes             string                         `json:"notes,omitempty"`
}

OpportunityBacktestObservation is one point-in-time research signal, trade model, realized outcome, and labelled opportunity target.

type OpportunityBacktestOutcome

type OpportunityBacktestOutcome struct {
	EntryDate                string   `json:"entry_date,omitempty"`
	ExitDate                 string   `json:"exit_date,omitempty"`
	EntryPrice               *float64 `json:"entry_price,omitempty"`
	ExitPrice                *float64 `json:"exit_price,omitempty"`
	PriceSource              string   `json:"price_source,omitempty"`
	BenchmarkSource          string   `json:"benchmark_source,omitempty"`
	Formula                  string   `json:"formula,omitempty"`
	PriceBasis               string   `json:"price_basis,omitempty"`
	SourceChecksum           string   `json:"source_checksum,omitempty"`
	BenchmarkSourceChecksum  string   `json:"benchmark_source_checksum,omitempty"`
	ForwardReturnPct         float64  `json:"forward_return_pct"`
	BenchmarkReturnPct       float64  `json:"benchmark_return_pct"`
	ExcessReturnPct          float64  `json:"excess_return_pct"`
	MaxAdverseExcursionPct   float64  `json:"max_adverse_excursion_pct"`
	MaxFavorableExcursionPct float64  `json:"max_favorable_excursion_pct"`
}

OpportunityBacktestOutcome contains the observed forward return, benchmark, excursion, and source-integrity measurements for a trade horizon.

type OpportunityBacktestResult

type OpportunityBacktestResult struct {
	RunAt        time.Time                           `json:"run_at"`
	Policy       string                              `json:"policy"`
	Observations []OpportunityBacktestRowResult      `json:"observations"`
	Metrics      OpportunityBacktestMetrics          `json:"metrics"`
	Simulation   OpportunityBacktestSimulation       `json:"simulation"`
	Evidence     OpportunityBacktestEvidence         `json:"evidence"`
	Diagnostics  OpportunityBacktestDiagnostics      `json:"diagnostics,omitzero"`
	Clusters     []OpportunityBacktestClusterMetrics `json:"clusters,omitempty"`
	Findings     []string                            `json:"findings,omitempty"`
	NotAdvice    string                              `json:"not_advice"`
}

OpportunityBacktestResult contains evaluated rows, portfolio simulation, evidence sufficiency, diagnostics, and aggregate metrics for one replay.

type OpportunityBacktestRowResult

type OpportunityBacktestRowResult struct {
	Date                 string                     `json:"date,omitempty"`
	Case                 string                     `json:"case,omitempty"`
	Split                string                     `json:"split,omitempty"`
	SplitProvenance      OpportunitySplitProvenance `json:"split_provenance,omitzero"`
	LabelStatus          string                     `json:"label_status,omitempty"`
	Holdout              bool                       `json:"holdout"`
	RetrospectiveHoldout bool                       `json:"retrospective_holdout,omitempty"`
	MarketCluster        string                     `json:"market_cluster,omitempty"`
	Theme                string                     `json:"theme,omitempty"`
	TargetOpportunity    bool                       `json:"target_opportunity"`
	TargetKind           string                     `json:"target_kind,omitempty"`
	TargetScope          string                     `json:"target_scope,omitempty"`
	SignalFired          bool                       `json:"signal_fired"`
	SignalKind           string                     `json:"signal_kind,omitempty"`
	SignalConfidence     string                     `json:"signal_confidence,omitempty"`
	SignalSource         string                     `json:"signal_source,omitempty"`
	SignalReasons        []string                   `json:"signal_reasons,omitempty"`
	SignalContextBlocked bool                       `json:"signal_context_blocked,omitempty"`
	TruePositive         bool                       `json:"true_positive"`
	FalsePositive        bool                       `json:"false_positive"`
	Miss                 bool                       `json:"miss"`
	PositiveExcess       bool                       `json:"positive_excess"`
	ExecutionCostPct     *float64                   `json:"execution_cost_pct,omitempty"`
	NetExcessReturnPct   *float64                   `json:"net_excess_return_pct,omitempty"`
	PositiveNetExcess    *bool                      `json:"positive_net_excess,omitempty"`
	Trade                OpportunityBacktestTrade   `json:"trade"`
	Outcome              OpportunityBacktestOutcome `json:"outcome"`
	// contains filtered or unexported fields
}

OpportunityBacktestRowResult records signal classification and cost-adjusted outcome measurements for one observation.

type OpportunityBacktestSignal

type OpportunityBacktestSignal struct {
	Fired      bool     `json:"fired"`
	Kind       string   `json:"kind,omitempty"`
	Confidence string   `json:"confidence,omitempty"`
	Source     string   `json:"source,omitempty"`
	Reasons    []string `json:"reasons,omitempty"`
}

OpportunityBacktestSignal records whether a research rule fired and the provenance and reasons it reported.

type OpportunityBacktestSimulation

type OpportunityBacktestSimulation struct {
	Model                string                             `json:"model,omitempty"`
	Signals              int                                `json:"signals"`
	FilledSignals        int                                `json:"filled_signals"`
	SkippedSignals       int                                `json:"skipped_signals"`
	MaxSlots             int                                `json:"max_slots"`
	MaxConcurrent        int                                `json:"max_concurrent"`
	AvgConcurrent        *float64                           `json:"avg_concurrent,omitempty"`
	InvestedExposureDays int                                `json:"invested_exposure_days"`
	PortfolioReturnPct   *float64                           `json:"portfolio_return_pct,omitempty"`
	BenchmarkReturnPct   *float64                           `json:"benchmark_return_pct,omitempty"`
	ExcessReturnPct      *float64                           `json:"excess_return_pct,omitempty"`
	TurnoverPct          *float64                           `json:"turnover_pct,omitempty"`
	AvgHoldDays          *float64                           `json:"avg_hold_days,omitempty"`
	CashDragDays         int                                `json:"cash_drag_days"`
	WindowStart          string                             `json:"window_start,omitempty"`
	WindowEnd            string                             `json:"window_end,omitempty"`
	Limitations          []string                           `json:"limitations,omitempty"`
	MarkToMarket         *OpportunityMarkToMarketSimulation `json:"mark_to_market,omitempty"`
	Holdout              *OpportunityBacktestSimulation     `json:"holdout,omitempty"`
}

OpportunityBacktestSimulation summarizes a bounded-slot portfolio replay and its explicit limitations.

type OpportunityBacktestTarget

type OpportunityBacktestTarget struct {
	Opportunity bool   `json:"opportunity"`
	Scope       string `json:"scope,omitempty"`
	Kind        string `json:"kind,omitempty"`
	Source      string `json:"source,omitempty"`
	Method      string `json:"method,omitempty"`
	Notes       string `json:"notes,omitempty"`
}

OpportunityBacktestTarget records the labelled opportunity outcome and its source and method.

type OpportunityBacktestTrade

type OpportunityBacktestTrade struct {
	Instrument       string   `json:"instrument,omitempty"`
	EntryRule        string   `json:"entry_rule,omitempty"`
	HorizonDays      int      `json:"horizon_days,omitempty"`
	Benchmark        string   `json:"benchmark,omitempty"`
	RoundTripCostBps *float64 `json:"round_trip_cost_bps,omitempty"`
	CostModel        string   `json:"cost_model,omitempty"`
}

OpportunityBacktestTrade describes the instrument, horizon, benchmark, and execution-cost assumptions used to score an observation.

type OpportunityFeatureProvenance

type OpportunityFeatureProvenance struct {
	Source   string `json:"source,omitempty"`
	Method   string `json:"method,omitempty"`
	Checksum string `json:"checksum,omitempty"`
}

OpportunityFeatureProvenance identifies the source, construction method, and integrity checksum for captured point-in-time features.

func (OpportunityFeatureProvenance) IsZero

IsZero reports whether no feature provenance fields are populated.

type OpportunityMacroContext

type OpportunityMacroContext struct {
	Source                     string          `json:"source,omitempty"`
	AsOf                       time.Time       `json:"as_of,omitzero"`
	Fingerprint                rpc.Fingerprint `json:"fingerprint,omitzero"`
	Label                      string          `json:"label,omitempty"`
	Tone                       string          `json:"tone,omitempty"`
	Stage                      string          `json:"stage,omitempty"`
	Severity                   string          `json:"severity,omitempty"`
	Readiness                  string          `json:"readiness,omitempty"`
	Confidence                 string          `json:"confidence,omitempty"`
	ClusterGreenCount          int             `json:"cluster_green_count,omitempty"`
	ClusterYellowCount         int             `json:"cluster_yellow_count,omitempty"`
	ClusterRedCount            int             `json:"cluster_red_count,omitempty"`
	ClusterRankedCount         int             `json:"cluster_ranked_count,omitempty"`
	ClusterEligibleRedCount    int             `json:"cluster_eligible_red_count,omitempty"`
	ClusterProvisionalRedCount int             `json:"cluster_provisional_red_count,omitempty"`
	Error                      string          `json:"error,omitempty"`
}

OpportunityMacroContext captures the regime evidence attached to an opportunity row, including its source time and semantic fingerprint.

type OpportunityMarkToMarketSimulation

type OpportunityMarkToMarketSimulation struct {
	Model                      string   `json:"model,omitempty"`
	Trades                     int      `json:"trades"`
	Bars                       int      `json:"bars"`
	MinTradeMarks              int      `json:"min_trade_marks"`
	MaxTradeMarkGapDays        int      `json:"max_trade_mark_gap_days"`
	PriceSource                string   `json:"price_source,omitempty"`
	SourceChecksum             string   `json:"source_checksum,omitempty"`
	SourceManifest             string   `json:"source_manifest,omitempty"`
	SourceManifestChecksum     string   `json:"source_manifest_checksum,omitempty"`
	SourceProvider             string   `json:"source_provider,omitempty"`
	SourceMethod               string   `json:"source_method,omitempty"`
	SourceCreatedAt            string   `json:"source_created_at,omitempty"`
	SourceQuality              string   `json:"source_quality,omitempty"`
	SourceWarnings             []string `json:"source_warnings,omitempty"`
	BarSources                 []string `json:"bar_sources,omitempty"`
	PriceBasis                 string   `json:"price_basis,omitempty"`
	PortfolioReturnPct         *float64 `json:"portfolio_return_pct,omitempty"`
	BenchmarkReturnPct         *float64 `json:"benchmark_return_pct,omitempty"`
	ExcessReturnPct            *float64 `json:"excess_return_pct,omitempty"`
	MaxDrawdownPct             *float64 `json:"max_drawdown_pct,omitempty"`
	BenchmarkMaxDrawdownPct    *float64 `json:"benchmark_max_drawdown_pct,omitempty"`
	WorstBarReturnPct          *float64 `json:"worst_bar_return_pct,omitempty"`
	BestBarReturnPct           *float64 `json:"best_bar_return_pct,omitempty"`
	BarReturnVolPct            *float64 `json:"bar_return_vol_pct,omitempty"`
	BenchmarkBarReturnVolPct   *float64 `json:"benchmark_bar_return_vol_pct,omitempty"`
	EndPortfolioEquityMultiple *float64 `json:"end_portfolio_equity_multiple,omitempty"`
	EndBenchmarkEquityMultiple *float64 `json:"end_benchmark_equity_multiple,omitempty"`
	Limitations                []string `json:"limitations,omitempty"`
}

OpportunityMarkToMarketSimulation summarizes bar-by-bar portfolio and benchmark performance with source provenance and data-quality limits.

type OpportunityPointInTimeFeatures

type OpportunityPointInTimeFeatures struct {
	Instrument         string                   `json:"instrument,omitempty"`
	SecType            string                   `json:"sec_type,omitempty"`
	Exchange           string                   `json:"exchange,omitempty"`
	Currency           string                   `json:"currency,omitempty"`
	LocalSymbol        string                   `json:"local_symbol,omitempty"`
	TradingClass       string                   `json:"trading_class,omitempty"`
	InstrumentTags     []string                 `json:"instrument_tags,omitempty"`
	ScanPreset         string                   `json:"scan_preset,omitempty"`
	ScanType           string                   `json:"scan_type,omitempty"`
	ScanRank           int                      `json:"scan_rank,omitempty"`
	DataType           string                   `json:"data_type,omitempty"`
	FeedType           string                   `json:"feed_type,omitempty"`
	QuoteQuality       string                   `json:"quote_quality,omitempty"`
	Indicative         bool                     `json:"indicative,omitempty"`
	Stale              bool                     `json:"stale,omitempty"`
	StaleReason        string                   `json:"stale_reason,omitempty"`
	QuoteError         string                   `json:"quote_error,omitempty"`
	TechnicalError     string                   `json:"technical_error,omitempty"`
	SessionContext     *rpc.MarketSession       `json:"session_context,omitempty"`
	PriceAsOf          string                   `json:"price_as_of,omitempty"`
	PriceAt            time.Time                `json:"price_at,omitzero"`
	DataQuality        string                   `json:"data_quality,omitempty"`
	TrendState         string                   `json:"trend_state,omitempty"`
	Price              *float64                 `json:"price,omitempty"`
	SMA50              *float64                 `json:"sma_50,omitempty"`
	SMA200             *float64                 `json:"sma_200,omitempty"`
	PctAbove50DMA      *float64                 `json:"pct_above_50dma,omitempty"`
	PctAbove200DMA     *float64                 `json:"pct_above_200dma,omitempty"`
	RS63D              *float64                 `json:"rs_63d,omitempty"`
	RS126D             *float64                 `json:"rs_126d,omitempty"`
	AvgDollarVolume20D *float64                 `json:"avg_dollar_volume_20d,omitempty"`
	Volume             *int64                   `json:"volume,omitempty"`
	ChangePct          *float64                 `json:"change_pct,omitempty"`
	EventGapPct        *float64                 `json:"event_gap_pct,omitempty"`
	ExtendedChaseRisk  bool                     `json:"extended_chase_risk,omitempty"`
	Macro              *OpportunityMacroContext `json:"macro,omitempty"`
}

OpportunityPointInTimeFeatures contains the market, liquidity, trend, and optional macro inputs available at capture time.

type OpportunityPointInTimeRow

type OpportunityPointInTimeRow struct {
	Date              string                         `json:"date,omitempty"`
	AsOf              time.Time                      `json:"as_of,omitzero"`
	Case              string                         `json:"case,omitempty"`
	Split             string                         `json:"split,omitempty"`
	SplitProvenance   OpportunitySplitProvenance     `json:"split_provenance,omitzero"`
	FeatureProvenance OpportunityFeatureProvenance   `json:"feature_provenance,omitzero"`
	LabelStatus       string                         `json:"label_status,omitempty"`
	MarketCluster     string                         `json:"market_cluster,omitempty"`
	Theme             string                         `json:"theme,omitempty"`
	Features          OpportunityPointInTimeFeatures `json:"features"`
	Trade             OpportunityBacktestTrade       `json:"trade"`
	Outcome           OpportunityBacktestOutcome     `json:"outcome"`
	Target            OpportunityBacktestTarget      `json:"target"`
	Notes             string                         `json:"notes,omitempty"`
}

OpportunityPointInTimeRow is a captured, pre-signal research row whose features, split assignment, and labels retain their provenance.

type OpportunityPriceBarRow

type OpportunityPriceBarRow struct {
	Symbol        string  `json:"symbol"`
	Date          string  `json:"date"`
	Open          float64 `json:"open,omitempty"`
	High          float64 `json:"high,omitempty"`
	Low           float64 `json:"low,omitempty"`
	Close         float64 `json:"close"`
	AdjustedClose float64 `json:"adjusted_close,omitempty"`
	Volume        int64   `json:"volume,omitempty"`
	Source        string  `json:"source,omitempty"`
}

OpportunityPriceBarRow is one dated market-data bar used to score forward opportunity outcomes and mark-to-market simulations.

type OpportunityResearchPlan

type OpportunityResearchPlan struct {
	ID          string `json:"id"`
	Family      string `json:"family,omitempty"`
	Description string `json:"description,omitempty"`
	Hypothesis  string `json:"hypothesis,omitempty"`
}

OpportunityResearchPlan describes one named signal hypothesis evaluated by the offline opportunity research workflow.

type OpportunityResearchPlanResult

type OpportunityResearchPlanResult struct {
	Rank           int                           `json:"rank"`
	Plan           OpportunityResearchPlan       `json:"plan"`
	RankValuePct   *float64                      `json:"rank_value_pct,omitempty"`
	Metrics        OpportunityBacktestMetrics    `json:"metrics"`
	TuningMetrics  OpportunityBacktestMetrics    `json:"tuning_metrics"`
	HoldoutMetrics OpportunityBacktestMetrics    `json:"holdout_metrics"`
	Simulation     OpportunityBacktestSimulation `json:"simulation"`
	Evidence       OpportunityBacktestEvidence   `json:"evidence"`
	Findings       []string                      `json:"findings,omitempty"`
}

OpportunityResearchPlanResult contains tuning and holdout results for one ranked research plan.

type OpportunityResearchResult

type OpportunityResearchResult struct {
	RunAt          time.Time                       `json:"run_at"`
	Rows           int                             `json:"rows"`
	PlansEvaluated int                             `json:"plans_evaluated"`
	RankedBy       string                          `json:"ranked_by"`
	PlanMode       string                          `json:"plan_mode"`
	Plans          []OpportunityResearchPlanResult `json:"plans"`
	Findings       []string                        `json:"findings,omitempty"`
	NotAdvice      string                          `json:"not_advice"`
}

OpportunityResearchResult ranks evaluated plans and retains their metrics, evidence status, findings, and simulation outputs.

type OpportunitySplitProvenance

type OpportunitySplitProvenance struct {
	Source                  string    `json:"source,omitempty"`
	Method                  string    `json:"method,omitempty"`
	PlanID                  string    `json:"plan_id,omitempty"`
	AssignedAt              time.Time `json:"assigned_at,omitzero"`
	LabelStatusAtAssignment string    `json:"label_status_at_assignment,omitempty"`
	PreRegistered           bool      `json:"pre_registered,omitempty"`
}

OpportunitySplitProvenance records how and when a tuning or holdout split was assigned, including whether it was preregistered before labels were known.

func (OpportunitySplitProvenance) IsZero

func (p OpportunitySplitProvenance) IsZero() bool

IsZero reports whether no split-assignment provenance is populated.

type RegimeBacktestClusterMetrics

type RegimeBacktestClusterMetrics struct {
	Name    string                `json:"name"`
	Metrics RegimeBacktestMetrics `json:"metrics"`
}

RegimeBacktestClusterMetrics associates regime metrics with one named market cluster.

type RegimeBacktestMetrics

type RegimeBacktestMetrics struct {
	Observations         int      `json:"observations"`
	ScoredObservations   int      `json:"scored_observations"`
	OutOfScope           int      `json:"out_of_scope"`
	TargetStress         int      `json:"target_stress"`
	NonStress            int      `json:"non_stress"`
	StressWatch          int      `json:"stress_watch"`
	StressSignal         int      `json:"stress_signal"`
	DataQualityWatch     int      `json:"data_quality_watch"`
	WatchTruePositive    int      `json:"watch_true_positive"`
	WatchFalsePositive   int      `json:"watch_false_positive"`
	WatchMiss            int      `json:"watch_miss"`
	WatchPrecision       *float64 `json:"watch_precision,omitempty"`
	WatchRecall          *float64 `json:"watch_recall,omitempty"`
	WatchFalseAlarmRate  *float64 `json:"watch_false_alarm_rate,omitempty"`
	WatchAvgLeadDays     *float64 `json:"watch_avg_lead_days,omitempty"`
	StressTruePositive   int      `json:"stress_true_positive"`
	StressFalsePositive  int      `json:"stress_false_positive"`
	StressMiss           int      `json:"stress_miss"`
	StressPrecision      *float64 `json:"stress_precision,omitempty"`
	StressRecall         *float64 `json:"stress_recall,omitempty"`
	StressFalseAlarmRate *float64 `json:"stress_false_alarm_rate,omitempty"`
	StressAvgLeadDays    *float64 `json:"stress_avg_lead_days,omitempty"`
}

RegimeBacktestMetrics summarizes scored regime watch and stress-signal performance; out-of-scope rows are counted separately.

type RegimeBacktestObservation

type RegimeBacktestObservation struct {
	Date          string                   `json:"date,omitempty"`
	AsOf          time.Time                `json:"as_of,omitzero"`
	Case          string                   `json:"case,omitempty"`
	MarketCluster string                   `json:"market_cluster,omitempty"`
	Regime        rpc.RegimeSnapshotResult `json:"regime"`
	Target        RegimeBacktestTarget     `json:"target"`
	Notes         string                   `json:"notes,omitempty"`
}

RegimeBacktestObservation is one point-in-time regime snapshot and its labelled forward stress target.

type RegimeBacktestResult

type RegimeBacktestResult struct {
	RunAt        time.Time                      `json:"run_at"`
	Policy       string                         `json:"policy"`
	Observations []RegimeBacktestRowResult      `json:"observations"`
	Metrics      RegimeBacktestMetrics          `json:"metrics"`
	Baseline     RegimeBacktestMetrics          `json:"baseline"`
	Lifecycle    BacktestLifecycleMetrics       `json:"lifecycle"`
	Events       BacktestEventMetrics           `json:"events"`
	Clusters     []RegimeBacktestClusterMetrics `json:"clusters,omitempty"`
	Findings     []string                       `json:"findings,omitempty"`
	NotAdvice    string                         `json:"not_advice"`
}

RegimeBacktestResult contains row-level regime evaluations and aggregate detection, lifecycle, and baseline metrics for one replay.

type RegimeBacktestRowResult

type RegimeBacktestRowResult struct {
	Date              string                    `json:"date,omitempty"`
	Case              string                    `json:"case,omitempty"`
	MarketCluster     string                    `json:"market_cluster,omitempty"`
	TargetStress      bool                      `json:"target_stress"`
	TargetKind        string                    `json:"target_kind,omitempty"`
	TargetScope       string                    `json:"target_scope,omitempty"`
	Scored            bool                      `json:"scored"`
	WindowDays        int                       `json:"window_days,omitempty"`
	DaysToStress      *int                      `json:"days_to_stress,omitempty"`
	MaxSPYDrawdownPct *float64                  `json:"max_spy_drawdown_pct,omitempty"`
	VIXShockPct       *float64                  `json:"vix_shock_pct,omitempty"`
	Verdict           string                    `json:"verdict,omitempty"`
	RedClusters       int                       `json:"red_clusters"`
	YellowClusters    int                       `json:"yellow_clusters"`
	RankedClusters    int                       `json:"ranked_clusters"`
	UnrankedClusters  int                       `json:"unranked_clusters"`
	RedClusterNames   []string                  `json:"red_cluster_names,omitempty"`
	LifecycleStage    string                    `json:"lifecycle_stage,omitempty"`
	StressWatch       bool                      `json:"stress_watch"`
	StressSignal      bool                      `json:"stress_signal"`
	DataQualityWatch  bool                      `json:"data_quality_watch"`
	EarlyWarning      bool                      `json:"early_warning"`
	ConfirmedStress   bool                      `json:"confirmed_stress"`
	Panic             bool                      `json:"panic"`
	Stabilization     bool                      `json:"stabilization"`
	Opportunity       bool                      `json:"opportunity"`
	BaselineWatch     bool                      `json:"baseline_watch"`
	BaselineStress    bool                      `json:"baseline_stress"`
	Regime            *rpc.RegimeSnapshotResult `json:"regime,omitempty"`
}

RegimeBacktestRowResult records the regime verdict, evidence counts, and scoring flags for one labelled observation.

type RegimeBacktestTarget

type RegimeBacktestTarget struct {
	Stress            bool     `json:"stress"`
	Kind              string   `json:"kind,omitempty"`
	Scope             string   `json:"scope,omitempty"`
	WindowDays        int      `json:"window_days,omitempty"`
	DaysToStress      *int     `json:"days_to_stress,omitempty"`
	MaxSPYDrawdownPct *float64 `json:"max_spy_drawdown_pct,omitempty"`
	VIXShockPct       *float64 `json:"vix_shock_pct,omitempty"`
	Notes             string   `json:"notes,omitempty"`
}

RegimeBacktestTarget records the forward-window stress label used to score a regime observation.

type RegimePointInTimeBreadth

type RegimePointInTimeBreadth struct {
	RegimePointInTimeMeta
	PctAbove50DMA  *float64 `json:"pct_above_50dma,omitempty"`
	PctAbove200DMA *float64 `json:"pct_above_200dma,omitempty"`
	NewHighsToday  int      `json:"new_highs_today,omitempty"`
	NewLowsToday   int      `json:"new_lows_today,omitempty"`
	NetNewHighsPct *float64 `json:"net_new_highs_pct,omitempty"`
}

RegimePointInTimeBreadth captures moving-average participation and new-high versus new-low inputs.

type RegimePointInTimeCredit

type RegimePointInTimeCredit struct {
	RegimePointInTimeMeta
	HYOAS       *float64 `json:"hy_oas,omitempty"`
	IGOAS       *float64 `json:"ig_oas,omitempty"`
	HYIGSpread  *float64 `json:"hy_ig_spread,omitempty"`
	HY20DChange *float64 `json:"hy_oas_20d_change,omitempty"`
}

RegimePointInTimeCredit captures investment-grade and high-yield spread inputs.

type RegimePointInTimeFunding

type RegimePointInTimeFunding struct {
	RegimePointInTimeMeta
	CP3M      *float64 `json:"cp_3m_rate,omitempty"`
	TBill3M   *float64 `json:"tbill_3m_rate,omitempty"`
	SpreadBps *float64 `json:"spread_bps,omitempty"`
}

RegimePointInTimeFunding captures commercial-paper and Treasury-bill funding spread inputs.

type RegimePointInTimeGamma

type RegimePointInTimeGamma struct {
	Trusted  bool                   `json:"trusted,omitempty"`
	Method   string                 `json:"method,omitempty"`
	Source   string                 `json:"source,omitempty"`
	AsOf     time.Time              `json:"as_of,omitzero"`
	Envelope rpc.GammaZeroSPXResult `json:"envelope"`
}

RegimePointInTimeGamma captures a gamma envelope with its source and trust classification.

type RegimePointInTimeHYGSPY

type RegimePointInTimeHYGSPY struct {
	RegimePointInTimeMeta
	HYGPrice     *float64 `json:"hyg_price,omitempty"`
	HYG50DMA     *float64 `json:"hyg_50dma,omitempty"`
	SPYPrice     *float64 `json:"spy_price,omitempty"`
	SPY52WHigh   *float64 `json:"spy_52w_high,omitempty"`
	SPYPrevClose *float64 `json:"spy_prev_close,omitempty"`
	SPYChange    *float64 `json:"spy_change,omitempty"`
	SPYChangePct *float64 `json:"spy_change_pct,omitempty"`
}

RegimePointInTimeHYGSPY captures high-yield credit and equity divergence inputs.

type RegimePointInTimeMeta

type RegimePointInTimeMeta struct {
	Status   string    `json:"status,omitempty"`
	Source   string    `json:"source,omitempty"`
	AsOf     time.Time `json:"as_of,omitzero"`
	AsOfDate string    `json:"as_of_date,omitempty"`
}

RegimePointInTimeMeta carries source, status, and observation time shared by captured regime clusters.

type RegimePointInTimeRow

type RegimePointInTimeRow struct {
	Date             string                    `json:"date,omitempty"`
	AsOf             time.Time                 `json:"as_of,omitzero"`
	Case             string                    `json:"case,omitempty"`
	MarketCluster    string                    `json:"market_cluster,omitempty"`
	VIXTermStructure RegimePointInTimeVIXTerm  `json:"vix_term_structure"`
	VolOfVol         RegimePointInTimeVolOfVol `json:"vol_of_vol"`
	HYGSPYDivergence RegimePointInTimeHYGSPY   `json:"hyg_spy_divergence"`
	CreditSpreads    RegimePointInTimeCredit   `json:"credit_spreads"`
	FundingStress    RegimePointInTimeFunding  `json:"funding_stress"`
	USDJPY           RegimePointInTimeUSDJPY   `json:"usd_jpy"`
	GammaZero        *RegimePointInTimeGamma   `json:"gamma_zero,omitempty"`
	Breadth          RegimePointInTimeBreadth  `json:"breadth"`
	Target           RegimeBacktestTarget      `json:"target"`
	Notes            string                    `json:"notes,omitempty"`
}

RegimePointInTimeRow is a captured market panel and forward stress target used to rebuild a regime observation without future data.

type RegimePointInTimeUSDJPY

type RegimePointInTimeUSDJPY struct {
	RegimePointInTimeMeta
	Last         *float64 `json:"last,omitempty"`
	Close7DAgo   *float64 `json:"close_7d_ago,omitempty"`
	WeeklyChange *float64 `json:"weekly_change_pct,omitempty"`
}

RegimePointInTimeUSDJPY captures USD/JPY level and weekly-change inputs.

type RegimePointInTimeVIXTerm

type RegimePointInTimeVIXTerm struct {
	RegimePointInTimeMeta
	VIX          *float64 `json:"vix,omitempty"`
	VIX3M        *float64 `json:"vix3m,omitempty"`
	Ratio        *float64 `json:"ratio,omitempty"`
	VIXPrevClose *float64 `json:"vix_prev_close,omitempty"`
	VIXChangePct *float64 `json:"vix_change_pct,omitempty"`
}

RegimePointInTimeVIXTerm captures VIX term-structure inputs and their shared point-in-time metadata.

type RegimePointInTimeVolOfVol

type RegimePointInTimeVolOfVol struct {
	RegimePointInTimeMeta
	Last      *float64 `json:"last,omitempty"`
	Change20D *float64 `json:"change_20d_pct,omitempty"`
}

RegimePointInTimeVolOfVol captures volatility-of-volatility inputs.

type StressBacktestClusterMetrics

type StressBacktestClusterMetrics struct {
	Name    string                `json:"name"`
	Metrics StressBacktestMetrics `json:"metrics"`
}

StressBacktestClusterMetrics associates stress metrics with one named category or market cluster.

type StressBacktestMetrics

type StressBacktestMetrics struct {
	Observations         int      `json:"observations"`
	TargetStress         int      `json:"target_stress"`
	NonStress            int      `json:"non_stress"`
	SignalWatch          int      `json:"signal_watch"`
	DefensiveWatch       int      `json:"defensive_watch"`
	DefensiveAct         int      `json:"defensive_act"`
	RebalanceWatch       int      `json:"rebalance_watch"`
	DataQualityWatch     int      `json:"data_quality_watch"`
	Blocked              int      `json:"blocked"`
	SignalTruePositive   int      `json:"signal_true_positive"`
	SignalFalsePositive  int      `json:"signal_false_positive"`
	SignalMiss           int      `json:"signal_miss"`
	SignalPrecision      *float64 `json:"signal_precision,omitempty"`
	SignalRecall         *float64 `json:"signal_recall,omitempty"`
	SignalFalseAlarmRate *float64 `json:"signal_false_alarm_rate,omitempty"`
	SignalAvgLeadDays    *float64 `json:"signal_avg_lead_days,omitempty"`
	WatchTruePositive    int      `json:"watch_true_positive"`
	WatchFalsePositive   int      `json:"watch_false_positive"`
	WatchMiss            int      `json:"watch_miss"`
	WatchPrecision       *float64 `json:"watch_precision,omitempty"`
	WatchRecall          *float64 `json:"watch_recall,omitempty"`
	WatchFalseAlarmRate  *float64 `json:"watch_false_alarm_rate,omitempty"`
	WatchAvgLeadDays     *float64 `json:"watch_avg_lead_days,omitempty"`
	ActTruePositive      int      `json:"act_true_positive"`
	ActFalsePositive     int      `json:"act_false_positive"`
	ActMiss              int      `json:"act_miss"`
	ActPrecision         *float64 `json:"act_precision,omitempty"`
	ActRecall            *float64 `json:"act_recall,omitempty"`
	ActFalseAlarmRate    *float64 `json:"act_false_alarm_rate,omitempty"`
	ActAvgLeadDays       *float64 `json:"act_avg_lead_days,omitempty"`
}

StressBacktestMetrics summarizes row-level watch and defensive-action classification performance.

type StressBacktestObservation

type StressBacktestObservation struct {
	Date          string                   `json:"date,omitempty"`
	AsOf          time.Time                `json:"as_of,omitzero"`
	Case          string                   `json:"case,omitempty"`
	MarketCluster string                   `json:"market_cluster,omitempty"`
	Account       rpc.AccountResult        `json:"account"`
	Positions     rpc.PositionsResult      `json:"positions"`
	Regime        rpc.RegimeSnapshotResult `json:"regime"`
	Target        StressBacktestTarget     `json:"target"`
	Notes         string                   `json:"notes,omitempty"`
}

StressBacktestObservation is one point-in-time stress input and its labelled forward stress target.

type StressBacktestRegimeLift

type StressBacktestRegimeLift struct {
	PortfolioStressRows         int      `json:"portfolio_stress_rows"`
	RegimeOnlyWatchTruePositive int      `json:"regime_only_watch_true_positive"`
	StressWatchTruePositive     int      `json:"stress_watch_true_positive"`
	StressAddedTruePositive     int      `json:"stress_added_true_positive"`
	RegimeOnlyRecall            *float64 `json:"regime_only_recall,omitempty"`
	StressRecall                *float64 `json:"stress_recall,omitempty"`
}

StressBacktestRegimeLift compares stress watch recall with the regime-only baseline on portfolio-stress rows.

type StressBacktestResult

type StressBacktestResult struct {
	RunAt        time.Time                      `json:"run_at"`
	Policy       string                         `json:"policy"`
	Observations []StressBacktestRowResult      `json:"observations"`
	Metrics      StressBacktestMetrics          `json:"metrics"`
	RegimeOnly   StressBacktestMetrics          `json:"regime_only"`
	Lifecycle    BacktestLifecycleMetrics       `json:"lifecycle"`
	Events       BacktestEventMetrics           `json:"events"`
	Categories   []StressBacktestClusterMetrics `json:"categories,omitempty"`
	RegimeLift   StressBacktestRegimeLift       `json:"regime_lift,omitzero"`
	Clusters     []StressBacktestClusterMetrics `json:"clusters,omitempty"`
	Findings     []string                       `json:"findings,omitempty"`
	NotAdvice    string                         `json:"not_advice"`
}

StressBacktestResult contains row-level stress evaluations and aggregate detection, lifecycle, and regime-lift metrics for one replay.

type StressBacktestRowResult

type StressBacktestRowResult struct {
	Date               string                `json:"date,omitempty"`
	Case               string                `json:"case,omitempty"`
	MarketCluster      string                `json:"market_cluster,omitempty"`
	TargetStress       bool                  `json:"target_stress"`
	TargetKind         string                `json:"target_kind,omitempty"`
	TargetScope        string                `json:"target_scope,omitempty"`
	WindowDays         int                   `json:"window_days,omitempty"`
	DaysToStress       *int                  `json:"days_to_stress,omitempty"`
	MaxSPYDrawdownPct  *float64              `json:"max_spy_drawdown_pct,omitempty"`
	VIXShockPct        *float64              `json:"vix_shock_pct,omitempty"`
	Direction          risk.SignalDirection  `json:"direction,omitempty"`
	Action             string                `json:"action,omitempty"`
	MarketConfirmation string                `json:"market_confirmation,omitempty"`
	PortfolioFit       string                `json:"portfolio_fit,omitempty"`
	InputHealth        string                `json:"input_health,omitempty"`
	Severity           risk.SignalSeverity   `json:"severity"`
	PlannerMode        risk.PlannerMode      `json:"planner_mode,omitempty"`
	PlannerReadiness   risk.PlannerReadiness `json:"planner_readiness,omitempty"`
	PrimaryDrivers     []risk.SignalID       `json:"primary_drivers,omitempty"`
	LifecycleStage     string                `json:"lifecycle_stage,omitempty"`
	SignalWatch        bool                  `json:"signal_watch"`
	DefensiveWatch     bool                  `json:"defensive_watch"`
	DefensiveAct       bool                  `json:"defensive_act"`
	RebalanceWatch     bool                  `json:"rebalance_watch"`
	DataQualityWatch   bool                  `json:"data_quality_watch"`
	Blocked            bool                  `json:"blocked"`
	EarlyWarning       bool                  `json:"early_warning"`
	ConfirmedStress    bool                  `json:"confirmed_stress"`
	Panic              bool                  `json:"panic"`
	Stabilization      bool                  `json:"stabilization"`
	Opportunity        bool                  `json:"opportunity"`
	RegimeOnlyWatch    bool                  `json:"regime_only_watch"`
	RegimeOnlyAct      bool                  `json:"regime_only_act"`
	Stress             *rpc.StressResult     `json:"stress,omitempty"`
}

StressBacktestRowResult records the stress decision and scoring flags for one labelled observation.

type StressBacktestTarget

type StressBacktestTarget struct {
	Stress            bool     `json:"stress"`
	Kind              string   `json:"kind,omitempty"`
	Scope             string   `json:"scope,omitempty"`
	WindowDays        int      `json:"window_days,omitempty"`
	DaysToStress      *int     `json:"days_to_stress,omitempty"`
	MaxSPYDrawdownPct *float64 `json:"max_spy_drawdown_pct,omitempty"`
	VIXShockPct       *float64 `json:"vix_shock_pct,omitempty"`
	Notes             string   `json:"notes,omitempty"`
}

StressBacktestTarget records the forward-window stress label used to score a stress observation.

type StressInput

type StressInput = rpc.StressInput

StressInput is the typed input consumed by the shared stress evaluator.

type StressMarketIndicator

type StressMarketIndicator = rpc.StressMarketIndicator

StressMarketIndicator is one normalized market input in a stress summary.

type StressMarketSummary

type StressMarketSummary = rpc.StressMarketSummary

StressMarketSummary is the market-side evidence summarized for the stress read.

type StressResult

type StressResult = rpc.StressResult

StressResult is the complete typed output of a stress evaluation.

func ComputeStress

func ComputeStress(in StressInput) StressResult

ComputeStress evaluates in through the shared pure stress engine.

type StressRow

type StressRow = rpc.StressRow

StressRow is one evidence row in a stress result.

type SubcommandSpec

type SubcommandSpec struct {
	Name  string
	Guard GuardClass
}

SubcommandSpec captures nested command words that are useful for completion and guard classification. The existing handlers remain authoritative for parsing and validation.

type TUISupport

type TUISupport string

TUISupport describes how the full-screen terminal app should handle a command. External commands are advertised for discovery but should be run in a regular terminal because they own a process, stdio stream, or installer lifecycle outside the TUI's prompt/output model.

const (
	TUISupported TUISupport = "supported"
	TUIExternal  TUISupport = "external"
)

TUI support classifications used by the command catalog.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL