Metadata-Version: 2.5
Name: nlalpha_nautilus
Version: 0.9.2
Summary: Nautilus Trader engine adapter for NLAlpha
Project-URL: Homepage, https://github.com/ruimarj/nlalpha-nautilus
Project-URL: Repository, https://github.com/ruimarj/nlalpha-nautilus
Project-URL: Issues, https://github.com/ruimarj/nlalpha-nautilus/issues
Project-URL: Changelog, https://github.com/ruimarj/nlalpha-nautilus/releases
License-Expression: AGPL-3.0-or-later
License-File: LICENSE
Requires-Python: <3.13,>=3.12
Requires-Dist: nautilus-trader==1.226.0
Requires-Dist: nlalpha-core>=0.7.1
Requires-Dist: nlalpha-performance>=0.6.0
Requires-Dist: numpy<3,>=2.3.3
Requires-Dist: pandas<3,>=2.3
Description-Content-Type: text/markdown

# nlalpha-nautilus

`nlalpha-nautilus` 0.9.2 adapts Nautilus Trader 1.226.0 to the `nlalpha-core` 0.7.x strategy, market, and backtest contracts. It is the event-driven engine installed by the backtest service and its execution images. The provider is discovered through the `nlalpha.engines` entry point `nautilus`; its manifest declares compatible run modes and input schemas.

## Supported account and instruments

The direct provider contract requires `execution.bar_interval`; it does not derive this value from the input bars. The MCP backtest tool can derive the interval from `data.interval` when its execution request omits `bar_interval`, then sends the resolved value to the provider. Direct callers must supply the interval themselves, and every native run still requires valid instrument, capital, venue, and timestamp inputs accepted by the provider.

Set commission as a ratio per instrument in `contract.instruments[<symbol>]`: `maker_fee` and `taker_fee` each default to `0.0` and accept finite values in `[0, 1)` (`0.001` is `0.1%`). Native bar execution charges `taker_fee`, and results include total commission. This MCP field path is not `execution.fee_rate` (the separate Vector setting). Unknown-key validation reports allowed fields for the current config scope and prioritizes unsupported keys in its suggestion. The related fee-contract tests pass; no real strategy or backtest was run.

One run uses one venue, one valuation currency, and a shared NETTING account. `capital` requires a positive `initial` and explicit supported `currency`. `contract.instruments` must define every configured symbol exactly once, with an explicit `instrument_type` and the fields required for that instrument type. The adapter does not infer instrument types from ticker spelling or duplicate capital across symbols. Every instrument's quote, settlement, and valuation currency must match the account currency; cross-currency aggregation is not performed. `crypto_perpetual` requires `execution.account_type="margin"`; the native CASH account rejects it.

Supported `instrument_type` values are `equity`, `futures`, `crypto_perpetual`, and `currency_pair`. Type-specific fields are allow-listed; unknown fields are rejected rather than ignored. Equities and futures use whole-unit quantities; do not provide `size_precision` for either type. Currency pairs and crypto perpetuals accept `size_precision` and `size_increment` to define fractional quantity precision. Futures require `asset_class` (for example `COMMODITY`), `multiplier`, and ISO-8601 timezone-aware `activation` and `expiration` values, with expiration after activation. Currency pairs and crypto perpetuals require an explicit `base_currency`; their `quote_currency` defaults to and must match the account currency. Crypto perpetual `settlement_currency` also defaults to and must match it, and inverse contracts are unsupported. Crypto perpetuals require a margin account. Instrument price precision and increments are validated against the selected type's accepted settings.

For example, a single USD equity can use `capital={"initial":100000,"currency":"USD"}`, `execution={"mode":"native_bar","bar_interval":"1d","account_type":"cash"}`, and `contract={"instruments":{"AAPL":{"instrument_type":"equity","currency":"USD"}}}`. A futures definition must provide its asset class, multiplier, and both timezone-aware lifecycle dates. A crypto perpetual must use `account_type="margin"`, provide `base_currency`, match quote and settlement currencies to capital, and use the non-inverse model. A currency pair likewise needs an explicit base currency and a quote currency matching capital. For both currency-pair and crypto-perpetual quantities, configure `size_precision` and `size_increment` together when the defaults do not match the instrument.

For example, a futures entry includes both timezone-aware lifecycle bounds:

```json
{
  "instrument_type": "futures",
  "asset_class": "COMMODITY",
  "multiplier": 10,
  "activation": "2020-01-01T00:00:00Z",
  "expiration": "2030-01-01T00:00:00Z"
}
```

A currency pair in a USD account must specify its base currency; its quote currency must be USD. For fractional sizing, set `size_precision` and `size_increment` to matching values.

A complete crypto-perpetual contract entry can look like this when the account currency is USD:

```json
{
  "capital": {"initial": 100000, "currency": "USD"},
  "execution": {"account_type": "margin", "mode": "native_bar", "bar_interval": "15m"},
  "contract": {
    "instruments": {
      "BTCUSD-PERP": {
        "instrument_type": "crypto_perpetual",
        "base_currency": "BTC",
        "quote_currency": "USD",
        "settlement_currency": "USD",
        "is_inverse": false,
        "size_precision": 3,
        "size_increment": 0.001
      }
    }
  }
}
```

## Bar data and strategy callbacks

Execution uses native OHLCV bars with `execution.mode="native_bar"` and an explicit positive `execution.bar_interval` aggregation label corresponding to `data.interval`. With explicit `open_time`/`close_time` bounds, their actual session or aggregation endpoints define the bar and need not span the nominal fixed interval. A one-column `datetime` source requires explicit `timestamp_semantics` (`open` or `close`); naive values require an explicit source IANA timezone. Canonical `data_ref` bounds are UTC and carry original source semantics in `time_contract`; raw mixed sources are normalized independently before combination. Bars become UTC close-time events, and sub-microsecond Python Bar values are rejected rather than truncated.

When a source bar price carries more decimal places than the configured instrument `price_precision`, the adapter quantizes OHLC to instrument precision before native execution; strategy callbacks still receive the original JA Bar. This permits unrounded qfq bars. Volume must still fit `size_precision`, and submitted order prices must fit `price_precision`; precision errors name `price_precision`, `price_increment`, `size_precision`, or `size_increment`.

CTA strategies may implement `on_bar(bar)` for sparse per-symbol event times or `on_bars(bars)` for synchronized groups. `on_bar` events are ordered by UTC event time, then configured symbol order. `on_bars` requires every configured symbol at each timestamp on the same exact time grid; missing bars are not filled and the input is not reduced to an intersection. Use the CTA per-symbol history and position APIs for multi-instrument strategies.

## Execution and results

The engine supports one shared account and native instrument/order behavior; it does not replicate account funds per symbol. OHLCV execution uses bar data, without tick/order-book liquidity simulation or invented slippage. Instrument maker/taker fees are applied as configured. Results include actual fills and fees, per-symbol final positions, free cash/equity, an equity curve with initial baseline, timestamp-group snapshots and final post-fee equity, and native rejection/denial diagnostics. `trade_count` is the number of fill events, not completed round trips. Open positions remain open at the end. `performance.total_return` and `risk.max_drawdown` are ratios; unavailable metrics are omitted rather than filled with zero.

## Historical order lifecycle

The CTA strategy submits immutable `Order` commands and can request cancellation by order ID. Local `queued` status means a submission is waiting for the engine; it does not claim native acceptance or execution. `cancel_order` records intent only. Native events determine acceptance, fill progress, average price, rejection, expiry, cancellation, or cancel rejection. Immutable snapshots expose requested and remaining quantity, filled quantity, average price, native timestamp, and reason. A helper's `price` is a reference value, not an execution price.

`diagnostics.final_orders` contains final order snapshots. `diagnostics.order_events` preserves native event arrival order and nanosecond timestamps; lifecycle kinds include `initialized`, `submitted`, `accepted`, `triggered`, `partially_filled`, `filled`, `pending_cancel`, `canceled`, `expired`, `denied`, `rejected`, and `cancel_rejected`, plus other supported Nautilus 1.226 lifecycle events. Native order status names are lower-case; local `queued` is the pre-submission state. Full result diagnostics cap each array at 100 entries and include count/truncated metadata; the complete result remains stored.

`on_order` / `on_trade` callbacks receive native notifications only while the strategy is running; initial events during `on_init` / `on_start` may not be delivered as callbacks, so inspect snapshots for current engine state. `on_stop` is for observation and cleanup only; commands submitted or canceled there fail the job. This order lifecycle is historical simulation. It does not connect to a broker or exchange or establish real-world fills.

This milestone does not provide cross-currency portfolio valuation, multiple venues, multiple independently funded accounts, inferred instrument settings, or Vector's `next_open` semantics. Choose the engine only after confirming the requested instrument, account, bar, and order behavior matches this contract.


## Annualized statistics

The provider emits `metrics.performance.annual_return`, `metrics.risk.annual_volatility`, and `metrics.risk.sharpe_ratio`; annual return and volatility are ratios, Sharpe is dimensionless, and unavailable values are `null` with reasons in `diagnostics.statistics.unavailable`. Set `execution.annualization` to a positive integer observations-per-year assumption. Without it, all three remain unavailable as `annualization_not_provided`; no frequency such as 252 is inferred. `execution.risk_free_rate` is a finite annual rate greater than -1, defaults to 0 from `engine_default`, and, when annualization is configured, is converted to a per-observation rate with `expm1(log1p(rate) / annualization)`.

The initial-equity baseline to the first completed bar-close group counts as one return period, followed by simple returns between completed bar-close groups using net equity. Fees are already reflected in that equity. Irregular timestamp gaps are reported without filling or resampling; annualization is an explicit observation-frequency assumption, not actual elapsed-time CAGR. Diagnostics disclose parameter values/sources, `variance_ddof=1`, return basis, period risk-free rate, unavailable reasons, observation timestamps/count and min/max spacing, irregularity, and fee treatment. A single return is insufficient for volatility/Sharpe; zero variance yields annual volatility 0 and an unavailable Sharpe, while non-positive equity or numerical overflow is reported as unavailable with a reason.

## Native reports

Before disposal, the adapter asks the native trader to generate `orders`, `order_fills`, `fills`, `positions`, and `account` reports and retains native columns and index values. An empty native report is `available` with zero rows. A report-generation error is represented as `unavailable` and fails the backtest. Native `stats_pnls`, `stats_returns`, `stats_general`, and run/analyzer details are preserved under `diagnostics.native_analysis` with provenance. Annualized return uses daily account balance observations with forward fill where possible, falling back to closed-position returns grouped by close time when observations are insufficient; native default annualization is 252. It does not apply shared execution annualization or risk-free rate, does not replace net-equity metrics, and does not explicitly pass unrealized PnL.

## Historical Nautilus 0.6.0 focused verification

Historical Nautilus 0.6.0 focused private verification with a real sparse-time drawdown run, including fee-driven initial-reference censoring with null economic duration and observed-duration lower bound; native analysis remained intact. Nautilus 0.5.0 checks are historical. This is not a full-suite result or benchmark rerun.

## Drawdown episodes

The shared drawdown summary is `metrics.risk.drawdowns` with `episode_count`, `recovered_episode_count`, `unrecovered_episode_count`, and `deepest`, `longest`, `current` episode rows (each nullable when absent). `metrics.risk.max_drawdown` remains the scalar maximum and agrees with `deepest.depth`, or is zero when observations exist without an episode. `reports.drawdowns` uses the standard report envelope and columns: `episode_id`, `status`, `peak_equity`, `peak_timestamp_ns`, `peak_observation_index`, `peak_is_initial`, `start_timestamp_ns`, `start_observation_index`, `trough_equity`, `trough_timestamp_ns`, `trough_observation_index`, `recovery_equity`, `recovery_timestamp_ns`, `recovery_observation_index`, `end_timestamp_ns`, `end_observation_index`, `depth`, `decline_duration_ns`, `recovery_duration_ns`, `duration_ns`, `observed_duration_ns`, `duration_is_lower_bound`, `decline_observations`, `recovery_observations`, `duration_observations`. The Vector and Nautilus schema IDs and sources remain engine-specific.

Episodes use completed-bar-close net equity, with fees already reflected. The initial-capital reference is index 0 but has no economic timestamp; its actual reference timestamp, when known, is informational metadata only. The high-water mark resets on equal or greater equity (latest equal peak); a drawdown starts strictly below it, recovery is the first observation at or above the episode peak, and equal troughs keep the earliest trough. Depth is `(peak_equity - trough_equity) / peak_equity`, a proportion. `deepest` chooses greatest depth (ties: earlier episode); `longest` means longest observed drawdown, ordered by observed elapsed duration, then observation intervals, then earlier episode.

If the peak is initial capital, peak timestamp, decline duration and total duration are null because the economic start is unknown. Observed duration from the first underwater point is only a lower bound (`duration_is_lower_bound=true`). Recovery duration is measured from trough to recovery only for recovered episodes; unrecovered recovery fields remain null. Elapsed nanoseconds and observation interval counts are separate, exact quantities: the initial reference to the first actual observation counts as an interval, never as a fabricated 1 ns. An episode still open at sample end uses the last observed point as its observational end without assuming recovery. No observations yield `unavailable/no_equity_observations`; available with zero rows means observations existed and no episode occurred.

The report describes sampled closes, not intrabar peaks/troughs. It does not resample calendars, infer annualization, or synthesize timestamps. Nautilus always records its available observed path, while Vector summary keeps bounded O(1) tracker state and aggregate rows but marks episode history `not_recorded/record_mode_summary` with the known episode count; Vector full records all episodes. Continue using `get_backtest_report` for paged drawdown rows (maximum 200 rows per page); the existing 32 MiB artifact cap remains.

## Monthly and yearly net returns

`metrics.performance.period_returns` summarizes observed `monthly` and `yearly` buckets; detailed rows are exposed by the existing `reports.monthly_returns` and `reports.yearly_returns` tables and retrieved with `get_backtest_report`. No tool ID or input schema is added. Each report has an engine-specific schema and the shared report envelope. Rows identify the Gregorian period in `execution.analysis_timezone` and its exact calendar bounds represented as UTC nanoseconds, reference/end equity and timestamps, endpoint net PnL/return, observation indexes/count, sample-boundary flags, cross-period attribution, skipped periods, non-positive-equity observation count, and per-field unavailable reasons.

Buckets use local Gregorian month/year boundaries from raw nanosecond timestamps in `execution.analysis_timezone` (default `UTC`); boundaries are represented as UTC nanoseconds. A bucket return is the net-equity change assigned to the period of its ending observation; the initial bucket uses starting capital as reference and has no economic reference timestamp. Later buckets use the preceding real observation as reference. Fees and slippage are already reflected in net equity. Non-positive reference equity makes return unavailable; valid negative/zero end equity is preserved. Missing calendar periods are omitted, never filled with zero or carried equity. Skipped-period and cross-period interval diagnostics disclose when a bucket endpoint return spans a gap. `diagnostics.period_returns` records the analysis timezone, pinned timezone database version and TZIF hash, and strict local-midnight boundary policy; ambiguous or nonexistent month boundaries fail explicitly.

Summary counts, positive fraction, best/worst/current include valid observed buckets, including partial first and last sample periods; denominators are valid observed buckets, not all elapsed or only complete calendar periods. `yearly_returns` are observed yearly endpoint changes, not `annual_return` or CAGR and are not compounded from monthly rows. A `summary` run retains these bounded aggregates but marks report rows `not_recorded`; `full` stores rows. Vector uses O(1) aggregation without per-bar date conversion within a bucket. Nautilus independently derives its period rows from its own raw-nanosecond net-equity path, excluding its artificial baseline from buckets while preserving native execution and reporting. Engine schemas and sources remain distinct.

Each frequency summary reports `observed_period_count`, `valid_period_count`, `unavailable_period_count`, positive/negative/flat counts and fraction, skipped-period and cross-period interval counts, skipped-gap bucket count, and best/worst/current rows. Row fields include `period`, local calendar start/end represented as UTC nanoseconds, reference and ending equity/timestamp/index, `net_pnl`, `net_return`, `observation_count`, first/last flags, `closed_by_next_period`, `cross_period_interval_count`, `skipped_periods_before`, `non_positive_equity_observation_count`, and `unavailable` reasons. `yearly` and `monthly` use the same conceptual fields under their own table schema.

## Historical Nautilus 0.7.0 verification

Nautilus 0.7.0 ran an independent five-observation period-return path matching hand calculations, with native reports and analysis preserved. A separate two-bar fee case confirmed that an initial reference extending into the prior year does not create a fabricated December bucket. This was focused verification, not a full suite or benchmark rerun.

`execution.analysis_timezone` controls only monthly/yearly analytics and defaults to `UTC`; it does not alter native order matching or the native analysis. The converter groups its own native equity observations by local Gregorian periods using Core’s pinned timezone bytes. Timestamps and report timestamp columns remain UTC nanoseconds, and timezone database identity is disclosed in diagnostics.

## Historical Nautilus 0.8.0 time-contract verification

Nautilus 0.8.0 focused private runs with one and two symbols verified source identity preservation and configured local-calendar period grouping. No full suite or benchmark rerun is claimed.

Engine report metadata declares timestamp-bearing columns; native-analysis diagnostics likewise declare the bounded timestamp fields that can be formatted. The raw nanosecond values remain canonical UTC even when a display timezone is requested.

## 0.9.0 success criteria

A Native result is successful only after clean completion. Mock validation requires the run to start, process all bars and timestamp groups, deliver every native fill to the bridge, and complete `on_stop` without trading. Preserve the original error; partial reports are failure evidence and cannot be presented as a normal backtest. Mock success does not guarantee real-data, account, or market success. Validate a submitted run with the same strategy and configuration.

## Canonical configuration guide

The full Nautilus-specific strategy and configuration guide is maintained in [`knowledge/backtest-config.md`](src/nlalpha_nautilus/knowledge/backtest-config.md). It belongs to this engine package. The backtest host's generic execution and evidence guidance is maintained separately by `nlalpha-backtest`. A future `backtest.confess(engine_id="nautilus")` consumer reads this guide from the provider package; runtime integration remains pending.


## License

Community distribution under AGPL-3.0-or-later. Nautilus Trader and other third-party dependencies retain their own licenses.
