### Rust: Insert and Get Key-Value from BTreeMap Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/type Demonstrates how to create a BTreeMap, insert a key-value pair, and retrieve the value associated with a key. It shows basic usage of `insert` and `get` methods. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Rust: Implementing DataClient Start Method Source: https://nautilustrader.io/docs/core-latest/src/nautilus_databento/data Provides the implementation for the `start` method of the `DatabentoDataClient`. This method is responsible for initiating the client's operations. Currently, it only logs a debug message. ```Rust /// Starts the data client. /// /// # Errors /// /// Returns an error if the client fails to start. fn start(&mut self) -> anyhow::Result<()> { tracing::debug!("Starting"); Ok(()) } ``` -------------------------------- ### Start Components in Rust Source: https://nautilustrader.io/docs/core-latest/src/nautilus_system/trader Initiates the startup sequence for all registered actors, strategies, and execution algorithms within the Trader component. It iterates through the stored IDs and calls the respective start functions, logging the progress. Dependencies include the `log` crate for debugging output and `anyhow::Result` for error handling. ```rust pub fn start_components(&mut self) -> anyhow::Result<()> { // Start actors (retrieved from global registry) for actor_id in &self.actor_ids { log::debug!("Starting actor '{}'", actor_id); start_component(&actor_id.inner())?; } for strategy_id in &mut self.strategies.keys() { log::debug!("Starting strategy '{}'", strategy_id); // strategy.start()?; // TODO: TBD } for exec_algorithm_id in &mut self.exec_algorithms.keys() { log::debug!("Starting execution algorithm '{}'", exec_algorithm_id); // exec_algorithm.start()?; // TODO: TBD } Ok(()) } ``` -------------------------------- ### Start Nautilus System Kernel Asynchronously - Rust Source: https://nautilustrader.io/docs/core-latest/src/nautilus_system/kernel Initiates the startup sequence for the Nautilus system kernel asynchronously. This involves starting engines, initializing the trader, connecting clients, and logging the start event. ```rust pub async fn start_async(&mut self) { log::info!("Starting"); self.start_engines(); log::info!("Initializing trader"); if let Err(e) = self.trader.initialize() { log::error!("Error initializing trader: {e:?}"); return; } log::info!("Connecting clients..."); if let Err(e) = self.connect_clients().await { log::error!("Error connecting clients: {e:?}"); } log::info!("Clients connected"); if let Err(e) = self.trader.start() { log::error!("Error starting trader: {e:?}"); } self.ts_started = Some(self.clock.borrow().timestamp_ns()); log::info!("Started"); } ``` -------------------------------- ### Start Component in Registry (Rust) Source: https://nautilustrader.io/docs/core-latest/src/nautilus_common/component Safely calls the `start()` method on a component identified by its ID in the global component registry. It retrieves the component, obtains mutable access via `UnsafeCell`, and executes `start()`. Returns an error if the component is not found. ```rust pub fn start_component(id: &Ustr) -> anyhow::Result<()> { if let Some(component_ref) = get_component_registry().get(id) { // SAFETY: We have exclusive access to the component and are calling start() which takes &mut self unsafe { let component = &mut *component_ref.get(); component.start() } } else { anyhow::bail!("Component '{id}' not found in global registry"); } } ``` -------------------------------- ### Start Execution Client Method Source: https://nautilustrader.io/docs/core-latest/nautilus_execution/client/trait Initiates the execution client, establishing necessary connections and preparing it for order processing. Errors are returned if the client fails to start. ```rust fn start(&mut self) -> Result<()> ``` -------------------------------- ### Rust BTreeMap: Get Value Example Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/type Illustrates the `get` method for Rust's `BTreeMap`, which returns an `Option<&V>` reference to the value associated with a given key. The key can be a borrowed form of the map's key type, provided the ordering matches. ```Rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "apple"); assert_eq!(map.get(&1), Some(&"apple")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Initialize CoinbaseIntxWebSocketClient Source: https://nautilustrader.io/docs/core-latest/nautilus_coinbase_intx/websocket/client/struct Provides methods to create new instances of the CoinbaseIntxWebSocketClient. It supports initialization with explicit parameters like URL and API credentials, or through environment variables for convenience. Errors may occur if necessary environment variables are missing or invalid. ```rust pub fn new( url: Option, api_key: Option, api_secret: Option, api_passphrase: Option, heartbeat: Option, ) -> Result ``` ```rust pub fn from_env() -> Result ``` -------------------------------- ### Get Last Started Timestamp (ns) - Rust Source: https://nautilustrader.io/docs/core-latest/src/nautilus_system/kernel Returns an optional UNIX timestamp in nanoseconds indicating when the kernel was last started. Returns None if never started. ```rust pub const fn ts_started(&self) -> Option { self.ts_started } ``` -------------------------------- ### BacktestExecutionClient Initialization Source: https://nautilustrader.io/docs/core-latest/nautilus_backtest/execution_client/struct Details on how to initialize the BacktestExecutionClient for backtesting environments. This constructor sets up the client with necessary components for simulated trading. ```APIDOC ## `new` - BacktestExecutionClient Constructor ### Description Initializes a new instance of the `BacktestExecutionClient` for backtesting trading operations. This constructor takes various dependencies required for simulating exchange interactions and managing trading state. ### Method `pub fn new` ### Parameters - **trader_id** (`TraderId`) - Required - The identifier for the trader. - **account_id** (`AccountId`) - Required - The identifier for the trading account. - **exchange** (`Rc>`) - Required - A reference-counted, interior-mutable reference to the simulated exchange. - **cache** (`Rc>`) - Required - A reference-counted, interior-mutable reference to the cache. - **clock** (`Rc>`) - Required - A reference-counted, interior-mutable reference to the clock used for timekeeping. - **routing** (`Option`) - Optional - A boolean flag to indicate if routing is enabled. - **frozen_account** (`Option`) - Optional - A boolean flag to indicate if the account is frozen. ### Returns - `Self` - A new instance of `BacktestExecutionClient`. ``` -------------------------------- ### HyperSyncClient Initialization Source: https://nautilustrader.io/docs/core-latest/nautilus_blockchain/hypersync/client/struct Creates a new HyperSyncClient instance. ```APIDOC ## POST /hypersync/client/new ### Description Creates a new `HyperSyncClient` instance for the given chain and message sender. ### Method POST ### Endpoint /hypersync/client/new ### Parameters #### Request Body - **chain** (SharedChain) - Required - The shared chain configuration. - **tx** (Option>) - Optional - A sender for blockchain messages. ``` -------------------------------- ### Get Start Time from Metadata (Rust) Source: https://nautilustrader.io/docs/core-latest/src/nautilus_model/data/mod Retrieves an Option parsed from the metadata's 'start' field. Panics if metadata is missing or the 'start' value is invalid. Requires `UnixNanos` to support parsing from a string. ```Rust pub fn start(&self) -> Option { let metadata = self.metadata.as_ref()?; let start_str = metadata.get("start")?; Some(UnixNanos::from_str(start_str).expect("Invalid `UnixNanos` for 'start'")) } ``` -------------------------------- ### LiveNode Start and Run Source: https://nautilustrader.io/docs/core-latest/src/nautilus_live/python/node Methods to start and run the LiveNode, including signal handling for graceful shutdown. ```APIDOC ## LiveNode Start and Run ### Description Methods to initiate the operation of the `LiveNode` and manage its execution lifecycle, including graceful shutdown via signal handling. ### Method - `LiveNode.start() -> PyResult<()>`: Starts the node in a non-blocking manner. - `LiveNode.run(py: Python) -> PyResult<()>`: Runs the node and sets up signal handlers for graceful shutdown. ### Endpoint N/A (Python methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Using start (non-blocking) node.start() # Using run (blocking with signal handling) node.run(py) ``` ### Response #### Success Response (200) - **()** - An empty tuple indicating successful execution. #### Response Example (No explicit response body for these methods, success is indicated by the absence of an error). ### Error Handling - **PyRuntimeError**: Raised if the node is already running or if an internal error occurs during start or run. - **PyValueError**: Potentially raised during signal handler setup if invalid signals are encountered. ``` -------------------------------- ### CoinbaseIntxWebSocketClient Initialization Source: https://nautilustrader.io/docs/core-latest/nautilus_coinbase_intx/websocket/client/struct Methods for creating and initializing the CoinbaseIntxWebSocketClient. ```APIDOC ## `CoinbaseIntxWebSocketClient` Initialization ### `new` #### Description Creates a new `CoinbaseIntxWebSocketClient` instance. #### Method `pub fn new(url: Option, api_key: Option, api_secret: Option, api_passphrase: Option, heartbeat: Option) -> Result` #### Parameters - `url` (Option) - Optional - The WebSocket URL for the connection. - `api_key` (Option) - Optional - The API key for authentication. - `api_secret` (Option) - Optional - The API secret for authentication. - `api_passphrase` (Option) - Optional - The API passphrase for authentication. - `heartbeat` (Option) - Optional - The heartbeat interval in seconds. #### Errors Returns an error if required environment variables are missing or invalid. ### `from_env` #### Description Creates a new authenticated `CoinbaseIntxWebSocketClient` using environment variables and the default Coinbase International production websocket URL. #### Method `pub fn from_env() -> Result` #### Errors Returns an error if required environment variables are missing or invalid. ``` -------------------------------- ### get Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/type Retrieves a reference to the value associated with a given key from the BTreeMap. ```APIDOC ## GET /websites/nautilustrader_io_core-latest/get ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type. ### Method GET ### Endpoint /websites/nautilustrader_io_core-latest/get ### Parameters #### Query Parameters - **key** (&Q) - Required - The key to look up in the map. ### Request Example ```json { "key": "some_key" } ``` ### Response #### Success Response (200) - **Option<&V>** - An Option containing a reference to the value if the key is found, otherwise None. #### Response Example ```json { "value": "associated_value" } ``` ``` -------------------------------- ### Rust: Test Axum Router Setup Source: https://nautilustrader.io/docs/core-latest/src/nautilus_network/http Sets up a basic `axum` router for testing purposes. It defines routes for common HTTP methods like GET, POST, and PATCH, each returning a simple response. This router can be used to simulate a web server for integration tests. ```rust fn create_router() -> Router { Router::new() .route("/get", get(|| async { "hello-world!" })) .route("/post", post(|| async { StatusCode::OK })) .route("/patch", patch(|| async { StatusCode::OK })) } ``` -------------------------------- ### Rust: Test GET Request with InnerHttpClient Source: https://nautilustrader.io/docs/core-latest/src/nautilus_network/http This test case verifies the functionality of a GET request to the test server. It starts the test server, constructs the request URL, and uses `InnerHttpClient` to send a GET request. The assertions check for a successful response status and the expected body content. ```rust @tokio::test async fn test_get() { let addr = start_test_server().await.unwrap(); let url = format!("http://{addr}"); let client = InnerHttpClient::default(); let response = client .send_request(reqwest::Method::GET, format!("{url}/get"), None, None, None) .await .unwrap(); assert!(response.status.is_success()); assert_eq!(String::from_utf8_lossy(&response.body), "hello-world!"); } ``` -------------------------------- ### BacktestDataClient Initialization Source: https://nautilustrader.io/docs/core-latest/nautilus_backtest/data_client/struct Provides information on how to initialize the BacktestDataClient. ```APIDOC ## BacktestDataClient Data client implementation for backtesting market data operations. ### Constructor ```rust pub const fn new(client_id: ClientId, venue: Venue, cache: Rc>) -> Self ``` **Parameters** - **client_id** (ClientId) - The unique identifier for the data client. - **venue** (Venue) - The venue associated with the data client. - **cache** (Rc>) - A shared, mutable reference to the cache for storing data. ``` -------------------------------- ### BitmexWebSocketClient Initialization Source: https://nautilustrader.io/docs/core-latest/nautilus_bitmex/websocket/client/struct Methods for creating and initializing a BitmexWebSocketClient instance. ```APIDOC ## `new` ### Description Creates a new `BitmexWebSocketClient` instance. ### Method `pub fn new( url: Option, api_key: Option, api_secret: Option, account_id: Option, heartbeat: Option, ) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual) let client = BitmexWebSocketClient::new( Some("wss://testnet.bitmex.com/realtime".to_string()), Some("your_api_key".to_string()), Some("your_api_secret".to_string()), None, // account_id Some(30), // heartbeat in seconds ); ``` ### Response #### Success Response A new `BitmexWebSocketClient` instance. #### Response Example ```rust // Success is indicated by the Result type, no specific return value shown here. ``` #### Errors - Returns an error if only one of `api_key` or `api_secret` is provided (both or neither required). ``` ```APIDOC ## `from_env` ### Description Creates a new authenticated `BitmexWebSocketClient` using environment variables. ### Method `pub fn from_env() -> Result` ### Parameters None ### Request Example ```rust // Ensure BITMEX_API_KEY, BITMEX_API_SECRET, and BITMEX_ACCOUNT_ID environment variables are set. let client = BitmexWebSocketClient::from_env(); ``` ### Response #### Success Response A new authenticated `BitmexWebSocketClient` instance. #### Response Example ```rust // Success is indicated by the Result type, no specific return value shown here. ``` #### Errors - Returns an error if environment variables are not set or credentials are invalid. ``` -------------------------------- ### Get DashMap Length (Rust) Source: https://nautilustrader.io/docs/core-latest/nautilus_network/ratelimiter/type This example shows how to get the total number of key-value pairs currently stored in a DashMap. It inserts several items and then asserts that the map's length is correct. ```rust use dashmap::DashMap; let people = DashMap::new(); people.insert("Albin", 15); people.insert("Jones", 22); people.insert("Charlie", 27); assert_eq!(people.len(), 3); ``` -------------------------------- ### DataClientAdapter Initialization and Access Methods Source: https://nautilustrader.io/docs/core-latest/nautilus_data/client/struct Provides methods for creating a new DataClientAdapter instance and accessing its underlying DataClient. The `new` function initializes the adapter with essential parameters, while `get_client` returns a reference to the boxed DataClient. ```rust pub fn new( client_id: ClientId, venue: Option, handles_order_book_deltas: bool, handles_order_book_snapshots: bool, client: Box, ) -> Self { // ... implementation details ... } pub fn get_client(&self) -> &Box { // ... implementation details ... } ``` -------------------------------- ### Create CoinbaseIntxFixClient Instance Source: https://nautilustrader.io/docs/core-latest/nautilus_coinbase_intx/fix/client/struct Creates a new CoinbaseIntxFixClient instance with provided endpoint, API credentials, and portfolio ID. It may return an error if essential environment variables or parameters are not supplied. ```rust pub fn new( endpoint: Option, api_key: Option, api_secret: Option, api_passphrase: Option, portfolio_id: Option, ) -> Result ``` -------------------------------- ### Get Dataset Range Source: https://nautilustrader.io/docs/core-latest/src/nautilus_databento/python/historical Retrieves the start and end timestamps for a given dataset. ```APIDOC ## GET /datasets/{dataset}/range ### Description Retrieves the start and end timestamps for a given dataset. ### Method GET ### Endpoint `/datasets/{dataset}/range` ### Parameters #### Path Parameters - **dataset** (string) - Required - The name of the dataset to query. #### Query Parameters None #### Request Body None ### Request Example ```python start_end_times = client.get_dataset_range("MY_DATASET") print(f"Start: {start_end_times['start']}, End: {start_end_times['end']}") ``` ### Response #### Success Response (200) - **start** (datetime) - The start timestamp of the dataset. - **end** (datetime) - The end timestamp of the dataset. #### Response Example ```json { "start": "2023-01-01T00:00:00Z", "end": "2023-12-31T23:59:59Z" } ``` ``` -------------------------------- ### Start and Stop Trading Client - Rust Source: https://nautilustrader.io/docs/core-latest/src/nautilus_backtest/execution_client Functions to manage the lifecycle of the trading client. `start` sets the client as connected and logs a start message. `stop` sets the client as disconnected and logs a stop message. Both return a Result indicating success or failure. ```Rust fn start(&mut self) -> anyhow::Result<()> { self.is_connected = true; log::info!("Backtest execution client started"); Ok(()) } fn stop(&mut self) -> anyhow::Result<()> { self.is_connected = false; log::info!("Backtest execution client stopped"); Ok(()) } ``` -------------------------------- ### Get lower bound cursor in BTreeMap in Rust Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/type Demonstrates how to get a cursor pointing at the gap before the smallest key greater than the given bound. Requires std::collections::BTreeMap and the `btree_cursors` feature. This is a nightly-only experimental API. ```Rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let cursor = map.lower_bound(Bound::Included(&2)); assert_eq!(cursor.peek_prev(), Some((&1, &"a"))); assert_eq!(cursor.peek_next(), Some((&2, &"b"))); let cursor = map.lower_bound(Bound::Excluded(&2)); assert_eq!(cursor.peek_prev(), Some((&2, &"b"))); assert_eq!(cursor.peek_next(), Some((&3, &"c"))); let cursor = map.lower_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some((&1, &"a"))); ``` -------------------------------- ### Rust RiskEngine Initialization Source: https://nautilustrader.io/docs/core-latest/nautilus_risk/engine/struct Demonstrates the creation of a new RiskEngine instance. It requires configuration, portfolio data, a clock, and a cache to initialize the risk management system. ```rust pub fn new( config: RiskEngineConfig, portfolio: Portfolio, clock: Rc>, cache: Rc>, ) -> Self ``` -------------------------------- ### Start Engine Components Source: https://nautilustrader.io/docs/core-latest/src/nautilus_system/kernel Starts all engine components, beginning with the data engine. Placeholder comments indicate where methods for other engines would be called once available. ```Rust fn start_engines(&self) { self.data_engine.borrow_mut().start(); // TODO: Start other engines when methods are available } ``` -------------------------------- ### PostgresCopyHandler - Initialization Source: https://nautilustrader.io/docs/core-latest/nautilus_blockchain/cache/copy/struct Provides information on how to initialize the PostgresCopyHandler. ```APIDOC ## POST /postgres/copy/new ### Description Creates a new COPY handler with a reference to the database pool. ### Method POST ### Endpoint /postgres/copy/new ### Parameters #### Request Body - **pool** (PgPool) - Required - A reference to the PostgreSQL database pool. ### Request Example ```json { "pool": "" } ``` ### Response #### Success Response (200) - **PostgresCopyHandler** (object) - The initialized PostgresCopyHandler instance. #### Response Example ```json { "handler": "" } ``` ``` -------------------------------- ### Get Mutable Reference to Value in Rust BTreeMap Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/type Illustrates how to get a mutable reference to a value associated with a key in a BTreeMap using `get_mut`. This allows in-place modification of values. The key can be any borrowed form that matches the map's key ordering. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### Rust: BlockchainSubscriberActor on_start Logic Source: https://nautilustrader.io/docs/core-latest/src/node_test/node_test Implements the `on_start` method for the BlockchainSubscriberActor in Rust. This method is called when the actor starts and is responsible for setting up subscriptions to blockchain data. It subscribes to blocks for a given chain and to pool-related events (pool data, swaps, liquidity updates) for specified instrument IDs. It also sets up two timers for periodic actions. ```rust impl DataActor for BlockchainSubscriberActor { fn on_start(&mut self) -> anyhow::Result<()> { let client_id = self.config.client_id; self.subscribe_blocks(self.config.chain, Some(client_id), None); let pool_instrument_ids = self.config.pools.clone(); for instrument_id in pool_instrument_ids { self.subscribe_pool(instrument_id, Some(client_id), None); self.subscribe_pool_swaps(instrument_id, Some(client_id), None); self.subscribe_pool_liquidity_updates(instrument_id, Some(client_id), None); } self.clock().set_timer( "TEST-TIMER-1-SECOND", Duration::from_secs(1), None, None, None, Some(true), Some(false), )?; self.clock().set_timer( "TEST-TIMER-2-SECOND", Duration::from_secs(2), None, None, None, Some(true), Some(false), )?; Ok(()) } // ... other methods ``` -------------------------------- ### Instantiate SimulatedExchange Source: https://nautilustrader.io/docs/core-latest/nautilus_backtest/exchange/struct Creates a new SimulatedExchange instance with various configuration options. This constructor allows for detailed setup of trading parameters, including balances, leverage, and simulation modules. ```rust pub fn new( venue: Venue, oms_type: OmsType, account_type: AccountType, starting_balances: Vec, base_currency: Option, default_leverage: Decimal, leverages: HashMap, modules: Vec>, cache: Rc>, clock: Rc>, fill_model: FillModel, fee_model: FeeModelAny, book_type: BookType, latency_model: Option, bar_execution: Option, reject_stop_orders: Option, support_gtd_orders: Option, support_contingent_orders: Option, use_position_ids: Option, use_random_ids: Option, use_reduce_only: Option, use_message_queue: Option, allow_cash_borrowing: Option, frozen_account: Option, ) -> Result ``` -------------------------------- ### Get Previous Forex Session Start Time (Rust/Python) Source: https://nautilustrader.io/docs/core-latest/src/nautilus_trading/python/sessions Retrieves the start time of the previous Forex session. The input `time_now` must be timezone-aware (e.g., UTC). This function is exposed to Python via pyo3 and returns a PyResult, handling potential conversion errors. ```Rust #[pyfunction] #[pyo3(name = "fx_prev_start")] pub fn py_fx_prev_start(session: ForexSession, time_now: DateTime) -> PyResult> { Ok(fx_prev_start(session, time_now)) } ``` -------------------------------- ### Get and modify an entry in BTreeMap using entry() in Rust Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/type Demonstrates how to get a key's corresponding entry in a BTreeMap and modify it in-place using the `entry()` method. It counts the number of occurrences of letters in a vector. Requires the `std::collections::BTreeMap` module. ```Rust use std::collections::BTreeMap; let mut count: BTreeMap<&str, usize> = BTreeMap::new(); // count the number of occurrences of letters in the vec for x in ["a", "b", "a", "c", "a", "b"] { count.entry(x).and_modify(|curr| *curr += 1).or_insert(1); } assert_eq!(count["a"], 3); assert_eq!(count["b"], 2); assert_eq!(count["c"], 1); ``` -------------------------------- ### Rust: Portfolio Initialization and State Checks Source: https://nautilustrader.io/docs/core-latest/nautilus_portfolio/portfolio/struct Provides methods for creating a new Portfolio instance and checking its initialization status. The `new` function takes dependencies like cache, clock, and configuration. ```rust pub fn new( cache: Rc>, clock: Rc>, config: Option, ) -> Self ``` ```rust pub fn reset(&mut self) ``` ```rust pub fn is_initialized(&self) -> bool ``` -------------------------------- ### Get Dataset Range in Python using DatabentoHistoricalClient Source: https://nautilustrader.io/docs/core-latest/src/nautilus_databento/python/historical Retrieves the start and end timestamps for a given dataset from the Databento historical client. This function is asynchronous and returns a Python dictionary containing 'start' and 'end' values, or a PyException if an error occurs. ```python #[pyo3(name = "get_dataset_range")] fn py_get_dataset_range<'py>( &self, py: Python<'py>, dataset: String, ) -> PyResult> { let inner = self.inner.clone(); pyo3_async_runtimes::tokio::future_into_py(py, async move { let response = inner.get_dataset_range(&dataset).await; match response { Ok(res) => Python::with_gil(|py| { let dict = PyDict::new(py); dict.set_item("start", res.start)?; dict.set_item("end", res.end)?; dict.into_py_any(py) }), Err(e) => Err(PyErr::new::(format!( "Error handling response: {e}" ))), } }) } ``` -------------------------------- ### Initialize and Configure BacktestEngine in Rust Source: https://context7.com/context7/nautilustrader_io_core-latest/llms.txt Demonstrates how to initialize the BacktestEngine and add a simulated venue with detailed configuration options, including order management, account types, book types, starting balances, and various simulation parameters. This is essential for setting up backtesting environments. ```rust use nautilus_backtest::engine::BacktestEngine; use nautilus_backtest::config::BacktestEngineConfig; use nautilus_model::enums::{OmsType, AccountType, BookType}; use nautilus_model::types::{Money, Currency}; use nautilus_model::identifiers::Venue; use std::collections::HashMap; // Create backtest engine with configuration let config = BacktestEngineConfig::default(); let mut engine = BacktestEngine::new(config) .expect("Failed to initialize BacktestEngine"); // Add a simulated venue with starting balances let venue = Venue::new("BINANCE"); let starting_balances = vec![ Money::new(100000.0, Currency::USD()), Money::new(10.0, Currency::BTC()), ]; engine.add_venue( venue, OmsType::Netting, // Order management system type AccountType::Cash, // Cash or margin account BookType::L2_MBP, // Level 2 market by price order book starting_balances, // Initial account balances Some(Currency::USD()), // Base currency None, // Default leverage HashMap::new(), // Per-instrument leverage overrides vec![], // Simulation modules FillModel::default(), // Order fill simulation model FeeModelAny::default(), // Fee calculation model None, // Latency model Some(true), // Enable routing Some(false), // Reject stop orders Some(true), // Support GTD orders Some(true), // Support contingent orders Some(false), // Use position IDs Some(false), // Use random IDs Some(true), // Use reduce-only flag Some(false), // Use message queue Some(true), // Enable bar execution Some(false), // Bar adaptive high/low ordering Some(true), // Enable trade execution Some(false), // Allow cash borrowing Some(false), // Frozen account ).expect("Failed to add venue"); ``` -------------------------------- ### Initialize and Use LiveTimer in Rust Source: https://nautilustrader.io/docs/core-latest/src/nautilus_common/python/timer Initializes a LiveTimer with a specified interval, start and stop times, and a callback function. It then starts the timer and waits until it expires. This example assumes the existence of `get_atomic_clock_realtime`, `UnixNanos`, `NonZeroU64`, `TestTimeEventSender`, `LiveTimer`, and `wait_until` functionalities. ```Rust let clock = get_atomic_clock_realtime(); let start_time = UnixNanos::default(); let interval_ns = NonZeroU64::new(1).unwrap(); let stop_time = clock.get_time_ns(); let test_sender = Arc::new(TestTimeEventSender); let mut timer = LiveTimer::new( "TEST_TIMER".into(), interval_ns, start_time, Some(stop_time), callback, false, Some(test_sender), ); timer.start(); wait_until(|| timer.is_expired(), Duration::from_secs(2)); ``` -------------------------------- ### Get Missing Data Intervals (Rust) Source: https://nautilustrader.io/docs/core-latest/src/nautilus_persistence/python/catalog Retrieves missing time intervals for a data request within a specified start and end time. It accepts an optional instrument ID for filtering and returns a list of (start, end) timestamp tuples. Errors are mapped to PyIOError. ```rust /// Get missing time intervals for a data request. /// /// # Parameters /// /// - `start`: Start timestamp (nanoseconds since Unix epoch) /// - `end`: End timestamp (nanoseconds since Unix epoch) /// - `data_cls`: The data class name /// - `instrument_id`: Optional instrument ID filter /// /// # Returns /// /// Returns a list of (start, end) timestamp tuples representing missing intervals. #[pyo3(signature = (start, end, data_cls, instrument_id=None))] pub fn get_missing_intervals_for_request( &self, start: u64, end: u64, data_cls: &str, instrument_id: Option, ) -> PyResult> { self.inner .get_missing_intervals_for_request(start, end, data_cls, instrument_id) .map_err(|e| PyIOError::new_err(format!("Failed to get missing intervals: {e}"))) } ``` -------------------------------- ### Get Dataset Date Range - Rust Source: https://nautilustrader.io/docs/core-latest/src/nautilus_databento/historical Retrieves the date range (start and end dates) for a given dataset from the Databento API. This is an asynchronous operation that requires an active client connection. The result is a DatasetRange struct containing string representations of the start and end dates. ```rust /// Gets the date range for a specific dataset. /// /// # Errors /// /// Returns an error if the API request fails. pub async fn get_dataset_range(&self, dataset: &str) -> anyhow::Result { let mut client = self.inner.lock().await; let response = client ``` -------------------------------- ### NautilusKernelBuilder Initialization and Configuration Source: https://nautilustrader.io/docs/core-latest/nautilus_system/builder/struct This section covers the initialization of the NautilusKernelBuilder and its various configuration methods for building a NautilusKernel. ```APIDOC ## NautilusKernelBuilder Builder for constructing a `NautilusKernel` with a fluent API. Provides a convenient way to configure and build a kernel instance with optional components and settings. ### `NautilusKernelBuilder::new()` Creates a new `NautilusKernelBuilder` with required parameters. #### Parameters - **name** (String) - Required - The name of the kernel. - **trader_id** (TraderId) - Required - The ID of the trader. - **environment** (Environment) - Required - The environment for the kernel. ### `NautilusKernelBuilder::with_instance_id()` Set the instance ID for the kernel. #### Parameters - **instance_id** (UUID4) - Required - The instance ID for the kernel. ### `NautilusKernelBuilder::with_load_state()` Configure whether to load state on startup. #### Parameters - **load_state** (bool) - Required - Whether to load state. ### `NautilusKernelBuilder::with_save_state()` Configure whether to save state on shutdown. #### Parameters - **save_state** (bool) - Required - Whether to save state. ### `NautilusKernelBuilder::with_logging_config()` Set the logging configuration. #### Parameters - **config** (LoggerConfig) - Required - The logging configuration. ### `NautilusKernelBuilder::with_timeout_connection()` Set the connection timeout in seconds. #### Parameters - **timeout_secs** (u64) - Required - The connection timeout in seconds. ### `NautilusKernelBuilder::with_timeout_reconciliation()` Set the reconciliation timeout in seconds. #### Parameters - **timeout_secs** (u64) - Required - The reconciliation timeout in seconds. ### `NautilusKernelBuilder::with_timeout_portfolio()` Set the portfolio initialization timeout in seconds. #### Parameters - **timeout_secs** (u64) - Required - The portfolio initialization timeout in seconds. ### `NautilusKernelBuilder::with_timeout_disconnection()` Set the disconnection timeout in seconds. #### Parameters - **timeout_secs** (u64) - Required - The disconnection timeout in seconds. ### `NautilusKernelBuilder::with_delay_post_stop()` Set the post-stop delay in seconds. #### Parameters - **delay_secs** (u64) - Required - The post-stop delay in seconds. ### `NautilusKernelBuilder::with_timeout_shutdown()` Set the shutdown timeout in seconds. #### Parameters - **timeout_secs** (u64) - Required - The shutdown timeout in seconds. ### `NautilusKernelBuilder::with_cache_config()` Set the cache configuration. #### Parameters - **config** (CacheConfig) - Required - The cache configuration. ### `NautilusKernelBuilder::with_data_engine_config()` Set the data engine configuration. #### Parameters - **config** (DataEngineConfig) - Required - The data engine configuration. ### `NautilusKernelBuilder::with_risk_engine_config()` Set the risk engine configuration. #### Parameters - **config** (RiskEngineConfig) - Required - The risk engine configuration. ### `NautilusKernelBuilder::with_exec_engine_config()` Set the execution engine configuration. #### Parameters - **config** (ExecutionEngineConfig) - Required - The execution engine configuration. ### `NautilusKernelBuilder::with_portfolio_config()` Set the portfolio configuration. #### Parameters - **config** (PortfolioConfig) - Required - The portfolio configuration. ### `NautilusKernelBuilder::build()` Build the `NautilusKernel` with the configured settings. #### Errors Returns an error if kernel initialization fails. #### Response ##### Success Response (200) - **NautilusKernel** (Result) - The constructed NautilusKernel instance or an error. ### `NautilusKernelBuilder::default()` Create a default builder with minimal configuration for testing/development. ``` -------------------------------- ### Rust: Start TimeBarAggregator and Schedule Alerts Source: https://nautilustrader.io/docs/core-latest/src/nautilus_data/aggregation Starts the TimeBarAggregator by scheduling periodic bar builds on the clock. It calculates the initial start time, adjusts for the bar build delay, and sets time alerts using the provided callback. For monthly bars, it calculates the alert time based on the step interval and expects the clock to trigger the callback accordingly. Errors can occur if timer setup fails. ```rust impl TimeBarAggregator where H: FnMut(Bar) + 'static, { // ... (previous methods) /// Starts the time bar aggregator, scheduling periodic bar builds on the clock. /// /// # Errors /// /// Returns an error if setting up the underlying clock timer fails. /// /// # Panics /// /// Panics if the underlying clock timer registration fails. pub fn start(&mut self, callback: NewBarCallback) -> anyhow::Result<()> { let now = self.clock.borrow().utc_now(); let mut start_time = get_time_bar_start(now, &self.bar_type(), self.time_bars_origin_offset); if start_time == now { self.skip_first_non_full_bar = false; } start_time += TimeDelta::microseconds(self.bar_build_delay as i64); let spec = &self.bar_type().spec(); let start_time_ns = UnixNanos::from(start_time); if spec.aggregation == BarAggregation::Month { let step = spec.step.get() as u32; let alert_time_ns = add_n_months_nanos(start_time_ns, step).expect(FAILED); self.clock .borrow_mut() .set_time_alert_ns(&self.timer_name, alert_time_ns, Some(callback.into()), None) .expect(FAILED); } else { // (logic for other interval types would follow here) } Ok(()) } } ``` -------------------------------- ### Initialize BaseExecutionClient Source: https://nautilustrader.io/docs/core-latest/nautilus_execution/client/base/struct Constructs a new BaseExecutionClient instance with the provided parameters. It requires identifiers, venue and OMS types, account details, currency, and dependencies like a clock and cache. This is the primary method for creating an execution client. ```rust pub const fn new( trader_id: TraderId, client_id: ClientId, venue: Venue, oms_type: OmsType, account_id: AccountId, account_type: AccountType, base_currency: Option, clock: Rc>, cache: Rc>, ) -> Self ``` -------------------------------- ### Setup Axum Test Server Source: https://nautilustrader.io/docs/core-latest/src/nautilus_testkit/files Sets up a basic Axum web server for testing purposes. It binds to a random local port and configures a route that returns a specified status code and response body. This function is useful for integration tests involving HTTP requests. ```rust async fn setup_test_server( server_content: Option, status_code: StatusCode, ) -> SocketAddr { let server_content = Arc::new(server_content); let server_content_clone = server_content.clone(); let app = Router::new().route( "/testfile.txt", get(move || { let server_content = server_content_clone.clone(); async move { let response_body = match &*server_content { Some(content) => content.clone(), None => "File not found".to_string(), }; (status_code, response_body) } }), ); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); task::spawn(async move { serve(listener, app).await.unwrap(); }); sleep(Duration::from_millis(100)).await; // Allow server to start addr } ``` -------------------------------- ### Rust Arc weak_count Example Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/analyzer/type Shows how to get the number of Weak references pointing to the same allocation as the given Arc. Note that this count can change concurrently. ```rust use std::sync::Arc; let five = Arc::new(5); let _weak_five = Arc::downgrade(&five); // This assertion is deterministic because we haven't shared // the `Arc` or `Weak` between threads. assert_eq!(1, Arc::weak_count(&five)); ``` -------------------------------- ### Get Next Forex Session Start Time in Python Source: https://nautilustrader.io/docs/core-latest/src/nautilus_trading/python/sessions This Python function, exposed via Rust's `pyo3`, calculates and returns the next start time of a given Forex session in UTC. The input `time_now` must be timezone-aware, using standard `datetime.timezone` objects. It will return a `PyErr` if any conversion or calculation errors occur. ```rust /// Returns the next session start time in UTC. /// /// The `time_now` must be timezone-aware with its tzinfo set to a built-in `datetime.timezone` /// (e.g. `datetime.timezone.utc`). Third-party tzinfo objects (like those from `pytz`) are not supported. /// /// # Errors /// /// Returns a `PyErr` if an error occurs during session conversion or value conversion to Python. #[pyfunction] #[pyo3(name = "fx_next_start")] pub fn py_fx_next_start(session: ForexSession, time_now: DateTime) -> PyResult> { Ok(fx_next_start(session, time_now)) } ``` -------------------------------- ### PortfolioAnalyzer Initialization and Statistic Registration (Rust) Source: https://nautilustrader.io/docs/core-latest/src/nautilus_analysis/analyzer Demonstrates the creation of a PortfolioAnalyzer and the registration of various default performance statistics. It shows how to initialize the analyzer and add statistics like MaxWinner, SharpeRatio, and WinRate. ```rust impl Default for PortfolioAnalyzer { /// Creates a new default [`PortfolioAnalyzer`] instance. fn default() -> Self { let mut analyzer = Self::new(); analyzer.register_statistic(Arc::new(MaxWinner {})); analyzer.register_statistic(Arc::new(AvgWinner {})); analyzer.register_statistic(Arc::new(MinWinner {})); analyzer.register_statistic(Arc::new(MinLoser {})); analyzer.register_statistic(Arc::new(MaxLoser {})); analyzer.register_statistic(Arc::new(Expectancy {})); analyzer.register_statistic(Arc::new(WinRate {})); analyzer.register_statistic(Arc::new(ReturnsVolatility::new(None))); analyzer.register_statistic(Arc::new(ReturnsAverage {})); analyzer.register_statistic(Arc::new(ReturnsAverageLoss {})); analyzer.register_statistic(Arc::new(ReturnsAverageWin {})); analyzer.register_statistic(Arc::new(SharpeRatio::new(None))); analyzer.register_statistic(Arc::new(SortinoRatio::new(None))); analyzer.register_statistic(Arc::new(ProfitFactor {})); analyzer.register_statistic(Arc::new(RiskReturnRatio {})); analyzer.register_statistic(Arc::new(LongRatio::new(None))); analyzer } } ``` ```rust impl PortfolioAnalyzer { /// Creates a new [`PortfolioAnalyzer`] instance. /// /// Starts with empty state. #[must_use] pub fn new() -> Self { Self { statistics: HashMap::new(), account_balances_starting: HashMap::new(), account_balances: HashMap::new(), positions: Vec::new(), realized_pnls: HashMap::new(), returns: BTreeMap::new(), } } /// Registers a new portfolio statistic for calculation. pub fn register_statistic(&mut self, statistic: Statistic) { self.statistics.insert(statistic.name(), statistic); } /// Removes a specific statistic from calculation. pub fn deregister_statistic(&mut self, statistic: Statistic) { self.statistics.remove(&statistic.name()); } /// Removes all registered statistics. pub fn deregister_statistics(&mut self) { ``` -------------------------------- ### PortfolioAnalyzer Initialization and State Management Source: https://nautilustrader.io/docs/core-latest/nautilus_analysis/analyzer/struct Provides methods for creating, resetting, and managing the state of the PortfolioAnalyzer. This includes initializing a new analyzer, resetting all analysis data, and handling currency tracking. ```rust pub fn new() -> Self Resets all analysis data to initial state. pub fn reset(&mut self) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.