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