TradingStrategyUniverse#

tradeexecutor.strategy.trading_strategy_universe.TradingStrategyUniverse Python class in Trading Strategy framework.

class TradingStrategyUniverse[source]#

Bases: StrategyExecutionUniverse

A trading executor trading universe that using data from TradingStrategy.ai data feeds.

  • Supports generic trading universe definitions

  • Adds special support for reserve currency handling and take profit/stop loss backtesting

__init__(reserve_assets, universe=None, backtest_stop_loss_time_bucket=None, backtest_stop_loss_candles=None, required_history_period=None)#
Parameters:
Return type:

None

Methods

__init__(reserve_assets[, universe, ...])

clone()

Create a copy of this universe.

create_limited_pair_universe(dataset, ...[, ...])

Filters down the dataset for couple trading pair.

create_multichain_universe_by_pair_descriptions(...)

Create a trading universe based on list of (exchange, pair tuples)

create_multipair_universe(dataset, ...[, ...])

Create a trading universe where pairs match a filter conditions.

create_single_pair_universe([chain_id, ...])

Filters down the dataset for a single trading pair.

get_pair_by_address(address)

Get a trading pair data by a smart contract address.

get_pair_by_human_description(desc)

Get pair by its human-readable description.

get_pair_count()

get_reserve_asset()

Get the default reserve asset.

get_single_pair()

Get the single trading pair in this universe.

has_stop_loss_data()

Do we have data available to determine trade stop losses.

is_empty()

This is an empty universe

is_open_ended_universe()

Can new trading pairs to be added to this universe over time.

is_single_pair_universe()

Is this trading universe made for a single pair trading.

read_pickle_dangerous(path)

Write a pickled ouput of this universe.

validate()

Check that the created universe looks good.

write_pickle(path)

Write a pickled ouput of this universe

Attributes

backtest_stop_loss_candles

Special Pandas data feed for candles used only during the backtesting.

backtest_stop_loss_time_bucket

Are we using special take profit/stop loss trigger data.

required_history_period

How much historic data is needed by the strategy to make its decision.

universe

Trading universe datasets.

universe: Optional[Universe] = None#

Trading universe datasets.

This encapsulates more generic Universe class from tradingstrategy package.

backtest_stop_loss_time_bucket: Optional[TimeBucket] = None#

Are we using special take profit/stop loss trigger data.

If we are, what is the time granularity of this data.

backtest_stop_loss_candles: Optional[GroupedCandleUniverse] = None#

Special Pandas data feed for candles used only during the backtesting.

This allows us to simulate take profit and stop loss trigger orders that would be based on real-time market data in a live execution environment.

required_history_period: Optional[timedelta] = None#

How much historic data is needed by the strategy to make its decision.

This is the explicit time frame in days or hours for the historical data before today for the strategy to make a decision.

This will limit the amount of data downloaded from the oracle and greatly optimise the strategy decision execution.

E.g. for 90 days you can use datetime.timedelta(days=90)

is_open_ended_universe()[source]#

Can new trading pairs to be added to this universe over time.

Returns:

True if the trading universe may contain hundreds or thousands of trading pairs.

Return type:

bool

clone()[source]#

Create a copy of this universe.

Any dataframes are now copied, but set by reference.

Return type:

TradingStrategyUniverse

write_pickle(path)[source]#

Write a pickled ouput of this universe

Parameters:

path (Path) –

static read_pickle_dangerous(path)[source]#

Write a pickled ouput of this universe.

Warning

Only use for trusted input. Python pickle issue.

Parameters:

path (Path) –

Return type:

TradingStrategyUniverse

is_empty()[source]#

This is an empty universe

  • without trading pairs

  • …or without candles

Return type:

bool

is_single_pair_universe()[source]#

Is this trading universe made for a single pair trading.

Note that even a single pair universe may contain two trading pairs, if we need intermediate routing pairs. E.g. AAVE -> BNB -> BUSD/

Return type:

bool

has_stop_loss_data()[source]#

Do we have data available to determine trade stop losses.

Note that this applies for backtesting only - when doing production trade execution, stop loss data is not part of the universe but real time pricing comes directly from the exchange using real-time side channels.

Return type:

bool

validate()[source]#

Check that the created universe looks good.

Raises:

TradingUniverseIssue – In the case of detected issues

get_pair_by_human_description(desc)[source]#

Get pair by its human-readable description.

See tradingstrategy.pair.PandasPairUniverse.get_pair_by_human_description()

The trading pair must be loaded in the exchange universe.

Returns:

The trading pair on the exchange.

Highest volume trading pair if multiple matches.

Raises:

NoPairFound – In the case input data cannot be resolved.

Parameters:

desc (Union[Tuple[ChainId, str, str, str, float], Tuple[ChainId, str, str, str]]) –

Return type:

TradingPairIdentifier

create_single_pair_universe(chain_id=None, exchange_slug=None, base_token=None, quote_token=None, pair=None)[source]#

Filters down the dataset for a single trading pair.

This is ideal for strategies that only want to trade a single pair.

Parameters:
Return type:

TradingStrategyUniverse

static create_limited_pair_universe(dataset, chain_id, exchange_slug, pairs, reserve_asset_pair_ticker=None)[source]#

Filters down the dataset for couple trading pair.

This is ideal for strategies that only want to trade few pairs, or a single pair using three-way trading on a single exchange.

The university reserve currency is set to the quote token of the first pair.

Parameters:
  • dataset (Dataset) – Datasets downloaded from the server

  • pairs (Set[Tuple[str, str]]) – List of trading pairs as ticket tuples. E.g. [ (“WBNB, “BUSD”), (“Cake”, “WBNB”) ]

  • reserve_asset_pair_ticker (Optional[Tuple[str, str]]) – Choose the quote token of this trading pair as a reserve asset. This must be given if there are several pairs (Python set order is unstable).

  • chain_id (ChainId) –

  • exchange_slug (str) –

Return type:

TradingStrategyUniverse

get_pair_by_address(address)[source]#

Get a trading pair data by a smart contract address.

Parameters:

address (str) –

Return type:

Optional[TradingPairIdentifier]

get_single_pair()[source]#

Get the single trading pair in this universe.

Return type:

TradingPairIdentifier

static create_multipair_universe(dataset, chain_ids, exchange_slugs, quote_tokens, reserve_token, factory_router_map, liquidity_resample_frequency=None)[source]#

Create a trading universe where pairs match a filter conditions.

These universe may contain thousands of trading pairs. This is for strategies that trade across multiple pairs, like momentum strategies.

Parameters:
  • dataset (Dataset) – Datasets downloaded from the oracle

  • chain_ids (Iterable[ChainId]) – Allowed blockchains

  • exchange_slugs (Iterable[str]) – Allowed exchanges

  • quote_tokens (Iterable[str]) – Allowed quote tokens as smart contract addresses

  • reserve_token (str) – The token addresses that are used as reserve assets.

  • factory_router_map (Dict[str, tuple]) – Ensure we have a router address for every exchange we are going to use. TODO: In the future this information is not needed.

  • liquidity_resample_frequency (Optional[str]) –

    Create a resampled liquidity universe instead of accurate one.

    If given, this will set Universe.resampled_liquidity attribute.

    Using ResampledLiquidityUniverse will greatly speed up backtests that estimate trading pair liquidity, by trading off sample accuracy for code execution speed.

    Must be a Pandas frequency string value, like 1d.

    Note that resamping itself takes a lot of time upfront, so you want to use this only if the backtest takes lont time.

Return type:

TradingStrategyUniverse

static create_multichain_universe_by_pair_descriptions(dataset, pairs, reserve_token_symbol)[source]#

Create a trading universe based on list of (exchange, pair tuples)

This is designed for backtesting multipe pairs across different chains. The created universe do not have any routing options and thus cannot make any trades.

Parameters:
  • dataset (Dataset) – Datasets downloaded from the oracle

  • pairs (Collection[Union[Tuple[ChainId, str, str, str, float], Tuple[ChainId, str, str, str]]]) –

    List of trading pairs to filter down.

    The pair set is desigend to be small, couple of dozens of pairs max.

    See HumanReadableTradingPairDescription.

  • reserve_token_symbol (str) –

    The token symbol of the reverse asset.

    Because we do not support routing, we just pick the first matching token.

Return type:

TradingStrategyUniverse

__init__(reserve_assets, universe=None, backtest_stop_loss_time_bucket=None, backtest_stop_loss_candles=None, required_history_period=None)#
Parameters:
Return type:

None