nautilus_model/data/
close.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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//! An `InstrumentClose` data type representing an instrument close at a venue.
17
18use std::{collections::HashMap, fmt::Display, hash::Hash};
19
20use indexmap::IndexMap;
21use nautilus_core::{UnixNanos, serialization::Serializable};
22use serde::{Deserialize, Serialize};
23
24use super::HasTsInit;
25use crate::{
26    enums::InstrumentCloseType,
27    identifiers::InstrumentId,
28    types::{Price, fixed::FIXED_SIZE_BINARY},
29};
30
31/// Represents an instrument close at a venue.
32#[repr(C)]
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(tag = "type")]
35#[cfg_attr(
36    feature = "python",
37    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
38)]
39pub struct InstrumentClose {
40    /// The instrument ID.
41    pub instrument_id: InstrumentId,
42    /// The closing price for the instrument.
43    pub close_price: Price,
44    /// The type of closing price.
45    pub close_type: InstrumentCloseType,
46    /// UNIX timestamp (nanoseconds) when the close price event occurred.
47    pub ts_event: UnixNanos,
48    /// UNIX timestamp (nanoseconds) when the instance was created.
49    pub ts_init: UnixNanos,
50}
51
52impl InstrumentClose {
53    /// Creates a new [`InstrumentClose`] instance.
54    pub fn new(
55        instrument_id: InstrumentId,
56        close_price: Price,
57        close_type: InstrumentCloseType,
58        ts_event: UnixNanos,
59        ts_init: UnixNanos,
60    ) -> Self {
61        Self {
62            instrument_id,
63            close_price,
64            close_type,
65            ts_event,
66            ts_init,
67        }
68    }
69
70    /// Returns the metadata for the type, for use with serialization formats.
71    #[must_use]
72    pub fn get_metadata(
73        instrument_id: &InstrumentId,
74        price_precision: u8,
75    ) -> HashMap<String, String> {
76        let mut metadata = HashMap::new();
77        metadata.insert("instrument_id".to_string(), instrument_id.to_string());
78        metadata.insert("price_precision".to_string(), price_precision.to_string());
79        metadata
80    }
81
82    /// Returns the field map for the type, for use with Arrow schemas.
83    #[must_use]
84    pub fn get_fields() -> IndexMap<String, String> {
85        let mut metadata = IndexMap::new();
86        metadata.insert("close_price".to_string(), FIXED_SIZE_BINARY.to_string());
87        metadata.insert("close_type".to_string(), "UInt8".to_string());
88        metadata.insert("ts_event".to_string(), "UInt64".to_string());
89        metadata.insert("ts_init".to_string(), "UInt64".to_string());
90        metadata
91    }
92}
93
94impl Display for InstrumentClose {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        write!(
97            f,
98            "{},{},{},{}",
99            self.instrument_id, self.close_price, self.close_type, self.ts_event
100        )
101    }
102}
103
104impl Serializable for InstrumentClose {}
105
106impl HasTsInit for InstrumentClose {
107    fn ts_init(&self) -> UnixNanos {
108        self.ts_init
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use nautilus_core::serialization::msgpack::{FromMsgPack, ToMsgPack};
115    use rstest::rstest;
116
117    use super::*;
118    use crate::{identifiers::InstrumentId, types::Price};
119
120    #[rstest]
121    fn test_new() {
122        let instrument_id = InstrumentId::from("AAPL.XNAS");
123        let close_price = Price::from("150.20");
124        let close_type = InstrumentCloseType::EndOfSession;
125        let ts_event = UnixNanos::from(1);
126        let ts_init = UnixNanos::from(2);
127
128        let instrument_close =
129            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
130
131        assert_eq!(instrument_close.instrument_id, instrument_id);
132        assert_eq!(instrument_close.close_price, close_price);
133        assert_eq!(instrument_close.close_type, close_type);
134        assert_eq!(instrument_close.ts_event, ts_event);
135        assert_eq!(instrument_close.ts_init, ts_init);
136    }
137
138    #[rstest]
139    fn test_to_string() {
140        let instrument_id = InstrumentId::from("AAPL.XNAS");
141        let close_price = Price::from("150.20");
142        let close_type = InstrumentCloseType::EndOfSession;
143        let ts_event = UnixNanos::from(1);
144        let ts_init = UnixNanos::from(2);
145
146        let instrument_close =
147            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
148
149        assert_eq!(
150            format!("{instrument_close}"),
151            "AAPL.XNAS,150.20,END_OF_SESSION,1"
152        );
153    }
154
155    #[rstest]
156    fn test_json_serialization() {
157        let instrument_id = InstrumentId::from("AAPL.XNAS");
158        let close_price = Price::from("150.20");
159        let close_type = InstrumentCloseType::EndOfSession;
160        let ts_event = UnixNanos::from(1);
161        let ts_init = UnixNanos::from(2);
162
163        let instrument_close =
164            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
165
166        let serialized = instrument_close.to_json_bytes().unwrap();
167        let deserialized = InstrumentClose::from_json_bytes(serialized.as_ref()).unwrap();
168
169        assert_eq!(deserialized, instrument_close);
170    }
171
172    #[rstest]
173    fn test_msgpack_serialization() {
174        let instrument_id = InstrumentId::from("AAPL.XNAS");
175        let close_price = Price::from("150.20");
176        let close_type = InstrumentCloseType::EndOfSession;
177        let ts_event = UnixNanos::from(1);
178        let ts_init = UnixNanos::from(2);
179
180        let instrument_close =
181            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
182
183        let serialized = instrument_close.to_msgpack_bytes().unwrap();
184        let deserialized = InstrumentClose::from_msgpack_bytes(serialized.as_ref()).unwrap();
185
186        assert_eq!(deserialized, instrument_close);
187    }
188}