Skip to main content

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.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 hash of the block observed when this swap was ingested.
78    pub block_hash: Option<String>,
79    /// The unique hash identifier of the blockchain transaction containing the swap.
80    pub transaction_hash: String,
81    /// The index position of the transaction within the block.
82    pub transaction_index: u32,
83    /// The index position of the swap event log within the transaction.
84    pub log_index: u32,
85    /// The blockchain address of the user or contract that initiated the swap.
86    pub sender: Address,
87    /// The blockchain address that received the swapped tokens.
88    pub recipient: Address,
89    /// The sqrt price after the swap (Q64.96 format).
90    pub sqrt_price_x96: U160,
91    /// The amount of token0 involved in the swap.
92    pub amount0: I256,
93    /// The amount of token1 involved in the swap.
94    pub amount1: I256,
95    /// The liquidity of the pool after the swap occurred.
96    pub liquidity: u128,
97    /// The current tick of the pool after the swap occurred.
98    pub tick: i32,
99    /// UNIX timestamp (nanoseconds) when the swap event occurred.
100    pub ts_event: UnixNanos,
101    /// UNIX timestamp (nanoseconds) when the instance was initialized.
102    pub ts_init: UnixNanos,
103    /// Optional computed trade information in market-oriented format.
104    /// This translates raw blockchain data into standard trading terminology.
105    pub trade_info: Option<SwapTradeInfo>,
106}
107
108impl PoolSwap {
109    /// Creates a new [`PoolSwap`] instance with the specified properties.
110    #[must_use]
111    #[expect(clippy::too_many_arguments)]
112    pub fn new(
113        chain: SharedChain,
114        dex: SharedDex,
115        instrument_id: InstrumentId,
116        pool_identifier: PoolIdentifier,
117        block: u64,
118        transaction_hash: String,
119        transaction_index: u32,
120        log_index: u32,
121        ts_event: UnixNanos,
122        ts_init: UnixNanos,
123        sender: Address,
124        recipient: Address,
125        amount0: I256,
126        amount1: I256,
127        sqrt_price_x96: U160,
128        liquidity: u128,
129        tick: i32,
130    ) -> Self {
131        Self {
132            chain,
133            dex,
134            instrument_id,
135            pool_identifier,
136            block,
137            block_hash: None,
138            transaction_hash,
139            transaction_index,
140            log_index,
141            ts_event,
142            ts_init,
143            sender,
144            recipient,
145            amount0,
146            amount1,
147            sqrt_price_x96,
148            liquidity,
149            tick,
150            trade_info: None,
151        }
152    }
153
154    /// Calculates and populates the `trade_info` field with market-oriented trade data.
155    ///
156    /// This method transforms the raw blockchain swap data (token0/token1 amounts) into
157    /// standard trading terminology (base/quote, buy/sell, execution price). The computation
158    /// determines token roles based on priority and handles decimal adjustments.
159    ///
160    /// # Arguments
161    ///
162    /// * `token0` - Reference to token0 in the pool
163    /// * `token1` - Reference to token1 in the pool
164    /// * `sqrt_price_x96` - Optional square root price before the swap (Q96 format) for calculating price impact and slippage
165    ///
166    /// # Errors
167    ///
168    /// Returns an error if the trade info computation or price calculations fail.
169    pub fn calculate_trade_info(
170        &mut self,
171        token0: &Token,
172        token1: &Token,
173        sqrt_price_x96: Option<U160>,
174    ) -> anyhow::Result<()> {
175        let trade_info_calculator = SwapTradeInfoCalculator::new(
176            token0,
177            token1,
178            RawSwapData::new(self.amount0, self.amount1, self.sqrt_price_x96),
179        );
180        self.trade_info = Some(trade_info_calculator.compute(sqrt_price_x96)?);
181
182        Ok(())
183    }
184}
185
186impl Display for PoolSwap {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        write!(
189            f,
190            "{}(instrument_id={})",
191            stringify!(PoolSwap),
192            self.instrument_id,
193        )
194    }
195}