EthereumExecution#

API documentation for tradeexecutor.ethereum.execution.EthereumExecution Python class in Trading Strategy framework.

class EthereumExecution[source]#

Bases: ExecutionModel

Run order execution on a single Uniswap v2 style exchanges.

__init__(tx_builder, min_balance_threshold=Decimal('0.5'), confirmation_block_count=6, confirmation_timeout=datetime.timedelta(seconds=300), max_slippage=0.01, stop_on_execution_failure=True, swap_gas_fee_limit=2000000, mainnet_fork=False)[source]#
Parameters:
  • tx_builder (TransactionBuilder) – Hot wallet instance used for this execution

  • min_balance_threshold – Abort execution if our hot wallet gas fee balance drops below this

  • confirmation_block_count – How many blocks to wait for the receipt confirmations to mitigate unstable chain tip issues

  • confirmation_timeout – How long we wait transactions to clear

  • stop_on_execution_failure – Raise an exception if any of the trades fail top execute

  • max_slippage (float) –

    TODO: No longer used. Set in TradeExecution object.

    Max slippage tolerance per trade. 0.01 is 1%.

  • mainnet_fork – Is this Anvil in automining mainnet fork mode

Methods

__init__(tx_builder[, ...])

param tx_builder:

broadcast_and_resolve_multiple_nodes(...[, ...])

Do the live trade execution using multiple nodes.

broadcast_and_resolve_old(state, trades, ...)

Do the live trade execution.

create_default_routing_model(strategy_universe)

Get the default routing model for this executor.

execute_trades(ts, state, trades, ...[, ...])

Execute the trades determined by the algo on a designed Uniswap v2 instance.

get_balance_address()

Get the address where the strat holds tokens.

get_routing_state_details()

Get needed details to establish a routing state.

get_safe_latest_block()

Fix the block number for all checks and actions.

initialize()

Set up the wallet

is_live_trading()

is_stop_loss_supported()

Do we support stop-loss/take profit functionality with this execution model?

pre_execute_assertions(ts, routing_model, ...)

preflight_check()

Check that we can connect to the web3 node

repair_unconfirmed_trades(state)

Repair unconfirmed trades.

resolve_trades(ts, routing_model, state, ...)

Resolve trade outcome.

update_confirmation_status(ts, tx_map, receipts)

First update the state of all transactions, as we now have receipt for them.

Attributes

chain_id

Which chain the live execution is connected to.

web3

__init__(tx_builder, min_balance_threshold=Decimal('0.5'), confirmation_block_count=6, confirmation_timeout=datetime.timedelta(seconds=300), max_slippage=0.01, stop_on_execution_failure=True, swap_gas_fee_limit=2000000, mainnet_fork=False)[source]#
Parameters:
  • tx_builder (TransactionBuilder) – Hot wallet instance used for this execution

  • min_balance_threshold – Abort execution if our hot wallet gas fee balance drops below this

  • confirmation_block_count – How many blocks to wait for the receipt confirmations to mitigate unstable chain tip issues

  • confirmation_timeout – How long we wait transactions to clear

  • stop_on_execution_failure – Raise an exception if any of the trades fail top execute

  • max_slippage (float) –

    TODO: No longer used. Set in TradeExecution object.

    Max slippage tolerance per trade. 0.01 is 1%.

  • mainnet_fork – Is this Anvil in automining mainnet fork mode

property chain_id: int#

Which chain the live execution is connected to.

get_balance_address()[source]#

Get the address where the strat holds tokens.

Returns:

None if this executor does not use on-chain addresses.

Return type:

str

get_safe_latest_block()[source]#

Fix the block number for all checks and actions.

  • At the start of each action cycle (strategy decision, position triggers) we fix ourselves to a certain block number we know is “safe” and the data in at this block number is unlike to change

  • We then perform all deposit and redemptions and accounting checks using this block number as end block, to get a

Returns:

A good safe latest block number.

Return None if the block number is irrelevant for the execution, like backtesting and such.

Return type:

int

repair_unconfirmed_trades(state)[source]#

Repair unconfirmed trades.

Repair trades that failed to properly broadcast or confirm due to blockchain node issues.

Parameters:

state (State) –

Return type:

List[TradeExecution]

is_stop_loss_supported()[source]#

Do we support stop-loss/take profit functionality with this execution model?

  • For backtesting we need to have data stream for candles used to calculate stop loss

  • For production execution, we need to have special oracle data streams for checking real-time stop loss

Return type:

bool

preflight_check()[source]#

Check that we can connect to the web3 node

initialize()[source]#

Set up the wallet

broadcast_and_resolve_old(state, trades, routing_model, confirmation_timeout=datetime.timedelta(seconds=60), confirmation_block_count=0, stop_on_execution_failure=False)[source]#

Do the live trade execution.

  • Push trades to a live blockchain

  • Wait transactions to be mined

  • Based on the transaction result, update the state of the trade if it was success or not

Parameters:
  • confirmation_block_count (int) – How many blocks to wait until marking transaction as confirmed

  • stop_on_execution_failure – If any of the transactions fail, then raise an exception. Set for unit test.

  • state (State) –

  • trades (List[TradeExecution]) –

  • routing_model (RoutingModel) –

  • confirmation_timeout (timedelta) –

Confirmation_timeout:

Max time to wait for a confirmation.

We can use zero or negative values to simulate unconfirmed trades. See test_broadcast_failed_and_repair_state.

broadcast_and_resolve_multiple_nodes(routing_model, state, trades, confirmation_timeout=datetime.timedelta(seconds=60), confirmation_block_count=0, stop_on_execution_failure=False, rebroadcast=False)[source]#

Do the live trade execution using multiple nodes.

See eth_defi.confirmation.wait_and_broadcast_multiple_nodes()

Parameters:
  • state (State) – The current state of the strategy

  • trades (List[TradeExecution]) – List of trades we need to execute on-chain

  • confirmation_block_count (int) – How many blocks to wait until marking transaction as confirmed

  • confirmation_timeout (timedelta) –

    Max time to wait for a confirmation.

    We can use zero or negative values to simulate unconfirmed trades. See test_broadcast_failed_and_repair_state.

  • stop_on_execution_failure – If any of the transactions fail, then raise an exception. Set for unit test.

  • routing_model (RoutingModel) –

execute_trades(ts, state, trades, routing_model, routing_state, check_balances=False, rebroadcast=False, triggered=False)[source]#

Execute the trades determined by the algo on a designed Uniswap v2 instance.

Parameters:
  • ts (datetime) – Timestamp of the trade cycle.

  • universe – Current trading universe for this cycle.

  • state (State) – State of the trade executor.

  • trades (List[TradeExecution]) – List of trades decided by the strategy. Will be executed and modified in place.

  • routing_model (RoutingModel) – Routing model how to execute the trades

  • routing_state (RoutingState) – State of already made on-chain transactions and such on this cycle

  • max_slippage – Max slippage % allowed on trades before trade execution fails.

  • check_balances – Check that on-chain accounts have enough balance before creating transaction objects. Useful during unit tests to spot issues in trade routing.

  • rebroadcast

    This is a rebroadcast and reconfirmation of existing transactions.

    Transactions had been marked for a broadcast before, but their status is unknown.

    See tradeexecutor.ethereum.rebroadcast.

  • triggered – Was this execution initiated from stop loss etc. triggers

get_routing_state_details()[source]#

Get needed details to establish a routing state.

Return type:

RoutingStateDetails

update_confirmation_status(ts, tx_map, receipts)[source]#

First update the state of all transactions, as we now have receipt for them. Update the transaction confirmation status

Parameters:
Return type:

set[tradeexecutor.state.trade.TradeExecution]

resolve_trades(ts, routing_model, state, tx_map, receipts, stop_on_execution_failure=True)[source]#

Resolve trade outcome.

Read on-chain Uniswap swap data from the transaction receipt and record how it went.

Mutates the trade objects in-place.

Parameters:
create_default_routing_model(strategy_universe)[source]#

Get the default routing model for this executor.

Returns:

Parameters:

strategy_universe (TradingStrategyUniverse) –

Return type:

RoutingModel