basana.backtesting.exchange

class basana.backtesting.exchange.Exchange(dispatcher, initial_balances, liquidity_strategy_factory=<class 'basana.backtesting.liquidity.VolumeShareImpact'>, fee_strategy=<basana.backtesting.fees.NoFee object>, default_pair_info=PairInfo(base_precision=0, quote_precision=2), bid_ask_spread=Decimal('0.5'), lending_strategy=<basana.backtesting.lending.base.NoLoans object>, immediate_order_processing=False)

This class implements a backtesting exchange.

This backtesting exchange has support for Market, Limit, Stop and Stop Limit orders and it will simulate order execution based on summarized trading activity (basana.BarEvent).

Parameters:
  • dispatcher (BacktestingDispatcher) – The event dispatcher.

  • initial_balances (Dict[str, Decimal]) – The initial balance for each currency/symbol/etc.

  • liquidity_strategy_factory (Callable[[], LiquidityStrategy]) – A callable that returns a new liquidity strategy.

  • fee_strategy (FeeStrategy) – The stragegy to use to calculate fees.

  • default_pair_info (PairInfo | None) – The default pair information if a specific one was not set using Exchange.set_pair_info().

  • bid_ask_spread (Decimal) – The spread, as a percentage, to use for Exchange.get_bid_ask().

  • lending_strategy (LendingStrategy) – The strategy to use for managing loans.

  • immediate_order_processing (bool) – If True, orders will be processed immediately after being added, using the closing price of the last bar available. If False, orders will be processed in the next bar event.

add_bar_source(bar_source)

Adds an event source that produces basana.BarEvent instances.

These will be used to drive the backtest.

Parameters:

bar_source (EventSource) – An event source that produces basana.BarEvent instances.

async cancel_order(order_id)

Cancels an order.

If the order doesn’t exist, or its not open, an Error will be raised.

Parameters:

order_id (str) – The order id.

Return type:

CanceledOrder

async create_limit_order(operation, pair, amount, limit_price, auto_borrow=False, auto_repay=False)

Creates a limit order.

A limit order is an order to buy or sell at a specific price or better. A buy limit order can only be executed at the limit price or lower, and a sell limit order can only be executed at the limit price or higher.

If the order can’t be created an Error will be raised.

Parameters:
  • operation (OrderOperation) – The order operation.

  • pair (Pair) – The pair to trade.

  • amount (Decimal) – The base amount to buy/sell.

  • limit_price (Decimal) – The limit price.

  • auto_borrow (bool) – Automatically borrow missing funds.

  • auto_repay (bool) – Automatically repay open loans once the order gets filled.

Return type:

CreatedOrder

async create_loan(symbol, amount)

Creates a loan.

Parameters:
  • symbol (str) – The symbol to borrow.

  • amount (Decimal) – The amount to borrow.

Return type:

LoanInfo

async create_market_order(operation, pair, amount, auto_borrow=False, auto_repay=False)

Creates a market order.

A market order is an order to immediately buy or sell at the best available price. Generally, this type of order will be executed on the next bar using the open price as a reference, and according to the rules defined by the liquidity strategy. If the order is not filled on the next bar, due to lack of liquidity or funds, the order will be canceled.

If the order can’t be created an Error will be raised.

Parameters:
  • operation (OrderOperation) – The order operation.

  • pair (Pair) – The pair to trade.

  • amount (Decimal) – The base amount to buy/sell.

  • auto_borrow (bool) – Automatically borrow missing funds.

  • auto_repay (bool) – Automatically repay open loans once the order gets filled.

Return type:

CreatedOrder

async create_stop_limit_order(operation, pair, amount, stop_price, limit_price, auto_borrow=False, auto_repay=False)

Creates a stop limit order.

A stop-limit order is an order to buy or sell that combines the features of a stop order and a limit order. Once the stop price is reached, a stop-limit order becomes a limit order that will be executed at a specified price (or better).

If the order can’t be created an Error will be raised.

Parameters:
  • operation (OrderOperation) – The order operation.

  • pair (Pair) – The pair to trade.

  • amount (Decimal) – The base amount to buy/sell.

  • stop_price (Decimal) – The stop price.

  • limit_price (Decimal) – The limit price.

  • auto_borrow (bool) – Automatically borrow missing funds.

  • auto_repay (bool) – Automatically repay open loans once the order gets filled.

Return type:

CreatedOrder

async create_stop_order(operation, pair, amount, stop_price, auto_borrow=False, auto_repay=False)

Creates a stop order.

A stop order, also referred to as a stop-loss order, is an order to buy or sell once the price reaches a specified price, known as the stop price. When the stop price is reached, a stop order becomes a market order.

  • A buy stop order is entered at a stop price above the current market price. Investors generally use a buy stop order to limit a loss or to protect a profit on an instrument that they have sold short.

  • A sell stop order is entered at a stop price below the current market price. Investors generally use a sell stop order to limit a loss or to protect a profit on an instrument that they own.

If the order can’t be created an Error will be raised.

Parameters:
  • operation (OrderOperation) – The order operation.

  • pair (Pair) – The pair to trade.

  • amount (Decimal) – The base amount to buy/sell.

  • stop_price (Decimal) – The stop price.

  • auto_borrow (bool) – Automatically borrow missing funds.

  • auto_repay (bool) – Automatically repay open loans once the order gets filled.

Return type:

CreatedOrder

async get_balance(symbol)

Returns the balance for a specific currency/symbol/etc..

Parameters:

symbol (str) – The currency/symbol/etc..

Return type:

Balance

async get_balances()

Returns all balances.

Return type:

Dict[str, Balance]

async get_bid_ask(pair)

Returns the last bid and ask price.

This is calculated using the closing price of the last bar, and the bid/ask spread specified during initialization.

Parameters:

pair (Pair) – The trading pair.

Return type:

Tuple[Decimal, Decimal]

async get_loan(loan_id)

Returns information about a loan.

Parameters:

loan_id (str) – The loan id.

Return type:

LoanInfo

async get_loans(borrowed_symbol=None, is_open=None)

Returns loans filtered by various conditions.

Parameters:
  • borrowed_symbol (str | None) – If set, only loans matching this borrowed symbol will be returned.

  • is_open (bool | None) – If set, only open or closed loans will be returned.

Return type:

List[LoanInfo]

async get_open_orders(pair=None)

Returns open orders.

Parameters:

pair (Pair | None) – If set, only open orders matching this pair will be returned, otherwise all open orders will be returned.

Return type:

List[OpenOrder]

async get_order_info(order_id)

Returns information about an order.

If the order doesn’t exist, or its not open, an Error will be raised.

Parameters:

order_id (str) – The order id.

Return type:

OrderInfo

async get_orders(pair=None, is_open=None)

Returns orders filtered by various conditions.

Parameters:
  • pair (Pair | None) – If set, only orders matching this pair will be returned.

  • is_open (bool | None) – If set, only open or closed orders will be returned.

Return type:

List[OrderInfo]

async get_pair_info(pair)

Returns information about a trading pair.

Parameters:

pair (Pair) – The trading pair.

Return type:

PairInfo

async repay_loan(loan_id)

Repays a loan fully.

Parameters:

loan_id (str) – The loan id.

set_pair_info(pair, pair_info)

Set information about a trading pair.

Parameters:
  • pair (Pair) – The trading pair.

  • pair_info (PairInfo) – The pair information.

set_symbol_precision(symbol, precision)

Set precision for a symbol.

Parameters:
  • symbol (str) – The symbol.

  • precision (int) – The precision.

subscribe_to_bar_events(pair, event_handler)

Registers an async callable that will be called when a new bar is available.

Parameters:
  • pair (Pair) – The trading pair.

  • event_handler (Callable[[BarEvent], Awaitable[Any]]) – An async callable that receives a basana.BarEvent.

subscribe_to_order_events(event_handler)

Registers an async callable that will be called when an order is accepted or updated.

Parameters:

event_handler (Callable[[OrderEvent], Awaitable[Any]]) – The event handler.

exception basana.backtesting.exchange.Error

Bases: Error

Base class for backtesting exceptions.

class basana.backtesting.exchange.Balance(available: decimal.Decimal, hold: decimal.Decimal, borrowed: decimal.Decimal)
Parameters:
  • available (Decimal)

  • hold (Decimal)

  • borrowed (Decimal)

available: Decimal

The available balance.

borrowed: Decimal

The balance borrowed.

hold: Decimal

The balance on hold (reserved for open sell orders).

total: Decimal

The total balance (available + hold - borrowed).

class basana.backtesting.exchange.CreatedOrder(id, pair, is_open, operation, amount, amount_filled, amount_remaining, quote_amount_filled, fees, limit_price=None, stop_price=None, loan_ids=<factory>, fills=<factory>)
Parameters:
  • id (str)

  • pair (Pair)

  • is_open (bool)

  • operation (OrderOperation)

  • amount (Decimal)

  • amount_filled (Decimal)

  • amount_remaining (Decimal)

  • quote_amount_filled (Decimal)

  • fees (Dict[str, Decimal])

  • limit_price (Decimal | None)

  • stop_price (Decimal | None)

  • loan_ids (List[str])

  • fills (List[Fill])

amount: Decimal

The original amount.

amount_filled: Decimal

The amount filled.

amount_remaining: Decimal

The amount remaining.

fees: Dict[str, Decimal]

The fees charged.

property fill_price: Decimal | None

The fill price.

fills: List[Fill]

The fills.

id: str

The order id.

is_open: bool

True if the order is open, False otherwise.

limit_price: Decimal | None = None

The limit price.

loan_ids: List[str]

The ids of the associated loans.

operation: OrderOperation

The operation.

pair: Pair

The pair.

quote_amount_filled: Decimal

The quote amount filled.

stop_price: Decimal | None = None

The stop price.

class basana.backtesting.exchange.CanceledOrder(id: str)
Parameters:

id (str)

id: str

The order id.

class basana.backtesting.exchange.Fill(when: datetime.datetime, balance_updates: Dict[str, decimal.Decimal], fees: Dict[str, decimal.Decimal], fill_price: decimal.Decimal)
Parameters:
  • when (datetime)

  • balance_updates (Dict[str, Decimal])

  • fees (Dict[str, Decimal])

  • fill_price (Decimal)

balance_updates: Dict[str, Decimal]

The balance updates.

fees: Dict[str, Decimal]

The fees.

fill_price: Decimal

The fill price.

when: datetime

The time when the fill took place.

class basana.backtesting.exchange.OrderInfo(id: str, pair: basana.core.pair.Pair, is_open: bool, operation: basana.core.enums.OrderOperation, amount: decimal.Decimal, amount_filled: decimal.Decimal, amount_remaining: decimal.Decimal, quote_amount_filled: decimal.Decimal, fees: Dict[str, decimal.Decimal], limit_price: Optional[decimal.Decimal] = None, stop_price: Optional[decimal.Decimal] = None, loan_ids: List[str] = <factory>, fills: List[basana.backtesting.orders.Fill] = <factory>)
Parameters:
  • id (str)

  • pair (Pair)

  • is_open (bool)

  • operation (OrderOperation)

  • amount (Decimal)

  • amount_filled (Decimal)

  • amount_remaining (Decimal)

  • quote_amount_filled (Decimal)

  • fees (Dict[str, Decimal])

  • limit_price (Decimal | None)

  • stop_price (Decimal | None)

  • loan_ids (List[str])

  • fills (List[Fill])

amount: Decimal

The original amount.

amount_filled: Decimal

The amount filled.

amount_remaining: Decimal

The amount remaining.

fees: Dict[str, Decimal]

The fees charged.

property fill_price: Decimal | None

The fill price.

fills: List[Fill]

The fills.

id: str

The order id.

is_open: bool

True if the order is open, False otherwise.

limit_price: Decimal | None = None

The limit price.

loan_ids: List[str]

The ids of the associated loans.

operation: OrderOperation

The operation.

pair: Pair

The pair.

quote_amount_filled: Decimal

The quote amount filled.

stop_price: Decimal | None = None

The stop price.

class basana.backtesting.exchange.OpenOrder(id: str, operation: basana.core.enums.OrderOperation, amount: decimal.Decimal, amount_filled: decimal.Decimal)
Parameters:
  • id (str)

  • operation (OrderOperation)

  • amount (Decimal)

  • amount_filled (Decimal)

amount: Decimal

The original amount.

amount_filled: Decimal

The amount filled.

id: str

The order id.

operation: OrderOperation

The operation.

class basana.backtesting.exchange.OrderEvent(when, order)

An event for order updates.

Parameters:
order: OrderInfo

The order.