Refine exit process for Strategy #3425
Open
+324
−1
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
This PR introduces a refined market exit process for strategies in
nautilus_trader. It provides a mechanism to gracefully stop a strategy by cancelling all open orders and closing all open positions, waiting for all in-flight actions to resolve before finalising the stop.Changes
StrategyConfig: Addedinflight_check_interval_ms(defaulting to 100ms) to control the frequency of checks during the market exit process.Strategy:market_exit()method which initiates the cancellation of all orders and closing of all positions.on_market_exit()andafter_market_exit()lifecycle hooks for custom logic._check_market_exit()which uses a timer to iteratively ensure all orders are resolved and positions are closed before stopping the strategy.Controller&Trader: Added support for theMarketExitStrategycommand and corresponding methods to trigger the exit process from the controller/trader levels.MarketExitStrategy: New command message to trigger the exit process.Tests: Added comprehensive unit tests in
test_strategy.pycovering standard market exit and market exit with open positions.Implementation Details
The market exit process is iterative. Upon initiation, it immediately attempts to cancel all open orders and close all open positions for all instruments the strategy is involved with. A periodic timer is then started to monitor the state. The strategy only transitions to the
STOPPEDstate once the cache reports no open or in-flight orders, and no open positions. If open positions remain without active orders, the process will re-attempt to close them.Related Issues/PRs
#2876
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.