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.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 occurred.
98    pub timestamp: Option<UnixNanos>,
99    /// UNIX timestamp (nanoseconds) when the instance was initialized.
100    pub ts_init: Option<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        timestamp: Option<UnixNanos>,
120        sender: Address,
121        recipient: Address,
122        amount0: I256,
123        amount1: I256,
124        sqrt_price_x96: U160,
125        liquidity: u128,
126        tick: i32,
127    ) -> Self {
128        Self {
129            chain,
130            dex,
131            instrument_id,
132            pool_identifier,
133            block,
134            transaction_hash,
135            transaction_index,
136            log_index,
137            timestamp,
138            sender,
139            recipient,
140            amount0,
141            amount1,
142            sqrt_price_x96,
143            liquidity,
144            tick,
145            ts_init: timestamp, // TODO: Use swap timestamp as init timestamp for now
146            trade_info: None,
147        }
148    }
149
150    /// Calculates and populates the `trade_info` field with market-oriented trade data.
151    ///
152    /// This method transforms the raw blockchain swap data (token0/token1 amounts) into
153    /// standard trading terminology (base/quote, buy/sell, execution price). The computation
154    /// determines token roles based on priority and handles decimal adjustments.
155    ///
156    /// # Arguments
157    ///
158    /// * `token0` - Reference to token0 in the pool
159    /// * `token1` - Reference to token1 in the pool
160    /// * `sqrt_price_x96` - Optional square root price before the swap (Q96 format) for calculating price impact and slippage
161    ///
162    /// # Errors
163    ///
164    /// Returns an error if the trade info computation or price calculations fail.
165    ///
166    pub fn calculate_trade_info(
167        &mut self,
168        token0: &Token,
169        token1: &Token,
170        sqrt_price_x96: Option<U160>,
171    ) -> anyhow::Result<()> {
172        let trade_info_calculator = SwapTradeInfoCalculator::new(
173            token0,
174            token1,
175            RawSwapData::new(self.amount0, self.amount1, self.sqrt_price_x96),
176        );
177        self.trade_info = Some(trade_info_calculator.compute(sqrt_price_x96)?);
178
179        Ok(())
180    }
181}
182
183impl Display for PoolSwap {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        write!(
186            f,
187            "{}(instrument_id={})",
188            stringify!(PoolSwap),
189            self.instrument_id,
190        )
191    }
192}