Virtual Broker#

broker='virtual'

The virtual broker immitates the functionality of a real broker for the purpose of backtesting and live papertrading.

Virtual Account Configuration#

Whenever the virtual broker is used (for example in backtesting or papertrading), the virtual trading account must be configured using the virtual_account_config method. If multiple brokers are being used simultaneously, this method must be called once for each broker.

When a real broker/exchange is specified in this method, the instance of AutoData created for data management will be connected to the broker specified.

Internal Position Management#

Orders#

Orders can take one of four statuses:

  1. pending - a pending order is one which has been submitted, but is being held until new data arrives.

  2. open - an open order is one which is valid to be filled. In the case of a market order, it will be filled as soon as new data is seen. In the case of limit orders, the order will remain open until its limit price has been triggered.

  3. filled - after an order has been filled, its status is changed to ‘filled’.

  4. cancelled - if an order is invalid, or gets cancelled by the user, its status will be changed to ‘cancelled’.

Positions#

Positions in an instrument are the result of orders being filled and trades being made.

In order to keep track of stop-losses and take-profits associated with individual orders, a position is made up of multiple IsolatedPositions. These are positions resulting from a single trade, and are treated in isolation of the entire position in case there is a stop-loss or take-proft attached to them.

Trade Execution#

The virtual broker maintains its own orderbook. The details of this depend on whether AutoTrader is in backtest or livetrade mode.

Backtest Mode#

When backtesting, the top levels of the book are simulated to have infinite liquidity. The bid and ask prices are set using the OHLC data and the specified bid/ask spread model.

Livetrade Mode#

When livetrading (including papertrading), the execution of orders can become more accurate by tapping into the real-time orderbook of your chosen exchange. To do so, the broker/exchange specified in AutoTrader.configure and AutoTrader.virtual_account_config is connected to when creating an instance of the virtual broker. When orders are recieved, the real-time order book will be queried and used to simulate execution.

API Reference#

class autotrader.brokers.virtual.broker.Broker(broker_config: dict | None = None, utils: BrokerUtils | None = None)#

Autotrader Virtual Broker for simulated trading.

verbosity#

The verbosity of the broker.

Type:

int

pending_orders#

A dictionary containing pending orders.

Type:

dict

open_orders#

A dictionary containing open orders yet to be filled.

Type:

dict

filled_orders#

A dictionary containing filled orders.

Type:

dict

cancelled_orders#

A dictionary containing cancelled orders.

Type:

dict

open_trades#

A dictionary containing currently open trades (fills).

Type:

dict

closed_trades#

A dictionary containing closed trades.

Type:

dict

base_currency#

The base currency of the account. The default is ‘AUD’.

Type:

str

NAV#

The net asset value of the account.

Type:

float

equity#

The account equity balance.

Type:

float

floating_pnl#

The floating PnL.

Type:

float

margin_available#

The margin available on the account.

Type:

float

leverage#

The account leverage.

Type:

int

spread#

The average spread to use when opening and closing trades.

Type:

float

spread_units#

The units of the spread (eg. ‘price’ or ‘percentage’). The default is ‘price’.

Type:

str

hedging#

Flag whethere hedging is enabled on the account. The default is False.

Type:

bool

margin_closeout#

The fraction of margin available at margin call. The default is 0.

Type:

float

commission_scheme#

The commission scheme being used (‘percentage’, ‘fixed_per_unit’ or ‘flat’). The default is ‘percentage’.

Type:

str

commission#

The commission value associated with the commission scheme.

Type:

float

maker_commission#

The commission value associated with liquidity making orders.

Type:

float

taker_commission#

The commission value associated with liquidity taking orders.

Type:

float

_add_orders_to_book(instrument, orderbook)#

Adds local orders to the orderbook.

_adjust_balance(amount: float, latest_time: datetime | None = None) None#

Adjusts the balance of the account.

_calculate_commissions(price: float, units: float | None = None, HCF: float = 1, order_type: str = 'market') float#

Calculates trade commissions.

_calculate_margin(position_value: float) float#

Calculates margin required to take a position with the available leverage of the account.

_fill_order(last_price: float, fill_price: float, fill_time: datetime, order: Order | None = None, liquidation_order: bool = False) None#

Marks an order as filled and records the trade as a Fill.

Parameters:
  • fill_price (float) – The fill price.

  • fill_time (datetime) – The time at which the order is filled.

  • order (Order, optional) – The order to fill. The default is None, in which case the arguments below must be specified.

  • liquidation_order (bool, optional) – A flag whether this is a liquidation order from the broker.

_load_state()#

Loads the state of the broker from a pickle.

_make_deposit(deposit: float) None#

Adds deposit to account balance and NAV.

_margin_call(instrument: str, latest_time: datetime, latest_price: float)#

Closes the open position of the instrument.

_modify_position(trade: Trade, reduce_only: bool)#

Modifies the position in a position.

_move_order(order: Order, from_dict: str = '_open_orders', to_dict: str = '_filled_orders', new_status: str = 'filled') None#

Moves an order from the from_dict to the to_dict.

_process_order(order: Order, fill_time: datetime | None = None, reference_price: float | None = None, trade_size: float | None = None)#

Processes an order, either filling or cancelling it.

Parameters:
  • order (Order) – The order being processed.

  • fill_time (datetime, optional) – The time to fill the order.

  • reference_price (float, optional) – The order reference price (either market price or order limit price).

  • trade_size (float, optional) – The size of a public trade being used to fill orders (papertrade mode). The default is None.

_public_trade(instrument: str, trade: dict)#

Uses a public trade to update virtual orders.

_save_state()#

Pickles the current state of the broker.

_trade_through_book(instrument: str, direction: int, size: float, reference_price: float | None = None, precision: int | None = None) float#

Returns an average fill price by filling an order through the orderbook.

Parameters:
  • instrument (str) – The instrument to fetch the orderbook for.

  • direction (int) – The direction of the trade (1 for long, -1 for short). Used to specify either bid or ask prices.

  • size (float) – The size of the trade.

  • reference_price (float, optional) – The reference price to use if artificially creating an orderbook.

  • precision (dict, optional) – The precision to use for rounding prices. The default is None.

_update_all()#

Convenience method to update all open positions when paper trading.

_update_instrument(instrument)#

Convenience method to update a single instrument when paper trading.

_update_margin(instrument: str | None = None, latest_time: datetime | None = None) None#

Updates the margin available in the account.

_update_positions(instrument: str, candle: Series | None = None, L1: dict | None = None, trade: dict | None = None) None#

Updates orders and open positions based on the latest data.

Parameters:
  • instrument (str) – The name of the instrument being updated.

  • candle (pd.Series) – An OHLC candle used to update orders and trades.

  • L1 (dict, optional) – A dictionary a containing level 1 price snapshot to update the positions with. This dictionary must have the keys ‘bid’, ‘ask’, ‘bid_size’ and ‘ask_size’.

  • trade (dict, optional) – A public trade, used to update virtual limit orders.

static _zero_slippage_model(*args, **kwargs)#

Returns zero slippage.

cancel_order(order_id: int, reason: str | None = None, from_dict: str = '_open_orders', timestamp: datetime | None = None, **kwargs) None#

Cancels the order.

Parameters:
  • order_id (int) – The ID of the order to be cancelled.

  • reason (str, optional) – The reason why the order is being cancelled. The default is None.

  • from_dict (str, optional) – The dictionary currently holding the order. The default is ‘open_orders’.

  • timestamp (datetime, optional) – The datetime stamp of the order cancellation. The default is None.

configure(verbosity: int | None = None, initial_balance: float | None = None, leverage: int | None = None, spread: float | None = None, spread_units: str | None = None, commission: float | None = None, commission_scheme: str | None = None, maker_commission: float | None = None, taker_commission: float | None = None, hedging: bool | None = None, base_currency: str | None = None, paper_mode: bool | None = None, public_trade_access: bool | None = None, margin_closeout: float | None = None, default_slippage_model: Callable | None = None, slippage_models: dict | None = None, charge_funding: bool | None = None, funding_history: DataFrame | None = None, autodata_config: dict | None = None, picklefile: str | None = None, **kwargs)#

Configures the broker and account settings.

Parameters:
  • verbosity (int, optional) – The verbosity of the broker. The default is 0.

  • initial_balance (float, optional) – The initial balance of the account, specified in the base currency. The default is 0.

  • leverage (int, optional) – The leverage available. The default is 1.

  • spread (float, optional) – The bid/ask spread to use in backtest (specified in units defined by the spread_units argument). The default is 0.

  • spread_units (str, optional) – The unit of the spread specified. Options are ‘price’, meaning that the spread is quoted in price units, or ‘percentage’, meaning that the spread is quoted as a percentage of the market price. The default is ‘price’.

  • commission (float, optional) – Trading commission as percentage per trade. The default is 0.

  • commission_scheme (str, optional) – The method with which to apply commissions to trades made. The options are (1) ‘percentage’, where the percentage specified by the commission argument is applied to the notional trade value, (2) ‘fixed_per_unit’, where the monetary value specified by the commission argument is multiplied by the number of units in the trade, and (3) ‘flat’, where a flat monetary value specified by the commission argument is charged per trade made, regardless of size. The default is ‘percentage’.

  • maker_commission (float, optional) – The commission to charge on liquidity-making orders. The default is None, in which case the nominal commission argument will be used.

  • taker_commission (float, optional) – The commission to charge on liquidity-taking orders. The default is None, in which case the nominal commission argument will be used.

  • hedging (bool, optional) – Allow hedging in the virtual broker (opening simultaneous trades in oposing directions). The default is False.

  • base_currency (str, optional) – The base currency of the account. The default is AUD.

  • paper_mode (bool, optional) – A boolean flag to indicate if the broker is in paper trade mode. The default is False.

  • public_trade_access (bool, optional) – A boolean flag to signal if public trades are being used to update limit orders. The default is False.

  • margin_closeout (float, optional) – The fraction of margin usage at which a margin call will occur. The default is 0.

  • default_slippage_model (Callable, optional) – The default model to use when calculating the percentage slippage on the fill price, for a given order size. The default functon returns zero.

  • slippage_models (dict, optional) – A dictionary of callable slippage models, keyed by instrument.

  • charge_funding (bool, optional) – A boolean flag to charge funding rates. The default is False.

  • funding_history (pd.DataFrame, optional) – A DataFrame of funding rate histories for instruments being traded, to backtest trading perpetual futures. This is a single frame with as many columns as instruments being traded. If an instrument is not present, the funding rate will be zero.

  • picklefile (str, optional) – The filename of the picklefile to load state from. If you do not wish to load from state, leave this as None. The default is None.

get_NAV() float#

Returns Net Asset Value of account.

get_balance() float#

Returns balance of account.

get_margin_available() float#

Returns the margin available on the account.

get_orderbook(instrument: str, midprice: float | None = None) OrderBook#

Returns the orderbook.

get_orders(instrument: str | None = None, order_status: str = 'open') dict#

Returns orders of status order_status.

get_positions(instrument: str | None = None) dict#

Returns the positions held by the account, sorted by instrument.

Parameters:

instrument (str, optional) – The trading instrument name (symbol). If ‘None’ is provided, all positions will be returned. The default is None.

Returns:

open_positions – A dictionary containing details of the open positions.

Return type:

dict

Notes

net_position: refers to the number of units held in the position.

get_trades(instrument: str | None = None, **kwargs) dict#

Returns fills for the specified instrument.

Parameters:

instrument (str, optional) – The instrument to fetch trades under. The default is None.

place_order(order: Order, **kwargs) None#

Place order with broker.