Refine handling of timers in backtest engine #3456
Open
+1,805
−97
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Pull Request
NautilusTrader prioritizes correctness and reliability, please follow existing patterns for validation and testing.
CONTRIBUTING.mdand followed the established practicesSummary
Summary
BacktestEngineto ensure correct chronological processing when data is exhausted._process_next_timerapproach. This allows the engine to correctly handle on-the-fly data loading triggered by timer callbacks (e.g., subscriptions during a backtest)._last_nswas set to 0 instead of the backtest start time.Key changes
Backtest engine refinements
nautilus_trader/backtest/engine.pyxto implement_process_next_timer, which finds the absolute next timer time across all component clocks and advances to it._process_next_timerwhen the data stream is empty, ensuring that timers within the backtest range are processed sequentially._last_nsto prevent premature time jumps or incorrect event processing at the start of a backtest.Testing and examples
tests/unit_tests/backtest/test_engine_timers.pywith 7 new test cases to validate timer execution with and without data, chained alerts, and interleaved processing.examples/backtest/notebooks/databento_test_order_book_deltas.pyto useset_time_alertfor more robust testing of order book delta subscriptions.Test plan
uv run --no-sync pytest tests/unit_tests/backtest/test_engine_timers.py.Related Issues/PRs
Type of change
Breaking change details (if applicable)
Documentation
docs/developer_guide/docs.md)Release notes
RELEASES.mdthat follows the existing conventions (when applicable)Testing
Ensure new or changed logic is covered by tests.