├── .gitignore ├── README.md ├── forex.py ├── requirements.txt └── stock.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # backtrader-interactive-brokers 2 | integrate backtrader with interactive brokers 3 | 4 | 5 | Video Tutorials: 6 | 7 | Part 1 (Forex): https://www.youtube.com/watch?v=ZOohpUDdqKQ 8 | 9 | Part 2 (Stocks): https://www.youtube.com/watch?v=QF0aSdjv3Jc 10 | 11 | Support the Channel by Visiting Interactive Brokers: 12 | 13 | https://www.interactivebrokers.com/mkt/?src=ptlg&url=%2Fen%2Findex.php%3Ff%3D1338 14 | 15 | Or Buy Me a Coffee: 16 | 17 | https://buymeacoffee.com/parttimelarry 18 | -------------------------------------------------------------------------------- /forex.py: -------------------------------------------------------------------------------- 1 | import backtrader as bt 2 | 3 | class MyStrategy(bt.Strategy): 4 | 5 | def __init__(self): 6 | print("initializing strategy") 7 | self.data_ready = False 8 | 9 | def notify_data(self, data, status): 10 | print('Data Status =>', data._getstatusname(status)) 11 | if status == data.LIVE: 12 | self.data_ready = True 13 | 14 | def log_data(self): 15 | ohlcv = [] 16 | ohlcv.append(str(self.data.datetime.datetime())) 17 | ohlcv.append(str(self.data.open[0])) 18 | ohlcv.append(str(self.data.high[0])) 19 | ohlcv.append(str(self.data.low[0])) 20 | ohlcv.append(str(self.data.close[0])) 21 | ohlcv.append(str(self.data.volume[0])) 22 | print(",".join(ohlcv)) 23 | 24 | def next(self): 25 | self.log_data() 26 | 27 | if not self.data_ready: 28 | return 29 | 30 | # if not self.position: 31 | # self.buy(size=2) 32 | # elif self.position: 33 | # self.sell() 34 | 35 | 36 | 37 | 38 | def start(): 39 | print("starting backtrader") 40 | cerebro = bt.Cerebro() 41 | 42 | store = bt.stores.IBStore(port=7497) 43 | data = store.getdata(dataname='USD.JPY', sectype='CASH', exchange='IDEALPRO', timeframe=bt.TimeFrame.Seconds) 44 | cerebro.resampledata(data, timeframe=bt.TimeFrame.Seconds, compression=15) 45 | 46 | cerebro.broker = store.getbroker() 47 | cerebro.addstrategy(MyStrategy) 48 | cerebro.run() 49 | 50 | start() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | backtrader 2 | IbPy2 -------------------------------------------------------------------------------- /stock.py: -------------------------------------------------------------------------------- 1 | import backtrader as bt 2 | 3 | class StockStrategy(bt.Strategy): 4 | 5 | def __init__(self): 6 | print("initializing strategy") 7 | self.data_ready = False 8 | self.highest = bt.ind.Highest(self.data.high, period=5) 9 | self.lowest = bt.ind.Lowest(self.data.low, period=5) 10 | 11 | def notify_data(self, data, status): 12 | print('Data Status =>', data._getstatusname(status)) 13 | if status == data.LIVE: 14 | self.data_ready = True 15 | 16 | def log_data(self): 17 | ohlcv = [] 18 | ohlcv.append(str(self.data.datetime.datetime())) 19 | ohlcv.append(str(self.data.open[0])) 20 | ohlcv.append(str(self.data.high[0])) 21 | ohlcv.append(str(self.data.low[0])) 22 | ohlcv.append(str(self.data.close[0])) 23 | ohlcv.append(str(self.data.volume[0])) 24 | print(",".join(ohlcv)) 25 | 26 | def next(self): 27 | self.log_data() 28 | if not self.data_ready: 29 | return 30 | 31 | print("current highest high", self.highest[0]) 32 | print("current lowest low", self.lowest[0]) 33 | print("previous highest high", self.highest[-1]) 34 | print("previous lowest low", self.lowest[-1]) 35 | 36 | previous_highest_high = self.highest[-1] 37 | if self.data.close[0] > (previous_highest_high - 0.50): 38 | print(f"closed at {self.data.close[0]}, which is above previous high of {previous_highest_high}, let's buy!") 39 | # uncomment this if you want to buy 40 | # self.buy_bracket(limitprice=self.data.close[0]+1.00, price=self.data.close[0], stopprice=self.data.close[0]-0.50) 41 | 42 | 43 | def start(): 44 | print("starting backtrader") 45 | cerebro = bt.Cerebro() 46 | 47 | store = bt.stores.IBStore(port=7497) 48 | data = store.getdata(dataname='AAPL', sectype='STK', exchange='ISLAND', timeframe=bt.TimeFrame.Minutes) 49 | cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=1) 50 | 51 | cerebro.broker = store.getbroker() 52 | cerebro.addstrategy(StockStrategy) 53 | cerebro.run() 54 | 55 | start() --------------------------------------------------------------------------------