nautilus-model 0.62.0

Domain model for the Nautilus trading engine
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
446
447
448
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Pluggable margin calculation models for [`MarginAccount`](super::MarginAccount).

use rust_decimal::Decimal;

use crate::{
    instruments::Instrument,
    types::{Money, Price, Quantity},
};

/// Determines how margin requirements are calculated for leveraged positions.
pub trait MarginModel {
    /// Calculates the initial (order) margin requirement.
    ///
    /// # Errors
    ///
    /// Returns an error if margin cannot be computed (e.g. invalid instrument).
    fn calculate_initial_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money>;

    /// Calculates the maintenance (position) margin requirement.
    ///
    /// # Errors
    ///
    /// Returns an error if margin cannot be computed (e.g. invalid instrument).
    fn calculate_maintenance_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money>;
}

/// Enum dispatch for [`MarginModel`] implementations.
#[derive(Debug, Clone)]
pub enum MarginModelAny {
    Standard(StandardMarginModel),
    Leveraged(LeveragedMarginModel),
}

impl MarginModel for MarginModelAny {
    fn calculate_initial_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money> {
        match self {
            Self::Standard(m) => m.calculate_initial_margin(
                instrument,
                quantity,
                price,
                leverage,
                use_quote_for_inverse,
            ),
            Self::Leveraged(m) => m.calculate_initial_margin(
                instrument,
                quantity,
                price,
                leverage,
                use_quote_for_inverse,
            ),
        }
    }

    fn calculate_maintenance_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money> {
        match self {
            Self::Standard(m) => m.calculate_maintenance_margin(
                instrument,
                quantity,
                price,
                leverage,
                use_quote_for_inverse,
            ),
            Self::Leveraged(m) => m.calculate_maintenance_margin(
                instrument,
                quantity,
                price,
                leverage,
                use_quote_for_inverse,
            ),
        }
    }
}

impl Default for MarginModelAny {
    fn default() -> Self {
        Self::Leveraged(LeveragedMarginModel)
    }
}

/// Resolves the margin currency based on instrument properties.
fn margin_currency(
    instrument: &dyn Instrument,
    use_quote_for_inverse: bool,
) -> anyhow::Result<crate::types::Currency> {
    if instrument.is_inverse() && !use_quote_for_inverse {
        instrument.base_currency().ok_or_else(|| {
            anyhow::anyhow!(
                "Inverse instrument {} has no base currency",
                instrument.id()
            )
        })
    } else {
        Ok(instrument.quote_currency())
    }
}

/// Uses fixed margin percentages without leverage division.
///
/// Margin is calculated as `notional_value * margin_rate`, ignoring the
/// account leverage. Appropriate for traditional brokers where margin
/// requirements are fixed percentages of notional value.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
pub struct StandardMarginModel;

impl MarginModel for StandardMarginModel {
    fn calculate_initial_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        _leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money> {
        let use_quote = use_quote_for_inverse.unwrap_or(false);
        let notional = instrument.try_calculate_notional_value(quantity, price, Some(use_quote))?;
        // Spreads and options may quote negative, which carries the sign into the notional.
        // A requirement is a reserve against exposure magnitude, so take it on `abs`.
        let margin = notional
            .as_decimal()
            .abs()
            .checked_mul(instrument.margin_init())
            .ok_or_else(|| anyhow::anyhow!("initial margin calculation overflow"))?;
        let currency = margin_currency(instrument, use_quote)?;
        Money::from_decimal(margin, currency).map_err(Into::into)
    }

    fn calculate_maintenance_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        _leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money> {
        let use_quote = use_quote_for_inverse.unwrap_or(false);
        let notional = instrument.try_calculate_notional_value(quantity, price, Some(use_quote))?;
        let margin = notional
            .as_decimal()
            .abs()
            .checked_mul(instrument.margin_maint())
            .ok_or_else(|| anyhow::anyhow!("maintenance margin calculation overflow"))?;
        let currency = margin_currency(instrument, use_quote)?;
        Money::from_decimal(margin, currency).map_err(Into::into)
    }
}

/// Divides notional value by leverage before applying margin rates.
///
/// Margin is calculated as `(notional_value / leverage) * margin_rate`.
/// This is the default model, appropriate for crypto exchanges and venues
/// where leverage directly reduces margin requirements.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
pub struct LeveragedMarginModel;

impl MarginModel for LeveragedMarginModel {
    fn calculate_initial_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money> {
        if leverage <= Decimal::ZERO {
            anyhow::bail!("Invalid leverage {leverage} for {}", instrument.id());
        }
        let use_quote = use_quote_for_inverse.unwrap_or(false);
        let notional = instrument.try_calculate_notional_value(quantity, price, Some(use_quote))?;
        let margin = notional
            .as_decimal()
            .abs()
            .checked_div(leverage)
            .and_then(|adjusted| adjusted.checked_mul(instrument.margin_init()))
            .ok_or_else(|| anyhow::anyhow!("initial margin calculation overflow"))?;
        let currency = margin_currency(instrument, use_quote)?;
        Money::from_decimal(margin, currency).map_err(Into::into)
    }

    fn calculate_maintenance_margin(
        &self,
        instrument: &dyn Instrument,
        quantity: Quantity,
        price: Price,
        leverage: Decimal,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money> {
        if leverage <= Decimal::ZERO {
            anyhow::bail!("Invalid leverage {leverage} for {}", instrument.id());
        }
        let use_quote = use_quote_for_inverse.unwrap_or(false);
        let notional = instrument.try_calculate_notional_value(quantity, price, Some(use_quote))?;
        let margin = notional
            .as_decimal()
            .abs()
            .checked_div(leverage)
            .and_then(|adjusted| adjusted.checked_mul(instrument.margin_maint()))
            .ok_or_else(|| anyhow::anyhow!("maintenance margin calculation overflow"))?;
        let currency = margin_currency(instrument, use_quote)?;
        Money::from_decimal(margin, currency).map_err(Into::into)
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use rust_decimal::Decimal;
    use rust_decimal_macros::dec;
    use ustr::Ustr;

    use super::*;
    use crate::{
        enums::AssetClass,
        identifiers::{InstrumentId, Symbol},
        instruments::{
            CryptoPerpetual, FuturesSpread, Instrument, stubs::crypto_perpetual_ethusdt,
        },
        types::{Currency, Price, Quantity},
    };

    fn ethusdt() -> CryptoPerpetual {
        crypto_perpetual_ethusdt()
    }

    #[rstest]
    fn test_leveraged_initial_margin() {
        let model = LeveragedMarginModel;
        let instrument = ethusdt();
        let quantity = Quantity::from("10.000");
        let price = Price::from("5000.00");
        let leverage = dec!(10);

        let margin = model
            .calculate_initial_margin(&instrument, quantity, price, leverage, None)
            .unwrap();

        // notional = 10 * 5000 = 50000, adjusted = 50000/10 = 5000
        // margin = 5000 * margin_init
        let expected = Decimal::from(50000) / leverage * instrument.margin_init();
        assert_eq!(margin.as_decimal(), expected);
        assert_eq!(margin.currency, Currency::USDT());
    }

    #[rstest]
    fn test_standard_ignores_leverage() {
        let model = StandardMarginModel;
        let instrument = ethusdt();
        let quantity = Quantity::from("10.000");
        let price = Price::from("5000.00");

        let margin_low = model
            .calculate_initial_margin(&instrument, quantity, price, dec!(2), None)
            .unwrap();
        let margin_high = model
            .calculate_initial_margin(&instrument, quantity, price, dec!(100), None)
            .unwrap();

        // StandardMarginModel ignores leverage so both should be equal
        assert_eq!(margin_low, margin_high);
    }

    /// A spread carrying non-zero margin rates, so the assertions below cannot pass on a
    /// zero requirement. `FuturesSpread` is one of the three classes permitting a negative
    /// price (see `InstrumentClass::allows_negative_price`).
    fn negative_price_spread() -> FuturesSpread {
        FuturesSpread::builder()
            .instrument_id(InstrumentId::from("ESM4-ESU4.GLBX"))
            .raw_symbol(Symbol::from("ESM4-ESU4"))
            .asset_class(AssetClass::Index)
            .underlying(Ustr::from("ES"))
            .strategy_type(Ustr::from("EQ"))
            .activation_ns(1_000.into())
            .expiration_ns(2_000.into())
            .currency(Currency::USD())
            .price_precision(2)
            .price_increment(Price::from("0.01"))
            .multiplier(Quantity::from(50))
            .lot_size(Quantity::from(1))
            .margin_init(dec!(0.01))
            .margin_maint(dec!(0.02))
            .ts_event(1.into())
            .ts_init(2.into())
            .build()
            .unwrap()
    }

    #[rstest]
    fn test_standard_margin_is_positive_for_a_negative_price() {
        let model = StandardMarginModel;
        let instrument = negative_price_spread();
        let quantity = Quantity::from(2);
        let positive = Price::from("2.00");
        let negative = Price::from("-2.00");

        let initial = model
            .calculate_initial_margin(&instrument, quantity, negative, dec!(1), None)
            .unwrap();
        let maintenance = model
            .calculate_maintenance_margin(&instrument, quantity, negative, dec!(1), None)
            .unwrap();

        // notional magnitude = 2 * 50 * 2.00 = 200
        assert_eq!(initial.as_decimal(), dec!(2));
        assert_eq!(maintenance.as_decimal(), dec!(4));
        // A negative quote reserves the same as the equivalent positive one.
        assert_eq!(
            initial,
            model
                .calculate_initial_margin(&instrument, quantity, positive, dec!(1), None)
                .unwrap()
        );
    }

    #[rstest]
    fn test_leveraged_margin_is_positive_for_a_negative_price() {
        let model = LeveragedMarginModel;
        let instrument = negative_price_spread();
        let quantity = Quantity::from(2);
        let negative = Price::from("-2.00");
        let leverage = dec!(10);

        let initial = model
            .calculate_initial_margin(&instrument, quantity, negative, leverage, None)
            .unwrap();
        let maintenance = model
            .calculate_maintenance_margin(&instrument, quantity, negative, leverage, None)
            .unwrap();

        // notional magnitude = 200, adjusted = 200 / 10 = 20
        assert_eq!(initial.as_decimal(), dec!(0.2));
        assert_eq!(maintenance.as_decimal(), dec!(0.4));
    }

    #[rstest]
    fn test_leveraged_zero_leverage_errors() {
        let model = LeveragedMarginModel;
        let instrument = ethusdt();

        let result = model.calculate_initial_margin(
            &instrument,
            Quantity::from("1.000"),
            Price::from("5000.00"),
            Decimal::ZERO,
            None,
        );

        assert!(result.is_err());
    }

    #[rstest]
    fn test_leveraged_margin_decimal_overflow_returns_error() {
        let model = LeveragedMarginModel;
        let instrument = ethusdt();

        let result = model.calculate_initial_margin(
            &instrument,
            Quantity::from("1.000"),
            Price::from("5000.00"),
            Decimal::new(1, 28),
            None,
        );

        assert_eq!(
            result.unwrap_err().to_string(),
            "initial margin calculation overflow"
        );
    }

    #[rstest]
    fn test_margin_model_any_default_is_leveraged() {
        let model = MarginModelAny::default();
        assert!(matches!(model, MarginModelAny::Leveraged(_)));
    }

    #[rstest]
    fn test_maintenance_margin() {
        let model = LeveragedMarginModel;
        let instrument = ethusdt();
        let quantity = Quantity::from("10.000");
        let price = Price::from("5000.00");
        let leverage = dec!(10);

        let margin = model
            .calculate_maintenance_margin(&instrument, quantity, price, leverage, None)
            .unwrap();

        let expected = Decimal::from(50000) / leverage * instrument.margin_maint();
        assert_eq!(margin.as_decimal(), expected);
    }
}