StrategyRunner#
API documentation for tradeexecutor.strategy.runner.StrategyRunner Python class in Trading Strategy framework.
- class StrategyRunner[source]#
Bases:
ABC
A base class for a strategy executor.
Each different strategy type needs its own runner. Currently we have
TODO: Make user_supplied_routing_model non-optional after eliminating legacy code.
- __init__(timed_task_context_manager, execution_model, approval_model, valuation_model_factory, sync_model, pricing_model_factory, execution_context, routing_model=None, routing_model_factory=None, run_state=None, accounting_checks=False, unit_testing=False, trade_settle_wait=None, parameters=None, create_indicators=None, visualisation=True)[source]#
- Parameters:
engine_version –
Strategy execution version.
Changes function arguments based on this. See StrategyModuleInformation.trading_strategy_engine_version.
timed_task_context_manager (AbstractContextManager) –
execution_model (ExecutionModel) –
approval_model (ApprovalModel) –
valuation_model_factory (ValuationModelFactory) –
pricing_model_factory (Callable[[ExecutionModel, StrategyExecutionUniverse, RoutingModel], PricingModel]) –
execution_context (ExecutionContext) –
routing_model (Optional[RoutingModel]) –
routing_model_factory (Optional[Callable[[], RoutingModel]]) –
parameters (Optional[StrategyParameters]) –
create_indicators (Optional[Union[CreateIndicatorsProtocolV1, CreateIndicatorsProtocolV2]]) –
Methods
__init__
(timed_task_context_manager, ...[, ...])- param engine_version:
check_accounts
(universe, state[, ...])Perform extra accounting checks on live trading startup.
check_balances_post_execution
(universe, ...)Check that on-chain balances matches our internal accounting after executing trades.
check_position_triggers
(clock, state, ...[, ...])Check stop loss/take profit for positions.
Collect post execution data for all trades.
Do we log the strategy steps to logger?
on_clock
(clock, universe, pricing_model, ...)Perform the core strategy decision cycle.
pretick_check
(ts, universe)Check the universe for good data before a strategy tick is executed.
refresh_visualisations
(state, universe)Update the visualisations in the run state.
repair_state
(state)Repair unclean state issues.
report_after_execution
(clock, universe, ...)report_after_sync_and_revaluation
(clock, ...)report_before_execution
(clock, universe, ...)Strategy admin helpers to understand a live running strategy.
revalue_state
(ts, state, valuation_model)Revalue portfolio based on the latest prices.
setup_routing
(universe)Setups routing state for this cycle.
sync_portfolio
(...[, end_block, ...])Adjust portfolio balances based on the external events.
tick
(strategy_cycle_timestamp, universe, ...)Execute the core functions of a strategy.
- __init__(timed_task_context_manager, execution_model, approval_model, valuation_model_factory, sync_model, pricing_model_factory, execution_context, routing_model=None, routing_model_factory=None, run_state=None, accounting_checks=False, unit_testing=False, trade_settle_wait=None, parameters=None, create_indicators=None, visualisation=True)[source]#
- Parameters:
engine_version –
Strategy execution version.
Changes function arguments based on this. See StrategyModuleInformation.trading_strategy_engine_version.
timed_task_context_manager (AbstractContextManager) –
execution_model (ExecutionModel) –
approval_model (ApprovalModel) –
valuation_model_factory (ValuationModelFactory) –
pricing_model_factory (Callable[[ExecutionModel, StrategyExecutionUniverse, RoutingModel], PricingModel]) –
execution_context (ExecutionContext) –
routing_model (Optional[RoutingModel]) –
routing_model_factory (Optional[Callable[[], RoutingModel]]) –
parameters (Optional[StrategyParameters]) –
create_indicators (Optional[Union[CreateIndicatorsProtocolV1, CreateIndicatorsProtocolV2]]) –
- abstract pretick_check(ts, universe)[source]#
Check the universe for good data before a strategy tick is executed.
If there are data errors, then log and abort with helpful error messages.
Only relevant for live trading; if backtesting data fails it can be diagnosed in the backtesting itself.
- Parameters:
client – Trading Strategy client to check server versions etc.
universe (StrategyExecutionUniverse) – THe currently constructed universe
ts (datetime) – Real-time clock signal or past clock timestamp in the case of unit testing
- Raises:
PreflightCheckFailed – In the case we cannot go live
- is_progress_report_needed()[source]#
Do we log the strategy steps to logger?
Disabled for backtesting to speed up
Can be enabled by hacking this function if backtesting needs debugging
- Return type:
- sync_portfolio(strategy_cycle_or_trigger_check_ts, universe, state, debug_details, end_block=None, long_short_metrics_latest=None)[source]#
Adjust portfolio balances based on the external events.
External events include
Deposits
Withdrawals
Interest accrued
Token rebases
- Parameters:
strategy_cycle_or_trigger_check_ts (datetime) – Timestamp for the event trigger
universe (StrategyExecutionUniverse) – Loaded universe
state (State) – Currnet strategy state
Sync until this block.
If not given sync to the lateshish.
debug_details (dict) – Dictionary of debug data that will be passed down to the callers
long_short_metrics_latest (Optional[StatisticsTable]) – Latest long/short statistics table, if available
- revalue_state(ts, state, valuation_model)[source]#
Revalue portfolio based on the latest prices.
- Parameters:
ts (datetime) –
state (State) –
valuation_model (ValuationModel) –
- collect_post_execution_data(execution_context, pricing_model, trades)[source]#
Collect post execution data for all trades.
Collect prices after the execution
Mostly matters for failed execution only, but we collect for everything
- Parameters:
execution_context (ExecutionContext) –
pricing_model (PricingModel) –
trades (List[TradeExecution]) –
- on_clock(clock, universe, pricing_model, state, debug_details, indicators=None)[source]#
Perform the core strategy decision cycle.
- Parameters:
clock (datetime) – The current cycle timestamp
universe (StrategyExecutionUniverse) – Our trading pairs and such. Refreshed before the cycle.
pricing_model (PricingModel) – When constructing trades, uses pricing model to estimate the cost of a trade.
state (State) – The current trade execution and portfolio status
debug_details (dict) –
indicators (Optional[StrategyInputIndicators]) –
- Returns:
List of new trades to execute
- Return type:
- report_strategy_thinking(strategy_cycle_timestamp, cycle, universe, state, trades, debug_details)[source]#
Strategy admin helpers to understand a live running strategy.
Post latest variables
Draw the single pair strategy visualisation.
- Parameters:
strategy_cycle_timestamp (datetime) – real time lock
cycle (int) – Cycle number
universe (TradingStrategyUniverse) – Currnet trading universe
trades (List[TradeExecution]) – Trades executed on this cycle
state (State) – Current execution state
debug_details (dict) – Dict of random debug stuff
- setup_routing(universe)[source]#
Setups routing state for this cycle.
- Parameters:
universe (StrategyExecutionUniverse) – The currently tradeable universe
- Returns:
Tuple(routing state, pricing model, valuation model)
- Return type:
- check_balances_post_execution(universe, state, cycle)[source]#
Check that on-chain balances matches our internal accounting after executing trades.
Crash the execution if the on-chain balance is not what we expect
Call after we have stored the execution state in the database
- Parameters:
universe (StrategyExecutionUniverse) –
state (State) –
cycle (int) –
- tick(strategy_cycle_timestamp, universe, state, debug_details, cycle_duration=None, cycle=None, store=None, long_short_metrics_latest=None, indicators=None)[source]#
Execute the core functions of a strategy.
TODO: This function is vulnerable to balance changes in the middle of execution. It’s not possible to fix this until we have atomic rebalances.
- Parameters:
strategy_cycle_timestamp (datetime) – Current timestamp of the execution cycle.
universe (StrategyExecutionUniverse) – Loaded trading data
state (State) – The current state of the strategy (open position, past trades, visualisation)
debug_details (dict) – Internal bunch of data used in unit testing
cycle_duration (Optional[CycleDuration]) – The currenct cycle duration (time between ticks). This may be specific in a strategy module, but also overridden for testing. This is used only for logging purposes.
execution_context – Live or backtesting
indicators (Optional[StrategyInputIndicators]) – Precalculated backtest or live calculated indicator values.
store (Optional[StateStore]) –
long_short_metrics_latest (Optional[StatisticsTable]) –
- Returns:
Debug details dictionary where different subsystems can write their diagnostics information what is happening during the dict. Mostly useful for integration testing.
- Return type:
- check_position_triggers(clock, state, universe, stop_loss_pricing_model, routing_state, long_short_metrics_latest=None)[source]#
Check stop loss/take profit for positions.
Unlike trade balancing in tick()
Stop loss/take profit can occur only to any existing positions. No new positions are opened.
Trading Universe cannot change for these triggers, but remains stable between main ticks.
check_position_triggers() is much more lightweight and can be called much more frequently, even once per minute
- Returns:
List of generated stop loss trades
- Parameters:
clock (datetime) –
state (State) –
universe (StrategyExecutionUniverse) –
stop_loss_pricing_model (PricingModel) –
routing_state (RoutingState) –
long_short_metrics_latest (Optional[StatisticsTable]) –
- Return type:
- repair_state(state)[source]#
Repair unclean state issues.
Currently supports
Fixing unfinished trades
- Returns:
List of fixed trades
- Parameters:
state (State) –
- Return type:
- refresh_visualisations(state, universe)[source]#
Update the visualisations in the run state.
This will update RunState.visualisations for the current strategy.
In-process memory charts are served by webhook
In-process memory charts are posted to Discord, etc.
This is called on the startup, so that we have immediately good visualisation to show over the webhook when the web server boots up
This is called after each strategy thinking cycle is complete.
The function is overridden by the child class for actual strategy runner specific implementation.
- Parameters:
state (State) –
universe (TradingStrategyUniverse) –