nautilus-model 0.55.0

Domain model for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Data types specific to automated-market-maker (AMM) protocols.

use std::{fmt::Display, sync::Arc};

use alloy_primitives::{Address, U160};
use nautilus_core::UnixNanos;
use serde::{Deserialize, Serialize};

use crate::{
    data::HasTsInit,
    defi::{
        Blockchain, PoolIdentifier, SharedDex, chain::SharedChain, dex::Dex,
        tick_map::tick_math::get_tick_at_sqrt_ratio, token::Token,
    },
    identifiers::{InstrumentId, Symbol, Venue},
};

/// Represents a liquidity pool in a decentralized exchange.
///
/// ## Pool Identification Architecture
///
/// Pools are identified differently depending on the DEX protocol version:
///
/// **UniswapV2/V3**: Each pool has its own smart contract deployed at a unique address.
/// - `address` = pool contract address
/// - `pool_identifier` = same as address (hex string)
///
/// **UniswapV4**: All pools share a singleton PoolManager contract. Pools are distinguished
/// by a unique Pool ID (keccak256 hash of currencies, fee, tick spacing, and hooks).
/// - `address` = PoolManager contract address (shared by all pools)
/// - `pool_identifier` = Pool ID (bytes32 as hex string)
///
/// ## Instrument ID Format
///
/// The instrument ID encodes with the following components:
/// - `symbol` – The pool identifier (address for V2/V3, Pool ID for V4)
/// - `venue`  – The chain name plus DEX ID
///
/// String representation: `<POOL_IDENTIFIER>.<CHAIN_NAME>:<DEX_ID>`
///
/// Example: `0x11b815efB8f581194ae79006d24E0d814B7697F6.Ethereum:UniswapV3`
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Pool {
    /// The blockchain network where this pool exists.
    pub chain: SharedChain,
    /// The decentralized exchange protocol that created and manages this pool.
    pub dex: SharedDex,
    /// The blockchain address where the pool smart contract code is deployed.
    pub address: Address,
    /// The unique identifier for this pool across all pools on the DEX.
    pub pool_identifier: PoolIdentifier,
    /// The instrument ID for the pool.
    pub instrument_id: InstrumentId,
    /// The block number when this pool was created on the blockchain.
    pub creation_block: u64,
    /// The first token in the trading pair.
    pub token0: Token,
    /// The second token in the trading pair.
    pub token1: Token,
    /// The trading fee tier used by the pool expressed in hundred-thousandths
    /// (1e-6) of one unit – identical to Uniswap-V3’s fee representation.
    ///
    /// Examples:
    /// • `500`   →  0.05 %  (5 bps)
    /// • `3_000` →  0.30 %  (30 bps)
    /// • `10_000`→  1.00 %
    pub fee: Option<u32>,
    /// The minimum tick spacing for positions in concentrated liquidity AMMs.
    pub tick_spacing: Option<u32>,
    /// The initial tick when the pool was first initialized.
    pub initial_tick: Option<i32>,
    /// The initial square root price when the pool was first initialized.
    pub initial_sqrt_price_x96: Option<U160>,
    /// The hooks contract address for Uniswap V4 pools.
    /// For V2/V3 pools, this will be None. For V4, it contains the hooks contract address.
    pub hooks: Option<Address>,
    /// UNIX timestamp (nanoseconds) when the instance was created.
    pub ts_init: UnixNanos,
}

/// A thread-safe shared pointer to a `Pool`, enabling efficient reuse across multiple components.
pub type SharedPool = Arc<Pool>;

impl Pool {
    /// Creates a new [`Pool`] instance with the specified properties.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        chain: SharedChain,
        dex: SharedDex,
        address: Address,
        pool_identifier: PoolIdentifier,
        creation_block: u64,
        token0: Token,
        token1: Token,
        fee: Option<u32>,
        tick_spacing: Option<u32>,
        ts_init: UnixNanos,
    ) -> Self {
        let instrument_id = Self::create_instrument_id(chain.name, &dex, pool_identifier.as_str());

        Self {
            chain,
            dex,
            address,
            pool_identifier,
            instrument_id,
            creation_block,
            token0,
            token1,
            fee,
            tick_spacing,
            initial_tick: None,
            initial_sqrt_price_x96: None,
            hooks: None,
            ts_init,
        }
    }

    /// Returns a formatted string representation of the pool for display purposes.
    pub fn to_full_spec_string(&self) -> String {
        format!(
            "{}/{}-{}.{}",
            self.token0.symbol,
            self.token1.symbol,
            self.fee.unwrap_or(0),
            self.instrument_id.venue
        )
    }

    /// Initializes the pool with the initial tick and square root price.
    ///
    /// This method should be called when an Initialize event is processed
    /// to set the initial price and tick values for the pool.
    ///
    /// # Panics
    ///
    /// Panics if the provided tick does not match the tick calculated from sqrt_price_x96.
    pub fn initialize(&mut self, sqrt_price_x96: U160, tick: i32) {
        let calculated_tick = get_tick_at_sqrt_ratio(sqrt_price_x96);

        assert_eq!(
            tick, calculated_tick,
            "Provided tick {tick} does not match calculated tick {calculated_tick} for sqrt_price_x96 {sqrt_price_x96}",
        );

        self.initial_sqrt_price_x96 = Some(sqrt_price_x96);
        self.initial_tick = Some(tick);
    }

    /// Sets the hooks contract address for this pool.
    ///
    /// This is typically called for Uniswap V4 pools that have hooks enabled.
    pub fn set_hooks(&mut self, hooks: Address) {
        self.hooks = Some(hooks);
    }

    pub fn create_instrument_id(
        chain: Blockchain,
        dex: &Dex,
        pool_identifier: &str,
    ) -> InstrumentId {
        let symbol = Symbol::new(pool_identifier);
        let venue = Venue::new(format!("{}:{}", chain, dex.name));
        InstrumentId::new(symbol, venue)
    }

    /// Returns the base token based on token priority.
    ///
    /// The base token is the asset being traded/priced. Token priority determines
    /// which token becomes base vs quote:
    /// - Lower priority number (1=stablecoin, 2=native, 3=other) = quote token
    /// - Higher priority number = base token
    pub fn get_base_token(&self) -> &Token {
        let priority0 = self.token0.get_token_priority();
        let priority1 = self.token1.get_token_priority();

        if priority0 < priority1 {
            &self.token1
        } else {
            &self.token0
        }
    }

    /// Returns the quote token based on token priority.
    ///
    /// The quote token is the pricing currency. Token priority determines
    /// which token becomes quote:
    /// - Lower priority number (1=stablecoin, 2=native, 3=other) = quote token
    pub fn get_quote_token(&self) -> &Token {
        let priority0 = self.token0.get_token_priority();
        let priority1 = self.token1.get_token_priority();

        if priority0 < priority1 {
            &self.token0
        } else {
            &self.token1
        }
    }

    /// Returns whether the base/quote order is inverted from token0/token1 order.
    ///
    /// # Returns
    /// - `true` if base=token1, quote=token0 (inverted from pool order)
    /// - `false` if base=token0, quote=token1 (matches pool order)
    ///
    /// # Use Case
    /// This is useful for knowing whether prices need to be inverted when
    /// converting from pool convention (token1/token0) to market convention (base/quote).
    pub fn is_base_quote_inverted(&self) -> bool {
        let priority0 = self.token0.get_token_priority();
        let priority1 = self.token1.get_token_priority();

        // Inverted when token0 has higher priority (becomes quote instead of base)
        priority0 < priority1
    }
}

impl Display for Pool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Pool(instrument_id={}, dex={}, fee={}, address={})",
            self.instrument_id,
            self.dex.name,
            self.fee
                .map_or("None".to_string(), |fee| format!("fee={fee}, ")),
            self.address
        )
    }
}

impl HasTsInit for Pool {
    fn ts_init(&self) -> UnixNanos {
        self.ts_init
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use rstest::rstest;

    use super::*;
    use crate::defi::{
        chain::chains,
        dex::{AmmType, Dex, DexType},
        token::Token,
    };

    #[rstest]
    fn test_pool_constructor_and_methods() {
        let chain = Arc::new(chains::ETHEREUM.clone());
        let dex = Dex::new(
            chains::ETHEREUM.clone(),
            DexType::UniswapV3,
            "0x1F98431c8aD98523631AE4a59f267346ea31F984",
            0,
            AmmType::CLAMM,
            "PoolCreated(address,address,uint24,int24,address)",
            "Swap(address,address,int256,int256,uint160,uint128,int24)",
            "Mint(address,address,int24,int24,uint128,uint256,uint256)",
            "Burn(address,int24,int24,uint128,uint256,uint256)",
            "Collect(address,address,int24,int24,uint128,uint128)",
        );

        let token0 = Token::new(
            chain.clone(),
            "0xA0b86a33E6441b936662bb6B5d1F8Fb0E2b57A5D"
                .parse()
                .unwrap(),
            "Wrapped Ether".to_string(),
            "WETH".to_string(),
            18,
        );

        let token1 = Token::new(
            chain.clone(),
            "0xdAC17F958D2ee523a2206206994597C13D831ec7"
                .parse()
                .unwrap(),
            "Tether USD".to_string(),
            "USDT".to_string(),
            6,
        );

        let pool_address: Address = "0x11b815efB8f581194ae79006d24E0d814B7697F6"
            .parse()
            .unwrap();
        let pool_identifier = PoolIdentifier::from_address(pool_address);
        let ts_init = UnixNanos::from(1_234_567_890_000_000_000u64);

        let pool = Pool::new(
            chain.clone(),
            Arc::new(dex),
            pool_address,
            pool_identifier,
            12345678,
            token0,
            token1,
            Some(3000),
            Some(60),
            ts_init,
        );

        assert_eq!(pool.chain.chain_id, chain.chain_id);
        assert_eq!(pool.dex.name, DexType::UniswapV3);
        assert_eq!(pool.address, pool_address);
        assert_eq!(pool.creation_block, 12345678);
        assert_eq!(pool.token0.symbol, "WETH");
        assert_eq!(pool.token1.symbol, "USDT");
        assert_eq!(pool.fee.unwrap(), 3000);
        assert_eq!(pool.tick_spacing.unwrap(), 60);
        assert_eq!(pool.ts_init, ts_init);
        assert_eq!(
            pool.instrument_id.symbol.as_str(),
            "0x11b815efB8f581194ae79006d24E0d814B7697F6"
        );
        assert_eq!(pool.instrument_id.venue.as_str(), "Ethereum:UniswapV3");
        // We expect WETH to be a base and USDT a quote token
        assert_eq!(pool.get_base_token().symbol, "WETH");
        assert_eq!(pool.get_quote_token().symbol, "USDT");
        assert!(!pool.is_base_quote_inverted());
        assert_eq!(
            pool.to_full_spec_string(),
            "WETH/USDT-3000.Ethereum:UniswapV3"
        );
    }

    #[rstest]
    fn test_pool_instrument_id_format() {
        let chain = Arc::new(chains::ETHEREUM.clone());
        let factory_address = "0x1F98431c8aD98523631AE4a59f267346ea31F984";

        let dex = Dex::new(
            chains::ETHEREUM.clone(),
            DexType::UniswapV3,
            factory_address,
            0,
            AmmType::CLAMM,
            "PoolCreated(address,address,uint24,int24,address)",
            "Swap(address,address,int256,int256,uint160,uint128,int24)",
            "Mint(address,address,int24,int24,uint128,uint256,uint256)",
            "Burn(address,int24,int24,uint128,uint256,uint256)",
            "Collect(address,address,int24,int24,uint128,uint128)",
        );

        let token0 = Token::new(
            chain.clone(),
            "0xA0b86a33E6441b936662bb6B5d1F8Fb0E2b57A5D"
                .parse()
                .unwrap(),
            "Wrapped Ether".to_string(),
            "WETH".to_string(),
            18,
        );

        let token1 = Token::new(
            chain.clone(),
            "0xdAC17F958D2ee523a2206206994597C13D831ec7"
                .parse()
                .unwrap(),
            "Tether USD".to_string(),
            "USDT".to_string(),
            6,
        );

        let pool_address = "0x11b815efB8f581194ae79006d24E0d814B7697F6"
            .parse()
            .unwrap();
        let pool = Pool::new(
            chain,
            Arc::new(dex),
            pool_address,
            PoolIdentifier::from_address(pool_address),
            0,
            token0,
            token1,
            Some(3000),
            Some(60),
            UnixNanos::default(),
        );

        assert_eq!(
            pool.instrument_id.to_string(),
            "0x11b815efB8f581194ae79006d24E0d814B7697F6.Ethereum:UniswapV3"
        );
    }
}