nautilus-model 0.55.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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Domain types representing *price* data (index-price, mark-price, etc.).

use std::{collections::HashMap, fmt::Display};

use indexmap::IndexMap;
use nautilus_core::{UnixNanos, serialization::Serializable};
use serde::{Deserialize, Serialize};

use super::HasTsInit;
use crate::{
    identifiers::InstrumentId,
    types::{Price, fixed::FIXED_SIZE_BINARY},
};

/// Represents a mark price update.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type")]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
pub struct MarkPriceUpdate {
    /// The instrument ID for the mark price.
    pub instrument_id: InstrumentId,
    /// The mark price.
    pub value: Price,
    /// UNIX timestamp (nanoseconds) when the price event occurred.
    pub ts_event: UnixNanos,
    /// UNIX timestamp (nanoseconds) when the instance was created.
    pub ts_init: UnixNanos,
}

impl MarkPriceUpdate {
    /// Creates a new [`MarkPriceUpdate`] instance.
    #[must_use]
    pub fn new(
        instrument_id: InstrumentId,
        value: Price,
        ts_event: UnixNanos,
        ts_init: UnixNanos,
    ) -> Self {
        Self {
            instrument_id,
            value,
            ts_event,
            ts_init,
        }
    }

    /// Returns the metadata for the type, for use with serialization formats.
    #[must_use]
    pub fn get_metadata(
        instrument_id: &InstrumentId,
        price_precision: u8,
    ) -> HashMap<String, String> {
        let mut metadata = HashMap::new();
        metadata.insert("instrument_id".to_string(), instrument_id.to_string());
        metadata.insert("price_precision".to_string(), price_precision.to_string());
        metadata
    }

    /// Returns the field map for the type, for use with Arrow schemas.
    #[must_use]
    pub fn get_fields() -> IndexMap<String, String> {
        let mut metadata = IndexMap::new();
        metadata.insert("value".to_string(), FIXED_SIZE_BINARY.to_string());
        metadata.insert("ts_event".to_string(), "UInt64".to_string());
        metadata.insert("ts_init".to_string(), "UInt64".to_string());
        metadata
    }
}

impl Display for MarkPriceUpdate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{},{},{},{}",
            self.instrument_id, self.value, self.ts_event, self.ts_init
        )
    }
}

impl Serializable for MarkPriceUpdate {}

impl HasTsInit for MarkPriceUpdate {
    fn ts_init(&self) -> UnixNanos {
        self.ts_init
    }
}

/// Represents an index price update.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type")]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
pub struct IndexPriceUpdate {
    /// The instrument ID for the index price.
    pub instrument_id: InstrumentId,
    /// The index price.
    pub value: Price,
    /// UNIX timestamp (nanoseconds) when the price event occurred.
    pub ts_event: UnixNanos,
    /// UNIX timestamp (nanoseconds) when the instance was created.
    pub ts_init: UnixNanos,
}

impl IndexPriceUpdate {
    /// Creates a new [`IndexPriceUpdate`] instance.
    #[must_use]
    pub fn new(
        instrument_id: InstrumentId,
        value: Price,
        ts_event: UnixNanos,
        ts_init: UnixNanos,
    ) -> Self {
        Self {
            instrument_id,
            value,
            ts_event,
            ts_init,
        }
    }

    /// Returns the metadata for the type, for use with serialization formats.
    #[must_use]
    pub fn get_metadata(
        instrument_id: &InstrumentId,
        price_precision: u8,
    ) -> HashMap<String, String> {
        let mut metadata = HashMap::new();
        metadata.insert("instrument_id".to_string(), instrument_id.to_string());
        metadata.insert("price_precision".to_string(), price_precision.to_string());
        metadata
    }

    /// Returns the field map for the type, for use with Arrow schemas.
    #[must_use]
    pub fn get_fields() -> IndexMap<String, String> {
        let mut metadata = IndexMap::new();
        metadata.insert("value".to_string(), FIXED_SIZE_BINARY.to_string());
        metadata.insert("ts_event".to_string(), "UInt64".to_string());
        metadata.insert("ts_init".to_string(), "UInt64".to_string());
        metadata
    }
}

impl Display for IndexPriceUpdate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{},{},{},{}",
            self.instrument_id, self.value, self.ts_event, self.ts_init
        )
    }
}

impl Serializable for IndexPriceUpdate {}

impl HasTsInit for IndexPriceUpdate {
    fn ts_init(&self) -> UnixNanos {
        self.ts_init
    }
}

#[cfg(test)]
mod tests {
    use std::{
        collections::hash_map::DefaultHasher,
        hash::{Hash, Hasher},
    };

    use nautilus_core::serialization::{
        Serializable,
        msgpack::{FromMsgPack, ToMsgPack},
    };
    use rstest::{fixture, rstest};
    use serde_json;

    use super::*;

    #[fixture]
    fn instrument_id() -> InstrumentId {
        InstrumentId::from("BTC-USDT.OKX")
    }

    #[fixture]
    fn price() -> Price {
        Price::from("150_500.10")
    }

    #[rstest]
    fn test_mark_price_update_new(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        assert_eq!(mark_price.instrument_id, instrument_id);
        assert_eq!(mark_price.value, price);
        assert_eq!(mark_price.ts_event, ts_event);
        assert_eq!(mark_price.ts_init, ts_init);
    }

    #[rstest]
    fn test_mark_price_update_display(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        assert_eq!(format!("{mark_price}"), "BTC-USDT.OKX,150500.10,1,2");
    }

    #[rstest]
    fn test_mark_price_update_get_ts_init(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        assert_eq!(mark_price.ts_init(), ts_init);
    }

    #[rstest]
    fn test_mark_price_update_eq_hash(instrument_id: InstrumentId, price: Price) {
        use std::{
            collections::hash_map::DefaultHasher,
            hash::{Hash, Hasher},
        };

        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price1 = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);
        let mark_price2 = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);
        let mark_price3 =
            MarkPriceUpdate::new(instrument_id, Price::from("143_500.50"), ts_event, ts_init);

        assert_eq!(mark_price1, mark_price2);
        assert_ne!(mark_price1, mark_price3);

        // Test Hash implementation
        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        mark_price1.hash(&mut hasher1);
        mark_price2.hash(&mut hasher2);
        assert_eq!(hasher1.finish(), hasher2.finish());
    }

    #[rstest]
    fn test_mark_price_update_json_serialization(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        let serialized = mark_price.to_json_bytes().unwrap();
        let deserialized = MarkPriceUpdate::from_json_bytes(&serialized).unwrap();

        assert_eq!(mark_price, deserialized);
    }

    #[rstest]
    fn test_mark_price_update_msgpack_serialization(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        let serialized = mark_price.to_msgpack_bytes().unwrap();
        let deserialized = MarkPriceUpdate::from_msgpack_bytes(&serialized).unwrap();

        assert_eq!(mark_price, deserialized);
    }

    #[rstest]
    fn test_mark_price_update_clone(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);
        let cloned = mark_price;

        assert_eq!(mark_price, cloned);
    }

    #[rstest]
    fn test_mark_price_update_serde_json(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let mark_price = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        let json_str = serde_json::to_string(&mark_price).unwrap();
        let deserialized: MarkPriceUpdate = serde_json::from_str(&json_str).unwrap();

        assert_eq!(mark_price, deserialized);
    }

    #[rstest]
    fn test_index_price_update_new(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let index_price = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        assert_eq!(index_price.instrument_id, instrument_id);
        assert_eq!(index_price.value, price);
        assert_eq!(index_price.ts_event, ts_event);
        assert_eq!(index_price.ts_init, ts_init);
    }

    #[rstest]
    fn test_index_price_update_display(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let index_price = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        assert_eq!(format!("{index_price}"), "BTC-USDT.OKX,150500.10,1,2");
    }

    #[rstest]
    fn test_index_price_update_get_ts_init(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let index_price = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        assert_eq!(index_price.ts_init(), ts_init);
    }

    #[rstest]
    fn test_index_price_update_eq_hash(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let index_price1 = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);
        let index_price2 = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);
        let index_price3 = IndexPriceUpdate::new(instrument_id, price, UnixNanos::from(3), ts_init);

        assert_eq!(index_price1, index_price2);
        assert_ne!(index_price1, index_price3);

        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        index_price1.hash(&mut hasher1);
        index_price2.hash(&mut hasher2);
        assert_eq!(hasher1.finish(), hasher2.finish());
    }

    #[rstest]
    fn test_index_price_update_json_serialization(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let index_price = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        let serialized = index_price.to_json_bytes().unwrap();
        let deserialized = IndexPriceUpdate::from_json_bytes(&serialized).unwrap();

        assert_eq!(index_price, deserialized);
    }

    #[rstest]
    fn test_index_price_update_msgpack_serialization(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let index_price = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        let serialized = index_price.to_msgpack_bytes().unwrap();
        let deserialized = IndexPriceUpdate::from_msgpack_bytes(&serialized).unwrap();

        assert_eq!(index_price, deserialized);
    }

    #[rstest]
    fn test_index_price_update_serde_json(instrument_id: InstrumentId, price: Price) {
        let ts_event = UnixNanos::from(1);
        let ts_init = UnixNanos::from(2);

        let index_price = IndexPriceUpdate::new(instrument_id, price, ts_event, ts_init);

        let json_str = serde_json::to_string(&index_price).unwrap();
        let deserialized: IndexPriceUpdate = serde_json::from_str(&json_str).unwrap();

        assert_eq!(index_price, deserialized);
    }
}