Expand description
§fin-primitives
The basic parts of trading software, done once and checked: exact price and size types that refuse bad values, an order book, candles built from trades, indicators, option prices and risk limits.

Add it (the dec! macro for decimal literals needs both rust_decimal crates):
cargo add fin-primitives rust_decimal rust_decimal_macrosThe main types: Price, Quantity and
Symbol (validated values), OrderBook,
OhlcvAggregator (ticks to candles), the
Signal trait and its indicators,
PositionLedger, RiskMonitor,
BlackScholes, and one error type, FinError.
§A first look
Build a book from sequenced deltas, read the top of book, and price a market order by walking the levels:
use fin_primitives::orderbook::{BookDelta, DeltaAction, OrderBook};
use fin_primitives::types::{Price, Quantity, Side, Symbol};
use rust_decimal_macros::dec;
let mut book = OrderBook::new(Symbol::new("BTC-USD")?);
let levels = [
(Side::Ask, dec!(64250.50), dec!(0.842)),
(Side::Ask, dec!(64251.00), dec!(1.310)),
(Side::Bid, dec!(64250.00), dec!(1.204)),
(Side::Bid, dec!(64249.50), dec!(0.655)),
];
for (seq, (side, price, qty)) in (1..).zip(levels) {
book.apply_delta(BookDelta {
side,
price: Price::new(price)?,
quantity: Quantity::new(qty)?,
action: DeltaAction::Set,
sequence: seq,
})?;
}
assert_eq!(book.spread(), Some(dec!(0.50)));
assert_eq!(book.mid_price(), Some(dec!(64250.25)));
// Buying 1 BTC takes all 0.842 at the best ask and 0.158 at the next level.
let vwap = book.vwap_for_qty(Side::Ask, Quantity::new(dec!(1))?)?;
assert_eq!(vwap, dec!(64250.579));
// A delta that would cross the book is rejected and rolled back.
let crossing = BookDelta {
side: Side::Bid,
price: Price::new(dec!(64251.00))?,
quantity: Quantity::new(dec!(2))?,
action: DeltaAction::Set,
sequence: 5,
};
assert!(book.apply_delta(crossing).is_err());
assert_eq!(book.sequence(), 4);Ticks become bars, and bars feed indicators. Indicators return
SignalValue::Unavailable until they
have enough history, never a NaN or a zero:
use fin_primitives::ohlcv::{OhlcvAggregator, Timeframe};
use fin_primitives::signals::indicators::Sma;
use fin_primitives::signals::{BarInput, Signal, SignalValue};
use fin_primitives::tick::Tick;
use fin_primitives::types::{NanoTimestamp, Price, Quantity, Side, Symbol};
use rust_decimal_macros::dec;
let sym = Symbol::new("ETH-USD")?;
let mut agg = OhlcvAggregator::new(sym.clone(), Timeframe::Minutes(1))?;
let mut sma = Sma::new("sma3", 3)?;
let mut values = Vec::new();
for (minute, close) in [(0, dec!(3180)), (1, dec!(3190)), (2, dec!(3200)), (3, dec!(3230))] {
let tick = Tick::new(
sym.clone(),
Price::new(close)?,
Quantity::new(dec!(1))?,
Side::Bid,
NanoTimestamp::from_secs(1_767_625_200 + minute * 60),
);
for bar in agg.push_tick(&tick)? {
values.push(sma.update(&BarInput::from(&bar))?);
}
}
// Three bars have closed; the fourth is still open.
assert_eq!(values[0], SignalValue::Unavailable);
assert_eq!(values[1], SignalValue::Unavailable);
assert_eq!(values[2], SignalValue::Scalar(dec!(3190)));§Runnable examples
The repository ships examples that print formatted, colored output:
| Command | Shows |
|---|---|
cargo run --example order_book | depth ladder, spread, micro-price, VWAP fill, rejected deltas |
cargo run --example candles | ticks to 1-minute candles, EMA and RSI with warm-up |
cargo run --example position_risk | fills, mark-to-market, drawdown and equity-floor breaches |
cargo run --example option_chain | Black-Scholes chain with Greeks and an implied-vol round trip |
§Where things live
| Module | What it provides |
|---|---|
types | Price, Quantity, Symbol, NanoTimestamp, Side |
tick | Tick, TickFilter, TickReplayer |
orderbook | OrderBook: L2 book with sequence checks and crossed-book rollback |
ohlcv | OhlcvBar, OhlcvAggregator, OhlcvSeries analytics |
signals | the Signal trait, SignalPipeline, and several hundred indicators in signals::indicators |
position | Fill, Position, PositionLedger, Kelly sizing |
risk | DrawdownTracker, the RiskRule trait, RiskMonitor, VaR and stress tools |
greeks | BlackScholes pricing, Greeks, implied volatility, multi-leg spreads |
backtest | bar-by-bar Backtester, Strategy trait, WalkForwardOptimizer |
async_signals | Tokio-based StreamingSignalPipeline |
regime | Hurst exponent, GARCH(1,1), correlation-breakdown regime detection |
Further modules cover portfolio optimization, factor models, yield curves, fixed income, credit, derivatives, execution cost, microstructure, Monte Carlo, pairs trading, tax lots and more; see the module list below.
§Feature flags
| feature | default | adds |
|---|---|---|
serde | yes | Serialize/Deserialize on the data types; deserializing re-runs validation |
async | yes | async_signals: a Tokio task that runs a signal pipeline over a channel |
ta, yata, wickra | no | interop with those crates: their indicators read fin-primitives bars, their bars convert to BarInput |
arrow | no | arrow: bars to and from Apache Arrow with exact Decimal128 columns |
python | no | PyO3 bindings, built with maturin from the repository’s python/ folder |
normal has the standard normal CDF, PDF and inverse used by every pricer and
VaR model here (accurate to about 1e-15 relative, including the tails).
§Design
- Validated at construction.
Price::newrejects zero and negative values;Quantity::newrejects negatives;Symbol::newrejects empty or whitespace strings. Code that holds one of these types can trust it. - Decimal where money is. Prices, quantities, P&L and order-book math
use
rust_decimal::Decimal. Statistical models (GARCH, optimizers, Black-Scholes internals) compute inf64and convert at the boundary. - Typed errors. Fallible operations return
Result<_, FinError>, and the crate’s Clippy config warns onunwrap,expectandpanic. - Traits at the seams.
risk::RiskRule,signals::Signalandtick::TickFilterare traits, so your own rules and indicators plug in next to the built-in ones. - No unsafe code. The crate is
#![forbid(unsafe_code)].
Sister crate: fin-stream handles real-time market data ingestion on top of these types.
Re-exports§
pub use error::FinError;
Modules§
- alternative_
data - Alternative data integration: social sentiment, web traffic, satellite imagery,
credit card data, job postings, and patent filings.
Provides
AltDataAggregatorwith composite signals, Pearson correlation, z-score anomaly detection, and staleness checking. - arbitrage
- Cross-market arbitrage detection: ArbitrageOpportunity, TriangularArb, StatisticalArb, ArbitrageScanner (scan_cross_market, scan_triangular, filter_by_min_profit, rank_by_confidence).
- async_
signals async - Tokio-based streaming signal pipeline: push bars in, receive
SignalUpdates out. - attribution
- Portfolio performance attribution: Brinson-Hood-Beebower decomposition, multi-factor attribution, marginal risk contribution, and comprehensive performance tearsheet.
- backtest
- Bar-by-bar backtester, the
Strategytrait, and a walk-forward optimizer. - clustering
- Asset clustering using k-means on return correlations.
- correlation
- Streaming Pearson correlation matrix for indicator redundancy detection.
- credit
- Credit analytics module.
- cross_
asset - Cross-asset rolling correlations and PCA-based dimensionality reduction.
- crypto
- Crypto-specific financial metrics: funding rates, perpetual basis, open-interest ratio, liquidation heatmap, and Fear & Greed index.
- derivatives
- Derivative pricing modules.
- error
- Error types for the fin-primitives crate.
- events
- Event Study Framework
- execution
- Execution cost estimation and turnover optimization.
- execution_
cost - Execution cost models: commission (Fixed, Proportional, Tiered, ZeroCommission), SpreadCost, MarketImpact (linear, sqrt, Almgren-Chriss), TotalExecutionCost, ExecutionCostBreakdown.
- factor
- Fama-French style multi-factor regression and portfolio factor exposure.
- fixed_
income - Fixed income analytics: bond pricing, duration, convexity, and yield calculations.
- funding
- Funding rate calculations for perpetual futures: premium index, clamped funding rate, payment computation, annualization, exponentially-weighted rate prediction, and rolling history with avg/volatility/cumulative-payment aggregation.
- greeks
- Black-Scholes pricing, the five Greeks, implied volatility and multi-leg spreads.
- impact
- Almgren-Chriss optimal order execution and market impact model.
- interop
- Interop with other Rust trading crates, so you can add fin-primitives to a project that already uses one of them without rewriting anything.
- latency
- Order latency tracking: measures submit→ack, ack→fill, fill→book-update phases.
- liquidity
- Liquidity measures: bid-ask spread, market depth, composite liquidity scoring, and Amihud (2002) illiquidity ratio with rolling window averaging.
- microstructure
- Tick-level microstructure metrics: bid-ask spread, Amihud illiquidity, Kyle’s lambda, Roll implied spread.
- ml
- ML feature vector builder: snapshot N indicator outputs, normalize, and serialize for ML pipelines.
- ml_
features - ML feature engineering: price features, microstructure features, feature vectors, z-score normalization, cross-sectional ranking, and lagged feature construction.
- montecarlo
- Monte Carlo price-path simulation: GBM, VaR, CVaR, and percentile paths.
- normal
- The standard normal distribution: density, cumulative probability and its inverse.
- ohlcv
- OHLCV bars, tick-to-bar aggregation by timeframe, and
OhlcvSeriesanalytics. - options
- Black-Scholes options pricing engine with Greeks and implied volatility solver.
- orderbook
- Level-2 order book with sequence-checked deltas and crossed-book rollback.
- pairs_
trading - Statistical pairs trading: Engle-Granger cointegration, ADF stationarity test, spread z-score signal generation, and Welford online mean/variance tracking.
- performance
- Portfolio performance metrics.
- pnl
- Streaming P&L attribution: decomposes realized P&L into alpha and cost components.
- portfolio
- Portfolio construction and optimization.
- position
- Fills, positions and a multi-symbol
PositionLedgerwith realized and unrealized P&L. - rebalancing
- Portfolio rebalancing: drift calculation, threshold and calendar triggers, trade generation, turnover estimation, and tax-aware rebalancing.
- regime
- Market regime engine: Hurst exponent, GARCH(1,1), cross-asset correlation breakdown,
RegimeConditionalSignal(regime-adaptive RSI), and fullRegimeHistoryaudit trail. - risk
- Drawdown tracking, pluggable
RiskRules,RiskMonitor, VaR and stress tools. - scenario
- Risk scenario backtesting: replays historical bars through risk rules.
- signals
- The
Signaltrait, signal pipelines, composition, warm-up contracts and the indicator library. - tax
- Tax lot accounting with FIFO, LIFO, SpecificLot, MinTax, and AverageCost disposal methods.
- technical
- Technical analysis indicators for OHLCV price series.
- tick
- Trade ticks, composable tick filters and a timestamp-ordered tick replayer.
- types
- Validated newtypes:
Price,Quantity,Symbol,NanoTimestampandSide. - volatility
- Realised volatility estimators: Close-to-Close, Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang.
Also provides
volatility::garchwith GARCH(1,1) MLE fitting, conditional variance, multi-step forecasting, and volatility term structure. - yield_
curve - Yield Curve Modeler