TradeExecution#

tradeexecutor.state.trade.TradeExecution class.

class TradeExecution[source]#

Bases: object

Trade execution tracker.

Each trade has a reserve currency that we use to trade the token (usually USDC).

Each trade can be - Buy: swap quote token -> base token - Sell: swap base token -> quote token

When doing a buy planned_reserve (fiat) is the input. This yields to executed_quantity of tokens that may be different from planned_quantity.

When doing a sell planned_quantity (token) is the input. This yields to executed_reserve of fiat that might be different from `planned_reserve.

Trade execution has four states - Planning: The execution object is prepared - Capital allocation and transaction creation: We move reserve from out portfolio to the trade in internal accounting - Transaction broadcast: trade cannot be cancelled in this point - Resolving the trade: We check the Ethereum transaction receipt to see how well we succeeded in the trade

There trade state is resolved based on the market variables (usually timestamps).

__init__(trade_id, position_id, trade_type, pair, opened_at, planned_quantity, planned_reserve, planned_price, reserve_currency, planned_max_slippage=None, started_at=None, reserve_currency_allocated=None, broadcasted_at=None, executed_at=None, failed_at=None, executed_price=None, executed_quantity=None, executed_reserve=None, lp_fees_paid=None, native_token_price=None, retry_of=None, blockchain_transactions=<factory>, notes=None, repaired_at=None)#
Parameters
Return type

None

Methods

__init__(trade_id, position_id, trade_type, ...)

from_dict(kvs, *[, infer_missing])

from_json(s, *[, parse_float, parse_int, ...])

get_allocated_value()

get_credit_debit()

Returns the token quantity and reserve currency quantity for this trade.

get_equity_for_position()

Get the planned or executed quantity of the base token.

get_equity_for_reserve()

Get the planned or executed quantity of the quote token.

get_executed_value()

get_execution_sort_position()

When this trade should be executed.

get_fees_paid()

TODO: Make this functio to behave :return:

get_human_description()

User friendly description for this trade

get_planned_max_gas_price()

Get the maximum gas fee set to all transactions in this trade.

get_planned_reserve()

get_planned_value()

get_position_quantity()

Get the planned or executed quantity of the base token.

get_raw_planned_quantity()

Return the amount of USD token for the buy as raw token units.

get_raw_planned_reserve()

Return the amount of USD token for the buy as raw token units.

get_reserve_quantity()

Get the planned or executed quantity of the quote token.

get_status()

get_value()

Get estimated or realised value of this trade.

is_accounted_for_equity()

Does this trade contribute towards the trading position equity.

is_buy()

is_failed()

This trade was succcessfully completed.

is_pending()

This trade was succcessfully completed.

is_planned()

This trade is still in planning, unallocated.

is_rebalance()

This trade is part of the normal strategy rebalance.

is_repaired()

The automatic execution failed and this was later repaired.

is_sell()

is_started()

This trade has a txid allocated.

is_stop_loss()

This trade is made to close stop loss on a position.

is_success()

This trade was succcessfully completed.

is_take_profit()

This trade is made to close take profit on a position.

is_unfinished()

We could not confirm this trade back from the blockchain after broadcasting.

mark_broadcasted(broadcasted_at)

mark_failed(failed_at)

mark_success(executed_at, executed_price, ...)

schema(*[, infer_missing, only, exclude, ...])

set_blockchain_transactions(txs)

Set the physical transactions needed to perform this trade.

to_dict([encode_json])

to_json(*[, skipkeys, ensure_ascii, ...])

Attributes

broadcasted_at

When this trade entered mempool

executed_at

Timestamp of the block where the txid was first mined

executed_price

What was the actual price we received

executed_quantity

How much underlying token we traded, the actual realised amount.

executed_reserve

How much reserves we spend for this traded, the actual realised amount.

failed_at

The trade did not go through.

lp_fees_paid

LP fees estimated in the USD

native_token_price

USD price per blockchain native currency unit, at the time of execution

notes

Human readable notes about this trade

planned_max_slippage

How much slippage we could initially tolerate, 0.01 is 1% slippage.

repaired_at

Trade was manually repaird

reserve_currency_allocated

How much reserves was moved on this trade before execution

retry_of

started_at

When capital is allocated for this trade

trade_id

Trade id is unique among all trades in the same portfolio

position_id

Position id is unique among all trades in the same portfolio

trade_type

Spot, margin, lending, etc.

pair

Which trading pair this trade was for

opened_at

When the trade was opened

planned_quantity

Positive for buy, negative for sell.

planned_reserve

How many reserve tokens (USD) we use in this trade Always known accurately for buys.

planned_price

What we thought the execution price for this trade would have been at the moment of strategy decision.

reserve_currency

Which reserve currency we are going to take.

blockchain_transactions

Associated blockchain transaction details.

trade_id: int#

Trade id is unique among all trades in the same portfolio

position_id: int#

Position id is unique among all trades in the same portfolio

trade_type: TradeType#

Spot, margin, lending, etc.

pair: TradingPairIdentifier#

Which trading pair this trade was for

opened_at: datetime#

When the trade was opened

planned_quantity: Decimal#

Positive for buy, negative for sell. Always accurately known for sells.

planned_reserve: Decimal#

How many reserve tokens (USD) we use in this trade Always known accurately for buys. Expressed in reserve_currency.

planned_price: USDollarAmount#

What we thought the execution price for this trade would have been at the moment of strategy decision.

reserve_currency: AssetIdentifier#

Which reserve currency we are going to take. Note that pair.quote might be different from reserve currency. This is because we can do three-way trades like BUSD -> BNB -> Cake when our routing model supports this.

planned_max_slippage: Optional[float] = None#

How much slippage we could initially tolerate, 0.01 is 1% slippage.

started_at: Optional[datetime] = None#

When capital is allocated for this trade

reserve_currency_allocated: Optional[Decimal] = None#

How much reserves was moved on this trade before execution

broadcasted_at: Optional[datetime] = None#

When this trade entered mempool

executed_at: Optional[datetime] = None#

Timestamp of the block where the txid was first mined

failed_at: Optional[datetime] = None#

The trade did not go through. The timestamp when we figured this out.

executed_price: Optional[USDollarAmount] = None#

What was the actual price we received

executed_quantity: Optional[Decimal] = None#

How much underlying token we traded, the actual realised amount. Positive for buy, negative for sell

executed_reserve: Optional[Decimal] = None#

How much reserves we spend for this traded, the actual realised amount.

lp_fees_paid: Optional[USDollarAmount] = None#

LP fees estimated in the USD

native_token_price: Optional[USDollarAmount] = None#

USD price per blockchain native currency unit, at the time of execution

blockchain_transactions: List[BlockchainTransaction]#

Associated blockchain transaction details. Each trade contains 1 … n blockchain transactions. Typically this is approve() + swap() for Uniswap v2 or just swap() if we have the prior approval and approve does not need to be done for the hot wallet anymore.

notes: Optional[str] = None#

Human readable notes about this trade

Used to mark test trades from command line. Special case; not worth to display unless the field is filled in.

repaired_at: Optional[datetime] = None#

Trade was manually repaird

E.g. failed broadcast issue was fixed. Marked when the repair command is called.

get_human_description()[source]#

User friendly description for this trade

Return type

str

is_success()[source]#

This trade was succcessfully completed.

is_failed()[source]#

This trade was succcessfully completed.

is_pending()[source]#

This trade was succcessfully completed.

is_planned()[source]#

This trade is still in planning, unallocated.

is_started()[source]#

This trade has a txid allocated.

is_rebalance()[source]#

This trade is part of the normal strategy rebalance.

is_stop_loss()[source]#

This trade is made to close stop loss on a position.

is_take_profit()[source]#

This trade is made to close take profit on a position.

is_accounted_for_equity()[source]#

Does this trade contribute towards the trading position equity.

Failed trades are reverted. Only their fees account.

Return type

bool

is_unfinished()[source]#

We could not confirm this trade back from the blockchain after broadcasting.

Return type

bool

is_repaired()[source]#

The automatic execution failed and this was later repaired.

A manual repair command was issued and it manaeged to correctly repair this trade and underlying transactions.

Return type

bool

get_raw_planned_reserve()[source]#

Return the amount of USD token for the buy as raw token units.

Return type

int

get_raw_planned_quantity()[source]#

Return the amount of USD token for the buy as raw token units.

Return type

int

get_position_quantity()[source]#

Get the planned or executed quantity of the base token.

Positive for buy, negative for sell.

Return type

Decimal

get_reserve_quantity()[source]#

Get the planned or executed quantity of the quote token.

Negative for buy, positive for sell.

Return type

Decimal

get_equity_for_position()[source]#

Get the planned or executed quantity of the base token.

Positive for buy, negative for sell.

Return type

Decimal

get_equity_for_reserve()[source]#

Get the planned or executed quantity of the quote token.

Negative for buy, positive for sell.

Return type

Decimal

get_value()[source]#

Get estimated or realised value of this trade.

Value is always a positive number.

Return type

USDollarAmount

get_credit_debit()[source]#

Returns the token quantity and reserve currency quantity for this trade.

If buy this is (+trading position quantity/-reserve currency quantity).

If sell this is (-trading position quantity/-reserve currency quantity).

Return type

Tuple[Decimal, Decimal]

get_fees_paid()[source]#

TODO: Make this functio to behave :return:

Return type

USDollarAmount

get_execution_sort_position()[source]#

When this trade should be executed.

Lower, negative, trades should be executed first.

We need to execute sells first because we need to have cash in hand to execute buys.

Return type

int

set_blockchain_transactions(txs)[source]#

Set the physical transactions needed to perform this trade.

Parameters

txs (List[BlockchainTransaction]) –

get_planned_max_gas_price()[source]#

Get the maximum gas fee set to all transactions in this trade.

Return type

int

__init__(trade_id, position_id, trade_type, pair, opened_at, planned_quantity, planned_reserve, planned_price, reserve_currency, planned_max_slippage=None, started_at=None, reserve_currency_allocated=None, broadcasted_at=None, executed_at=None, failed_at=None, executed_price=None, executed_quantity=None, executed_reserve=None, lp_fees_paid=None, native_token_price=None, retry_of=None, blockchain_transactions=<factory>, notes=None, repaired_at=None)#
Parameters
Return type

None