Heritage + MathIR + Frontier AI

Time doesn’t flow uniformly.
Neither should your pricing.

One second of an FOMC announcement injects more variance than an entire trading session. ReflexLibs.ai transforms calendar time into market time — event-aware, composable, deterministic. Built on 15 years of production C++ heritage, generated from a single TOML spec into 9 languages, with optional 128-bit decimal precision.
Layer ★ — Time Dilation
Event-Aware Variance Time
Traditional models assume time flows uniformly. Reality disagrees. An FOMC rate decision injects 4 hours of variance in one second. Time dilation transforms calendar time → market time before pricing — composable, deterministic, and compatible with every model in the library.
The Pipeline
DateTime → CalendarDays → TimeDilation → MarketDays → YearBasis → T. The raw math (Layer 2) always receives year fractions. Time dilation sits above it.
Event Warping
FOMC (×7200), NFP (×14400), CPI (×3600), ECB (×5400), Earnings (×1800). Each event has a warp factor and exponential decay half-life. Variance injected at the moment of announcement.
Composable Dilations
Weekend exclusion × trading hours × event warping. Chain any combination. Identity dilation recovers standard Black-Scholes.
Standard Presets
Weekend-excluded (×5/7), business days (×252/365), trading hours only (×6.5/24). Holiday calendars: NYSE, LSE, TARGET, custom.
CUDA Strategy
CPU computes dilated T[] for all options. GPU receives pre-dilated year fractions. Clean separation: sophistication on CPU, parallelism on GPU.
Model Wrapper Pattern
Black76.WithTimeDilation(events) — wrap any model with time dilation. Automatic scaling from dates to dilated year fractions. Same API, smarter time.
Time Dilation — Event-Aware Pricing
// Time Dilation — from TIME_DILATION_ARCHITECTURE.toml
// Wrap any model. Same API, smarter time.
var dilation = TimeDilatedPricerBuilder.Create()
    .WithWeekendExclusion()           // ×5/7
    .WithTradingHours(6.5)           // ×6.5/24
    .WithEvents(
        ScheduledEvent.Presets.FOMC(2026-01-29),  // warp ×7200
        ScheduledEvent.Presets.NFP(2026-02-07),   // warp ×14400
        ScheduledEvent.Presets.CPI(2026-02-12)    // warp ×3600
    )
    .Build();

// T_market absorbs weekend, trading hours, and event variance
var T_market = dilation.ScaleInterval(now, expiry);

// Raw math is unchanged — pure year fraction, no dates
var price = Black76.Raw.PriceOfCall(F, K, T_market, sigma);
Layer 1 — NanoMath
Base Math — Shipping Now
High-precision mathematical functions generated from a single TOML specification. Optional 128-bit decimal arithmetic eliminates IEEE 754 rounding drift. Every function ships in 9 languages with proven cross-language parity.
Black-76 Family
Lognormal, Bachelier, shifted-lognormal pricing. Call, put, Greeks (delta, gamma, vega, theta, vanna, volga). Implied volatility via Jaeckel.
SABR Calibration
Stochastic Alpha Beta Rho. Vol surface calibration, smile dynamics, forward-forward volatility. Heritage C++ reference with Rust port.
Svensson Yield Curves
Nelson-Siegel-Svensson and FrontJet variants. Discount factors, forward rates, zero curves. Forward swap rate fitting.
Spline Interpolation
Linear, log-linear, cubic and quartic splines. Monotone-preserving. Curve construction building blocks.
Decimal128 Precision
Optional 128-bit decimal (rust_decimal / System.Decimal). 333 tests across 6 phases. No silent IEEE 754 rounding.
High-Precision Normal CDF
Erfc-based implementation. Tail-stable for deep OTM puts. Abramowitz & Stegun coefficients with extended precision.
Time Dilation Models
Novel research: relativistic time-decay corrections for theta and variance processes. Python prototyping, Rust production (next).
Every pricing function accepts an injectable NormDist — swap in StandardNormDist (f64, erfc-based, tail-stable for deep OTM puts) or StandardNormDistDecimal (128-bit, 28-digit arithmetic via rust_decimal / System.Decimal). Time dilation transforms calendar time into market time before the math runs — FOMC, NFP, CPI, ECB event warping with exponential decay, composable with weekend exclusion and trading hours. The WIT Component Model (WASM Interface Types) defines the typed boundary: record decimal28 { lo, mid, hi, flags } is bit-identical across Rust, C#, and C++ at the WASM layer.
Generated from MathIR
/// Black-76 call — actual code from ReflexLibs.Ai/options/black76
/// High-precision NormDist injectable: StandardNormDist (f64, erfc tail-stable)
/// or StandardNormDistDecimal (128-bit, 28-digit arithmetic)
#[inline]
pub fn price_of_call_nd<N: NormDist>(
    nd: &N,
    forward: f64, strike: f64, time_to_expiry: f64, volatility: f64,
) -> Result<f64, Black76Error> {
    if forward <= 0.0 { return Err(Black76Error::NegativeForward); }
    let t_vol = volatility * time_to_expiry.sqrt();
    let d1 = (forward / strike).ln() / t_vol + 0.5 * t_vol;
    let d2 = d1 - t_vol;
    Ok((forward * nd.cdf(d1) - strike * nd.cdf(d2)).max(0.0))
}

// f64 — StandardNormDist (erfc-based, tail-stable)
let price = price_of_call_nd(&StandardNormDist, F, K, T_market, sigma)?;

// Decimal128 — StandardNormDistDecimal (28-digit arithmetic)
let price = lognormal_decimal::price_of_call_nd(
    &StandardNormDistDecimal, F, K, T_market, sigma)?;

// Time-dilated — FOMC/NFP event warping baked into T
let T_market = dilation.scale_interval(now, expiry);
let price = price_of_call_nd(&StandardNormDist, F, K, T_market, sigma)?;
Generated from MathIR
// Black-76 call price — Heritage C++ reference implementation
// 15 years in production. Every port validates against this.
constexpr inline double call_price(
    double F, double K, double D, double sigma, double T) noexcept {
    const auto total_vol = sigma * std::sqrt(T);
    const auto d1 = (std::log(F / K) + 0.5 * sigma * sigma * T) / total_vol;
    const auto d2 = d1 - total_vol;
    return D * (F * N(d1) - K * N(d2));
}
Generated from MathIR
// Black-76 call — actual pattern from ReflexLibs.Ai
// High-precision INormDist<T> injectable — ErfcNormDist for tail-stable deep OTM puts
// At parity with Rust: same _nd pattern, same injectable trait
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OneOf<double, Black76Error> PriceOfCallNd(
    INormDist nd,
    double forward, double strike,
    double timeToExpiry, double volatility) {
    if (forward <= 0) return Black76Error.NegativeForward;
    var tVol = volatility * Math.Sqrt(timeToExpiry);
    var d1 = Math.Log(forward / strike) / tVol + 0.5 * tVol;
    var d2 = d1 - tVol;
    return Math.Max(forward * nd.Cdf(d1) - strike * nd.Cdf(d2), 0);
}

// f64 — ErfcNormDist (erfc-based, tail-stable)
var price = PriceOfCallNd(new ErfcNormDist(), F, K, T_market, sigma);

// Decimal128 — DecimalNormDist (28-digit System.Decimal)
var price = PriceOfCallNdDecimal(new DecimalNormDist(), F, K, T_market, sigma);

// Time-dilated: FOMC + NFP event warping
var T_market = dilation.ScaleInterval(now, expiry);
var price = PriceOfCallNd(new ErfcNormDist(), F, K, T_market, sigma);
Generated from MathIR
// Black-76 call price — Go implementation (planned)
// Same MathIR spec, same test vectors, Go idioms
func CallPrice(F, K, D, sigma, T float64) (float64, error) {
    if math.IsNaN(F) { return 0, ErrNaN }
    totalVol := sigma * math.Sqrt(T)
    d1 := (math.Log(F/K) + 0.5*sigma*sigma*T) / totalVol
    d2 := d1 - totalVol
    return D * (F*normCdf(d1) - K*normCdf(d2)), nil
}
Generated from MathIR
// nano-math.wit — actual WIT from the repo
// package xll-ai:nano-math@6.4.12

interface special-math {
    /// Standard normal CDF Φ(x). Range: (0, 1).
    phi:  func(x: f64) -> result<f64, math-error>;
    /// Complementary error function erfc(x) = 1 - erf(x).
    erfc: func(x: f64) -> result<f64, math-error>;
}

interface decimal-math {
    /// 28-digit decimal — bit-compatible with rust_decimal + System.Decimal
    record decimal28 { lo: u32, mid: u32, hi: u32, flags: u32 }

    /// Normal CDF to ~7 significant digits in decimal arithmetic.
    phi:  func(x: f64) -> result<decimal28, math-error>;
}

/// No export ever returns NaN or Infinity — errors are explicit.
variant math-error {
    non-finite-input,
    negative-input,
    overflow,
}

// JavaScript host — inject high-precision phi into Black-76
const { phi } = await instantiate(wasmBytes);  // WIT component
const T_market = dilation.scaleInterval(now, expiry);
const price = black76Call(F, K, D, sigma, T_market, phi);  // phi injected
Generated from MathIR
// Black-76 call — Type-safe, generated from MathIR
// NaN caught at compile time via Result<T, PricingError>
export function callPrice(
    F: number, K: number, D: number,
    sigma: number, T: number
): Result<number, PricingError> {
    if (Number.isNaN(F)) return { ok: false, error: PricingError.NaN };
    const totalVol = sigma * Math.sqrt(T);
    const d1 = (Math.log(F / K) + 0.5 * sigma ** 2 * T) / totalVol;
    const d2 = d1 - totalVol;
    return { ok: true, value: D * (F * normCdf(d1) - K * normCdf(d2)) };
}
Generated from MathIR
# Black-76 call — Generated from MathIR (TOML → Python)
# Rustified style: tuple result, explicit NaN guard
def call_price(F: float, K: float, D: float,
               sigma: float, T: float) -> MathResult:
    if math.isnan(F): return (False, float('nan'))
    total_vol = sigma * math.sqrt(T)
    d1 = (math.log(F / K) + 0.5 * sigma**2 * T) / total_vol
    d2 = d1 - total_vol
    return (True, D * (F * norm_cdf(d1) - K * norm_cdf(d2)))
Generated from MathIR
// Black-76 — actual CUDA kernel from ReflexLibs.Ai/cuda
// __host__ __device__ : runs on both CPU and GPU
__host__ __device__ inline float norm_cdf(float x) {
    const float INV_SQRT2 = 0.70710678118654752440f;
    return 0.5f * erfcf(-x * INV_SQRT2);
}

__host__ __device__ inline void black76_one(
    float F, float K, float T, float sigma, float DF,
    float& call, float& put) {
    float sqrtT = sqrtf(T);
    float d1 = (logf(F / K) + 0.5f * sigma * sigma * T) / (sigma * sqrtT);
    float d2 = d1 - sigma * sqrtT;
    call = DF * (F * norm_cdf(d1) - K * norm_cdf(d2));
    put  = DF * (K * norm_cdf(-d2) - F * norm_cdf(-d1));
}

__global__ void black76_kernel(
    int n, const float* F, const float* K, const float* T,
    const float* V, const float* DF, float* C, float* P) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) black76_one(F[i], K[i], T[i], V[i], DF[i], C[i], P[i]);
}
Generated from MathIR
// Black-76 call — Pure Excel LAMBDA, no VBA, no add-in
// Paste into Name Manager, use from any cell

BLACK76.CALL = LAMBDA(F, K, D, sigma, T,
  LET(
    tv,  sigma * SQRT(T),
    d1,  (LN(F/K) + 0.5*sigma^2*T) / tv,
    d2,  d1 - tv,
    D * (F * NORM.S.DIST(d1,1) - K * NORM.S.DIST(d2,1))
  )
)
78 testsDecimal128WIT
src/ReflexLibs.Ai/src/finance/options/black76/rust/src/lognormal.rs
Injectable NormDist trait: StandardNormDist (f64, erfc tail-stable) or StandardNormDistDecimal (128-bit). All pricing functions are generic over the normal distribution implementation. Result<T, Black76Error> — no silent NaN.
/// Black-76 call — actual code from lognormal.rs
#[inline]
pub fn price_of_call_nd<N: NormDist>(
    nd: &N,
    forward: f64, strike: f64, time_to_expiry: f64, volatility: f64,
) -> Result<f64, Black76Error> {
    if forward <= 0.0 { return Err(Black76Error::NegativeForward); }
    let t_vol = volatility * time_to_expiry.sqrt();
    let d1 = (forward / strike).ln() / t_vol + 0.5 * t_vol;
    let d2 = d1 - t_vol;
    Ok((forward * nd.cdf(d1) - strike * nd.cdf(d2)).max(0.0))
}
Reference impl
src/ReflexLibs.Ai/src/finance/options/black76/cpp/black76.h
15 years in production. constexpr inline noexcept. Every port validates against this implementation. Abramowitz & Stegun coefficients for normal CDF with extended precision tail behaviour.
// Black-76 call — Heritage C++ (15 years production)
constexpr inline double call_price(
    double F, double K, double D,
    double sigma, double T) noexcept {
    const auto total_vol = sigma * std::sqrt(T);
    const auto d1 = (std::log(F / K) + 0.5 * sigma * sigma * T) / total_vol;
    const auto d2 = d1 - total_vol;
    return D * (F * N(d1) - K * N(d2));
}
78 tests✅ At parity with RustDecimal128
src/ReflexLibs.Ai/src/finance/options/black76/csharp/Lognormal.cs
At parity with Rust. Injectable INormDist interface: ErfcNormDist (tail-stable) or DecimalNormDist (28-digit). OneOf<double, Black76Error> — Rustified, no exceptions.
// Black-76 call — C# at parity with Rust
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OneOf<double, Black76Error> PriceOfCallNd(
    INormDist nd,
    double forward, double strike,
    double timeToExpiry, double volatility) {
    if (forward <= 0) return Black76Error.NegativeForward;
    var tVol = volatility * Math.Sqrt(timeToExpiry);
    var d1 = Math.Log(forward / strike) / tVol + 0.5 * tVol;
    var d2 = d1 - tVol;
    return Math.Max(forward * nd.Cdf(d1) - strike * nd.Cdf(d2), 0);
}
Decimal128WIT
src/Xll.Ai.Nano.Math/nano-math-all-wasm/wit/nano-math.wit
WASM Interface Types define the typed boundary. special-math.phi provides normal CDF, decimal-math provides 128-bit arithmetic. JS host injects phi into Black-76 via the WIT contract.
// nano-math.wit — package xll-ai:nano-math@6.4.12
interface special-math {
    phi:  func(x: f64) -> result<f64, math-error>;
    erfc: func(x: f64) -> result<f64, math-error>;
}

interface decimal-math {
    record decimal28 { lo: u32, mid: u32, hi: u32, flags: u32 }
    phi: func(x: f64) -> result<decimal28, math-error>;
}
src/ReflexLibs.Ai/src/finance/options/black76/cuda/black76_cpu_fallback.cu.txt
__host__ __device__ dual-target: runs on CPU and GPU. Batch call+put pricing, one thread per option. Time dilation computed on CPU, pre-dilated T[] passed to GPU kernel.
// CUDA kernel — actual code from the repo
__host__ __device__ inline float norm_cdf(float x) {
    return 0.5f * erfcf(-x * 0.70710678118654752440f);
}

__global__ void black76_kernel(
    int n, const float* F, const float* K,
    const float* T, const float* V,
    const float* DF, float* C, float* P) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) black76_one(F[i], K[i], T[i], V[i], DF[i], C[i], P[i]);
}
codegen/python/black76.py
Generated from MathIR TOML spec. Rustified style: tuple result, explicit NaN guard. Research bridge for prototyping with identical math to production Rust/C#.
# Generated from MathIR — same test vectors as Rust
def call_price(F: float, K: float, D: float,
               sigma: float, T: float) -> MathResult:
    if math.isnan(F): return (False, float('nan'))
    total_vol = sigma * math.sqrt(T)
    d1 = (math.log(F / K) + 0.5 * sigma**2 * T) / total_vol
    d2 = d1 - total_vol
    return (True, D * (F * norm_cdf(d1) - K * norm_cdf(d2)))
codegen/excel/BLACK76.CALL.lambda
Pure Excel LAMBDA, no VBA, no add-in. Paste into Name Manager. Same formula, same test vectors. Traders can validate in their own spreadsheet.
BLACK76.CALL = LAMBDA(F, K, D, sigma, T,
  LET(
    tv,  sigma * SQRT(T),
    d1,  (LN(F/K) + 0.5*sigma^2*T) / tv,
    d2,  d1 - tv,
    D * (F * NORM.S.DIST(d1,1) - K * NORM.S.DIST(d2,1))
  )
)
Layer 2 — Instrument Contracts
Typed Definitions — C# + Rust
Production instrument interfaces ported from 15 years of ReflexDotnet heritage. Parallel C# (readonly record struct, OneOf<T,E>) and Rust (traits, Result<T,E>) implementations. Clean dependency graph: Types ← Legs ← Accrual ← Instruments.
Delta One
IFixedRateSwap, ITenorBasisSwap, IIndexBasisSwap, ICurrencyBasisSwap (Float/Float, Float/Fixed, Fixed/Fixed). IInflationSwap (ZC, YoY). IFRA, IDeposit, IFuture.
Options
ISwaption (cash/swap settle), ICap/Floor, IFutureOption (exchange-traded). CallOrPut enum, strike, expiry adjustment.
Pricing Infrastructure
IPricingContext: discount factors, FX rates, inflation index values, projected rates. IDiscountCurveCore, IProjectionCurveCore. Multi-curve OIS discounting.
Accrual & Day Count
AccrualPeriod, Basis (30/360, ACT/360, ACT/365, ACT/ACT). Floatlet/fixlet compounding. Inclusive/exclusive spread. Integer day-count variants.
Type System
Currency, CurrencyPair, Tenor, Frequency, ISIN, InstrumentId, InflationIndex, InterestIndex. Enum discriminants match across C# and Rust.
Instrument Contract — C# (Rustified)
// IFixedRateSwap — Heritage: ReflexDotnet-2023
// Rustified: readonly record struct, OneOf<T,E>, no exceptions
public interface IFixedRateSwap : ISwap {
    IFixedLeg FixedLeg { get; }
    IFloatLeg FloatLeg { get; }
    ICurrency PayingCurrency { get; }
}

public interface IPricingContext {
    double DiscountFactor(ICurrency ccy, DateTime date);
    double Fx(CurrencyPair pair);
    double InflationIndexValue(IInflationIndex idx, DateOnly month);
}
Instrument Contract — Rust
/// IFixedRateSwap — Rust trait, Result<T,E>
pub trait FixedRateSwap: Swap {
    fn fixed_leg(&self) -> &dyn FixedLeg;
    fn float_leg(&self) -> &dyn FloatLeg;
    fn paying_currency(&self) -> Currency;
}

pub trait PricingContext {
    fn discount_factor(&self, ccy: Currency, date: NaiveDate) -> f64;
    fn fx(&self, pair: CurrencyPair) -> f64;
    fn inflation_index(&self, idx: &InflationIndex, month: NaiveDate) -> f64;
}
42 testsDecimal128
src/ReflexLibs.Ai/src/finance/curves/nss/rust/src/lib.rs
Nelson-Siegel-Svensson yield curve fitting. Discount factors, zero rates, forward rates. Levenberg-Marquardt calibration with analytic Jacobian. Decimal128 variant for basis-point precision.
/// Svensson 6-parameter yield curve
pub fn zero_rate(
    params: &SvenssonParams, tau: f64,
) -> Result<f64, CurveError> {
    if tau <= 0.0 { return Err(CurveError::NonPositiveTenor); }
    let e1 = (-tau / params.tau1).exp();
    let e2 = (-tau / params.tau2).exp();
    let t1 = (1.0 - e1) / (tau / params.tau1);
    let t2 = (1.0 - e2) / (tau / params.tau2);
    Ok(params.beta0 + params.beta1 * t1
        + params.beta2 * (t1 - e1)
        + params.beta3 * (t2 - e2))
}
Reference impl
src/ReflexLibs.Ai/src/finance/curves/nss/cpp/svensson.h
Production yield curve calibration. Cubic and quartic spline interpolation. OIS discounting and funding spread separation. Multi-curve framework.
// Svensson zero rate — Heritage C++
constexpr inline double zero_rate(
    const SvenssonParams& p, double tau) noexcept {
    const auto e1 = std::exp(-tau / p.tau1);
    const auto e2 = std::exp(-tau / p.tau2);
    const auto t1 = (1.0 - e1) * p.tau1 / tau;
    const auto t2 = (1.0 - e2) * p.tau2 / tau;
    return p.beta0 + p.beta1*t1 + p.beta2*(t1-e1) + p.beta3*(t2-e2);
}
42 tests✅ At parity with RustDecimal128
src/ReflexLibs.Ai/src/finance/curves/nss/csharp/Svensson.cs
At parity with Rust NSS implementation. OIS discounting, funding spreads, multi-curve framework. OneOf<double, CurveError> result type.
// Svensson zero rate — C# at parity with Rust
public static OneOf<double, CurveError> ZeroRate(
    SvenssonParams p, double tau) {
    if (tau <= 0) return CurveError.NonPositiveTenor;
    var e1 = Math.Exp(-tau / p.Tau1);
    var e2 = Math.Exp(-tau / p.Tau2);
    var t1 = (1.0 - e1) * p.Tau1 / tau;
    var t2 = (1.0 - e2) * p.Tau2 / tau;
    return p.Beta0 + p.Beta1*t1 + p.Beta2*(t1-e1) + p.Beta3*(t2-e2);
}
codegen/js/svensson.mjs
Browser-side yield curve evaluation. Generated from MathIR, validated against Rust test vectors.
// Svensson — generated from MathIR
export function zeroRate(p, tau) {
    if (tau <= 0) return { ok: false, error: 'non_positive_tenor' };
    const e1 = Math.exp(-tau / p.tau1);
    const e2 = Math.exp(-tau / p.tau2);
    const t1 = (1 - e1) * p.tau1 / tau;
    const t2 = (1 - e2) * p.tau2 / tau;
    return { ok: true, value: p.beta0+p.beta1*t1+p.beta2*(t1-e1)+p.beta3*(t2-e2) };
}
codegen/python/svensson.py
Research bridge for curve fitting. Same parameters, same test vectors. NumPy-compatible.
# Svensson — generated from MathIR
def zero_rate(p: SvenssonParams, tau: float) -> Result:
    if tau <= 0: return (False, 0.0)
    e1 = math.exp(-tau / p.tau1)
    e2 = math.exp(-tau / p.tau2)
    t1 = (1 - e1) * p.tau1 / tau
    t2 = (1 - e2) * p.tau2 / tau
    return (True, p.beta0+p.beta1*t1+p.beta2*(t1-e1)+p.beta3*(t2-e2))
36 testsDecimal128WIT
src/ReflexLibs.Ai/src/finance/options/sabr/rust/src/lib.rs
Stochastic Alpha Beta Rho: Hagan expansion + Obloj correction. Smile dynamics, forward-forward volatility. Injectable NormDist for CDF calls within calibration.
/// SABR implied vol — Hagan 2002 + Obloj correction
pub fn implied_vol<N: NormDist>(
    nd: &N,
    params: &SabrParams,
    forward: f64, strike: f64, expiry: f64,
) -> Result<f64, SabrError> {
    let alpha = params.alpha;
    let beta = params.beta;
    let rho = params.rho;
    let nu = params.nu;
    let fk = (forward * strike).powf((1.0 - beta) / 2.0);
    let z = (nu / alpha) * fk * (forward / strike).ln();
    let x = (((1.0 - 2.0*rho*z + z*z).sqrt() + z - rho)
            / (1.0 - rho)).ln();
    // ... Hagan expansion terms
    Ok(alpha * z / (fk * x) * correction)
}
36 tests✅ At parity with RustDecimal128
src/ReflexLibs.Ai/src/finance/options/sabr/csharp/Sabr.cs
At parity with Rust SABR. Hagan + Obloj. Injectable INormDist. OneOf error handling.
// SABR implied vol — C# at parity with Rust
public static OneOf<double, SabrError> ImpliedVol(
    INormDist nd, SabrParams p,
    double forward, double strike, double expiry) {
    var fk = Math.Pow(forward * strike, (1.0 - p.Beta) / 2.0);
    var z = (p.Nu / p.Alpha) * fk * Math.Log(forward / strike);
    var x = Math.Log((Math.Sqrt(1 - 2*p.Rho*z + z*z) + z - p.Rho)
            / (1 - p.Rho));
    // Hagan expansion + correction
    return p.Alpha * z / (fk * x) * correction;
}
Reference impl
src/ReflexLibs.Ai/src/finance/options/sabr/cpp/sabr.h
Production SABR implementation. Hagan 2002 original formulation. Smile-consistent Greeks. Heritage reference for all ports.
// SABR — Heritage C++, production since 2012
inline double implied_vol(
    const SabrParams& p,
    double F, double K, double T) noexcept {
    const auto fk = std::pow(F * K, (1.0 - p.beta) / 2.0);
    const auto z = (p.nu / p.alpha) * fk * std::log(F / K);
    // ... Hagan expansion
    return p.alpha * z / (fk * x) * correction;
}
WIT
src/Xll.Ai.Nano.Math/nano-math-all-wasm/wit/reflexlibs-options.wit
Full WIT interface: Black-76, Bachelier, Shifted, SABR. decimal28 support for precision-critical calibration. JS host injects phi.
// reflexlibs-options.wit — SABR interface
interface sabr-model {
    record sabr-params {
        alpha: f64, beta: f64,
        rho: f64, nu: f64,
    }
    implied-vol: func(
        params: sabr-params,
        forward: f64, strike: f64, expiry: f64,
    ) -> result<f64, pricing-error>;
}
src/ReflexLibs.Ai/src/finance/options/black76/cuda/black76_cpu_fallback.cu.txt
Actual CUDA kernel for batch call+put pricing. __host__ __device__ dual-target. SABR on GPU requires pre-computed vol surface — feed strike/vol grid, not raw params.
// Batch option pricing — one thread per option
__global__ void black76_kernel(
    int n, const float* F, const float* K,
    const float* T, const float* V,
    const float* DF, float* C, float* P) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) black76_one(F[i], K[i], T[i], V[i], DF[i], C[i], P[i]);
}
codegen/python/sabr.py
MathIR-generated SABR. NumPy-compatible for surface fitting research. Same test vectors.
# SABR implied vol — Python research bridge
def implied_vol(p: SabrParams,
                F: float, K: float, T: float) -> Result:
    fk = (F * K) ** ((1 - p.beta) / 2)
    z = (p.nu / p.alpha) * fk * math.log(F / K)
    x = math.log((math.sqrt(1 - 2*p.rho*z + z**2) + z - p.rho) / (1 - p.rho))
    # Hagan expansion
    return (True, p.alpha * z / (fk * x) * correction)
shipping
src/Xll.Ai.NanoLibs/ReflexLibs.Options.Math.Ai/reflexlibs-math-rust-port-0-unsafe/…/heston_normal.rs
Stochastic-vol with normal (Bachelier) dynamics — prices OTM on negative forwards, which Lognormal can't. 1024-node Gauss-Legendre on [0,∞), heritage closed-form for characteristic function φ, ε=1e-4 contour shift. Heritage port validated against C++ oracle at 1e-9 tolerance.
/// Heston Normal — kernel signatures, full bodies in heston_normal.rs
pub fn price_of_call(
    forward: f64, strike: f64, tau: f64,
    kappa: f64, theta: f64, omega: f64,
    rho: f64, v0: f64,
) -> Result<f64, HestonError> { /* … Gauss-Legendre over φ(iε−ξ) */ }

pub fn delta_of_call(/* same signature */) -> Result<f64, HestonError> { /* … */ }
pub fn gamma        (/* same signature */) -> Result<f64, HestonError> { /* … */ }
pub fn theta_forward(/* same signature */) -> Result<f64, HestonError> { /* … */ }

/// Characteristic function φ — paper Φ(τ,u,ν₀) = exp(C + Dν₀ − iux₀)
fn phi(u: Complex<f64>, /* params … */) -> Complex<f64> { /* … */ }
Reference impl
src/Xll.Ai.NanoLibs/ReflexLibs.Options.Math.Ai/reflex_analytic_raw/HestonNormal.h
15 years in production. Templated on double/float. Paper companion: Sidani 2014 (SSRN 2445328) derives the same kernel with a clean public provenance.
// HestonNormal.h — 6 templated entry points, one file per pricing family
template<class T>
T price_of_call(T F, T K, T tau,
                  T kappa, T theta, T omega, T rho, T v0) noexcept;

template<class T> T price_of_put (/* same signature */) noexcept;
template<class T> T delta_of_call(/* … */)                    noexcept;
template<class T> T delta_of_put (/* … */)                    noexcept;
template<class T> T gamma        (/* … */)                    noexcept;
template<class T> T theta_forward(/* … */)                    noexcept;

// Implementation: bodies in HestonNormal.cpp — Gauss-Legendre quadrature,
// characteristic function in HestonNormalCharacteristic.cpp
174 assertions draftdual-path A≡B @ 1e-10
src/ReflexLibs.Ai/src/finance/options/heston/csharp/HestonNormalFromPaper.cs (draft)
Dual-path C# port: Path A clean-room from Sidani 2014 SSRN 2445328 + Path B heritage port under permission grant. Both emit identical Re[⋅] despite opposite Fourier sign conventions. Cross-check at 1e-10 on 25 randomised parameters.
// HestonNormalFromPaper.cs — Path A (clean-room from SSRN 2445328)
public static class HestonNormalFromPaper {
    public static double PriceOfCall(
        double forward, double strike, double timeToExpiry,
        double kappa, double theta, double omega,
        double rho, double v0,
        int nodeCount = 1024) { /* … integrate Re[φ·(−e^…K)/(ξ−iε)²] / π */ }

    public static double PriceOfPut  (/* same signature */) { /* … put-call parity */ }
    public static double DeltaOfCall (/* … */) { /* … multiplier −iu */ }
    public static double Gamma       (/* … */) { /* … multiplier −u² */ }
    public static double ThetaForward(/* … */) { /* … ∂φ/∂τ via ODE 9a/9b */ }

    // Φ(τ,u,ν₀) = exp(C(τ) + D(τ)ν₀ − iu·x₀)  — paper §3, negative-i convention
    private static (Complex phi, Complex phiDot) CharacteristicFunction(/* … */) { /* … */ }
}

// HestonNormalFromHeritage.cs — Path B (under permission grant)
public static class HestonNormalFromHeritage { /* same 6 entry points, +i convention */ }
heritage port
src/Xll.Ai.NanoLibs/ReflexLibs.Options.Math.Ai/reflexlibs-math-rust-port-0-unsafe/…/bates_lognormal.rs
Heston + compound Poisson jumps — Merton jump diffusion bolted onto stochastic volatility. Heritage C++ port already in-tree; dual-path C# port queued behind Heston Normal.
/// Bates Lognormal — kernel signatures (Heston params + jump params)
pub fn price_of_call(
    forward: f64, strike: f64, tau: f64,
    kappa: f64, theta: f64, omega: f64, rho: f64, v0: f64,
    lambda_j: f64, mu_j: f64, sigma_j: f64,
) -> Result<f64, BatesError> { /* … Heston φ · jump-CF … */ }

pub fn delta_of_call(/* same signature */) -> Result<f64, BatesError> { /* … */ }
pub fn gamma        (/* same signature */) -> Result<f64, BatesError> { /* … */ }
pub fn theta_forward(/* same signature */) -> Result<f64, BatesError> { /* … */ }

/// φ_Bates(u) = φ_Heston(u) · exp(τ·λ(e^{iμ_j u − ½σ_j² u²} − 1 − iμu))
fn jump_characteristic(u: Complex<f64>, /* … */) -> Complex<f64> { /* … */ }
Reference impl
src/Xll.Ai.NanoLibs/ReflexLibs.Options.Math.Ai/reflex_analytic_raw/BatesLognormal.h
15 years in production. Bates 1996 (Rev. Financ. Stud.) jump-diffusion-stochastic-vol. Shares characteristic-function plumbing with HestonLognormal; adds compound Poisson jump CF.
// BatesLognormal.h — 6 entry points per variant (Normal/Lognormal/LognormalShifted)
template<class T>
T price_of_call(T F, T K, T tau,
                  T kappa, T theta, T omega, T rho, T v0,
                  T lambda_j, T mu_j, T sigma_j) noexcept;

template<class T> T price_of_put (/* same signature */) noexcept;
template<class T> T delta_of_call(/* … */)                    noexcept;
template<class T> T delta_of_put (/* … */)                    noexcept;
template<class T> T gamma        (/* … */)                    noexcept;
template<class T> T theta_forward(/* … */)                    noexcept;

// Variants: BatesLognormal, BatesNormal, BatesLognormalShifted
// Shared CF plumbing with HestonLognormal, +Merton jump component
queued
src/ReflexLibs.Ai/src/finance/options/bates/csharp/ (queued)
Will follow the Heston Normal dual-path pattern: Path A from Bates 1996 + Path B from heritage BatesLognormal.cpp. Reuses the Heston Lognormal characteristic-function φ; adds the Merton jump CF as a multiplicative factor.
// BatesLognormalFromPaper.cs — Path A (queued, Bates 1996 RFS)
public static class BatesLognormalFromPaper {
    public static double PriceOfCall(
        double forward, double strike, double timeToExpiry,
        double kappa, double theta, double omega, double rho, double v0,
        double lambdaJ, double muJ, double sigmaJ,
        int nodeCount = 1024) { /* … Heston φ × jump-CF … */ }

    public static double PriceOfPut  (/* same signature */) { /* … */ }
    public static double DeltaOfCall (/* … */)                         { /* … */ }
    public static double Gamma       (/* … */)                         { /* … */ }
    public static double ThetaForward(/* … */)                         { /* … */ }
}

// BatesLognormalFromHeritage.cs — Path B under permission grant
public static class BatesLognormalFromHeritage { /* same 6 entry points */ }
src/ReflexLibs.Ai/src/finance/reflex-contracts/rust/src/instruments.rs
Production instrument traits ported from Heritage C#. FixedRateSwap, TenorBasisSwap, InflationSwap. Result<T,E> throughout. Clean dependency graph: Types ← Legs ← Accrual ← Instruments.
/// Fixed Rate Swap — Rust trait
pub trait FixedRateSwap: Swap {
    fn fixed_leg(&self) -> &dyn FixedLeg;
    fn float_leg(&self) -> &dyn FloatLeg;
    fn paying_currency(&self) -> Currency;
}

/// Accrual Period — generic over day count basis
pub struct AccrualPeriod {
    pub start: NaiveDate,
    pub end: NaiveDate,
    pub basis: DayCountBasis,
    pub notional: f64,
}
Reference impl
src/ReflexLibs.Ai/src/finance/reflex-contracts/Instruments/cpp/include/reflex/contracts/instruments/
Header-only C++17 port of the Delta One instrument hierarchy. Ported from Rust, not from heritage C++ — preserves the Rustified type system end-to-end. Pure-virtual interfaces with virtual ~IX() = default;, template-over-Currency, std::variant for sum types, std::optional for nullable values. Five packs (Types, Legs, Accrual, Pricing, Instruments) built as CMake INTERFACE libraries.
// IFixedRateSwap — C++17 Delta One
template <class C>
class IFixedRateSwap : public ISwap {
public:
    virtual const IFixedLeg<C>& fixed_leg() const = 0;
    virtual const IFloatLeg<C>& float_leg() const = 0;
    virtual const C& paying_currency() const = 0;
};

// AccrualPeriod — no chrono dependency at contract level
struct AccrualPeriod {
    Ymd start;
    Ymd end;
    std::optional<StubData> stub;
};

// Discriminants match Rust #[repr(u8)] and C# : byte exactly
enum class Basis : std::uint8_t {
    ActualActualIsda = 4,
    Actual360Fixed   = 5,
    Actual365Fixed   = 6,
    // ... 14 conventions total
};
Heritage + Rustified
src/ReflexLibs.Ai/src/finance/reflex-contracts/csharp/Instruments/
15 years of production interfaces. IFixedRateSwap, ITenorBasisSwap, IInflationSwap. Rustified: readonly record struct, OneOf<T,E>, no exceptions. IPricingContext for multi-curve OIS discounting.
// IFixedRateSwap — Rustified C# from Heritage
public interface IFixedRateSwap : ISwap {
    IFixedLeg FixedLeg { get; }
    IFloatLeg FloatLeg { get; }
    ICurrency PayingCurrency { get; }
}

// AccrualPeriod — day count, compounding, spread
public readonly record struct AccrualPeriod(
    DateOnly Start, DateOnly End,
    DayCountBasis Basis, double Notional);
src/ReflexLibs.Ai/src/finance/reflex-contracts/rust/src/options.rs
ISwaption (cash/swap settle), ICap/Floor, IFutureOption. CallOrPut enum, exercise style, strike adjustment. Forward premium pricing default. Clean trait hierarchy.
/// Swaption — Rust
pub trait Swaption: Option {
    fn underlying_swap(&self) -> &dyn FixedRateSwap;
    fn settlement(&self) -> SettlementType;
    fn call_or_put(&self) -> CallOrPut;
    fn expiry(&self) -> NaiveDate;
}

pub enum SettlementType { Cash, Physical }
pub enum CallOrPut { Call, Put }
PlannedPlanned
src/ReflexLibs.Ai/src/finance/reflex-contracts/cpp/ (planned)
C++ port of options contracts from Rust. Will follow the swaption trait pattern with abstract base classes. Part of Priority 3 C++ port.
Heritage
src/ReflexLibs.Ai/src/finance/reflex-contracts/csharp/Instruments/
ISwaption, ICapFloor, IFutureOption. Cash/swap settlement. Forward premium pricing. CallOrPut enum matches Rust discriminant values.
// ISwaption — Heritage C#
public interface ISwaption : IOption {
    IFixedRateSwap UnderlyingSwap { get; }
    SettlementType Settlement { get; }
    CallOrPut CallOrPut { get; }
    DateOnly Expiry { get; }
}

public enum SettlementType { Cash, Physical }
public enum CallOrPut { Call, Put }
Layer 3 — MathIR Pipeline
One Spec → Nine Languages
TOML is the single source of mathematical truth. The MathIR compiler parses formulas into a typed AST, validates domains and invariants, then emits deterministic code for each target language. Humans write the spec. Machines write the code. Drift is impossible.
TOML → Typed AST
Restricted expression grammar: +, -, *, /, ^, named functions, variables. No loops, no conditionals, no implicit coercions. Formal language spec.
Deterministic Lowering
Each AST node has a fixed expansion per language. Add(a,b) → a + b. No ambiguity. Domain checks inserted before computation, never after.
9 Language Emitters
Rust, C++, C#, Go, JavaScript, TypeScript, Python, CUDA, Excel LAMBDA. Same spec, same math, verified parity via shared JSON test vectors.
Invariant Verification
Put-call parity (±1e-12), ATM equality, delta sum, bound checks, gamma/vega positivity. Invariants declared in TOML, enforced in every language.
Precision Escalation
f64 → Decimal128 → big:256 → big:1024. Declared per-algorithm. Automatic when precision matters.
MathIR Source — relation.toml
# MathIR: Black-76 Forward Option Model
# This TOML is the single source of truth.
# 9 language emitters generate from this spec.

[relation]
id    = "xll.ai.math.ir.options.black76"
title = "Black-76 Forward Option Model"

[variables]
F     = "Real > 0"      # Forward price
K     = "Real > 0"      # Strike price
sigma = "Real > 0"      # Log-normal volatility
T     = "Real > 0"      # Time to expiry

[auxiliaries]
total_vol = "sigma * sqrt(T)"
d1 = "(ln(F/K) + 0.5 * sigma^2 * T) / total_vol"
d2 = "d1 - total_vol"

[constraint]
formula = "C = D * (F * N(d1) - K * N(d2))"

[[invariants]]
id = "put_call_parity"
formula   = "C - P = D * (F - K)"
tolerance = 1e-12

[codegen]
languages = ["rust", "csharp", "cpp", "javascript", "python",
             "go", "typescript", "cuda", "excel_lambda"]
Layer 4 — Acceleration
GPU + WASM + Native
The same pure math compiled for maximum performance on each target. CUDA kernels for batch pricing on NVIDIA GPUs. Rust WASM for browser-side computation. wgpu GPU renderer for NanoTable (next).
CUDA Black-76 Kernel
Actual production kernel: __host__ __device__ dual-target, norm_cdf via erfcf, batch call+put pricing. One thread per option, millions per second.
Rust → WASM
wasm-pack compilation. nanotable_wasm.wasm <500KB. Browser-side pricing with no server round-trip. Shipping now.
wgpu GPU Renderer
Phase 3: GPU-accelerated NanoTable rendering via wgpu+dwrote+etagere. Font atlas, on-demand glyph rasterization. Next.
Generated from MathIR
// Black-76 — actual CUDA kernel from ReflexLibs.Ai/cuda
// __host__ __device__ : runs on both CPU and GPU
__host__ __device__ inline float norm_cdf(float x) {
    const float INV_SQRT2 = 0.70710678118654752440f;
    return 0.5f * erfcf(-x * INV_SQRT2);
}

__host__ __device__ inline void black76_one(
    float F, float K, float T, float sigma, float DF,
    float& call, float& put) {
    float sqrtT = sqrtf(T);
    float d1 = (logf(F / K) + 0.5f * sigma * sigma * T) / (sigma * sqrtT);
    float d2 = d1 - sigma * sqrtT;
    call = DF * (F * norm_cdf(d1) - K * norm_cdf(d2));
    put  = DF * (K * norm_cdf(-d2) - F * norm_cdf(-d1));
}

__global__ void black76_kernel(
    int n, const float* F, const float* K, const float* T,
    const float* V, const float* DF, float* C, float* P) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) black76_one(F[i], K[i], T[i], V[i], DF[i], C[i], P[i]);
}
Heritage
src/ReflexLibs.Ai/src/finance/risk/cpp/
Zero-coupon and projection curve sensitivities. Scenario analysis. Seasonality and calendar sensitivities. Layered OIS discounting separation. Production since 2011.
// Curve sensitivity — bump-and-reprice
template<typename Curve>
std::vector<double> zc_sensitivities(
    const Curve& base_curve,
    const std::vector<double>& tenors,
    double bump_size = 0.0001) {
    std::vector<double> sensitivities;
    for (const auto& tenor : tenors) {
        auto bumped = base_curve.bump(tenor, bump_size);
        sensitivities.push_back(reprice(bumped) - reprice(base_curve));
    }
    return sensitivities;
}
src/ReflexLibs.Ai/src/finance/risk/csharp/
Curve sensitivities, scenario analysis. Integrated with IPricingContext for consistent multi-curve bumping. Layered OIS discounting.
// Curve sensitivity — C# bump-and-reprice
public static double[] ZcSensitivities(
    IDiscountCurve baseCurve,
    ReadOnlySpan<double> tenors,
    double bumpSize = 0.0001) {
    var result = new double[tenors.Length];
    for (var i = 0; i < tenors.Length; i++) {
        var bumped = baseCurve.Bump(tenors[i], bumpSize);
        result[i] = Reprice(bumped) - Reprice(baseCurve);
    }
    return result;
}
Heritage
src/ReflexLibs.Ai/src/finance/timeseries/cpp/
MA, EMA, MACD, ADX, Ichimoku. Realized volatility, variance, correlation. Intraday analytics. Discrete unhedgeable jump separation. Production since 2010.
// Exponential Moving Average — Heritage C++
template<typename T>
class EMA {
    T _alpha, _value;
    bool _initialized = false;
public:
    explicit EMA(int period)
        : _alpha(2.0 / (period + 1)), _value{} {}
    T update(T price) {
        if (!_initialized) { _value = price; _initialized = true; }
        else _value = _alpha * price + (1 - _alpha) * _value;
        return _value;
    }
};
src/ReflexLibs.Ai/src/finance/timeseries/csharp/
Full suite of technical indicators. Integrated with NanoTable rendering pipeline. Span<T> for zero-allocation streaming updates.
// EMA — C# with Span<T> streaming
public sealed class Ema {
    private readonly double _alpha;
    private double _value;
    private bool _init;

    public Ema(int period) => _alpha = 2.0 / (period + 1);

    public double Update(double price) {
        if (!_init) { _value = price; _init = true; }
        else _value = _alpha * price + (1 - _alpha) * _value;
        return _value;
    }
}
Languages

One Library, Nine Runtimes

Rust
Rust
Golden master. Zero-cost.
C++
C++
Heritage. 15 years production.
C#
C#
Triumvirate. .NET 8.
Go
Go
Cloud-native. gRPC.
JavaScript
JavaScript
Browser validation.
TypeScript
TypeScript
Type-safe web.
Python
Python
Research bridge.
CUDA
CUDA
GPU parallel.
Excel Lambda
Excel Lambda
Spreadsheet-native.
9
Languages
333
Decimal128 Tests
15+
Years Heritage
128
Bit Precision