1use std::{
19 io::{Cursor, Write},
20 sync::LazyLock,
21};
22
23use ahash::RandomState;
24use anyhow::Context;
25use nautilus_core::nanos::UnixNanos;
26pub use nautilus_core::serialization::{
27 deserialize_decimal_or_zero, deserialize_optional_decimal,
28 deserialize_optional_decimal_from_str, deserialize_optional_decimal_or_zero,
29 deserialize_optional_decimal_str, parse_decimal, parse_optional_decimal,
30 serialize_decimal_as_str, serialize_optional_decimal_as_str,
31};
32use nautilus_model::{
33 data::BarSpecification,
34 enums::AggressorSide,
35 identifiers::{ClientOrderId, TradeId},
36 types::{Price, Quantity, fixed::FIXED_PRECISION, quantity::QuantityRaw},
37};
38
39use super::enums::AxCandleWidth;
40
41const NANOSECONDS_IN_SECOND: u64 = 1_000_000_000;
42
43pub fn ax_timestamp_s_to_unix_nanos(seconds: i64) -> anyhow::Result<UnixNanos> {
49 anyhow::ensure!(
50 seconds >= 0,
51 "AX timestamp must be non-negative, was {seconds}"
52 );
53 Ok(UnixNanos::from(seconds as u64 * NANOSECONDS_IN_SECOND))
54}
55
56pub fn ax_timestamp_stn_to_unix_nanos(seconds: i64, nanos: i64) -> anyhow::Result<UnixNanos> {
62 anyhow::ensure!(
63 seconds >= 0,
64 "AX timestamp must be non-negative, was {seconds}"
65 );
66 let nanos_part = nanos.max(0) as u64;
67 Ok(UnixNanos::from(
68 seconds as u64 * NANOSECONDS_IN_SECOND + nanos_part,
69 ))
70}
71
72pub fn ax_timestamp_ns_to_unix_nanos(nanos: i64) -> anyhow::Result<UnixNanos> {
78 anyhow::ensure!(
79 nanos >= 0,
80 "AX timestamp_ns must be non-negative, was {nanos}"
81 );
82 Ok(UnixNanos::from(nanos as u64))
83}
84
85const TRADE_ID_DOMAIN: &[u8] = b"nautilus-architect-ax/trade-id/v1";
90
91pub fn create_architect_trade_id(
131 ts_event: UnixNanos,
132 price: Price,
133 quantity: Quantity,
134 aggressor_side: AggressorSide,
135) -> anyhow::Result<TradeId> {
136 const FAILED: &str = "Failed to create TradeId";
137
138 let price = price.as_decimal().normalize();
140 let quantity = quantity.as_decimal().normalize();
141
142 let side = match aggressor_side {
143 AggressorSide::NoAggressor => b'N',
144 AggressorSide::Buy => b'B',
145 AggressorSide::Sell => b'S',
146 };
147
148 let mut input = [0u8; TRADE_ID_DOMAIN.len() + 8 + 16 + 4 + 16 + 4 + 1];
150 let mut offset = 0;
151 for part in [
152 TRADE_ID_DOMAIN,
153 &ts_event.as_u64().to_be_bytes(),
154 &price.mantissa().to_be_bytes(),
155 &price.scale().to_be_bytes(),
156 &quantity.mantissa().to_be_bytes(),
157 &quantity.scale().to_be_bytes(),
158 &[side],
159 ] {
160 let end = offset + part.len();
161 input[offset..end].copy_from_slice(part);
162 offset = end;
163 }
164
165 let hash = blake3::hash(&input);
166
167 let mut digest = [0u8; 8];
168 digest.copy_from_slice(&hash.as_bytes()[..8]);
169 let suffix = u64::from_be_bytes(digest);
170
171 let mut buffer = [0u8; 37];
173 let mut cursor = Cursor::new(buffer.as_mut_slice());
174 write!(cursor, "{}-{suffix:016x}", ts_event.as_u64()).context(FAILED)?;
175 let len = cursor.position() as usize;
176
177 TradeId::from_bytes(&buffer[..len]).context(FAILED)
178}
179
180static CID_HASHER: LazyLock<RandomState> = LazyLock::new(|| {
182 RandomState::with_seeds(
183 0x517cc1b727220a95,
184 0x9b5c18c90c3c314d,
185 0x5851f42d4c957f2d,
186 0x14057b7ef767814f,
187 )
188});
189
190pub fn map_bar_spec_to_candle_width(spec: &BarSpecification) -> anyhow::Result<AxCandleWidth> {
196 AxCandleWidth::try_from(spec)
197}
198
199pub fn quantity_to_contracts(quantity: Quantity) -> anyhow::Result<u64> {
210 let raw = quantity.raw();
211 let scale = 10_u64.pow(FIXED_PRECISION as u32) as QuantityRaw;
212
213 if !raw.is_multiple_of(scale) {
215 anyhow::bail!(
216 "AX requires whole contract quantities, was {}",
217 quantity.as_f64()
218 );
219 }
220
221 #[allow(clippy::unnecessary_cast)]
224 let contracts = (raw / scale) as u64;
225 if contracts == 0 {
226 anyhow::bail!("Order quantity must be at least 1 contract");
227 }
228 Ok(contracts)
229}
230
231#[must_use]
235pub fn client_order_id_to_cid(client_order_id: &ClientOrderId) -> u64 {
236 CID_HASHER.hash_one(client_order_id.inner()) & i64::MAX as u64
237}
238
239#[must_use]
244pub fn cid_to_client_order_id(cid: u64) -> ClientOrderId {
245 ClientOrderId::new(format!("CID-{cid}"))
246}
247
248#[cfg(test)]
249mod tests {
250 use nautilus_model::{
251 enums::{BarAggregation, PriceType},
252 identifiers::ClientOrderId,
253 types::Quantity,
254 };
255 use rstest::rstest;
256 use rust_decimal::Decimal;
257 use rust_decimal_macros::dec;
258
259 use super::*;
260
261 const CAPTURED_TS_EVENT: u64 = 1_766_193_240_334_589_144;
264
265 fn captured_trade_id() -> TradeId {
266 create_architect_trade_id(
267 UnixNanos::from(CAPTURED_TS_EVENT),
268 Price::from_decimal_dp(dec!(1.1719), 4).unwrap(),
269 Quantity::from_decimal_dp(dec!(400), 0).unwrap(),
270 AggressorSide::Buy,
271 )
272 .unwrap()
273 }
274
275 #[rstest]
276 fn test_create_architect_trade_id_format() {
277 let trade_id = captured_trade_id().to_string();
278
279 let (timestamp, digest) = trade_id.split_once('-').unwrap();
280
281 assert_eq!(trade_id.len(), 36);
282 assert_eq!(timestamp, CAPTURED_TS_EVENT.to_string());
283 assert_eq!(digest.len(), 16);
284 assert!(digest.chars().all(|c| c.is_ascii_hexdigit()));
285 }
286
287 #[rstest]
288 #[case(0, AggressorSide::Buy, "0-d66565de305e3202")]
289 #[case(9, AggressorSide::Buy, "9-234d0e8a3df3ae3a")]
290 #[case(10, AggressorSide::Buy, "10-530bf8286ba92b03")]
291 #[case(11, AggressorSide::Buy, "11-011253287c67070e")]
292 #[case(
293 CAPTURED_TS_EVENT,
294 AggressorSide::Buy,
295 "1766193240334589144-38b4fe5a94a253d0"
296 )]
297 #[case(
298 CAPTURED_TS_EVENT,
299 AggressorSide::Sell,
300 "1766193240334589144-5e683093e85c0d45"
301 )]
302 #[case(
303 CAPTURED_TS_EVENT,
304 AggressorSide::NoAggressor,
305 "1766193240334589144-925e31984d86a444"
306 )]
307 #[case(
308 9_999_999_999_999_999_999,
309 AggressorSide::Buy,
310 "9999999999999999999-9b3cb6ef2c9195a6"
311 )]
312 fn test_create_architect_trade_id_preserves_bytes(
313 #[case] timestamp: u64,
314 #[case] aggressor_side: AggressorSide,
315 #[case] expected: &str,
316 ) {
317 let trade_id = create_architect_trade_id(
318 UnixNanos::from(timestamp),
319 Price::from_decimal_dp(dec!(1.1719), 4).unwrap(),
320 Quantity::from_decimal_dp(dec!(400), 0).unwrap(),
321 aggressor_side,
322 )
323 .unwrap();
324
325 assert_eq!(trade_id.as_str(), expected);
326 }
327
328 #[rstest]
329 fn test_create_architect_trade_id_is_deterministic() {
330 assert_eq!(captured_trade_id(), captured_trade_id());
331 }
332
333 #[rstest]
334 fn test_create_architect_trade_id_ignores_trailing_wire_zeros() {
335 let padded = create_architect_trade_id(
337 UnixNanos::from(CAPTURED_TS_EVENT),
338 Price::from_decimal_dp(dec!(1.17190000), 4).unwrap(),
339 Quantity::from_decimal_dp(dec!(400.00), 0).unwrap(),
340 AggressorSide::Buy,
341 )
342 .unwrap();
343
344 assert_eq!(padded, captured_trade_id());
345 }
346
347 #[rstest]
348 fn test_create_architect_trade_id_ignores_instrument_precision() {
349 let wider = create_architect_trade_id(
352 UnixNanos::from(CAPTURED_TS_EVENT),
353 Price::from_decimal_dp(dec!(1.1719), 6).unwrap(),
354 Quantity::from_decimal_dp(dec!(400), 2).unwrap(),
355 AggressorSide::Buy,
356 )
357 .unwrap();
358
359 assert_eq!(wider, captured_trade_id());
360 }
361
362 #[rstest]
363 #[case(dec!(1.1720), dec!(400), AggressorSide::Buy)]
364 #[case(dec!(1.1719), dec!(100), AggressorSide::Buy)]
365 #[case(dec!(1.1719), dec!(400), AggressorSide::Sell)]
366 #[case(dec!(1.1719), dec!(400), AggressorSide::NoAggressor)]
367 fn test_create_architect_trade_id_separates_prints_within_one_timestamp(
368 #[case] price: Decimal,
369 #[case] quantity: Decimal,
370 #[case] aggressor_side: AggressorSide,
371 ) {
372 let other = create_architect_trade_id(
373 UnixNanos::from(CAPTURED_TS_EVENT),
374 Price::from_decimal_dp(price, 4).unwrap(),
375 Quantity::from_decimal_dp(quantity, 0).unwrap(),
376 aggressor_side,
377 )
378 .unwrap();
379
380 assert_ne!(other, captured_trade_id());
381 }
382
383 #[rstest]
384 #[case(10_000_000_000_000_000_000)]
385 #[case(u64::MAX)]
386 fn test_create_architect_trade_id_rejects_timestamp_beyond_capacity(#[case] timestamp: u64) {
387 let error = create_architect_trade_id(
389 UnixNanos::from(timestamp),
390 Price::from_decimal_dp(dec!(1.1719), 4).unwrap(),
391 Quantity::from_decimal_dp(dec!(400), 0).unwrap(),
392 AggressorSide::Buy,
393 )
394 .unwrap_err();
395
396 assert_eq!(error.to_string(), "Failed to create TradeId");
397 }
398
399 #[rstest]
400 fn test_client_order_id_to_cid_deterministic() {
401 let coid = ClientOrderId::new("O-20240101-000001");
402
403 let cid1 = client_order_id_to_cid(&coid);
405 let cid2 = client_order_id_to_cid(&coid);
406 let cid3 = client_order_id_to_cid(&coid);
407
408 assert_eq!(cid1, cid2);
409 assert_eq!(cid2, cid3);
410 }
411
412 #[rstest]
413 fn test_client_order_id_to_cid_different_ids() {
414 let coid1 = ClientOrderId::new("O-20240101-000001");
415 let coid2 = ClientOrderId::new("O-20240101-000002");
416
417 let cid1 = client_order_id_to_cid(&coid1);
418 let cid2 = client_order_id_to_cid(&coid2);
419
420 assert_ne!(cid1, cid2);
421 }
422
423 #[rstest]
424 fn test_client_order_id_to_cid_fits_signed_64_bit_range() {
425 let coid = ClientOrderId::new("O-20260720-055815-001-001-1");
426
427 let cid = client_order_id_to_cid(&coid);
428
429 assert!(i64::try_from(cid).is_ok());
430 }
431
432 #[rstest]
433 #[case("O-1")]
434 #[case("O-SHORT")]
435 #[case("O-20240101-000001")]
436 #[case("Order-with-dashes-and-digits-12345")]
437 #[case("SINGLE")]
438 #[case("a")]
439 #[case("X")]
440 #[case("LONG-ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789")]
441 fn test_client_order_id_to_cid_stable_across_varied_inputs(#[case] value: &str) {
442 let coid = ClientOrderId::new(value);
446 let cid_a = client_order_id_to_cid(&coid);
447 let cid_b = client_order_id_to_cid(&coid);
448 assert_eq!(cid_a, cid_b, "hash must be deterministic");
449
450 let recovered = cid_to_client_order_id(cid_a);
451 assert!(
452 recovered.inner().starts_with("CID-"),
453 "recovered id should have CID prefix: {recovered}",
454 );
455 assert!(
456 !recovered.inner().is_empty(),
457 "recovered id should not be empty",
458 );
459 }
460
461 #[rstest]
462 fn test_client_order_id_to_cid_collision_resistance_small_corpus() {
463 let values = [
465 "O-1",
466 "O-2",
467 "O-10",
468 "O-11",
469 "O-20240101-000001",
470 "O-20240101-000002",
471 "strategy-a/1",
472 "strategy-a/2",
473 "strategy-b/1",
474 ];
475
476 let mut seen = std::collections::HashSet::new();
477 for v in values {
478 let coid = ClientOrderId::new(v);
479 let cid = client_order_id_to_cid(&coid);
480 assert!(seen.insert(cid), "cid collision for {v}");
481 }
482 }
483
484 #[rstest]
485 fn test_quantity_to_contracts_valid_precision_zero() {
486 let qty = Quantity::new(10.0, 0);
487 let result = quantity_to_contracts(qty);
488 assert!(result.is_ok());
489 assert_eq!(result.unwrap(), 10);
490 }
491
492 #[rstest]
493 fn test_quantity_to_contracts_valid_with_precision() {
494 let qty = Quantity::new(10.0, 2);
496 let result = quantity_to_contracts(qty);
497 assert!(result.is_ok());
498 assert_eq!(result.unwrap(), 10);
499 }
500
501 #[rstest]
502 fn test_quantity_to_contracts_fractional_rejects() {
503 let qty = Quantity::new(10.5, 1);
504 let result = quantity_to_contracts(qty);
505 assert!(result.is_err());
506 }
507
508 #[rstest]
509 fn test_quantity_to_contracts_zero_rejects() {
510 let qty = Quantity::new(0.0, 0);
511 let result = quantity_to_contracts(qty);
512 assert!(result.is_err());
513 }
514
515 #[rstest]
516 fn test_map_bar_spec_1_second() {
517 let spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
518 let result = map_bar_spec_to_candle_width(&spec);
519 assert!(result.is_ok());
520 assert!(matches!(result.unwrap(), AxCandleWidth::Seconds1));
521 }
522
523 #[rstest]
524 fn test_map_bar_spec_5_second() {
525 let spec = BarSpecification::new(5, BarAggregation::Second, PriceType::Last);
526 let result = map_bar_spec_to_candle_width(&spec);
527 assert!(result.is_ok());
528 assert!(matches!(result.unwrap(), AxCandleWidth::Seconds5));
529 }
530
531 #[rstest]
532 fn test_map_bar_spec_1_minute() {
533 let spec = BarSpecification::new(1, BarAggregation::Minute, PriceType::Last);
534 let result = map_bar_spec_to_candle_width(&spec);
535 assert!(result.is_ok());
536 assert!(matches!(result.unwrap(), AxCandleWidth::Minutes1));
537 }
538
539 #[rstest]
540 fn test_map_bar_spec_5_minute() {
541 let spec = BarSpecification::new(5, BarAggregation::Minute, PriceType::Last);
542 let result = map_bar_spec_to_candle_width(&spec);
543 assert!(result.is_ok());
544 assert!(matches!(result.unwrap(), AxCandleWidth::Minutes5));
545 }
546
547 #[rstest]
548 fn test_map_bar_spec_15_minute() {
549 let spec = BarSpecification::new(15, BarAggregation::Minute, PriceType::Last);
550 let result = map_bar_spec_to_candle_width(&spec);
551 assert!(result.is_ok());
552 assert!(matches!(result.unwrap(), AxCandleWidth::Minutes15));
553 }
554
555 #[rstest]
556 fn test_map_bar_spec_1_hour() {
557 let spec = BarSpecification::new(1, BarAggregation::Hour, PriceType::Last);
558 let result = map_bar_spec_to_candle_width(&spec);
559 assert!(result.is_ok());
560 assert!(matches!(result.unwrap(), AxCandleWidth::Hours1));
561 }
562
563 #[rstest]
564 fn test_map_bar_spec_1_day() {
565 let spec = BarSpecification::new(1, BarAggregation::Day, PriceType::Last);
566 let result = map_bar_spec_to_candle_width(&spec);
567 assert!(result.is_ok());
568 assert!(matches!(result.unwrap(), AxCandleWidth::Days1));
569 }
570
571 #[rstest]
572 fn test_map_bar_spec_unsupported_step() {
573 let spec = BarSpecification::new(3, BarAggregation::Minute, PriceType::Last);
574 let result = map_bar_spec_to_candle_width(&spec);
575 assert!(result.is_err());
576 }
577
578 #[rstest]
579 fn test_map_bar_spec_unsupported_aggregation() {
580 let spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
581 let result = map_bar_spec_to_candle_width(&spec);
582 assert!(result.is_err());
583 }
584
585 #[rstest]
586 fn test_ax_timestamp_s_to_unix_nanos_valid() {
587 let result = ax_timestamp_s_to_unix_nanos(1_000).unwrap();
588 assert_eq!(result, UnixNanos::from(1_000_000_000_000u64));
589 }
590
591 #[rstest]
592 fn test_ax_timestamp_s_to_unix_nanos_zero() {
593 let result = ax_timestamp_s_to_unix_nanos(0).unwrap();
594 assert_eq!(result, UnixNanos::from(0u64));
595 }
596
597 #[rstest]
598 fn test_ax_timestamp_s_to_unix_nanos_negative_errors() {
599 assert!(ax_timestamp_s_to_unix_nanos(-1).is_err());
600 }
601
602 #[rstest]
603 fn test_ax_timestamp_ns_to_unix_nanos_valid() {
604 let result = ax_timestamp_ns_to_unix_nanos(1_000_000_000).unwrap();
605 assert_eq!(result, UnixNanos::from(1_000_000_000u64));
606 }
607
608 #[rstest]
609 fn test_ax_timestamp_ns_to_unix_nanos_negative_errors() {
610 assert!(ax_timestamp_ns_to_unix_nanos(-1).is_err());
611 }
612
613 #[rstest]
614 fn test_ax_timestamp_stn_to_unix_nanos_combines_seconds_and_nanos() {
615 let result = ax_timestamp_stn_to_unix_nanos(1_000, 500).unwrap();
616 assert_eq!(result, UnixNanos::from(1_000_000_000_500u64));
617 }
618
619 #[rstest]
620 fn test_ax_timestamp_stn_to_unix_nanos_zero_nanos() {
621 let result = ax_timestamp_stn_to_unix_nanos(1_000, 0).unwrap();
622 assert_eq!(result, UnixNanos::from(1_000_000_000_000u64));
623 }
624
625 #[rstest]
626 fn test_ax_timestamp_stn_to_unix_nanos_negative_seconds_errors() {
627 assert!(ax_timestamp_stn_to_unix_nanos(-1, 0).is_err());
628 }
629
630 #[rstest]
631 fn test_ax_timestamp_stn_to_unix_nanos_negative_nanos_clamps_to_zero() {
632 let result = ax_timestamp_stn_to_unix_nanos(1_000, -1).unwrap();
633 assert_eq!(result, UnixNanos::from(1_000_000_000_000u64));
634 }
635}