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