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, max_price_impact=None)[source]#
Parameters:

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(...)

Collect post execution data for all trades.

is_progress_report_needed()

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, ...)

report_strategy_thinking(...)

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, max_price_impact=None)[source]#
Parameters:
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:

bool

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

  • end_block (int | None) –

    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 (tradeexecutor.statistics.statistics_table.StatisticsTable | None) – Latest long/short statistics table, if available

revalue_state(ts, state, valuation_model)[source]#

Revalue portfolio based on the latest prices.

Parameters:
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:
on_clock(clock, universe, pricing_model, state, debug_details, indicators=None)[source]#

Perform the core strategy decision cycle.

Parameters:
Returns:

List of new trades to execute

Return type:

List[TradeExecution]

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:

Tuple[RoutingState, PricingModel, ValuationModel]

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:
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.

  • cycle (Optional[int]) – Strategy cycle number

  • execution_context – Live or backtesting

  • indicators (tradeexecutor.strategy.pandas_trader.strategy_input.StrategyInputIndicators | None) – Precalculated backtest or live calculated indicator values.

  • store (Optional[StateStore]) –

  • long_short_metrics_latest (tradeexecutor.statistics.statistics_table.StatisticsTable | None) –

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:

dict

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:
Return type:

List[TradeExecution]

repair_state(state)[source]#

Repair unclean state issues.

Currently supports

  • Fixing unfinished trades

Returns:

List of fixed trades

Parameters:

state (State) –

Return type:

List[TradeExecution]

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:
check_accounts(universe, state, report_only=False, end_block=None, cycle=None)[source]#

Perform extra accounting checks on live trading startup.

Must be enabled in the settings. Enabled by default for live trading.

Parameters:
  • report_only – Don’t crash if we get problems in accounts

  • end_block (int | None) –

    Check specifically at this block.

    If not given use the lateshish block.

  • universe (TradingStrategyUniverse) –

  • state (State) –

  • cycle (int | None) –

Raises:

UnexpectedAccountingCorrectionIssue – Aborting execution.