-
Notifications
You must be signed in to change notification settings - Fork 65
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit ee6a1d5
Showing
13 changed files
with
4,021 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
share/python-wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
*.py,cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
cover/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
db.sqlite3-journal | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
.pybuilder/ | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
# For a library or package, you might want to ignore these files since the code is | ||
# intended to run in multiple environments; otherwise, check them in: | ||
# .python-version | ||
|
||
# pipenv | ||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | ||
# However, in case of collaboration, if having platform-specific dependencies or dependencies | ||
# having no cross-platform support, pipenv may install dependencies that don't work, or not | ||
# install all needed dependencies. | ||
#Pipfile.lock | ||
|
||
# poetry | ||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. | ||
# This is especially recommended for binary packages to ensure reproducibility, and is more | ||
# commonly ignored for libraries. | ||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control | ||
#poetry.lock | ||
|
||
# pdm | ||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. | ||
#pdm.lock | ||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it | ||
# in version control. | ||
# https://pdm.fming.dev/#use-with-ide | ||
.pdm.toml | ||
|
||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm | ||
__pypackages__/ | ||
|
||
# Celery stuff | ||
celerybeat-schedule | ||
celerybeat.pid | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json | ||
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# pytype static type analyzer | ||
.pytype/ | ||
|
||
# Cython debug symbols | ||
cython_debug/ | ||
|
||
# PyCharm | ||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can | ||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore | ||
# and can be added to the global gitignore or merged into this file. For a more nuclear | ||
# option (not recommended) you can uncomment the following to ignore the entire idea folder. | ||
#.idea/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
BSD 2-Clause License | ||
|
||
Copyright (c) 2022, Atreyu Group LLC | ||
All rights reserved. | ||
|
||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are met: | ||
|
||
* Redistributions of source code must retain the above copyright notice, this | ||
list of conditions and the following disclaimer. | ||
|
||
* Redistributions in binary form must reproduce the above copyright notice, | ||
this list of conditions and the following disclaimer in the documentation | ||
and/or other materials provided with the distribution. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
Introduction | ||
============ | ||
|
||
Currently `backtrader` has a built-in integration for Interactive Brokers(IB) [Trader Workstation API](<http://interactivebrokers.github.io/tws-api/>), but it only works for older versions of the API. | ||
|
||
This project re-worked the orginal integration and created a pluggable version allowing `backtrader` to use the latest IB API. | ||
|
||
1. Open an account with IB | ||
2. Download the IB Python native API | ||
3. Download your IB client (TWS or IB Gateway) [Trader Workstation Platform](https://www.interactivebrokers.com/en/home.php) | ||
4. Test for connectivity – Check code sample below | ||
|
||
Installation | ||
------------ | ||
|
||
Create a local python virtual environment: | ||
|
||
`python3 -m venv ./env` | ||
|
||
Activate the environment, all the following packages will be install in the local ./env directory | ||
|
||
`source ./env/bin/activate` | ||
|
||
Install backtrader locally (see [Installing Backtrader](https://www.backtrader.com/docu/installation/) for more options) | ||
|
||
`pip install backtrader` | ||
|
||
Download Interactive Brokers TWS API (from [Trader Workstation API](<http://interactivebrokers.github.io/tws-api/>)) | ||
|
||
Select the latest copy, currently it is (twsapi_macunix.1016.01.zip for Linux) | ||
|
||
`unzip twsapi_macunix.1016.01.zip` | ||
|
||
The file will unzip to the directoty `IBJts` | ||
|
||
`cd IBJts/source/pythonclient` | ||
|
||
Run the setup.py to install the TWS API. | ||
`python setup.py install` | ||
|
||
Download a Atreyu Backtrader API, released version: | ||
|
||
`wget https://github.com/atreyuxtrading/atreyu-backtrader-api/archive/refs/tags/v1.0.zip` | ||
|
||
Unzip file, and install the Atreyu Backtrader API. | ||
|
||
`unzip v1.0.zip` | ||
|
||
`cd atreyu-backtrader-api-1.0 ; python setup.py install` | ||
|
||
Example Program to get market data from TWS. Note that you need a valid login account on TWS | ||
|
||
Check Settings of Locally Running TWS Running | ||
--------------------------------------------- | ||
|
||
![TWS Settings](images/image-01.png "TWS Settings") | ||
|
||
Example: Download Realtime Bar Data from TWS | ||
------------------------------------------- | ||
|
||
```python | ||
import backtrader as bt | ||
from atreyu_backtrader_api import IBData | ||
|
||
cerebro = bt.Cerebro() | ||
# Check IB documentation: https://interactivebrokers.github.io/tws-api/historical_bars.html | ||
# for the 'what' parameter | ||
data = IBData(host='127.0.0.1', port=7497, clientId=35, | ||
name="GOOG", # Data name | ||
dataname='GOOG', # Symbol name | ||
secType='STK', # SecurityType is STOCK | ||
exchange='SMART',# Trading exchange IB's SMART exchange | ||
currency='USD', # Currency of SecurityType | ||
what='BID_ASK', # Get data fields (see note above) | ||
rtbar=True, # Request Realtime bars | ||
_debug=True # Set to True to print out debug messagess from IB TWS API | ||
) | ||
|
||
cerebro.adddata(data) | ||
cerebro.run() | ||
``` | ||
|
||
Disclaimer | ||
---------- | ||
The software is provided on the conditions of the simplified BSD license. | ||
|
||
This project is not affiliated with Interactive Brokers Group, Inc. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
from .ibstore import IBStore | ||
from .ibbroker import IBBroker | ||
from .ibdata import IBData | ||
from .custom_logger import setup_custom_logger | ||
|
||
__all__ = [ | ||
'IBStore', 'IBBroker', 'IBData', 'setup_custom_logger', | ||
] | ||
__version__ = '0.1.0' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import logging | ||
|
||
from datetime import datetime | ||
import os | ||
|
||
# Create the global logger | ||
def setup_custom_logger(global_name, filename, logdirname = './logs', debug_level = logging.ERROR, console_level = logging.ERROR, console = False): | ||
|
||
# Check if logdir exists | ||
if not os.path.exists(logdirname): | ||
# Create it if not there | ||
try: | ||
os.mkdir(logdirname) | ||
except OSError: | ||
print(f"Creation log_dir: {logdirname} failed") | ||
return None | ||
else: | ||
print (f"Created log_dir: {logdirname}") | ||
|
||
# Check if the file exists | ||
logfilename = os.path.join(logdirname, filename) | ||
if os.path.exists(logfilename): | ||
# Create a new logfile for every run | ||
now = datetime.now().strftime('%Y%m%dT%H%M%S') | ||
new_logfile = os.path.join(logdirname, now + "." + filename) | ||
os.rename(logfilename, new_logfile) | ||
|
||
# Set up a log line format | ||
log_fmt = '%(asctime)s.%(msecs)03d - %(levelname)-7s - %(threadName)s - %(filename)s:%(lineno)d [%(funcName)s] - %(message)s' | ||
date_fmt = '%Y-%m-%d %H:%M:%S' | ||
logging.basicConfig(filename=logfilename, level=debug_level, format=log_fmt, datefmt=date_fmt) | ||
|
||
logger = logging.getLogger(global_name) | ||
logger.setLevel(debug_level) | ||
|
||
if console: | ||
# Create console handler and set debug_level | ||
ch = logging.StreamHandler() | ||
ch.setLevel(console_level) | ||
|
||
# Create formatter | ||
formatter = logging.Formatter(fmt=log_fmt, datefmt=date_fmt) | ||
|
||
# Add formatter to ch | ||
ch.setFormatter(formatter) | ||
|
||
# Add ch to logger | ||
logger.addHandler(ch) | ||
|
||
return logger |
Oops, something went wrong.