fin-primitives 2.15.0

Checked building blocks for Rust trading code: exact decimal price and quantity types, a level-2 order book, ticks to OHLCV candles, 700+ streaming indicators, Black-Scholes Greeks, a position ledger and risk limits.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! PyO3 Python bindings (enabled by the `python` feature).
//!
//! ## Responsibility
//! PyO3 Python bindings for core fin-primitives types and indicators.
//!
//! Enabled via the `python` Cargo feature. When the feature is active, this module
//! exposes a `_fin_primitives` Python extension module containing:
//! - `PyPrice`, `PyQuantity`, `PyOHLCV` — validated newtype wrappers
//! - `PyOrderBook` — L2 order book with Python-friendly methods
//! - `PySMA`, `PyEMA`, `PyRSI` — streaming indicators
//!
//! ## Build
//! Requires `maturin`. See the `python/` directory for a `pyproject.toml`
//! and `maturin develop` instructions.
//!
//! ## NOT Responsible For
//! - GIL management beyond pyo3 defaults
//! - Numpy interop (callers can convert scalars as needed)


use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use rust_decimal::prelude::FromStr;
use rust_decimal::Decimal;

use crate::orderbook::{BookDelta, DeltaAction, OrderBook};
use crate::signals::indicators::{ema::Ema, rsi::Rsi, sma::Sma};
use crate::signals::{BarInput, Signal};
use crate::types::{Price, Quantity, Side, Symbol};

/// Convert a Python float to the decimal it prints as (`0.1` becomes exactly `0.1`).
///
/// `Decimal::from_f64_retain`, used before 2.15, kept the binary rounding error, so
/// `PyPrice(0.1)` held `0.1000000000000000055511151231`.
fn py_float_to_decimal(value: f64) -> PyResult<Decimal> {
    if !value.is_finite() {
        return Err(PyValueError::new_err(format!("cannot convert {value} to Decimal")));
    }
    Decimal::from_str(&value.to_string()).map_err(|e| PyValueError::new_err(e.to_string()))
}

/// Python-visible `Price` newtype.
///
/// Wraps a validated, strictly-positive `Decimal`.
///
/// # Example (Python)
/// ```python
/// from _fin_primitives import PyPrice
/// p = PyPrice(100.50)
/// print(p.value)  # "100.50"
/// ```
#[pyclass(name = "PyPrice")]
pub struct PyPrice {
    inner: Price,
}

#[pymethods]
impl PyPrice {
    /// Construct a `PyPrice` from a float or string.
    #[new]
    pub fn new(value: f64) -> PyResult<Self> {
        let d = py_float_to_decimal(value)?;
        let p = Price::new(d).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(Self { inner: p })
    }

    /// The price as a Python float.
    #[getter]
    pub fn value(&self) -> f64 {
        use rust_decimal::prelude::ToPrimitive;
        self.inner.value().to_f64().unwrap_or(f64::NAN)
    }

    /// String representation with full decimal precision.
    fn __repr__(&self) -> String {
        format!("PyPrice({})", self.inner.value())
    }

    fn __str__(&self) -> String {
        self.inner.value().to_string()
    }
}

/// Python-visible `Quantity` newtype.
///
/// Non-negative decimal quantity.
///
/// # Example (Python)
/// ```python
/// from _fin_primitives import PyQuantity
/// q = PyQuantity(100.0)
/// print(q.value)  # 100.0
/// ```
#[pyclass(name = "PyQuantity")]
pub struct PyQuantity {
    inner: Quantity,
}

#[pymethods]
impl PyQuantity {
    /// Create a new `PyQuantity`; raises `ValueError` on invalid input.
    #[new]
    pub fn new(value: f64) -> PyResult<Self> {
        let d = py_float_to_decimal(value)?;
        let q = Quantity::new(d).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(Self { inner: q })
    }

    /// The `value` value.
    #[getter]
    pub fn value(&self) -> f64 {
        use rust_decimal::prelude::ToPrimitive;
        self.inner.value().to_f64().unwrap_or(f64::NAN)
    }

    fn __repr__(&self) -> String {
        format!("PyQuantity({})", self.inner.value())
    }

    fn __str__(&self) -> String {
        self.inner.value().to_string()
    }
}

/// Python-visible OHLCV bar.
///
/// # Example (Python)
/// ```python
/// from _fin_primitives import PyOHLCV
/// bar = PyOHLCV(open=100.0, high=105.0, low=99.0, close=103.0, volume=1000.0)
/// print(bar.close)  # 103.0
/// ```
#[pyclass(name = "PyOHLCV")]
pub struct PyOHLCV {
    /// Bar open.
    pub open: f64,
    /// Bar high.
    pub high: f64,
    /// Bar low.
    pub low: f64,
    /// Bar close.
    pub close: f64,
    /// Bar volume.
    pub volume: f64,
}

#[pymethods]
impl PyOHLCV {
    /// Create a new `PyOHLCV`; raises `ValueError` on invalid input.
    #[new]
    #[pyo3(signature = (open, high, low, close, volume))]
    pub fn new(open: f64, high: f64, low: f64, close: f64, volume: f64) -> PyResult<Self> {
        if high < open || high < close || low > open || low > close || high < low {
            return Err(PyValueError::new_err(
                "OHLCV invariant violated: check that high >= open/close and low <= open/close",
            ));
        }
        if volume < 0.0 {
            return Err(PyValueError::new_err("volume must be non-negative"));
        }
        Ok(Self { open, high, low, close, volume })
    }

    /// The `open` value.
    #[getter]
    pub fn open(&self) -> f64 { self.open }
    /// The `high` value.
    #[getter]
    pub fn high(&self) -> f64 { self.high }
    /// The `low` value.
    #[getter]
    pub fn low(&self) -> f64 { self.low }
    /// The `close` value.
    #[getter]
    pub fn close(&self) -> f64 { self.close }
    /// The `volume` value.
    #[getter]
    pub fn volume(&self) -> f64 { self.volume }

    /// Typical price: (high + low + close) / 3.
    pub fn typical_price(&self) -> f64 {
        (self.high + self.low + self.close) / 3.0
    }

    fn __repr__(&self) -> String {
        format!(
            "PyOHLCV(open={}, high={}, low={}, close={}, volume={})",
            self.open, self.high, self.low, self.close, self.volume
        )
    }
}

/// Python-visible L2 order book.
///
/// # Example (Python)
/// ```python
/// from _fin_primitives import PyOrderBook
/// book = PyOrderBook("AAPL")
/// print(book.mid_price())   # None (empty)
/// ```
#[pyclass(name = "PyOrderBook")]
pub struct PyOrderBook {
    inner: OrderBook,
}

#[pymethods]
impl PyOrderBook {
    /// Create a new empty order book for `symbol`.
    #[new]
    pub fn new(symbol: &str) -> PyResult<Self> {
        let sym = Symbol::new(symbol).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(Self { inner: OrderBook::new(sym) })
    }

    /// Best bid price, or `None` if empty.
    pub fn best_bid(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        self.inner.best_bid().and_then(|level| level.price.value().to_f64())
    }

    /// Best ask price, or `None` if empty.
    pub fn best_ask(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        self.inner.best_ask().and_then(|level| level.price.value().to_f64())
    }

    /// Bid-ask spread (ask - bid), or `None` if either side is empty.
    pub fn bid_ask_spread(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid = self.inner.best_bid()?.price.value();
        let ask = self.inner.best_ask()?.price.value();
        (ask - bid).to_f64()
    }

    /// Mid-price: (bid + ask) / 2, or `None` if either side is empty.
    pub fn mid_price(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid = self.inner.best_bid()?.price.value();
        let ask = self.inner.best_ask()?.price.value();
        ((bid + ask) / Decimal::TWO).to_f64()
    }

    /// Order book imbalance: (bid_qty - ask_qty) / (bid_qty + ask_qty).
    ///
    /// Returns `None` if either side is empty or total quantity is zero.
    pub fn imbalance(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid_qty: Decimal = self.inner.top_bids(usize::MAX).iter().map(|l| l.quantity.value()).sum();
        let ask_qty: Decimal = self.inner.top_asks(usize::MAX).iter().map(|l| l.quantity.value()).sum();
        let total = bid_qty + ask_qty;
        if total.is_zero() {
            return None;
        }
        ((bid_qty - ask_qty) / total).to_f64()
    }

    /// Apply a delta: `(side, price, qty, action_set, sequence)`.
    ///
    /// `side` must be `"bid"` or `"ask"`. `action_set` is `True` for Set, `False` for Remove.
    pub fn apply_delta(
        &mut self,
        side: &str,
        price: f64,
        qty: f64,
        action_set: bool,
        sequence: u64,
    ) -> PyResult<()> {
        let s = match side.to_lowercase().as_str() {
            "bid" => Side::Bid,
            "ask" => Side::Ask,
            other => {
                return Err(PyValueError::new_err(format!("side must be 'bid' or 'ask', got '{other}'")));
            }
        };
        let pd = Decimal::from_str(&price.to_string())
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        let qd = Decimal::from_str(&qty.to_string())
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        let price_t = crate::types::Price::new(pd).map_err(|e| PyValueError::new_err(e.to_string()))?;
        let qty_t = crate::types::Quantity::new(qd).map_err(|e| PyValueError::new_err(e.to_string()))?;
        let delta = BookDelta {
            side: s,
            price: price_t,
            quantity: qty_t,
            action: if action_set { DeltaAction::Set } else { DeltaAction::Remove },
            sequence,
        };
        self.inner.apply_delta(delta).map_err(|e| PyValueError::new_err(e.to_string()))
    }

    /// Current sequence number.
    pub fn sequence(&self) -> u64 {
        self.inner.sequence()
    }

    fn __repr__(&self) -> String {
        format!(
            "PyOrderBook(symbol={}, seq={}, bid={:?}, ask={:?})",
            self.inner.symbol.as_str(),
            self.inner.sequence(),
            self.best_bid(),
            self.best_ask(),
        )
    }
}

/// Python-visible Simple Moving Average.
///
/// # Example (Python)
/// ```python
/// from _fin_primitives import PySMA
/// sma = PySMA("sma_20", 20)
/// result = sma.update(close=105.0)
/// print(result)  # None until 20 bars seen
/// ```
#[pyclass(name = "PySMA")]
pub struct PySMA {
    inner: Sma,
}

#[pymethods]
impl PySMA {
    /// Create a new `PySMA`; raises `ValueError` on invalid input.
    #[new]
    pub fn new(name: &str, period: usize) -> PyResult<Self> {
        let inner = Sma::new(name, period).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(Self { inner })
    }

    /// Feed one bar's close price and return the SMA value, or `None` if not ready.
    pub fn update(&mut self, close: f64) -> PyResult<Option<f64>> {
        use rust_decimal::prelude::ToPrimitive;
        let d = py_float_to_decimal(close)?;
        let bar = BarInput::from_close(d);
        let sv = self.inner.update(&bar).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(sv.as_decimal().and_then(|v| v.to_f64()))
    }

    /// Name of this indicator.
    #[getter]
    pub fn name(&self) -> &str {
        self.inner.name()
    }

    fn __repr__(&self) -> String {
        format!("PySMA(name={})", self.inner.name())
    }
}

/// Python-visible Exponential Moving Average.
///
/// # Example (Python)
/// ```python
/// from _fin_primitives import PyEMA
/// ema = PyEMA("ema_12", 12)
/// result = ema.update(close=100.0)
/// ```
#[pyclass(name = "PyEMA")]
pub struct PyEMA {
    inner: Ema,
}

#[pymethods]
impl PyEMA {
    /// Create a new `PyEMA`; raises `ValueError` on invalid input.
    #[new]
    pub fn new(name: &str, period: usize) -> PyResult<Self> {
        let inner = Ema::new(name, period).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(Self { inner })
    }

    /// Feed one bar's close price and return the EMA value, or `None` if not ready.
    pub fn update(&mut self, close: f64) -> PyResult<Option<f64>> {
        use rust_decimal::prelude::ToPrimitive;
        let d = py_float_to_decimal(close)?;
        let bar = BarInput::from_close(d);
        let sv = self.inner.update(&bar).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(sv.as_decimal().and_then(|v| v.to_f64()))
    }

    /// The `name` value.
    #[getter]
    pub fn name(&self) -> &str {
        self.inner.name()
    }

    fn __repr__(&self) -> String {
        format!("PyEMA(name={})", self.inner.name())
    }
}

/// Python-visible Relative Strength Index.
///
/// # Example (Python)
/// ```python
/// from _fin_primitives import PyRSI
/// rsi = PyRSI("rsi_14", 14)
/// result = rsi.update(close=50.0)
/// ```
#[pyclass(name = "PyRSI")]
pub struct PyRSI {
    inner: Rsi,
}

#[pymethods]
impl PyRSI {
    /// Create a new `PyRSI`; raises `ValueError` on invalid input.
    #[new]
    pub fn new(name: &str, period: usize) -> PyResult<Self> {
        let inner = Rsi::new(name, period).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(Self { inner })
    }

    /// Feed one bar's close price and return the RSI value (0–100), or `None` if not ready.
    pub fn update(&mut self, close: f64) -> PyResult<Option<f64>> {
        use rust_decimal::prelude::ToPrimitive;
        let d = py_float_to_decimal(close)?;
        let bar = BarInput::from_close(d);
        let sv = self.inner.update(&bar).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(sv.as_decimal().and_then(|v| v.to_f64()))
    }

    /// The `name` value.
    #[getter]
    pub fn name(&self) -> &str {
        self.inner.name()
    }

    fn __repr__(&self) -> String {
        format!("PyRSI(name={})", self.inner.name())
    }
}

/// Registers all Python-visible types and creates the `_fin_primitives` module.
#[pymodule]
pub fn _fin_primitives(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyPrice>()?;
    m.add_class::<PyQuantity>()?;
    m.add_class::<PyOHLCV>()?;
    m.add_class::<PyOrderBook>()?;
    m.add_class::<PySMA>()?;
    m.add_class::<PyEMA>()?;
    m.add_class::<PyRSI>()?;
    Ok(())
}