AutoTrader#

from autotrader import AutoTrader

The AutoTrader class is the orchestrator of your trading system. It will sort out all the boring stuff so that you can spend more time where it matters - researching good trading strategies.

Configuration Methods#

The following methods are used to configure the active instance of AutoTrader.

Run Configuration#

To configure the settings of AutoTrader, use the configure method. Here you can specifiy the verbosity of AutoTrader, set your data feed, set which broker to trade with and more. If you are going to provide local data, you should always call the configure method prior to specifying the local data via the add_data method, to ensure that the working directory is correctly configured. In general, it is always good to call configure first up.

AutoTrader.configure(verbosity: int = 1, broker: str | None = None, execution_method: Callable | None = None, feed: str | None = None, req_liveprice: bool = False, notify: int = 0, notification_provider: str | None = None, home_dir: str | None = None, allow_dancing_bears: bool = False, account_id: str | None = None, environment: str = 'paper', show_plot: bool = False, jupyter_notebook: bool = False, mode: str = 'continuous', update_interval: str | None = None, data_index_time: str = 'open', global_config: dict | None = None, instance_str: str | None = None, broker_verbosity: int = 0, home_currency: str | None = None, allow_duplicate_bars: bool = False, deploy_time: datetime | None = None, max_workers: int | None = None) None#

Configures run settings for AutoTrader.

Parameters:
  • verbosity (int, optional) – The verbosity of AutoTrader (0, 1, 2). The default is 1.

  • broker (str, optional) – The broker(s) to connect to for trade execution. Multiple exchanges can be provided using comma separattion. The default is ‘virtual’.

  • execution_method (Callable, optional) – The execution model to call when submitting orders to the broker. This method must accept the broker instance, the order object, order_time and any *args, **kwargs.

  • feed (str, optional) – The data feed to be used. This can be the same as the broker being used, or another data source. Options include ‘yahoo’, ‘oanda’, ‘ib’, ‘dydx’, ‘ccxt’, ‘local’ or ‘none’. When data is provided via the add_data method, the feed is automatically set to ‘local’. The default is None.

  • req_liveprice (bool, optional) – Request live market price from broker before placing trade, rather than using the data already provided. The default is False.

  • notify (int, optional) – The level of notifications (0, 1, 2). The default is 0.

  • notification_provider (str, optional) – The notifications provider to use (currently only Telegram supported). The default is None.

  • home_dir (str, optional) – The project home directory. The default is the current working directory.

  • allow_dancing_bears (bool, optional) – Allow incomplete candles to be passed to the strategy. The default is False.

  • account_id (str, optional) – The brokerage account ID to be used. The default is None.

  • environment (str, optional) – The trading environment of this instance (‘paper’, ‘live’). The default is ‘paper’.

  • show_plot (bool, optional) – Automatically generate trade chart. The default is False.

  • jupyter_notebook (bool, optional) – Set to True when running in Jupyter notebook environment. The default is False.

  • mode (str, optional) – The run mode (either ‘periodic’ or ‘continuous’). The default is ‘periodic’.

  • update_interval (str, optional) – The update interval to use when running in ‘continuous’ mode. This should align with the highest resolution bar granularity in your strategy to allow adequate updates. The string inputted will be converted to a timedelta object. If None is passed, the update interval will be inferred from the strategy INTERVAL. The default is None.

  • data_index_time (str, optional) – The time by which the data is indexed. Either ‘open’, if the data is indexed by the bar open time, or ‘close’, if the data is indexed by the bar close time. The default is ‘open’.

  • global_config (dict, optional) – Optionally provide your global configuration directly as a dictionary, rather than it being read in from a yaml file. The default is None.

  • instance_str (str, optional) – The name of the active AutoTrader instance, used to control bots deployed when livetrading in continuous mode. When not specified, the instance string will be of the form ‘autotrader_instance_n’. The default is None.

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

  • home_currency (str, optional) – The home currency of trading accounts used (intended for FX conversions). The default is None.

  • allow_duplicate_bars (bool, optional) – Allow duplicate bars to be passed on to the strategy. The default is False.

  • deploy_time (datetime, optional) – The time to deploy the bots. If this is a future time, AutoTrader will wait until it is reached before deploying. It will also be used as an anchor to synchronise future bot updates. If not specified, bots will be deployed as soon as possible, with successive updates synchronised to the deployment time.

  • max_workers (int, optional) – The maximum number of workers to use when spawning threads. The default is None.

Returns:

Calling this method configures the internal settings of the active AutoTrader instance.

Return type:

None

Backtest Configuration#

To configure a backtest, use the backtest method.

AutoTrader.backtest(start: str | None = None, end: str | None = None, start_dt: datetime | None = None, end_dt: datetime | None = None, warmup_period: str = '0s') None#

Configures settings for backtesting.

Parameters:
  • start (str, optional) – Start date for backtesting, in format dd/mm/yyyy. The default is None.

  • end (str, optional) – End date for backtesting, in format dd/mm/yyyy. The default is None.

  • start_dt (datetime, optional) – Datetime object corresponding to start time. The default is None.

  • end_dt (datetime, optional) – Datetime object corresponding to end time. The default is None.

  • warmup_period (str, optional) – A string describing the warmup period to be used. This is equivalent to the minimum period of time required to collect sufficient data for the strategy. The default is ‘0s’.

Notes

Start and end times must be specified as the same type. For example, both start and end arguments must be provided together, or alternatively, start_dt and end_dt must both be provided.

Virtual Account Configuration#

Any time you are simulating trading, either in backtest or papertrading, you should configure the simulated trading account. This is done using the virtual_account_config method. Here, you can set your initial balance, the bid/ask spread, the trading fees and more. If you do not call this method when simulating trading, the default settings will be used.

If you plan on simultaneously trading across multiple venues, you will need to configure a virtual account for each exchange being simulated. When doing so, use the exchange argument to specify which account it is that you are configuring. This should align with the brokers/exchanges specified to the broker argument in AutoTrader.configure.

AutoTrader.virtual_account_config(verbosity: int = 0, initial_balance: float = 1000, spread: float = 0, commission: float = 0, spread_units: str = 'price', commission_scheme: str = 'percentage', maker_commission: float | None = None, taker_commission: float | None = None, leverage: int = 1, hedging: bool = False, margin_call_fraction: float = 0, default_slippage_model: Callable | None = None, slippage_models: dict | None = None, picklefile: str | None = None, exchange: str | None = None, tradeable_instruments: list | None = None, refresh_freq: str = '1s', home_currency: str | None = None, papertrade: bool = True) None#

Configures the virtual broker’s initial state to allow livetrading on the virtual broker. If you wish to create multiple virtual broker instances, call this method for each virtual account.

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

  • initial_balance (float, optional) – The initial balance of the account. The default is 1000.

  • 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.

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

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

  • margin_call_fraction (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.

  • 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.

  • exchange (str, optional) – The name of the exchange to use for execution. This gets passed to an instance of AutoData to update prices and use the realtime orderbook for virtual order execution. The default is None.

  • tradeable_instruments (list, optional) – A list containing strings of the instruments tradeable through the exchange specified. This is used to determine which exchange orders should be submitted to when trading across multiple exchanges. This should account for all instruments provided in the watchlist. The default is None.

  • refresh_freq (str, optional) – The timeperiod to sleep for in between updates of the virtual broker data feed when manually papertrading. The default is ‘1s’.

  • home_currency (str, optional) – The home currency of the account. The default is None.

  • papertrade (bool, optional) – A boolean to flag when the account is to be used for papertrading (real-time trading on paper). The default is True.

Configure AutoPlot Settings#

To configure the settings used by AutoPlot when creating charts, use the plot_settings method.

AutoTrader.plot_settings(max_indis_over: int = 3, max_indis_below: int = 2, fig_tools: str = 'pan,wheel_zoom,box_zoom,undo,redo,reset,save,crosshair', ohlc_height: int = 400, ohlc_width: int = 800, top_fig_height: int = 150, bottom_fig_height: int = 150, jupyter_notebook: bool = False, show_cancelled: bool = True, chart_timeframe: str = 'default', chart_theme: str = 'caliber', use_strat_plot_data: bool = False, portfolio_chart: bool = False) None#

Configure the plot settings.

Parameters:
  • max_indis_over (int, optional) – Maximum number of indicators overlaid on the main chart. The default is 3.

  • max_indis_below (int, optional) – Maximum number of indicators below the main chart. The default is 2.

  • fig_tools (str, optional) – The figure tools. The default is “pan,wheel_zoom,box_zoom,undo, redo,reset,save,crosshair”.

  • ohlc_height (int, optional) – The height (px) of the main chart. The default is 400.

  • ohlc_width (int, optional) – The width (px) of the main chart. The default is 800.

  • top_fig_height (int, optional) – The height (px) of the figure above the main chart. The default is 150.

  • bottom_fig_height (int, optional) – The height (px) of the figure(s) below the main chart. The default is 150.

  • jupyter_notebook (bool, optional) – Boolean flag when running in Jupyter Notebooks, to allow inline plotting. The default is False.

  • show_cancelled (bool, optional) – Show/hide cancelled trades. The default is True.

  • chart_timeframe (str, optional) – The bar timeframe to use when gerating the chart. The timeframe provided must be a part of the strategy dataset. The default is ‘default’.

  • chart_theme (bool, optional) – The theme of the Bokeh chart generated. The default is “caliber”.

  • use_strat_plot_data (bool, optional) – Boolean flag to use data from the strategy instead of candlestick data for the chart. If True, ensure your strategy has a timeseries data attribute named ‘plot_data’. The default is False.

  • portfolio_chart (bool, optional) – Override the default plot settings to plot the portfolio chart even when running a single instrument backtest.

Returns:

The plot settings will be saved to the active AutoTrader instance.

Return type:

None

Other Methods#

Below are the methods used to add your own components to AutoTrader.

Add New Strategy#

Trading strategies can be added using the add_strategy method of AutoTrader. If you would like to add multiple strategies to the same instance of AutoTrader, simply call this method for each strategy being added. Note that this method accepts both strategy_filename and strategy_dict arguments. The first of these is used to provide the prefix of a strategy configuration file, while the second can be used to directly pass in a strategy configuration dictionary.

AutoTrader.add_strategy(config_filename: str | None = None, config_dict: dict | None = None, strategy=None, shutdown_method: str | None = None) None#

Adds a strategy to AutoTrader.

Parameters:
  • config_filename (str, optional) – The prefix of the yaml strategy configuration file, located in home_dir/config. The default is None.

  • config_dict (dict, optional) – Alternative to config_filename, a strategy configuration dictionary can be passed directly. The default is None.

  • strategy (AutoTrader Strategy, optional) – The strategy class object. The default is None.

  • shutdown_method (str, optional) – The name of the shutdown method in the strategy (if any). This method will be called when AutoTrader is livetrading in continuous mode, and the instance has recieved the shutdown signal. The default is None.

Returns:

The strategy will be added to the active AutoTrader instance.

Return type:

None

Add Data#

To trade using a local data source, use the add_data method to tell AutoTrader where to look for the data. You can use this method for both backtesting and livetrading. Of course, if you are livetrading, you will need to make sure that the locally stored data is being updated at an appropriate interval.

Note that you do not have to call this method if you are directly connecting to one of the supported exchanges for a data feed. In this case, AutoTrader will automatically download data using the information provided in your strategy configuration and supply it to your strategy.

Important

The configure method should be called before calling add_data, as it will set the home_dir of your project.

AutoTrader.add_data(data_dict: dict | None = None, mapper_func: callable | None = None, quote_data: dict | None = None, data_directory: str = 'price_data', abs_dir_path: str | None = None, auxdata: dict | None = None, stream_object=None, dynamic_data: bool = False) None#

Specify local data to run AutoTrader on.

Parameters:
  • data_dict (dict, optional) – A dictionary containing the filenames of the datasets to be used. The default is None.

  • mapper_func (callable, optional) – A callable used to provide the absolute filepath to the data given the instrument name (as it appears in the watchlist) as an input argument. The default is None.

  • quote_data (dict, optional) – A dictionary containing the quote data filenames of the datasets provided in data_dict. The default is None.

  • data_directory (str, optional) – The name of the sub-directory containing price data files. This directory should be located in the project home directory (at.home_dir). The default is ‘price_data’.

  • abs_dir_path (str, optional) – The absolute path to the data_directory. This parameter may be used when the datafiles are stored outside of the project directory. The default is None.

  • auxdata (dict, optional) – A dictionary containing the data paths to supplement the data passed to the strategy module. For strategies involving multiple products, the keys of this dictionary must correspond to the products, with the auxdata in nested dictionaries or otherwise. The default is None.

  • stream_object (DataStream, optional) – A custom data stream object, allowing custom data pipelines. The default is DataStream (from autotrader.utilities).

  • dynamic_data (bool, optional) – A boolean flag to signal that the stream object provided should be refreshed each timestep of a backtest. This can be useful when backtesting strategies with futures contracts, which expire and must be rolled. The default is False.

Raises:

Exception – When multiple quote-data files are provided per instrument traded.

Returns:

Data will be assigned to the active AutoTrader instance for later use.

Return type:

None

Notes

To ensure proper directory configuration, this method should only be called after calling autotrader.configure().

The data provided to the strategy will either contain a single timeframe OHLC dataframe, a dictionary of MTF dataframes, or a dict with ‘base’ and ‘aux’ keys, for aux and base strategy data (which could be single of MTF).

Examples

An example data_dict is shown below.

>>> data_dict = {'product1': 'filename1.csv',
                 'product2': 'filename2.csv'}

For MTF data, data_dict should take the form shown below. In the case of MTF data, quote data should only be provided for the base timeframe (ie. the data which will be iterated on when backtesting). Therefore, the quote_data dict will look the same for single timeframe and MTF backtests.

>>> data_dict = {'product1': {'H1': 'product1_H1.csv',
                              'D': 'product1_D.csv'},
                 'product2': {'H1': 'product2_H1.csv',
                              'D': 'product2_D.csv'}
                 }

An example for the quate_data dictionary is shown below.

>>> quote_data = {'product1': 'product1_quote.csv',
                  'product2': 'product2_quote.csv'}

The auxdata dictionary can take the form shown below. This data will be passed on to your strategy.

>>> auxdata = {'product1': 'aux_price_data.csv',
               'product2': {'extra_data1': 'dataset1.csv',
                            'extra_data2': 'dataset2.csv'}
               }

Get Bots Deployed#

After running AutoTrader, it may be of interest to access the trading bots that were deployed. To do so, use the get_bots_deployed method.

AutoTrader.get_bots_deployed(instrument: str | None = None) dict#

Returns a dictionary of AutoTrader trading bots, organised by instrument traded.

Parameters:

instrument (str, optional) – The instrument of the bot to retrieve. The default is None.

Returns:

A dictionary of deployed AutoTrader bot instances.

Return type:

dict

Notes

If there is only one trading bot deployed, this will be returned directly, rather than in a dict.

Plot Backtest#

After running a backtest, you can call plot_backtest to create a chart of the trade results. You can also pass in a specific trading bot to view the trades taken by that specific bot.

AutoTrader.plot_backtest(bot=None) None#

Plots trade results of an AutoTrader Bot.

Parameters:

bot (AutoTrader bot instance, optional) – AutoTrader bot class containing trade results. The default is None.

Returns:

A chart will be generated and shown.

Return type:

None

Run AutoTrader#

After configuring AutoTrader, adding a strategy and specifying how you would like to trade, you are ready to run AutoTrader. To do so, simply call the run method.

AutoTrader.run() AbstractBroker#

Performs essential checks and runs AutoTrader.

Example Runfiles#

Shown below are example scripts for running AutoTrader.

See also

More examples can be found in the demo repository.

from autotrader import AutoTrader

at = AutoTrader()
at.configure(feed='oanda', broker='oanda', verbosity=1)
at.add_strategy('macd_crossover')
at.backtest(start='1/1/2015', end='1/3/2022')
at.virtual_account_config(leverage=30, exchange='oanda')
at.run()
from autotrader import AutoTrader

at = AutoTrader()
at.configure(feed='oanda', broker='oanda', verbosity=1)
at.add_strategy('macd_crossover')
at.virtual_account_config(leverage=30, exchange='oanda')
at.run()
from autotrader import AutoTrader

at = AutoTrader()
at.configure(feed='oanda', broker='oanda', verbosity=1)
at.add_strategy('macd_crossover')
at.run()