nautilus_model/data/
trade.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//! A `TradeTick` data type representing a single trade in a market.
17
18use std::{collections::HashMap, fmt::Display, hash::Hash};
19
20use derive_builder::Builder;
21use indexmap::IndexMap;
22use nautilus_core::{UnixNanos, correctness::FAILED, serialization::Serializable};
23use serde::{Deserialize, Serialize};
24
25use super::GetTsInit;
26use crate::{
27    enums::AggressorSide,
28    identifiers::{InstrumentId, TradeId},
29    types::{Price, Quantity, fixed::FIXED_SIZE_BINARY, quantity::check_positive_quantity},
30};
31
32/// Represents a trade tick in a market.
33#[repr(C)]
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Builder)]
35#[serde(tag = "type")]
36#[cfg_attr(
37    feature = "python",
38    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.model")
39)]
40pub struct TradeTick {
41    /// The trade instrument ID.
42    pub instrument_id: InstrumentId,
43    /// The traded price.
44    pub price: Price,
45    /// The traded size.
46    pub size: Quantity,
47    /// The trade aggressor side.
48    pub aggressor_side: AggressorSide,
49    /// The trade match ID (assigned by the venue).
50    pub trade_id: TradeId,
51    /// UNIX timestamp (nanoseconds) when the trade event occurred.
52    pub ts_event: UnixNanos,
53    /// UNIX timestamp (nanoseconds) when the struct was initialized.
54    pub ts_init: UnixNanos,
55}
56
57impl TradeTick {
58    /// Creates a new [`TradeTick`] instance with correctness checking.
59    ///
60    /// # Errors
61    ///
62    /// Returns an error if `size` is not positive (> 0).
63    ///
64    /// # Notes
65    ///
66    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
67    pub fn new_checked(
68        instrument_id: InstrumentId,
69        price: Price,
70        size: Quantity,
71        aggressor_side: AggressorSide,
72        trade_id: TradeId,
73        ts_event: UnixNanos,
74        ts_init: UnixNanos,
75    ) -> anyhow::Result<Self> {
76        check_positive_quantity(size, stringify!(size))?;
77
78        Ok(Self {
79            instrument_id,
80            price,
81            size,
82            aggressor_side,
83            trade_id,
84            ts_event,
85            ts_init,
86        })
87    }
88
89    /// Creates a new [`TradeTick`] instance.
90    ///
91    /// # Panics
92    ///
93    /// Panics if `size` is not positive (> 0).
94    #[must_use]
95    pub fn new(
96        instrument_id: InstrumentId,
97        price: Price,
98        size: Quantity,
99        aggressor_side: AggressorSide,
100        trade_id: TradeId,
101        ts_event: UnixNanos,
102        ts_init: UnixNanos,
103    ) -> Self {
104        Self::new_checked(
105            instrument_id,
106            price,
107            size,
108            aggressor_side,
109            trade_id,
110            ts_event,
111            ts_init,
112        )
113        .expect(FAILED)
114    }
115
116    /// Returns the metadata for the type, for use with serialization formats.
117    #[must_use]
118    pub fn get_metadata(
119        instrument_id: &InstrumentId,
120        price_precision: u8,
121        size_precision: u8,
122    ) -> HashMap<String, String> {
123        let mut metadata = HashMap::new();
124        metadata.insert("instrument_id".to_string(), instrument_id.to_string());
125        metadata.insert("price_precision".to_string(), price_precision.to_string());
126        metadata.insert("size_precision".to_string(), size_precision.to_string());
127        metadata
128    }
129
130    /// Returns the field map for the type, for use with Arrow schemas.
131    #[must_use]
132    pub fn get_fields() -> IndexMap<String, String> {
133        let mut metadata = IndexMap::new();
134        metadata.insert("price".to_string(), FIXED_SIZE_BINARY.to_string());
135        metadata.insert("size".to_string(), FIXED_SIZE_BINARY.to_string());
136        metadata.insert("aggressor_side".to_string(), "UInt8".to_string());
137        metadata.insert("trade_id".to_string(), "Utf8".to_string());
138        metadata.insert("ts_event".to_string(), "UInt64".to_string());
139        metadata.insert("ts_init".to_string(), "UInt64".to_string());
140        metadata
141    }
142}
143
144impl Display for TradeTick {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        write!(
147            f,
148            "{},{},{},{},{},{}",
149            self.instrument_id,
150            self.price,
151            self.size,
152            self.aggressor_side,
153            self.trade_id,
154            self.ts_event,
155        )
156    }
157}
158
159impl Serializable for TradeTick {}
160
161impl GetTsInit for TradeTick {
162    fn ts_init(&self) -> UnixNanos {
163        self.ts_init
164    }
165}
166
167////////////////////////////////////////////////////////////////////////////////
168// Tests
169////////////////////////////////////////////////////////////////////////////////
170#[cfg(test)]
171mod tests {
172    use nautilus_core::{UnixNanos, serialization::Serializable};
173    use pyo3::{IntoPyObjectExt, Python};
174    use rstest::rstest;
175
176    use crate::{
177        data::{TradeTick, stubs::stub_trade_ethusdt_buyer},
178        enums::AggressorSide,
179        identifiers::{InstrumentId, TradeId},
180        types::{Price, Quantity},
181    };
182
183    #[cfg(feature = "high-precision")] // TODO: Add 64-bit precision version of test
184    #[rstest]
185    #[should_panic(expected = "invalid `Quantity` for 'size' not positive, was 0")]
186    fn test_trade_tick_new_with_zero_size_panics() {
187        let instrument_id = InstrumentId::from("ETH-USDT-SWAP.OKX");
188        let price = Price::from("10000.00");
189        let zero_size = Quantity::from(0);
190        let aggressor_side = AggressorSide::Buyer;
191        let trade_id = TradeId::from("123456789");
192        let ts_event = UnixNanos::from(0);
193        let ts_init = UnixNanos::from(1);
194
195        let _ = TradeTick::new(
196            instrument_id,
197            price,
198            zero_size,
199            aggressor_side,
200            trade_id,
201            ts_event,
202            ts_init,
203        );
204    }
205
206    #[rstest]
207    fn test_trade_tick_new_checked_with_zero_size_error() {
208        let instrument_id = InstrumentId::from("ETH-USDT-SWAP.OKX");
209        let price = Price::from("10000.00");
210        let zero_size = Quantity::from(0);
211        let aggressor_side = AggressorSide::Buyer;
212        let trade_id = TradeId::from("123456789");
213        let ts_event = UnixNanos::from(0);
214        let ts_init = UnixNanos::from(1);
215
216        let result = TradeTick::new_checked(
217            instrument_id,
218            price,
219            zero_size,
220            aggressor_side,
221            trade_id,
222            ts_event,
223            ts_init,
224        );
225
226        assert!(result.is_err());
227    }
228
229    #[rstest]
230    fn test_to_string(stub_trade_ethusdt_buyer: TradeTick) {
231        let trade = stub_trade_ethusdt_buyer;
232        assert_eq!(
233            trade.to_string(),
234            "ETHUSDT-PERP.BINANCE,10000.0000,1.00000000,BUYER,123456789,0"
235        );
236    }
237
238    #[rstest]
239    fn test_deserialize_raw_string() {
240        let raw_string = r#"{
241            "type": "TradeTick",
242            "instrument_id": "ETHUSDT-PERP.BINANCE",
243            "price": "10000.0000",
244            "size": "1.00000000",
245            "aggressor_side": "BUYER",
246            "trade_id": "123456789",
247            "ts_event": 0,
248            "ts_init": 1
249        }"#;
250
251        let trade: TradeTick = serde_json::from_str(raw_string).unwrap();
252
253        assert_eq!(trade.aggressor_side, AggressorSide::Buyer);
254    }
255
256    #[rstest]
257    fn test_from_pyobject(stub_trade_ethusdt_buyer: TradeTick) {
258        pyo3::prepare_freethreaded_python();
259        let trade = stub_trade_ethusdt_buyer;
260
261        Python::with_gil(|py| {
262            let tick_pyobject = trade.into_py_any(py).unwrap();
263            let parsed_tick = TradeTick::from_pyobject(tick_pyobject.bind(py)).unwrap();
264            assert_eq!(parsed_tick, trade);
265        });
266    }
267
268    #[rstest]
269    fn test_json_serialization(stub_trade_ethusdt_buyer: TradeTick) {
270        let trade = stub_trade_ethusdt_buyer;
271        let serialized = trade.to_json_bytes().unwrap();
272        let deserialized = TradeTick::from_json_bytes(serialized.as_ref()).unwrap();
273        assert_eq!(deserialized, trade);
274    }
275
276    #[rstest]
277    fn test_msgpack_serialization(stub_trade_ethusdt_buyer: TradeTick) {
278        let trade = stub_trade_ethusdt_buyer;
279        let serialized = trade.to_msgpack_bytes().unwrap();
280        let deserialized = TradeTick::from_msgpack_bytes(serialized.as_ref()).unwrap();
281        assert_eq!(deserialized, trade);
282    }
283}