API Reference
Core Go packages and function signatures in floe.
Pricing (blackscholes)
BlackScholes
price := blackscholes.BlackScholes(floe.BlackScholesParams{
Spot: 100, Strike: 105, TimeToExpiry: 0.25,
RiskFreeRate: 0.05, Volatility: 0.20,
OptionType: floe.Call,
})
// Error-returning variant for untrusted inputs:
checkedPrice, err := blackscholes.BlackScholesPrice(params)
BlackScholes computes the European Black–Scholes–Merton price per unit at full IEEE-754 float64 precision without Greeks or cent rounding. At zero time to expiration it returns the intrinsic value, and at zero volatility the discounted deterministic payoff max(0, ±(S·e^(−qT) − K·e^(−rT))). Zero spot is valid (K·e^(−rT) for a put). Invalid or non-finite inputs return an error from BlackScholesPrice and panic in BlackScholes. CalculateGreeks().Price continues to round to two decimals.
CalculateGreeks
g := blackscholes.CalculateGreeks(params)
fmt.Println(g.Price, g.Delta, g.Gamma, g.Theta, g.Vega, g.Rho)
fmt.Println(g.Vanna, g.Charm, g.Volga, g.Speed, g.Zomma, g.Color, g.Ultima)
CalculateImpliedVolatility
ivPercent := blackscholes.CalculateImpliedVolatility(
3.50, // option price
100, // spot
105, // strike
0.05, // risk-free rate
0.01, // dividend yield
0.25, // time to expiry (years)
floe.Call,
)
The bisection solver inverts the unrounded full-precision price rather than a cent-rounded price. Non-positive or non-finite inputs continue to return 0 without panicking.
GetTimeToExpirationInYears
tte := blackscholes.GetTimeToExpirationInYears(expirationMs, time.Now().UnixMilli())
Statistics (statistics)
cdf := statistics.CumulativeNormalDistribution(1.96)
pdf := statistics.NormalPDF(0)
Volatility Surfaces (volatility)
GetIVSurfaces
surfaces := volatility.GetIVSurfaces(
floe.SmoothingTotalVariance,
chain,
time.Now().UnixMilli(),
)
GetIVForStrike
ivAtK := volatility.GetIVForStrike(surfaces, expiryMs, floe.Call, 450)
SmoothTotalVarianceSmile
smoothed := volatility.SmoothTotalVarianceSmile(
[]float64{440, 445, 450, 455, 460},
[]float64{23, 21, 19, 20, 22},
0.08,
)
Dealer Exposure (exposure)
CalculateGammaVannaCharmExposures
variants := exposure.CalculateGammaVannaCharmExposures(
chain,
surfaces,
floe.ExposureCalculationOptions{AsOfTimestamp: time.Now().UnixMilli()},
)
for _, v := range variants {
fmt.Println(v.Expiration, v.Canonical.TotalNetExposure)
}
CalculateSharesNeededToCover
cover := exposure.CalculateSharesNeededToCover(900_000_000, totalNetExposure, spot)
fmt.Println(cover.ActionToCover, cover.SharesToCover, cover.ImpliedMoveToCover)
Hedge Flow (hedgeflow)
ComputeHedgeImpulseCurve
curve := hedgeflow.ComputeHedgeImpulseCurve(
canonicalExposure,
callSurface,
hedgeflow.HedgeImpulseConfig{RangePercent: 3, StepPercent: 0.05, KernelWidthStrikes: 2},
time.Now().UnixMilli(),
)
ComputeCharmIntegral
charm := hedgeflow.ComputeCharmIntegral(
canonicalExposure,
hedgeflow.CharmIntegralConfig{TimeStepMinutes: 15},
time.Now().UnixMilli(),
)
AnalyzeHedgeFlow
analysis := hedgeflow.AnalyzeHedgeFlow(
canonicalExposure,
callSurface,
hedgeflow.HedgeImpulseConfig{},
hedgeflow.CharmIntegralConfig{},
time.Now().UnixMilli(),
)
Implied Probability (impliedpdf)
EstimateImpliedProbabilityDistribution
result := impliedpdf.EstimateImpliedProbabilityDistribution(
"QQQ",
502.5,
callOptions,
time.Now().UnixMilli(),
)
EstimateImpliedProbabilityDistributions
dists := impliedpdf.EstimateImpliedProbabilityDistributions(
"QQQ",
502.5,
allOptions,
time.Now().UnixMilli(),
)
Query helpers
prob := impliedpdf.GetProbabilityInRange(dist, 495, 510)
cum := impliedpdf.GetCumulativeProbability(dist, 500)
q90 := impliedpdf.GetQuantile(dist, 0.90)
IV vs RV (iv, rv, volresponse)
Model-free IV
near := iv.ComputeVarianceSwapIV(nearTermOptions, spot, 0.05, time.Now().UnixMilli())
targetDays := 1
interp := iv.ComputeImpliedVolatility(nearTermOptions, spot, 0.05, time.Now().UnixMilli(), farTermOptions, &targetDays)
Realized volatility
rvResult := rv.ComputeRealizedVolatility(observations)
Vol response z-score
obs := volresponse.BuildVolResponseObservation(currentIV, currentRV, currentSpot, nowMs, prevIV, prevSpot)
result := volresponse.ComputeVolResponseZScore(series, volresponse.VolResponseConfig{})
Dataset API Client (apiclient)
NewApiClient
client := apiclient.NewApiClient("YOUR_API_KEY", nil)
GetHindsightData
events, err := client.GetHindsightData(ctx, apiclient.HindsightDataRequest{
StartDate: "2026-03-01",
EndDate: "2026-03-16",
Country: "US",
MinVolatility: 2,
Event: "CPI",
})
GetHindsightSample
sample, err := client.GetHindsightSample(ctx)
GetDealerMinuteSurfaces
rows, err := client.GetDealerMinuteSurfaces(ctx, apiclient.DealerMinuteSurfacesRequest{
Symbol: "SPY",
TradeDate: "2026-03-10",
})
GetAMTSessionStats
rows, err := client.GetAMTSessionStats(ctx, apiclient.AMTRequest{
Symbol: "NQ",
SessionID: "2026-03-10",
})
GetAMTEvents
rows, err := client.GetAMTEvents(ctx, apiclient.AMTRequest{
Symbol: "NQ",
SessionID: "2026-03-10",
})
Profit and Loss (pnl)
All functions in github.com/FullStackCraft/floe-go/pnl are synchronous, zero-dependency, and return (result, error) on invalid inputs without panicking. *PreparedPnLPosition is safe for concurrent use across goroutines.
| Entry point | Result |
|---|---|
pnl.CalculatePnL(position, market, options) |
Single-spot valuation, signed position value, P&L, total entry cost, and scenario metadata |
pnl.CalculatePnLCurve(position, market, options) |
Spot curve points, analytic or numerical break-evens, expiration bounds, and sampled extrema |
pnl.CalculatePnLCurves(items, defaults) |
Packed []float64 P&L buffer, interned shared grids, and per-position metadata |
pnl.CalculatePnLSurface(position, market, options) |
Two axis slices, width, height, row-major []float64 P&L buffer, and grid min/max |
pnl.PreparePnLPosition(position, market) |
Reusable goroutine-safe snapshot with CalculatePoint, CalculateCurve, CalculateSurface, CalculateEnvelope, and ResolveSmile |
Positions and Market Context
Each pnl.PnLPosition has one underlying, a non-empty Legs slice, optional ID, Symbol, and non-negative Fees. Positive quantities are long and negative quantities are short. Pointer helpers pnl.Float64, pnl.Int64, pnl.Int, and pnl.Bool construct optional values cleanly.
now := time.Now().UnixMilli()
expiration := now + 7*86_400_000
market := pnl.PnLMarketContext{
Spot: 354,
AsOfTimestamp: now,
RiskFreeRate: 0.04,
DividendYield: 0.004,
}
position := pnl.PnLPosition{
Symbol: "AAPL",
Fees: 1.50,
Legs: []pnl.PnLLeg{
{Type: pnl.LegTypeStock, Quantity: 100, EntryPrice: 350},
{
Type: pnl.LegTypeOption,
OptionType: floe.Call,
Strike: 360,
ExpirationTimestamp: expiration,
Quantity: -1,
EntryPrice: 3,
ImpliedVolatility: pnl.Float64(0.25),
},
},
}
point, err := pnl.CalculatePnL(position, market, &pnl.PnLPointOptions{
PnLScenario: pnl.PnLScenario{Spot: pnl.Float64(355)},
PnLOutputOptions: pnl.PnLOutputOptions{IncludeLegBreakdown: true, IncludeGreeks: true},
})
prepared, err := pnl.PreparePnLPosition(position, market)
expCurve, err := prepared.CalculateCurve(&pnl.PnLCurveOptions{
PnLScenario: pnl.PnLScenario{EvaluationTimestamp: prepared.EarliestExpiration},
})
nextDay, err := prepared.CalculateCurve(&pnl.PnLCurveOptions{
PnLScenario: pnl.PnLScenario{
EvaluationTimestamp: pnl.Int64(now + 86_400_000),
VolatilityShift: 0.05,
},
})
Curves, Break-Evens, and Bounds
PriceRange: &pnl.PnLPriceRange{Min, Max, Points} defines a uniform base grid (defaulting to 500 points widened by exp(±2σ√T) clamped between 5% and 75%, or ±20% when no IV is known). Alternatively pass a strictly increasing Spots slice.
- Analytic expiration payoff: When all option legs share a single expiration and
EvaluationTimestampequals that expiration (or the position is stock-only),BreakEvens(Method: pnl.MethodAnalytic,Complete: true) andExpirationStatistics(MaxProfit,MaxLoss,MaxProfitRegions,MaxLossRegions) are computed globally from the exact piecewise-linear knot sweep. - Numerical break-evens: Pre-expiration and front-expiration calendar curves refine sign crossings via bisection and local extrema via ternary search (
Method: pnl.MethodNumerical,Complete: false). Customize viaRootSearch: &pnl.PnLRootSearch{...}.
Volatility Scenarios
All P&L implied volatilities and shifts are annualized decimals (0.05 adds five percentage points). Legacy floe.IVSurface values in percent are converted once during preparation.
PnLVolatilityModel.Kind |
Assumption |
|---|---|
pnl.ModelConstant (default) |
Hold each leg's baseline IV constant (or interpolate the reference surface if leg IV is nil). |
pnl.ModelStickyStrike |
Read the reference smile at the fixed contract strike and original tenor. |
pnl.ModelStickyMoneyness |
Read the original tenor at strike * referenceSpot / scenarioSpot. |
pnl.ModelCoupled |
Apply directional (BetaReturn) and absolute (BetaAbsReturn) log-return stresses to baseline IV. |
pnl.ModelDynamic |
Roll the smile along spot moneyness and remaining tenor, plus skew, curvature, and annual drift stresses. |
Custom resolvers implement pnl.PnLVolatilityResolver:
pt, err := prepared.CalculatePoint(&pnl.PnLPointOptions{
PnLScenario: pnl.PnLScenario{
VolatilityShift: 0.01,
VolatilityResolver: func(ctx pnl.PnLVolatilityContext) float64 {
base := 0.25
if ctx.BaseIV != nil {
base = *ctx.BaseIV
}
if ctx.ScenarioSpot < ctx.ReferenceSpot {
return base + 0.04
}
return base
},
},
})
Batch Screening and 2D Surfaces
pnl.CalculatePnLCurves(items, defaults) packs every curve's P&L into one contiguous []float64 slice and interns identical coordinate grids:
batch, err := pnl.CalculatePnLCurves(items, &pnl.PnLBatchOptions{
OnError: pnl.BatchErrorCollect,
PnLCurveOptions: pnl.PnLCurveOptions{
PriceRange: &pnl.PnLPriceRange{Min: 300, Max: 400, Points: 50},
PnLOutputOptions: pnl.PnLOutputOptions{IncludeStatistics: pnl.Bool(false)},
},
})
for _, row := range batch.Rows {
if row.Error != "" {
continue // failed row span in batch.PnL is filled with NaN
}
grid := batch.Grids[row.GridIndex]
values := batch.PnL[row.Offset : row.Offset+row.Length]
_ = grid
_ = values
}
pnl.CalculatePnLSurface evaluates a row-major rectangular grid across any two distinct dimensions (pnl.DimensionSpot, pnl.DimensionTime, pnl.DimensionVolatilityShift).
Benchmarks
Run go test -bench=. -benchmem ./pnl for native Go CPU and allocation measurements. Representative results on an Apple M3 Max (go1.26.2 darwin/arm64):
| Workload | Time / op | Allocs / op |
|---|---|---|
| 100 expiration curves × 50 points (1 leg) | 0.076 ms | 1,112 |
| 100 expiration curves × 500 points (1 leg) | 0.36 ms | 1,213 |
| 1,000 expiration curves × 500 points (1 leg) | 3.5 ms | 12,016 |
| 1 theoretical curve × 501 points, roots + stats | 0.060 ms | 536 |
| 100 theoretical curves × 500 points (1 leg / 4 legs) | 2.3 ms / 8.6 ms | 1,413 / 2,514 |
| 100 four-leg curves × 500 points, coupled IV | 13.1 ms | 2,914 |
| 1 spot/time surface, 200 × 100 | 0.92 ms | 910 |
100,000 prices: BlackScholes / CalculateGreeks |
6.3 ms / 16.5 ms | 0 / 0 |