Skip to main content

Crate fin_primitives

Crate fin_primitives 

Source
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.

Three bundled examples running in a terminal: an order book ladder, an option chain with Greeks, and a position ledger tripping a drawdown limit

Add it (the dec! macro for decimal literals needs both rust_decimal crates):

cargo add fin-primitives rust_decimal rust_decimal_macros

The 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);

Animated diagram: real ticks land in one-minute buckets, push_tick returns the finished bar when the next bucket starts, and RSI(14) returns Unavailable until bar 15

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:

CommandShows
cargo run --example order_bookdepth ladder, spread, micro-price, VWAP fill, rejected deltas
cargo run --example candlesticks to 1-minute candles, EMA and RSI with warm-up
cargo run --example position_riskfills, mark-to-market, drawdown and equity-floor breaches
cargo run --example option_chainBlack-Scholes chain with Greeks and an implied-vol round trip

§Where things live

ModuleWhat it provides
typesPrice, Quantity, Symbol, NanoTimestamp, Side
tickTick, TickFilter, TickReplayer
orderbookOrderBook: L2 book with sequence checks and crossed-book rollback
ohlcvOhlcvBar, OhlcvAggregator, OhlcvSeries analytics
signalsthe Signal trait, SignalPipeline, and several hundred indicators in signals::indicators
positionFill, Position, PositionLedger, Kelly sizing
riskDrawdownTracker, the RiskRule trait, RiskMonitor, VaR and stress tools
greeksBlackScholes pricing, Greeks, implied volatility, multi-leg spreads
backtestbar-by-bar Backtester, Strategy trait, WalkForwardOptimizer
async_signalsTokio-based StreamingSignalPipeline
regimeHurst 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

featuredefaultadds
serdeyesSerialize/Deserialize on the data types; deserializing re-runs validation
asyncyesasync_signals: a Tokio task that runs a signal pipeline over a channel
ta, yata, wickranointerop with those crates: their indicators read fin-primitives bars, their bars convert to BarInput
arrownoarrow: bars to and from Apache Arrow with exact Decimal128 columns
pythonnoPyO3 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::new rejects zero and negative values; Quantity::new rejects negatives; Symbol::new rejects 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 in f64 and convert at the boundary.
  • Typed errors. Fallible operations return Result<_, FinError>, and the crate’s Clippy config warns on unwrap, expect and panic.
  • Traits at the seams. risk::RiskRule, signals::Signal and tick::TickFilter are 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 AltDataAggregator with 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_signalsasync
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 Strategy trait, 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 OhlcvSeries analytics.
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 PositionLedger with 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 full RegimeHistory audit trail.
risk
Drawdown tracking, pluggable RiskRules, RiskMonitor, VaR and stress tools.
scenario
Risk scenario backtesting: replays historical bars through risk rules.
signals
The Signal trait, 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, NanoTimestamp and Side.
volatility
Realised volatility estimators: Close-to-Close, Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang. Also provides volatility::garch with GARCH(1,1) MLE fitting, conditional variance, multi-step forecasting, and volatility term structure.
yield_curve
Yield Curve Modeler