### Create BacktestRunConfig with Engine, Venues, and Data Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart Combines the configured engine, venues, and data into a single `BacktestRunConfig` object. This object encapsulates the complete setup required to execute a backtest. ```python config = BacktestRunConfig( engine=engine, venues=[venue], data=[data], ) ``` -------------------------------- ### Install and Configure Rust Nightly Toolchain for Faster Builds Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs the Rust nightly toolchain, sets it as the default, and installs the rust-analyzer LSP. It also shows how to reset to the stable toolchain. This setup is necessary for enabling the cranelift backend for significantly reduced build times. ```bash rustup install nightly rustup override set nightly rustup component add rust-analyzer # install nightly lsp rustup override set stable # reset to stable ``` -------------------------------- ### Cap'n Proto - Installing and Verifying Source: https://nautilustrader.io/docs/nightly/developer_guide/rust Provides instructions for installing the Cap'n Proto compiler and verifying its correct installation. It also includes a warning regarding Ubuntu's default package and recommends installing from source. ```bash capnp --version # Should match the version in capnp-version ``` -------------------------------- ### Install Cap'n Proto with Chocolatey (Windows) Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs Cap'n Proto on Windows using the Chocolatey package manager. Users should verify that the installed version matches the `capnp-version` file. Alternative installation methods may be needed if Chocolatey provides an outdated version. ```shell choco install capnproto ``` -------------------------------- ### Configure Backtest Data with QuoteTick and BacktestDataConfig Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart Configures the data for a backtest by specifying the catalog path, data class (QuoteTick), instrument ID, and end time. This setup is crucial for providing the necessary market data to the trading engine. ```python 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", ) ``` -------------------------------- ### Verify Cap'n Proto Installation Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Verifies the installation of Cap'n Proto by checking its version. This command should be run after installing Cap'n Proto to ensure it was successful and the correct version is active. ```shell capnp --version ``` -------------------------------- ### Install Cap'n Proto from Source (Linux) Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs Cap'n Proto from source on Linux, typically required when the default distribution package is too old. This process involves downloading, extracting, configuring, compiling, and installing the Cap'n Proto C++ library. ```shell CAPNP_VERSION=$(cat capnp-version) cd ~ wget https://capnproto.org/capnproto-c++-${CAPNP_VERSION}.tar.gz tar xzf capnproto-c++-${CAPNP_VERSION}.tar.gz cd capnproto-c++-${CAPNP_VERSION} ./configure make -j$(nproc) sudo make install sudo ldconfig ``` -------------------------------- ### Install Cap'n Proto with Homebrew (macOS) Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs Cap'n Proto on macOS using the Homebrew package manager. Users should verify that the installed version matches the version specified in the `capnp-version` file. If the Homebrew version is too old, installation from source is recommended. ```shell brew install capnp ``` -------------------------------- ### Install Project with Make Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs the NautilusTrader project using the Makefile. This is a convenient alternative to directly using uv sync for setting up the project environment. ```shell make install ``` -------------------------------- ### Minimal TradingNode Configuration Example Source: https://nautilustrader.io/docs/nightly/integrations/betfair This example demonstrates a minimal setup for configuring a live `TradingNode` with Betfair data and execution clients, specifying the account currency. ```APIDOC ## Contributing ### Description Information on how to contribute to the Betfair adapter or request additional features. ### Method Informational ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response N/A ``` -------------------------------- ### start Source: https://nautilustrader.io/docs/nightly/api_reference/adapters/coinbase_intx Starts the component. Exceptions during the start process will be logged and re-raised, leaving the component in a 'STARTING' state. ```APIDOC ## POST /websites/nautilustrader_io_nightly/start ### Description Start the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. ### Method POST ### Endpoint /websites/nautilustrader_io_nightly/start ### Parameters None ### Response #### Success Response (200) - **status** (string) - Indicates the start operation. #### Response Example ```json { "status": "Component start initiated." } ``` ``` -------------------------------- ### Demo Trading Setup Source: https://nautilustrader.io/docs/nightly/integrations/okx Guide to setting up and using the OKX demo trading environment for testing strategies without real funds. ```APIDOC ## Demo Trading ### Description OKX provides a demo trading environment for testing strategies. This section outlines how to set up demo trading and configure the adapter. ### Setting up a Demo Account 1. Log into your OKX account at okx.com. 2. Navigate to **Trade** → **Demo Trading**. 3. Go to **Personal Center** within Demo Trading. 4. Select **Demo Trading API** and create a new API key. 5. Note down your demo API key, secret, and passphrase. ### Providing Demo Credentials Provide demo credentials via environment variables: ```bash export OKX_API_KEY="your_demo_api_key" export OKX_API_SECRET="your_demo_api_secret" export OKX_API_PASSPHRASE="your_demo_passphrase" ``` ### Configuration Enable demo mode by setting `is_demo=True` in your client configuration: ```python config = TradingNodeConfig( data_clients={ OKX: OKXDataClientConfig( is_demo=True, # Enable demo mode # ... other config ) }, exec_clients={ OKX: OKXExecClientConfig( is_demo=True, # Enable demo mode # ... other config ) }, ) ``` When demo mode is enabled: - REST API requests include the `x-simulated-trading: 1` header. - WebSocket connections use demo endpoints (`wspap.okx.com`). **Note**: Demo API keys are separate from production keys. You must create API keys specifically for demo trading; production API keys will not work in demo mode. ``` -------------------------------- ### Configure Backtest Venue in Python Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart This Python code snippet configures a simulated trading venue for a backtest using NautilusTrader. It sets up a 'SIM' venue with netting order management, margin account type, USD base currency, and an initial balance. This configuration is a minimal setup for initiating a backtest run. ```python venue = BacktestVenueConfig( name="SIM", oms_type="NETTING", account_type="MARGIN", base_currency="USD", starting_balances=["1_000_000 USD"], ) ``` -------------------------------- ### Start Component Source: https://nautilustrader.io/docs/nightly/api_reference/execution Starts the component. Exceptions during the start process are logged and re-raised, transitioning the component to a `STARTING` state. This method should not be overridden. ```python def start(self) -> None: """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. """ ``` -------------------------------- ### Start Specific Docker Compose Services Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Allows starting only specific services defined in the `docker-compose.yml` file. For example, `docker-compose up -d postgres` will only start the PostgreSQL service in detached mode. ```bash docker-compose up -d postgres ``` -------------------------------- ### Install cargo-flamegraph Source: https://nautilustrader.io/docs/nightly/developer_guide/benchmarking Installs the `cargo-flamegraph` tool, which is used for generating flamegraphs to profile benchmark performance. This is a one-time installation per machine. ```bash cargo install flamegraph ``` -------------------------------- ### Import NautilusTrader Backtesting Components Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart This code snippet imports necessary classes for configuring and running backtests in NautilusTrader. It includes configurations for data, engine, run, venue, and strategy, as well as logging and data models. ```python 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 ``` -------------------------------- ### Start Component Initialization Source: https://nautilustrader.io/docs/nightly/api_reference/adapters/binance Starts the initialization process for a component. During 'on_start()', any exceptions are logged and re-raised, transitioning the component to a 'STARTING' state. This method should not be overridden, and execution requires a valid component state. ```python 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. ``` -------------------------------- ### Install Development Dependencies with uv Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs all development and test dependencies for NautilusTrader using the uv package manager. This command ensures all necessary groups and extras are included for a comprehensive development setup. ```shell uv sync --active --all-groups --all-extras ``` -------------------------------- ### Get Start Time in Nanoseconds from BacktestDataConfig Source: https://nautilustrader.io/docs/nightly/api_reference/config Returns the start time specified in the BacktestDataConfig, converted to UNIX nanoseconds. Returns zero if no start time was provided. ```python backtest_config.start_time_nanos ``` -------------------------------- ### Configure Backtest Engine with MACDStrategy and Logging Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart Sets up the backtest engine configuration, including strategies and logging. It uses `ImportableStrategyConfig` to specify the strategy and its configuration paths, and `LoggingConfig` to control log levels. Note the comment regarding Jupyter notebook logging limitations. ```python # NautilusTrader currently exceeds the rate limit for Jupyter notebook logging (stdout output), # which 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 being investigated which involves # either raising the configured rate limits for Jupyter, or throttling the log flushing. # 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"), ) ``` -------------------------------- ### POST /start Source: https://nautilustrader.io/docs/nightly/api_reference/adapters/binance Starts the component. Any exceptions during the start process will be logged and re-raised. ```APIDOC ## POST /start ### Description Start the component. While executing on_start() any exception will be logged and reraised, then the component will remain in a `STARTING` state. ### Method POST ### Endpoint /start ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (string) - Indicates that the component start process has been initiated. #### Response Example ```json { "status": "Component start initiated" } ``` ``` -------------------------------- ### Install Linux Perf Tools Source: https://nautilustrader.io/docs/nightly/developer_guide/benchmarking Installs the necessary `perf` tools on Debian/Ubuntu systems, which are required by `cargo-flamegraph` for profiling on Linux. It ensures the correct version of `linux-tools` is installed based on the running kernel. ```bash sudo apt install linux-tools-common linux-tools-$(uname -r) ``` -------------------------------- ### Load and Verify Parquet Data Catalog in NautilusTrader Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart This script demonstrates how to load a Parquet data catalog from the current working directory and list the available instruments. It assumes the catalog has been previously created. It requires the `nautilus_trader` library and a `catalog` directory. ```python # Load the catalog from current working directory catalog_path = Path.cwd() / "catalog" catalog = ParquetDataCatalog(str(catalog_path)) instruments = catalog.instruments() print(f"Loaded catalog from: {catalog_path}") print(f"Available instruments: {[str(i.id) for i in instruments]}") if instruments: print(f"\nUsing instrument: {instruments[0].id}") else: print("\nNo instruments found. Please run the data download cell first.") ``` -------------------------------- ### Configure Instruments for Backtesting with ParquetDataCatalog Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart This snippet demonstrates how to retrieve a list of instruments from a catalog, which is a prerequisite for configuring backtest data. It utilizes the `ParquetDataCatalog` to access instrument information. ```python instruments = catalog.instruments() instruments ``` -------------------------------- ### Execute Backtest using BacktestNode Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart Initializes and runs the backtest using the `BacktestNode`. This class orchestrates the execution of one or more backtest configurations synchronously, returning a list of `BacktestResult` objects. ```python from nautilus_trader.backtest.results import BacktestResult node = BacktestNode(configs=[config]) # Runs one or many configs synchronously results: list[BacktestResult] = node.run() ``` -------------------------------- ### Install Cap'n Proto with Script (Linux/macOS) Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs the specific version of Cap'n Proto required by NautilusTrader on Linux and macOS using a provided installation script. This ensures compatibility for serialization schema compilation. ```shell ./scripts/install-capnp.sh ``` -------------------------------- ### Get Backtest Start Time Source: https://nautilustrader.io/docs/nightly/api_reference/backtest Retrieves the start time of the last completed backtest run. Returns None if no backtest has been run. ```python start_time = engine.backtest_start if start_time: print(f"Backtest started at: {start_time}") ``` -------------------------------- ### Download and Prepare FX Sample Data for NautilusTrader Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart This script downloads EUR/USD historical tick data from a remote URL, processes it using QuoteTickDataWrangler, and saves it to a Parquet data catalog. It requires Python 3.12+, NautilusTrader, and its dependencies. The output is a catalog containing instrument and tick data. ```python import os import urllib.request from pathlib import Path from nautilus_trader.persistence.catalog import ParquetDataCatalog from nautilus_trader.persistence.wranglers import QuoteTickDataWrangler from nautilus_trader.test_kit.providers import CSVTickDataLoader from nautilus_trader.test_kit.providers import TestInstrumentProvider # Create catalog directory in current working directory catalog_path = Path.cwd() / "catalog" catalog_path.mkdir(exist_ok=True) print(f"Working directory: {Path.cwd()}") print(f"Catalog directory: {catalog_path}") try: # Download EUR/USD sample data print("Downloading EUR/USD sample data...") url = "https://raw.githubusercontent.com/nautechsystems/nautilus_data/main/raw_data/fx_hist_data/DAT_ASCII_EURUSD_T_202001.csv.gz" filename = "EURUSD_202001.csv.gz" print(f"Downloading from: {url}") urllib.request.urlretrieve(url, filename) # noqa: S310 print("Download complete") # Create the instrument print("Creating EUR/USD instrument...") instrument = TestInstrumentProvider.default_fx_ccy("EUR/USD") # Load and process the tick data print("Loading tick data...") wrangler = QuoteTickDataWrangler(instrument) df = CSVTickDataLoader.load( filename, index_col=0, datetime_format="%Y%m%d %H%M%S%f", ) df.columns = ["bid_price", "ask_price", "size"] print(f"Loaded {len(df)} ticks") # Process ticks print("Processing ticks...") ticks = wrangler.process(df) # Write to catalog print("Writing data to catalog...") catalog = ParquetDataCatalog(str(catalog_path)) catalog.write_data([instrument]) print("Instrument written to catalog") catalog.write_data(ticks) print("Tick data written to catalog") # Verify what was written print("\nVerifying catalog contents...") test_catalog = ParquetDataCatalog(str(catalog_path)) loaded_instruments = test_catalog.instruments() print(f"Instruments in catalog: {[str(i.id) for i in loaded_instruments]}") # Clean up downloaded file os.unlink(filename) print("\nData setup complete!") except Exception as e: print(f"Error: {e}") import traceback traceback.print_exc() ``` -------------------------------- ### Get Timedelta for Time-Based Bars (Python Example) Source: https://nautilustrader.io/docs/nightly/api_reference/model Retrieves the timedelta for time-based bars. This example demonstrates how to instantiate a BarSpecification with a specific time interval and then access its timedelta attribute. ```python from nautilustrader.core.spec import BarSpecification from nautilustrader.enum.bar import BarAggregation from nautilustrader.enum.price import PriceType spec = BarSpecification(30, BarAggregation.SECOND, PriceType.LAST) print(spec.timedelta) ``` -------------------------------- ### on_start Source: https://nautilustrader.io/docs/nightly/api_reference/backtest Performs actions on initial start of a trading run. It is recommended to subscribe/request for data here. This system method is intended for override. ```APIDOC ## on_start ### Description Actions to be performed on start. The intent is that this method is called once per trading ‘run’, when initially starting. It is recommended to subscribe/request for data here. ### Method Implicitly called by the system ### Endpoint N/A (System Method) ### Parameters None ### Request Example ``` # This is a system method and not directly callable. ``` ### Response #### Success Response (void) This method returns void. #### Response Example ``` # No response body for void methods ``` ``` -------------------------------- ### Start DataEngine Component Source: https://nautilustrader.io/docs/nightly/api_reference/live Starts the component. Exceptions during the on_start() execution are logged and re-raised, leaving the component in a STARTING state. This method should not be overridden. ```python start(self) → void ``` -------------------------------- ### Start Component in Python Source: https://nautilustrader.io/docs/nightly/api_reference/adapters/betfair Starts the component. Any exceptions encountered during the start-up process are logged and re-raised, potentially leaving the component in a 'STARTING' state. This method is not intended for overriding. ```Python def start(self) -> None: """Start the component.""" pass ``` -------------------------------- ### Install NautilusTrader CLI Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs the NautilusTrader CLI using the provided Makefile target. This command leverages `cargo install` and places the `nautilus` binary in your system's PATH, assuming Rust's `cargo` is correctly configured. ```bash make install-cli ``` -------------------------------- ### Retrieve and Analyze Backtest Engine Reports Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart Retrieves the `BacktestEngine` instance used during the run and generates various reports, including order fills, positions, and account details for a specified venue. This allows for detailed inspection of the backtest's operational data. ```python from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.model import Venue engine: BacktestEngine = node.get_engine(config.id) len(engine.trader.generate_order_fills_report()) engine.trader.generate_positions_report() engine.trader.generate_account_report(Venue("SIM")) ``` -------------------------------- ### Start NautilusTrader Development Services with Docker Compose Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Starts all required services for the NautilusTrader development environment using Docker Compose. This includes PostgreSQL, Redis, and PgAdmin. The command `docker-compose up -d` starts the services in detached mode. ```bash docker-compose up -d ``` -------------------------------- ### Set Up Backtest Engine Configuration and Initialization Source: https://nautilustrader.io/docs/nightly/tutorials/backtest_fx_bars Configures and initializes the BacktestEngine for a backtesting run. It sets up basic parameters like trader ID, logging level, and optionally bypasses risk engine checks. ```python # Initialize a backtest configuration config = BacktestEngineConfig( trader_id="BACKTESTER-001", logging=LoggingConfig(log_level="ERROR"), risk_engine=RiskEngineConfig( bypass=True, # Example of bypassing pre-trade risk checks for backtests ), ) # Build backtest engine engine = BacktestEngine(config=config) ``` -------------------------------- ### Install Nautilus Trader Visualization Dependencies Source: https://nautilustrader.io/docs/nightly/concepts/reports Installs the necessary dependencies for visualization features within Nautilus Trader. This command should be run in your terminal or command prompt to enable plotting and charting capabilities. ```bash uv pip install "nautilus_trader[visualization]" ``` -------------------------------- ### Configure Kraken Demo Environment for Futures Trading Source: https://nautilustrader.io/docs/nightly/integrations/kraken Sets up Kraken clients for the demo environment, specifically for Futures trading. This involves specifying the Kraken environment as DEMO and the product type as FUTURES. Assumes API credentials are set as environment variables. ```python from nautilus_trader.adapters.kraken import KRAKEN from nautilus_trader.adapters.kraken import KrakenEnvironment from nautilus_trader.adapters.kraken import KrakenProductType config = TradingNodeConfig( ..., # Omitted data_clients={ KRAKEN: { "environment": KrakenEnvironment.DEMO, "product_types": (KrakenProductType.FUTURES,), }, }, exec_clients={ KRAKEN: { "environment": KrakenEnvironment.DEMO, "product_types": (KrakenProductType.FUTURES,), }, }, ) ``` -------------------------------- ### Install NautilusTrader in Debug Mode Source: https://nautilustrader.io/docs/nightly/developer_guide/environment_setup Installs the NautilusTrader project in debug mode using the Makefile. This is recommended for frequent development iterations as it offers significantly faster compilation times compared to an optimized build. ```shell make install-debug ``` -------------------------------- ### POST /websites/nautilustrader_io_nightly/start Source: https://nautilustrader.io/docs/nightly/api_reference/backtest Starts the component. Any exceptions raised during the on_start() execution will be logged and re-raised, leaving the component in a STARTING state. This method should not be overridden, and attempting to call it when the component is not in a valid state will result in an error log without changing the component's state. ```APIDOC ## POST /websites/nautilustrader_io_nightly/start ### Description Starts the component. Any exceptions raised during the on_start() execution will be logged and re-raised, leaving the component in a STARTING state. This method should not be overridden, and attempting to call it when the component is not in a valid state will result in an error log without changing the component's state. ### Method POST ### Endpoint /websites/nautilustrader_io_nightly/start ### Parameters No parameters required. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **void** - This endpoint does not return a value upon successful execution. #### Response Example ```json // No response body ``` ### 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. ``` -------------------------------- ### Get Component State Source: https://nautilustrader.io/docs/nightly/api_reference/live Returns the current state of the component. The state indicates whether the component is starting, running, stopping, or in another lifecycle phase. ```python state() ``` -------------------------------- ### Generate Performance Statistics from Backtest Results Source: https://nautilustrader.io/docs/nightly/getting_started/quickstart Extracts and displays key performance metrics from the completed backtest. This includes generating reports for account status, open positions, and executed orders, providing insights into the strategy's profitability and trading activity. ```python # Get performance statistics # Get the account and positions account = engine.trader.generate_account_report(Venue("SIM")) positions = engine.trader.generate_positions_report() orders = engine.trader.generate_order_fills_report() ``` -------------------------------- ### Get Strategies and Strategy IDs from Trader Source: https://nautilustrader.io/docs/nightly/api_reference/trading Retrieve lists of loaded strategies and their corresponding IDs from the trader. These functions are essential for inspecting the current trading setup. ```python strategies() → list[Strategy] Return the strategies loaded in the trader. * **Return type:** list[Strategy] strategy_ids() → list[StrategyId] Return the strategy IDs loaded in the trader. * **Return type:** list[StrategyId] ``` -------------------------------- ### Initialize and Build Nautilus Trader Node with Kraken Clients Source: https://nautilustrader.io/docs/nightly/integrations/kraken Demonstrates how to initialize a Nautilus Trader TradingNode with a given configuration and then register the Kraken client factories for live data and execution. Finally, it builds the node, making it ready for operation. ```python from nautilus_trader.adapters.kraken import KRAKEN from nautilus_trader.adapters.kraken import KrakenLiveDataClientFactory from nautilus_trader.adapters.kraken import KrakenLiveExecClientFactory from nautilus_trader.live.node import TradingNode # Instantiate the live trading node with a configuration node = TradingNode(config=config) # Register the client factories with the node node.add_data_client_factory(KRAKEN, KrakenLiveDataClientFactory) node.add_exec_client_factory(KRAKEN, KrakenLiveExecClientFactory) # Finally build the node node.build() ``` -------------------------------- ### Tokio MPSC Unbounded Channel Creation and Handler Setup (Rust) Source: https://nautilustrader.io/docs/nightly/developer_guide/adapters Demonstrates the creation of unbounded MPSC channels for venue and output messages using tokio, and the subsequent setup of a FeedHandler that consumes these channels. This illustrates the `raw` -> `msg` -> `out` channel transformation pipeline. ```rust // Client creates venue message and output channels let (msg_tx, msg_rx) = tokio::sync::mpsc::unbounded_channel(); // Venue messages (BybitWsMessage) let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel(); // Nautilus messages (NautilusWsMessage) // Handler receives venue messages, outputs Nautilus messages let handler = FeedHandler::new( cmd_rx, msg_rx, // Input: BybitWsMessage out_tx, // Output: NautilusWsMessage // ... ); ``` -------------------------------- ### Initialize ParquetDataCatalog from URI in Python Source: https://nautilustrader.io/docs/nightly/concepts/data Demonstrates initializing the ParquetDataCatalog using a URI string. The `from_uri` method automatically parses the protocol and storage options from the provided URI, simplifying initialization for local filesystems and cloud storage like S3. ```python # Local filesystem catalog = ParquetDataCatalog.from_uri("/path/to/catalog") # S3 bucket catalog = ParquetDataCatalog.from_uri("s3://my-bucket/nautilus-data/") ``` -------------------------------- ### Documenting Documentation Updates in Release Notes Source: https://nautilustrader.io/docs/nightly/developer_guide/releases Explains how to document changes to guides and examples. Entries should clearly state what was added or improved. ```markdown - Added rate limit tables with links to official docs - Improved dark and light themes for readability - Fixed broken links ``` -------------------------------- ### LiveExecutionClient Initialization Source: https://nautilustrader.io/docs/nightly/api_reference/live Initializes the LiveExecutionClient with necessary parameters for connecting to a trading venue. ```APIDOC ## LiveExecutionClient ### Description The base class for all live execution clients. This class is responsible for interfacing with a particular API which may be presented directly by a venue, or through a broker intermediary. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **loop** (_asyncio.AbstractEventLoop_) – The event loop for the client. * **client_id** (_ClientId_) – The client ID. * **venue** (Venue or `None`) – The client venue. If multi-venue then can be `None`. * **instrument_provider** (_InstrumentProvider_) – The instrument provider for the client. * **account_type** (_AccountType_) – The account type for the client. * **base_currency** (_Currency_ _,_ _optional_) – The account base currency for the client. Use `None` for multi-currency accounts. * **msgbus** (_MessageBus_) – The message bus for the client. * **cache** (_Cache_) – The cache for the client. * **clock** (_LiveClock_) – The clock for the client. * **config** (_NautilusConfig_ _,_ _optional_) – The configuration for the instance. ### Raises **ValueError** – If oms_type is `UNSPECIFIED` (must be specified). ### WARNING This class should not be used directly, but through a concrete subclass. ``` -------------------------------- ### Release Notes Style Guide - Specificity Example Source: https://nautilustrader.io/docs/nightly/developer_guide/releases Illustrates the importance of being specific in release notes, contrasting a vague improvement with a precise one. ```markdown ❌ Improved Binance adapter ✅ Improved Binance fill handling when instrument not cached ``` -------------------------------- ### LiveRiskEngine Initialization Source: https://nautilustrader.io/docs/nightly/api_reference/live Initializes the LiveRiskEngine with necessary dependencies and configuration. ```APIDOC ## LiveRiskEngine Class Bases: `RiskEngine` Provides a high-performance asynchronous live risk engine. ### Parameters - **loop** (_asyncio.AbstractEventLoop_) – The event loop for the engine. - **portfolio** (_PortfolioFacade_) – The portfolio for the engine. - **msgbus** (_MessageBus_) – The message bus for the engine. - **cache** (_CacheFacade_) – The read-only cache for the engine. - **clock** (_LiveClock_) – The clock for the engine. - **config** (_LiveRiskEngineConfig_) – The configuration for the instance. ### Raises - **TypeError** – If config is not of type LiveRiskEngineConfig. ``` -------------------------------- ### Initialize Binance Spot Execution Client Source: https://nautilustrader.io/docs/nightly/api_reference/adapters/binance Initializes an execution client for the Binance Spot/Margin exchange. It requires an asyncio event loop, an HTTP client, a message bus, cache, clock, instrument provider, WebSocket base URL, configuration, and optionally an account type and client name. ```python class BinanceSpotExecutionClient(BinanceCommonExecutionClient): def __init__( self, loop: asyncio.AbstractEventLoop, client: BinanceHttpClient, msgbus: MessageBus, cache: Cache, clock: LiveClock, instrument_provider: BinanceSpotInstrumentProvider, base_url_ws: str, config: BinanceExecClientConfig, account_type: BinanceAccountType = 'SPOT', name: str | None = None, ): super().__init__(...) ``` -------------------------------- ### Get Dataset Range (Python) Source: https://nautilustrader.io/docs/nightly/tutorials/databento_overview Determines the available historical data range for a specified dataset. The start and end values returned can be used with other API endpoints for data retrieval. ```python available_range = client.metadata.get_dataset_range(dataset="GLBX.MDP3") available_range ``` -------------------------------- ### Start Redis Docker Container Source: https://nautilustrader.io/docs/nightly/getting_started/installation Starts a Redis container using Docker. This command pulls the latest Redis image, runs it in detached mode, names it 'redis', and maps the default Redis port 6379. This is useful for setting up Redis as an optional backend for NautilusTrader's cache or message bus. ```bash docker run -d --name redis -p 6379:6379 redis:latest ```