### Copy and Run Rust Quickstart Source: https://nautilustrader.io/docs/latest/how_to/get_started_lighter Copies the Lighter Rust quickstart example to your workspace and runs it. This sets up a LiveNode with a data client connected to the testnet. ```bash cp -R examples/quickstarts/lighter-rust-data-client/ ~/lighter-rust-data-client cd ~/lighter-rust-data-client cargo run ``` -------------------------------- ### Nautilus Trader Strategy Start Handler Example Source: https://nautilustrader.io/docs/latest/concepts/strategies Example implementation of an on_start handler for initializing indicators, requesting historical data, and subscribing to live data. The cache check is crucial for live trading. ```python 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() # Transitions strategy to STOPPED state 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 and subscribe to live data self.request_bars( self.bar_type, callback=lambda _: self.subscribe_bars(self.bar_type), ) self.subscribe_quote_ticks(self.instrument_id) ``` -------------------------------- ### Run dYdX Grid Market Maker Example Source: https://nautilustrader.io/docs/latest/tutorials/grid_market_maker_dydx Execute the dYdX Grid Market Maker example using Cargo. Ensure the 'examples' feature is enabled. ```bash cargo run --example dydx-grid-mm --package nautilus-dydx --features examples ``` -------------------------------- ### Async Runtime Setup with Tokio Source: https://nautilustrader.io/docs/latest/how_to/run_rust_live_trading The `LiveNode::run()` method is asynchronous and requires a Tokio runtime. This example shows how to set up the main function with `#[tokio::main]` to enable async execution. Make sure to include `dotenvy::dotenv().ok();` if you are using environment variables from a `.env` file. ```rust #[tokio::main] async fn main() -> Result<(), Box> { dotenvy::dotenv().ok(); // ... node setup ... node.run().await?; Ok(()) } ``` -------------------------------- ### Install Rustup Source: https://nautilustrader.io/docs/latest/getting_started/installation Installs rustup, the Rust toolchain installer. Run this script to set up the Rust environment. ```shell curl https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### NautilusTrader Developer Guide Structure Example Source: https://nautilustrader.io/docs/latest/developer_guide/docs An example of a typical heading structure for the NautilusTrader Developer Guide, demonstrating hierarchical organization. ```markdown # NautilusTrader Developer Guide ## Getting started with Python ## Using the Binance adapter ## REST API implementation ## WebSocket data streaming ## Testing with pytest ``` -------------------------------- ### Run BitMEX Grid Market Maker Example Source: https://nautilustrader.io/docs/latest/tutorials/grid_market_maker_bitmex Execute the BitMEX Grid Market Maker example using Cargo. Ensure you have the necessary features enabled for examples. ```bash cargo run --example bitmex-grid-mm --package nautilus-bitmex --features examples ``` -------------------------------- ### Python Config: Open Position on Start Source: https://nautilustrader.io/docs/latest/developer_guide/spec_exec_testing Configure the ExecTester to open a position immediately when the strategy starts by setting `open_position_on_start_qty`. ```python ExecTesterConfig( instrument_id=instrument_id, order_qty=Decimal("0.01"), open_position_on_start_qty=Decimal("0.01"), ) ``` -------------------------------- ### Run Betfair Backtest Example Source: https://nautilustrader.io/docs/latest/tutorials/backtest_book_imbalance_betfair Execute the Betfair backtest example using cargo to generate log data for visualization. ```bash IMBALANCE_LOG_INTERVAL=200 cargo run -p nautilus-betfair --features examples --release \ --example betfair-backtest > /tmp/betfair.log 2>&1 ``` -------------------------------- ### Install Nightly Rust Toolchain Source: https://nautilustrader.io/docs/latest/developer_guide/environment_setup Steps to install the nightly Rust toolchain, set it as the override, and install the rust-analyzer component. ```bash rustup install nightly rustup override set nightly rustup component add rust-analyzer # install nightly lsp rustup override set stable # reset to stable ``` -------------------------------- ### Install from GitHub Release Source: https://nautilustrader.io/docs/latest/getting_started/installation Use this command to install a binary wheel from a GitHub release. Replace `.whl` with the actual downloaded file name. ```bash uv pip install .whl ``` -------------------------------- ### Install Development Tools Source: https://nautilustrader.io/docs/latest/developer_guide/environment_setup Installs all development tools pinned in `Cargo.toml` and `tools.toml`. This is the primary command for setting up your development environment. ```bash make install-tools ``` -------------------------------- ### Running Bybit Options Data Examples Source: https://nautilustrader.io/docs/latest/tutorials/options_data_bybit These commands show how to run the Bybit Greeks Tester and Option Chain Tester examples using Cargo. Ensure you have the 'examples' feature enabled for the 'nautilus-bybit' package. ```bash # Per-instrument Greeks cargo run --example bybit-greeks-tester --package nautilus-bybit --features examples # Option chain snapshots cargo run --example bybit-option-chain --package nautilus-bybit --features examples ``` -------------------------------- ### Run Databento Data Tester Example Source: https://nautilustrader.io/docs/latest/integrations/databento This command runs the Databento data tester example, which subscribes to live quotes and trades for configured instruments. ```bash cargo run --example databento-data-tester --package nautilus-databento ``` -------------------------------- ### Install Linux Perf Tools (Debian/Ubuntu) Source: https://nautilustrader.io/docs/latest/developer_guide/benchmarking Install the necessary 'perf' tools for Linux systems, required for profiling. ```bash sudo apt install linux-tools-common linux-tools-$(uname -r) ``` -------------------------------- ### Install Cap'n Proto Source: https://nautilustrader.io/docs/latest/developer_guide/environment_setup Execute this script to install the required version of Cap'n Proto for serialization schema compilation on Linux or macOS. ```bash ./scripts/install-capnp.sh ``` -------------------------------- ### Run NautilusTrader in Docker Source: https://nautilustrader.io/docs/latest/getting_started Pull the NautilusTrader JupyterLab Docker image and run it to access a pre-configured environment. This is useful for getting started without local setup. ```bash docker pull ghcr.io/nautechsystems/jupyterlab:nightly --platform linux/amd64 docker run -p 8888:8888 ghcr.io/nautechsystems/jupyterlab:nightly ``` -------------------------------- ### Run Kraken Hurst VPIN Live Example Source: https://nautilustrader.io/docs/latest/tutorials/hurst_vpin_kraken Execute the live Kraken Hurst VPIN strategy example. Ensure Kraken Futures API credentials are set in the environment before running. ```bash cargo run -p nautilus-kraken --features examples \ --example kraken-hurst-vpin-live ``` -------------------------------- ### Install cargo-flamegraph Source: https://nautilustrader.io/docs/latest/developer_guide/benchmarking Install the cargo-flamegraph tool globally on your machine. This is a one-time setup. ```bash cargo install flamegraph ``` -------------------------------- ### Running the Betfair Backtest Example Source: https://nautilustrader.io/docs/latest/tutorials/backtest_book_imbalance_betfair Commands to build and run the Betfair backtest example. Use the debug build for development and release build for performance. A custom data file can also be specified. ```bash # Debug build cargo run -p nautilus-betfair --features examples --example betfair-backtest ``` ```bash # Release build (recommended) cargo run -p nautilus-betfair --features examples --release --example betfair-backtest ``` ```bash # Custom data file cargo run -p nautilus-betfair --features examples --release --example betfair-backtest -- path/to/file.gz ``` -------------------------------- ### Set up Backtest Engine Source: https://nautilustrader.io/docs/latest/tutorials/gold_book_imbalance_ax Initialize the BacktestEngine with trader and logging configurations. Add venues, instruments, historical data, and the configured strategy to prepare for backtesting. ```python from nautilus_trader.backtest.config import BacktestEngineConfig from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.config import LoggingConfig from nautilus_trader.model.enums import AccountType from nautilus_trader.model.enums import OmsType from nautilus_trader.model.identifiers import TraderId from nautilus_trader.model.identifiers import Venue from nautilus_trader.model.objects import Money engine = BacktestEngine( BacktestEngineConfig( trader_id=TraderId("BACKTESTER-001"), logging=LoggingConfig(log_level="INFO"), ), ) AX = Venue("AX") engine.add_venue( venue=AX, oms_type=OmsType.NETTING, account_type=AccountType.MARGIN, base_currency=USD, starting_balances=[Money(100_000, USD)], ) engine.add_instrument(XAU_PERP) engine.add_data(quotes) engine.add_strategy(strategy) engine.run() ``` -------------------------------- ### Documentation Updates Format Source: https://nautilustrader.io/docs/latest/developer_guide/releases Use this format for changes to guides and examples. Examples include adding rate limit tables or improving themes. ```markdown - Added rate limit tables with links to official docs - Improved dark and light themes for readability - Fixed broken links ``` -------------------------------- ### Configure Lighter Data and Execution Clients Source: https://nautilustrader.io/docs/latest/integrations/lighter Example demonstrating how to build configuration objects for Lighter data and execution clients, specifying the environment and other relevant settings. Credentials can be overridden by directly setting account index, API key index, and private key. ```rust use nautilus_lighter:: common::enums::LighterEnvironment, config::{LighterDataClientConfig, LighterExecClientConfig}; let data_config = LighterDataClientConfig::builder() .environment(LighterEnvironment::Testnet) .build(); let exec_config = LighterExecClientConfig::builder() .trader_id(trader_id) .account_id(account_id) .environment(LighterEnvironment::Testnet) .build(); ``` -------------------------------- ### Run Backtest as a Binary Source: https://nautilustrader.io/docs/latest/tutorials/hurst_vpin_kraken Compiles and runs the Kraken Hurst VPIN backtest example as a release binary. This command assumes the necessary features are enabled. ```bash cargo run -p nautilus-kraken --features examples \ --example kraken-hurst-vpin-backtest --release ``` -------------------------------- ### Import Core NautilusTrader Modules Source: https://nautilustrader.io/docs/latest/getting_started/backtest_high_level Imports essential modules for backtesting, data configuration, engine setup, and strategy implementation. Ensure NautilusTrader is installed. ```python import os import shutil from decimal import Decimal from pathlib import Path import pandas as pd 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.core.datetime import dt_to_unix_nanos from nautilus_trader.model import QuoteTick 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 ``` -------------------------------- ### Setup Mixed Debugging Configuration Source: https://nautilustrader.io/docs/latest/developer_guide/testing Initialize the debugging environment for mixed Python and Rust debugging. This function sets up VS Code debugging configurations and starts a debugpy server. ```python from nautilus_trader.test_kit.debug_helpers import setup_debugging setup_debugging() ``` -------------------------------- ### Configure Backtest Engine Source: https://nautilustrader.io/docs/latest/tutorials/grid_market_maker_bitmex Set up the BacktestEngine with venue, account type, and initial balances. The starting balance for XBTUSD is in BTC as it's BTC-margined. ```python from nautilus_trader.backtest.config import BacktestEngineConfig from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.config import LoggingConfig from nautilus_trader.model.enums import AccountType from nautilus_trader.model.enums import OmsType from nautilus_trader.model.identifiers import TraderId from nautilus_trader.model.identifiers import Venue from nautilus_trader.model.objects import Money engine = BacktestEngine( BacktestEngineConfig( trader_id=TraderId("BACKTESTER-001"), logging=LoggingConfig(log_level="INFO"), ), ) BITMEX = Venue("BITMEX") engine.add_venue( venue=BITMEX, oms_type=OmsType.NETTING, account_type=AccountType.MARGIN, base_currency=BTC, starting_balances=[Money(1, BTC)], ) engine.add_instrument(XBTUSD) engine.add_data(quotes + trades) ``` -------------------------------- ### Generate Synthetic EUR/USD Bars Source: https://nautilustrader.io/docs/latest/getting_started/quickstart Generates 10,000 synthetic 1-minute EUR/USD bars using a random walk. This is useful for self-contained quickstart examples. In practice, load real market data. ```python import numpy as np import pandas as pd from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.config import BacktestEngineConfig from nautilus_trader.config import LoggingConfig from nautilus_trader.model.currencies import USD from nautilus_trader.model.enums import AccountType from nautilus_trader.model.enums import OmsType from nautilus_trader.model.identifiers import Venue from nautilus_trader.model.objects import Money from nautilus_trader.persistence.wranglers import BarDataWrangler from nautilus_trader.test_kit.providers import TestInstrumentProvider # Create a EUR/USD instrument on the SIM venue EURUSD = TestInstrumentProvider.default_fx_ccy("EUR/USD") # Generate synthetic 1-minute bars (random walk around 1.10) rng = np.random.default_rng(42) n = 10_000 price = 1.10 + np.cumsum(rng.normal(0, 0.0002, n)) spread = np.abs(rng.normal(0, 0.0003, n)) bars_df = pd.DataFrame( { "open": price, "high": price + spread, "low": price - spread, "close": price + rng.normal(0, 0.00005, n), }, index=pd.date_range("2024-01-01", periods=n, freq="1min", tz="UTC"), ) bars_df["high"] = bars_df[["open", "high", "close"]].max(axis=1) bars_df["low"] = bars_df[["open", "low", "close"]].min(axis=1) bar_type = BarType.from_str("EUR/USD.SIM-1-MINUTE-LAST-EXTERNAL") bars = BarDataWrangler(bar_type, EURUSD).process(bars_df) ``` -------------------------------- ### Run Delta Neutral Strategy on Derive Source: https://nautilustrader.io/docs/latest/tutorials/delta_neutral_options_derive Configure the Derive environment to mainnet and disable hedging. Execute the delta-neutral example using Cargo, directing output to a log file. This setup is for data collection and visualization, not live trading. ```bash export DERIVE_ENVIRONMENT=mainnet export DERIVE_DELTA_NEUTRAL_HEDGE_ENABLED=false timeout 45 cargo run --example derive-delta-neutral --package nautilus-derive --features examples \ > /tmp/derive_dn.log 2>&1 uv sync --extra visualization export DN_LOG=/tmp/derive_dn.log python3 docs/tutorials/assets/delta_neutral_options_derive/render_panels.py ``` -------------------------------- ### Configure and Run Backtest Engine Source: https://nautilustrader.io/docs/latest/getting_started/quickstart Set up the backtest engine, add a simulated FX venue with a margin account, wire up the instrument, data, and strategy, and then run the backtest. The engine processes bars in timestamp order with deterministic execution. ```python engine = BacktestEngine( config=BacktestEngineConfig( logging=LoggingConfig(log_level="ERROR"), ), ) # Add a simulated FX venue SIM = Venue("SIM") engine.add_venue( venue=SIM, oms_type=OmsType.NETTING, account_type=AccountType.MARGIN, starting_balances=[Money(1_000_000, USD)], base_currency=USD, default_leverage=Decimal(1), ) # Add instrument, data, and strategy engine.add_instrument(EURUSD) engine.add_data(bars) strategy = EMACross( EMACrossConfig( instrument_id=EURUSD.id, bar_type=bar_type, trade_size=Decimal(100000), ), ) engine.add_strategy(strategy) # Run the backtest engine.run() ``` -------------------------------- ### Install uv Source: https://nautilustrader.io/docs/latest/getting_started/installation Installs uv, a fast Python package installer and dependency resolver. This script handles the installation of uv. ```shell curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Run Delta-Neutral Options Example Source: https://nautilustrader.io/docs/latest/tutorials/delta_neutral_options_bybit Execute the delta-neutral options example using Cargo. This command builds and runs the example with the 'nautilus-bybit' package, enabling the 'examples' feature. ```bash cargo run --example bybit-delta-neutral --package nautilus-bybit --features examples ``` -------------------------------- ### Build Documentation with All Features Source: https://nautilustrader.io/docs/latest/developer_guide/rust Use this command to build documentation for the entire workspace, enabling all features and excluding dependencies to ensure comprehensive documentation generation. ```bash cargo +nightly doc --all-features --no-deps --workspace ``` -------------------------------- ### Start Local Blockchain Services Source: https://nautilustrader.io/docs/latest/integrations/blockchain Use these make commands to start the local development environment including Postgres, Redis, and pgAdmin. Ensure these services are running before proceeding with database initialization. ```bash make start-services ``` ```bash make init-db ``` -------------------------------- ### Run Delta Neutral Example Source: https://nautilustrader.io/docs/latest/tutorials/delta_neutral_options_derive Execute the delta neutral options example using Cargo. This command runs the example with default settings. ```bash cargo run --example derive-delta-neutral --package nautilus-derive --features examples ``` -------------------------------- ### Install cargo-binstall Source: https://nautilustrader.io/docs/latest/developer_guide/environment_setup Installs `cargo-binstall` to fetch prebuilt binaries, used by `make install-tools` for tools like `prek`. This is a one-time installation per machine. ```bash cargo install cargo-binstall --locked ``` -------------------------------- ### LiveMarketDataClient Adapter Example Source: https://nautilustrader.io/docs/latest/developer_guide/adapters This example demonstrates the structure of a custom `LiveMarketDataClient` adapter by showing the abstract methods that must be implemented. It includes placeholders for connection, disconnection, and various subscription types. ```python from nautilus_trader.data.messages import RequestBars from nautilus_trader.data.messages import RequestData from nautilus_trader.data.messages import RequestInstrument from nautilus_trader.data.messages import RequestInstruments from nautilus_trader.data.messages import RequestOrderBookDeltas from nautilus_trader.data.messages import RequestOrderBookDepth from nautilus_trader.data.messages import RequestOrderBookSnapshot from nautilus_trader.data.messages import RequestQuoteTicks from nautilus_trader.data.messages import RequestTradeTicks from nautilus_trader.data.messages import SubscribeBars from nautilus_trader.data.messages import SubscribeData from nautilus_trader.data.messages import SubscribeFundingRates from nautilus_trader.data.messages import SubscribeIndexPrices from nautilus_trader.data.messages import SubscribeInstrument from nautilus_trader.data.messages import SubscribeInstrumentClose from nautilus_trader.data.messages import SubscribeInstruments from nautilus_trader.data.messages import SubscribeInstrumentStatus from nautilus_trader.data.messages import SubscribeMarkPrices from nautilus_trader.data.messages import SubscribeOrderBook from nautilus_trader.data.messages import SubscribeQuoteTicks from nautilus_trader.data.messages import SubscribeTradeTicks from nautilus_trader.data.messages import UnsubscribeBars from nautilus_trader.data.messages import UnsubscribeData from nautilus_trader.data.messages import UnsubscribeFundingRates from nautilus_trader.data.messages import UnsubscribeIndexPrices from nautilus_trader.data.messages import UnsubscribeInstrument from nautilus_trader.data.messages import UnsubscribeInstrumentClose from nautilus_trader.data.messages import UnsubscribeInstruments from nautilus_trader.data.messages import UnsubscribeInstrumentStatus from nautilus_trader.data.messages import UnsubscribeMarkPrices from nautilus_trader.data.messages import UnsubscribeOrderBook from nautilus_trader.data.messages import UnsubscribeQuoteTicks from nautilus_trader.data.messages import UnsubscribeTradeTicks from nautilus_trader.live.data_client import LiveMarketDataClient class TemplateLiveMarketDataClient(LiveMarketDataClient): """Example `LiveMarketDataClient` showing the overridable abstract methods.""" async def _connect(self) -> None: raise NotImplementedError("implement `_connect` in your adapter subclass") async def _disconnect(self) -> None: raise NotImplementedError("implement `_disconnect` in your adapter subclass") async def _subscribe(self, command: SubscribeData) -> None: raise NotImplementedError("implement `_subscribe` in your adapter subclass") async def _subscribe_instruments(self, command: SubscribeInstruments) -> None: raise NotImplementedError("implement `_subscribe_instruments` in your adapter subclass") async def _subscribe_instrument(self, command: SubscribeInstrument) -> None: raise NotImplementedError("implement `_subscribe_instrument` in your adapter subclass") async def _subscribe_order_book_deltas(self, command: SubscribeOrderBook) -> None: raise NotImplementedError("implement `_subscribe_order_book_deltas` in your adapter subclass") async def _subscribe_order_book_depth(self, command: SubscribeOrderBook) -> None: raise NotImplementedError("implement `_subscribe_order_book_depth` in your adapter subclass") async def _subscribe_quote_ticks(self, command: SubscribeQuoteTicks) -> None: raise NotImplementedError("implement `_subscribe_quote_ticks` in your adapter subclass") async def _subscribe_trade_ticks(self, command: SubscribeTradeTicks) -> None: raise NotImplementedError("implement `_subscribe_trade_ticks` in your adapter subclass") async def _subscribe_mark_prices(self, command: SubscribeMarkPrices) -> None: raise NotImplementedError("implement `_subscribe_mark_prices` in your adapter subclass") async def _subscribe_index_prices(self, command: SubscribeIndexPrices) -> None: raise NotImplementedError("implement `_subscribe_index_prices` in your adapter subclass") async def _subscribe_bars(self, command: SubscribeBars) -> None: raise NotImplementedError("implement `_subscribe_bars` in your adapter subclass") async def _subscribe_funding_rates(self, command: SubscribeFundingRates) -> None: raise NotImplementedError("implement `_subscribe_funding_rates` in your adapter subclass") async def _subscribe_instrument_status(self, command: SubscribeInstrumentStatus) -> None: raise NotImplementedError("implement `_subscribe_instrument_status` in your adapter subclass") ``` -------------------------------- ### Install Nautilus CLI Source: https://nautilustrader.io/docs/latest/developer_guide/environment_setup Use this Makefile target to install the Nautilus CLI. It relies on `cargo install` and ensures the `nautilus` binary is in your system's PATH. ```makefile make install-cli ``` -------------------------------- ### Complete Polymarket Backtest Example Source: https://nautilustrader.io/docs/latest/integrations/polymarket A full example demonstrating how to set up and run a backtest using Polymarket data with a simple EMA cross strategy. This includes initializing the data loader, configuring the backtest engine, adding instruments and data, and running the strategy. ```python import asyncio from decimal import Decimal from nautilus_trader.adapters.polymarket import POLYMARKET_VENUE from nautilus_trader.adapters.polymarket import PolymarketDataLoader from nautilus_trader.backtest.config import BacktestEngineConfig from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.examples.strategies.ema_cross_long_only import EMACrossLongOnly from nautilus_trader.examples.strategies.ema_cross_long_only import EMACrossLongOnlyConfig from nautilus_trader.model.currencies import pUSD from nautilus_trader.model.data import BarType from nautilus_trader.model.enums import AccountType from nautilus_trader.model.enums import OmsType from nautilus_trader.model.identifiers import TraderId from nautilus_trader.model.objects import Money async def run_backtest(): # Initialize loader and fetch market data loader = await PolymarketDataLoader.from_market_slug("gta-vi-released-before-june-2026") instrument = loader.instrument # Load historical trades from the Polymarket Data API trades = await loader.load_trades() # Configure and run backtest config = BacktestEngineConfig(trader_id=TraderId("BACKTESTER-001")) engine = BacktestEngine(config=config) engine.add_venue( venue=POLYMARKET_VENUE, oms_type=OmsType.NETTING, account_type=AccountType.CASH, base_currency=pUSD, starting_balances=[Money(10_000, pUSD)], ) engine.add_instrument(instrument) engine.add_data(trades) bar_type = BarType.from_str(f"{instrument.id}-100-TICK-LAST-INTERNAL") strategy_config = EMACrossLongOnlyConfig( instrument_id=instrument.id, bar_type=bar_type, trade_size=Decimal("20"), ) strategy = EMACrossLongOnly(config=strategy_config) engine.add_strategy(strategy=strategy) engine.run() # Display results print(engine.trader.generate_account_report(POLYMARKET_VENUE)) # Run the backtest asyncio.run(run_backtest()) ``` -------------------------------- ### Run the Full EMA Cross Example Source: https://nautilustrader.io/docs/latest/how_to/run_rust_backtest Execute the complete EMA Cross backtesting example using the Cargo command. This command compiles and runs the example located in the `nautilus-backtest` crate. ```bash cargo run -p nautilus-backtest --features examples --example engine-ema-cross ``` -------------------------------- ### Initialize Backtest Engine and Configure Venue Source: https://nautilustrader.io/docs/latest/tutorials/fx_mean_reversion_ax Sets up the backtesting engine and configures the AX venue with initial balances and currency. Ensure all necessary imports are present. ```python from nautilus_trader.backtest.config import BacktestEngineConfig from nautilus_trader.backtest.engine import BacktestEngine from nautilus_trader.config import LoggingConfig from nautilus_trader.model.data import BarType from nautilus_trader.model.enums import AccountType from nautilus_trader.model.enums import OmsType from nautilus_trader.model.identifiers import TraderId from nautilus_trader.model.identifiers import Venue from nautilus_trader.model.objects import Money engine = BacktestEngine( BacktestEngineConfig( trader_id=TraderId("BACKTESTER-001"), logging=LoggingConfig(log_level="INFO"), ), ) AX = Venue("AX") engine.add_venue( venue=AX, oms_type=OmsType.NETTING, account_type=AccountType.MARGIN, base_currency=USD, starting_balances=[Money(100_000, USD)], ) ``` -------------------------------- ### Configure Demo Trading Environment Source: https://nautilustrader.io/docs/latest/integrations/binance Set up the adapter for demo trading with simulated funds. Ensure you have generated separate demo API credentials. ```python config = BinanceExecClientConfig( api_key="YOUR_DEMO_API_KEY", api_secret="YOUR_DEMO_API_SECRET", account_type=BinanceAccountType.SPOT, environment=BinanceEnvironment.DEMO, ) ``` -------------------------------- ### Enhancements Release Note Examples Source: https://nautilustrader.io/docs/latest/developer_guide/releases Examples of release notes for user-facing enhancements. ```markdown - Added BitMEX conditional orders support ``` -------------------------------- ### Attribution Examples Source: https://nautilustrader.io/docs/latest/developer_guide/releases Examples of how to attribute external contributors and include issue/PR numbers. ```markdown thanks @username ``` ```markdown thanks for reporting @username ``` ```markdown (#1234) ``` -------------------------------- ### Build LiveNode with OKX Clients Source: https://nautilustrader.io/docs/latest/how_to/run_rust_live_trading Configure and build the `LiveNode` for live trading. This involves setting up data and execution clients for a specific venue (OKX in this example), configuring logging, and defining trader and account identifiers. Reconciliation is disabled for simplicity in this example. ```rust use log::LevelFilter; use nautilus_common::{enums::Environment, logging::logger::LoggerConfig}; use nautilus_live::node::LiveNode; use nautilus_model::identifiers::{AccountId, TraderId}; use nautilus_okx:: common::enums::OKXInstrumentType, config::{OKXDataClientConfig, OKXExecClientConfig}, factories::{OKXDataClientFactory, OKXExecutionClientFactory}; let trader_id = TraderId::from("TESTER-001"); let account_id = AccountId::from("OKX-001"); let data_config = OKXDataClientConfig::builder() .instrument_types(vec![OKXInstrumentType::Swap]) .build(); let exec_config = OKXExecClientConfig::builder() .trader_id(trader_id) .account_id(account_id) .instrument_types(vec![OKXInstrumentType::Swap]) .build(); let log_config = LoggerConfig { stdout_level: LevelFilter::Info, ..Default::default() }; let mut node = LiveNode::builder(trader_id, Environment::Live)? .with_name("MY-NODE-001".to_string()) .with_logging(log_config) .add_data_client( None, Box::new(OKXDataClientFactory::new()), Box::new(data_config), )? .add_exec_client( None, Box::new(OKXExecutionClientFactory::new()), Box::new(exec_config), )? .with_reconciliation(false) // Simplified; enable in production .with_delay_post_stop_secs(5) .build()?; ``` -------------------------------- ### Configuring with Default Values Source: https://nautilustrader.io/docs/latest/developer_guide/adapters Example of creating a configuration instance, using ..Default::default() to include all default values except for explicitly set fields. ```rust let config = VenueExecClientConfig { trader_id, account_id, environment: VenueEnvironment::Testnet, ..Default::default() }; ``` -------------------------------- ### Instrument ID Example Source: https://nautilustrader.io/docs/latest/concepts/instruments An example of a unique InstrumentId for a Binance Futures perpetual contract. ```text ETHUSDT-PERP.BINANCE ``` -------------------------------- ### Internal Improvements Release Note Examples Source: https://nautilustrader.io/docs/latest/developer_guide/releases Examples of release notes for internal implementation changes. ```markdown - Implemented BitMEX ping/pong handling ``` -------------------------------- ### Run Lighter NVDA Composite Market Maker Example Source: https://nautilustrader.io/docs/latest/tutorials/lighter_rwa_composite_mm Execute the example binary from a NautilusTrader checkout. Ensure credential environment variables are set. Defaults to DRY_RUN = true. ```bash cargo run --bin lighter-nvda-composite-mm --package nautilus-tutorials --features examples ``` -------------------------------- ### Install Gitlint Source: https://nautilustrader.io/docs/latest/developer_guide/coding_standards Install gitlint locally using pip to help enforce commit message standards. ```shell uv pip install gitlint ``` -------------------------------- ### Configure BacktestEngine with Kraken Venue Source: https://nautilustrader.io/docs/latest/tutorials/hurst_vpin_kraken Initializes the BacktestEngine and adds a simulated Kraken venue with specific configuration for netting, margin account, and L1 MBP book type. Starting balances are set to 100,000 USD. ```rust use nautilus_backtest::{ config::{BacktestEngineConfig, SimulatedVenueConfig}, engine::BacktestEngine, }; use nautilus_model::{ data::Data, enums::{AccountType, BookType, OmsType}, identifiers::Venue, instruments::{Instrument, InstrumentAny}, types::Money, }; let mut engine = BacktestEngine::new(BacktestEngineConfig::default())?; engine.add_venue( SimulatedVenueConfig::builder() .venue(Venue::from("KRAKEN")) .oms_type(OmsType::Netting) .account_type(AccountType::Margin) .book_type(BookType::L1_MBP) .starting_balances(vec![Money::from("100_000 USD")]) .build()?, )?; engine.add_instrument(&InstrumentAny::CryptoPerpetual(instrument))?; ```