Skip to content

Martingale42/nautilus-dev / skills/nt-trading

nt-trading

Verified

Use when working with strategy logic, order execution, risk management, position/portfolio tracking, or exec algorithms in NautilusTrader.

FileKindSize
SKILL.mdskill md18.0 KB
references/api/.gitkeepother0 B
references/api/accounting.mdmarkdown888 B
references/api/events.mdmarkdown543 B
references/api/execution.mdmarkdown1.3 KB
references/api/orders.mdmarkdown1.8 KB
references/api/portfolio.mdmarkdown380 B
references/api/position.mdmarkdown162 B
references/api/risk.mdmarkdown359 B
references/api/trading.mdmarkdown680 B
references/architecture_patterns.mdmarkdown16.2 KB
references/concepts/.gitkeepother0 B
references/concepts/actors.mdmarkdown14.9 KB
references/concepts/execution.mdmarkdown23.1 KB
references/concepts/orders.mdmarkdown42.6 KB
references/concepts/portfolio.mdmarkdown6.7 KB
references/concepts/positions.mdmarkdown17.2 KB
references/concepts/rust.mdmarkdown16.1 KB
references/concepts/strategies.mdmarkdown25.7 KB
references/examples/.gitkeepother0 B
references/examples/actor_data/README.mdmarkdown653 B
references/examples/actor_data/run_example.pyscript3.9 KB
references/examples/actor_data/strategy.pyscript5.6 KB
references/examples/actor_signals/README.mdmarkdown669 B
references/examples/actor_signals/run_example.pyscript3.9 KB
references/examples/actor_signals/strategy.pyscript4.8 KB
references/examples/crypto_ema_cross_ethusdt_trade_ticks.pyexecutablescript5.3 KB
references/examples/fx_ema_cross_audusd_bars_from_ticks.pyexecutablescript4.2 KB
references/examples/msgbus/README.mdmarkdown1.0 KB
references/examples/msgbus/run_example.pyscript3.9 KB
references/examples/msgbus/strategy.pyscript4.5 KB
references/examples/rust_trading/examples/actors/imbalance/actor.rsscript6.5 KB
references/examples/rust_trading/examples/actors/imbalance/config.rsscript2.8 KB
references/examples/rust_trading/examples/mod.rsscript963 B
references/examples/rust_trading/examples/strategies/ema_cross.rsscript4.9 KB
references/examples/rust_trading/examples/strategies/ema_cross/config.rsscript3.7 KB
references/examples/rust_trading/examples/strategies/ema_cross/strategy.rsscript4.6 KB
references/examples/rust_trading/examples/strategies/grid_mm.rsscript31.0 KB
references/examples/rust_trading/examples/strategies/grid_mm/config.rsscript6.9 KB
references/examples/rust_trading/examples/strategies/grid_mm/strategy.rsscript13.3 KB
references/examples/rust_trading/examples/strategies/mod.rsscript1.1 KB
references/guides/.gitkeepother0 B
references/guides/rust_patterns.mdmarkdown17.2 KB
references/guides/testing.mdmarkdown7.9 KB
references/guides/troubleshooting_rust.mdmarkdown12.3 KB
references/guides/write_rust_actor.mdmarkdown3.9 KB
references/guides/write_rust_strategy.mdmarkdown4.7 KB
templates/.gitkeepother0 B
templates/actor.pyscript2.1 KB
templates/exec_algorithm.pyscript2.4 KB
templates/strategy.pyscript3.8 KB

references/guides/testing.md

View on GitHub
# Testing

Our automated tests serve as executable specifications for the trading platform.
A healthy suite documents intended behaviour, gives contributors confidence to refactor, and catches regressions before they reach production.
Tests also double as living examples that clarify complex flows and provide rapid CI feedback so issues surface early.

The suite covers these categories:

- Unit tests
- Integration tests
- Acceptance tests
- Performance tests
- Property-based tests
- Fuzzing
- Memory leak tests

## Property-based testing

Property testing verifies that logic holds for *all* valid inputs, not just hand-picked examples.
We use [`proptest`](https://altsysrq.github.io/proptest-book/intro.html) in Rust to enforce invariants.

- **Use cases:** Core domain types (`Price`, `Quantity`, `UnixNanos`), accounting engines, matching engines, and state machines.
- **Example invariants:**
  - Round-trip serialization: `parse(to_string(value)) == value`
  - Inverse operations: `(A + B) - B == A`
  - Transitivity: `If A < B and B < C, then A < C`

## Fuzzing

Fuzzing introduces unstructured or malicious data to the system to ensure it fails gracefully.

- **Use cases:** Network boundaries, exchange data parsers (JSON, FIX, WebSocket feeds), and complex state machines.
- **Goal:** The system returns a `Result::Err` and never panics, hangs, or leaks memory when encountering malformed data.

When building or modifying core types, write property tests to cover the mathematical boundaries.

Performance tests help evolve performance-critical components.

Run tests with [pytest](https://docs.pytest.org), our primary test runner.
Use parametrized tests and fixtures (e.g., `@pytest.mark.parametrize`) to avoid repetitive code and improve clarity.

## Running tests

### Python tests

From the repository root:

```bash
make pytest
# or
uv run --active --no-sync pytest --new-first --failed-first
# or
pytest
```

For performance tests:

```bash
make test-performance
# or
uv run --active --no-sync pytest tests/performance_tests --benchmark-disable-gc --codspeed
```

The `--benchmark-disable-gc` flag prevents garbage collection from skewing results. Run performance tests in isolation (not with unit tests) to avoid interference.

### Rust tests

```bash
make cargo-test
# or
cargo nextest run --workspace --features "python,ffi,high-precision,defi" --cargo-profile nextest
```

#### Testing with optional features

Use `EXTRA_FEATURES` to include optional features like `capnp` or `hypersync`:

```bash
# Test with capnp feature
make cargo-test EXTRA_FEATURES="capnp"

# Test with multiple features
make cargo-test EXTRA_FEATURES="capnp hypersync"

# Legacy shorthand for hypersync
make cargo-test HYPERSYNC=true

# Test specific crate with features
make cargo-test-crate-nautilus-serialization FEATURES="capnp"
```

### IDE integration

- **PyCharm**: Right-click the tests folder or file → "Run pytest".
- **VS Code**: Use the Python Test Explorer extension.

## Test style

- Name test functions after what they exercise; you do not need to encode the expected assertions in the name.
- Add docstrings when they clarify setup, scenarios, or expectations.
- Prefer pytest-style free functions for Python tests instead of test classes with setup methods.
- **Group assertions** when possible: perform all setup/act steps first, then assert together to avoid the act-assert-act smell.
- Use `unwrap`, `expect`, or direct `panic!`/`assert` calls inside tests; clarity and conciseness matter more than defensive error handling here.

For Rust-specific test conventions (module structure, `#[rstest]`, parameterization), see the [Rust guide](rust.md#testing-conventions).

## Waiting for asynchronous effects

When waiting for background work to complete, prefer the polling helpers `await eventually(...)` from `nautilus_trader.test_kit.functions` and `wait_until_async(...)` from `nautilus_common::testing` instead of arbitrary sleeps. They surface failures faster and reduce flakiness in CI because they stop as soon as the condition is satisfied or time out with a useful error.

## Mocks

Prefer hand-written stubs that return fixed values over mocking frameworks. Use `MagicMock` only when you need to assert call counts/arguments or simulate complex state changes. Avoid mocking the objects you're actually testing.

## Code coverage

We generate coverage reports with `coverage` and publish them to [codecov](https://about.codecov.io/).

Aim for high coverage without sacrificing appropriate error handling or causing "test induced damage" to the architecture.

Some branches remain untestable without modifying production behaviour.
For example, a final condition in a defensive if-else block may only trigger for unexpected values; leave these checks in place so future changes can exercise them if needed.

Design-time exceptions can also be impractical to test, so 100% coverage is not the target.

## Excluded code coverage

We use `pragma: no cover` comments to [exclude code from coverage](https://coverage.readthedocs.io/en/coverage-4.3.3/excluding.html) when tests would be redundant.
Typical examples include:

- Asserting an abstract method raises `NotImplementedError` when called.
- Asserting the final condition check of an if-else block when impossible to test (as above).

Such tests are expensive to maintain because they must track refactors while providing little value.
Ensure concrete implementations of abstract methods remain fully covered.
Remove `pragma: no cover` when it no longer applies and restrict its use to the cases above.

## Debugging Rust tests

Use the default test configuration to debug Rust tests.

To run the full suite with debug symbols for later, run `make cargo-test-debug` instead of `make cargo-test`.

In IntelliJ IDEA, adjust the run configuration for parametrised `#[rstest]` cases so it reads `test --package nautilus-model --lib data::bar::tests::test_get_time_bar_start::case_1`
(remove `-- --exact` and append `::case_n` where `n` starts at 1). This workaround matches the behaviour explained [here](https://github.com/rust-lang/rust-analyzer/issues/8964#issuecomment-871592851).

In VS Code you can pick the specific test case to debug directly.

## Python + Rust Mixed Debugging

This workflow lets you debug Python and Rust code simultaneously from a Jupyter notebook inside VS Code.

### Setup

Install these VS Code extensions: Rust Analyzer, CodeLLDB, Python, Jupyter.

### Step 0: Compile `nautilus_trader` with debug symbols

   ```bash
   cd nautilus_trader && make build-debug-pyo3
   ```

### Step 1: Set up debugging configuration

```python
from nautilus_trader.test_kit.debug_helpers import setup_debugging

setup_debugging()
```

This command creates the required VS Code debugging configurations and starts a `debugpy` server for the Python debugger.

By default `setup_debugging()` expects the `.vscode` folder one level above the `nautilus_trader` root directory.
Adjust the target location if your workspace layout differs.

### Step 2: Set breakpoints

- **Python breakpoints:** Set in VS Code in the Python source files.
- **Rust breakpoints:** Set in VS Code in the Rust source files.

### Step 3: Start mixed debugging

1. In VS Code select the **"Debug Jupyter + Rust (Mixed)"** configuration.
2. Start debugging (F5) or press the green run arrow.
3. Both Python and Rust debuggers attach to your Jupyter session.

### Step 4: Execute code

Run Jupyter notebook cells that call Rust functions. The debugger stops at breakpoints in both Python and Rust code.

### Available configurations

`setup_debugging()` creates these VS Code configurations:

- **`Debug Jupyter + Rust (Mixed)`** - Mixed debugging for Jupyter notebooks.
- **`Jupyter Mixed Debugging (Python)`** - Python-only debugging for notebooks.
- **`Rust Debugger (for Jupyter debugging)`** - Rust-only debugging for notebooks.

### Example

Open and run the example notebook: `debug_mixed_jupyter.ipynb`.

### Reference

- [PyO3 debugging](https://pyo3.rs/v0.25.1/debugging.html?highlight=deb#debugging-from-jupyter-notebooks)
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall