1use std::collections::HashMap;
17
18use arrow::{datatypes::Schema, error::ArrowError, record_batch::RecordBatch};
19use nautilus_model::events::{OrderSnapshot, PositionSnapshot};
20
21use super::{
22 ArrowSchemaProvider, DecodeTypedFromRecordBatch, EncodeToRecordBatch, EncodingError,
23 KEY_INSTRUMENT_ID,
24 json::{JsonFieldSpec, decode_batch, encode_batch, metadata_for_type, schema_for_type},
25};
26
27const ORDER_SNAPSHOT_FIELDS: &[JsonFieldSpec] = &[
28 JsonFieldSpec::utf8("trader_id", false),
29 JsonFieldSpec::utf8("strategy_id", false),
30 JsonFieldSpec::utf8("instrument_id", false),
31 JsonFieldSpec::utf8("client_order_id", false),
32 JsonFieldSpec::utf8("venue_order_id", true),
33 JsonFieldSpec::utf8("position_id", true),
34 JsonFieldSpec::utf8("account_id", true),
35 JsonFieldSpec::utf8("last_trade_id", true),
36 JsonFieldSpec::utf8("order_type", false),
37 JsonFieldSpec::utf8("order_side", false),
38 JsonFieldSpec::utf8("quantity", false),
39 JsonFieldSpec::utf8("price", true),
40 JsonFieldSpec::utf8("trigger_price", true),
41 JsonFieldSpec::utf8("trigger_type", true),
42 JsonFieldSpec::utf8("limit_offset", true),
43 JsonFieldSpec::utf8("trailing_offset", true),
44 JsonFieldSpec::utf8("trailing_offset_type", true),
45 JsonFieldSpec::utf8("time_in_force", false),
46 JsonFieldSpec::timestamp("expire_time", true),
47 JsonFieldSpec::utf8("filled_qty", false),
48 JsonFieldSpec::utf8("liquidity_side", true),
49 JsonFieldSpec::utf8("avg_px", true),
50 JsonFieldSpec::utf8("slippage", true),
51 JsonFieldSpec::utf8_json("commissions", false),
52 JsonFieldSpec::utf8("status", false),
53 JsonFieldSpec::boolean("is_post_only", false),
54 JsonFieldSpec::boolean("is_reduce_only", false),
55 JsonFieldSpec::boolean("is_quote_quantity", false),
56 JsonFieldSpec::utf8("display_qty", true),
57 JsonFieldSpec::utf8("emulation_trigger", true),
58 JsonFieldSpec::utf8("trigger_instrument_id", true),
59 JsonFieldSpec::utf8("contingency_type", true),
60 JsonFieldSpec::utf8("order_list_id", true),
61 JsonFieldSpec::utf8_json("linked_order_ids", true),
62 JsonFieldSpec::utf8("parent_order_id", true),
63 JsonFieldSpec::utf8("exec_algorithm_id", true),
64 JsonFieldSpec::utf8_json("exec_algorithm_params", true),
65 JsonFieldSpec::utf8("exec_spawn_id", true),
66 JsonFieldSpec::utf8_json("tags", true),
67 JsonFieldSpec::utf8("init_id", false),
68 JsonFieldSpec::timestamp("ts_init", false),
69 JsonFieldSpec::timestamp("ts_last", false),
70 JsonFieldSpec::utf8("activation_price", true),
73];
74
75const POSITION_SNAPSHOT_FIELDS: &[JsonFieldSpec] = &[
76 JsonFieldSpec::utf8("trader_id", false),
77 JsonFieldSpec::utf8("strategy_id", false),
78 JsonFieldSpec::utf8("instrument_id", false),
79 JsonFieldSpec::utf8("position_id", false),
80 JsonFieldSpec::utf8("account_id", false),
81 JsonFieldSpec::utf8("opening_order_id", false),
82 JsonFieldSpec::utf8("closing_order_id", true),
83 JsonFieldSpec::utf8("entry", false),
84 JsonFieldSpec::utf8("side", false),
85 JsonFieldSpec::f64("signed_qty", false),
86 JsonFieldSpec::utf8("quantity", false),
87 JsonFieldSpec::utf8("peak_qty", false),
88 JsonFieldSpec::utf8("quote_currency", false),
89 JsonFieldSpec::utf8("base_currency", true),
90 JsonFieldSpec::utf8("settlement_currency", false),
91 JsonFieldSpec::f64("avg_px_open", false),
92 JsonFieldSpec::f64("avg_px_close", true),
93 JsonFieldSpec::f64("realized_return", true),
94 JsonFieldSpec::utf8("realized_pnl", true),
95 JsonFieldSpec::utf8("unrealized_pnl", true),
96 JsonFieldSpec::utf8_json("commissions", false),
97 JsonFieldSpec::u64("duration_ns", true),
98 JsonFieldSpec::timestamp("ts_opened", false),
99 JsonFieldSpec::timestamp("ts_closed", true),
100 JsonFieldSpec::timestamp("ts_init", false),
101 JsonFieldSpec::timestamp("ts_last", false),
102 JsonFieldSpec::utf8_json("replay_state", true),
103];
104
105fn instrument_metadata(type_name: &'static str, instrument_id: &str) -> HashMap<String, String> {
106 let mut metadata = metadata_for_type(type_name);
107 metadata.insert(KEY_INSTRUMENT_ID.to_string(), instrument_id.to_string());
108 metadata
109}
110
111macro_rules! impl_snapshot_arrow {
112 ($type:ty, $type_name:expr, $fields:expr) => {
113 impl ArrowSchemaProvider for $type {
114 fn get_schema(metadata: Option<HashMap<String, String>>) -> Schema {
115 schema_for_type($type_name, metadata, $fields)
116 }
117 }
118
119 impl EncodeToRecordBatch for $type {
120 fn encode_batch<T>(
121 metadata: &HashMap<String, String>,
122 data: &[T],
123 ) -> Result<RecordBatch, ArrowError>
124 where
125 T: std::borrow::Borrow<Self>,
126 {
127 encode_batch(
128 $type_name,
129 metadata,
130 data.iter().map(std::borrow::Borrow::borrow),
131 $fields,
132 )
133 }
134
135 fn metadata(&self) -> HashMap<String, String> {
136 instrument_metadata($type_name, &self.instrument_id.to_string())
137 }
138 }
139
140 impl DecodeTypedFromRecordBatch for $type {
141 fn decode_typed_batch(
142 metadata: &HashMap<String, String>,
143 record_batch: RecordBatch,
144 ) -> Result<Vec<Self>, EncodingError> {
145 decode_batch(metadata, &record_batch, $fields, Some($type_name))
146 }
147 }
148 };
149}
150
151impl_snapshot_arrow!(OrderSnapshot, "OrderSnapshot", ORDER_SNAPSHOT_FIELDS);
152impl_snapshot_arrow!(
153 PositionSnapshot,
154 "PositionSnapshot",
155 POSITION_SNAPSHOT_FIELDS
156);
157
158#[cfg(test)]
159mod tests {
160 use std::str::FromStr;
161
162 use arrow::datatypes::DataType;
163 use nautilus_core::{DurationNanos, UnixNanos};
164 use nautilus_model::{
165 enums::{OrderSide, OrderType, PositionSide, TrailingOffsetType},
166 identifiers::{AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TraderId},
167 orders::OrderTestBuilder,
168 types::{Currency, Money, Price, Quantity},
169 };
170 use rstest::rstest;
171 use rust_decimal::Decimal;
172 use rust_decimal_macros::dec;
173
174 use super::*;
175
176 #[rstest]
177 fn test_order_snapshot_round_trip_preserves_decimal_precision() {
178 let order = OrderTestBuilder::new(OrderType::TrailingStopLimit)
179 .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
180 .side(OrderSide::Buy)
181 .price(Price::from("50000"))
182 .trigger_price(Price::from("50500"))
183 .limit_offset(Decimal::from_str("0.123456789123456789").unwrap())
184 .trailing_offset(Decimal::from_str("0.987654321987654321").unwrap())
185 .trailing_offset_type(TrailingOffsetType::Price)
186 .quantity(Quantity::from("0.5"))
187 .build();
188 let snapshot = OrderSnapshot::from(order);
189 let metadata = snapshot.metadata();
190 let batch =
191 OrderSnapshot::encode_batch(&metadata, std::slice::from_ref(&snapshot)).unwrap();
192 let decoded = OrderSnapshot::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
193
194 assert_eq!(decoded, vec![snapshot]);
195 }
196
197 fn make_order_snapshot(avg_px: Option<Decimal>, slippage: Option<Decimal>) -> OrderSnapshot {
198 let order = OrderTestBuilder::new(OrderType::Limit)
199 .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
200 .side(OrderSide::Buy)
201 .price(Price::from("50000"))
202 .quantity(Quantity::from("0.5"))
203 .build();
204 let mut snapshot = OrderSnapshot::from(order);
205 snapshot.avg_px = avg_px;
206 snapshot.slippage = slippage;
207 snapshot
208 }
209
210 fn float64_fields() -> Vec<JsonFieldSpec> {
212 ORDER_SNAPSHOT_FIELDS
213 .iter()
214 .map(|spec| match spec.name {
215 "avg_px" | "slippage" => JsonFieldSpec::f64(spec.name, spec.nullable),
216 _ => *spec,
217 })
218 .collect()
219 }
220
221 #[rstest]
222 fn test_order_snapshot_round_trip_preserves_exact_avg_px_and_slippage() {
223 let snapshot = make_order_snapshot(
226 Some(Decimal::from_str("1.6666666666666666666666666667").unwrap()),
227 Some(Decimal::from_str("0.0000000000000000000000000001").unwrap()),
228 );
229 let metadata = snapshot.metadata();
230 let batch =
231 OrderSnapshot::encode_batch(&metadata, std::slice::from_ref(&snapshot)).unwrap();
232
233 let avg_px_field = batch.schema().field_with_name("avg_px").unwrap().clone();
234 let slippage_field = batch.schema().field_with_name("slippage").unwrap().clone();
235 let decoded = OrderSnapshot::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
236
237 assert_eq!(avg_px_field.data_type(), &DataType::Utf8);
238 assert_eq!(slippage_field.data_type(), &DataType::Utf8);
239 assert_eq!(decoded, vec![snapshot]);
240 }
241
242 #[rstest]
243 fn test_order_snapshot_round_trip_null_avg_px_and_slippage() {
244 let snapshot = make_order_snapshot(None, None);
245 let metadata = snapshot.metadata();
246 let batch =
247 OrderSnapshot::encode_batch(&metadata, std::slice::from_ref(&snapshot)).unwrap();
248 let decoded = OrderSnapshot::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
249
250 assert_eq!(decoded, vec![snapshot]);
251 }
252
253 #[rstest]
254 fn test_order_snapshot_rejects_float64_avg_px_column() {
255 let snapshot = make_order_snapshot(Some(dec!(1.07)), Some(dec!(0.07)));
257 let metadata = snapshot.metadata();
258 let batch = encode_batch(
259 "OrderSnapshot",
260 &metadata,
261 std::slice::from_ref(&snapshot),
262 &float64_fields(),
263 )
264 .unwrap();
265
266 let error =
267 OrderSnapshot::decode_typed_batch(batch.schema().metadata(), batch).unwrap_err();
268
269 assert!(matches!(
270 error,
271 EncodingError::InvalidColumnType("avg_px", _, DataType::Utf8, DataType::Float64)
272 ));
273 }
274
275 fn make_position_snapshot() -> PositionSnapshot {
276 PositionSnapshot {
277 trader_id: TraderId::from("TRADER-001"),
278 strategy_id: StrategyId::from("EMA-CROSS"),
279 instrument_id: InstrumentId::from("EURUSD.SIM"),
280 position_id: PositionId::from("P-001"),
281 account_id: AccountId::from("SIM-001"),
282 opening_order_id: ClientOrderId::from("O-1"),
283 closing_order_id: Some(ClientOrderId::from("O-2")),
284 entry: OrderSide::Buy,
285 side: PositionSide::Long,
286 signed_qty: 100.0,
287 quantity: Quantity::from("100"),
288 peak_qty: Quantity::from("100"),
289 quote_currency: Currency::USD(),
290 base_currency: Some(Currency::EUR()),
291 settlement_currency: Currency::USD(),
292 avg_px_open: 1.0500,
293 avg_px_close: Some(1.0600),
294 realized_return: Some(0.0095),
295 realized_pnl: Some(Money::new(100.0, Currency::USD())),
296 unrealized_pnl: Some(Money::new(50.0, Currency::USD())),
297 commissions: vec![Money::new(2.0, Currency::USD())],
298 duration_ns: Some(DurationNanos::new(3_600_000_000_000)),
299 ts_opened: UnixNanos::from(1_000_000_000),
300 ts_closed: Some(UnixNanos::from(4_600_000_000)),
301 ts_init: UnixNanos::from(2_000_000_000),
302 ts_last: UnixNanos::from(4_600_000_000),
303 replay_state: None,
304 }
305 }
306
307 #[rstest]
308 fn test_position_snapshot_round_trip() {
309 let mut snapshot = make_position_snapshot();
310 snapshot.replay_state = Some(serde_json::json!({"fill_voids": []}));
311 let metadata = snapshot.metadata();
312 let batch =
313 PositionSnapshot::encode_batch(&metadata, std::slice::from_ref(&snapshot)).unwrap();
314 let decoded =
315 PositionSnapshot::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
316
317 assert_eq!(decoded, vec![snapshot]);
318 }
319
320 #[rstest]
321 fn test_position_snapshot_round_trip_null_optionals() {
322 let mut snapshot = make_position_snapshot();
323 snapshot.closing_order_id = None;
324 snapshot.base_currency = None;
325 snapshot.avg_px_close = None;
326 snapshot.realized_return = None;
327 snapshot.realized_pnl = None;
328 snapshot.unrealized_pnl = None;
329 snapshot.duration_ns = None;
330 snapshot.ts_closed = None;
331
332 let metadata = snapshot.metadata();
333 let batch =
334 PositionSnapshot::encode_batch(&metadata, std::slice::from_ref(&snapshot)).unwrap();
335 let decoded =
336 PositionSnapshot::decode_typed_batch(batch.schema().metadata(), batch).unwrap();
337
338 assert_eq!(decoded, vec![snapshot]);
339 }
340}