totalfinance.artifact.compare
Compare a baseline and a candidate artifact of the same type leaf by leaf: value differences with absolute and relative deltas, added and removed paths, whether inputs and producers match, and — when a tolerance is supplied — whether every numeric leaf is within it. The result is compareAnalysisArtifacts(...) verbatim.
artifact · Opt-in · Full schemas and capability contract
totalfinance.artifact.read
Validate a Gate B analysis artifact (its envelope, its recomputed inputs hash, and its content-hash identity) and return its identity, type, producer, provenance warnings, table names, and a bounded preview of the stored result — the one read door for any artifact over the wire. Migrations are not registered over the wire; a stored older version is refused with the versions named.
artifact · Opt-in · Full schemas and capability contract
totalfinance.backtest.cross_sectional_run
Backtest a point-in-time cross-sectional strategy: a returns dataset with declared features, a universe history with entries and exits, one declarative signal (a versioned factor recipe, a composite score, or a screen), a rebalance schedule, and a portfolio construction (quantile/count/fraction selection on each side; equal, score, inverse-volatility, or risk-budget weights; dollar/sector/beta/factor neutrality; position, weight, turnover, and participation caps — every trim a reported goal). Fills go through the execution policy into the portfolio ledger; the final value reconciles to the ledger NAV. Rebalances, holdings, fills, the ledger, the timeline, attribution, the benchmark block, and the performance summary — crossSectionalBacktest(...) verbatim. Opt-in (backtestPack): payloads and runtime are heavier than the default set; bulk row sets above the row cap travel by handle.
backtest · Opt-in · Full schemas and capability contract
totalfinance.backtest.environment_episode
Run one of the six maintained baseline policies through the deterministic trading environment over a catalogue episode (or a named declarative definition) at a seed, and return Agent Bench's report for that episode: operational conformance (look-ahead, replay equality, duplicate orders under the retry drive, external-order attempts, reconciliation; the mask and limit counts) apart from strategy quality (return, volatility, Sharpe, Sortino, drawdown, turnover, cost, exposure, violations) — no single score by design. With artifact: 'embed', the recorded episode travels as an `environment` run artifact that replays to its run hash. Declarative inputs only: a TypeScript policy or a reward goal callback is SDK-only. Opt-in (backtestPack).
backtest · Opt-in · Full schemas and capability contract
totalfinance.backtest.options_run
Backtest a declarative options strategy over chain snapshots: structure selection by delta and DTE, exit and roll triggers, optional delta hedging, declarative commission and slippage, American assignment modelling, and the marking policy (current-quote or entry volatility; what a missing mark does). Several rules may hold several trades at once (book), pre-trade limits reject entries with rows, combo or legged fills, quote freshness, split lineage, dividend evidence, the surface summary, and the portfolio ledger the equity reconciles to. Equity points, trades with per-leg attribution and mark counts, settlements, and the standard performance summary. The result is optionsBacktest(...) verbatim. Opt-in (backtestPack): payloads and runtime are heavier than the default set.
backtest · Opt-in · Full schemas and capability contract
totalfinance.backtest.portfolio_run
Backtest a multi-asset portfolio through the ledger: instruments with built-in adapters (equity, etf, option, future, fx-forward, crypto-spot, crypto-perpetual, bond), market data by row set, a model or inline targets on a rebalance schedule, an execution policy with settlement lags, external flows, a calendar, and the margin check with forced liquidation. Every fill, flow, lifecycle fact, and liquidation is a portfolio event; the equity is the ledger's net asset value. The result is portfolioBacktest(...) verbatim. Opt-in (backtestPack): payloads and runtime are heavier than the default set; bulk row sets above the row cap travel by handle.
backtest · Opt-in · Full schemas and capability contract
totalfinance.backtest.vectorized_run
Run a single-asset vectorized backtest: signal-following fills at close, optional bps fees. Returns final value, turnover, and the performance summary; every hidden policy the run assumed (fill timing, costs, slippage, settlement, calendar, margin) is echoed in `assumptions`, and the implementation-risk warnings (look-ahead, data alignment) ride `diagnostics`. Deliberately opt-in (backtestPack) — payloads and runtime are heavier than the default tools. executionLag shifts signal lookup before rebalance sampling; a month-end target can miss the next monthly sample. Use the SDK researchProtocol and selection-hygiene workflow before comparing candidates; see docs/guides/dogfood-journeys.md.
backtest · Opt-in · Full schemas and capability contract
totalfinance.calendar.sessions
Trading days, holidays, and half days for an exchange calendar over a date range (≤ ~13 months), plus option expirations (weekly Fridays / monthly OPEX / quarterly, shifted off holidays from the calendar data) when `expirationKind` is set, and the next expiry after the range start. NYSE/CBOE one-off closure coverage begins 2001-01-01; earlier ranges carry a diagnostic. Rules project other dates, not future emergency closures.
calendar · Default · Full schemas and capability contract
totalfinance.crypto.futures_basis
Annualized basis of a dated future over spot — the cash-and-carry yield. Reports raw and percentage basis, simple and continuously-compounded annualization, contango/backwardation, and flags an arbitrage-sized basis.
crypto · Default · Full schemas and capability contract
totalfinance.crypto.perpetual_funding
Annualize a perpetual funding rate into the implied cost-of-carry: the mark/index premium, simple and compounded annualized funding, and an extreme-funding flag. All rates are decimals; the interval defaults to the standard 8 hours.
crypto · Default · Full schemas and capability contract
totalfinance.fixed_income.bond_analytics
Full fixed-rate bond analytics from a specification: given a `yield`, price it; given a `price`, solve the yield to maturity — then report clean/dirty price, accrued interest, Macaulay/modified duration, convexity, and DV01. Dates are YYYY-MM-DD; rates are decimals.
fixed_income · Default · Full schemas and capability contract
totalfinance.option.greeks
Compute first-order Greeks (delta, gamma, theta/day, vega/1%, rho/1%) for a European option under Black–Scholes–Merton. Supply time as timeToExpiryYears (years) or as expiry + asOf (dates).
options · Default · Full schemas and capability contract
totalfinance.option.implied_volatility
Solve Black–Scholes–Merton implied volatility from an observed option price using the method suite (auto/brent/newton/halley/householder, with an optional Brent fallback). Supply time as timeToExpiryYears (years) or as expiry + asOf (dates). Non-convergence and no-arbitrage failures are reported in diagnostics (converged: false), never fabricated; the method actually used is echoed in diagnostics.method.
options · Default · Full schemas and capability contract
totalfinance.option.price
Price a European option with the Black–Scholes–Merton model. Supply time as timeToExpiryYears (years) or as expiry + asOf (dates). Returns the price plus the assumptions (day count, compounding, units, resolved timeToExpiryYears) and diagnostics that produced it.
options · Default · Full schemas and capability contract
totalfinance.performance.analyze
Summarize a return series or equity curve: total/annualized return, volatility, Sharpe, Sortino, Calmar, max drawdown, omega, hit rate, profit factor, expectancy — plus beta/alpha/tracking error/information ratio/Treynor when a `benchmark` is supplied. Suspicious inputs (prices passed as returns, returns passed as equity) are flagged in diagnostics.warnings, never silently reported.
performance · Default · Full schemas and capability contract
totalfinance.portfolio.analyze
One report of up to three direct results: the valuation snapshot at `asOf` (always), the dated timeline with P&L since each prior mark and drawdown (when `marks` are supplied), and the policy monitor with its alerts and carried state (when `monitor` is supplied). Each result is the direct function verbatim; nothing is aggregated across them, and one `assumptions` says which parts ran and why the others did not.
portfolio · Opt-in · Full schemas and capability contract
totalfinance.portfolio.create
Start here before portfolio.record_events: supply durable portfolioId, baseCurrency and explicit initial events (an empty array creates no cash). Uses the existing artifact store and ledger reducer. Requires portfolio:write and a writable store. Save the returned handle and open it with portfolio.inspect from portfolioPack (enable both trade and portfolio packs, or use --profile full); subsequent event writes return a new immutable handle. Opt-in (tradePack).
trade · Opt-in · Full schemas and capability contract
totalfinance.portfolio.explain_pnl
Explain the change in net asset value between two dated valuation marks: external flows, investment return, and the identity components (realized, unrealized, income, transaction costs, financing, foreign exchange) that reconcile to it with a published residual, by currency and by grouping. The result is portfolioPnl(...) verbatim.
portfolio · Opt-in · Full schemas and capability contract
totalfinance.portfolio.inspect
Open a returned totalfinance://portfolios/... handle through the same configured store, or import an inline serialized ledger for read-only inspection. Revalidates and replays the ledger. Summary returns identity/counts; events, positions and cash return bounded previews (default 20, maximum 100 rows). This does not value the portfolio; use portfolio.snapshot with explicit marks. Opt-in (portfolioPack).
portfolio · Opt-in · Full schemas and capability contract
totalfinance.portfolio.rebalance_proposal
Fold the ledger snapshot to its state, mark it from the market snapshot, and propose the trades that take the portfolio to the policy targets (or only the drifted ones) under the policy limits, lot sizes, minimum notional, transaction-cost estimates, and an optional external flow. The result is proposePortfolioRebalance(...) verbatim: weights before and after, the cash summary, the trades with their estimates, the objective, and every target it could not resolve. Read-only by construction — it returns a proposal and places nothing. Opt-in (portfolioPack).
portfolio · Opt-in · Full schemas and capability contract
totalfinance.portfolio.record_events
Fold validated portfolio events (fills from trade.submit, deposits, corporate actions) onto a ledger through the ledger's own reducer and put the new ledger into the artifact store as a content-addressed portfolio handle. The write is the put: an unchanged ledger is the same handle; identical replays fold once and applied counts only new events. Changed event bodies are refused. Requires a writable artifact store and the portfolio:write capability. Opt-in (tradePack).
trade · Opt-in · Full schemas and capability contract
totalfinance.portfolio.snapshot
Value every cash balance and position of a portfolio at one instant from a Gate B market snapshot: net asset value in the base currency, per-account cash rows (settled and unsettled), per-position marks, cost basis and unrealized P&L. Supply the portfolio as its serialized ledger envelope (re-hydrated through readPortfolioLedgerSnapshot) or as a derived PortfolioState. The result is portfolioSnapshot(...) verbatim.
portfolio · Opt-in · Full schemas and capability contract
totalfinance.research.event_study
Measure abnormal returns around dated events under a declared expected-return model (mean-adjusted, market-adjusted, or market model), with explicit session, overlap, and cumulation policies; per-event rows and cumulative abnormal returns, and the average abnormal return by offset with t-statistics. The result is eventStudy(...) verbatim.
research · Opt-in · Full schemas and capability contract
totalfinance.research.rank
Rank a point-in-time universe by one declared numeric field with an explicit tie policy (competition, dense, ordinal) and missing-value policy. The result is rankUniverse(...) verbatim.
research · Opt-in · Full schemas and capability contract
totalfinance.research.score
Score a point-in-time universe as a weighted composite of standardized components (z-score or percentile rank, higher- or lower-is-better) with an explicit missing-value policy. The result is scoreUniverse(...) verbatim.
research · Opt-in · Full schemas and capability contract
totalfinance.research.screen
Filter a point-in-time universe of instrument observations with a declarative filter tree, order the survivors, and optionally limit them — a replayable screen by construction (no caller predicate crosses the wire). The result is screenUniverse(...) verbatim.
research · Opt-in · Full schemas and capability contract
totalfinance.risk.optimize
Solve a portfolio: minVariance, maxSharpe (tangency), meanVariance utility, riskParity (equal risk contribution), hrp (hierarchical risk parity), or kelly. Returns the Computed envelope: value.weights + value.objective, assumptions echo the objective and budget, and diagnostics carry converged/iterations — a non-converged solve adds an optimize.not_converged warning instead of pretending.
risk · Default · Full schemas and capability contract
totalfinance.risk.value_at_risk
Estimate Value-at-Risk (VaR) and Conditional VaR / expected shortfall from a return series. Methods: historical (empirical quantile, default), parametric (Gaussian, optional Cornish-Fisher for skew/kurtosis), or monteCarlo. Both are positive loss magnitudes at the given `confidence`; the horizon scales by √-time. The applied confidence/method/horizon ride `assumptions` (with the resolved seed/samples for monteCarlo) and warnings ride `diagnostics`.
risk · Default · Full schemas and capability contract
totalfinance.scenario.run
Revalue every target under every scenario of a Gate B scenario set against a Gate B market snapshot: a scenario-major cell grid with base values, per-cell P&L in local and reporting currency, and per-scenario aggregates. Targets are the serializable kinds — spot assets, Taylor (greeks) positions, and a portfolio bound through Taylor bindings. The result is runScenarios(...) verbatim.
scenario · Opt-in · Full schemas and capability contract
totalfinance.strategy.analyze
Build a multi-leg options position from its legs and return breakevens, net debit/credit, max profit, and max loss. Legs may be given without premiums: pass `premiums: "model"` with a `market` snapshot (spot, volatility, riskFreeRate, asOf, expiry) and every unpriced leg is priced by the BSM engine — so an iron condor’s P&L and probability-of-profit come from strikes alone. Set `probability: true` (with `market`) to also get probability-of-profit, expected value, risk/reward, and probability-of-touch. `premiumSource` reports whether premiums were user- or model-supplied.
strategy · Default · Full schemas and capability contract
totalfinance.strategy.list
Discover every named strategy builder: name, one-line description, whether it spans multiple expiries, and a canonical example input (the exact shape `totalfinance.strategy.analyze` accepts via its `strategy` + `input` form). Agents self-serve the input shapes from here.
strategy · Default · Full schemas and capability contract
totalfinance.structure.exposures
Compute dealer-positioning exposure (net GEX/DEX at spot) and key levels — call/put walls, zero-gamma flip, max pain, pin risk, and 0DTE/weekly/monthly OPEX walls — from an option chain. Each row needs `strike`, `expiry`, `type`, `openInterest`, and either `impliedVolatility` or `price` (IV is implied from price when omitted). Inferred from open interest and a sign convention (echoed in `assumptions.convention`, with its caveats as `model.limitation` warnings in `diagnostics.warnings`) — it does not know true dealer books.
structure · Default · Full schemas and capability contract
totalfinance.structure.flow
Classify option prints into aggressor-side flow: sweeps (multi-print bursts, venue-verified when exchange codes are supplied), blocks, and multi-leg spreads. Aggressor side is NBBO-estimated (Lee–Ready style) — the honest caveats ride diagnostics.warnings as `model.limitation` entries (mirrored as `limitations` strings for quick reading); nothing is presented as exchange-confirmed unless it is.
structure · Default · Full schemas and capability contract
totalfinance.technical_analysis.calculate
Compute any of TotalFinance’s ~300 registered technical indicators over a price series. Pass canonical core Bar records directly under bars; symbol, timestampMs, vwap and adjusted are declared fields. Source records require open, one symbol and strictly increasing unique timestamps; no stripping or SDK preprocessing is needed. Identity/time are validated before OHLCV projection; retain the original source/provenance alongside the result. Close-based (`series`) indicators take `closes`; bar-based indicators take `bars` (OHLCV objects) or parallel column arrays under `series`; pair indicators (e.g. beta, correl) take `x` and `y`. Use `totalfinance.technical_analysis.list` to discover indicator names, input kinds, and parameters. Output is aligned to input length with null during warmup; `assumptions.parameters` echoes the parameters actually used (declared defaults merged with yours), and `diagnostics.warmup` is the first real index.
technical_analysis · Default · Full schemas and capability contract
totalfinance.technical_analysis.describe
Return the full card for a single indicator (alias-aware): category, input kind, parameters, defaults, which parameters are required, its warmup (leading bars before the first real value), and its cross-library aliases. The token-lean way to learn one indicator without listing all ~335. Discover names with `totalfinance.technical_analysis.list`; compute with `totalfinance.technical_analysis.calculate`.
technical_analysis · Default · Full schemas and capability contract
totalfinance.technical_analysis.list
Discover the technical indicators available to `totalfinance.technical_analysis.calculate`. Returns each indicator’s name, category, input kind (series | bars | pair), parameters, defaults, and which parameters are required. Narrow the ~335-indicator catalog with `search` (matches a name or a TA-Lib/pandas/TradingView alias) and/or `category`, and page it with `limit` (default 50) / `offset` (`total` is the full match count). For one indicator’s full card (including its warmup), use `totalfinance.technical_analysis.describe`. To browse momentum, use { category: "momentum" }, rather than searching the name momentum. Then pass a name to `totalfinance.technical_analysis.calculate`.
technical_analysis · Default · Full schemas and capability contract
totalfinance.trade.authorize
Bind human authority to one plan and one preflight report: the plan hash, the portfolio and market hashes preflight judged, the market instant and an age allowance, the paper mode, the account, a variance envelope, an expiry, the approver, and a closed set of idempotency keys. Refuses a denied preflight, an unjudged plan, or a stale expiry. The grant is put into the authorization store under its content hash and returned with its handle. Requires the trade:approve capability. Opt-in (tradePack).
trade · Opt-in · Full schemas and capability contract
totalfinance.trade.cancel
Journal cancel-requested then cancelled for an open order in the journal store under `<sourceId>:journal`; a terminal order is not cancelled twice (accepted: false, the state says why). Cancelling a combo leg cancels all remaining legs of that plan-local combo. Both the original journal and authorization stores are required to recover pending submissions before cancellation; no new grant is needed. A fill delivered after the cancellation is Decision 6's late-fill path. Paper only; requires trade:paper. Opt-in (tradePack).
trade · Opt-in · Full schemas and capability contract
totalfinance.trade.preflight
Normalize an intent (or take an execution plan) and judge it: the portfolio before and after through the ledger's own fold of hypothetical fills, every policy check with its verdict, declared-rate cost estimates, the monitor's alerts on the after-state, and one decision — allow only when every check passes, deny on any failure, require-approval when evidence is missing; never an allow from missing information. No effect. Opt-in (tradePack).
trade · Opt-in · Full schemas and capability contract
totalfinance.trade.reconcile
Join the journal's order states (from the journal store by `journalId`, or inline events) to the ledger's fills under the execution source in both directions, compare delivered fill quantities per order within an explicit tolerance, list the unresolved orders, and — with an external snapshot — compose reconcilePortfolio verbatim. With planHash, exclude other plans’ journaled orders and fills from both joins; unattributed source fills remain discrepancies. External snapshots are judged over the whole portfolio. reconciled is true only when everything agrees and no order is unresolved. No effect; requires trade:paper. Opt-in (tradePack).
trade · Opt-in · Full schemas and capability contract
totalfinance.trade.submit
Verify the grant against the plan, the portfolio and market hashes, the market instant, the account, and the idempotency key; journal submitted and acknowledged; return the content-addressed receipt — the SAME receipt for a retry with the same key and plan (no second order), trade.idempotency_conflict for the same key with another plan, trade.grant_expired for an expired grant. With `observations`, the open orders meet the market through the engines' own fill path. Top-level fills/events are only this call’s new deltas; the submission receipt is immutable. `currentOrders` is the authoritative journal-derived current state and cumulative filled/remaining quantities for this receipt. `recovery: { fills, events }` contains all persisted normalized fills and reproducible ledger envelopes for this receipt’s orders, including this call’s fills. Retry after a lost response and apply recovery.events with portfolio.record_events; identical events fold once. Recovery grows with later fills without replaying the fill engine. The journal continues transactionally from the required journal store under `<sourceId>:journal`; retries must retain that store and source. A grant atomically records its exact prepared submission before journal commit: a retry with the same key into the same store/journal recovers those events and reads the same receipt; any other submission of the grant is trade.grant_consumed. Every journal write recovers earlier pending submissions before allocating new identities. Inline history must match persisted history exactly. Inline grants must exist unchanged in the trusted authorization store. Paper only; requires trade:paper. Opt-in (tradePack).
trade · Opt-in · Full schemas and capability contract
totalfinance.valuation.company
Project the three statements from explicit drivers, take the free cash flows the valuation basis needs, and discount them under the stated conventions (basis, date, currency, the REQUIRED discount rate, compounding, day count, the terminal value method, the enterprise-to-equity bridge). The result is discountedCashFlowFromStatements(...) verbatim — the projection with its balance-sheet reconciliation, the cash flows used, and the valuation — plus discountedCashFlowSensitivityTable(...) over the same flows when a sensitivity request is supplied. Opt-in (valuationPack).
valuation · Opt-in · Full schemas and capability contract
totalfinance.volatility.event
Decompose pre-event implied volatility into base + event variance and the implied one-day event move (the earnings-move read): eventMove = √max(0, atmVolatility²·timeToExpiryYears − baseVolatility²·timeToExpiryYears). Optionally reports the variance risk premium when `realizedVolatility` is supplied.
volatility · Default · Full schemas and capability contract
totalfinance.volatility.expected_move
Compute the expected 1-sigma move of the underlying by expiry — the lognormal ±1σ band and the expected absolute move. Provide `impliedVolatility` + `timeToExpiryYears` to imply it from volatility, or `straddlePrice` to imply it from the ATM straddle. Risk-neutral, not a directional forecast.
volatility · Default · Full schemas and capability contract
totalfinance.volatility.metrics
Where does the current implied volatility sit against its history? Returns IV rank (min–max position, 0–100), IV percentile (share of history below current, 0–100), and summary statistics — the standard "is IV high?" read before selling or buying premium.
volatility · Default · Full schemas and capability contract
totalfinance.volatility.probability_in_the_money
Risk-neutral probability that an option finishes in the money at expiry — N(d2) for a call, N(−d2) for a put. This is the model probability P(S_t ⋛ K), not a real-world forecast.
volatility · Default · Full schemas and capability contract
totalfinance.volatility.probability_of_touch
Risk-neutral probability that the underlying TOUCHES `barrier` at any time before expiry (first-passage probability for geometric Brownian motion). Useful for stop/target and one-touch reasoning.
volatility · Default · Full schemas and capability contract
totalfinance.volatility.surface
Fit an implied-volatility surface from chain quotes (IV given directly, or implied from price) and return the surface rows, per-expiry ATM term structure, and the static-arbitrage report (calendar/butterfly violations). The surface never fabricates: non-convergence and extrapolation are reported in diagnostics/warnings.
volatility · Default · Full schemas and capability contract