nautilus_model/defi/data/swap.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::fmt::Display;
17
18use alloy_primitives::{Address, I256, U160};
19use nautilus_core::UnixNanos;
20
21use crate::{
22 defi::{
23 PoolIdentifier, SharedChain, SharedDex, Token,
24 data::swap_trade_info::{SwapTradeInfo, SwapTradeInfoCalculator},
25 },
26 identifiers::InstrumentId,
27};
28
29/// Raw swap data directly from the blockchain event log.
30#[derive(Debug, Clone)]
31pub struct RawSwapData {
32 /// Amount of token0 involved in the swap (positive = in, negative = out).
33 pub amount0: I256,
34 /// Amount of token1 involved in the swap (positive = in, negative = out).
35 pub amount1: I256,
36 /// Square root price of the pool AFTER the swap (Q64.96 fixed-point format).
37 pub sqrt_price_x96: U160,
38}
39
40impl RawSwapData {
41 /// Creates a new [`RawSwapData`] instance with the specified values.
42 #[must_use]
43 pub fn new(amount0: I256, amount1: I256, sqrt_price_x96: U160) -> Self {
44 Self {
45 amount0,
46 amount1,
47 sqrt_price_x96,
48 }
49 }
50}
51
52/// Represents a token swap transaction on a decentralized exchange (DEX).
53///
54/// This structure captures both the raw blockchain data from a swap event and
55/// optionally includes computed market-oriented trade information. It serves as
56/// the primary data structure for tracking and analyzing DEX swap activity.
57#[derive(Debug, Clone, PartialEq)]
58#[cfg_attr(
59 feature = "python",
60 pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
61)]
62#[cfg_attr(
63 feature = "python",
64 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
65)]
66pub struct PoolSwap {
67 /// The blockchain network where the swap occurred.
68 pub chain: SharedChain,
69 /// The decentralized exchange where the swap was executed.
70 pub dex: SharedDex,
71 /// The instrument ID for this pool's trading pair.
72 pub instrument_id: InstrumentId,
73 /// The unique identifier for this pool (could be an address or other protocol-specific hex string).
74 pub pool_identifier: PoolIdentifier,
75 /// The blockchain block number at which the swap was executed.
76 pub block: u64,
77 /// The unique hash identifier of the blockchain transaction containing the swap.
78 pub transaction_hash: String,
79 /// The index position of the transaction within the block.
80 pub transaction_index: u32,
81 /// The index position of the swap event log within the transaction.
82 pub log_index: u32,
83 /// The blockchain address of the user or contract that initiated the swap.
84 pub sender: Address,
85 /// The blockchain address that received the swapped tokens.
86 pub recipient: Address,
87 /// The sqrt price after the swap (Q64.96 format).
88 pub sqrt_price_x96: U160,
89 /// The amount of token0 involved in the swap.
90 pub amount0: I256,
91 /// The amount of token1 involved in the swap.
92 pub amount1: I256,
93 /// The liquidity of the pool after the swap occurred.
94 pub liquidity: u128,
95 /// The current tick of the pool after the swap occurred.
96 pub tick: i32,
97 /// UNIX timestamp (nanoseconds) when the swap event occurred.
98 pub ts_event: UnixNanos,
99 /// UNIX timestamp (nanoseconds) when the instance was initialized.
100 pub ts_init: UnixNanos,
101 /// Optional computed trade information in market-oriented format.
102 /// This translates raw blockchain data into standard trading terminology.
103 pub trade_info: Option<SwapTradeInfo>,
104}
105
106impl PoolSwap {
107 /// Creates a new [`PoolSwap`] instance with the specified properties.
108 #[must_use]
109 #[expect(clippy::too_many_arguments)]
110 pub fn new(
111 chain: SharedChain,
112 dex: SharedDex,
113 instrument_id: InstrumentId,
114 pool_identifier: PoolIdentifier,
115 block: u64,
116 transaction_hash: String,
117 transaction_index: u32,
118 log_index: u32,
119 ts_event: UnixNanos,
120 ts_init: UnixNanos,
121 sender: Address,
122 recipient: Address,
123 amount0: I256,
124 amount1: I256,
125 sqrt_price_x96: U160,
126 liquidity: u128,
127 tick: i32,
128 ) -> Self {
129 Self {
130 chain,
131 dex,
132 instrument_id,
133 pool_identifier,
134 block,
135 transaction_hash,
136 transaction_index,
137 log_index,
138 ts_event,
139 ts_init,
140 sender,
141 recipient,
142 amount0,
143 amount1,
144 sqrt_price_x96,
145 liquidity,
146 tick,
147 trade_info: None,
148 }
149 }
150
151 /// Calculates and populates the `trade_info` field with market-oriented trade data.
152 ///
153 /// This method transforms the raw blockchain swap data (token0/token1 amounts) into
154 /// standard trading terminology (base/quote, buy/sell, execution price). The computation
155 /// determines token roles based on priority and handles decimal adjustments.
156 ///
157 /// # Arguments
158 ///
159 /// * `token0` - Reference to token0 in the pool
160 /// * `token1` - Reference to token1 in the pool
161 /// * `sqrt_price_x96` - Optional square root price before the swap (Q96 format) for calculating price impact and slippage
162 ///
163 /// # Errors
164 ///
165 /// Returns an error if the trade info computation or price calculations fail.
166 ///
167 pub fn calculate_trade_info(
168 &mut self,
169 token0: &Token,
170 token1: &Token,
171 sqrt_price_x96: Option<U160>,
172 ) -> anyhow::Result<()> {
173 let trade_info_calculator = SwapTradeInfoCalculator::new(
174 token0,
175 token1,
176 RawSwapData::new(self.amount0, self.amount1, self.sqrt_price_x96),
177 );
178 self.trade_info = Some(trade_info_calculator.compute(sqrt_price_x96)?);
179
180 Ok(())
181 }
182}
183
184impl Display for PoolSwap {
185 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186 write!(
187 f,
188 "{}(instrument_id={})",
189 stringify!(PoolSwap),
190 self.instrument_id,
191 )
192 }
193}