Skip to main content

nautilus_serialization/arrow/
report.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
16use std::collections::HashMap;
17
18use arrow::{datatypes::Schema, error::ArrowError, record_batch::RecordBatch};
19use nautilus_model::reports::{
20    ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport,
21};
22
23use super::{
24    ArrowSchemaProvider, DecodeTypedFromRecordBatch, EncodeToRecordBatch, EncodingError,
25    KEY_INSTRUMENT_ID,
26    json::{JsonFieldSpec, decode_batch, encode_batch, metadata_for_type, schema_for_type},
27};
28
29const ORDER_STATUS_REPORT_FIELDS: &[JsonFieldSpec] = &[
30    JsonFieldSpec::utf8("account_id", false),
31    JsonFieldSpec::utf8("instrument_id", false),
32    JsonFieldSpec::utf8("client_order_id", true),
33    JsonFieldSpec::utf8("venue_order_id", false),
34    JsonFieldSpec::utf8("order_side", false),
35    JsonFieldSpec::utf8("order_type", false),
36    JsonFieldSpec::utf8("time_in_force", false),
37    JsonFieldSpec::utf8("order_status", false),
38    JsonFieldSpec::utf8("quantity", false),
39    JsonFieldSpec::utf8("filled_qty", false),
40    JsonFieldSpec::utf8("report_id", false),
41    JsonFieldSpec::timestamp("ts_accepted", false),
42    JsonFieldSpec::timestamp("ts_last", false),
43    JsonFieldSpec::timestamp("ts_init", false),
44    JsonFieldSpec::utf8("order_list_id", true),
45    JsonFieldSpec::utf8("venue_position_id", true),
46    JsonFieldSpec::utf8_json("linked_order_ids", true),
47    JsonFieldSpec::utf8("parent_order_id", true),
48    JsonFieldSpec::utf8("contingency_type", false),
49    JsonFieldSpec::timestamp("expire_time", true),
50    JsonFieldSpec::utf8("price", true),
51    JsonFieldSpec::utf8("activation_price", true),
52    JsonFieldSpec::utf8("trigger_price", true),
53    JsonFieldSpec::utf8("trigger_type", true),
54    JsonFieldSpec::utf8("limit_offset", true),
55    JsonFieldSpec::utf8("trailing_offset", true),
56    JsonFieldSpec::utf8("trailing_offset_type", false),
57    JsonFieldSpec::utf8("avg_px", true),
58    JsonFieldSpec::utf8("display_qty", true),
59    JsonFieldSpec::boolean("post_only", false),
60    JsonFieldSpec::boolean("reduce_only", false),
61    JsonFieldSpec::utf8("cancel_reason", true),
62    JsonFieldSpec::timestamp("ts_triggered", true),
63];
64
65const FILL_REPORT_FIELDS: &[JsonFieldSpec] = &[
66    JsonFieldSpec::utf8("account_id", false),
67    JsonFieldSpec::utf8("instrument_id", false),
68    JsonFieldSpec::utf8("venue_order_id", false),
69    JsonFieldSpec::utf8("trade_id", false),
70    JsonFieldSpec::utf8("order_side", false),
71    JsonFieldSpec::utf8("last_qty", false),
72    JsonFieldSpec::utf8("last_px", false),
73    JsonFieldSpec::utf8("commission", false),
74    JsonFieldSpec::utf8("liquidity_side", false),
75    JsonFieldSpec::utf8("report_id", false),
76    JsonFieldSpec::timestamp("ts_event", false),
77    JsonFieldSpec::timestamp("ts_init", false),
78    JsonFieldSpec::utf8("client_order_id", true),
79    JsonFieldSpec::utf8("venue_position_id", true),
80];
81
82const POSITION_STATUS_REPORT_FIELDS: &[JsonFieldSpec] = &[
83    JsonFieldSpec::utf8("account_id", false),
84    JsonFieldSpec::utf8("instrument_id", false),
85    JsonFieldSpec::utf8("position_side", false),
86    JsonFieldSpec::utf8("quantity", false),
87    JsonFieldSpec::utf8("signed_decimal_qty", false),
88    JsonFieldSpec::utf8("report_id", false),
89    JsonFieldSpec::timestamp("ts_last", false),
90    JsonFieldSpec::timestamp("ts_init", false),
91    JsonFieldSpec::utf8("venue_position_id", true),
92    JsonFieldSpec::utf8("avg_px_open", true),
93    JsonFieldSpec::utf8("avg_px_open_reconciliation", true),
94    JsonFieldSpec::u64("avg_px_open_precision", true),
95];
96
97const EXECUTION_MASS_STATUS_FIELDS: &[JsonFieldSpec] = &[
98    JsonFieldSpec::utf8("client_id", false),
99    JsonFieldSpec::utf8("account_id", false),
100    JsonFieldSpec::utf8("venue", false),
101    JsonFieldSpec::utf8("report_id", false),
102    JsonFieldSpec::timestamp("ts_init", false),
103    JsonFieldSpec::utf8_json("order_reports", false),
104    JsonFieldSpec::utf8_json("fill_reports", false),
105    JsonFieldSpec::utf8_json("position_reports", false),
106];
107
108fn instrument_metadata(type_name: &'static str, instrument_id: &str) -> HashMap<String, String> {
109    let mut metadata = metadata_for_type(type_name);
110    metadata.insert(KEY_INSTRUMENT_ID.to_string(), instrument_id.to_string());
111    metadata
112}
113
114macro_rules! impl_report_arrow {
115    ($type:ty, $type_name:expr, $fields:expr) => {
116        impl_report_arrow!($type, $type_name, $fields, |_: &RecordBatch| $fields);
117    };
118    ($type:ty, $type_name:expr, $fields:expr, $decode_fields:expr) => {
119        impl ArrowSchemaProvider for $type {
120            fn get_schema(metadata: Option<HashMap<String, String>>) -> Schema {
121                schema_for_type($type_name, metadata, $fields)
122            }
123        }
124
125        impl EncodeToRecordBatch for $type {
126            fn encode_batch<T>(
127                metadata: &HashMap<String, String>,
128                data: &[T],
129            ) -> Result<RecordBatch, ArrowError>
130            where
131                T: std::borrow::Borrow<Self>,
132            {
133                encode_batch(
134                    $type_name,
135                    metadata,
136                    data.iter().map(std::borrow::Borrow::borrow),
137                    $fields,
138                )
139            }
140
141            fn metadata(&self) -> HashMap<String, String> {
142                instrument_metadata($type_name, &self.instrument_id.to_string())
143            }
144        }
145
146        impl DecodeTypedFromRecordBatch for $type {
147            fn decode_typed_batch(
148                metadata: &HashMap<String, String>,
149                record_batch: RecordBatch,
150            ) -> Result<Vec<Self>, EncodingError> {
151                let fields = ($decode_fields)(&record_batch);
152                decode_batch(metadata, &record_batch, fields, Some($type_name))
153            }
154        }
155    };
156}
157
158impl_report_arrow!(
159    OrderStatusReport,
160    "OrderStatusReport",
161    ORDER_STATUS_REPORT_FIELDS
162);
163impl_report_arrow!(FillReport, "FillReport", FILL_REPORT_FIELDS);
164impl_report_arrow!(
165    PositionStatusReport,
166    "PositionStatusReport",
167    POSITION_STATUS_REPORT_FIELDS,
168    position_status_report_decode_fields
169);
170
171// Files written before the average reconciliation fields lack their two trailing columns
172fn position_status_report_decode_fields(record_batch: &RecordBatch) -> &'static [JsonFieldSpec] {
173    if record_batch
174        .schema()
175        .index_of("avg_px_open_reconciliation")
176        .is_ok()
177    {
178        POSITION_STATUS_REPORT_FIELDS
179    } else {
180        &POSITION_STATUS_REPORT_FIELDS[..POSITION_STATUS_REPORT_FIELDS.len() - 2]
181    }
182}
183
184impl ArrowSchemaProvider for ExecutionMassStatus {
185    fn get_schema(metadata: Option<HashMap<String, String>>) -> Schema {
186        schema_for_type(
187            "ExecutionMassStatus",
188            metadata,
189            EXECUTION_MASS_STATUS_FIELDS,
190        )
191    }
192}
193
194impl EncodeToRecordBatch for ExecutionMassStatus {
195    fn encode_batch<T>(
196        metadata: &HashMap<String, String>,
197        data: &[T],
198    ) -> Result<RecordBatch, ArrowError>
199    where
200        T: std::borrow::Borrow<Self>,
201    {
202        encode_batch(
203            "ExecutionMassStatus",
204            metadata,
205            data.iter().map(std::borrow::Borrow::borrow),
206            EXECUTION_MASS_STATUS_FIELDS,
207        )
208    }
209
210    fn metadata(&self) -> HashMap<String, String> {
211        metadata_for_type("ExecutionMassStatus")
212    }
213}
214
215impl DecodeTypedFromRecordBatch for ExecutionMassStatus {
216    fn decode_typed_batch(
217        metadata: &HashMap<String, String>,
218        record_batch: RecordBatch,
219    ) -> Result<Vec<Self>, EncodingError> {
220        decode_batch(
221            metadata,
222            &record_batch,
223            EXECUTION_MASS_STATUS_FIELDS,
224            Some("ExecutionMassStatus"),
225        )
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use std::str::FromStr;
232
233    use nautilus_core::{UUID4, UnixNanos};
234    use nautilus_model::{
235        enums::{
236            AvgPxReconciliation, OrderSide, OrderStatus, OrderType, PositionSide, TimeInForce,
237        },
238        identifiers::{AccountId, ClientOrderId, InstrumentId, PositionId, VenueOrderId},
239        reports::{OrderStatusReport, PositionStatusReport},
240        types::{Price, Quantity},
241    };
242    use rstest::rstest;
243    use rust_decimal::Decimal;
244
245    use super::*;
246
247    #[rstest]
248    fn test_order_status_report_round_trip() {
249        let report = OrderStatusReport::new(
250            AccountId::from("SIM-001"),
251            InstrumentId::from("AUDUSD.SIM"),
252            Some(ClientOrderId::from("O-19700101-000000-001-001-1")),
253            VenueOrderId::from("1"),
254            OrderSide::Buy.into(),
255            OrderType::Limit,
256            TimeInForce::Gtc,
257            OrderStatus::Accepted,
258            Quantity::from("100"),
259            Quantity::from("25"),
260            UnixNanos::from(1_000_000_000),
261            UnixNanos::from(2_000_000_000),
262            UnixNanos::from(3_000_000_000),
263            None,
264        )
265        .with_linked_order_ids([ClientOrderId::from("O-19700101-000000-001-001-2")]);
266        let report = OrderStatusReport {
267            activation_price: Some(Price::from("1.05000")),
268            limit_offset: Some(Decimal::from_str("0.123456789123456789").unwrap()),
269            trailing_offset: Some(Decimal::from_str("0.987654321987654321").unwrap()),
270            avg_px: Some(Decimal::from_str("1.23456789123456789").unwrap()),
271            ..report
272        };
273
274        let metadata = report.metadata();
275        let batch =
276            OrderStatusReport::encode_batch(&metadata, std::slice::from_ref(&report)).unwrap();
277        let decoded =
278            OrderStatusReport::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
279
280        assert_eq!(decoded, vec![report]);
281    }
282
283    #[rstest]
284    fn test_position_status_report_round_trip_preserves_decimal_precision() {
285        let report = PositionStatusReport {
286            account_id: AccountId::from("SIM-001"),
287            instrument_id: InstrumentId::from("AUDUSD.SIM"),
288            position_side: PositionSide::Long,
289            quantity: Quantity::from("100.25"),
290            signed_decimal_qty: Decimal::from_str("100.250000000123456789").unwrap(),
291            report_id: UUID4::default(),
292            ts_last: UnixNanos::from(1_000_000_000),
293            ts_init: UnixNanos::from(2_000_000_000),
294            venue_position_id: Some(PositionId::from("P-001")),
295            avg_px_open: Some(Decimal::from_str("1.23456789123456789").unwrap()),
296            avg_px_open_reconciliation: AvgPxReconciliation::OpeningOnly,
297            avg_px_open_precision: Some(4),
298        };
299        let metadata = report.metadata();
300        let batch =
301            PositionStatusReport::encode_batch(&metadata, std::slice::from_ref(&report)).unwrap();
302        let decoded =
303            PositionStatusReport::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
304
305        assert_eq!(decoded, vec![report]);
306    }
307
308    #[rstest]
309    #[case::missing_columns(true)]
310    #[case::null_values(false)]
311    fn test_position_status_report_decodes_without_avg_px_open_metadata(
312        #[case] omit_columns: bool,
313    ) {
314        let report = PositionStatusReport::new(
315            AccountId::from("SIM-001"),
316            InstrumentId::from("AUDUSD.SIM"),
317            PositionSide::Short,
318            Quantity::from("100.25"),
319            UnixNanos::from(1_000_000_000),
320            UnixNanos::from(2_000_000_000),
321            None,
322            None,
323            Some(Decimal::from_str("1.2345").unwrap()),
324        );
325        let metadata = report.metadata();
326
327        let batch = if omit_columns {
328            encode_batch(
329                "PositionStatusReport",
330                &metadata,
331                [&report],
332                &POSITION_STATUS_REPORT_FIELDS[..POSITION_STATUS_REPORT_FIELDS.len() - 2],
333            )
334            .unwrap()
335        } else {
336            let mut row = serde_json::to_value(&report).unwrap();
337            let object = row.as_object_mut().unwrap();
338            object.insert(
339                "avg_px_open_reconciliation".to_string(),
340                serde_json::Value::Null,
341            );
342            object.insert("avg_px_open_precision".to_string(), serde_json::Value::Null);
343            encode_batch(
344                "PositionStatusReport",
345                &metadata,
346                [&row],
347                POSITION_STATUS_REPORT_FIELDS,
348            )
349            .unwrap()
350        };
351
352        let decoded =
353            PositionStatusReport::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
354
355        assert_eq!(decoded, vec![report]);
356    }
357}