Everything cut from the main README.
The basic parts of a trading program in one cargo add: exact prices, an order book, candles, 700+ indicators, option pricing and risk limits.
f64 prices drift and accept nonsense. Here Price::new(dec!(-1)) is an error.
If it doesn't do what this README says, open an issue and I'll fix it.
For trading bots, backtesters, market data tools and quant research in Rust.
cargo add fin-primitives rust_decimal rust_decimal_macrosRust 1.81 or newer (checked in CI). rust_decimal_macros gives you the dec!(64250.50) literal.
use fin_primitives::signals::{indicators::Rsi, BarInput, Signal, SignalValue};
use fin_primitives::types::Price;
use rust_decimal_macros::dec;
fn main() -> Result<(), fin_primitives::FinError> {
assert!(Price::new(dec!(-1)).is_err()); // bad values never get in
let mut rsi = Rsi::new("rsi14", 14)?;
let closes = [dec!(44.34), dec!(44.09), dec!(44.15), dec!(43.61), dec!(44.33), dec!(44.83), dec!(45.10), dec!(45.42),
dec!(45.84), dec!(46.08), dec!(45.89), dec!(46.03), dec!(45.61), dec!(46.28), dec!(46.28), dec!(46.00)];
for close in closes {
if let SignalValue::Scalar(v) = rsi.update(&BarInput::from_close(close))? {
println!("RSI(14) = {}", v.round_dp(2)); // 70.46, then 66.25
}
}
Ok(())
}Indicators return Unavailable until they have enough bars (here 14). Never a fake 0 or NaN.
cargo test --doc runs this block.
Measured on the same 100,000 closes (bench/competitors, bench/talib_compare):
- Exact decimals. Everything is
rust_decimal::Decimal.0.1 + 0.2is0.3. P&L adds up to the cent. SMA and EMA matchtaandyatato 1e-12, and TA-Lib to 2e-11 or better on 22 shared indicators. - TA-Lib definitions.
Rsiis Wilder's RSI.ta's RSI was off by up to 20 points on the same data. - Bad input is an error. A zero price, a crossed book or a skipped sequence number is an
Err. Nounwrapin library code. - One crate: order book, ticks to bars, 700+ indicators, positions, drawdown and VaR limits, Black-Scholes with Greeks.
- Slower.
taandyataare 40 to 160 times faster per update (f64 vs 96-bit decimal). This still does 4 to 25 million updates per second per core. For long float64 histories, use them or TA-Lib.
Keep them. Turn on the matching feature. Their indicators read these bars, and their bars convert to these:
fin-primitives = { version = "3", features = ["ta"] } # or "yata", "wickra", "arrow"use ta::indicators::MovingAverageConvergenceDivergence;
use ta::Next;
let mut macd = MovingAverageConvergenceDivergence::new(12, 26, 9)?;
for bar in aggregator.push_tick(&tick)? { // fin_primitives::ohlcv::OhlcvBar
let m = macd.next(&bar); // ta reads the bar through ta::Close
let r = rsi.update_bar(&bar)?; // fin-primitives Wilder RSI, same bar
}Full version: cargo run --example with_ta --features ta. The other way:
BarInput::try_from(&ta::DataItem), BarInput::try_from(&yata::core::Candle),
BarInput::try_from(&wickra_core::Candle).
| feature | default | adds |
|---|---|---|
serde |
yes | Serialize/Deserialize on the data types; deserializing re-runs validation |
indicators |
yes | signals::indicators (700+ streaming indicators), technical, regime, correlation, volatility |
options |
yes | greeks (Black-Scholes, Greeks, implied volatility) and options |
portfolio, risk, backtest |
yes | ledger, P&L, attribution, risk limits, backtester, execution costs |
fixed-income, derivatives, crypto, credit, ml, tax, yield-curve, clustering, montecarlo |
yes | the other domain modules |
async |
no | async_signals: a Tokio task that runs a signal pipeline over a channel |
ta-compat |
no | a drop-in for the ta crate's API, computed with these indicators |
ta |
no | interop with the ta crate |
yata |
no | interop with the yata crate |
wickra |
no | interop with wickra-core (Rust 1.86+) |
arrow |
no | bars to and from Apache Arrow RecordBatch, prices as exact Decimal128 (Rust 1.88+) |
python |
no | PyO3 bindings for the fin-primitives Python package; cd python && maturin build (Rust 1.83+), see docs/python.md |
default-features = false leaves the core types (Price, Quantity, Symbol, Tick,
OrderBook, OHLCV, the Signal trait) and four dependencies: rust_decimal, chrono,
thiserror and libm. For the indicators alone use
default-features = false, features = ["indicators"]
(cargo run --example indicators_only --no-default-features --features indicators).
Builds for wasm32-unknown-unknown. Adding fin-primitives to another project:
INTEGRATION.md.
Trades come in as Ticks. OhlcvAggregator::push_tick puts each in a time bucket. When a trade
for the next bucket arrives, you get the finished candle. Candles feed indicators.
Money works the same way. Fills and marks go into a PositionLedger. Its value goes into a
RiskMonitor. Every broken rule comes back as a RiskBreach.
Six programs in examples/. No network, no keys, same output every run.
| Run this | You get |
|---|---|
cargo run --example order_book |
a BTC-USD depth ladder, spread, micro-price, the cost of a 5 BTC market buy, and two bad updates rejected |
cargo run --example candles |
337 trades rolled into 32 one-minute candles, drawn with EMA(9) and RSI(14) |
cargo run --example position_risk |
a trading session marked to market, with a drawdown rule and an equity floor firing |
cargo run --example option_chain |
a Black-Scholes option chain with Greeks and an implied-volatility round trip |
cargo run --example value_at_risk |
one-day and ten-day VaR for a $1M book: historical, parametric and Monte Carlo at 95%, 97.5% and 99% |
cargo run --example with_ta --features ta |
ticks rolled into bars by fin-primitives, fed to ta's MACD and Bollinger Bands and to fin-primitives' RSI |
order_book: knows its spread and mid price. Refuses updates that cross it or skip a sequence number.
position_risk (real output, run 2026-09-28, NO_COLOR=1):
# event equity drawdown risk
5 sell 100 AAPL @ 179.10 101,237.00 0.00% ok
6 mark MSFT 398.10 99,865.00 1.36% ok
7 mark AAPL 166.80 98,635.00 2.57% ok
8 mark MSFT 371.50 96,507.00 4.67% BREACH max_drawdown, min_equity
max_drawdown: drawdown 4.67% > 4.00%
min_equity: equity 96507.00 < floor 96600
rejected buy 1000 AAPL Insufficient funds: need 171351.00, have 79866.00
(rows 1 to 4 and 9 to 10 cut. The diagram above plays the whole session.)
1. Make a project and add the crate
cargo new book-demo && cd book-demo
cargo add fin-primitives rust_decimal rust_decimal_macros2. Put this in src/main.rs
use fin_primitives::orderbook::{BookDelta, DeltaAction, OrderBook};
use fin_primitives::types::{Price, Quantity, Side, Symbol};
use rust_decimal_macros::dec;
fn main() -> Result<(), fin_primitives::FinError> {
// 1. Values are checked when you create them.
println!("Price::new(-5) -> {}", Price::new(dec!(-5)).unwrap_err());
// 2. Build a small BTC-USD order book from four quotes.
let mut book = OrderBook::new(Symbol::new("BTC-USD")?);
let quotes = [
(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(quotes) {
book.apply_delta(BookDelta {
side,
price: Price::new(price)?,
quantity: Quantity::new(qty)?,
action: DeltaAction::Set,
sequence: seq,
})?;
}
// 3. Ask it questions.
println!("spread {}", book.spread().unwrap_or_default());
println!("mid price {}", book.mid_price().unwrap_or_default());
let one_btc = Quantity::new(dec!(1))?;
println!("buy 1 BTC at {} average", book.vwap_for_qty(Side::Ask, one_btc)?.round_dp(2));
Ok(())
}3. Run it
cargo runYou will see:
Price::new(-5) -> Price must be positive, got -5
spread 0.50
mid price 64250.25
buy 1 BTC at 64250.58 average
"What would 1 BTC cost" is one call (0.842 BTC at the best ask, 0.158 at the next level).
cargo test --doc runs this exact program.
Same 100,000 seeded OHLCV bars through both (method, script and full tables;
i7-13700KF, TA-Lib 0.8.1). Where definitions match, values agree to 2e-11 or better. The float64 side is the one that rounds.
One differs on purpose: Obv starts at 0. (Up to 3.9, Atr was a simple average of true range; since 4.0 it is
Wilder's, equal to TA-Lib ATR.) TA-Lib is about 100 times faster (0.2 to 12 ns per bar).
Use TA-Lib for long float64 histories. Use this for exact values, bar-by-bar state and no C dependency.
| indicator | max difference vs TA-Lib (after bar 1,000) | fin-primitives, ns per bar | TA-Lib batch, ns per bar |
|---|---|---|---|
| SMA(20) / EMA(20) | 9.8e-13 / 5.7e-14 | 74 / 149 | 0.8 / 1.3 |
| RSI(14) | 1.8e-13 | 252 | 2.1 |
| MACD(12,26,9) histogram | 5.0e-14 (seeded differently: 0.036 in the first bars) | 362 | 1.7 |
| Bollinger(20, 2) bands | 1.6e-11 | 1023 | 2.7 |
| ATR(14) / NATR(14) | 8.4e-15 / 6.4e-15 (Wilder, since 4.0; checked with fin_primitives.Indicator on the same bars) |
86 | 0.8 |
| Stochastic fast %K / %D (14, 3) | 6.7e-13 / 1.3e-12 | 174 / 259 | 7.7 |
| Williams %R(14) / CCI(20) / MFI(14) | 6.7e-13 / 1.0e-11 / 1.3e-12 | 170 / 1060 / 589 | 1.9 / 12.2 / 5.9 |
| ADX(14) | 3.7e-13, except near exact up/down ties that float64 splits | 794 | 6.2 |
| OBV | equals TA-Lib OBV - volume[0] exactly |
13 | 2.8 |
| Read this | For |
|---|---|
| docs.rs/fin-primitives | every type and method, with examples that compile |
| docs/ARCHITECTURE.md | how the modules connect, what each one guarantees, design rules, writing your own indicator or risk rule |
| docs/REFERENCE.md | module guides (indicators, series analytics, ledger, drawdown, attribution, Greeks, regimes, backtester, Monte Carlo, factor models, yield curves and more), math definitions, API listing |
| docs/TESTING.md | running the tests and benchmarks, current test status |
| docs/INTEGRATION.md | depending on it from another project: the minimal feature set, dependencies, stability, replacing pandas-ta calls |
| CHANGELOG.md | what changed in each version |
| Project site | the same overview as a web page |
Python: pip install fin-primitives gives all 743 indicators with exact Decimal or fast float output and numpy / pandas / polars batch helpers. Guide: docs/python.md. From source: cd python && maturin build, install the wheel, then pytest.
It does not place orders. Not financial advice.
Issues and PRs welcome. Public items need /// docs. Fallible code returns Result
(no unwrap, expect or panic! outside tests). New behavior needs a test.
Run cargo fmt, cargo clippy and cargo test --doc first. See CONTRIBUTING.md.
MIT, see LICENSE. fin-stream builds on this crate. It turns live Binance, Coinbase, Alpaca and Polygon trades into ticks, bars and order books.
Source, issues and stars: GitHub. Mirror and release downloads: GitLab. More of my Rust: tensorust.com/open-source.



