A Python-based development platform for automated trading systems - from backtesting to optimisation to livetrading.

Overview

AutoTrader Logo

AutoTrader

Latest version Total downloads Monthly downloads Build Status Documentation Status

AutoTrader is Python-based platform intended to help in the development, optimisation and deployment of automated trading systems. From simple indicator-based strategies, to complex non-directional hedging strategies, AutoTrader can do it all. If you prefer a more hands-on approach to trading, AutoTrader can also assist you by notifying you of price behaviour, ensuring you never miss a signal again. A basic level of experience with Python is recommended for using AutoTrader, but the docs aim to make using it as easy as possible with detailed tutorials and documentation.

Features

Installation

AutoTrader can be installed using pip:

pip install autotrader

Updating

AutoTrader can be updated by appending the --upgrade flag to the install command:

pip install autotrader --upgrade

Documentation

AutoTrader is very well documented in-code and on Read the Docs. There is also a detailed walthrough, covering everything from strategy concept to livetrading.

Example Strategies

Example strategies can be found in the demo repository. You can also request your own strategy to be built here.

Backtest Demo

The chart below is produced by a backtest of the MACD trend strategy documented in the tutorials (and available in the demo repository). Entry signals are defined by MACD crossovers, with exit targets defined by a 1.5 risk-to-reward ratio. Stop-losses are automatically placed using the custom swing detection indicator, and position sizes are dynamically calculated based on risk percentages defined in the strategy configuration.

Running this strategy with AutoTrader in backtest mode will produce the following interactive chart.

MACD-backtest-demo

Note that stop loss and take profit levels are shown for each trade taken. This allows you to see how effective your exit strategy is - are you being stopped out too early by placing your stop losses too tight? Are you missing out on otherwise profitable trades becuase your take profits are too far away? AutoTrader helps you visualise your strategy and answer these questions.

Legal

License

AutoTrader is licensed under the GNU General Public License v3.0.

Disclaimer

This platform is currently under heavy development and should not be considered stable for livetrading until version 1.0.0 is released.

Never risk money you cannot afford to lose. Always test your strategies on a paper trading account before taking it live.

Comments
  • Error encountered while running on Live Mode

    Error encountered while running on Live Mode

    Describe the bug Could not run on Live Mode on Oanda.

    Traceback (most recent call last):
      File "runfile.py", line 23, in <module>
        at.run()
      File "/usr/local/lib/python3.8/site-packages/autotrader/autotrader.py", line 218, in run
        self._main()
      File "/usr/local/lib/python3.8/site-packages/autotrader/autotrader.py", line 295, in _main
        bot = AutoTraderBot(instrument, self.strategies[strategy],
      File "/usr/local/lib/python3.8/site-packages/autotrader/autobot.py", line 146, in __init__
        data, quote_data, MTF_data = self._retrieve_data(instrument, self.feed)
      File "/usr/local/lib/python3.8/site-packages/autotrader/autobot.py", line 546, in _retrieve_data
        data = getattr(self.get_data, feed.lower())(instrument,
      File "/usr/local/lib/python3.8/site-packages/autotrader/lib/autodata.py", line 99, in oanda
        data        = self.response_to_df(response)
      File "/usr/local/lib/python3.8/site-packages/autotrader/lib/autodata.py", line 222, in response_to_df
        candles = response.body["candles"]
    KeyError: 'candles'
    

    To Reproduce Here is a copy of my strategy yaml file

    NAME: 'MACD Momentum Strategy'
    MODULE: 'macd'
    CLASS: 'SimpleMACD'
    INTERVAL: '5m'
    PERIOD: 200
    RISK_PC: 1
    SIZING: 'risk'
    PARAMETERS:
      ema_period_fast: 20
      ema_period_slow: 200
      MACD_fast: 12
      MACD_slow: 26
      MACD_smoothing: 9
    
    WATCHLIST: ['EURUSD=X']
    

    Expected behavior To be able to run as expected on Live Mode.

    Version of AutoTrader being used Latest.

    Any idea what the issue could be?

    opened by elijahho 20
  • dydx Connectivity

    dydx Connectivity

    Hi there, I am looking to live trade with dydx, but when I am attempting to connect and run a basic algorithm, I am getting errors.

    The first one is: AutoData is not defined. I fixed this by importing the class in the dydx/broker.py file.

    The next one is related to the data feed. The system exits right after the prompt "Please specify a data feed" shows up.

    Any help would be greatly appreciated! Jamie Capture

    bug 
    opened by jfitz001 13
  • STOCHASTIC Plotting doesn't work

    STOCHASTIC Plotting doesn't work

    Describe the bug When using the key STOCHASTIC in the indicators dictionary an error is thrown.

    To Reproduce Steps to reproduce the behaviour:

    1. Create a strategy and create STOCHK and STOCHD
            self.stoch_rsi = TA.STOCHRSI(self.data, rsi_period=6, stoch_period=27)
            self.stoch_rsi_k = TA.STOCH(self.data, period=3)
            self.stoch_rsi_d = TA.STOCHD(self.data, period=3, stoch_period=27)
    
    1. Create an indicator dictionary something like:
            self.indicators = {
                "RSI": {"type": "RSI", "data": self.stoch_rsi},
                "STOCHASTIC": {
                    "K": self.stoch_rsi_k,
                    "D": self.stoch_rsi_d,
                },
            }
    
    1. Run a backtest
    2. See error:
    
    Traceback (most recent call last):
      File "/home/lewis/Projects/trading_bot/runfile.py", line 65, in <module>
        main()
      File "/home/lewis/Projects/trading_bot/runfile.py", line 58, in main
        at.run()
      File "/home/lewis/.pyenv/versions/3.8.9/envs/maxwell/lib/python3.8/site-packages/autotrader/autotrader.py", line 711, in run
        self._main()
      File "/home/lewis/.pyenv/versions/3.8.9/envs/maxwell/lib/python3.8/site-packages/autotrader/autotrader.py", line 1120, in _main
        self.plot_backtest()
      File "/home/lewis/.pyenv/versions/3.8.9/envs/maxwell/lib/python3.8/site-packages/autotrader/autotrader.py", line 971, in plot_backtest
        ap.plot(backtest_dict=bot.backtest_results)
      File "/home/lewis/.pyenv/versions/3.8.9/envs/maxwell/lib/python3.8/site-packages/autotrader/autoplot.py", line 293, in plot
        bottom_figs = self._plot_indicators(indicators, main_plot)
      File "/home/lewis/.pyenv/versions/3.8.9/envs/maxwell/lib/python3.8/site-packages/autotrader/autoplot.py", line 736, in _plot_indicators
        indi_type = indicators[indicator]['type']
    KeyError: 'type'
    
    Process finished with exit code 1
    

    Expected behaviour Plot the two stochastic lines below the chart in one section.

    Screenshots n/a

    Version of AutoTrader being used autotrader==0.6.2

    Additional context Few other questions:

    • Is there any functionality during backtesting to access previous trades? e.g. last 4 trades were losses so use 0.5*RR
    • If the strategy has a lot of triggers it seems to cancel all trades, any idea why this might happen? My thought would be the whole account balance is in use so can't make a new trade without cancelling a previous one, when really it should just not create the new trade and let the old ones run.
    bug 
    opened by lleewwiiss 6
  • Interactive Brokers

    Interactive Brokers

    Noted that support for IB was planned, but did not spot any draft implementation

    Was thinking of implementing Interactive-Brokers support through using IB-Insync framework for simplicity(mainly using it for stocks), but if you already have something cooking that would save time and effort of course.. https://github.com/erdewit/ib_insync.git

    Note that I'm still on a steep learning curve, so things go slow ; ) Thanks for a nice package anyway.

    enhancement 
    opened by Polypod 6
  • Support for multi-time frame data

    Support for multi-time frame data

    Is your feature request related to a problem? Please describe. Support for allowing to read in 2+ different time frames at a time, this helps if you are building a strategy around higher time frame indicators but want to trade on a lower time frame.

    Describe the solution you'd like Similar to watchlist which allows for a list of product codes, allow for a list of time frames.

    Describe alternatives you've considered I realise you can just get the data manually and load it manually in the init of your strategy, but loading the data in your runfile will overwrite the data you specified in the YAML, so allowing for additional time frames, or another variable for supplementary data would be ideal.

    Additional context n/a

    opened by lleewwiiss 6
  • Backtest strategy using Oanda historical data ?

    Backtest strategy using Oanda historical data ?

    Hi, I'm trying to backtest your macd demo strategy using Oanda as broker but I'm not able to do so.

    Here's steps I've done :

    1. Create a demo account in Oanda , so to receive api v20 access token and account id

    2. Generate keys.yaml in /config folder where I've put previous data (ACCESS_TOKEN, DEFAULT_ACCOUNT_ID)

    3. Modified runfile.py to use oanda as broker at line: at.configure(verbosity=1, show_plot=True, feed='oanda', mode='periodic')

    4. Changed macd.yaml like to match EURUSD Oanda symbol at line : WATCHLIST: ['EUR_USD']

    5. Execute python runfile.py and received this error :

    (base) C:\Users\Giacomo\Downloads_AutoTrader\AT_DEMO>python runfile.py Traceback (most recent call last): File "C:\Users\Giacomo\Downloads_AutoTrader\AT_DEMO\runfile.py", line 9, in at.run() File "C:\Users\Giacomo\anaconda3\lib\site-packages\autotrader\autotrader.py", line 1049, in run self._main() File "C:\Users\Giacomo\anaconda3\lib\site-packages\autotrader\autotrader.py", line 1428, in _main self._assign_broker(broker_config) File "C:\Users\Giacomo\anaconda3\lib\site-packages\autotrader\autotrader.py", line 1635, in _assign_broker broker.configure(**account_config, autodata_config=autodata_config) File "C:\Users\Giacomo\anaconda3\lib\site-packages\autotrader\brokers\virtual\broker.py", line 256, in configure self._autodata = AutoData(data_config, **autodata_config) File "C:\Users\Giacomo\anaconda3\lib\site-packages\autotrader\autodata.py", line 82, in init self.ACCOUNT_ID = data_config["ACCOUNT_ID"] KeyError: 'ACCOUNT_ID'

    Is there something else that I have to set in order to be able to backtest whatever strategy using oanda historical prices ?

    Thanks, Regards Giacomo

    bug 
    opened by GL-Software 5
  • Insufficient margin to fill order when stop loss is set

    Insufficient margin to fill order when stop loss is set

    Describe the bug I've an issue when I set a stop loss in my strategy: Situation :

    • stop loss is equal to 6% ( issue still valid in case of different values)
    • result : 0 trade executed --> reason : "Insufficient margin to fill order."

    Configuration:

    • RISK_PC: 100
    • SIZING: 'risk'

    Backtest configuration:

    • initial_balance=32000,
    • leverage = 1,
    • spread=0.03,
    • commission=0.005

    Strategy Exit signals:

    If signal == 1:
         stop = self.data.Close[i] * (1 - 0.06)  # self.data.Close[i] is the close price
    If signal == -1:
         stop = self.data.Close[i] * (1 + 0.06)
    

    When I've performed some code investigation, I figured out that ; margin_required is always greater than self.margin_available ( in file broker.py inside _fill_order function ) Example : margin_required=377116.75920040935 , self.margin_available=32000

    This is due to how order.size is calculated in file broker_utils.py inside get_size function : It seems that when a stop loss is set, the number of units to buy is calculated as follows:

    price_distance = abs(price - stop_price)
    quote_risk = amount_risked / HCF
    units = quote_risk / price_distance
    

    where HCF = 1

    I don't understand why the position size is calculated in that way. why we divide it by the price_distance and not just price ? In my point of view it must always be like this : units = amount_risked/(HCF*price)

    Thanks

    opened by SeifallahSnoussi 5
  • Broker interface should be programmatically enforced

    Broker interface should be programmatically enforced

    Is your feature request related to a problem? Please describe. A common desire is to extend AutoTrader's functionality to new exchanges (either specific instances of exchanges or entire classes, such as DEXes). In order to do this, new implementations must conform to the broker interface. Unfortunately, this interface, despite having very real expectations on compliant implementations, is not enforced anywhere in the current codebase.

    Python purists will argue this is not Pythonic as it attempts to sidestep ducktyping; however, there is clearly confusion surrounding exactly what a broker must look like.

    Describe the solution you'd like At a high level, programmatic enforcement of the broker interface (which exists regardless of enforcement method). Actually achieving this in Python is sadly a best-effort endeavour though.

    The least insane solution is very likely an abstract base class. Specifically, by defining abstract methods. Something like the following should suffice:

    class Broker(metaclass=abc.ABCMeta):
        @classmethod
        def __subclasshook__(cls, subclass):
            return (hasattr(subclass, 'get_NAV') and 
                    callable(subclass.get_NAV) and 
                    hasattr(subclass, 'get_balance') and 
                    callable(subclass.get_balance) and
                    hasattr(subclass, 'place_order') and 
                    callable(subclass.place_order) and
                    hasattr(subclass, 'get_orders') and
                    callable(subclass.get_orders) and
                    hasattr(subclass, 'cancel_order') and
                    callable(subclass.cancel_order) and
                    hasattr(subclass, 'get_trades') and 
                    callable(subclass.get_trades) and
                    hasattr(subclass, 'get_positions') and
                    callable(subclass.get_positions) or
                    NotImplemented)
    
        @abc.abstractmethod
        def get_NAV(self) -> float:
           pass
           
        # etc. ...
    

    Describe alternatives you've considered Other methods like subclass hooks but these seem ugly and complicated (admittedly my Python knowledge may be lacking here and these might be The One True Way(TM)).

    Additional context None.

    enhancement 
    opened by jmcph4 4
  • Position size not fully filled when I switch position direction

    Position size not fully filled when I switch position direction

    Describe the bug

    In backtest, when a new signal is triggered, and it has a different direction than the current open position, the order size, is not entirely filled

    Expected behavior Like with tradingview pine scripts, when I switch position direction, the existing position is immediately closed and a new one is opened with the exact ordered size.

    Below, a screenshot of orders history, in which I added two columns about the desired position size (My order size) and current balance

    image

    Configuration Position size is calculated manually in each triggered signal position_size = floor(self.broker.get_NAV()/self.data.Close[i])

    Explanation In the second order, the script has ordered 1310 units, however, only 81 were executed. Of the 1310 units, 1229 were used to close the open position and the remaining ones have been executed in the new position.

    I think that this behavior comes from broker.py in lines 300 to 303

    image

    I tried to manipulate my order size to close the existing one and entirely fill the new position, but I got errors of insufficient margin

    Is there any way to overcome this behavior?

    Thanks,

    opened by SeifallahSnoussi 4
  • Local Sql Lite DB

    Local Sql Lite DB

    Hi, first of all what you did with this repo is really impressive. It will help lot of people to research & backtesting on stock market.

    I'm trying to create charts using data from local db. I've tick level data in sqllite db. Trying to understand how to provide that as input to add_data

    Currently I'm working on pandas dataframes to analyze, so this is how I access to data df_data[symbol] = pd.read_sql("SELECT * FROM {} where time BETWEEN {} and {}".format(tradesTableName,tickerStartDateTimestamp,tickerEndDateTimestamp), con=db)

    Any suggestions on how to plot the data?

    Thank you very much for your time.

    Cheers! Vamsi

    opened by vepak 4
  • Risk per trade

    Risk per trade

    Is your feature request related to a problem? Please describe. Right now, if I were to set 1% risk per trade, I get a lot of cancelled trades if the stop losses is tight. What happens is it tries to max out the margin based on the absolute loss for that trade. The trade does not go through because my account's leverage is not high enough.

    Describe the solution you'd like Can we modify the risk approach that does not max out the position sizing based on the 1% risk alone but take into account the leverage of the trading account. So the open trade could risk < 1% (based on my earlier example), and that's fine.

    Describe alternatives you've considered Indicate a smaller risk per trade amount, which prevents margin from being maxed out.

    Additional context N.A

    opened by elijahho 4
  • Crash: IndexError: only integers, slices (`:`), ellipsis (`...`),

    Crash: IndexError: only integers, slices (`:`), ellipsis (`...`),

    Have the issue:

    if self.data.Close.values[i] > self.ema[i] and
    IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

    Just run next:

    from autotrader import AutoTrader

    Create AutoTrader instance, configure it, and run backtest

    at = AutoTrader() at.configure(verbosity=1, show_plot=True, feed='yahoo') at.add_strategy('macd') at.backtest(start = '1/6/2022', end = '1/10/2022') at.virtual_account_config(initial_balance=1000, leverage = 1000) at.run()

    opened by SergKlein 0
  • Crash raise ValueError(

    Crash raise ValueError("No objects to concatenate")

    Have the issue:

    File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/reshape/concat.py", line 403, in init raise ValueError("No objects to concatenate")

    Just try to run next:

    from autotrader import AutoTrader

    Create AutoTrader instance, configure it, and run backtest

    at = AutoTrader() at.configure(verbosity=1, show_plot=True, feed='yahoo') at.add_strategy('long_ema_crossover') at.backtest(start = '1/9/2022', end = '1/10/2022') at.virtual_account_config(initial_balance=1000, leverage = 1000) at.run()

    opened by SergKlein 0
  • Can we please get an exact Step-by-Step tutorial of how to set it up with Crypto Exchange?

    Can we please get an exact Step-by-Step tutorial of how to set it up with Crypto Exchange?

    Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

    Describe the solution you'd like A clear and concise description of what you want to happen.

    Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

    Additional context Add any other context or screenshots about the feature request here.

    opened by thenodeprotocol1 1
  • AutoData docs

    AutoData docs

    **Is your feature request related to a problem? Imagine user wants to use data from other sources for AutoData() for example a data frame from MetaTrader5, how that user could integrate their strategies with auto trader?

    opened by rseverinop 1
  • Tox support

    Tox support

    Issue

    Closes #58.

    Changes

    $ git log main..58-tox-support
    b1b7fa3 (HEAD -> 58-tox-support, origin/58-tox-support) Add Tox configuration file
    

    Notes

    Blocked by #57

    opened by jmcph4 1
Trading Gym is an open source project for the development of reinforcement learning algorithms in the context of trading.

Trading Gym Trading Gym is an open-source project for the development of reinforcement learning algorithms in the context of trading. It is currently

Dimitry Foures 535 Nov 15, 2022
Trading and Backtesting environment for training reinforcement learning agent or simple rule base algo.

TradingGym TradingGym is a toolkit for training and backtesting the reinforcement learning algorithms. This was inspired by OpenAI Gym and imitated th

Yvictor 1.1k Jan 2, 2023
Trading environnement for RL agents, backtesting and training.

TradzQAI Trading environnement for RL agents, backtesting and training. Live session with coinbasepro-python is finaly arrived ! Available sessions: L

Tony Denion 164 Oct 30, 2022
A general-purpose, flexible, and easy-to-use simulator alongside an OpenAI Gym trading environment for MetaTrader 5 trading platform (Approved by OpenAI Gym)

gym-mtsim: OpenAI Gym - MetaTrader 5 Simulator MtSim is a simulator for the MetaTrader 5 trading platform alongside an OpenAI Gym environment for rein

Mohammad Amin Haghpanah 184 Dec 31, 2022
Code for How To Create A Fully Automated AI Based Trading System With Python

AI Based Trading System This code works as a boilerplate for an AI based trading system with yfinance as data source and RobinHood or Alpaca as broker

Rubén 196 Jan 5, 2023
Paddle implementation for "Cross-Lingual Word Embedding Refinement by ℓ1 Norm Optimisation" (NAACL 2021)

L1-Refinement Paddle implementation for "Cross-Lingual Word Embedding Refinement by ℓ1 Norm Optimisation" (NAACL 2021) ?? A more detailed readme is co

Lincedo Lab 4 Jun 9, 2021
Bayesian optimisation library developped by Huawei Noah's Ark Library

Bayesian Optimisation Research This directory contains official implementations for Bayesian optimisation works developped by Huawei R&D, Noah's Ark L

HUAWEI Noah's Ark Lab 395 Dec 30, 2022
Scalable, event-driven, deep-learning-friendly backtesting library

...Minimizing the mean square error on future experience. - Richard S. Sutton BTGym Scalable event-driven RL-friendly backtesting library. Build on

Andrew 922 Dec 27, 2022
Certis - Certis, A High-Quality Backtesting Engine

Certis - Backtesting For y'all Certis is a powerful, lightweight, simple backtes

Yeachan-Heo 46 Oct 30, 2022
Reinforcement Learning for Automated Trading

Reinforcement Learning for Automated Trading This thesis has been realized for the obtention of the Master's in Mathematical Engineering at the Polite

Pierpaolo Necchi 80 Jun 19, 2022
automated systems to assist guarding corona Virus precautions for Closed Rooms (e.g. Halls, offices, etc..)

Automatic-precautionary-guard automated systems to assist guarding corona Virus precautions for Closed Rooms (e.g. Halls, offices, etc..) what is this

badra 0 Jan 6, 2022
Code for Private Recommender Systems: How Can Users Build Their Own Fair Recommender Systems without Log Data? (SDM 2022)

Private Recommender Systems: How Can Users Build Their Own Fair Recommender Systems without Log Data? (SDM 2022) We consider how a user of a web servi

joisino 20 Aug 21, 2022
High frequency AI based algorithmic trading module.

Flow Flow is a high frequency algorithmic trading module that uses machine learning to self regulate and self optimize for maximum return. The current

null 59 Dec 14, 2022
Deep Reinforcement Learning based Trading Agent for Bitcoin

Deep Trading Agent Deep Reinforcement Learning based Trading Agent for Bitcoin using DeepSense Network for Q function approximation. For complete deta

Kartikay Garg 669 Dec 29, 2022
This is a Image aid classification software based on python TK library development

This is a Image aid classification software based on python TK library development.

EasonChan 1 Jan 17, 2022
mbrl-lib is a toolbox for facilitating development of Model-Based Reinforcement Learning algorithms.

mbrl-lib is a toolbox for facilitating development of Model-Based Reinforcement Learning algorithms. It provides easily interchangeable modeling and planning components, and a set of utility functions that allow writing model-based RL algorithms with only a few lines of code.

Facebook Research 724 Jan 4, 2023
Technical Indicators implemented in Python only using Numpy-Pandas as Magic - Very Very Fast! Very tiny! Stock Market Financial Technical Analysis Python library . Quant Trading automation or cryptocoin exchange

MyTT Technical Indicators implemented in Python only using Numpy-Pandas as Magic - Very Very Fast! to Stock Market Financial Technical Analysis Python

dev 34 Dec 27, 2022
A web-based application for quick, scalable, and automated hyperparameter tuning and stacked ensembling in Python.

Xcessiv Xcessiv is a tool to help you create the biggest, craziest, and most excessive stacked ensembles you can think of. Stacked ensembles are simpl

Reiichiro Nakano 1.3k Nov 17, 2022
LogDeep is an open source deeplearning-based log analysis toolkit for automated anomaly detection.

LogDeep is an open source deeplearning-based log analysis toolkit for automated anomaly detection.

donglee 279 Dec 13, 2022