Implementation:Nautechsystems Nautilus trader Strategy Cancel Close
| Field | Value |
|---|---|
| sources | https://github.com/nautechsystems/nautilus_trader , https://nautilustrader.io/docs/ |
| domains | algorithmic trading, order cancellation, position closure, graceful shutdown, NautilusTrader |
| last_updated | 2026-02-10 12:00 GMT |
Overview
Concrete tool for canceling all open orders and closing all open positions during strategy shutdown provided by NautilusTrader.
Description
NautilusTrader provides two primary methods on the Strategy class for graceful shutdown:
cancel_all_orders: Cancels all open, emulated, and in-flight orders for a given instrument and strategy. It sendsCancelAllOrderscommands to both theExecutionEngine(for venue orders) and theOrderEmulator(for locally emulated orders). It also cancels any orders managed by execution algorithms.
close_all_positions: Closes all open positions for a given instrument and strategy by submitting closingMarketOrderobjects (viaclose_position) for each open position. The closing order side is automatically determined as the opposite of the position side, and the quantity matches the full position size.
Additionally, the close_position method closes a single specific position by creating and submitting a closing market order.
Both methods include safety checks: if no orders/positions exist to cancel/close, they log an informational message and return immediately.
Usage
Call these methods in your strategy's on_stop method to ensure graceful teardown, or call them at any time during strategy execution for risk management (e.g., emergency position exit).
Code Reference
Source Location
nautilus_trader/trading/strategy.pyx, lines 1215-1490.
Signatures
cancel_all_orders:
cpdef void cancel_all_orders(
self,
InstrumentId instrument_id,
OrderSide order_side = OrderSide.NO_ORDER_SIDE,
ClientId client_id = None,
dict[str, object] params = None,
)
close_all_positions:
cpdef void close_all_positions(
self,
InstrumentId instrument_id,
PositionSide position_side = PositionSide.NO_POSITION_SIDE,
ClientId client_id = None,
list[str] tags = None,
TimeInForce time_in_force = TimeInForce.GTC,
bint reduce_only = True,
bint quote_quantity = False,
dict[str, object] params = None,
)
close_position:
cpdef void close_position(
self,
Position position,
ClientId client_id = None,
list[str] tags = None,
TimeInForce time_in_force = TimeInForce.GTC,
bint reduce_only = True,
bint quote_quantity = False,
dict[str, object] params = None,
)
Import
These methods are available on any Strategy instance. No separate import is needed.
from nautilus_trader.trading.strategy import Strategy # Methods available via self
I/O Contract
Inputs (cancel_all_orders)
| Parameter | Type | Required | Description |
|---|---|---|---|
instrument_id |
InstrumentId |
Yes | The instrument for which to cancel all orders. |
order_side |
OrderSide |
No | Side filter. Default NO_ORDER_SIDE (both sides). |
client_id |
ClientId or None |
No | Specific client ID. If None, inferred from venue. |
params |
dict[str, object] or None |
No | Additional parameters for the data client. |
Inputs (close_all_positions)
| Parameter | Type | Required | Description |
|---|---|---|---|
instrument_id |
InstrumentId |
Yes | The instrument for which to close all positions. |
position_side |
PositionSide |
No | Side filter. Default NO_POSITION_SIDE (both sides). |
client_id |
ClientId or None |
No | Specific client ID. If None, inferred from venue. |
tags |
list[str] or None |
No | Custom tags for the closing market orders. |
time_in_force |
TimeInForce |
No | Time in force for closing orders. Default GTC. |
reduce_only |
bool |
No | Whether closing orders are reduce-only. Default True. |
quote_quantity |
bool |
No | Whether quantity is in quote currency. Default False. |
params |
dict[str, object] or None |
No | Additional parameters for the data client. |
Inputs (close_position)
| Parameter | Type | Required | Description |
|---|---|---|---|
position |
Position |
Yes | The specific position to close. |
client_id |
ClientId or None |
No | Specific client ID. |
tags |
list[str] or None |
No | Custom tags for the closing market order. |
time_in_force |
TimeInForce |
No | Time in force. Default GTC. |
reduce_only |
bool |
No | Reduce-only flag. Default True. |
quote_quantity |
bool |
No | Quote quantity flag. Default False. |
params |
dict[str, object] or None |
No | Additional parameters. |
Outputs
| Output | Type | Description |
|---|---|---|
| None | void |
All methods return nothing. Side effects are cancel commands and closing order submissions sent to the execution engine. |
Usage Examples
Basic graceful shutdown in on_stop:
from nautilus_trader.trading.strategy import Strategy
from nautilus_trader.model.identifiers import InstrumentId
class GracefulStrategy(Strategy):
def __init__(self, config):
super().__init__(config)
self.instrument_id = InstrumentId.from_str("AAPL.XNAS")
def on_stop(self):
# Phase 1: Cancel all open orders
self.cancel_all_orders(self.instrument_id)
# Phase 2: Close all open positions
self.close_all_positions(self.instrument_id)
Shutdown with side filtering:
from nautilus_trader.model.enums import OrderSide, PositionSide
class SideFilteredShutdown(Strategy):
def on_stop(self):
instrument_id = InstrumentId.from_str("BTCUSDT.BINANCE")
# Cancel only BUY orders
self.cancel_all_orders(
instrument_id,
order_side=OrderSide.BUY,
)
# Close only LONG positions
self.close_all_positions(
instrument_id,
position_side=PositionSide.LONG,
)
Closing a specific position:
class TargetedCloseStrategy(Strategy):
def on_bar(self, bar):
# Close a specific position if a condition is met
positions = self.cache.positions_open(
instrument_id=bar.bar_type.instrument_id,
strategy_id=self.id,
)
for position in positions:
if float(position.unrealized_pnl) < -1000.0:
self.close_position(position, tags=["STOP_LOSS"])
Automatic market exit using manage_stop config:
from nautilus_trader.trading.config import StrategyConfig
# When manage_stop=True, calling stop() on the strategy
# automatically cancels all orders and closes all positions
# before transitioning to STOPPED state.
config = StrategyConfig(
manage_stop=True,
market_exit_interval_ms=100,
market_exit_max_attempts=50,
)