1use indexmap::{IndexMap, IndexSet};
24use nautilus_common::cache::Cache;
25use nautilus_core::UnixNanos;
26use nautilus_model::{
27 enums::{
28 AvgPxReconciliation, LiquiditySide, OrderSide, OrderStatus, OrderType, PositionSide,
29 TimeInForce,
30 },
31 identifiers::{AccountId, InstrumentId, TradeId, VenueOrderId},
32 instruments::{Instrument, InstrumentAny},
33 orders::Order,
34 position::Position,
35 reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
36 types::{Money, Quantity},
37};
38use rust_decimal::{Decimal, RoundingStrategy};
39
40use super::{
41 RECONCILIATION_ORDER_TAG,
42 ids::{create_synthetic_trade_id, create_synthetic_venue_order_id},
43 reconciliation_price,
44 types::{FillAdjustmentResult, FillSnapshot, ReconciliationResult, VenuePositionSnapshot},
45};
46
47const DEFAULT_TOLERANCE: Decimal = Decimal::from_parts(1, 0, 0, false, 4); pub fn process_mass_status_for_reconciliation(
60 mass_status: &ExecutionMassStatus,
61 instrument: &InstrumentAny,
62 tolerance: Option<Decimal>,
63) -> anyhow::Result<ReconciliationResult> {
64 process_mass_status_for_reconciliation_inner(mass_status, instrument, tolerance, true)
65}
66
67pub fn process_mass_status_for_reconciliation_without_synthetic_reports(
75 mass_status: &ExecutionMassStatus,
76 instrument: &InstrumentAny,
77 tolerance: Option<Decimal>,
78) -> anyhow::Result<ReconciliationResult> {
79 process_mass_status_for_reconciliation_inner(mass_status, instrument, tolerance, false)
80}
81
82fn process_mass_status_for_reconciliation_inner(
83 mass_status: &ExecutionMassStatus,
84 instrument: &InstrumentAny,
85 tolerance: Option<Decimal>,
86 generate_synthetic_reports: bool,
87) -> anyhow::Result<ReconciliationResult> {
88 let instrument_id = instrument.id();
89 let account_id = mass_status.account_id;
90 let tol = tolerance.unwrap_or(DEFAULT_TOLERANCE);
91
92 let position_reports = mass_status.position_reports();
93
94 let venue_position = match position_reports.get(&instrument_id).and_then(|r| r.first()) {
95 Some(report) if report.avg_px_open.is_some() => position_report_to_snapshot(report),
96 _ => {
97 return Ok(extract_instrument_reports(mass_status, instrument_id));
99 }
100 };
101
102 let extracted = extract_fills_for_instrument(mass_status, instrument_id);
103 let fill_snapshots = extracted.snapshots;
104 let mut order_map = extracted.orders;
105 let mut fill_map = extracted.fills;
106 let mut order_only_ids = IndexSet::new();
107 let mut order_only_fill_keys = IndexSet::new();
108
109 if fill_snapshots.is_empty() {
110 return Ok(ReconciliationResult {
111 orders: order_map,
112 fills: fill_map,
113 order_only_ids,
114 order_only_fill_keys,
115 });
116 }
117
118 let result = adjust_fills_for_partial_window(&fill_snapshots, &venue_position, tol);
119
120 match result {
121 FillAdjustmentResult::NoAdjustment => {}
122
123 FillAdjustmentResult::AddSyntheticOpening {
124 synthetic_fill,
125 existing_fills: _,
126 } if generate_synthetic_reports => {
127 let venue_order_id = create_synthetic_venue_order_id(&synthetic_fill, instrument_id);
128
129 let order = create_synthetic_order_report(
130 &synthetic_fill,
131 account_id,
132 instrument_id,
133 instrument,
134 venue_order_id,
135 )?;
136 let fill = create_synthetic_fill_report(
137 &synthetic_fill,
138 account_id,
139 instrument_id,
140 instrument,
141 venue_order_id,
142 )?;
143
144 order_map.insert(venue_order_id, order);
145 fill_map.entry(venue_order_id).or_default().insert(0, fill);
146 }
147
148 FillAdjustmentResult::ReplaceCurrentLifecycle { synthetic_fill }
149 if generate_synthetic_reports =>
150 {
151 let venue_order_id = create_synthetic_venue_order_id(&synthetic_fill, instrument_id);
152
153 let order = create_synthetic_order_report(
154 &synthetic_fill,
155 account_id,
156 instrument_id,
157 instrument,
158 venue_order_id,
159 )?;
160 let fill = create_synthetic_fill_report(
161 &synthetic_fill,
162 account_id,
163 instrument_id,
164 instrument,
165 venue_order_id,
166 )?;
167
168 order_only_ids.extend(order_map.keys().copied());
171 fill_map.retain(|id, _| order_only_ids.contains(id));
172 order_map.insert(venue_order_id, order);
173 fill_map.insert(venue_order_id, vec![fill]);
174 }
175
176 FillAdjustmentResult::FilterToCurrentLifecycle {
177 last_zero_crossing_ts,
178 current_lifecycle_fills: _,
179 } => {
180 fill_map.retain(|_, fills| {
183 if !fills
184 .iter()
185 .any(|f| f.ts_event.as_u64() > last_zero_crossing_ts)
186 {
187 return false;
188 }
189 order_only_fill_keys.extend(
190 fills
191 .iter()
192 .filter(|f| f.ts_event.as_u64() <= last_zero_crossing_ts)
193 .map(|f| (f.account_id, f.instrument_id, f.trade_id)),
194 );
195 true
196 });
197
198 order_map.retain(|id, order| {
200 fill_map.contains_key(id)
201 || !matches!(
202 order.order_status,
203 OrderStatus::Denied
204 | OrderStatus::Rejected
205 | OrderStatus::Canceled
206 | OrderStatus::Expired
207 | OrderStatus::Filled
208 )
209 });
210 }
211
212 FillAdjustmentResult::AddSyntheticOpening { .. }
213 | FillAdjustmentResult::ReplaceCurrentLifecycle { .. } => {}
214 }
215
216 Ok(ReconciliationResult {
217 orders: order_map,
218 fills: fill_map,
219 order_only_ids,
220 order_only_fill_keys,
221 })
222}
223
224#[must_use]
233pub(super) fn adjust_fills_for_partial_window(
234 fills: &[FillSnapshot],
235 venue_position: &VenuePositionSnapshot,
236 tolerance: Decimal,
237) -> FillAdjustmentResult {
238 let Some(first_fill) = fills.first() else {
239 return FillAdjustmentResult::NoAdjustment;
240 };
241
242 if venue_position.qty == Decimal::ZERO {
243 return FillAdjustmentResult::NoAdjustment;
244 }
245
246 let zero_crossings = detect_zero_crossings(fills);
247 let venue_qty_signed = venue_position.signed_qty();
248
249 if let Some(&last_zero_crossing_ts) = zero_crossings.last() {
251 let mut last_flat_crossing_ts = None;
254 let mut running_qty = Decimal::ZERO;
255
256 for fill in fills {
257 let prev_qty = running_qty;
258 running_qty += Decimal::from(fill.direction()) * fill.qty;
259
260 if prev_qty != Decimal::ZERO && running_qty == Decimal::ZERO {
261 last_flat_crossing_ts = Some(fill.ts_event);
262 }
263 }
264
265 let lifecycle_boundary_ts = last_flat_crossing_ts.unwrap_or(last_zero_crossing_ts);
266
267 let current_lifecycle_fills: Vec<FillSnapshot> = fills
269 .iter()
270 .filter(|f| f.ts_event > lifecycle_boundary_ts)
271 .cloned()
272 .collect();
273
274 let Some(first_fill) = current_lifecycle_fills.first() else {
275 return FillAdjustmentResult::NoAdjustment;
276 };
277
278 let (current_qty, current_value) = simulate_position(¤t_lifecycle_fills);
279
280 if check_position_match(current_qty, current_value, venue_position, tolerance) {
281 return FillAdjustmentResult::FilterToCurrentLifecycle {
283 last_zero_crossing_ts: lifecycle_boundary_ts,
284 current_lifecycle_fills,
285 };
286 }
287
288 let synthetic_fill = FillSnapshot::new(
290 first_fill.venue_order_id,
291 position_to_order_side(venue_position.side),
292 venue_position.qty,
293 venue_position.avg_px,
294 first_fill.ts_event.saturating_sub(1), );
296
297 return FillAdjustmentResult::ReplaceCurrentLifecycle { synthetic_fill };
298 }
299
300 let (oldest_qty, oldest_value) = simulate_position(fills);
301
302 if check_position_match(oldest_qty, oldest_value, venue_position, tolerance) {
303 return FillAdjustmentResult::NoAdjustment;
304 }
305
306 let oldest_avg_px = if oldest_qty == Decimal::ZERO {
308 None
309 } else {
310 Some(oldest_value / oldest_qty.abs())
311 };
312
313 let Some(opening_px) = synthetic_opening_price(oldest_qty, oldest_avg_px, venue_position)
314 else {
315 return FillAdjustmentResult::NoAdjustment;
316 };
317
318 let opening_qty = if oldest_qty == Decimal::ZERO {
319 venue_qty_signed
320 } else {
321 venue_qty_signed - oldest_qty
323 };
324
325 if opening_qty.abs() == Decimal::ZERO {
326 return FillAdjustmentResult::NoAdjustment;
327 }
328
329 let synthetic_side = if opening_qty > Decimal::ZERO {
330 OrderSide::Buy
331 } else {
332 OrderSide::Sell
333 };
334
335 let synthetic_fill = FillSnapshot::new(
336 first_fill.venue_order_id,
337 synthetic_side,
338 opening_qty.abs(),
339 opening_px,
340 first_fill.ts_event.saturating_sub(1),
341 );
342
343 FillAdjustmentResult::AddSyntheticOpening {
344 synthetic_fill,
345 existing_fills: fills.to_vec(),
346 }
347}
348
349fn synthetic_opening_price(
350 window_qty: Decimal,
351 window_avg_px: Option<Decimal>,
352 venue_position: &VenuePositionSnapshot,
353) -> Option<Decimal> {
354 match venue_position.avg_px_reconciliation {
355 AvgPxReconciliation::OpeningOnly => Some(venue_position.avg_px),
357 AvgPxReconciliation::Match => calculate_reconciliation_price(
358 window_qty,
359 window_avg_px,
360 venue_position.signed_qty(),
361 Some(venue_position.avg_px),
362 AvgPxReconciliation::Match,
363 venue_position.avg_px_precision,
364 ),
365 }
366}
367
368pub fn check_position_reconciliation(
379 report: &PositionStatusReport,
380 cached_signed_qty: Decimal,
381 size_precision: Option<u8>,
382) -> bool {
383 let venue_signed_qty = report.signed_decimal_qty;
384
385 if venue_signed_qty == Decimal::ZERO && cached_signed_qty == Decimal::ZERO {
386 return true;
387 }
388
389 if let Some(precision) = size_precision
390 && is_within_single_unit_tolerance(cached_signed_qty, venue_signed_qty, precision)
391 {
392 log::debug!(
393 "Position for {} within tolerance: cached={}, venue={}",
394 report.instrument_id,
395 cached_signed_qty,
396 venue_signed_qty
397 );
398 return true;
399 }
400
401 if cached_signed_qty == venue_signed_qty {
402 return true;
403 }
404
405 log::warn!(
406 "Position discrepancy for {}: cached={}, venue={}",
407 report.instrument_id,
408 cached_signed_qty,
409 venue_signed_qty
410 );
411
412 false
413}
414
415#[must_use]
420pub fn fill_precedes_snapshot_reconciled_position(cache: &Cache, report: &FillReport) -> bool {
421 cache
422 .positions_refs(
423 None,
424 Some(&report.instrument_id),
425 None,
426 Some(&report.account_id),
427 None,
428 )
429 .into_iter()
430 .any(|position| {
431 fill_precedes_reconciled_position(cache, &position, report.trade_id, report.ts_event)
432 })
433}
434
435pub(crate) fn fill_precedes_reconciled_position(
436 cache: &Cache,
437 position: &Position,
438 trade_id: TradeId,
439 ts_event: UnixNanos,
440) -> bool {
441 !position.trade_ids.contains(&trade_id)
442 && position.events.iter().rev().any(|fill| {
443 ts_event < fill.ts_event
444 && cache.order(&fill.client_order_id).is_some_and(|order| {
445 order.tags().is_some_and(|tags| {
446 tags.iter()
447 .any(|tag| tag.as_str() == RECONCILIATION_ORDER_TAG)
448 })
449 })
450 })
451}
452
453pub(super) fn cap_price_at_instrument_max(px: Decimal, instrument: &InstrumentAny) -> Decimal {
471 let Some(max) = instrument.max_price() else {
472 return px;
473 };
474 let cap = max.as_decimal().round_dp_with_strategy(
475 u32::from(instrument.price_precision()),
476 RoundingStrategy::ToZero,
477 );
478 px.min(cap)
479}
480
481pub(super) fn create_synthetic_order_report(
491 fill: &FillSnapshot,
492 account_id: AccountId,
493 instrument_id: InstrumentId,
494 instrument: &InstrumentAny,
495 venue_order_id: VenueOrderId,
496) -> anyhow::Result<OrderStatusReport> {
497 let order_qty = Quantity::from_decimal_dp(fill.qty, instrument.size_precision())?;
498
499 let mut report = OrderStatusReport::new(
500 account_id,
501 instrument_id,
502 None, venue_order_id,
504 fill.side.into(),
505 OrderType::Market,
506 TimeInForce::Gtc,
507 OrderStatus::Filled,
508 order_qty,
509 order_qty, UnixNanos::from(fill.ts_event),
511 UnixNanos::from(fill.ts_event),
512 UnixNanos::from(fill.ts_event),
513 None, );
515 report.avg_px = Some(cap_price_at_instrument_max(fill.px, instrument));
516 Ok(report)
517}
518
519pub(super) fn create_synthetic_fill_report(
525 fill: &FillSnapshot,
526 account_id: AccountId,
527 instrument_id: InstrumentId,
528 instrument: &InstrumentAny,
529 venue_order_id: VenueOrderId,
530) -> anyhow::Result<FillReport> {
531 let trade_id = create_synthetic_trade_id(fill);
532 let qty = Quantity::from_decimal_dp(fill.qty, instrument.size_precision())?;
533 let px = reconciliation_price(cap_price_at_instrument_max(fill.px, instrument), instrument)?;
534
535 Ok(FillReport::new(
536 account_id,
537 instrument_id,
538 venue_order_id,
539 trade_id,
540 fill.side,
541 qty,
542 px,
543 Money::zero(instrument.quote_currency()),
544 LiquiditySide::NoLiquiditySide,
545 None, None, fill.ts_event.into(),
548 fill.ts_event.into(),
549 None, ))
551}
552
553fn position_report_to_snapshot(report: &PositionStatusReport) -> VenuePositionSnapshot {
555 VenuePositionSnapshot {
556 side: report.position_side,
557 qty: report.quantity.into(),
558 avg_px: report.avg_px_open.unwrap_or(Decimal::ZERO),
559 avg_px_reconciliation: report.avg_px_open_reconciliation,
560 avg_px_precision: report.avg_px_open_precision,
561 }
562}
563
564fn position_to_order_side(side: PositionSide) -> OrderSide {
570 match side {
571 PositionSide::Long => OrderSide::Buy,
572 PositionSide::Short => OrderSide::Sell,
573 PositionSide::Flat => {
574 unreachable!("flat venue position must be guarded by an earlier check")
575 }
576 }
577}
578
579fn extract_instrument_reports(
581 mass_status: &ExecutionMassStatus,
582 instrument_id: InstrumentId,
583) -> ReconciliationResult {
584 let mut orders = IndexMap::new();
585 let mut fills = IndexMap::new();
586
587 for (id, order) in mass_status.order_reports() {
588 if order.instrument_id == instrument_id {
589 orders.insert(id, order);
590 }
591 }
592
593 for (id, fill_list) in mass_status.fill_reports() {
594 let filtered: Vec<_> = fill_list
595 .iter()
596 .filter(|f| {
597 if f.instrument_id != instrument_id {
598 return false;
599 }
600
601 if f.last_qty.is_zero() {
602 log::warn!("Skipping zero-quantity fill report: {f}");
603 return false;
604 }
605
606 true
607 })
608 .cloned()
609 .collect();
610
611 if !filtered.is_empty() {
612 fills.insert(id, filtered);
613 }
614 }
615
616 ReconciliationResult {
617 orders,
618 fills,
619 order_only_ids: IndexSet::new(),
620 order_only_fill_keys: IndexSet::new(),
621 }
622}
623
624struct ExtractedFills {
626 snapshots: Vec<FillSnapshot>,
627 orders: IndexMap<VenueOrderId, OrderStatusReport>,
628 fills: IndexMap<VenueOrderId, Vec<FillReport>>,
629}
630
631fn extract_fills_for_instrument(
633 mass_status: &ExecutionMassStatus,
634 instrument_id: InstrumentId,
635) -> ExtractedFills {
636 let mut snapshots = Vec::new();
637 let mut order_map = IndexMap::new();
638 let mut fill_map = IndexMap::new();
639
640 for (id, order) in mass_status.order_reports() {
642 if order.instrument_id == instrument_id {
643 order_map.insert(id, order);
644 }
645 }
646
647 for (venue_order_id, fill_reports) in mass_status.fill_reports() {
649 for fill in fill_reports {
650 if fill.instrument_id == instrument_id {
651 if fill.last_qty.is_zero() {
652 log::warn!("Skipping zero-quantity fill report: {fill}");
653 continue;
654 }
655
656 let side = mass_status
657 .order_reports()
658 .get(&venue_order_id)
659 .and_then(|order| order.order_side)
660 .unwrap_or(fill.order_side);
661
662 snapshots.push(FillSnapshot::new(
663 venue_order_id,
664 side,
665 fill.last_qty.into(),
666 fill.last_px.into(),
667 fill.ts_event.as_u64(),
668 ));
669
670 fill_map
671 .entry(venue_order_id)
672 .or_insert_with(Vec::new)
673 .push(fill);
674 }
675 }
676 }
677
678 snapshots.sort_by_key(|f| f.ts_event);
680
681 ExtractedFills {
682 snapshots,
683 orders: order_map,
684 fills: fill_map,
685 }
686}
687
688#[must_use]
694pub(super) fn simulate_position(fills: &[FillSnapshot]) -> (Decimal, Decimal) {
695 let mut qty = Decimal::ZERO;
696 let mut value = Decimal::ZERO;
697
698 for fill in fills {
699 debug_assert!(
700 fill.qty > Decimal::ZERO,
701 "fill snapshot qty must be positive, received {}",
702 fill.qty,
703 );
704 let direction = Decimal::from(fill.direction());
705 let new_qty = qty + (direction * fill.qty);
706
707 if (qty >= Decimal::ZERO && direction > Decimal::ZERO)
709 || (qty <= Decimal::ZERO && direction < Decimal::ZERO)
710 {
711 value += fill.qty * fill.px;
713 qty = new_qty;
714 } else {
715 if qty.abs() >= fill.qty {
717 let close_ratio = fill.qty / qty.abs();
719 value *= Decimal::ONE - close_ratio;
720 qty = new_qty;
721 } else {
722 let remaining = fill.qty - qty.abs();
724 qty = direction * remaining;
725 value = remaining * fill.px;
726 }
727 }
728 }
729
730 debug_assert!(
731 value >= Decimal::ZERO,
732 "simulated position value must be non-negative, was {value}",
733 );
734 debug_assert!(
735 !(qty != Decimal::ZERO && value.is_sign_negative()),
736 "simulated avg price invariant: qty={qty}, value={value}",
737 );
738
739 (qty, value)
740}
741
742#[must_use]
751pub(super) fn detect_zero_crossings(fills: &[FillSnapshot]) -> Vec<u64> {
752 let mut running_qty = Decimal::ZERO;
753 let mut zero_crossings = Vec::new();
754
755 for fill in fills {
756 let prev_qty = running_qty;
757 running_qty += Decimal::from(fill.direction()) * fill.qty;
758
759 if prev_qty != Decimal::ZERO {
761 if running_qty == Decimal::ZERO {
762 zero_crossings.push(fill.ts_event);
764 } else if (prev_qty > Decimal::ZERO) != (running_qty > Decimal::ZERO) {
765 zero_crossings.push(fill.ts_event);
767 }
768 }
769 }
770
771 zero_crossings
772}
773
774#[must_use]
783pub(super) fn check_position_match(
784 simulated_qty: Decimal,
785 simulated_value: Decimal,
786 venue_position: &VenuePositionSnapshot,
787 tolerance: Decimal,
788) -> bool {
789 if simulated_qty != venue_position.signed_qty() {
790 return false;
791 }
792
793 if simulated_qty == Decimal::ZERO {
794 return true; }
796
797 if venue_position.avg_px_reconciliation == AvgPxReconciliation::OpeningOnly {
798 return true;
799 }
800
801 let simulated_avg_px = simulated_value / simulated_qty.abs();
802
803 position_prices_match(
804 simulated_avg_px,
805 venue_position.avg_px,
806 Some(tolerance),
807 venue_position.avg_px_precision,
808 )
809}
810
811#[must_use]
819pub fn position_prices_match(
820 cached_avg_px: Decimal,
821 venue_avg_px: Decimal,
822 tolerance: Option<Decimal>,
823 venue_precision: Option<u8>,
824) -> bool {
825 if venue_avg_px.is_zero() {
826 return false;
827 }
828
829 let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
830 let diff = (cached_avg_px - venue_avg_px).abs();
831
832 if diff / venue_avg_px.abs() <= tolerance {
833 return true;
834 }
835
836 venue_precision.is_some_and(|precision| {
837 let unit = Decimal::try_new(1, u32::from(precision)).unwrap_or(Decimal::ZERO);
838 diff <= tolerance * venue_avg_px.abs() + unit
839 })
840}
841
842pub fn calculate_reconciliation_price(
868 current_position_qty: Decimal,
869 current_position_avg_px: Option<Decimal>,
870 target_position_qty: Decimal,
871 target_position_avg_px: Option<Decimal>,
872 target_avg_px_reconciliation: AvgPxReconciliation,
873 target_avg_px_precision: Option<u8>,
874) -> Option<Decimal> {
875 let qty_diff = target_position_qty - current_position_qty;
876
877 if qty_diff == Decimal::ZERO {
878 return None; }
880
881 let is_same_side = current_position_qty != Decimal::ZERO
882 && target_position_qty != Decimal::ZERO
883 && (current_position_qty > Decimal::ZERO) == (target_position_qty > Decimal::ZERO);
884
885 if is_same_side
886 && let Some(current_avg_px) = current_position_avg_px
887 && keeps_current_avg_px(
888 current_avg_px,
889 target_position_avg_px,
890 target_avg_px_reconciliation,
891 target_avg_px_precision,
892 )
893 {
894 return Some(current_avg_px);
895 }
896
897 if target_position_qty == Decimal::ZERO {
900 return current_position_avg_px;
901 }
902
903 let target_avg_px = target_position_avg_px?;
905 if target_avg_px == Decimal::ZERO {
906 return None;
907 }
908
909 if current_position_qty == Decimal::ZERO || current_position_avg_px.is_none() {
911 return Some(target_avg_px);
912 }
913
914 let current_avg_px = current_position_avg_px?;
915
916 let is_flip = (current_position_qty > Decimal::ZERO) != (target_position_qty > Decimal::ZERO)
919 && target_position_qty != Decimal::ZERO;
920
921 if is_flip {
922 return Some(target_avg_px);
923 }
924
925 if target_position_qty.abs() < current_position_qty.abs() {
926 return Some(target_avg_px);
927 }
928
929 let target_value = target_position_qty * target_avg_px;
932 let current_value = current_position_qty * current_avg_px;
933 let diff_value = target_value - current_value;
934
935 let reconciliation_px = diff_value / qty_diff;
937
938 if reconciliation_px > Decimal::ZERO {
940 return Some(reconciliation_px);
941 }
942
943 None
944}
945
946fn keeps_current_avg_px(
947 current_avg_px: Decimal,
948 target_avg_px: Option<Decimal>,
949 target_avg_px_reconciliation: AvgPxReconciliation,
950 target_avg_px_precision: Option<u8>,
951) -> bool {
952 match target_avg_px_reconciliation {
953 AvgPxReconciliation::OpeningOnly => true,
954 AvgPxReconciliation::Match => {
955 target_avg_px_precision.is_some()
956 && target_avg_px.is_some_and(|target_avg_px| {
957 position_prices_match(
958 current_avg_px,
959 target_avg_px,
960 None,
961 target_avg_px_precision,
962 )
963 })
964 }
965 }
966}
967
968#[must_use]
973pub(super) fn is_within_single_unit_tolerance(
974 value1: Decimal,
975 value2: Decimal,
976 precision: u8,
977) -> bool {
978 if precision == 0 {
979 return value1 == value2;
980 }
981
982 let tolerance = Decimal::new(1, u32::from(precision));
983 let difference = (value1 - value2).abs();
984 difference <= tolerance
985}