nautilus_model/data/
close.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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 = "posei_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////////////////////////////////////////////////////////////////////////////////
113// Tests
114////////////////////////////////////////////////////////////////////////////////
115#[cfg(test)]
116mod tests {
117    use rstest::rstest;
118
119    use super::*;
120    use crate::{identifiers::InstrumentId, types::Price};
121
122    #[rstest]
123    fn test_new() {
124        let instrument_id = InstrumentId::from("AAPL.XNAS");
125        let close_price = Price::from("150.20");
126        let close_type = InstrumentCloseType::EndOfSession;
127        let ts_event = UnixNanos::from(1);
128        let ts_init = UnixNanos::from(2);
129
130        let instrument_close =
131            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
132
133        assert_eq!(instrument_close.instrument_id, instrument_id);
134        assert_eq!(instrument_close.close_price, close_price);
135        assert_eq!(instrument_close.close_type, close_type);
136        assert_eq!(instrument_close.ts_event, ts_event);
137        assert_eq!(instrument_close.ts_init, ts_init);
138    }
139
140    #[rstest]
141    fn test_to_string() {
142        let instrument_id = InstrumentId::from("AAPL.XNAS");
143        let close_price = Price::from("150.20");
144        let close_type = InstrumentCloseType::EndOfSession;
145        let ts_event = UnixNanos::from(1);
146        let ts_init = UnixNanos::from(2);
147
148        let instrument_close =
149            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
150
151        assert_eq!(
152            format!("{instrument_close}"),
153            "AAPL.XNAS,150.20,END_OF_SESSION,1"
154        );
155    }
156
157    #[rstest]
158    fn test_json_serialization() {
159        let instrument_id = InstrumentId::from("AAPL.XNAS");
160        let close_price = Price::from("150.20");
161        let close_type = InstrumentCloseType::EndOfSession;
162        let ts_event = UnixNanos::from(1);
163        let ts_init = UnixNanos::from(2);
164
165        let instrument_close =
166            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
167
168        let serialized = instrument_close.to_json_bytes().unwrap();
169        let deserialized = InstrumentClose::from_json_bytes(serialized.as_ref()).unwrap();
170
171        assert_eq!(deserialized, instrument_close);
172    }
173
174    #[rstest]
175    fn test_msgpack_serialization() {
176        let instrument_id = InstrumentId::from("AAPL.XNAS");
177        let close_price = Price::from("150.20");
178        let close_type = InstrumentCloseType::EndOfSession;
179        let ts_event = UnixNanos::from(1);
180        let ts_init = UnixNanos::from(2);
181
182        let instrument_close =
183            InstrumentClose::new(instrument_id, close_price, close_type, ts_event, ts_init);
184
185        let serialized = instrument_close.to_msgpack_bytes().unwrap();
186        let deserialized = InstrumentClose::from_msgpack_bytes(serialized.as_ref()).unwrap();
187
188        assert_eq!(deserialized, instrument_close);
189    }
190}