Skip to main content

nautilus_risk/python/
sizing.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Python bindings for position sizing.
17
18use nautilus_core::{
19    correctness::{check_equal, check_positive_i64},
20    python::{
21        correctness_error_to_pyvalue_err, to_pynotimplemented_err, to_pytype_err, to_pyvalue_err,
22    },
23};
24use nautilus_model::{
25    instruments::{Instrument, InstrumentAny},
26    python::instruments::pyobject_to_instrument_any,
27    types::{Money, Price, Quantity},
28};
29use pyo3::{
30    prelude::*,
31    sync::PyOnceLock,
32    types::{PyAny, PyType},
33};
34use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pymethods};
35use rust_decimal::Decimal;
36
37use crate::sizing::calculate_fixed_risk_position_size;
38
39/// Base class for position sizers.
40#[allow(missing_debug_implementations)]
41#[gen_stub_pyclass(module = "nautilus_trader.risk")]
42#[pyclass(module = "nautilus_trader.risk", subclass)]
43pub struct PositionSizer {
44    instrument: Py<PyAny>,
45    instrument_any: InstrumentAny,
46}
47
48#[gen_stub_pymethods]
49#[pymethods]
50impl PositionSizer {
51    #[new]
52    #[gen_stub(override_return_type(type_repr = "typing.Self", imports = ("typing",)))]
53    fn py_new(py: Python<'_>, instrument: Py<PyAny>) -> PyResult<Self> {
54        Self::from_instrument(py, instrument)
55    }
56
57    /// Returns the instrument used for position sizing.
58    #[getter]
59    fn instrument<'py>(&self, py: Python<'py>) -> Bound<'py, PyAny> {
60        self.instrument.bind(py).clone()
61    }
62
63    /// Updates the instrument used for position sizing.
64    ///
65    /// # Errors
66    ///
67    /// Returns an error if `instrument` is invalid or its ID differs from the
68    /// current instrument ID.
69    fn update_instrument(&mut self, py: Python<'_>, instrument: Py<PyAny>) -> PyResult<()> {
70        let updated = Self::from_instrument(py, instrument)?;
71        check_equal(
72            &self.instrument_any.id(),
73            &updated.instrument_any.id(),
74            "instrument.id",
75            "instrument.id",
76        )
77        .map_err(correctness_error_to_pyvalue_err)?;
78        *self = updated;
79        Ok(())
80    }
81
82    /// Calculates the position size quantity for the given risk parameters.
83    ///
84    /// # Errors
85    ///
86    /// Returns an error if called. Subclasses override this method.
87    #[pyo3(signature = (
88        entry,
89        stop_loss,
90        equity,
91        risk,
92        commission_rate = Decimal::ZERO,
93        exchange_rate = Decimal::ONE,
94        hard_limit = None,
95        unit_batch_size = Decimal::ONE,
96        units = 1
97    ))]
98    #[expect(
99        clippy::too_many_arguments,
100        reason = "position sizing API takes fixed-risk inputs used by callers"
101    )]
102    #[allow(unused_variables, clippy::unused_self)]
103    fn calculate(
104        &self,
105        entry: Price,
106        stop_loss: Price,
107        equity: Money,
108        #[pyo3(from_py_with = extract_decimal)] risk: Decimal,
109        #[pyo3(from_py_with = extract_decimal)] commission_rate: Decimal,
110        #[pyo3(from_py_with = extract_decimal)] exchange_rate: Decimal,
111        #[pyo3(from_py_with = extract_optional_decimal)] hard_limit: Option<Decimal>,
112        #[pyo3(from_py_with = extract_decimal)] unit_batch_size: Decimal,
113        units: i64,
114    ) -> PyResult<Quantity> {
115        Err(to_pynotimplemented_err(
116            "PositionSizer subclasses must implement `calculate`",
117        ))
118    }
119}
120
121/// Fixed-risk position sizer.
122#[allow(missing_debug_implementations)]
123#[gen_stub_pyclass(module = "nautilus_trader.risk")]
124#[pyclass(module = "nautilus_trader.risk", extends = PositionSizer)]
125pub struct FixedRiskSizer;
126
127#[gen_stub_pymethods]
128#[pymethods]
129#[expect(
130    clippy::use_self,
131    reason = "`Self` breaks pyo3-stub-gen derive for subclass pyclasses"
132)]
133impl FixedRiskSizer {
134    #[new]
135    #[gen_stub(override_return_type(type_repr = "typing.Self", imports = ("typing",)))]
136    fn py_new(
137        py: Python<'_>,
138        instrument: Py<PyAny>,
139    ) -> PyResult<PyClassInitializer<FixedRiskSizer>> {
140        Ok(
141            PyClassInitializer::from(PositionSizer::from_instrument(py, instrument)?)
142                .add_subclass(FixedRiskSizer),
143        )
144    }
145
146    /// Calculates the position size quantity for the given risk parameters.
147    ///
148    /// Returns zero when no position is riskable, including for a zero exchange rate
149    /// or equal valid entry and stop-loss prices.
150    /// Rounds the final quantity down within the risk budget and quantity limits.
151    /// Inverse futures, perpetuals, and futures spreads use reciprocal-price PnL;
152    /// inverse options and option spreads retain premium-based sizing.
153    ///
154    /// # Parameters
155    ///
156    /// - `entry`: The entry price. Must be positive for reciprocal-price sizing.
157    /// - `stop_loss`: The stop-loss price. Must be positive for reciprocal-price sizing.
158    /// - `equity`: The account equity.
159    /// - `risk`: The positive risk fraction.
160    /// - `commission_rate`: The non-negative commission rate.
161    /// - `exchange_rate`: The non-negative rate from instrument quote currency to equity currency.
162    ///   Reciprocal-price sizing uses PnL directly when equity uses the instrument's base currency;
163    ///   otherwise it values PnL in quote currency at the stop-loss price before conversion.
164    /// - `hard_limit`: The optional positive limit for the total quantity.
165    /// - `unit_batch_size`: The non-negative unit batch size.
166    /// - `units`: The positive number of units to divide the position into.
167    ///
168    /// # Errors
169    ///
170    /// Returns an error if:
171    /// - A decimal argument is not a `decimal.Decimal`.
172    /// - A parameter violates the constraints above.
173    /// - Decimal arithmetic overflows.
174    /// - The final size rounds to zero or cannot be represented as a `Quantity`.
175    #[pyo3(signature = (
176        entry,
177        stop_loss,
178        equity,
179        risk,
180        commission_rate = Decimal::ZERO,
181        exchange_rate = Decimal::ONE,
182        hard_limit = None,
183        unit_batch_size = Decimal::ONE,
184        units = 1
185    ))]
186    #[expect(
187        clippy::too_many_arguments,
188        reason = "position sizing API takes fixed-risk inputs used by callers"
189    )]
190    fn calculate(
191        slf: PyRef<'_, Self>,
192        entry: Price,
193        stop_loss: Price,
194        equity: Money,
195        #[pyo3(from_py_with = extract_decimal)] risk: Decimal,
196        #[pyo3(from_py_with = extract_decimal)] commission_rate: Decimal,
197        #[pyo3(from_py_with = extract_decimal)] exchange_rate: Decimal,
198        #[pyo3(from_py_with = extract_optional_decimal)] hard_limit: Option<Decimal>,
199        #[pyo3(from_py_with = extract_decimal)] unit_batch_size: Decimal,
200        units: i64,
201    ) -> PyResult<Quantity> {
202        check_positive_i64(units, "units").map_err(correctness_error_to_pyvalue_err)?;
203        let units = usize::try_from(units).map_err(to_pyvalue_err)?;
204
205        let base = slf.into_super();
206        calculate_fixed_risk_position_size(
207            &base.instrument_any,
208            entry,
209            stop_loss,
210            equity,
211            risk,
212            commission_rate,
213            exchange_rate,
214            hard_limit,
215            unit_batch_size,
216            units,
217        )
218        .map_err(correctness_error_to_pyvalue_err)
219    }
220}
221
222impl PositionSizer {
223    fn from_instrument(py: Python<'_>, instrument: Py<PyAny>) -> PyResult<Self> {
224        let instrument_any =
225            pyobject_to_instrument_any(py, instrument.clone_ref(py)).map_err(|_| {
226                let type_name = instrument
227                    .bind(py)
228                    .get_type()
229                    .name()
230                    .map_or_else(|_| "unknown".to_string(), |name| name.to_string());
231                to_pytype_err(format!(
232                    "`instrument` must be an `Instrument`, was `{type_name}`"
233                ))
234            })?;
235        Ok(Self {
236            instrument,
237            instrument_any,
238        })
239    }
240}
241
242static DECIMAL_TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
243
244fn extract_decimal(value: &Bound<'_, PyAny>) -> PyResult<Decimal> {
245    let decimal_type = DECIMAL_TYPE.import(value.py(), "decimal", "Decimal")?;
246    if !value.is_instance(decimal_type)? {
247        return Err(to_pytype_err(format!(
248            "expected decimal.Decimal, was {}",
249            value.get_type().name()?
250        )));
251    }
252    value.extract()
253}
254
255fn extract_optional_decimal(value: &Bound<'_, PyAny>) -> PyResult<Option<Decimal>> {
256    if value.is_none() {
257        Ok(None)
258    } else {
259        extract_decimal(value).map(Some)
260    }
261}