ExecutionLoop#
API documentation for tradeexecutor.cli.loop.ExecutionLoop Python class in Trading Strategy framework.
- class ExecutionLoop[source]#
Bases:
object
Live or backtesting trade execution loop.
This is the main loop of any strategy execution.
Run scheduled tasks for different areas (trade cycle, position revaluation, stop loss triggers)
Call
ExecutionModel
to perform ticking through the strategyManage the persistent state of the strategy
- __init__(*ignore, name, command_queue, execution_model, execution_context, sync_model, approval_model, pricing_model_factory, valuation_model_factory, store, client, strategy_factory, cycle_duration, stats_refresh_frequency, position_trigger_check_frequency, max_data_delay=None, reset=False, max_cycles=None, debug_dump_file=None, backtest_start=None, backtest_end=None, backtest_setup=None, backtest_candle_time_frame_override=None, backtest_stop_loss_time_frame_override=None, backtest_strategy_indicators=None, stop_loss_check_frequency=None, tick_offset=datetime.timedelta(0), trade_immediately=False, run_state=None, strategy_cycle_trigger=StrategyCycleTrigger.cycle_offset, routing_model=None, execution_test_hook=None, metadata=None, check_accounts=None, minimum_data_lookback_range=None, universe_options=None, sync_treasury_on_startup=False, create_indicators=None, parameters=None, visualisation=True, max_price_impact=None)[source]#
See main.py for details.
- Parameters:
name (str) –
command_queue (Queue) –
execution_model (ExecutionModel) –
execution_context (ExecutionContext) –
sync_model (SyncModel) –
approval_model (ApprovalModel) –
pricing_model_factory (Callable[[ExecutionModel, StrategyExecutionUniverse, RoutingModel], PricingModel]) –
valuation_model_factory (ValuationModelFactory) –
store (StateStore) –
client (Optional[BaseClient]) –
strategy_factory (Optional[StrategyFactory]) –
cycle_duration (CycleDuration) –
backtest_candle_time_frame_override (Optional[TimeBucket]) –
backtest_stop_loss_time_frame_override (Optional[TimeBucket]) –
backtest_strategy_indicators (Optional[StrategyInputIndicators]) –
stop_loss_check_frequency (Optional[TimeBucket]) –
tick_offset (timedelta) –
strategy_cycle_trigger (StrategyCycleTrigger) –
routing_model (Optional[RoutingModel]) –
execution_test_hook (Optional[ExecutionTestHook]) –
universe_options (Optional[UniverseOptions]) –
sync_treasury_on_startup (bool) –
create_indicators (tradeexecutor.strategy.pandas_trader.indicator.CreateIndicatorsProtocolV1 | tradeexecutor.strategy.pandas_trader.indicator.CreateIndicatorsProtocolV2) –
parameters (StrategyParameters) –
visualisation (bool) –
max_price_impact (float | None) –
Methods
__init__
(*ignore, name, command_queue, ...)See main.py for details.
check_position_triggers
(ts, state, universe)Run stop loss/take profit/market limit price checks.
Extracts the latest long short metrics from the state and execution loop
Initialise the execution.
init_live_run_state
(run_description)Initialise run-state object.
init_simulation
(universe_model, runner)Set up running on a simulated blockchain.
Initialize the state for this run.
Are we doing a backtest execution.
Are we attempting to test live trading functionality in unit tests.
refresh_live_run_state
(state[, ...])Update the in-process strategy context which we serve over the webhook.
run
()Start the execution.
run_and_setup_backtest
()run_backtest
(state)Backtest loop.
run_backtest_trigger_checks
(start_ts, ...)Generate stop loss price checks.
run_live
(state)Run live trading cycle.
run_with_state
(state)Start the execution.
Set up backtesting start and end times.
setup
()Set up the main loop of trade executor.
tick
(unrounded_timestamp, cycle_duration, ...)Run one trade execution tick.
update_position_valuations
(clock, state, ...)Revalue positions and update statistics.
Load backtesting trading universe.
Load live trading universe.
- __init__(*ignore, name, command_queue, execution_model, execution_context, sync_model, approval_model, pricing_model_factory, valuation_model_factory, store, client, strategy_factory, cycle_duration, stats_refresh_frequency, position_trigger_check_frequency, max_data_delay=None, reset=False, max_cycles=None, debug_dump_file=None, backtest_start=None, backtest_end=None, backtest_setup=None, backtest_candle_time_frame_override=None, backtest_stop_loss_time_frame_override=None, backtest_strategy_indicators=None, stop_loss_check_frequency=None, tick_offset=datetime.timedelta(0), trade_immediately=False, run_state=None, strategy_cycle_trigger=StrategyCycleTrigger.cycle_offset, routing_model=None, execution_test_hook=None, metadata=None, check_accounts=None, minimum_data_lookback_range=None, universe_options=None, sync_treasury_on_startup=False, create_indicators=None, parameters=None, visualisation=True, max_price_impact=None)[source]#
See main.py for details.
- Parameters:
name (str) –
command_queue (Queue) –
execution_model (ExecutionModel) –
execution_context (ExecutionContext) –
sync_model (SyncModel) –
approval_model (ApprovalModel) –
pricing_model_factory (Callable[[ExecutionModel, StrategyExecutionUniverse, RoutingModel], PricingModel]) –
valuation_model_factory (ValuationModelFactory) –
store (StateStore) –
client (Optional[BaseClient]) –
strategy_factory (Optional[StrategyFactory]) –
cycle_duration (CycleDuration) –
backtest_candle_time_frame_override (Optional[TimeBucket]) –
backtest_stop_loss_time_frame_override (Optional[TimeBucket]) –
backtest_strategy_indicators (Optional[StrategyInputIndicators]) –
stop_loss_check_frequency (Optional[TimeBucket]) –
tick_offset (timedelta) –
strategy_cycle_trigger (StrategyCycleTrigger) –
routing_model (Optional[RoutingModel]) –
execution_test_hook (Optional[ExecutionTestHook]) –
universe_options (Optional[UniverseOptions]) –
sync_treasury_on_startup (bool) –
create_indicators (tradeexecutor.strategy.pandas_trader.indicator.CreateIndicatorsProtocolV1 | tradeexecutor.strategy.pandas_trader.indicator.CreateIndicatorsProtocolV2) –
parameters (StrategyParameters) –
visualisation (bool) –
max_price_impact (float | None) –
- is_live_trading_unit_test()[source]#
Are we attempting to test live trading functionality in unit tests.
See test_cli_commands.py
- Return type:
- init_state()[source]#
Initialize the state for this run.
If we are doing live trading, load the last saved state
In backtesting the state is always reset. We do not support resumes for crashed backetsting.
- Return type:
- init_execution_model()[source]#
Initialise the execution.
Perform preflight checks e.g. to see if our trading accounts look sane.
- init_simulation(universe_model, runner)[source]#
Set up running on a simulated blockchain.
Used with
tradeexecutor.testing.simulated_execution_loop
to allow fine granularity manipulation of in-memory blockchain to simulate trigger conditions in testing.- Parameters:
universe_model (UniverseModel) –
runner (StrategyRunner) –
- init_live_run_state(run_description)[source]#
Initialise run-state object.
We do need to do these updates only once on the startup, as there run-state variables do not change over the process lifetime.
- Parameters:
run_description (StrategyExecutionDescription) –
- refresh_live_run_state(state, visualisation=False, universe=None, cycle_duration=None)[source]#
Update the in-process strategy context which we serve over the webhook.
Note
There is still a gap between be able to serve the full run state and the webhook startup. This is because for the full run state, we need to have visualisations and we do not have those availble until we have loaded the trading universe data, which may take some time.
- Parameters:
visualisation – Also update technical charts
state (State) –
universe (TradingStrategyUniverse) –
cycle_duration (CycleDuration) –
- tick(unrounded_timestamp, cycle_duration, state, cycle, live, existing_universe=None, strategy_cycle_timestamp=None, extra_debug_data=None, indicators=None)[source]#
Run one trade execution tick.
- Parameters:
unrounded_timestamp (datetime) – The approximately time when this ticket was triggered. Alawys after the tick timestamp. Will be rounded to the nearest cycle duration timestamps.
strategy_cycle_timestamp (Optional[datetime]) – Precalculated strategy cycle timestamp based on unrounded timestamp
state (State) – The current state of the strategy
cycle (int) – The number of this cycle
cycle_duration (CycleDuration) – Cycle duration for this cycle. Either from the strategy module, or a backtest override.
live (bool) – We are doing live trading.
existing_universe (Optional[StrategyExecutionUniverse]) – If passed, use this universe instead of trying to download and filter new one. This is shortcut for backtesting where the universe does not change between cycles (as opposite to live trading new pairs pop in to the existence).
extra_debug_data (Optional[dict]) – Extra data to be passed to the debug dump used in unit testing.
indicators (tradeexecutor.strategy.pandas_trader.strategy_input.StrategyInputIndicators | None) –
- Returns:
The universe where we are trading.
- Return type:
- update_position_valuations(clock, state, universe, execution_mode)[source]#
Revalue positions and update statistics.
A new statistics entry is calculated for portfolio and all of its positions and added to the state.
- Parameters:
clock (datetime) – Real-time or historical clock
state (State) –
universe (StrategyExecutionUniverse) –
execution_mode (ExecutionMode) –
- extract_long_short_stats_from_state(state)[source]#
Extracts the latest long short metrics from the state and execution loop
- Parameters:
state – Current state for the strategy
- Returns:
StatisticsTable of the latest long short metrics
- Return type:
StatisticsTable
- check_position_triggers(ts, state, universe)[source]#
Run stop loss/take profit/market limit price checks.
Used for live stop loss check; backtesting uses optimised
run_backtest_stop_loss_checks()
.- Parameters:
ts (datetime) – Timestamp of this check cycle
state (State) –
universe (TradingStrategyUniverse) –
- Return type:
- param universe:
Trading universe containing price data for stoploss checks.
- Returns:
List of generated trigger trades
- Parameters:
ts (datetime) –
state (State) –
universe (TradingStrategyUniverse) –
- Return type:
- warm_up_backtest()[source]#
Load backtesting trading universe.
Display progress bars for data downloads.
- Return type:
- warm_up_live_trading()[source]#
Load live trading universe.
Display progress bars for data downloads.
- Return type:
- run_backtest_trigger_checks(start_ts, end_ts, state, universe)[source]#
Generate stop loss price checks.
Backtests may use finer grade data for stop loss signals, to be more realistic with actual trading.
Here we use the finer grade data to check the stop losses on a given time period.
For live trading see
check-position_triggers()
- Parameters:
start_ts (datetime) – When to start testing (exclusive). We test for the next available timestamp.
end_ts (datetime) – When to stop testing (exclusive).
universe (TradingStrategyUniverse) – Trading universe containing price data for stoploss checks.
state (State) –
- Returns:
Tuple (take profit, stop loss) count triggered
- Return type:
- run_live(state)[source]#
Run live trading cycle.
- Raises:
LiveSchedulingTaskFailed – If any of live trading concurrent tasks crashes with an exception
- Parameters:
state (State) –
- setup()[source]#
Set up the main loop of trade executor.
Main entry point to the loop.
Chooses between live and backtesting execution mode
Loads or creates the initial state
Sets up strategy runner
- Returns:
Loaded execution state
- Return type:
- set_backtest_start_and_end()[source]#
Set up backtesting start and end times. If no start, end, or lookback info provided, will set automatically to the entire available data range.