======================== CODE SNIPPETS ======================== TITLE: Download and Load Sample Data for NautilusTrader DESCRIPTION: This command sequence updates package lists, installs curl, and then downloads and executes a Python script to load sample historical data into the Nautilus persistence format (Parquet). This prepares the necessary data for backtesting examples. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: Shell CODE: ``` !apt-get update && apt-get install curl -y !curl https://raw.githubusercontent.com/nautechsystems/nautilus_data/main/nautilus_data/hist_data_to_catalog.py | python - ``` ---------------------------------------- TITLE: Install NautilusTrader Development Dependencies DESCRIPTION: Instructions for installing all necessary development and test dependencies for the NautilusTrader project. It provides options for a full installation using `uv` or `make`, and a faster debug mode installation for frequent iteration. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: Shell CODE: ``` uv sync --active --all-groups --all-extras ``` LANGUAGE: Make CODE: ``` make install ``` LANGUAGE: Make CODE: ``` make install-debug ``` ---------------------------------------- TITLE: Install Rust Nightly Toolchain for Faster Builds DESCRIPTION: Commands to install and configure the Rust nightly toolchain, including `rust-analyzer`, for improved build times and IDE checks. It also shows how to reset to the stable toolchain after configuration. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: bash CODE: ``` rustup install nightly rustup override set nightly rustup component add rust-analyzer # install nightly lsp rustup override set stable # reset to stable ``` ---------------------------------------- TITLE: Start All Nautilus Docker Services DESCRIPTION: Command to start all services defined in the `.docker/docker-compose.yml` file, bootstrapping the Nautilus working environment in detached mode. This includes services like Postgres, Redis, and PgAdmin. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: docker-compose CODE: ``` docker-compose up -d ``` ---------------------------------------- TITLE: Install Pre-commit Hooks DESCRIPTION: Command to set up the pre-commit hook, which automatically runs various checks, auto-formatters, and linting tools before each commit, ensuring code quality and consistency. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: Shell CODE: ``` pre-commit install ``` ---------------------------------------- TITLE: Example Markdown Table Structure DESCRIPTION: Illustrates the recommended structure and content for Markdown tables, including guidelines for column alignment, spacing, notes, descriptions, and support indicators. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/docs LANGUAGE: Markdown CODE: ``` | Order Type | Spot | Margin | USDT Futures | Coin Futures | Notes | |------------------------|------|--------|--------------|--------------|-------------------------| | `MARKET` | ✓ | ✓ | ✓ | ✓ | | | `STOP_MARKET` | - | ✓ | ✓ | ✓ | Not supported for Spot. | | `MARKET_IF_TOUCHED` | - | - | ✓ | ✓ | Futures only. | ``` ---------------------------------------- TITLE: Install NautilusTrader from Downloaded GitHub Wheel DESCRIPTION: Installs a NautilusTrader binary wheel file (.whl) downloaded from a GitHub release using pip. This is an alternative installation method for pre-built binaries. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` pip install .whl ``` ---------------------------------------- TITLE: start Component Method DESCRIPTION: Starts the component. Exceptions during `on_start()` are logged and re-raised, leaving the component in a `STARTING` state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` Method: start(self) -> void Warnings: - Do not override. If the component is not in a valid state for this method, its state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: Start Component: start(self) -> void DESCRIPTION: Start the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/betfair LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Start Component Method DESCRIPTION: Starts the component. While executing on_start(), any exception will be logged and re-raised, then the component will remain in a `STARTING` state. A general warning advises against overriding this method. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/bybit LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: API: start Method DESCRIPTION: Starts the component. While executing on_start() any exception will be logged and re-raised, then the component will remain in a STARTING state. This method should not be overridden. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Start Specific Nautilus Docker Service DESCRIPTION: Command to start a specific service (e.g., `postgres`) from the `.docker/docker-compose.yml` file in detached mode. This is useful for running only necessary components for development or testing. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: docker-compose CODE: ``` docker-compose up -d postgres ``` ---------------------------------------- TITLE: Install Nautilus CLI via Makefile DESCRIPTION: Command to install the Nautilus CLI tool using a Makefile target. This leverages `cargo install` internally to place the `nautilus` binary in the system's PATH, assuming Rust's `cargo` is configured. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: makefile CODE: ``` make install-cli ``` ---------------------------------------- TITLE: Install NautilusTrader with Binance Support DESCRIPTION: Instructions on how to install the NautilusTrader library with support for Binance integration using pip, or how to build from source with all extras using uv. SOURCE: https://nautilustrader.io/docs/latest/integrations/binance LANGUAGE: Shell CODE: ``` pip install --upgrade "nautilus_trader[binance]" ``` LANGUAGE: Shell CODE: ``` uv sync --all-extras ``` ---------------------------------------- TITLE: Start Component Operation DESCRIPTION: Starts the component. If an exception occurs during the `on_start()` execution, it will be logged and re-raised, leaving the component in a `STARTING` state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/bybit LANGUAGE: APIDOC CODE: ``` start(self) → void WARNING: Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: Clone and Sync NautilusTrader Source with uv DESCRIPTION: Clones the develop branch of the NautilusTrader repository from GitHub with a shallow depth and then uses uv sync to install all project dependencies. This prepares the environment for a source build. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` git clone --branch develop --depth 1 https://github.com/nautechsystems/nautilus_trader cd nautilus_trader uv sync --all-extras ``` ---------------------------------------- TITLE: Start Component Operation DESCRIPTION: Starts the component. Any exception during `on_start()` will be logged and re-raised, leaving the component in a `STARTING` state. This method should not be overridden. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` start(self) -> void Description: Start the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. WARNING: Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: Configure PostgreSQL Database Connection with .env File DESCRIPTION: Example of a .env file to provide PostgreSQL connection configuration, including host, port, username, password, and database name. This file is used by Nautilus CLI database commands. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: Shell CODE: ``` POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_USERNAME=postgres POSTGRES_PASSWORD=pass POSTGRES_DATABASE=nautilus ``` ---------------------------------------- TITLE: Initialize NautilusTrader Backtest Engine DESCRIPTION: This snippet demonstrates how to initialize the BacktestEngine with a custom BacktestEngineConfig. It shows the basic setup required to start a backtesting simulation, allowing for custom trader_id specification. SOURCE: https://nautilustrader.io/docs/latest/getting_started/backtest_low_level LANGUAGE: Python CODE: ``` # Configure backtest engine config = BacktestEngineConfig(trader_id=TraderId("BACKTESTER-001")) # Build the backtest engine engine = BacktestEngine(config=config) ``` ---------------------------------------- TITLE: Rust Test Naming Conventions Examples DESCRIPTION: Provides examples of descriptive test names in Rust, emphasizing clarity about the scenario being tested and the expected behavior. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` fn test_sma_with_no_inputs() fn test_sma_with_single_input() fn test_symbol_is_composite() ``` ---------------------------------------- TITLE: Manage Redis Docker Container DESCRIPTION: Commands to start and stop the named 'redis' Docker container, allowing control over the Redis instance used by NautilusTrader. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: Shell CODE: ``` docker start redis docker stop redis ``` ---------------------------------------- TITLE: Install NautilusTrader with optional dependencies (extras) DESCRIPTION: Installs `nautilus_trader` along with specific optional dependencies (extras) for integrations like Docker and Interactive Brokers using pip. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` pip install -U "nautilus_trader[docker,ib]" ``` ---------------------------------------- TITLE: Documenting Rust Public Functions DESCRIPTION: Guidelines for documenting public Rust functions, covering their purpose, behavior, input argument usage, and conditions for panics. The example shows the `base_balance` function. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` /// Returns a reference to the `AccountBalance` for the specified currency, or `None` if absent. /// /// # Panics /// /// Panics if `currency` is `None` and `self.base_currency` is `None`. pub fn base_balance(&self, currency: Option) -> Option<&AccountBalance> { // Implementation } ``` ---------------------------------------- TITLE: Run NautilusTrader JupyterLab in Docker DESCRIPTION: This snippet provides shell commands to download and run a self-contained Jupyter notebook server for NautilusTrader using Docker. It eliminates the need for local setup and installation, allowing quick access to interactive tutorials. Users must have Docker installed. Be aware that any data generated within the container will be lost upon its deletion. SOURCE: https://nautilustrader.io/docs/latest/tutorials LANGUAGE: shell CODE: ``` docker pull ghcr.io/nautechsystems/jupyterlab:nightly --platform linux/amd64 docker run -p 8888:8888 ghcr.io/nautechsystems/jupyterlab:nightly ``` ---------------------------------------- TITLE: Start Component (NautilusTrader API) DESCRIPTION: Starts the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/interactive_brokers LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: API Method: Start Component DESCRIPTION: Starts the component. Exceptions during on_start() are logged and re-raised, leaving the component in a `STARTING` state. This method should not be overridden, and if the component is not in a valid state, an error will be logged without state change. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/polymarket LANGUAGE: APIDOC CODE: ``` start(self) -> void Start the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. WARNING: Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: API: Start Component DESCRIPTION: Starts the component. While executing on_start(), any exception will be logged and re-raised, then the component will remain in a STARTING state. This method should not be overridden. SOURCE: https://nautilustrader.io/docs/latest/api_reference/data LANGUAGE: APIDOC CODE: ``` start(self) -> void WARNING: Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: Documenting Unsafe Rust Functions with Safety Justification DESCRIPTION: Guidelines for documenting unsafe Rust functions, requiring a `SAFETY:` prefix followed by a description explaining why the unsafe operation is valid. The example shows the `from_raw_parts` function. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` /// Creates a new instance from raw components without validation. /// /// # Safety /// /// The caller must ensure that all input parameters are valid and properly initialized. pub unsafe fn from_raw_parts(ptr: *const u8, len: usize) -> Self { // SAFETY: Caller guarantees ptr is valid and len is correct Self { data: std::slice::from_raw_parts(ptr, len), } } ``` ---------------------------------------- TITLE: Start Component Execution (NautilusTrader API) DESCRIPTION: Starts the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/coinbase_intx LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Start Component Execution DESCRIPTION: Starts the component's operation. If an exception occurs during the on_start() execution, it will be logged and re-raised, leaving the component in a 'STARTING' state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/polymarket LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Connect to Postgres Database via psql CLI DESCRIPTION: Command to connect to the PostgreSQL database using the `psql` command-line interface as the `postgres` user. This is typically used for initial database setup or administration tasks. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: bash CODE: ``` psql -h localhost -p 5432 -U postgres ``` ---------------------------------------- TITLE: Get Account Starting Balances DESCRIPTION: Return the account starting balances. SOURCE: https://nautilustrader.io/docs/latest/api_reference/accounting LANGUAGE: APIDOC CODE: ``` starting_balances(self) -> dict[Currency, Money] ``` ---------------------------------------- TITLE: Rust Unsafe Code Safety Policy Implementation Example DESCRIPTION: Shows an example of implementing a `Send` trait for `MessageBus` using `unsafe` Rust, along with the required `SAFETY:` comment explaining the justification for the unsafe operation and upholding the safety policy. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` // SAFETY: Message bus is not meant to be passed between threads #[allow(unsafe_code)] unsafe impl Send for MessageBus {} ``` ---------------------------------------- TITLE: Start Component DESCRIPTION: Starts the component. If an exception occurs during on_start(), it is logged and re-raised, leaving the component in a 'STARTING' state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/dydx LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Start Component (Python API) DESCRIPTION: Starts the component. Any exception during `on_start()` will be logged and re-raised, leaving the component in a `STARTING` state. This method should not be overridden. If the component is not in a valid state, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` start(self) -> void Start the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state. WARNING: Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: Install Rust Toolchain (rustup) for NautilusTrader Source Build DESCRIPTION: Installs rustup, the Rust toolchain installer, on Linux and macOS systems. This is a prerequisite for building NautilusTrader from source, as it has Rust dependencies. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` curl https://sh.rustup.rs -sSf | sh ``` ---------------------------------------- TITLE: Install NautilusTrader with Betfair Support DESCRIPTION: Instructions for installing NautilusTrader with Betfair integration, either via pip for pre-built packages or from source using uv. SOURCE: https://nautilustrader.io/docs/latest/integrations/betfair LANGUAGE: Python CODE: ``` pip install --upgrade "nautilus_trader[betfair]" ``` LANGUAGE: Shell CODE: ``` uv sync --all-extras ``` ---------------------------------------- TITLE: Start Component (NautilusTrader API) DESCRIPTION: Starts the component. If any exception occurs during the on_start() execution, it will be logged and re-raised, causing the component to remain in a 'STARTING' state. This method is not intended for overriding. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/dydx LANGUAGE: APIDOC CODE: ``` start(self) -> void WARNING: Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: Start Component Execution DESCRIPTION: Starts the component. If an exception occurs during on_start(), it will be logged and re-raised, leaving the component in a STARTING state. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/coinbase_intx LANGUAGE: APIDOC CODE: ``` start(self) Returns: void ``` ---------------------------------------- TITLE: Install uv Package Manager for NautilusTrader Source Build DESCRIPTION: Installs uv, a fast Python package installer and resolver, using a shell script. uv is recommended for managing dependencies when building NautilusTrader from source. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` curl -LsSf https://astral.sh/uv/install.sh | sh ``` ---------------------------------------- TITLE: Install NautilusTrader with pip (Pre-release) DESCRIPTION: Installs the latest available pre-release version of NautilusTrader, including development wheels, from the specified package index. This command uses the --pre flag to consider pre-release versions. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` pip install -U nautilus_trader --pre --index-url=https://packages.nautechsystems.io/simple ``` ---------------------------------------- TITLE: Install stable NautilusTrader from Nautech Systems package index DESCRIPTION: Installs the latest stable release of `nautilus_trader` from the Nautech Systems package index, which hosts official releases and is PEP-503 compliant. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` pip install -U nautilus_trader --index-url=https://packages.nautechsystems.io/simple ``` ---------------------------------------- TITLE: API Method: start Component Execution DESCRIPTION: Starts the component. Exceptions during `on_start()` are logged and re-raised, leaving the component in a `STARTING` state. This method should not be overridden. If the component is not in a valid state for execution, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Install Databento Python Library DESCRIPTION: This snippet provides the command to install the Databento Python library using pip. This library is essential for programmatically accessing and interacting with Databento's data services and is used throughout the tutorials. SOURCE: https://nautilustrader.io/docs/latest/tutorials/databento_overview LANGUAGE: Python CODE: ``` pip install -U databento ``` ---------------------------------------- TITLE: Documenting Rust Modules with Brief Descriptions DESCRIPTION: Guidelines for module-level documentation in Rust, starting with a brief description of the module's purpose and functionality, adhering to a 'design by contract' philosophy for validation checking. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` //! Functions for correctness checks similar to the *design by contract* philosophy. //! //! This module provides validation checking of function or method conditions. //! //! A condition is a predicate which must be true just prior to the execution of //! some section of code - for correct behavior as per the design specification. ``` ---------------------------------------- TITLE: Start Component DESCRIPTION: Start the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/data LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Assemble Backtest Run Configuration DESCRIPTION: This snippet combines the previously configured engine, venues, and data into a single `BacktestRunConfig` object. This object encapsulates all necessary settings for a backtest run. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: python CODE: ``` config = BacktestRunConfig( engine=engine, venues=[venue], data=[data], ) ``` ---------------------------------------- TITLE: Install NautilusTrader from PyPI DESCRIPTION: Installs the latest `nautilus_trader` binary wheel or sdist package from PyPI using Python's pip package manager. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` pip install -U nautilus_trader ``` ---------------------------------------- TITLE: Get Kernel Last Started Timestamp DESCRIPTION: Returns the UNIX timestamp (nanoseconds) when the kernel was last started. SOURCE: https://nautilustrader.io/docs/latest/api_reference/system LANGUAGE: APIDOC CODE: ``` property ts_started: int | None Return type: int or None ``` ---------------------------------------- TITLE: Initialize Parquet Data Catalog and List Instruments DESCRIPTION: Initializes a `ParquetDataCatalog` instance, which can be configured from environment variables or a specified relative path. This step is crucial for accessing pre-loaded historical data and verifies that instruments are correctly visible in the catalog. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: Python CODE: ``` # You can also use a relative path such as `ParquetDataCatalog("./catalog")`, # for example if you're running this notebook after the data setup from the docs. # catalog = ParquetDataCatalog("./catalog") catalog = ParquetDataCatalog.from_env() catalog.instruments() ``` ---------------------------------------- TITLE: Start Component Operation DESCRIPTION: Starts the component. Any exception during the `on_start()` execution will be logged and re-raised, leaving the component in a `STARTING` state. This method should not be overridden. If the component is not in a valid state for this operation, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` Component.start(self) -> void ``` ---------------------------------------- TITLE: Install Clang on Linux for NautilusTrader Source Build DESCRIPTION: Installs the Clang C language frontend for LLVM on Debian/Ubuntu-based Linux systems using apt-get. Clang is a required build dependency for NautilusTrader when installing from source. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` sudo apt-get install clang ``` ---------------------------------------- TITLE: Install NautilusTrader with Bybit Support DESCRIPTION: Installs the NautilusTrader library with the necessary Bybit integration components using pip. SOURCE: https://nautilustrader.io/docs/latest/integrations/bybit LANGUAGE: Python CODE: ``` pip install --upgrade "nautilus_trader[bybit]" ``` ---------------------------------------- TITLE: Execute Backtest with BacktestNode DESCRIPTION: This snippet demonstrates how to execute the backtest using the `BacktestNode` class. It initializes the node with the assembled `BacktestRunConfig` and then calls the `run()` method to synchronously execute the backtest, returning a list of `BacktestResult` objects. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: python CODE: ``` from nautilus_trader.backtest.results import BacktestResult node = BacktestNode(configs=[config]) # Runs one or many configs synchronously results: list[BacktestResult] = node.run() ``` ---------------------------------------- TITLE: Connect to Dockerized IB Gateway with NautilusTrader Python DESCRIPTION: This example demonstrates how to establish a connection to a Dockerized Interactive Brokers Gateway using NautilusTrader's DockerizedIBGatewayConfig and DockerizedIBGateway classes. It shows the configuration, starting the gateway, and verifying the login status and logs. Credentials can be passed via config or environment variables. SOURCE: https://nautilustrader.io/docs/latest/integrations/ib LANGUAGE: python CODE: ``` from nautilus_trader.adapters.interactive_brokers.config import DockerizedIBGatewayConfig from nautilus_trader.adapters.interactive_brokers.gateway import DockerizedIBGateway gateway_config = DockerizedIBGatewayConfig( username="test", password="test", trading_mode="paper", ) # This may take a short while to start up, especially the first time gateway = DockerizedIBGateway( config=gateway_config ) gateway.start() # Confirm you are logged in print(gateway.is_logged_in(gateway.container)) # Inspect the logs print(gateway.container.logs()) ``` ---------------------------------------- TITLE: NautilusTrader Strategy Initialization with on_start Handler DESCRIPTION: This example demonstrates a typical `on_start` handler implementation in a NautilusTrader strategy. It shows how to register indicators for bar updates, request historical data to hydrate indicators, and subscribe to live data feeds for instruments and quote ticks. SOURCE: https://nautilustrader.io/docs/latest/concepts/strategies LANGUAGE: Python CODE: ``` def on_start(self) -> None: """ Actions to be performed on strategy start. """ self.instrument = self.cache.instrument(self.instrument_id) if self.instrument is None: self.log.error(f"Could not find instrument for {self.instrument_id}") self.stop() return # Register the indicators for updating self.register_indicator_for_bars(self.bar_type, self.fast_ema) self.register_indicator_for_bars(self.bar_type, self.slow_ema) # Get historical data self.request_bars(self.bar_type) # Subscribe to live data self.subscribe_bars(self.bar_type) self.subscribe_quote_ticks(self.instrument_id) ``` ---------------------------------------- TITLE: API: Start Component DESCRIPTION: Starts the component. If an exception occurs during on_start(), it will be logged and re-raised, leaving the component in a `STARTING` state. This method should not be overridden. If the component is not in a valid state for this operation, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/databento LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Start Component Method DESCRIPTION: Starts the component. During execution of `on_start()`, any exceptions are logged and re-raised, leaving the component in a `STARTING` state. It is critical not to override this method, as an invalid component state will prevent execution and log an error. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/interactive_brokers LANGUAGE: APIDOC CODE: ``` start(self) -> void Purpose: Start the component. Behavior: While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. Warning: Do not override. If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged. ``` ---------------------------------------- TITLE: Generate Backtest Analysis Reports with BacktestEngine DESCRIPTION: These snippets demonstrate how to retrieve the BacktestEngine instance using the run configuration ID and then generate various analytical reports. This includes reports for order fills, positions, and account activity, providing detailed insights into the backtest's outcomes. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: Python CODE: ``` from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.model import Venue engine: BacktestEngine = node.get_engine(config.id) engine.trader.generate_order_fills_report() ``` LANGUAGE: Python CODE: ``` engine.trader.generate_positions_report() ``` LANGUAGE: Python CODE: ``` engine.trader.generate_account_report(Venue("SIM")) ``` ---------------------------------------- TITLE: Run Redis Docker Container for NautilusTrader DESCRIPTION: This command starts a Redis Docker container, pulling the latest image if needed, running it in detached mode, naming it 'redis', and exposing it on port 6379. This makes Redis accessible to NautilusTrader for optional cache or message bus backend. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: Shell CODE: ``` docker run -d --name redis -p 6379:6379 redis:latest ``` ---------------------------------------- TITLE: Import NautilusTrader Backtest and Model Components DESCRIPTION: Imports essential classes from the `nautilus_trader` library, including configuration for backtesting nodes, engine, and run settings, as well as core model types like Quantity and QuoteTick, and the ParquetDataCatalog for data persistence. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: Python CODE: ``` from nautilus_trader.backtest.node import BacktestDataConfig from nautilus_trader.backtest.node import BacktestEngineConfig from nautilus_trader.backtest.node import BacktestNode from nautilus_trader.backtest.node import BacktestRunConfig from nautilus_trader.backtest.node import BacktestVenueConfig from nautilus_trader.config import ImportableStrategyConfig from nautilus_trader.config import LoggingConfig from nautilus_trader.model import Quantity from nautilus_trader.model import QuoteTick from nautilus_trader.persistence.catalog import ParquetDataCatalog ``` ---------------------------------------- TITLE: Install NautilusTrader with Interactive Brokers and Docker Support DESCRIPTION: This command installs or upgrades the NautilusTrader library, including optional dependencies for Interactive Brokers (IB) integration and Docker support. It ensures all necessary packages for connecting to IB and managing Dockerized IB Gateway are available. SOURCE: https://nautilustrader.io/docs/latest/integrations/ib LANGUAGE: Shell CODE: ``` pip install --upgrade "nautilus_trader[ib,docker]" ``` ---------------------------------------- TITLE: Documenting Single-Line Errors and Panics in Rust Functions DESCRIPTION: Guidelines for documenting single-line error and panic conditions in Rust functions, using sentence case. The example shows the `base_balance` function with `Errors` and `Panics` sections. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` /// Returns a reference to the `AccountBalance` for the specified currency, or `None` if absent. /// /// # Errors /// /// Returns an error if the currency conversion fails. /// /// # Panics /// /// Panics if `currency` is `None` and `self.base_currency` is `None`. pub fn base_balance(&self, currency: Option) -> anyhow::Result> { // Implementation } ``` ---------------------------------------- TITLE: Documenting Rust Struct and Enum Fields DESCRIPTION: Guidelines for documenting fields within Rust structs and enums, requiring a brief description for each field, terminated with a period. The example demonstrates documentation for a `Currency` struct's fields. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` pub struct Currency { /// The currency code as an alpha-3 string (e.g. "USD", "EUR"). pub code: Ustr, /// The currency decimal precision. pub precision: u8, /// The ISO 4217 currency code. pub iso4217: u16, /// The full name of the currency. pub name: Ustr, /// The currency type, indicating its category (e.g. Fiat, Crypto). pub currency_type: CurrencyType, } ``` ---------------------------------------- TITLE: Start Component (NautilusTrader API) DESCRIPTION: Starts the component. While executing `on_start()`, any exception will be logged and re-raised, then the component will remain in a `STARTING` state. This method should not be overridden; if the component is not in a valid state, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/risk LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Start Component Operation DESCRIPTION: Starts the component. If an exception occurs during `on_start()`, it will be logged and re-raised, leaving the component in a `STARTING` state. Do not override this method. If the component is not in a valid state, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/data LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Get Configuration Hashed Identifier (property) DESCRIPTION: Returns a hashed identifier for the configuration instance. This property can be used for uniquely identifying a specific configuration setup. SOURCE: https://nautilustrader.io/docs/latest/api_reference/config LANGUAGE: APIDOC CODE: ``` property id: str Returns: str ``` ---------------------------------------- TITLE: Install Specific NautilusTrader Development Wheel with pip DESCRIPTION: Installs a specific development wheel of NautilusTrader by exact version number from the custom package index. This is useful for reproducing builds or testing specific development snapshots. SOURCE: https://nautilustrader.io/docs/latest/getting_started/installation LANGUAGE: bash CODE: ``` pip install nautilus_trader==1.208.0a20241212 --index-url=https://packages.nautechsystems.io/simple ``` ---------------------------------------- TITLE: Install NautilusTrader with dYdX Support DESCRIPTION: Installs or upgrades the NautilusTrader library to include support for dYdX, enabling connectivity to the decentralized exchange. SOURCE: https://nautilustrader.io/docs/latest/integrations/dydx LANGUAGE: Python CODE: ``` pip install --upgrade "nautilus_trader[dydx]" ``` ---------------------------------------- TITLE: Load Instruments from Parquet Data Catalog DESCRIPTION: This snippet shows how to load available instruments from a `ParquetDataCatalog` instance. The `catalog.instruments()` method retrieves a list of instruments that can then be used for data configuration. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: python CODE: ``` instruments = catalog.instruments() instruments ``` ---------------------------------------- TITLE: Get Dataset Available Range DESCRIPTION: Discovers the earliest and latest available dates for a specific dataset. The returned start and end values can be used with time series and batch job endpoints. SOURCE: https://nautilustrader.io/docs/latest/tutorials/databento_overview LANGUAGE: Python CODE: ``` available_range = client.metadata.get_dataset_range(dataset="GLBX.MDP3") available_range ``` ---------------------------------------- TITLE: Configure QuoteTick Data for Backtest DESCRIPTION: This snippet configures the input data for the backtest using `BacktestDataConfig`. It specifies the path to the data catalog, the data class (`QuoteTick`), the instrument ID from the loaded instruments, and an end time for the data. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: python CODE: ``` from nautilus_trader.model import QuoteTick data = BacktestDataConfig( catalog_path=str(catalog.path), data_cls=QuoteTick, instrument_id=instruments[0].id, end_time="2020-01-10", ) ``` ---------------------------------------- TITLE: Build NautilusTrader from Source with All Extras DESCRIPTION: Demonstrates how to build NautilusTrader from its source code, including all optional dependencies like Bybit, using the `uv` tool. SOURCE: https://nautilustrader.io/docs/latest/integrations/bybit LANGUAGE: Shell CODE: ``` uv sync --all-extras ``` ---------------------------------------- TITLE: Market Data Strategy Example with NautilusTrader Cache DESCRIPTION: A simple strategy example demonstrating subscription to bars, accessing historical bars, and retrieving the latest quote and trade ticks from the cache for analysis. SOURCE: https://nautilustrader.io/docs/latest/concepts/cache LANGUAGE: Python CODE: ``` class MarketDataStrategy(Strategy): def on_start(self): # Subscribe to 1-minute bars self.bar_type = BarType.from_str(f"{self.instrument_id}-1-MINUTE-LAST-EXTERNAL") # example of instrument_id = "EUR/USD.FXCM" self.subscribe_bars(self.bar_type) def on_bar(self, bar: Bar) -> None: bars = self.cache.bars(self.bar_type)[:3] if len(bars) < 3: # Wait until we have at least 3 bars return # Access last 3 bars for analysis current_bar = bars[0] # Most recent bar prev_bar = bars[1] # Second to last bar prev_prev_bar = bars[2] # Third to last bar # Get latest quote and trade latest_quote = self.cache.quote_tick(self.instrument_id) latest_trade = self.cache.trade_tick(self.instrument_id) if latest_quote is not None: current_spread = latest_quote.ask_price - latest_quote.bid_price self.log.info(f"Current spread: {current_spread}") ``` ---------------------------------------- TITLE: Python: Examples of IBContract for Various Security Types DESCRIPTION: Provides multiple Python examples of `IBContract` instantiation for common security types. This includes configurations for Stocks, Bonds, Options, CFDs, Futures, Forex, and Crypto, illustrating the specific parameters required for each type. SOURCE: https://nautilustrader.io/docs/latest/integrations/ib LANGUAGE: Python CODE: ``` from nautilus_trader.adapters.interactive_brokers.common import IBContract # Stock IBContract(secType='STK', exchange='SMART', primaryExchange='ARCA', symbol='SPY') # Bond IBContract(secType='BOND', secIdType='ISIN', secId='US03076KAA60') # Option IBContract(secType='STK', exchange='SMART', primaryExchange='ARCA', symbol='SPY', lastTradeDateOrContractMonth='20251219', build_options_chain=True) # CFD IBContract(secType='CFD', symbol='IBUS30') # Future IBContract(secType='CONTFUT', exchange='CME', symbol='ES', build_futures_chain=True) # Forex IBContract(secType='CASH', exchange='IDEALPRO', symbol='EUR', currency='GBP') # Crypto IBContract(secType='CRYPTO', symbol='ETH', exchange='PAXOS', currency='USD') ``` ---------------------------------------- TITLE: Accessing Quote Tick Market Data from Cache DESCRIPTION: This code demonstrates how to retrieve quote tick data from the Cache, providing examples for fetching all quotes for an instrument, getting the latest quote, and accessing a specific historical quote by its index. SOURCE: https://nautilustrader.io/docs/latest/concepts/cache LANGUAGE: python CODE: ``` # Get quotes quotes = self.cache.quote_ticks(instrument_id) # Returns List[QuoteTick] or an empty list if no quotes found latest_quote = self.cache.quote_tick(instrument_id) # Returns QuoteTick or None if no such object exists second_last_quote = self.cache.quote_tick(instrument_id, index=1) # Returns QuoteTick or None if no such object exists ``` ---------------------------------------- TITLE: Method: build DESCRIPTION: Initializes and builds all configured clients within the trading node, preparing them for operation. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` build() -> None Description: Build the nodes clients. ``` ---------------------------------------- TITLE: Method: run DESCRIPTION: Starts and runs the trading node, initiating its operational processes. Optionally re-raises runtime exceptions. SOURCE: https://nautilustrader.io/docs/latest/api_reference/live LANGUAGE: APIDOC CODE: ``` run(raise_exception: bool = False) -> None Description: Start and run the trading node. Parameters: raise_exception (bool, default False): If runtime exceptions should be re-raised as well as being logged. ``` ---------------------------------------- TITLE: Start Component Operation DESCRIPTION: Starts the component. If an exception occurs during the on_start() execution, it will be logged and re-raised, leaving the component in a 'STARTING' state. This method should not be overridden. If the component is not in a valid state for this operation, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/betfair LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: CacheConfig Flush On Start Property DESCRIPTION: If database should be flushed on start. SOURCE: https://nautilustrader.io/docs/latest/api_reference/config LANGUAGE: APIDOC CODE: ``` flush_on_start: bool ``` ---------------------------------------- TITLE: Start Component DESCRIPTION: Initializes and starts the component. Any exceptions during the on_start() execution will be logged and re-raised, causing the component to remain in a 'STARTING' state. This method should not be overridden. If the component is not in a valid state, its state will not change, and an error will be logged. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/tardis LANGUAGE: APIDOC CODE: ``` start(self) -> void ``` ---------------------------------------- TITLE: Recompile NautilusTrader Project Files DESCRIPTION: Commands to recompile project files (`.rs`, `.pyx`, or `.pxd`) after making changes. Options are provided for a standard build using `uv` or `make`, and a significantly faster debug build for development iteration. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: Shell CODE: ``` uv run --no-sync python build.py ``` LANGUAGE: Make CODE: ``` make build ``` LANGUAGE: Make CODE: ``` make build-debug ``` ---------------------------------------- TITLE: Documenting Multi-Line Errors and Panics in Rust Functions DESCRIPTION: Guidelines for documenting multi-line error and panic conditions in Rust functions, using sentence case with bullet points and terminating periods. The example shows the `calculate_unrealized_pnl` function. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` /// Calculates the unrealized profit and loss for the position. /// /// # Errors /// /// This function will return an error if: /// - The market price for the instrument cannot be found. /// - The conversion rate calculation fails. /// - Invalid position state is encountered. /// /// # Panics /// /// This function will panic if: /// - The instrument ID is invalid or uninitialized. /// - Required market data is missing from the cache. /// - Internal state consistency checks fail. pub fn calculate_unrealized_pnl(&self, market_price: Price) -> anyhow::Result { // Implementation } ``` ---------------------------------------- TITLE: Example Tardis Machine Replay Configuration DESCRIPTION: An example JSON configuration file for the Tardis Machine, illustrating how to specify WebSocket URL, output path, and replay options including exchange, symbols, data types, and time range. SOURCE: https://nautilustrader.io/docs/latest/integrations/tardis LANGUAGE: JSON CODE: ``` { "tardis_ws_url": "ws://localhost:8001", "output_path": null, "options": [ { "exchange": "bitmex", "symbols": [ "xbtusd", "ethusd" ], "data_types": [ "trade" ], "from": "2019-10-01", "to": "2019-10-02" } ] } ``` ---------------------------------------- TITLE: NautilusTrader Get Current UTC Timestamp as Unix Nanoseconds DESCRIPTION: This example demonstrates how to retrieve the current Coordinated Universal Time (UTC) timestamp as nanoseconds since the Unix epoch. The `timestamp_ns()` method provides a high-precision integer representation of the current time. SOURCE: https://nautilustrader.io/docs/latest/concepts/strategies LANGUAGE: Python CODE: ``` unix_nanos: int = self.clock.timestamp_ns() ``` ---------------------------------------- TITLE: Documenting Inline Unsafe Blocks in Rust DESCRIPTION: Guidelines for documenting inline unsafe blocks in Rust, using a `SAFETY:` comment directly above the unsafe code to justify its validity. The example shows an unsafe block within a `send` method. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/rust LANGUAGE: Rust CODE: ``` impl Send for MessageBus { fn send(&self) { // SAFETY: Message bus is not meant to be passed between threads unsafe { // unsafe operation here } } } ``` ---------------------------------------- TITLE: Install NautilusTrader with Polymarket Integration DESCRIPTION: This command demonstrates how to install NautilusTrader, including its Polymarket-specific dependencies, using pip. This ensures all required libraries for interacting with the Polymarket CLOB API are available in your Python environment. SOURCE: https://nautilustrader.io/docs/latest/integrations/polymarket LANGUAGE: Shell CODE: ``` pip install --upgrade "nautilus_trader[polymarket]" ``` ---------------------------------------- TITLE: Configure Backtest Engine with MACD Strategy DESCRIPTION: This snippet sets up the `BacktestEngineConfig` for the core trading system. It includes an `ImportableStrategyConfig` for a `MACDStrategy`, specifying its path, configuration path, and parameters like instrument ID, fast period, and slow period. It also sets the logging level to 'ERROR' to avoid Jupyter notebook hanging issues. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: python CODE: ``` # NautilusTrader currently exceeds the rate limit for Jupyter notebook logging (stdout output), # this is why the `log_level` is set to "ERROR". If you lower this level to see # more logging then the notebook will hang during cell execution. A fix is currently # being investigated which involves either raising the configured rate limits for # Jupyter, or throttling the log flushing from Nautilus. # https://github.com/jupyterlab/jupyterlab/issues/12845 # https://github.com/deshaw/jupyterlab-limit-output engine = BacktestEngineConfig( strategies=[ ImportableStrategyConfig( strategy_path="__main__:MACDStrategy", config_path="__main__:MACDConfig", config={ "instrument_id": instruments[0].id, "fast_period": 12, "slow_period": 26, }, ) ], logging=LoggingConfig(log_level="ERROR"), ) ``` ---------------------------------------- TITLE: Configure Cache with Database Persistence DESCRIPTION: This example demonstrates how to integrate DatabaseConfig into CacheConfig to enable persistent storage for market data, using Redis as an example database type with specified host, port, and timeout settings. SOURCE: https://nautilustrader.io/docs/latest/concepts/cache LANGUAGE: python CODE: ``` from nautilus_trader.config import DatabaseConfig config = CacheConfig( database=DatabaseConfig( type="redis", # Database type host="localhost", # Database host port=6379, # Database port timeout=2 # Connection timeout (seconds) ) ) ``` ---------------------------------------- TITLE: NautilusTrader Set Continuous Timer for Recurring Events DESCRIPTION: This snippet demonstrates how to set up a continuous timer in NautilusTrader. The timer generates a `TimeEvent` at regular intervals, which can be processed by the `on_event` handler, until it expires or is explicitly canceled. The example sets a timer to fire every minute, starting immediately. SOURCE: https://nautilustrader.io/docs/latest/concepts/strategies LANGUAGE: Python CODE: ``` import pandas as pd # Fire a TimeEvent every minute self.clock.set_timer( name="MyTimer1", interval=pd.Timedelta(minutes=1), ) ``` ---------------------------------------- TITLE: Get Instrument Definition Time Series Range Asynchronously DESCRIPTION: Requests a time series of instrument definitions for given instrument IDs from Databento's /timeseries.get_range endpoint. Allows specifying a start and end datetime for the range. This method incurs a cost to your Databento account. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/databento LANGUAGE: APIDOC CODE: ``` async get_range( instrument_ids: list[InstrumentId], start: Timestamp | date | str | int, end: Timestamp | date | str | int | None = None, filters: dict | None = None ) -> list[Instrument] Parameters: instrument_ids (list[InstrumentId]): The instrument IDs for the request. start (pd.Timestamp or date or str or int): The start datetime of the request time range (inclusive). Assumes UTC as timezone unless tz-aware. If an integer, represents nanoseconds since UNIX epoch. end (pd.Timestamp or date or str or int, optional): The end datetime of the request time range (exclusive). Assumes UTC as timezone unless tz-aware. If an integer, represents nanoseconds since UNIX epoch. Values are forward-filled based on resolution. Defaults to the same value as start. filters (dict, optional): The optional filters for the instrument definition request. ``` ---------------------------------------- TITLE: Discovering Instruments for Binance Futures Testnet DESCRIPTION: This Python example demonstrates how to use the BinanceFuturesInstrumentProvider to discover and load available instruments from the Binance Futures testnet. It involves setting up an asynchronous HTTP client with API credentials and then using the provider to load all instruments. SOURCE: https://nautilustrader.io/docs/latest/concepts/adapters LANGUAGE: Python CODE: ``` import asyncio import os from nautilus_trader.adapters.binance.common.enums import BinanceAccountType from nautilus_trader.adapters.binance import get_cached_binance_http_client from nautilus_trader.adapters.binance.futures.providers import BinanceFuturesInstrumentProvider from nautilus_trader.common.component import LiveClock clock = LiveClock() account_type = BinanceAccountType.USDT_FUTURE client = get_cached_binance_http_client( loop=asyncio.get_event_loop(), clock=clock, account_type=account_type, key=os.getenv("BINANCE_FUTURES_TESTNET_API_KEY"), secret=os.getenv("BINANCE_FUTURES_TESTNET_API_SECRET"), is_testnet=True, ) await client.connect() provider = BinanceFuturesInstrumentProvider( client=client, account_type=BinanceAccountType.USDT_FUTURE, ) await provider.load_all_async() ``` ---------------------------------------- TITLE: Install Web3 Python Package for Polymarket Adapter DESCRIPTION: Before running the allowance script, ensure the `web3` Python package is installed at the specified version to meet script dependencies. This is a crucial prerequisite for the script's functionality. SOURCE: https://nautilustrader.io/docs/latest/integrations/polymarket LANGUAGE: Shell CODE: ``` pip install --upgrade web3==5.28 ``` ---------------------------------------- TITLE: Configure Simulated FX ECN Venue for Backtest DESCRIPTION: This snippet demonstrates how to create a `BacktestVenueConfig` for a simulated FX ECN. It sets the venue name as 'SIM', specifies 'NETTING' OMS type, 'MARGIN' account type, 'USD' base currency, and an initial balance of '1_000_000 USD'. SOURCE: https://nautilustrader.io/docs/latest/getting_started/quickstart LANGUAGE: python CODE: ``` venue = BacktestVenueConfig( name="SIM", oms_type="NETTING", account_type="MARGIN", base_currency="USD", starting_balances=["1_000_000 USD"] ) ``` ---------------------------------------- TITLE: Import NautilusTrader Modules for Low-Level Backtesting DESCRIPTION: This snippet imports essential modules from the NautilusTrader library and Python's decimal module. It includes components for the BacktestEngine, example strategies and execution algorithms, various data models (BarType, Money, TraderId, Venue), currency definitions, enumeration types (AccountType, OmsType), data persistence wranglers, and test utility providers, all necessary for setting up and executing a low-level backtest. SOURCE: https://nautilustrader.io/docs/latest/getting_started/backtest_low_level LANGUAGE: python CODE: ``` from decimal import Decimal from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.backtest.engine import BacktestEngineConfig from nautilus_trader.examples.algorithms.twap import TWAPExecAlgorithm from nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAP from nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAPConfig from nautilus_trader.model import BarType from nautilus_trader.model import Money from nautilus_trader.model import TraderId from nautilus_trader.model import Venue from nautilus_trader.model.currencies import ETH from nautilus_trader.model.currencies import USDT from nautilus_trader.model.enums import AccountType from nautilus_trader.model.enums import OmsType from nautilus_trader.persistence.wranglers import TradeTickDataWrangler from nautilus_trader.test_kit.providers import TestDataProvider from nautilus_trader.test_kit.providers import TestInstrumentProvider ``` ---------------------------------------- TITLE: Bybit Live Data and Execution Client Factories DESCRIPTION: Factory classes for creating live data and execution clients for Bybit, enabling real-time market data subscriptions and order management. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/bybit LANGUAGE: APIDOC CODE: ``` class BybitLiveDataClientFactory class BybitLiveExecClientFactory ``` ---------------------------------------- TITLE: API: Connect Client DESCRIPTION: Connects the client to the trading system. This method initializes the client's connection, making it ready for operations. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/bybit LANGUAGE: APIDOC CODE: ``` connect() -> None ``` ---------------------------------------- TITLE: View Nautilus CLI Help and Commands DESCRIPTION: Command to display the help message for the Nautilus CLI, showing its overall structure and available command groups. This is useful for discovering functionalities and usage instructions. SOURCE: https://nautilustrader.io/docs/latest/developer_guide/environment_setup LANGUAGE: bash CODE: ``` nautilus --help ``` ---------------------------------------- TITLE: Build NautilusTrader from Source with All Extras DESCRIPTION: This command utilizes `uv sync` to build the NautilusTrader project from its source code, incorporating all optional dependencies and 'extras,' such as the Polymarket integration. This method is typically used by developers or for custom build configurations. SOURCE: https://nautilustrader.io/docs/latest/integrations/polymarket LANGUAGE: Shell CODE: ``` uv sync --all-extras ``` ---------------------------------------- TITLE: Bybit Live Execution Client Factory Class DESCRIPTION: Defines the BybitLiveExecClientFactory class, which extends LiveExecClientFactory and provides methods for creating Bybit live execution clients. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/bybit LANGUAGE: APIDOC CODE: ``` class BybitLiveExecClientFactory Bases: LiveExecClientFactory ``` ---------------------------------------- TITLE: Bybit Live Execution Client Factory Class DESCRIPTION: This class provides a factory for creating Bybit live execution clients, inheriting from `LiveExecClientFactory`. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/bybit LANGUAGE: APIDOC CODE: ``` Class: BybitLiveExecClientFactory Bases: LiveExecClientFactory Description: Provides a Bybit live execution client factory. ``` ---------------------------------------- TITLE: Create Bybit Live Execution Client DESCRIPTION: Creates a new Bybit execution client, requiring an event loop, custom ID, configuration, message bus, cache, and live clock. Returns an instance of BybitExecutionClient. SOURCE: https://nautilustrader.io/docs/latest/api_reference/adapters/bybit LANGUAGE: APIDOC CODE: ``` static create( loop: asyncio.AbstractEventLoop, name: str, config: BybitExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock ) -> BybitExecutionClient Parameters: loop (asyncio.AbstractEventLoop): The event loop for the client. name (str): The custom client ID. config (BybitExecClientConfig): The client configuration. msgbus (MessageBus): The message bus for the client. cache (Cache): The cache for the client. clock (LiveClock): The clock for the client. Return type: BybitExecutionClient ```