Package: nautilus_trader
BranchVersionStatusmasternightlydevelopPlatformRustPythonLinux (x86_64)1.76.0+3.10+macOS (x86_64)1.76.0+3.10+macOS (arm64)1.76.0+3.10+Windows (x86_64)1.76.0+3.10+Website:https://nautilustrader.ioDocs:https://docs.nautilustrader.ioSupport:support@nautilustrader.ioIntroductionNautilusTrader is an open-source, high-performance, production-grade algorithmic trading platform,
providing quantitative traders with the ability to backtest portfolios of automated trading strategies
on historical data with an event-driven engine, and also deploy those same strategies live, with no code changes.The platform is 'AI-first', designed to develop and deploy algorithmic trading strategies within a highly performant
and robust Python native environment. This helps to address the parity challenge of keeping the Python research/backtest
environment, consistent with the production live trading environment.NautilusTraders design, architecture and implementation philosophy holds software correctness and safety at the
highest level, with the aim of supporting Python native, mission-critical, trading system backtesting
and live deployment workloads.The platform is also universal and asset class agnostic - with any REST, WebSocket or FIX API able to be integrated via modular
adapters. Thus, it can handle high-frequency trading operations for any asset classes
including FX, Equities, Futures, Options, CFDs, Crypto and Betting - across multiple venues simultaneously.FeaturesFast- C-level speed through Rust and Cython. Asynchronous networking withuvloopReliable- Type safety through Rust and Cython. Redis backed performant state persistencePortable- OS independent, runs on Linux, macOS, Windows. Deploy using DockerFlexible- Modular adapters mean any REST, WebSocket, or FIX API can be integratedAdvanced- Time in forceIOC,FOK,GTD,AT_THE_OPEN,AT_THE_CLOSE, advanced order types and conditional triggers. Execution instructionspost-only,reduce-only, and icebergs. Contingency order lists includingOCO,OTOCustomizable- Add user defined custom components, or assemble entire systems from scratch leveraging the cache and message busBacktesting- Run with multiple venues, instruments and strategies simultaneously using historical quote tick, trade tick, bar, order book and custom data with nanosecond resolutionLive- Use identical strategy implementations between backtesting and live deploymentsMulti-venue- Multiple venue capabilities facilitate market making and statistical arbitrage strategiesAI Agent Training- Backtest engine fast enough to be used to train AI trading agents (RL/ES)nautilus - from ancient Greek 'sailor' and naus 'ship'.The nautilus shell consists of modular chambers with a growth factor which approximates a logarithmic spiral.
The idea is that this can be translated to the aesthetics of design and architecture.Why NautilusTrader?Highly performant event-driven Python- native binary core componentsParity between backtesting and live trading- identical strategy codeReduced operational risk- risk management functionality, logical correctness and type safetyHighly extendable- message bus, custom components and actors, custom data, custom adaptersTraditionally, trading strategy research and backtesting might be conducted in Python (or other suitable language)
using vectorized methods, with the strategy then needing to be reimplemented in a more event-drive way
using C++, C#, Java or other statically typed language(s). The reasoning here is that vectorized backtesting code cannot
express the granular time and event dependent complexity of real-time trading, where compiled languages have
proven to be more suitable due to their inherently higher performance, and type safety.One of the key advantages of NautilusTrader here, is that this reimplementation step is now circumvented - as the critical core components of the platform
have all been written entirely in Rust or Cython. This means we're using the right tools for the job, where systems programming languages compile performant binaries,
with CPython C extension modules then able to offer a Python native environment, suitable for professional quantitative traders and trading firms.Why Python?Python was originally created decades ago as a simple scripting language with a clean straight
forward syntax. It has since evolved into a fully fledged general purpose object-oriented
programming language. Based on the TIOBE index, Python is currently the most popular programming language in the world.
Not only that, Python has become thede facto lingua francaof data science, machine learning, and artificial intelligence.The language out of the box is not without its drawbacks however, especially in the context of
implementing large performance-critical systems. Cython has addressed a lot of these issues, offering all the advantages
of a statically typed language, embedded into Pythons rich ecosystem of software libraries and
developer/user communities.What is Cython?Cythonis a compiled programming language which aims to be a superset of the Python programming
language, designed to give C-like performance with code that is written in Python - with
optional C-inspired syntax.The project heavily utilizes Cython to provide static type safety and increased performance
for Python throughC extension modules. The vast majority of the production code is actually
written in Cython, however the libraries can be accessed from both Python and Cython.What is Rust?Rustis a multi-paradigm programming language designed for performance and safety, especially safe
concurrency. Rust is blazingly fast and memory-efficient (comparable to C and C++) with no garbage collector.
It can power mission-critical systems, run on embedded devices, and easily integrates with other languages.Rust’s rich type system and ownership model guarantees memory-safety and thread-safety deterministically —
eliminating many classes of bugs at compile-time.The project increasingly utilizes Rust for core performance-critical components. Python language binding is handled through
Cython, with static libraries linked at compile-time before the wheel binaries are packaged, so a user
does not need to have Rust installed to run NautilusTrader. In the future as more Rust code is introduced,PyO3will be leveraged for easier Python bindings.This project makes theSoundness Pledge:“The intent of this project is to be free of soundness bugs.
The developers will do their best to avoid them, and welcome help in analyzing and fixing them.”Architecture (data flow)Quality AttributesReliabilityPerformanceModularityTestabilityMaintainabilityDeployabilityIntegrationsNautilusTrader is designed in a modular way to work with 'adapters' which provide
connectivity to data providers and/or trading venues - converting their raw API
into a unified interface. The following integrations are currently supported:NameIDTypeStatusDocsBetfairBETFAIRSports betting exchangeGuideBinanceBINANCECrypto exchange (CEX)GuideBinance USBINANCECrypto exchange (CEX)GuideBinance FuturesBINANCECrypto exchange (CEX)GuideBybitBYBITCrypto exchange (CEX)DatabentoDATABENTOData providerInteractive BrokersINTERACTIVE_BROKERSBrokerage (multi-venue)GuideRefer to theIntegrationsdocumentation for further details.InstallationFrom PyPIWe recommend running the platform with the latest stable version of Python, and in a virtual environment to isolate the dependencies.To install the latest binary wheel from PyPI:pip install -U nautilus_traderFrom SourceInstallation from source requires thePython.hheader file, which is included in development releases such aspython-dev.
You'll also need the latest stablerustcandcargoto compile the Rust libraries.For MacBook Pro M1/M2, make sure your Python installed using pyenv is configured with--enable-shared:PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install <python_version>Seehttps://pyo3.rs/latest/getting_started#virtualenvs.It's possible to install from source usingpipif you first install the build dependencies
as specified in thepyproject.toml. However, we highly recommend installing usingpoetryas below.Installrustup(the Rust toolchain installer):Linux and macOS:curl https://sh.rustup.rs -sSf | shWindows:Download and installrustup-init.exeInstall "Desktop development with C++" withBuild Tools for Visual Studio 2019Enablecargoin the current shell:Linux and macOS:source $HOME/.cargo/envWindows:Start a new PowerShellInstall poetry (or follow the installation guide on their site):curl -sSLhttps://install.python-poetry.org| python3 -Clone the source withgit, and install from the projects root directory:git clonehttps://github.com/nautechsystems/nautilus_tradercd nautilus_trader
poetry install --only main --all-extrasRefer to theInstallation Guidefor other options and further details.Versioning and releasesNautilusTrader is currently following a bi-weekly beta release schedule.
The API is becoming more stable, however breaking changes are still possible between releases.
Documentation of these changes in the release notes are made on a best-effort basis.Branchesmasterbranch will always reflect the source code for the latest released versionnightlybranch may contain experimental features and is generally merged fromdevelopbranch daily, and also when requireddevelopbranch is normally very active with frequent commits and may contain experimental features. We aim to maintain a stable
passing build on this branchThe current roadmap has a goal of achieving a stable API for a2.xversion. From this
point we will follow a formal process for releases, with deprecation periods for any API changes.MakefileAMakefileis provided to automate most installation and build tasks for development. It provides the following targets:make install-- Installs inreleasebuild mode withmain,devandtestdependencies then installs the package using poetry (default)make install-debug-- Same asmake installbut withdebugbuild modemake install-just-deps-- Installs just themain,devandtestdependencies (does not install package)make install-just-deps-all-- Same asmake install-just-depsand additionally installsdocsdependenciesmake build-- Runs the Cython build script inreleasebuild mode (default)make build-debug-- Runs the Cython build script indebugbuild modemake build-wheel-- Runs the Poetry build with a wheel format inreleasemodemake build-wheel-debug-- Runs the Poetry build with a wheel format indebugmodemake clean--CAUTIONCleans all non-source artifacts from the repositorymake docs-- Builds the documentation HTML using Sphinxmake pre-commit-- Runs the pre-commit checks over all filesmake ruff-- Runs ruff over all files using thepyproject.tomlconfigmake outdated-- Runs commands to show outdated dependencies for both Rust and Pythonmake pytest-- Runs all tests withpytest(except performance tests)make pytest-coverage-- Same asmake pytestand additionally runs with test coverage and produces a reportExamplesIndicators and strategies can be developed in both Python and Cython (although if performance and latency sensitivity are import we recommend Cython).
The below are some examples of this:indicatorexample written in Pythonindicatorexamples written in Cythonstrategyexamples written in both Python and Cythonbacktestexamples using aBacktestEnginedirectlyDockerDocker containers are built using a basepython:3.11-slimwith the following image variant tags:nautilus_trader:latesthas the latest release version installednautilus_trader:nightlyhas the head of thenightlybranch installedjupyterlab:latesthas the latest release version installed along withjupyterlaband an
example backtest notebook with accompanying datajupyterlab:nightlyhas the head of thenightlybranch installed along withjupyterlaband an
example backtest notebook with accompanying dataThe container images can be pulled as follows:docker pull ghcr.io/nautechsystems/<image_variant_tag> --platform linux/amd64You can launch the backtest example container by running:docker pull ghcr.io/nautechsystems/jupyterlab:nightly --platform linux/amd64
docker run -p 8888:8888 ghcr.io/nautechsystems/jupyterlab:nightlyThen open your browser at the following address:http://127.0.0.1:8888/lab:warning: WARNINGNautilusTrader currently exceeds the rate limit for Jupyter notebook logging (stdout output),
this is whylog_levelin the examples is set toERROR. 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/12845https://github.com/deshaw/jupyterlab-limit-outputMinimal StrategyThe following is a minimal EMA Cross strategy example which just uses bar data.
While trading strategies can become very advanced with this platform, it's still possible to put
together simple strategies. First inherit from theStrategybase class, then only the
methods which are required by the strategy need to be implemented.classEMACross(Strategy):"""A simple moving average cross example strategy.When the fast EMA crosses the slow EMA then enter a position at the marketin that direction.Cancels all orders and closes all positions on stop."""def__init__(self,config:EMACrossConfig)->None:super().__init__(config)# Configurationself.instrument_id=config.instrument_idself.bar_type=config.bar_typeself.trade_size=Decimal(config.trade_size)# Create the indicators for the strategyself.fast_ema=ExponentialMovingAverage(config.fast_ema_period)self.slow_ema=ExponentialMovingAverage(config.slow_ema_period)self.instrument:Instrument|None=None# Initialized in on_startdefon_start(self)->None:"""Actions to be performed on strategy start."""# Get instrumentself.instrument=self.cache.instrument(self.instrument_id)# Register the indicators for updatingself.register_indicator_for_bars(self.bar_type,self.fast_ema)self.register_indicator_for_bars(self.bar_type,self.slow_ema)# Get historical dataself.request_bars(self.bar_type)# Subscribe to live dataself.subscribe_bars(self.bar_type)defon_bar(self,bar:Bar)->None:"""Actions to be performed when the strategy receives a bar."""# BUY LOGICifself.fast_ema.value>=self.slow_ema.value:ifself.portfolio.is_flat(self.instrument_id):self.buy()elifself.portfolio.is_net_short(self.instrument_id):self.close_all_positions(self.instrument_id)self.buy()# SELL LOGICelifself.fast_ema.value<self.slow_ema.value:ifself.portfolio.is_flat(self.instrument_id):self.sell()elifself.portfolio.is_net_long(self.instrument_id):self.close_all_positions(self.instrument_id)self.sell()defbuy(self)->None:"""Users simple buy method (example)."""order:MarketOrder=self.order_factory.market(instrument_id=self.instrument_id,order_side=OrderSide.BUY,quantity=self.instrument.make_qty(self.trade_size),)self.submit_order(order)defsell(self)->None:"""Users simple sell method (example)."""order:MarketOrder=self.order_factory.market(instrument_id=self.instrument_id,order_side=OrderSide.SELL,quantity=self.instrument.make_qty(self.trade_size),)self.submit_order(order)defon_stop(self)->None:"""Actions to be performed when the strategy is stopped."""# Cleanup orders and positionsself.cancel_all_orders(self.instrument_id)self.close_all_positions(self.instrument_id)# Unsubscribe from dataself.unsubscribe_bars(self.bar_type)defon_reset(self)->None:"""Actions to be performed when the strategy is reset."""# Reset indicators hereself.fast_ema.reset()self.slow_ema.reset()DevelopmentWe aim to provide the most pleasant developer experience possible for this hybrid codebase of Python, Cython and Rust.
Refer to theDeveloper Guidefor helpful information.cargo-nextestis the standard Rust test runner for NautilusTrader. You can install it by running:cargo install cargo-nextestContributingThank you for considering contributing to Nautilus Trader! We welcome any and all help to improve
the project. If you have an idea for an enhancement or a bug fix, the first step is to open anissueon GitHub to discuss it with the team. This helps to ensure that your contribution will be
well-aligned with the goals of the project and avoids duplication of effort.Once you're ready to start working on your contribution, make sure to follow the guidelines
outlined in theCONTRIBUTING.mdfile. This includes signing a Contributor License Agreement (CLA)
to ensure that your contributions can be included in the project.Note that all pull requests should be made to thedevelopbranch. This is where new features
and improvements are integrated before being released to the public.Thank you again for your interest in Nautilus Trader! We look forward to reviewing your contributions and working with you to improve the project.CommunityJoin our community of users and contributors onDiscordto chat
and stay up-to-date with the latest announcements and features of NautilusTrader. Whether you're a
developer looking to contribute or just want to learn more about the platform, all are welcome on our server.LicenseThe source code for NautilusTrader is available on GitHub under theGNU Lesser General Public License v3.0.
Contributions to the project are welcome and require the completion of a standard Contributor License Agreement (CLA).NautilusTrader is developed and maintained by Nautech Systems, a technology
company specializing in the development of high-performance trading systems.
Although the project utilizes the Rust programming language and benefits from its ecosystem,
Nautech Systems is not affiliated with the Rust Foundation, and this project is not an official
work of the Rust Foundation.
For more information, visithttps://nautilustrader.io.Copyright (C) 2015-2024 Nautech Systems Pty Ltd. All rights reserved.