Skip to main content

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